diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentMapNaturality.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentMapNaturality.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0839c3b9712a9854dd3e1134757fd7f67b1fb93 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentMapNaturality.lean @@ -0,0 +1,25 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +variable {A B C D : Type*} [CommRing A] [CommRing B] [CommRing C] [CommRing D] +lemma mapRing_square (f : A →+* B) (g : C →+* D) (p : A →+* C) (q : B →+* D) + (h : ∀ x,q (f x)=g (p x)) (x : LaurentSeries A) : + mapRing q (mapRing f x)=mapRing g (mapRing p x) := by + apply HahnSeries.ext + funext k + exact h (x.coeff k) +lemma mapUnit_square (f : A →+* B) (g : C →+* D) (p : A →+* C) (q : B →+* D) + (h : ∀ x,q (f x)=g (p x)) (x : (LaurentSeries A)ˣ) : + Units.map (mapRing q).toMonoidHom (Units.map (mapRing f).toMonoidHom x)= + Units.map (mapRing g).toMonoidHom (Units.map (mapRing p).toMonoidHom x) := by + apply Units.ext + exact mapRing_square f g p q h x.val +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentProductNaturality.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentProductNaturality.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f9e7908b63a47f4cded30850846fe8be968c981 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentProductNaturality.lean @@ -0,0 +1,16 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +variable {R S : Type*} [CommRing R] [CommRing S] +lemma mapRing_mul_polynomial (f : R →+* S) (K : LaurentSeries R) (p : Polynomial R) : + mapRing f (K*polynomial p)=mapRing f K*polynomial (p.map f) := by + rw [map_mul,polynomial_map] +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentPureAction.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentPureAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd6219eea6ac982f61c5834a76fa2a7986b589b6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentPureAction.lean @@ -0,0 +1,177 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.QuantumTorusRaySeries +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalPureAction +import OAI.Combinatorics.Chromatic.Walls.LaurentCompletion + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus WallUnits PowerSeries HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) (p : M) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +def purePower : PowerSeries K →+* HahnSeries ℤ (Torus v Ω) := + (laurentRayHom v Ω p (hΩ p)).comp (HahnSeries.ofPowerSeries ℤ K) +lemma purePower_eq (f : PowerSeries K) : + purePower v Ω hΩ p f=HahnSeries.ofPowerSeries ℤ (Torus v Ω) (raySeries v Ω p f) := by + apply HahnSeries.ext + funext n + change Torus.monomial v Ω (n • p) ((HahnSeries.ofPowerSeries ℤ K f).coeff n)=_ + rcases le_or_gt 0 n with hn|hn + · lift n to ℕ using hn with j hj + rw [HahnSeries.ofPowerSeries_apply_coeff,HahnSeries.ofPowerSeries_apply_coeff,coeff_raySeries] + simp only [natCast_zsmul] + · have H : (HahnSeries.ofPowerSeries ℤ K f).coeff n=0 := by + rw [HahnSeries.ofPowerSeries_apply] + apply HahnSeries.embDomain_of_notMem_range + rintro ⟨a,ha⟩ + change (a:ℤ)=n at ha + omega + have H' : (HahnSeries.ofPowerSeries ℤ (Torus v Ω) (raySeries v Ω p f)).coeff n=0 := by + rw [HahnSeries.ofPowerSeries_apply] + apply HahnSeries.embDomain_of_notMem_range + rintro ⟨a,ha⟩ + change (a:ℤ)=n at ha + omega + rw [H,H',Torus.monomial_zero] +lemma purePower_commutation (m : M) (f : PowerSeries K) : + HahnSeries.single 0 (Torus.X v Ω m)*purePower v Ω hΩ p f= + purePower v Ω hΩ p (rescale (↑(v^(-2*Ω p m)):K) f)* + HahnSeries.single 0 (Torus.X v Ω m) := by + have H:=raySeries_twist v Ω hΩ p m (rescale (↑(v^(-2*Ω p m)):K) f) + rw [rescale_rescale,←Units.val_mul,←zpow_add, + show -2*Ω p m+2*Ω p m=0 by ring,zpow_zero,Units.val_one,rescale_one] at H + have HH:=congrArg (HahnSeries.ofPowerSeries ℤ (Torus v Ω)) H + rw [purePower_eq,purePower_eq] + simpa only [map_mul,HahnSeries.ofPowerSeries_C,HahnSeries.C_apply,RingHom.id_apply] using HH.symm +lemma purePower_scalar_commute (a : RatFunc K) (f : PowerSeries K) : + expandScalar v Ω hΩ p a*purePower v Ω hΩ p f= + purePower v Ω hΩ p f*expandScalar v Ω hΩ p a := by + change (laurentRayHom v Ω p (hΩ p)) (expandZero a)* + (laurentRayHom v Ω p (hΩ p)) (HahnSeries.ofPowerSeries ℤ K f)=_ + rw [←map_mul,mul_comm,map_mul] + rfl +lemma expandedPure_shifted + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) (t : ℤ) : + expandScalar v Ω hΩ p (pureRatio v t:RatFunc K)* + purePower v Ω hΩ p (shiftedElementary v t)=purePower v Ω hΩ p (shiftedElementary v 0) := by + have H:=congrArg (laurentRayHom v Ω p (hΩ p)) (expandedPure_times_shift v hq t) + simpa only [map_mul,expandScalar,purePower,RingHom.comp_apply] using H + +def pureLaurentUnit : (HahnSeries ℤ (Torus v Ω))ˣ where + val:=purePower v Ω hΩ p (shiftedElementary v 0) + inv:=purePower v Ω hΩ p (shiftedElementary v 0)⁻¹ + val_inv:=by + rw [←map_mul,PowerSeries.mul_inv_cancel _ (by rw [shiftedElementary_constant]; exact one_ne_zero),map_one] + inv_val:=by + rw [←map_mul,PowerSeries.inv_mul_cancel _ (by rw [shiftedElementary_constant]; exact one_ne_zero),map_one] +variable (k : M →+ ℤ) +lemma expand_pure_intertwine + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (f : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) : + expandFiber v Ω hΩ k p (pureAction v (complementOmega k Ω) (complementAlpha k p Ω) f)* + (↑(pureLaurentUnit v Ω hΩ p):HahnSeries ℤ (Torus v Ω))= + (↑(pureLaurentUnit v Ω hΩ p):HahnSeries ℤ (Torus v Ω))*expandFiber v Ω hΩ k p f := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [map_add,add_mul,mul_add,hf,hg] + | single l a=> + change expandFiber v Ω hΩ k p + (pureAction v _ _ (FiberTorus.monomial v _ _ l a))*_=_ + rw [pureAction_monomial] + change expandFiberAdd v Ω hΩ k p (FiberTorus.monomial v _ _ l + (a*(pureRatio v (Ω p l):RatFunc K)))*_= _*expandFiberAdd v Ω hΩ k p (FiberTorus.monomial v _ _ l a) + rw [expandFiberAdd_monomial,expandFiberAdd_monomial] + change (expandScalar v Ω hΩ p (a*(pureRatio v (Ω p l):RatFunc K))* + HahnSeries.single 0 (Torus.X v Ω l))*purePower v Ω hΩ p (shiftedElementary v 0)= + purePower v Ω hΩ p (shiftedElementary v 0)* + (expandScalar v Ω hΩ p a*HahnSeries.single 0 (Torus.X v Ω l)) + rw [map_mul,mul_assoc,mul_assoc,purePower_commutation] + have H : rescale (↑(v^(-2*Ω p l)):K) (shiftedElementary v 0)=shiftedElementary v (Ω p l) := by + rw [shiftedElementary_zero] + rfl + rw [H,←mul_assoc (expandScalar v Ω hΩ p (pureRatio v (Ω p l):RatFunc K)), + expandedPure_shifted v Ω hΩ p hq,←mul_assoc,purePower_scalar_commute,mul_assoc] +lemma expand_pure_conjugate + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (f : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) : + expandFiber v Ω hΩ k p (pureAction v (complementOmega k Ω) (complementAlpha k p Ω) f)= + innerHom (pureLaurentUnit v Ω hΩ p) (expandFiber v Ω hΩ k p f) := by + have H:=congrArg (fun x : HahnSeries ℤ (Torus v Ω)=>x*↑((pureLaurentUnit v Ω hΩ p)⁻¹)) + (expand_pure_intertwine v Ω hΩ p k hq f) + have hu : (↑(pureLaurentUnit v Ω hΩ p):HahnSeries ℤ (Torus v Ω))*↑((pureLaurentUnit v Ω hΩ p)⁻¹)=1 := + (pureLaurentUnit v Ω hΩ p).val_inv + change _=(↑(pureLaurentUnit v Ω hΩ p):HahnSeries ℤ (Torus v Ω))* + expandFiber v Ω hΩ k p f*↑((pureLaurentUnit v Ω hΩ p)⁻¹) + simpa only [mul_assoc,hu,mul_one] using H +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus WallUnits PowerSeries HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (δ κ : M →+ ℤ) (p : M) (hδ : δ p=0) (hκ : κ p=1) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +include hδ hκ in +lemma pure_biSupported (f : PowerSeries K) : BiSupported v Ω δ κ (raySeries v Ω p f) := by + intro n m hm + rw [coeff_raySeries] at hm + have he : m=n • p := by + by_contra H + exact hm (Finsupp.single_eq_of_ne H) + subst m + simp only [map_nsmul,hδ,hκ,nsmul_eq_mul,mul_one] + exact ⟨le_rfl,Int.natCast_nonneg _,by omega⟩ +include hδ hκ in +lemma biRegrade_pure (f : PowerSeries K) : + biRegrade v Ω δ κ (raySeries v Ω p f)=PowerSeries.C (raySeries v Ω p f) := by + apply PowerSeries.ext + intro d + apply PowerSeries.ext + intro e + rw [biRegrade_coeff,coeff_raySeries,biHomogenize_monomial] + simp only [map_nsmul,hδ,hκ,nsmul_eq_mul,mul_one, + Int.toNat_natCast,coeff_monomial] + by_cases hd : d=0 + · subst d + simp [coeff_C,coeff_raySeries] + · simp [coeff_C,hd] +include hδ hκ in +lemma oldLaurent_pure (f : PowerSeries K) : + oldLaurent v Ω δ κ (raySeries v Ω p f)=PowerSeries.C (purePower v Ω hΩ p f) := by + rw [oldLaurent,biRegrade_pure v Ω δ κ p hδ hκ,PowerSeries.map_C,purePower_eq] +include hδ hκ in +lemma oldLaurent_pure_unit : + oldLaurent v Ω δ κ (rayUnit v Ω p (hΩ p) (shiftedElementary v 0) + (shiftedElementary_constant v 0)).val= + PowerSeries.C (↑(pureLaurentUnit v Ω hΩ p):HahnSeries ℤ (Torus v Ω)) := + oldLaurent_pure v Ω hΩ δ κ p hδ hκ _ +include hδ hκ in +lemma oldLaurent_pure_inverse : + oldLaurent v Ω δ κ (rayUnit v Ω p (hΩ p) (shiftedElementary v 0) + (shiftedElementary_constant v 0)).inv= + PowerSeries.C (↑((pureLaurentUnit v Ω hΩ p)⁻¹):HahnSeries ℤ (Torus v Ω)) := + oldLaurent_pure v Ω hΩ δ κ p hδ hκ _ +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRectangularKernel.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRectangularKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..d59faa0b47362e8dddef20dab3c82532b1f33f52 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRectangularKernel.lean @@ -0,0 +1,144 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.RectangularKernel +variable {I : Type*} [Fintype I] +variable {G : Type*} [CommGroup G] + +noncomputable def rectangular {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b : I → I → ℤ) (v : ∀ i j,L i → R j → G) : G := + ∏ i,∏ j,∏ x : L i,∏ y : R j,v i j x y ^ b i j + +lemma rectangular_add {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b c : I → I → ℤ) (v : ∀ i j,L i → R j → G) : + rectangular (b+c) v=rectangular b v*rectangular c v := by + simp only [rectangular,Pi.add_apply,zpow_add,Finset.prod_mul_distrib] + +lemma rectangular_neg {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b : I → I → ℤ) (v : ∀ i j,L i → R j → G) : + rectangular (-b) v=(rectangular b v)⁻¹ := by + simp only [rectangular,Pi.neg_apply,zpow_neg,Finset.prod_inv_distrib] + +lemma rectangular_sub {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b c : I → I → ℤ) (v : ∀ i j,L i → R j → G) : + rectangular (b-c) v=rectangular b v*(rectangular c v)⁻¹ := by + rw [sub_eq_add_neg,rectangular_add,rectangular_neg] + +lemma rectangular_map {H : Type*} [CommGroup H] (f : G →* H) + {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b : I → I → ℤ) (v : ∀ i j,L i → R j → G) : + f (rectangular b v)=rectangular b (fun i j x y=>f (v i j x y)) := by + simp only [rectangular,map_prod,map_zpow] + +lemma rectangular_transpose {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b : I → I → ℤ) (v : ∀ i j,L i → R j → G) : + rectangular (fun i j=>b j i) (fun i j (x:R i) (y:L j)=>v j i y x)= + rectangular b v := by + unfold rectangular + rw [Finset.prod_comm] + apply Finset.prod_congr rfl + intro i hi + apply Finset.prod_congr rfl + intro j hj + exact Finset.prod_comm + +lemma rectangular_sum {L₁ L₂ R₁ R₂ : I → Type*} + [∀ i,Fintype (L₁ i)] [∀ i,Fintype (L₂ i)] + [∀ i,Fintype (R₁ i)] [∀ i,Fintype (R₂ i)] + (b : I → I → ℤ) (v : ∀ i j,(L₁ i⊕L₂ i) → (R₁ j⊕R₂ j) → G) : + rectangular b v= + rectangular b (fun i j x y=>v i j (Sum.inl x) (Sum.inl y))* + rectangular b (fun i j x y=>v i j (Sum.inl x) (Sum.inr y))* + rectangular b (fun i j x y=>v i j (Sum.inr x) (Sum.inl y))* + rectangular b (fun i j x y=>v i j (Sum.inr x) (Sum.inr y)) := by + simp only [rectangular,Fintype.prod_sum_type,Finset.prod_mul_distrib] + ac_rfl + +lemma rectangular_diagonal [DecidableEq I] {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (v : ∀ i j,L i → R j → G) : + rectangular (fun i j=>if i=j then 1 else 0) v= + ∏ i,∏ x:L i,∏ y:R i,v i i x y := by + unfold rectangular + apply Finset.prod_congr rfl + intro i hi + rw [Finset.prod_eq_single i] + · simp + · intro j hj hji + simp [Ne.symm hji] + · simp + +lemma four_rectangle_cancellation {L₁ L₂ R₁ R₂ : I → Type*} + [∀ i,Fintype (L₁ i)] [∀ i,Fintype (L₂ i)] + [∀ i,Fintype (R₁ i)] [∀ i,Fintype (R₂ i)] + (δ a : I → I → ℤ) (v : ∀ i j,(L₁ i⊕L₂ i) → (R₁ j⊕R₂ j) → G) : + rectangular (δ-a) v * (rectangular δ v)⁻¹ * + (rectangular δ (fun i j x y=>v i j (Sum.inl x) (Sum.inl y))* + rectangular δ (fun i j x y=>v i j (Sum.inr x) (Sum.inr y))* + rectangular a (fun i j x y=>v i j (Sum.inl x) (Sum.inr y))* + rectangular (fun i j=>a j i) (fun i j x y=>v i j (Sum.inr x) (Sum.inl y))) = + rectangular (δ-a) (fun i j x y=>v i j (Sum.inl x) (Sum.inl y))* + rectangular (δ-a) (fun i j x y=>v i j (Sum.inr x) (Sum.inr y))* + (rectangular (δ-a) (fun i j x y=>v i j (Sum.inr x) (Sum.inl y))* + (rectangular (δ-(fun i j=>a j i)) (fun i j x y=>v i j (Sum.inr x) (Sum.inl y)))⁻¹) := by + rw [rectangular_sub δ a v,rectangular_sum a v] + rw [rectangular_sub,rectangular_sub,rectangular_sub,rectangular_sub] + generalize rectangular δ v=K + generalize rectangular a (fun i j x y=>v i j (Sum.inl x) (Sum.inl y))=A + generalize rectangular a (fun i j x y=>v i j (Sum.inl x) (Sum.inr y))=B + generalize rectangular a (fun i j x y=>v i j (Sum.inr x) (Sum.inl y))=C + generalize rectangular a (fun i j x y=>v i j (Sum.inr x) (Sum.inr y))=D + generalize rectangular δ (fun i j x y=>v i j (Sum.inl x) (Sum.inl y))=P + generalize rectangular δ (fun i j x y=>v i j (Sum.inr x) (Sum.inr y))=Q + generalize rectangular δ (fun i j x y=>v i j (Sum.inr x) (Sum.inl y))=R + generalize rectangular (fun i j=>a j i) (fun i j x y=>v i j (Sum.inr x) (Sum.inl y))=S + simp [mul_comm,mul_left_comm,mul_assoc] + rw [mul_left_comm B P,mul_left_comm B Q,mul_left_comm B S,mul_left_comm B A⁻¹, + mul_inv_cancel_left] + +end ElementaryPositivity.RectangularKernel + +end +section +namespace ElementaryPositivity.RectangularKernel +variable {I : Type*} [Fintype I] +variable {G : Type*} [CommGroup G] + +lemma rectangular_mul {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b : I → I → ℤ) (v w : ∀ i j,L i → R j → G) : + rectangular b (fun i j x y=>v i j x y*w i j x y)=rectangular b v*rectangular b w := by + simp only [rectangular,mul_zpow,Finset.prod_mul_distrib] + +lemma prod_zpow_sum {α : Type*} (s : Finset α) (b : α → ℤ) (g : G) : + (∏ x∈s,g^b x)=g^(∑ x∈s,b x) := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert x s hx ih => rw [Finset.prod_insert hx,Finset.sum_insert hx,ih,zpow_add] + +lemma rectangular_constant {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b : I → I → ℤ) (g : G) : + rectangular (L:=L) (R:=R) b (fun _ _ _ _=>g)= + g^(∑ i,∑ j,b i j*(Fintype.card (L i):ℤ)*(Fintype.card (R j):ℤ)) := by + simp only [rectangular,Finset.prod_const,Finset.card_univ,←zpow_natCast,←zpow_mul] + rw [←prod_zpow_sum] + apply Finset.prod_congr rfl + intro i hi + rw [←prod_zpow_sum] + apply Finset.prod_congr rfl + intro j hj + congr 1 + ring + +lemma rectangular_scalar_mul {L R : I → Type*} [∀ i,Fintype (L i)] [∀ i,Fintype (R i)] + (b : I → I → ℤ) (g : G) (v : ∀ i j,L i → R j → G) : + rectangular b (fun i j x y=>g*v i j x y)= + g^(∑ i,∑ j,b i j*(Fintype.card (L i):ℤ)*(Fintype.card (R j):ℤ))*rectangular b v := by + rw [rectangular_mul,rectangular_constant] + +end ElementaryPositivity.RectangularKernel + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegrade.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegrade.lean new file mode 100644 index 0000000000000000000000000000000000000000..84971055fed94c42c57905de4d828de500168e8d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegrade.lean @@ -0,0 +1,291 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentHomogenize +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegrade + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ κ : M →+ ℤ) (B : ℕ) +local instance laurentRegradeRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance laurentRegradeAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance laurentRegradeAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def LaurentBounded (f : PowerSeries (Torus v Ω)) : Prop := + ∀ n m, coeff n f m ≠ 0 → + 0 ≤ δ m ∧ -(B : ℤ)*δ m ≤ κ m ∧ (n : ℤ) ≤ κ m + (B+1 : ℤ)*δ m + +lemma LaurentBounded.zero : LaurentBounded v Ω δ κ B 0 := by + intro n m h + simp at h +lemma LaurentBounded.one : LaurentBounded v Ω δ κ B 1 := by + intro n m hm + have hn : n = 0 := by by_contra hn; simp [coeff_one, hn] at hm + subst n + have hm0 : m = 0 := by + by_contra hm0 + apply hm + rw [coeff_one, ite_eq_left rfl] + exact Finsupp.single_eq_of_ne hm0 + subst m + simp +lemma LaurentBounded.add {f g : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (hg : LaurentBounded v Ω δ κ B g) : + LaurentBounded v Ω δ κ B (f+g) := by + intro n m hm + have H : coeff n f m ≠ 0 ∨ coeff n g m ≠ 0 := by + by_contra hh + push Not at hh + simp [hh.1, hh.2] at hm + exact H.elim (hf n m) (hg n m) +lemma LaurentBounded.neg {f : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) : LaurentBounded v Ω δ κ B (-f) := by + intro n m hm + apply hf n m + intro hz + apply hm + change -(coeff n f m) = 0 + rw [hz, neg_zero] +lemma LaurentBounded.mul {f g : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (hg : LaurentBounded v Ω δ κ B g) : + LaurentBounded v Ω δ κ B (f*g) := by + intro n r hr + obtain ⟨a,b,m,l,hab,hm,hl,rfl⟩ := series_product_nonzero v Ω f g n r hr + obtain ⟨hdm,hkm,hem⟩ := hf a m hm + obtain ⟨hdl,hkl,hel⟩ := hg b l hl + simp only [map_add] + refine ⟨add_nonneg hdm hdl, ?_, ?_⟩ + · nlinarith + · rw [←hab, Nat.cast_add] + nlinarith + +lemma LaurentBounded.laurent_vanish {f : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (d n : ℕ) (z : ℤ) + (hz : z < -(B : ℤ)*(d : ℤ) ∨ z + (B+1 : ℤ)*(d : ℤ) < n) : + (coeff d (laurentHomogenize v Ω δ κ (coeff n f))).coeff z = 0 := by + ext m + rw [laurentHomogenize_coeff] + split_ifs with hh + · by_contra hm + obtain ⟨hd,hk,hn⟩ := hf n m hm + have hD : δ m = (d : ℤ) := by rw [hh.1, Int.toNat_of_nonneg hd] + rw [hD, ←hh.2] at hk hn + rcases hz with hz | hz <;> omega + · rfl + +def laurentRegradeFamily (f : PowerSeries (Torus v Ω)) + (hf : LaurentBounded v Ω δ κ B f) (d : ℕ) : + HahnSeries.SummableFamily ℤ (Torus v Ω) ℕ where + toFun n := coeff d (laurentHomogenize v Ω δ κ (coeff n f)) + isPWO_iUnion_support' := by + apply Set.IsWF.isPWO + apply BddBelow.isWF + refine ⟨-(B : ℤ)*(d : ℤ), ?_⟩ + intro z hz + obtain ⟨n, hn⟩ := Set.mem_iUnion.mp hz + by_contra h + exact hn (hf.laurent_vanish v Ω δ κ B d n z (Or.inl (lt_of_not_ge h))) + finite_co_support' z := by + apply (Finset.finite_toSet (Finset.range ((z+(B+1 : ℤ)*(d : ℤ)).toNat+1))).subset + intro n hn + simp only [Finset.mem_coe, Finset.mem_range] + by_contra h + apply hn + apply hf.laurent_vanish v Ω δ κ B d n z + right + omega + +def laurentRegrade (f : PowerSeries (Torus v Ω)) + (hf : LaurentBounded v Ω δ κ B f) : PowerSeries (HahnSeries ℤ (Torus v Ω)) := + PowerSeries.mk fun d => (laurentRegradeFamily v Ω δ κ B f hf d).hsum + +lemma laurentRegrade_coeff (f : PowerSeries (Torus v Ω)) + (hf : LaurentBounded v Ω δ κ B f) (d : ℕ) (z : ℤ) : + (coeff d (laurentRegrade v Ω δ κ B f hf)).coeff z = + ∑ n ∈ Finset.range ((z+(B+1 : ℤ)*(d : ℤ)).toNat+1), + (coeff d (laurentHomogenize v Ω δ κ (coeff n f))).coeff z := by + rw [laurentRegrade, coeff_mk] + apply HahnSeries.SummableFamily.coeff_hsum_eq_sum_of_subset + intro n hn + simp only [Finset.mem_coe, Finset.mem_range] + by_contra h + exact hn (hf.laurent_vanish v Ω δ κ B d n z (Or.inr (by omega))) + +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ κ : M →+ ℤ) +local instance laurentRegradeBiRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance laurentRegradeBiAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance laurentRegradeBiAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def BiBounded (f : PowerSeries (Torus v Ω)) : Prop := + ∀ n m, coeff n f m ≠ 0 → 0 ≤ δ m ∧ 0 ≤ κ m ∧ (n : ℤ) ≤ δ m + κ m +lemma BiBounded.zero : BiBounded v Ω δ κ 0 := by intro n m h; simp at h +lemma BiBounded.one : BiBounded v Ω δ κ 1 := by + intro n m hm + have hn : n=0 := by by_contra hn; simp [coeff_one,hn] at hm + subst n + have hm0 : m=0 := by + by_contra hm0 + apply hm + rw [coeff_one,ite_eq_left rfl] + exact Finsupp.single_eq_of_ne hm0 + subst m + simp +lemma BiBounded.add {f g : PowerSeries (Torus v Ω)} + (hf : BiBounded v Ω δ κ f) (hg : BiBounded v Ω δ κ g) : BiBounded v Ω δ κ (f+g) := by + intro n m hm + have H : coeff n f m≠0 ∨ coeff n g m≠0 := by + by_contra hh + push Not at hh + simp [hh.1,hh.2] at hm + exact H.elim (hf n m) (hg n m) +lemma BiBounded.neg {f : PowerSeries (Torus v Ω)} (hf : BiBounded v Ω δ κ f) : + BiBounded v Ω δ κ (-f) := by + intro n m hm + apply hf n m + intro hz + apply hm + change -(coeff n f m)=0 + rw [hz,neg_zero] +lemma BiBounded.mul {f g : PowerSeries (Torus v Ω)} + (hf : BiBounded v Ω δ κ f) (hg : BiBounded v Ω δ κ g) : BiBounded v Ω δ κ (f*g) := by + intro j r hr + obtain ⟨a,b,m,n,hab,hm,hn,rfl⟩ := series_product_nonzero v Ω f g j r hr + obtain ⟨hdm,hkm,hem⟩ := hf a m hm + obtain ⟨hdn,hkn,hen⟩ := hg b n hn + simp only [map_add] + refine ⟨add_nonneg hdm hdn,add_nonneg hkm hkn,?_⟩ + rw [←hab,Nat.cast_add] + omega +lemma BiBounded.bi_vanish {f : PowerSeries (Torus v Ω)} (hf : BiBounded v Ω δ κ f) + (d e n : ℕ) (hne : d+e PowerSeries.mk fun e => + ∑ n ∈ Finset.range (d+e+1), coeff e (coeff d (biHomogenize v Ω δ κ (coeff n f))) +lemma boundedBiRegrade_coeff (f : PowerSeries (Torus v Ω)) (d e : ℕ) : + coeff e (coeff d (boundedBiRegrade v Ω δ κ f)) = + ∑ n ∈ Finset.range (d+e+1), coeff e (coeff d (biHomogenize v Ω δ κ (coeff n f))) := by + simp only [boundedBiRegrade,coeff_mk] + +section Topology +local instance laurentRegradeTopology : TopologicalSpace (Torus v Ω) := ⊥ +local instance laurentRegradeDiscreteTopology : DiscreteTopology (Torus v Ω) := ⟨rfl⟩ +open scoped PowerSeries.WithPiTopology +lemma boundedBiRegrade_hasSum {f : PowerSeries (Torus v Ω)} (hf : BiBounded v Ω δ κ f) : + HasSum (fun n => biHomogenize v Ω δ κ (coeff n f)) (boundedBiRegrade v Ω δ κ f) := by + rw [PowerSeries.WithPiTopology.hasSum_iff_hasSum_coeff] + intro d + rw [PowerSeries.WithPiTopology.hasSum_iff_hasSum_coeff] + intro e + rw [boundedBiRegrade_coeff] + apply hasSum_sum_of_ne_finset_zero + intro n hn + apply hf.bi_vanish v Ω δ κ d e n + simp only [Finset.mem_range,not_lt] at hn + omega +lemma boundedBiRegrade_product_summable {f g : PowerSeries (Torus v Ω)} + (hf : BiBounded v Ω δ κ f) (hg : BiBounded v Ω δ κ g) : + Summable (fun ab : ℕ×ℕ => biHomogenize v Ω δ κ (coeff ab.1 f)* + biHomogenize v Ω δ κ (coeff ab.2 g)) := by + rw [PowerSeries.WithPiTopology.summable_iff_summable_coeff] + intro d + rw [PowerSeries.WithPiTopology.summable_iff_summable_coeff] + intro e + apply summable_of_hasFiniteSupport + apply (Finset.finite_toSet ((Finset.range (d+e+1)).product (Finset.range (d+e+1)))).subset + intro ab hab + change coeff e (coeff d (biHomogenize v Ω δ κ (coeff ab.1 f)* + biHomogenize v Ω δ κ (coeff ab.2 g)))≠0 at hab + change ab∈(Finset.range (d+e+1)) ×ˢ (Finset.range (d+e+1)) + rw [Finset.mem_product,Finset.mem_range,Finset.mem_range] + by_contra H + exact hab (hf.bi_product_vanish v Ω δ κ hg d e ab.1 ab.2 (by omega)) +lemma boundedBiRegrade_mul {f g : PowerSeries (Torus v Ω)} + (hf : BiBounded v Ω δ κ f) (hg : BiBounded v Ω δ κ g) : + boundedBiRegrade v Ω δ κ (f*g) = boundedBiRegrade v Ω δ κ f*boundedBiRegrade v Ω δ κ g := by + rw [←(boundedBiRegrade_hasSum v Ω δ κ hf).tsum_eq, + ←(boundedBiRegrade_hasSum v Ω δ κ hg).tsum_eq, + (boundedBiRegrade_hasSum v Ω δ κ hf).summable.tsum_mul_tsum_eq_tsum_sum_antidiagonal + (boundedBiRegrade_hasSum v Ω δ κ hg).summable (boundedBiRegrade_product_summable v Ω δ κ hf hg), + ←(boundedBiRegrade_hasSum v Ω δ κ (hf.mul v Ω δ κ hg)).tsum_eq] + apply tsum_congr + intro n + rw [coeff_mul,_root_.map_sum] + apply Finset.sum_congr rfl + intro ab hab + exact biHomogenize_mul v Ω δ κ _ _ (fun m hm => ⟨(hf ab.1 m hm).1,(hf ab.1 m hm).2.1⟩) + (fun m hm => ⟨(hg ab.2 m hm).1,(hg ab.2 m hm).2.1⟩) +end Topology + +lemma boundedBiRegrade_add (f g : PowerSeries (Torus v Ω)) : + boundedBiRegrade v Ω δ κ (f+g) = boundedBiRegrade v Ω δ κ f+boundedBiRegrade v Ω δ κ g := by + apply PowerSeries.ext + intro d + apply PowerSeries.ext + intro e + rw [_root_.map_add, _root_.map_add, boundedBiRegrade_coeff, + boundedBiRegrade_coeff, boundedBiRegrade_coeff, ←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro n hn + rw [_root_.map_add, _root_.map_add, _root_.map_add, _root_.map_add] +lemma boundedBiRegrade_one : boundedBiRegrade v Ω δ κ 1=1 := by + apply PowerSeries.ext + intro d + apply PowerSeries.ext + intro e + rw [boundedBiRegrade_coeff] + rw [Finset.sum_eq_single 0] + · simp only [coeff_zero_one,biHomogenize_one] + · intro n hn hne + rw [coeff_one,ite_eq_right hne,_root_.map_zero,_root_.map_zero,_root_.map_zero] + · intro hn + exact (hn (by simp)).elim +lemma boundedBiRegrade_zero : boundedBiRegrade v Ω δ κ 0=0 := by + apply PowerSeries.ext + intro d + apply PowerSeries.ext + intro e + simp only [boundedBiRegrade_coeff,_root_.map_zero,Finset.sum_const_zero] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegradeFinite.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegradeFinite.lean new file mode 100644 index 0000000000000000000000000000000000000000..3466413255376cf5b2cfa540dfdb0985df1cb11f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegradeFinite.lean @@ -0,0 +1,79 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegradeFaithful +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentRegrade + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ κ : M →+ ℤ) (B D : ℕ) +local instance laurentRegradeFiniteRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance laurentRegradeFiniteAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance laurentRegradeFiniteAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +lemma sum_range_eq_of_tails_zero {A : Type*} [AddCommMonoid A] + (f : ℕ → A) (a b : ℕ) (ha : ∀n,a≤n → f n=0) (hb : ∀n,b≤n → f n=0) : + ∑n∈Finset.range a,f n=∑n∈Finset.range b,f n := by + have H (c : ℕ) (hc : c ≤ max a b) (h : ∀n,c≤n → f n=0) : + ∑n∈Finset.range c,f n=∑n∈Finset.range (max a b),f n := by + apply Finset.sum_subset (Finset.range_mono hc) + intro n hn hnc + exact h n (by simpa only [Finset.mem_range,not_lt] using hnc) + exact (H a (le_max_left _ _) ha).trans (H b (le_max_right _ _) hb).symm + +lemma laurentRegrade_off_diagonal {f : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (d : ℕ) (z : ℤ) (m : M) + (hm : ¬(d=(δ m).toNat ∧ z=κ m)) : + (coeff d (laurentRegrade v Ω δ κ B f hf)).coeff z m=0 := by + rw [laurentRegrade_coeff,nonp_torus_eval_sum] + apply Finset.sum_eq_zero + intro n hn + rw [laurentHomogenize_coeff,ite_eq_right hm] + +lemma laurentRegrade_finite {f : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (hg : RegradeBound v Ω δ D f) (d : ℕ) : + coeff d (laurentRegrade v Ω δ κ B f hf)= + coeff d (laurentHomogenize v Ω δ κ (coeff d (regrade v Ω δ D f))) := by + apply HahnSeries.ext + funext z + ext m + rw [laurentRegrade_coeff,nonp_torus_eval_sum,laurentHomogenize_coeff] + by_cases h : d=(δ m).toNat ∧ z=κ m + · rw [ite_eq_left h,regrade_coeff_eval,ite_eq_left h.1] + simp_rw [laurentHomogenize_coeff,ite_eq_left h] + apply sum_range_eq_of_tails_zero + · intro n hn + by_contra hm + obtain ⟨hd,hk,he⟩:=hf n m hm + have hD : δ m=(d:ℤ) := by rw [h.1,Int.toNat_of_nonneg hd] + rw [hD,←h.2] at he + omega + · intro n hn + by_contra hm + have H:=(hg n m hm).2 + rw [←h.1] at H + omega + · rw [ite_eq_right h] + apply Finset.sum_eq_zero + intro n hn + rw [laurentHomogenize_coeff,ite_eq_right h] + +lemma laurentRegrade_finite_read {f : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (hg : RegradeBound v Ω δ D f) + (d : ℕ) (z : ℤ) (m : M) : + (coeff d (laurentRegrade v Ω δ κ B f hf)).coeff z m= + if z=κ m then coeff d (regrade v Ω δ D f) m else 0 := by + rw [laurentRegrade_finite v Ω δ κ B D hf hg,laurentHomogenize_coeff] + by_cases he : d=(δ m).toNat + · simp only [he,true_and] + · rw [regrade_coeff_eval,ite_eq_right he] + simp +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegradePure.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegradePure.lean new file mode 100644 index 0000000000000000000000000000000000000000..e31b1d873b5fef6cc1736cce2b1500c190de0203 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentRegradePure.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.QuantumTorusRaySeries +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentRegrade + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ κ : M →+ ℤ) (B : ℕ) +variable (p : M) (hδ : δ p=0) (hκ : κ p=1) +local instance laurentRegradePureRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance laurentRegradePureAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance laurentRegradePureAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +include hδ hκ in +lemma pure_laurentBounded (f : PowerSeries R) : + LaurentBounded v Ω δ κ B (raySeries v Ω p f) := by + intro n m hm + rw [coeff_raySeries] at hm + have he : m=n • p := by + by_contra H + exact hm (Finsupp.single_eq_of_ne H) + subst m + simp only [map_nsmul,hδ,hκ,nsmul_eq_mul,mul_one,mul_zero,add_zero] + exact ⟨le_rfl,Int.natCast_nonneg _,le_rfl⟩ + +include hδ hκ in +lemma laurentRegrade_pure (f : PowerSeries R) : + laurentRegrade v Ω δ κ B (raySeries v Ω p f) + (pure_laurentBounded v Ω δ κ B p hδ hκ f)= + PowerSeries.C (HahnSeries.ofPowerSeries ℤ (Torus v Ω) (raySeries v Ω p f)) := by + classical + apply PowerSeries.ext + intro d + apply HahnSeries.ext + funext z + rw [laurentRegrade_coeff] + simp_rw [coeff_raySeries,laurentHomogenize_monomial] + simp only [map_nsmul,hδ,hκ,nsmul_eq_mul,mul_one,mul_zero,Int.toNat_zero,coeff_monomial] + by_cases hd : d=0 + · subst d + simp only [coeff_C,Nat.cast_zero,mul_zero,add_zero,ite_true] + by_cases hz : 0≤z + · lift z to ℕ using hz with j hj + simp [HahnSeries.coeff_single] + · have hz' : z<0 := lt_of_not_ge hz + have H (j : ℕ) : z≠(j:ℤ) := by omega + simp_rw [HahnSeries.coeff_single,ite_eq_right (H _)] + rw [Finset.sum_const_zero,HahnSeries.ofPowerSeries_apply,HahnSeries.embDomain_of_notMem_range] + rintro ⟨n,hn⟩ + simp only [Nat.castOrderEmbedding_apply] at hn + omega + · simp only [ite_eq_right hd,HahnSeries.coeff_zero,Finset.sum_const_zero,coeff_C] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentScalarNaturality.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentScalarNaturality.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ba96e9a2fa042541a8a4da20e971d4c2c4a2613 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentScalarNaturality.lean @@ -0,0 +1,26 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +open HahnSeries +variable {R S : Type*} [CommRing R] [CommRing S] [Algebra ℚ R] [Algebra ℚ S] +lemma rat_smul_series (r : ℚ) (x : LaurentSeries R) : + r • x=C (algebraMap ℚ R r)*x := by + apply HahnSeries.ext + funext k + simp only [HahnSeries.coeff_smul,HahnSeries.C_apply,HahnSeries.coeff_single_zero_mul] + exact Algebra.smul_def r (x.coeff k) +lemma mapRing_rat_smul (f : R →ₐ[ℚ] S) (r : ℚ) (x : LaurentSeries R) : + mapRing f.toRingHom (r • x)=r • mapRing f.toRingHom x := by + apply HahnSeries.ext + funext k + simp only [mapRing_coeff,HahnSeries.coeff_smul] + exact f.toLinearMap.map_smul r (x.coeff k) +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentSigns.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentSigns.lean new file mode 100644 index 0000000000000000000000000000000000000000..e93d19505a35e1362b63fce7f7bfccb2300faa62 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentSigns.lean @@ -0,0 +1,23 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +variable {R : Type*} [CommRing R] +lemma unit_neg_one_inv : (-1 : Rˣ)⁻¹=(-1 : Rˣ) := by + apply Units.ext + simp + +lemma unit_neg_one_zpow_sub (n m : ℤ) : + (-1 : Rˣ)^n*(-1 : Rˣ)^m=(-1 : Rˣ)^(n-m) := by + rw [zpow_sub,←inv_zpow,unit_neg_one_inv] + +end ElementaryPositivity + +lemma mul_sign_collect {G : Type*} [CommMonoid G] (s t p q r u : G) : + s*p*q*r*(t*u)=(s*t)*(p*q*r*u) := by ac_rfl + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentUnitSigns.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentUnitSigns.lean new file mode 100644 index 0000000000000000000000000000000000000000..59f7d026d6468acb23e5829b49c9fb8891a3a1e3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/LaurentUnitSigns.lean @@ -0,0 +1,24 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentSigns + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +open HahnSeries +variable {R : Type*} [CommRing R] [Algebra ℚ R] +lemma negative_unit_rat (n : ℤ) : + ((-1 : (LaurentSeries R)ˣ)^n).val=C (algebraMap ℚ R ((-1 : ℚ)^n)) := by + cases n with + | ofNat n => + simp only [Int.ofNat_eq_natCast,zpow_natCast,Units.val_pow_eq_pow_val,Units.val_neg, + Units.val_one,map_pow,map_neg,map_one] + | negSucc n => + rw [zpow_negSucc,←inv_pow,ElementaryPositivity.unit_neg_one_inv] + simp only [Units.val_pow_eq_pow_val,Units.val_neg,Units.val_one,zpow_negSucc, + ←inv_pow,inv_neg,inv_one,map_pow,map_neg,map_one] +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedEndpoint.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedEndpoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..42de4ba3318d4044d6ea2340024cb25e5be07db7 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedEndpoint.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationChamberPaths + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) + +def strictRootsThrough (D : ℕ) : Finset M := by + classical + exact (Finset.range D).biUnion (fun n=>(rootDegree_finite C (n+1)).toFinset) +omit [DecidableEq I] in +lemma mem_strictRootsThrough (D : ℕ) (m : M) : + m∈strictRootsThrough C D ↔ ∃n,n+1≤D ∧ HasRootDegree C (n+1) m := by + classical + simp only [strictRootsThrough,Finset.mem_biUnion,Finset.mem_range,Set.Finite.mem_toFinset, + Set.mem_ofPred_eq,Nat.lt_iff_add_one_le] + +omit [FiniteDimensional ℝ E] in +include hdeg in +lemma RegularCovector.simple_ne {a : Module.Dual ℝ E} (HA : RegularCovector C e a) : + a (e (simpleRoot C pc))≠0 := + HA 1 _ (realRoot_mem e C 1 1 le_rfl _ (simpleRoot_degree C pc)) + (realRoot_ne_zero C e L hdeg 1 (by omega) _ (simpleRoot_degree C pc)) + +include hnd in +lemma mutatedTransport_endpoint_support (V : M → Prop) + (hV : ∀a b,V a → V b → V (a+b)) (D : ℕ) + {a b : Module.Dual ℝ E} (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (hmatch : ∀n,n+1≤D → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → ¬V m → + (0¬V m) + let P:=R.image f + have hp (n : ℕ) (hn : n+1≤D) (m : M) + (hm : HasRootDegree (mutatedRoots Ω C pc) (n+1) m) (hv : ¬V m) : f m∈P:= + Finset.mem_image.mpr ⟨m,Finset.mem_filter.mpr + ⟨(mem_strictRootsThrough _ _ _).mpr ⟨n,hn,hm⟩,hv⟩,rfl⟩ + have hab : a∈mutationSignRegion e S (simpleRoot C pc) P ∧ + b∈mutationSignRegion e S (simpleRoot C pc) P:=by + have aux (x : E) (hx : x∈P) : + 0(aux x hx).1,fun x hx=>(aux x hx).2⟩ + apply mutatedTransport_protected Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd + P V hV D _ HA HB hab.1 hab.2 (HA.simple_ne C pc e L hdeg) (HB.simple_ne C pc e L hdeg) + intro n hn m hm hv + have hh:=hp n hn m hm hv + dsimp [f] at hh + split_ifs at hh + · exact Or.inl hh + · exact Or.inr hh +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedNoCutCone.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedNoCutCone.lean new file mode 100644 index 0000000000000000000000000000000000000000..92c1a7850b79b17ae35b40625449ce31c7d74ad3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedNoCutCone.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationOrientedCompatibility + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry RationalFiber +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] (v : Rˣ) (Ω : M →+ M →+ ℤ) +local instance mutatedNoCutConeRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance mutatedNoCutConeAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance mutatedNoCutConeAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +lemma series_support_addSubmonoid_one (P : AddSubmonoid M) : + ∀n m,coeff n (1 : PowerSeries (Torus v Ω)) m≠0 → m∈P := by + intro n m hm + rw [coeff_one] at hm + split_ifs at hm with hn + · have hm0 : m=0:=by + by_contra h + exact hm (Finsupp.single_eq_of_ne h) + exact hm0 ▸ P.zero_mem + · exact False.elim (hm rfl) +lemma series_support_addSubmonoid_mul (P : AddSubmonoid M) (f g : PowerSeries (Torus v Ω)) + (hf : ∀n m,coeff n f m≠0 → m∈P) (hg : ∀n m,coeff n g m≠0 → m∈P) : + ∀n m,coeff n (f*g) m≠0 → m∈P := by + classical + intro n m hm + rw [coeff_mul,nonp_torus_eval_sum] at hm + obtain ⟨ab,hab,hz⟩:=Finset.exists_ne_zero_of_sum_ne_zero hm + obtain ⟨a,b,ha,hb,he⟩:=torus_product_nonzero v Ω _ _ m hz + exact he ▸ P.add_mem (hf ab.1 a ha) (hg ab.2 b hb) +end +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance mutatedNoCutConeLaurentRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutatedNoCutConeLaurentAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutatedNoCutConeLaurentAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) +include hcoord hS hcomp in +lemma noncutOldLineFactor_cone (pos : Bool) (a : ℝ) + (hs : cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) : + ∀n m,coeff n (noncutOldLineFactor Ω C e he L hdeg v k H a) m≠0 → + m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos) := by + classical + unfold noncutOldLineFactor + split + · next ha=> + let data:=lineRayData C e he L hdeg v k H a ha + have hf:=simple_fiber_bound Ω C coord hcoord pc e he S hS hcomp L hdeg + data.root data.degree data.degree_pos data.root_degree (k+a • v) data.generic pos hs + change ∀n m,coeff n (orientPowerSeries (decide (v (e data.root)<0)) + (chartZero LaurentRay.vUnit Ω C ((k+a • v).toAddMonoidHom.comp e) (simpleTotalTransport Ω C)).val) m≠0 → _ + cases hh : decide (v (e data.root)<0) + · exact inverse_support_addSubmonoid LaurentRay.vUnit Ω _ _ hf + · exact hf + · exact series_support_addSubmonoid_one LaurentRay.vUnit Ω _ + +include hcoord hS hcomp in +lemma noncutComparisonWord_cone (pos : Bool) (lo hi : ℝ) (N : ℕ) + (hs : ∀a∈intervalEventList C e v k lo hi N, + cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) : + ∀n m,coeff n (comparisonWordOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineWord Ω C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N)).val.val m≠0 → + m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos) := by + let U:=fun a=>comparisonOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a) + have HH : ∀l : List ℝ, (∀a∈l,cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) → + ∀n m,coeff n (l.map U).prod.val.val m≠0 → + m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos) := by + intro l + induction l with + | nil=>intro _; exact series_support_addSubmonoid_one LaurentRay.vUnit Ω _ + | cons a l ih=> + intro hl + have ha:=hl a (by simp) + have hb:=noncutOldLineFactor_cone Ω C coord hcoord pc e he S hS hcomp L hdeg v k H pos a ha + rw [noncutOldLineFactor_comparison Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H pos a ha] at hb + exact series_support_addSubmonoid_mul LaurentRay.vUnit Ω _ _ _ hb + (ih (fun b hh=>hl b (List.mem_cons_of_mem a hh))) + simpa only [comparisonWordOld,actualLineWord,List.map_map,Function.comp_def] using + HH (intervalEventList C e v k lo hi N) hs + +include hΩ he hS hcomp hdeg H in +lemma noncutEndpointRatio_cone (pos : Bool) (lo hi : ℝ) (ho : lo.mp hh + have hab:=(Finset.mem_filter.mp hhF).2 + exact hs a hab.1 hab.2 + have hcone:=noncutComparisonWord_cone Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H pos lo hi n hsN + have ht:=actualLine_old_transport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi n + (ha n) (hb n) ho + have HH:=oldCoefficientsEqual_mul Ω coord pc n _ _ + (lineNegativeUnit Ω C coord hcoord pc e v k lo)⁻¹ + (lineNegativeUnit Ω C coord hcoord pc e v k lo)⁻¹ ht (fun _ _=>rfl) + simp only [mul_assoc,mul_inv_cancel,mul_one] at HH + apply hcone n m + rw [HH n le_rfl] + exact hm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedPureFace.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedPureFace.lean new file mode 100644 index 0000000000000000000000000000000000000000..2329d87343f8a505ad2f2271751adbf4e87cd049 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutatedPureFace.lean @@ -0,0 +1,107 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedWallKernel + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) +variable (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma pureFaceSeries_of_pure (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf:∀n m,coeff n f m≠0 → nonpDegree coord pc m=0) : pureFaceSeries Ω coord pc f=f := by + apply PowerSeries.ext + intro n + apply Finsupp.ext + intro m + rw [pureFaceSeries_apply] + split_ifs with h + · rfl + · exact (not_ne_iff.mp (fun H=>h (hf n m H))).symm + +include hcoord in +lemma pureFaceSeries_kernel_one (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf:SeriesGraded LaurentRay.vUnit Ω C f) (hc:constantCoeff f=1) + (h:M →+ ℝ) (hp:h (simpleRoot C pc)≠0) + (hk:∀n m,coeff n f m≠0 → h m=0) : pureFaceSeries Ω coord pc f=1 := by + apply PowerSeries.ext + intro n + cases n with + | zero => + rw [coeff_pureFaceSeries,coeff_zero_eq_constantCoeff_apply,hc,coeff_zero_eq_constantCoeff_apply, + constantCoeff_one,zeroProject_one] + | succ n => + apply Finsupp.ext + intro m + rw [pureFaceSeries_apply,coeff_one,ite_eq_right (show n+1≠0 by omega)] + change (if nonpDegree coord pc m=0 then coeff (n+1) f m else 0)=0 + split_ifs with hm + · by_contra hn + have hr:HasRootDegree C (n+1) m:=by + by_contra hh + exact hn (hf (n+1) m hh) + have HH:=hk (n+1) m hn + rw [nonp_zero_root C coord hcoord pc hr hm,map_nsmul,nsmul_eq_mul] at HH + exact hp ((mul_eq_zero.mp HH).resolve_left (by positivity)) + · rfl + +include hcoord in +lemma pureFaceSeries_orient_simple (b:Bool) : + pureFaceSeries Ω coord pc (orientPowerSeries b (normalizedSimple Ω (simpleRoot C pc)))= + orientPowerSeries b (normalizedSimple Ω (simpleRoot C pc)) := by + apply pureFaceSeries_of_pure + have HH:=orientPowerSeries_submonoid LaurentRay.vUnit Ω + ((nonpDegree coord pc).ker.toAddSubmonoid) b (normalizedSimple Ω (simpleRoot C pc)) + apply HH + intro n m hm + rw [normalizedSimple,coeff_raySeries] at hm + have heq:m=n • simpleRoot C pc:=by + by_contra hh + exact hm (Finsupp.single_eq_of_ne hh) + change nonpDegree coord pc m=0 + rw [heq,map_nsmul,nonpDegree_simple_self C coord hcoord,nsmul_zero] + +variable {E:Type*} [AddCommGroup E] [Module ℝ E] +variable (hΩ:∀m,Ω m m=0) (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k:Module.Dual ℝ E) (H:∀N,GenericOffset (realRootsThrough e C N) 0 v k) + +include hcoord hS hcomp in +lemma mutatedLineFactor_pure (a:ℝ) : + pureFaceSeries Ω (mutatedCoordinates Ω C coord pc) pc + (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H a)= + if (k+a • v) (e (simpleRoot C pc))=0 then + orientPowerSeries (!(decide (v (e (simpleRoot C pc))<0))) + (normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) pc)) else 1 := by + classical + by_cases hp:(k+a • v) (e (simpleRoot C pc))=0 + · have hevent:∃N,a∈lineEvents (realRootsThrough e C N) v k:= + ⟨1,RationalFiber.line_cut_event C pc e L hdeg v k H a hp⟩ + rw [ite_eq_left hp,mutatedLineFactor,dite_eq_left hevent,ite_eq_left hp] + exact pureFaceSeries_orient_simple Ω (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) (mutatedCoordinates_retraction Ω C coord hcoord pc) pc _ + · rw [ite_eq_right hp] + apply pureFaceSeries_kernel_one Ω (mutatedRoots Ω C pc) (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) pc _ + (mutatedLineFactor_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a) + (mutatedLineFactor_constant Ω hΩ C coord pc e he L hdeg v k H a) + ((realMutationCovector e S (simpleRoot C pc) (k+a • v)).toAddMonoidHom.comp e) + · change realMutationCovector e S (simpleRoot C pc) (k+a • v) + (e (simpleRoot (mutatedRoots Ω C pc) pc))≠0 + rw [mutatedRoot_p,map_neg,map_neg,realMutationCovector_at_p e S _ hS] + exact neg_ne_zero.mpr hp + · exact mutatedLineFactor_kernel Ω hΩ C coord pc e he S hS hcomp L hdeg v k H a +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutationCoordinates.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutationCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..de5a7641ee307a0d1b61b676581501fb1b872b5e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/MutationCoordinates.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.QuantumTorusChartCompletion + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (p : I) +def simpleRoot : M := C (Pi.single p 1) +def nonpDegree : M →+ ℤ where + toFun m:=∑i∈Finset.univ.erase p,coord m i + map_zero':=by simp + map_add':=by intro a b; simp [Finset.sum_add_distrib] +def fiberUpper (α : I → ℤ) (σ : ℤ) : M →+ ℤ where + toFun m:=∑i∈Finset.univ.erase p,max 0 (-σ*α i)*coord m i + map_zero':=by simp + map_add':=by intro a b; simp [mul_add,Finset.sum_add_distrib] +def fiberCone (α : I → ℤ) (σ : ℤ) : AddSubmonoid M where + carrier:={m | 0≤coord m p ∧ coord m p≤fiberUpper coord p α σ m} + zero_mem':=by simp + add_mem':=by + intro a b ha hb + change 0≤coord (a+b) p ∧ coord (a+b) p≤fiberUpper coord p α σ (a+b) + simp only [map_add,Pi.add_apply] + exact ⟨add_nonneg ha.1 hb.1,add_le_add ha.2 hb.2⟩ +include hcoord in +omit [DecidableEq I] in +lemma root_coordinates {n : ℕ} {m : M} (hm : HasRootDegree C n m) : + ∃d : I → ℕ,(∑i,d i)=n ∧ (∀i,coord m i=(d i:ℤ)) ∧ C (fun i=>(d i:ℤ))=m := by + obtain ⟨d,hd,hm⟩:=hm + refine ⟨d,hd,?_,hm⟩ + rw [←hm,hcoord] + exact fun _=>rfl +include hcoord in +lemma nonpDegree_root_nonneg {n : ℕ} {m : M} (hm : HasRootDegree C n m) : + 0≤nonpDegree coord p m := by + obtain ⟨d,hd,hc,hm⟩:=root_coordinates C coord hcoord hm + change 0≤∑i∈Finset.univ.erase p,coord m i + apply Finset.sum_nonneg + intro i hi + rw [hc] + positivity +include hcoord in +lemma nonpDegree_root_eq {n : ℕ} {m : M} (hm : HasRootDegree C n m) : + nonpDegree coord p m+coord m p=(n:ℤ) := by + obtain ⟨d,hd,hc,hm⟩:=root_coordinates C coord hcoord hm + change (∑i∈Finset.univ.erase p,coord m i)+coord m p=(n:ℤ) + rw [Finset.sum_erase_add _ _ (Finset.mem_univ p)] + simp only [hc,←Nat.cast_sum,hd] +include hcoord in +lemma nonp_zero_root {n : ℕ} {m : M} (hm : HasRootDegree C n m) + (hz : nonpDegree coord p m=0) : m=n • simpleRoot C p := by + obtain ⟨d,hd,hc,he⟩:=root_coordinates C coord hcoord hm + have hs : ∑i∈Finset.univ.erase p,(d i:ℤ)=0:=by simpa only [nonpDegree,AddMonoidHom.coe_mk,ZeroHom.coe_mk,hc] using hz + have hz' : ∀i,i≠p → d i=0:=by + intro i hi + have HH:=Finset.sum_eq_zero_iff_of_nonneg (fun i (hi : i∈Finset.univ.erase p)=>Int.natCast_nonneg (d i)) |>.mp hs i (Finset.mem_erase.mpr ⟨hi,Finset.mem_univ i⟩) + exact_mod_cast HH + have hdp : d p=n:=by + rw [←hd,Finset.sum_eq_single p] + · intro i hi hp; exact hz' i hp + · simp + have hds : (fun i=>(d i:ℤ))=n • (Pi.single p 1 : I → ℤ):=by + ext i + by_cases hi : i=p + · subst i; simp [hdp] + · simp [hz' i hi,hi] + rw [←he,hds,map_nsmul] + rfl +include hcoord in +lemma nonp_positive_off_cut {n : ℕ} (hn : 0(mutationPairing Ω C pc i).natAbs + +lemma mutationSize_bound (i : I) (hi : i≠pc) : + |mutationPairing Ω C pc i|≤(mutationSize Ω C pc:ℤ) := by + have HH : (mutationPairing Ω C pc i).natAbs ≤ mutationSize Ω C pc:= + Finset.le_sup (f:=fun i=>(mutationPairing Ω C pc i).natAbs) (Finset.mem_erase.mpr ⟨hi,Finset.mem_univ i⟩) + simpa only [Int.natCast_natAbs] using (show ((mutationPairing Ω C pc i).natAbs:ℤ)≤(mutationSize Ω C pc:ℤ) from by exact_mod_cast HH) + +lemma side_upper_le_abs (pos : Bool) (a : ℤ) : max 0 (-sideSign pos*a)≤|a| := by + cases pos + · simp only [sideSign,Bool.false_eq_true,ite_false,neg_neg,one_mul] + exact max_le (abs_nonneg _) (le_abs_self _) + · simp only [sideSign,ite_true,neg_mul,one_mul] + exact max_le (abs_nonneg _) (neg_le_abs _) + +include hcoord in +lemma fiberUpper_degree_bound (pos : Bool) {n : ℕ} {m : M} (hm : HasRootDegree C n m) : + fiberUpper coord pc (mutationPairing Ω C pc) (sideSign pos) m≤ + (mutationSize Ω C pc:ℤ)*nonpDegree coord pc m := by + obtain ⟨d,hd,hc,he⟩:=root_coordinates C coord hcoord hm + change (∑i∈Finset.univ.erase pc,max 0 (-sideSign pos*mutationPairing Ω C pc i)*coord m i)≤ + (mutationSize Ω C pc:ℤ)*(∑i∈Finset.univ.erase pc,coord m i) + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro i hi + apply mul_le_mul_of_nonneg_right + · exact (side_upper_le_abs pos _).trans (mutationSize_bound Ω C pc i (Finset.mem_erase.mp hi).1) + · rw [hc] + exact Int.natCast_nonneg _ + +include hcoord in +lemma fiber_full_degree_bound (pos : Bool) {n : ℕ} {m : M} (hm : HasRootDegree C n m) + (hb : m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + (n:ℤ)≤((mutationSize Ω C pc+1:ℕ):ℤ)*nonpDegree coord pc m := by + have Hn:=nonpDegree_root_eq C coord hcoord pc hm + have Hk:=hb.2.trans (fiberUpper_degree_bound Ω C coord hcoord pc pos hm) + push_cast + nlinarith + +include hcoord in +lemma mutation_root_image_bound (hΩ : ∀m,Ω m m=0) (pos : Bool) {n : ℕ} {m : M} + (hm : HasRootDegree C n m) + (hb : m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + ∃d : ℕ,HasRootDegree (mutatedRoots Ω C pc) d (mutationLinearPiece Ω C pc pos m) ∧ + (nonpDegree coord pc m:ℤ)≤(d:ℤ) ∧ n≤(mutationSize Ω C pc+1)*d := by + obtain ⟨d,hd,hde⟩:=mutation_root_image Ω C coord hcoord pc hΩ pos hm hb + have hwd : nonpDegree coord pc m≤(d:ℤ):=by have HB:=hb.2; omega + have Hn:=fiber_full_degree_bound Ω C coord hcoord pc pos hm hb + have HH : (n:ℤ)≤((mutationSize Ω C pc+1:ℕ):ℤ)*(d:ℤ):= + Hn.trans (mul_le_mul_of_nonneg_left hwd (Int.natCast_nonneg _)) + refine ⟨d,hd,hwd,?_⟩ + exact_mod_cast HH + +variable {E : Type*} [AddCommGroup E] [Module ℝ E] +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) +include hcoord he hB hcomp hdeg in +theorem actual_wall_mutation_root_bound (r : M) (dr : ℕ) (hdr : 0 + intro m hm + by_cases hn : n=0 + · subst n + rw [coeff_invOfUnit,ite_eq_left rfl] at hm + have hm0 : m=0:=by + by_contra hh + apply hm + change Finsupp.single 0 (1:R) m=0 + exact Finsupp.single_eq_of_ne hh + exact hm0 ▸ P.zero_mem + · rw [coeff_invOfUnit,ite_eq_right hn] at hm + simp only [inv_one,Units.val_one] at hm + rw [torus_neg_one_mul] at hm + change -(∑ab∈Finset.HasAntidiagonal.antidiagonal n, + if ab.2if i=pc then -d pc+∑j∈Finset.univ.erase pc,max 0 (-α j)*d j else d i + map_zero':=by ext i; simp + map_add':=by + intro a b; ext i + by_cases hi : i=pc + · subst i; simp only [ite_true,Pi.add_apply,neg_add,mul_add,Finset.sum_add_distrib]; ring + · simp [hi] + +@[simp] lemma mutatedCoefficientMap_off (α : I → ℤ) (d : I → ℤ) (i : I) (hi : i≠pc) : + mutatedCoefficientMap pc α d i=d i := by simp [mutatedCoefficientMap,hi] +@[simp] lemma mutatedCoefficientMap_at (α : I → ℤ) (d : I → ℤ) : + mutatedCoefficientMap pc α d pc= -d pc+∑j∈Finset.univ.erase pc,max 0 (-α j)*d j := by + simp [mutatedCoefficientMap] + +lemma mutatedCoefficientMap_involutive (α : I → ℤ) : + Function.Involutive (mutatedCoefficientMap pc α) := by + intro d; ext i + by_cases hi : i=pc + · subst i + rw [mutatedCoefficientMap_at,mutatedCoefficientMap_at] + have HH : (∑j∈Finset.univ.erase pc,max 0 (-α j)*mutatedCoefficientMap pc α d j)= + ∑j∈Finset.univ.erase pc,max 0 (-α j)*d j:=by + apply Finset.sum_congr rfl + intro j hj + rw [mutatedCoefficientMap_off pc α d j (Finset.mem_erase.mp hj).1] + rw [HH]; ring + · rw [mutatedCoefficientMap_off pc α _ i hi,mutatedCoefficientMap_off pc α _ i hi] + +def mutatedRoots : (I → ℤ) →+ M := C.comp (mutatedCoefficientMap pc (mutationPairing Ω C pc)) +def mutatedCoordinates : M →+ (I → ℤ) := + (mutatedCoefficientMap pc (mutationPairing Ω C pc)).comp coord + +include hcoord in +lemma mutatedCoordinates_retraction (d : I → ℤ) : + mutatedCoordinates Ω C coord pc (mutatedRoots Ω C pc d)=d := by + change mutatedCoefficientMap pc (mutationPairing Ω C pc) + (coord (C (mutatedCoefficientMap pc (mutationPairing Ω C pc) d)))=d + rw [hcoord] + exact mutatedCoefficientMap_involutive pc _ d + +lemma mutatedRoot_p : simpleRoot (mutatedRoots Ω C pc) pc= -simpleRoot C pc := by + have he : mutatedCoefficientMap pc (mutationPairing Ω C pc) (Pi.single pc 1)= + -(Pi.single pc 1 : I → ℤ):=by + ext i + by_cases hi : i=pc + · subst i + rw [mutatedCoefficientMap_at] + have HH : (∑j∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc j)*((Pi.single pc 1 : I → ℤ) j))=0:=by + apply Finset.sum_eq_zero + intro j hj + simp [(Finset.mem_erase.mp hj).1] + rw [HH]; simp + · rw [mutatedCoefficientMap_off pc _ _ i hi] + simp [hi] + change C (mutatedCoefficientMap pc (mutationPairing Ω C pc) (Pi.single pc 1))= -C (Pi.single pc 1) + rw [he,map_neg] + +lemma mutatedRoot_off (i : I) (hi : i≠pc) : + simpleRoot (mutatedRoots Ω C pc) i=simpleRoot C i+ + max 0 (-mutationPairing Ω C pc i) • simpleRoot C pc := by + have he : mutatedCoefficientMap pc (mutationPairing Ω C pc) (Pi.single i 1)= + (Pi.single i 1 : I → ℤ)+max 0 (-mutationPairing Ω C pc i) • Pi.single pc 1:=by + ext j + by_cases hj : j=pc + · subst j + rw [mutatedCoefficientMap_at] + have HH : (∑a∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc a)*((Pi.single i 1 : I → ℤ) a))= + max 0 (-mutationPairing Ω C pc i):=by + rw [Finset.sum_eq_single i] + · simp + · intro a ha hai; simp [hai] + · simp [hi] + rw [HH] + simp [Ne.symm hi] + · rw [mutatedCoefficientMap_off pc _ _ j hj] + simp [Pi.single_apply,hj] + change C (mutatedCoefficientMap pc (mutationPairing Ω C pc) (Pi.single i 1))=_ + rw [he,map_add,map_zsmul] + rfl + +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open WallUnits +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +def centeredCrossing (p m : M) (t : ℕ) : Torus v Ω := + ∑j : Fin (t+1),Torus.monomial v Ω (m+(j:ℕ) • p) ((centeredPolynomial v t).coeff j) +include hΩ in +lemma cut_centered_identity (p m : M) (t : ℕ) (ht : Ω p m=(t:ℤ)) : + Torus.push v Ω Ω (mutationShear Ω p) (mutationShear_pairing Ω hΩ p) + (centeredCrossing v Ω p m t)=centeredCrossing v Ω (-p) m t := by + unfold centeredCrossing + rw [map_sum] + have H (j : Fin (t+1)) : + Torus.push v Ω Ω (mutationShear Ω p) (mutationShear_pairing Ω hΩ p) + (Torus.monomial v Ω (m+(j:ℕ) • p) ((centeredPolynomial v t).coeff j))= + Torus.monomial v Ω (m+(j.rev:ℕ) • (-p)) ((centeredPolynomial v t).coeff j.rev) := by + rw [Torus.push_monomial] + have hj : (j:ℕ)≤t := by have HH:=j.isLt; omega + have hr : (j.rev:ℕ)=t-(j:ℕ):=by rw [Fin.val_rev]; omega + have he : mutationShear Ω p (m+(j:ℕ) • p)=m+(j.rev:ℕ) • (-p) := by + change (m+(j:ℕ) • p)-Ω p (m+(j:ℕ) • p) • p=_ + rw [map_add,map_nsmul,hΩ,smul_zero,add_zero,ht] + rw [←natCast_zsmul,←natCast_zsmul,smul_neg] + rw [hr] + have Hcast : ((t-(j:ℕ):ℕ):ℤ)=(t:ℤ)-(j:ℕ):=by omega + rw [Hcast,sub_smul] + abel + rw [he,hr,centeredPolynomial_coeff_symmetry v t j hj] + simp_rw [H] + exact Equiv.sum_comp Fin.revPerm + (fun j : Fin (t+1)=>Torus.monomial v Ω (m+(j:ℕ) • (-p)) ((centeredPolynomial v t).coeff j)) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NilpotentLogarithm.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NilpotentLogarithm.lean new file mode 100644 index 0000000000000000000000000000000000000000..6be00584b545a38c4849cd2d521f5e5442fa452c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NilpotentLogarithm.lean @@ -0,0 +1,245 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.FiniteLog +open PowerSeries + +lemma subst_one {R S : Type*} [CommRing R] [CommRing S] [Algebra R S] + {g : PowerSeries S} (hg : HasSubst g) : (1 : PowerSeries R).subst g=1 := +by + rw [←coe_substAlgHom hg,map_one] + +lemma deriv_log_mul_one_add_X : + derivative (log ℚ) * (1+X)=1 := by + rw [derivative_log,mul_add,mul_one] + ext n + cases n with + | zero => simp + | succ n => + simp only [map_add,coeff_mk,coeff_succ_mul_X,coeff_one, + Nat.succ_ne_zero,ite_false,pow_succ] + simp + +lemma log_subst_exp_sub_one : (log ℚ).subst (exp ℚ-1)=X := by + apply derivative.ext + · rw [derivative_subst HasSubst.exp_sub_one,derivative_X,map_sub,derivative_exp, + derivative_one,sub_zero] + have h := congrArg (fun f : PowerSeries ℚ=>f.subst (exp ℚ-1)) + deriv_log_mul_one_add_X + simpa only [subst_mul HasSubst.exp_sub_one,subst_add HasSubst.exp_sub_one, + subst_one HasSubst.exp_sub_one,subst_X HasSubst.exp_sub_one,add_sub_assoc,add_comm (1 : PowerSeries ℚ),add_sub_cancel_right,sub_add_cancel] using h + · rw [constantCoeff_X] + exact constantCoeff_subst_eq_zero + (show MvPowerSeries.constantCoeff (exp ℚ-1)=0 from by + change constantCoeff (exp ℚ-1)=0 + simp) _ (constantCoeff_log) + +lemma subst_reverse {R : Type*} [CommRing R] (f g : PowerSeries R) + (hf : constantCoeff f=0) (hg : constantCoeff g=0) + (hu : IsUnit (coeff 1 f)) (hfg : f.subst g=X) : g.subst f=X := by + let h := f.substInvOfIsUnit hu + have hF : HasSubst f := HasSubst.of_constantCoeff_zero' hf + have hG : HasSubst g := HasSubst.of_constantCoeff_zero' hg + have hlf : PowerSeries.subst f h=X := subst_substInvOfIsUnit_left f hf hu + have heq : g=h := by + calc + g=PowerSeries.subst g (X : PowerSeries R) := (subst_X hG).symm + _=PowerSeries.subst g (PowerSeries.subst f h) := by rw [hlf] + _=PowerSeries.subst (PowerSeries.subst g f) h := by + rw [subst_comp_subst_apply (R := R) (S := R) (T := R) (υ := Unit) hF hG] + _=h := by rw [hfg,X_subst] + simpa only [heq] using hlf + +lemma exp_subst_log : (exp ℚ).subst (log ℚ)=1+X := by + have h := subst_reverse (log ℚ) (exp ℚ-1) (by simp) (by simp) + (by simp) log_subst_exp_sub_one + rw [subst_sub HasSubst.log,subst_one HasSubst.log] at h + exact sub_eq_iff_eq_add.mp h |>.trans (add_comm _ _) + +end ElementaryPositivity.FiniteLog + +end +section +namespace ElementaryPositivity.FiniteLog +open PowerSeries + +variable {A B : Type*} [Ring A] [Ring B] [Algebra ℚ A] [Algebra ℚ B] + +noncomputable def nilEval (x : A) (f : PowerSeries ℚ) : A := + ∑ i ∈ Finset.range (nilpotencyClass x), coeff i f • x^i + +lemma nilEval_eq_sum {x : A} {n : ℕ} (hn : x^n=0) (f : PowerSeries ℚ) : + nilEval x f=∑ i ∈ Finset.range n,coeff i f • x^i := by + apply Finset.sum_subset (Finset.range_mono (csInf_le' hn)) + intro i hi hni + rw [Finset.mem_range,not_lt] at hni + rw [pow_eq_zero_of_le hni (pow_nilpotencyClass ⟨n,hn⟩),smul_zero] + +lemma map_nilEval (φ : A →ₐ[ℚ] B) {x : A} (hx : IsNilpotent x) (f : PowerSeries ℚ) : + φ (nilEval x f)=nilEval (φ x) f := by + obtain ⟨n,hn⟩ := hx + rw [nilEval_eq_sum hn,nilEval_eq_sum (show (φ x)^n=0 by rw [←map_pow,hn,map_zero])] + simp only [map_sum,map_smul,map_pow] + +lemma nilEval_exp {x : A} (hx : IsNilpotent x) : nilEval x (exp ℚ)=IsNilpotent.exp x := by + obtain ⟨n,hn⟩ := hx + rw [nilEval_eq_sum hn,IsNilpotent.exp_eq_sum hn] + congr 1 + ext i + simp only [coeff_exp,one_div,Algebra.algebraMap_self,RingHom.id_apply] + +section CommRing +variable {S : Type*} [CommRing S] [Algebra ℚ S] + +omit [Algebra ℚ S] in +lemma substConst_hasSubst {x : S} (hx : IsNilpotent x) : HasSubst (C x : PowerSeries S) := by + change IsNilpotent (constantCoeff (C x)) + rwa [constantCoeff_C] + +lemma nilEval_eq_constantCoeff {x : S} (hx : IsNilpotent x) (f : PowerSeries ℚ) : + nilEval x f=constantCoeff (PowerSeries.subst (C x : PowerSeries S) f) := by + rw [show constantCoeff (PowerSeries.subst (C x : PowerSeries S) f)= + MvPowerSeries.constantCoeff (PowerSeries.subst (C x : PowerSeries S) f) from rfl, + constantCoeff_subst (substConst_hasSubst hx)] + simp only [map_pow,show MvPowerSeries.constantCoeff (C x : PowerSeries S)=x from constantCoeff_C x] + symm + apply finsum_eq_sum_of_support_subset + intro i hi + by_contra h + rw [Finset.mem_coe,Finset.mem_range,not_lt] at h + apply hi + change coeff i f • x^i=0 + rw [pow_eq_zero_of_le h (pow_nilpotencyClass hx),smul_zero] + +noncomputable def nilEvalAlgHom {x : S} (hx : IsNilpotent x) : PowerSeries ℚ →ₐ[ℚ] S := + (constantCoeff : PowerSeries S →+* S).toRatAlgHom.comp (substAlgHom (substConst_hasSubst hx)) + +lemma nilEvalAlgHom_apply {x : S} (hx : IsNilpotent x) (f : PowerSeries ℚ) : + nilEvalAlgHom hx f=nilEval x f := by + rw [nilEval_eq_constantCoeff hx] + change constantCoeff ((substAlgHom (substConst_hasSubst hx)) f)=_ + rw [coe_substAlgHom] + +lemma subst_eq_nilEval {z : PowerSeries S} (hz : IsNilpotent z) (f : PowerSeries ℚ) : + PowerSeries.subst z f=nilEval z f := by + ext n + rw [coeff_subst' (hz.map constantCoeff)] + simp only [nilEval,map_sum] + apply finsum_eq_sum_of_support_subset + intro i hi + by_contra h + rw [Finset.mem_coe,Finset.mem_range,not_lt] at h + apply hi + change coeff i f • coeff n (z^i)=0 + rw [pow_eq_zero_of_le h (pow_nilpotencyClass hz),map_zero,smul_zero] + +lemma subst_C_nilEval {x : S} (hx : IsNilpotent x) (f : PowerSeries ℚ) : + PowerSeries.subst (C x : PowerSeries S) f=C (nilEval x f) := by + rw [subst_eq_nilEval (hx.map C)] + exact (map_nilEval (C : S →+* PowerSeries S).toRatAlgHom hx f).symm + +lemma nilEval_nilpotent {x : S} (hx : IsNilpotent x) {f : PowerSeries ℚ} + (hf : constantCoeff f=0) : IsNilpotent (nilEval x f) := by + rw [nilEval_eq_constantCoeff hx] + have h := (HasSubst.of_constantCoeff_zero' hf).comp (substConst_hasSubst hx) + rwa [coe_substAlgHom] at h + +lemma nilEval_subst {x : S} (hx : IsNilpotent x) {f : PowerSeries ℚ} + (hf : constantCoeff f=0) (g : PowerSeries ℚ) : + nilEval (nilEval x f) g=nilEval x (PowerSeries.subst f g) := by + calc + _=constantCoeff (PowerSeries.subst (C (nilEval x f) : PowerSeries S) g) := + nilEval_eq_constantCoeff (nilEval_nilpotent hx hf) g + _=constantCoeff (PowerSeries.subst (PowerSeries.subst (C x : PowerSeries S) f) g) := by + rw [subst_C_nilEval hx f] + _=constantCoeff (PowerSeries.subst (C x : PowerSeries S) (PowerSeries.subst f g)) := by + exact congrArg constantCoeff (subst_comp_subst_apply (R := ℚ) (S := ℚ) (T := S) + (υ := Unit) (HasSubst.of_constantCoeff_zero' hf) (substConst_hasSubst hx) g).symm + _=_ := (nilEval_eq_constantCoeff hx (PowerSeries.subst f g)).symm + +lemma nilEval_X {x : S} (hx : IsNilpotent x) : nilEval x X=x := by + rw [nilEval_eq_constantCoeff hx,subst_X (substConst_hasSubst hx),constantCoeff_C] + +lemma nilEval_one {x : S} (hx : IsNilpotent x) : nilEval x 1=1 := by + rw [←nilEvalAlgHom_apply hx,map_one] + +lemma nilEval_add {x : S} (hx : IsNilpotent x) (f g : PowerSeries ℚ) : + nilEval x (f+g)=nilEval x f+nilEval x g := by + simp only [←nilEvalAlgHom_apply hx,map_add] + +lemma nilEval_sub {x : S} (hx : IsNilpotent x) (f g : PowerSeries ℚ) : + nilEval x (f-g)=nilEval x f-nilEval x g := by + simp only [←nilEvalAlgHom_apply hx,map_sub] + +lemma exp_nilEval_log {x : S} (hx : IsNilpotent x) : + IsNilpotent.exp (nilEval x (log ℚ))=1+x := by + rw [←nilEval_exp (nilEval_nilpotent hx constantCoeff_log), + nilEval_subst hx constantCoeff_log,exp_subst_log,nilEval_add hx,nilEval_one hx,nilEval_X hx] + +lemma nilEval_log_exp_sub_one {x : S} (hx : IsNilpotent x) : + nilEval (IsNilpotent.exp x-1) (log ℚ)=x := by + rw [←nilEval_exp hx,←nilEval_one hx,←nilEval_sub hx, + nilEval_subst hx (by simp),log_subst_exp_sub_one,nilEval_X hx] + +lemma nilEval_log_mul_comm {x y : S} (hx : IsNilpotent x) (hy : IsNilpotent y) : + nilEval ((1+x)*(1+y)-1) (log ℚ)=nilEval x (log ℚ)+nilEval y (log ℚ) := by + have hlx := nilEval_nilpotent hx (constantCoeff_log (A := ℚ)) + have hly := nilEval_nilpotent hy (constantCoeff_log (A := ℚ)) + have hs := nilEval_log_exp_sub_one ((Commute.all _ _).isNilpotent_add hlx hly) + rw [IsNilpotent.exp_add_of_commute (Commute.all _ _) hlx hly, + exp_nilEval_log hx,exp_nilEval_log hy] at hs + exact hs + +omit [Algebra ℚ S] in +lemma nilpotent_one_add_mul_sub_one {x y : S} (hx : IsNilpotent x) (hy : IsNilpotent y) : + IsNilpotent ((1+x)*(1+y)-1) := by + rw [show (1+x)*(1+y)-1=x+y+x*y by ring] + exact (Commute.all _ _).isNilpotent_add ((Commute.all _ _).isNilpotent_add hx hy) + ((Commute.all _ _).isNilpotent_mul_right hx) + +end CommRing + +open scoped IsMulCommutative in +lemma nilEval_log_mul_of_commute {x y : A} (hxy : Commute x y) + (hx : IsNilpotent x) (hy : IsNilpotent y) : + nilEval ((1+x)*(1+y)-1) (log ℚ)=nilEval x (log ℚ)+nilEval y (log ℚ) := by + let s : Set A := {x,y} + have hs : ∀ u ∈ s, ∀ v ∈ s, u*v=v*u := by + intro u hu v hv + rcases hu with rfl | hu + · rcases hv with rfl | hv + · rfl + · rw [Set.mem_singleton_iff] at hv + subst v + exact hxy.eq + · rw [Set.mem_singleton_iff] at hu + subst u + rcases hv with rfl | hv + · exact hxy.eq.symm + · rw [Set.mem_singleton_iff] at hv + subst v + rfl + let T := Algebra.adjoin ℚ s + let : IsMulCommutative T := Algebra.isMulCommutative_adjoin ℚ + (fun left hleft right hright _ => hs left hleft right hright) + let : CommRing T := inferInstance + let tx : T := ⟨x,Algebra.subset_adjoin (Set.mem_insert x _)⟩ + let ty : T := ⟨y,Algebra.subset_adjoin (Set.mem_insert_of_mem x (Set.mem_singleton y))⟩ + have htx : IsNilpotent tx := by + obtain ⟨n,hn⟩ := hx + exact ⟨n,Subtype.ext hn⟩ + have hty : IsNilpotent ty := by + obtain ⟨n,hn⟩ := hy + exact ⟨n,Subtype.ext hn⟩ + have h := congrArg (Algebra.adjoin ℚ s).val (nilEval_log_mul_comm htx hty) + rw [map_nilEval _ (nilpotent_one_add_mul_sub_one htx hty),map_add, + map_nilEval _ htx,map_nilEval _ hty,map_sub,map_mul,map_add,map_add,map_one] at h + exact h + +end ElementaryPositivity.FiniteLog + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NilpotentSeriesInverse.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NilpotentSeriesInverse.lean new file mode 100644 index 0000000000000000000000000000000000000000..9347134a13f5d1750c325bc6dc48659d68ceacd9 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NilpotentSeriesInverse.lean @@ -0,0 +1,37 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.NilpotentLogarithm + +namespace OAI + +section +namespace ElementaryPositivity.FiniteLog +open PowerSeries +variable {A : Type*} [Ring A] [Algebra ℚ A] + +open scoped IsMulCommutative in +lemma nilEval_exp_log {x : A} (hx : IsNilpotent x) : + nilEval (nilEval x (log ℚ)) (exp ℚ)=1+x := by + let s : Set A := {x} + have hs : ∀ u ∈ s, ∀ v ∈ s, u*v=v*u := by + intro u hu v hv + rw [Set.mem_singleton_iff] at hu hv + subst u; subst v; rfl + let T := Algebra.adjoin ℚ s + let : IsMulCommutative T := Algebra.isMulCommutative_adjoin ℚ + (fun left hleft right hright _ => hs left hleft right hright) + let : CommRing T := inferInstance + let tx : T := ⟨x,Algebra.subset_adjoin (Set.mem_singleton x)⟩ + have htx : IsNilpotent tx := by + obtain ⟨n,hn⟩ := hx + exact ⟨n,Subtype.ext hn⟩ + have h := congrArg (Algebra.adjoin ℚ s).val (exp_nilEval_log htx) + rw [←nilEval_exp (nilEval_nilpotent htx (constantCoeff_log (A := ℚ))), + map_nilEval _ (nilEval_nilpotent htx (constantCoeff_log (A := ℚ))), + map_nilEval _ htx,map_add,map_one] at h + exact h + +end ElementaryPositivity.FiniteLog + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NoncommExpand.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NoncommExpand.lean new file mode 100644 index 0000000000000000000000000000000000000000..f7ecac4e74c3702fbff8d2646fee831b82d6d096 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NoncommExpand.lean @@ -0,0 +1,108 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.PowerSeriesDilate +open PowerSeries +noncomputable section +variable {R : Type*} [Semiring R] +variable (w : ℕ) (hw : 0if w∣n then coeff (n/w) f else 0) + +@[simp] lemma coeff_dilate (f : PowerSeries R) (n : ℕ) : + coeff n (dilate w f)=if w∣n then coeff (n/w) f else 0 := by + rw [dilate,coeff_mk] + +lemma dilate_C (r : R) : dilate w (C r)=C r := by + ext n + rw [coeff_dilate,coeff_C,coeff_C] + by_cases hn : n=0 + · subst n; simp + · rw [ite_eq_right hn] + by_cases hd : w∣n + · rw [ite_eq_left hd] + have H : n/w≠0 := by + intro hz + have HE:=Nat.div_mul_cancel hd + rw [hz,zero_mul] at HE + exact hn HE.symm + rw [ite_eq_right H] + · rw [ite_eq_right hd] + +lemma dilate_add (f g : PowerSeries R) : dilate w (f+g)=dilate w f+dilate w g := by + ext n + simp only [coeff_dilate,map_add] + split_ifs <;> simp + +def pairEmbedding : ℕ×ℕ ↪ ℕ×ℕ where + toFun p:=(w*p.1,w*p.2) + inj':=by + intro p q h + exact Prod.ext (Nat.eq_of_mul_eq_mul_left hw (congrArg Prod.fst h)) + (Nat.eq_of_mul_eq_mul_left hw (congrArg Prod.snd h)) + +include hw in +lemma dilate_mul (f g : PowerSeries R) : dilate w (f*g)=dilate w f*dilate w g := by + classical + ext n + rw [coeff_dilate,PowerSeries.coeff_mul n] + by_cases hn : w∣n + · rw [ite_eq_left hn,PowerSeries.coeff_mul (n/w)] + let s:=(Finset.HasAntidiagonal.antidiagonal (n/w)).map (pairEmbedding w hw) + have hs : s⊆Finset.HasAntidiagonal.antidiagonal n := by + intro p hp + rcases Finset.mem_map.mp hp with ⟨q,hq,rfl⟩ + have hq' := Finset.HasAntidiagonal.mem_antidiagonal.mp hq + rw [Finset.HasAntidiagonal.mem_antidiagonal] + change w*q.1+w*q.2=n + rw [←Nat.mul_add,hq',Nat.mul_div_cancel' hn] + calc + _ = ∑p∈s,coeff p.1 (dilate w f)*coeff p.2 (dilate w g) := by + rw [Finset.sum_map] + apply Finset.sum_congr rfl + intro p hp + change coeff p.1 f*coeff p.2 g=coeff (w*p.1) (dilate w f)*coeff (w*p.2) (dilate w g) + simp [hw.ne'] + _ = _ := Finset.sum_subset hs (by + intro p hp hnot + rw [coeff_dilate,coeff_dilate] + by_cases h₁ : w∣p.1 + · have h₂ : ¬w∣p.2 := by + intro h₂ + apply hnot + apply Finset.mem_map.mpr + refine ⟨(p.1/w,p.2/w),?_,?_⟩ + · rw [Finset.HasAntidiagonal.mem_antidiagonal] + have HH:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + rw [←Nat.add_div_of_dvd_left h₂,HH] + · change (w*(p.1/w),w*(p.2/w))=p + rw [Nat.mul_div_cancel' h₁,Nat.mul_div_cancel' h₂] + simp [h₂] + · simp [h₁]) + · rw [ite_eq_right hn] + symm + apply Finset.sum_eq_zero + intro p hp + rw [coeff_dilate,coeff_dilate] + by_cases h₁ : w∣p.1 + · have h₂ : ¬w∣p.2 := by + intro h₂ + exact hn (Finset.HasAntidiagonal.mem_antidiagonal.mp hp ▸ dvd_add h₁ h₂) + simp [h₂] + · simp [h₁] + +def hom : PowerSeries R →+* PowerSeries R where + toFun:=dilate w + map_one':=by simpa only [map_one] using dilate_C w (R:=R) 1 + map_zero':=by simpa only [map_zero] using dilate_C w (R:=R) 0 + map_add':=dilate_add w + map_mul':=dilate_mul w hw +end +end ElementaryPositivity.PowerSeriesDilate + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NoncommSeriesCalculus.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NoncommSeriesCalculus.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf4aef5775e660e3a78b4cddf4d863e6a8bb9651 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NoncommSeriesCalculus.lean @@ -0,0 +1,148 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.FormalLog +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] [Algebra ℚ R] + +def ncDerivative : PowerSeries R→ₗ[ℚ] PowerSeries R where + toFun F:=PowerSeries.mk (fun n=>(n+1) • coeff (n+1) F) + map_add' F G:=by ext n; simp + map_smul' a F:=by ext n; simp + +@[simp] lemma coeff_ncDerivative (F : PowerSeries R) (n : ℕ) : + coeff n (ncDerivative F)=(n+1) • coeff (n+1) F := by simp [ncDerivative] + +@[simp] lemma ncDerivative_one : ncDerivative (1 : PowerSeries R)=0 := by + ext n + simp + +lemma ncDerivative_mul (F G : PowerSeries R) : + ncDerivative (F*G)=ncDerivative F*G+F*ncDerivative G := by + ext n + simp only [coeff_ncDerivative,coeff_mul,map_add] + rw [Finset.smul_sum] + have H : (∑p∈Finset.HasAntidiagonal.antidiagonal (n+1), + (n+1) • (coeff p.1 F*coeff p.2 G))= + (∑p∈Finset.HasAntidiagonal.antidiagonal (n+1), + p.1 • (coeff p.1 F*coeff p.2 G))+ + (∑p∈Finset.HasAntidiagonal.antidiagonal (n+1), + p.2 • (coeff p.1 F*coeff p.2 G)) := by + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro p hp + rw [←add_nsmul,Finset.HasAntidiagonal.mem_antidiagonal.mp hp] + rw [H,Finset.Nat.sum_antidiagonal_succ,Finset.Nat.sum_antidiagonal_succ'] + simp only [zero_nsmul,zero_add,smul_mul_assoc,mul_smul_comm] + +omit [Algebra ℚ R] in +lemma coeff_power_vanish (F : PowerSeries R) (hF : constantCoeff F=0) + (k n : ℕ) (h : nomega + | succ k ih=> + rw [pow_succ,coeff_mul] + apply Finset.sum_eq_zero + intro p hp + have H:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + by_cases h0 : p.2=0 + · rw [h0,coeff_zero_eq_constantCoeff,hF,mul_zero] + · rw [ih p.1 (by omega),zero_mul] + +variable {K : Type*} [CommRing K] [Algebra ℚ K] +def traceSeries (τ : R→ₗ[ℚ] K) : PowerSeries R→ₗ[ℚ] PowerSeries K where + toFun F:=PowerSeries.mk (fun n=>τ (coeff n F)) + map_add' F G:=by ext n; simp + map_smul' a F:=by ext n; simp + +@[simp] lemma coeff_traceSeries (τ : R→ₗ[ℚ] K) (F : PowerSeries R) (n : ℕ) : + coeff n (traceSeries τ F)=τ (coeff n F) := by simp [traceSeries] + +variable (τ : R→ₗ[ℚ] K) (hτ : ∀a b,τ (a*b)=τ (b*a)) +include hτ in +lemma traceSeries_cyclic (F G : PowerSeries R) : traceSeries τ (F*G)=traceSeries τ (G*F) := by + ext n + simp only [coeff_traceSeries,coeff_mul,map_sum] + rw [←Finset.Nat.sum_antidiagonal_swap (f:=fun p=>τ (coeff p.1 G*coeff p.2 F))] + apply Finset.sum_congr rfl + intro p hp + exact hτ _ _ + +include hτ in +lemma trace_derivative_power (F : PowerSeries R) (k l : ℕ) : + traceSeries τ (ncDerivative (F^(k+1))*F^l)= + (k+1) • traceSeries τ (ncDerivative F*F^(k+l)) := by + induction k generalizing l with + | zero=>simp + | succ k ih=> + rw [pow_succ (F) (k+1),ncDerivative_mul,add_mul,map_add] + have H1 : ncDerivative (F^(k+1))*F*F^l=ncDerivative (F^(k+1))*F^(l+1) := by + rw [mul_assoc,←pow_succ'] + rw [H1,ih] + have H2 : traceSeries τ (F^(k+1)*ncDerivative F*F^l)= + traceSeries τ (ncDerivative F*F^(k+1+l)) := by + rw [mul_assoc,traceSeries_cyclic τ hτ, mul_assoc,←pow_add] + rw [Nat.add_comm l (k+1)] + rw [H2] + have heq : k+(l+1)=k+1+l := by omega + simp only [heq,add_nsmul,one_nsmul] + +include hτ in +lemma trace_derivative_power' (F : PowerSeries R) (k : ℕ) : + traceSeries τ (ncDerivative (F^(k+1)))= + (k+1) • traceSeries τ (ncDerivative F*F^k) := by + simpa using trace_derivative_power τ hτ F k 0 +end +end ElementaryPositivity.FormalLog + +end +section +namespace ElementaryPositivity.FormalLog +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] +lemma inverse_geometric_coeff (F : PowerSeries R) (hF : constantCoeff F=1) (n : ℕ) : + coeff n (invOfUnit F 1)=coeff n (∑k∈Finset.range (n+1),(-(F-1))^k) := by + let U:=-(F-1) + have hU : constantCoeff U=0:=by simp [U,hF] + have heq : 1-U=F := by dsimp [U]; abel + have H : (∑k∈Finset.range (n+1),U^k)*F=1-U^(n+1) := by + rw [←heq] + exact geom_sum_mul_neg U (n+1) + have HI : F*invOfUnit F 1=1:=mul_invOfUnit F 1 hF + have H' := congrArg (fun x : PowerSeries R=>x*invOfUnit F 1) H + rw [mul_assoc,HI,mul_one,sub_mul,one_mul] at H' + have Hzero : coeff n (U^(n+1)*invOfUnit F 1)=0 := by + rw [coeff_mul] + apply Finset.sum_eq_zero + intro p hp + rw [coeff_power_vanish U hU (n+1) p.1 (by + have :=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + omega),zero_mul] + have HH:=congrArg (coeff n) H' + rw [map_sub,Hzero,sub_zero] at HH + exact HH.symm + +lemma geometric_mul_coeff (F A : PowerSeries R) (hF : constantCoeff F=1) (n : ℕ) : + coeff n (A*invOfUnit F 1)= + coeff n (A*(∑k∈Finset.range (n+1),(-(F-1))^k)) := by + rw [coeff_mul,coeff_mul] + apply Finset.sum_congr rfl + intro p hp + congr 1 + have H:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + rw [inverse_geometric_coeff F hF p.2] + simp only [map_sum] + apply Finset.sum_subset (Finset.range_mono (by omega)) + intro k hk hkn + exact coeff_power_vanish (-(F-1)) (by simp [hF]) k p.2 + (by simp only [Finset.mem_range] at hkn; omega) +end +end ElementaryPositivity.FormalLog + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpHomogenize.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpHomogenize.lean new file mode 100644 index 0000000000000000000000000000000000000000..a69a70a0ba8ca6e9d2342fb0029a0bbb423a77f6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpHomogenize.lean @@ -0,0 +1,182 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ : M →+ ℤ) +local instance homogenizeRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance homogenizeAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance homogenizeAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +def homogenizeMonomial (m : M) : R →+ PowerSeries (Torus v Ω) := + (PowerSeries.monomial (δ m).toNat).toAddMonoidHom.comp + {toFun:=Torus.monomial v Ω m,map_zero':=by simp,map_add':=by intros; simp} +def homogenize : Torus v Ω →+ PowerSeries (Torus v Ω) := + Finsupp.liftAddHom (homogenizeMonomial v Ω δ) +@[simp] lemma homogenize_monomial (m : M) (a : R) : + homogenize v Ω δ (Torus.monomial v Ω m a)= + PowerSeries.monomial (δ m).toNat (Torus.monomial v Ω m a) := + Finsupp.liftAddHom_apply_single _ _ _ +lemma torus_sum_monomial (f : Torus v Ω) : + ∑m∈f.support,Torus.monomial v Ω m (f m)=f := by + classical + exact Finsupp.sum_single f +lemma homogenize_coeff (f : Torus v Ω) (d : ℕ) (m : M) : + coeff d (homogenize v Ω δ f) m=if d=(δ m).toNat then f m else 0 := by + classical + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=> + rw [_root_.map_add,_root_.map_add] + simp only [Finsupp.add_apply,hf,hg] + split_ifs <;> simp + | single n a=> + change coeff d (homogenize v Ω δ (Torus.monomial v Ω n a)) m=_ + rw [homogenize_monomial,coeff_monomial] + by_cases hm : m=n + · subst n; split_ifs <;> simp [Torus.monomial] + · split_ifs <;> simp [Torus.monomial,Finsupp.single_eq_of_ne hm] +lemma homogenize_monomial_mul (m n : M) (a b : R) (hm : 0≤δ m) (hn : 0≤δ n) : + homogenize v Ω δ (Torus.monomial v Ω m a*Torus.monomial v Ω n b)= + homogenize v Ω δ (Torus.monomial v Ω m a)*homogenize v Ω δ (Torus.monomial v Ω n b) := by + rw [Torus.monomial_mul_monomial,homogenize_monomial,homogenize_monomial, + homogenize_monomial,PowerSeries.monomial_mul_monomial,Torus.monomial_mul_monomial,_root_.map_add, + Int.toNat_add hm hn] +lemma homo_sum_mul {A : Type*} (s : Finset A) (f : A → Torus v Ω) (g : Torus v Ω) : + (∑i∈s,f i)*g=∑i∈s,f i*g := by + classical + induction s using Finset.induction_on with + | empty=>simp only [Finset.sum_empty,Torus.zero_mul] + | @insert a s ha ih=>simp only [Finset.sum_insert ha,Torus.add_mul,ih] +lemma homo_mul_sum {A : Type*} (s : Finset A) (f : A → Torus v Ω) (g : Torus v Ω) : + g*(∑i∈s,f i)=∑i∈s,g*f i := by + classical + induction s using Finset.induction_on with + | empty=>simp only [Finset.sum_empty,Torus.mul_zero] + | @insert a s ha ih=>simp only [Finset.sum_insert ha,Torus.mul_add,ih] +lemma homogenize_mul (f g : Torus v Ω) + (hf : ∀m,f m≠0 → 0≤δ m) (hg : ∀m,g m≠0 → 0≤δ m) : + homogenize v Ω δ (f*g)=homogenize v Ω δ f*homogenize v Ω δ g := by + classical + calc + _ = ∑m∈f.support,∑n∈g.support, + homogenize v Ω δ (Torus.monomial v Ω m (f m)*Torus.monomial v Ω n (g n)) := by + have H (s : Finset M) (a : M → Torus v Ω) : + homogenize v Ω δ (∑m∈s,a m)=∑m∈s,homogenize v Ω δ (a m) := + _root_.map_sum (homogenize v Ω δ) a s + simp_rw [←H] + congr 1 + simp_rw [←homo_mul_sum] + rw [torus_sum_monomial,←homo_sum_mul,torus_sum_monomial] + _ = ∑m∈f.support,∑n∈g.support, + homogenize v Ω δ (Torus.monomial v Ω m (f m))* + homogenize v Ω δ (Torus.monomial v Ω n (g n)) := by + apply Finset.sum_congr rfl + intro m hm + apply Finset.sum_congr rfl + intro n hn + exact homogenize_monomial_mul v Ω δ m n _ _ (hf m (Finsupp.mem_support_iff.mp hm)) + (hg n (Finsupp.mem_support_iff.mp hn)) + _ = _ := by + simp_rw [←Finset.mul_sum] + rw [←Finset.sum_mul] + congr 1 + · rw [←_root_.map_sum,torus_sum_monomial] + · rw [←_root_.map_sum,torus_sum_monomial] +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ κ : M →+ ℤ) +local instance biHomogenizeRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance biHomogenizeAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance biHomogenizeAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def biHomogenizeMonomial (m : M) : R →+ PowerSeries (PowerSeries (Torus v Ω)) := + (PowerSeries.monomial (δ m).toNat).toAddMonoidHom.comp + ((PowerSeries.monomial (κ m).toNat).toAddMonoidHom.comp + {toFun:=Torus.monomial v Ω m,map_zero':=by simp,map_add':=by intros; simp}) +def biHomogenize : Torus v Ω →+ PowerSeries (PowerSeries (Torus v Ω)) := + Finsupp.liftAddHom (biHomogenizeMonomial v Ω δ κ) +@[simp] lemma biHomogenize_monomial (m : M) (a : R) : + biHomogenize v Ω δ κ (Torus.monomial v Ω m a)= + monomial (δ m).toNat (monomial (κ m).toNat (Torus.monomial v Ω m a)) := + Finsupp.liftAddHom_apply_single _ _ _ +lemma biHomogenize_coeff (f : Torus v Ω) (d e : ℕ) (m : M) : + coeff e (coeff d (biHomogenize v Ω δ κ f)) m= + if d=(δ m).toNat ∧ e=(κ m).toNat then f m else 0 := by + classical + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=> + rw [_root_.map_add,_root_.map_add,_root_.map_add] + simp only [Finsupp.add_apply,hf,hg] + split_ifs <;> simp + | single n a=> + change coeff e (coeff d (biHomogenize v Ω δ κ (Torus.monomial v Ω n a))) m=_ + rw [biHomogenize_monomial,coeff_monomial] + by_cases hm : m=n + · subst n + by_cases hd : d=(δ m).toNat + · rw [ite_eq_left hd,coeff_monomial] + by_cases he : e=(κ m).toNat <;> simp [hd,he,Torus.monomial] + · simp [hd] + · by_cases hd : d=(δ n).toNat <;> by_cases he : e=(κ n).toNat <;> + simp [hd,he,Torus.monomial,Finsupp.single_eq_of_ne hm,coeff_monomial] +lemma biHomogenize_monomial_mul (m n : M) (a b : R) + (hm : 0≤δ m ∧ 0≤κ m) (hn : 0≤δ n ∧ 0≤κ n) : + biHomogenize v Ω δ κ (Torus.monomial v Ω m a*Torus.monomial v Ω n b)= + biHomogenize v Ω δ κ (Torus.monomial v Ω m a)* + biHomogenize v Ω δ κ (Torus.monomial v Ω n b) := by + rw [Torus.monomial_mul_monomial,biHomogenize_monomial,biHomogenize_monomial, + biHomogenize_monomial,monomial_mul_monomial,monomial_mul_monomial, + Torus.monomial_mul_monomial,map_add,map_add,Int.toNat_add hm.1 hn.1,Int.toNat_add hm.2 hn.2] +lemma biHomogenize_mul (f g : Torus v Ω) + (hf : ∀m,f m≠0 → 0≤δ m ∧ 0≤κ m) (hg : ∀m,g m≠0 → 0≤δ m ∧ 0≤κ m) : + biHomogenize v Ω δ κ (f*g)=biHomogenize v Ω δ κ f*biHomogenize v Ω δ κ g := by + classical + calc + _ = ∑m∈f.support,∑n∈g.support, + biHomogenize v Ω δ κ (Torus.monomial v Ω m (f m)*Torus.monomial v Ω n (g n)) := by + have H (s : Finset M) (a : M → Torus v Ω) : + biHomogenize v Ω δ κ (∑m∈s,a m)=∑m∈s,biHomogenize v Ω δ κ (a m) := + _root_.map_sum (biHomogenize v Ω δ κ) a s + simp_rw [←H] + congr 1 + simp_rw [←homo_mul_sum] + rw [torus_sum_monomial,←homo_sum_mul,torus_sum_monomial] + _ = ∑m∈f.support,∑n∈g.support, + biHomogenize v Ω δ κ (Torus.monomial v Ω m (f m))* + biHomogenize v Ω δ κ (Torus.monomial v Ω n (g n)) := by + apply Finset.sum_congr rfl + intro m hm + apply Finset.sum_congr rfl + intro n hn + exact biHomogenize_monomial_mul v Ω δ κ m n _ _ (hf m (Finsupp.mem_support_iff.mp hm)) + (hg n (Finsupp.mem_support_iff.mp hn)) + _ = _ := by + simp_rw [←Finset.mul_sum] + rw [←Finset.sum_mul] + congr 1 + · rw [←_root_.map_sum,torus_sum_monomial] + · rw [←_root_.map_sum,torus_sum_monomial] +lemma biHomogenize_one : biHomogenize v Ω δ κ 1=1 := by + change biHomogenize v Ω δ κ (Torus.monomial v Ω 0 1)=_ + rw [biHomogenize_monomial,_root_.map_zero,_root_.map_zero,Int.toNat_zero,monomial_zero_eq_C_apply,monomial_zero_eq_C_apply] + change C (C (1:Torus v Ω))=1 + simp +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpRegrade.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpRegrade.lean new file mode 100644 index 0000000000000000000000000000000000000000..076bf36cc1378a5d6cd3f729688ef7d84eea17ab --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpRegrade.lean @@ -0,0 +1,189 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpHomogenize + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) +local instance regradeSupportRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance regradeSupportAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance regradeSupportAddGroup : AddGroup (Torus v Ω) := + (Torus.instRing v Ω).toAddGroup +lemma torus_product_nonzero (f g : Torus v Ω) (r : M) (h : (f*g) r≠0) : + ∃m n,f m≠0 ∧ g n≠0 ∧ m+n=r := by + classical + by_contra H + apply h + change Torus.multiply v Ω f g r=0 + simp only [Torus.multiply,Finsupp.sum,Finsupp.finsetSum_apply] + apply Finset.sum_eq_zero + intro m hm + apply Finset.sum_eq_zero + intro n hn + apply Finsupp.single_eq_of_ne + intro hr + exact H ⟨m,n,Finsupp.mem_support_iff.mp hm,Finsupp.mem_support_iff.mp hn,hr.symm⟩ +lemma nonp_torus_eval_sum {A : Type*} (s : Finset A) (f : A → Torus v Ω) (r : M) : + (∑a∈s,f a) r=∑a∈s,f a r := by + classical + induction s using Finset.induction_on with + | empty=>rfl + | @insert a s ha ih=>simp only [Finset.sum_insert ha,Finsupp.add_apply,ih] +lemma series_product_nonzero (f g : PowerSeries (Torus v Ω)) (j : ℕ) (r : M) + (h : coeff j (f*g) r≠0) : + ∃a b m n,a+b=j ∧ coeff a f m≠0 ∧ coeff b g n≠0 ∧ m+n=r := by + classical + rw [coeff_mul,nonp_torus_eval_sum] at h + obtain ⟨ab,hab,hz⟩:=Finset.exists_ne_zero_of_sum_ne_zero h + obtain ⟨m,n,hm,hn,he⟩:=torus_product_nonzero v Ω _ _ r hz + exact ⟨ab.1,ab.2,m,n,Finset.HasAntidiagonal.mem_antidiagonal.mp hab,hm,hn,he⟩ + +def RegradeBound (δ : M →+ ℤ) (B : ℕ) (f : PowerSeries (Torus v Ω)) : Prop := + ∀n m,coeff n f m≠0 → 0≤δ m ∧ n≤B*(δ m).toNat +variable (δ : M →+ ℤ) (B : ℕ) +lemma RegradeBound.zero : RegradeBound v Ω δ B 0 := by intro n m h; simp at h +lemma RegradeBound.one : RegradeBound v Ω δ B 1 := by + intro n m hm + have hn : n=0:=by by_contra hn; simp [coeff_one,hn] at hm + subst n + have hm0 : m=0:=by + by_contra hm0 + apply hm + rw [coeff_one,ite_eq_left rfl] + exact Finsupp.single_eq_of_ne hm0 + subst m + simp +lemma RegradeBound.add {f g : PowerSeries (Torus v Ω)} (hf : RegradeBound v Ω δ B f) + (hg : RegradeBound v Ω δ B g) : RegradeBound v Ω δ B (f+g) := by + intro n m hm + have H : coeff n f m≠0 ∨ coeff n g m≠0:=by + by_contra hh + push Not at hh + simp [hh.1,hh.2] at hm + exact H.elim (hf n m) (hg n m) +lemma RegradeBound.neg {f : PowerSeries (Torus v Ω)} (hf : RegradeBound v Ω δ B f) : + RegradeBound v Ω δ B (-f) := by + intro n m hm + apply hf n m + change -(coeff n f m)≠0 at hm + exact neg_ne_zero.mp hm +lemma RegradeBound.mul {f g : PowerSeries (Torus v Ω)} (hf : RegradeBound v Ω δ B f) + (hg : RegradeBound v Ω δ B g) : RegradeBound v Ω δ B (f*g) := by + intro j r hr + obtain ⟨a,b,m,n,hab,hm,hn,rfl⟩:=series_product_nonzero v Ω f g j r hr + obtain ⟨hm0,hma⟩:=hf a m hm + obtain ⟨hn0,hnb⟩:=hg b n hn + refine ⟨by simpa only [map_add] using add_nonneg hm0 hn0,?_⟩ + rw [←hab,map_add,Int.toNat_add hm0 hn0,mul_add] + exact Nat.add_le_add hma hnb + +lemma RegradeBound.homogenize_vanish {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (d n : ℕ) (hn : B*d∑n∈Finset.range (B*d+1),coeff d (homogenize v Ω δ (coeff n f)) +lemma regrade_coeff (f : PowerSeries (Torus v Ω)) (d : ℕ) : + coeff d (regrade v Ω δ B f)= + ∑n∈Finset.range (B*d+1),coeff d (homogenize v Ω δ (coeff n f)) := coeff_mk _ _ + +section Topology +local instance regradeTopology : TopologicalSpace (Torus v Ω) := ⊥ +local instance regradeDiscreteTopology : DiscreteTopology (Torus v Ω) := ⟨rfl⟩ +open scoped PowerSeries.WithPiTopology + +lemma regrade_hasSum {f : PowerSeries (Torus v Ω)} (hf : RegradeBound v Ω δ B f) : + HasSum (fun n=>homogenize v Ω δ (coeff n f)) (regrade v Ω δ B f) := by + rw [PowerSeries.WithPiTopology.hasSum_iff_hasSum_coeff] + intro d + rw [regrade_coeff] + apply hasSum_sum_of_ne_finset_zero + intro n hn + apply hf.homogenize_vanish v Ω δ B d n + have H : B*d+1≤n:=by simpa only [Finset.mem_range,not_lt] using hn + omega + +lemma regrade_product_summable {f g : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hg : RegradeBound v Ω δ B g) : + Summable (fun ab : ℕ×ℕ=>homogenize v Ω δ (coeff ab.1 f)*homogenize v Ω δ (coeff ab.2 g)) := by + rw [PowerSeries.WithPiTopology.summable_iff_summable_coeff] + intro d + apply summable_of_hasFiniteSupport + apply (Finset.finite_toSet ((Finset.range (B*d+1)).product (Finset.range (B*d+1)))).subset + intro ab hab + change coeff d (homogenize v Ω δ (coeff ab.1 f)*homogenize v Ω δ (coeff ab.2 g))≠0 at hab + change ab∈(Finset.range (B*d+1)) ×ˢ (Finset.range (B*d+1)) + rw [Finset.mem_product,Finset.mem_range,Finset.mem_range] + by_contra H + apply hab + rw [coeff_mul] + apply Finset.sum_eq_zero + intro kl hkl + have hsum:=Finset.HasAntidiagonal.mem_antidiagonal.mp hkl + have hl : B*kl.1≤B*d:=Nat.mul_le_mul_left B (by omega) + have hr : B*kl.2≤B*d:=Nat.mul_le_mul_left B (by omega) + by_cases ha : ab.1(hf ab.1 m hm).1) (fun m hm=>(hg ab.2 m hm).1) + +lemma regrade_add {f g : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hg : RegradeBound v Ω δ B g) : + regrade v Ω δ B (f+g)=regrade v Ω δ B f+regrade v Ω δ B g := by + apply (regrade_hasSum v Ω δ B (hf.add v Ω δ B hg)).unique + have H : (fun n=>homogenize v Ω δ (coeff n (f+g)))= + (fun n=>homogenize v Ω δ (coeff n f)+homogenize v Ω δ (coeff n g)) := by + funext n + rw [_root_.map_add,_root_.map_add] + rw [H] + exact (regrade_hasSum v Ω δ B hf).add (regrade_hasSum v Ω δ B hg) +end Topology +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpRegradeFaithful.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpRegradeFaithful.lean new file mode 100644 index 0000000000000000000000000000000000000000..50e3f85162e04e4956d68920b1be0e9825594d9b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/NonpRegradeFaithful.lean @@ -0,0 +1,164 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegrade + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ : M →+ ℤ) (B : ℕ) +local instance regradeFaithfulRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance regradeFaithfulAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance regradeFaithfulAddGroup : AddGroup (Torus v Ω) := + (Torus.instRing v Ω).toAddGroup + +def FullHomogeneous (τ : M →+ ℤ) (f : PowerSeries (Torus v Ω)) : Prop := + ∀n m,coeff n f m≠0 → τ m=(n:ℤ) + +lemma regrade_coeff_eval (f : PowerSeries (Torus v Ω)) (d : ℕ) (m : M) : + coeff d (regrade v Ω δ B f) m= + if d=(δ m).toNat then ∑n∈Finset.range (B*d+1),coeff n f m else 0 := by + classical + rw [regrade_coeff,nonp_torus_eval_sum] + simp_rw [homogenize_coeff] + split_ifs <;> simp_all + +lemma regrade_read (τ : M →+ ℤ) {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hτ : FullHomogeneous v Ω τ f) + (n : ℕ) (m : M) (hm : τ m=(n:ℤ)) : + coeff (δ m).toNat (regrade v Ω δ B f) m=coeff n f m := by + classical + rw [regrade_coeff_eval,ite_eq_left rfl] + apply Finset.sum_eq_single n + · intro j hj hne + by_contra hz + have H:=hτ j m hz + have : j=n:=by omega + exact hne this + · intro hn + by_contra hz + have H:=(hf n m hz).2 + have HH : ¬n + intro m hm + by_cases hn : n=0 + · subst n + rw [coeff_invOfUnit,ite_eq_left rfl] at hm + have hm0 : m=0:=by + by_contra HH + apply hm + change Finsupp.single 0 (1:R) m=0 + exact Finsupp.single_eq_of_ne HH + subst m + simp + · rw [coeff_invOfUnit,ite_eq_right hn] at hm + simp only [inv_one,Units.val_one] at hm + rw [torus_neg_one_mul] at hm + change -(∑ab∈Finset.HasAntidiagonal.antidiagonal n, + if ab.2hf.add v Ω δ B hg + neg_mem':=fun hf=>hf.neg v Ω δ B + mul_mem':=fun hf hg=>hf.mul v Ω δ B hg + +def regradeHom : boundedRegradeSubring v Ω δ B →+* PowerSeries (Torus v Ω) where + toFun f:=regrade v Ω δ B f.val + map_zero':=regrade_zero v Ω δ B + map_one':=regrade_one v Ω δ B + map_add' f g:=regrade_add v Ω δ B f.property g.property + map_mul' f g:=regrade_mul v Ω δ B f.property g.property + +lemma regrade_inverse_mul {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hc : constantCoeff f=1) : + regrade v Ω δ B (PowerSeries.invOfUnit f 1)*regrade v Ω δ B f=1 := by + rw [←regrade_mul v Ω δ B (hf.invOfUnit v Ω δ B) hf, + PowerSeries.invOfUnit_mul f 1 hc,regrade_one] +lemma regrade_mul_inverse {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hc : constantCoeff f=1) : + regrade v Ω δ B f*regrade v Ω δ B (PowerSeries.invOfUnit f 1)=1 := by + rw [←regrade_mul v Ω δ B hf (hf.invOfUnit v Ω δ B), + PowerSeries.mul_invOfUnit f 1 hc,regrade_one] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesProductLeading.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesProductLeading.lean new file mode 100644 index 0000000000000000000000000000000000000000..72223f9babc8bc51971871fe24fad7866e41e3d5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesProductLeading.lean @@ -0,0 +1,70 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplitLeading + +namespace OAI + +section +section +namespace ElementaryPositivity.PowerSeriesSplit +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] +lemma multiply_leading_difference (f g f' g' : PowerSeries R) (n : ℕ) + (hf : constantCoeff f=1) (hg : constantCoeff g=1) + (hf' : constantCoeff f'=1) (hg' : constantCoeff g'=1) + (hff : ∀k≤n,coeff k f=coeff k f') (hgg : ∀k≤n,coeff k g=coeff k g') : + coeff (n+1) (f*g)-coeff (n+1) (f'*g')= + (coeff (n+1) f-coeff (n+1) f')+(coeff (n+1) g-coeff (n+1) g') := by + rw [coeff_mul_succ _ _ _ hf hg,coeff_mul_succ _ _ _ hf' hg'] + have he : (∑i : Fin n,coeff (i.val+1) f*coeff (n-i.val) g)= + ∑i : Fin n,coeff (i.val+1) f'*coeff (n-i.val) g' := by + apply Finset.sum_congr rfl + intro i _ + rw [hff (i.val+1) (by omega),hgg (n-i.val) (by omega)] + rw [he] + abel + +variable {A : Type*} (f g : A → PowerSeries R) +lemma product_constant (l : List A) (hf : ∀a∈l,constantCoeff (f a)=1) : + constantCoeff (l.map f).prod=1 := by + induction l with + | nil => exact map_one _ + | cons a l ih => + rw [List.map_cons,List.prod_cons,map_mul,hf a List.mem_cons_self,one_mul, + ih (fun b hb=>hf b (List.mem_cons_of_mem a hb))] + +lemma product_coeff_congr (l : List A) (n : ℕ) + (hfg : ∀a∈l,∀k≤n,coeff k (f a)=coeff k (g a)) : + coeff n (l.map f).prod=coeff n (l.map g).prod := by + induction l generalizing n with + | nil => rfl + | cons a l ih => + simp only [List.map_cons,List.prod_cons] + apply FormalLog.mul_coeff_congr + · exact hfg a List.mem_cons_self + · intro k hk + exact ih k (fun b hb j hj=>hfg b (List.mem_cons_of_mem a hb) j (hj.trans hk)) + +lemma product_leading_difference (l : List A) (n : ℕ) + (hf : ∀a∈l,constantCoeff (f a)=1) (hg : ∀a∈l,constantCoeff (g a)=1) + (hfg : ∀a∈l,∀k≤n,coeff k (f a)=coeff k (g a)) : + coeff (n+1) (l.map f).prod-coeff (n+1) (l.map g).prod= + (l.map (fun a=>coeff (n+1) (f a)-coeff (n+1) (g a))).sum := by + induction l with + | nil => simp only [List.map_nil,List.prod_nil,sub_self,List.sum_nil] + | cons a l ih => + have hfl : ∀b∈l,constantCoeff (f b)=1:=fun b hb=>hf b (List.mem_cons_of_mem a hb) + have hgl : ∀b∈l,constantCoeff (g b)=1:=fun b hb=>hg b (List.mem_cons_of_mem a hb) + have hfg' : ∀b∈l,∀k≤n,coeff k (f b)=coeff k (g b):= + fun b hb=>hfg b (List.mem_cons_of_mem a hb) + simp only [List.map_cons,List.prod_cons,List.sum_cons] + rw [multiply_leading_difference _ _ _ _ n (hf a List.mem_cons_self) + (product_constant f l hfl) (hg a List.mem_cons_self) (product_constant g l hgl) + (hfg a List.mem_cons_self) (fun k hk=>product_coeff_congr f g l k + (fun b hb j hj=>hfg' b hb j (hj.trans hk))),ih hfl hgl hfg'] +end +end ElementaryPositivity.PowerSeriesSplit +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesSplit.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..0247603e67d60538da994d982d8bfb691af78e43 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesSplit.lean @@ -0,0 +1,168 @@ +import Mathlib + +namespace OAI + +section +section +namespace ElementaryPositivity.PowerSeriesSplit +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] + +def pairCoefficients (P : R →+ R) (f : PowerSeries R) : ℕ → R × R + | 0 => (1,1) + | n+1 => + let r:=coeff (n+1) f - ∑i : Fin n, + (pairCoefficients P f (i.val+1)).1 * (pairCoefficients P f (n-i.val)).2 + (P r,r-P r) +termination_by n=>n +decreasing_by all_goals omega + +def leftFactor (P : R →+ R) (f : PowerSeries R) : PowerSeries R := + PowerSeries.mk (fun n=>(pairCoefficients P f n).1) +def rightFactor (P : R →+ R) (f : PowerSeries R) : PowerSeries R := + PowerSeries.mk (fun n=>(pairCoefficients P f n).2) + +@[simp] lemma left_constant (P : R →+ R) (f : PowerSeries R) : + constantCoeff (leftFactor P f)=1 := by + rw [←coeff_zero_eq_constantCoeff_apply] + simp only [leftFactor,coeff_mk,pairCoefficients] +@[simp] lemma right_constant (P : R →+ R) (f : PowerSeries R) : + constantCoeff (rightFactor P f)=1 := by + rw [←coeff_zero_eq_constantCoeff_apply] + simp only [rightFactor,coeff_mk,pairCoefficients] + +lemma coeff_mul_succ (f g : PowerSeries R) (n : ℕ) + (hf : constantCoeff f=1) (hg : constantCoeff g=1) : + coeff (n+1) (f*g)=coeff (n+1) f+coeff (n+1) g+ + ∑i : Fin n,coeff (i.val+1) f * coeff (n-i.val) g := by + rw [coeff_mul,Finset.Nat.sum_antidiagonal_eq_sum_range_succ_mk] + rw [Finset.sum_range_succ,Finset.sum_range_succ'] + simp only [Nat.sub_self,coeff_zero_eq_constantCoeff_apply,hf,hg,mul_one,one_mul,Nat.sub_zero] + rw [Fin.sum_univ_eq_sum_range (fun i=>coeff (i+1) f*coeff (n-i) g) n] + simp only [Nat.add_sub_add_right] + abel + +lemma factorization (P : R →+ R) (f : PowerSeries R) (hf : constantCoeff f=1) : + leftFactor P f * rightFactor P f=f := by + ext n + cases n with + | zero => simp only [coeff_zero_eq_constantCoeff_apply,map_mul,left_constant,right_constant,one_mul,hf] + | succ n => + rw [coeff_mul_succ _ _ n (left_constant P f) (right_constant P f)] + simp only [leftFactor,rightFactor,coeff_mk] + rw [pairCoefficients] + dsimp only + abel + +lemma left_fixed (P : R →+ R) (hP : ∀r,P (P r)=P r) (f : PowerSeries R) (n : ℕ) : + P (coeff (n+1) (leftFactor P f))=coeff (n+1) (leftFactor P f) := by + simp only [leftFactor,coeff_mk] + rw [pairCoefficients] + exact hP _ +lemma right_killed (P : R →+ R) (hP : ∀r,P (P r)=P r) (f : PowerSeries R) (n : ℕ) : + P (coeff (n+1) (rightFactor P f))=0 := by + simp only [rightFactor,coeff_mk] + rw [pairCoefficients] + simp only [map_sub,hP,sub_self] + +lemma uniqueness (P : R →+ R) (f a b : PowerSeries R) + (ha : constantCoeff a=1) (hb : constantCoeff b=1) + (hab : a*b=f) + (hleft : ∀n,P (coeff (n+1) a)=coeff (n+1) a) + (hright : ∀n,P (coeff (n+1) b)=0) : + a=leftFactor P f ∧ b=rightFactor P f := by + have h : ∀n,(coeff n a,coeff n b)=pairCoefficients P f n := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + cases n with + | zero => simp only [coeff_zero_eq_constantCoeff_apply,ha,hb,pairCoefficients] + | succ n => + have hsum : (∑i : Fin n, coeff (i.val+1) a * coeff (n-i.val) b)= + ∑i : Fin n,(pairCoefficients P f (i.val+1)).1 * + (pairCoefficients P f (n-i.val)).2 := by + apply Finset.sum_congr rfl + intro i hi + rw [←ih (i.val+1) (by omega),←ih (n-i.val) (by omega)] + have hcoeff := coeff_mul_succ a b n ha hb + rw [hab,hsum] at hcoeff + have hres : coeff (n+1) f-∑i : Fin n, + (pairCoefficients P f (i.val+1)).1 * (pairCoefficients P f (n-i.val)).2 = + coeff (n+1) a+coeff (n+1) b := by rw [hcoeff]; abel + rw [pairCoefficients,hres] + simp only [map_add,hleft,hright,add_zero] + congr 1 + abel + constructor + · ext n + simpa only [leftFactor,coeff_mk] using congrArg Prod.fst (h n) + · ext n + simpa only [rightFactor,coeff_mk] using congrArg Prod.snd (h n) + +lemma factors_mem (P : R →+ R) (S : Subring R) + (hP : ∀r∈S,P r∈S) (f : PowerSeries R) (hf : ∀n,coeff n f∈S) : + (∀n,coeff n (leftFactor P f)∈S) ∧ (∀n,coeff n (rightFactor P f)∈S) := by + have h : ∀n,(pairCoefficients P f n).1∈S ∧ (pairCoefficients P f n).2∈S := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + cases n with + | zero => simpa only [pairCoefficients] using And.intro S.one_mem S.one_mem + | succ n => + have hc : coeff (n+1) f-∑i : Fin n, + (pairCoefficients P f (i.val+1)).1*(pairCoefficients P f (n-i.val)).2∈S := by + apply S.sub_mem (hf (n+1)) + apply S.sum_mem + intro i hi + exact S.mul_mem (ih (i.val+1) (by omega)).1 (ih (n-i.val) (by omega)).2 + rw [pairCoefficients] + exact ⟨hP _ hc,S.sub_mem hc (hP _ hc)⟩ + constructor + · intro n + simpa only [leftFactor,coeff_mk] using (h n).1 + · intro n + simpa only [rightFactor,coeff_mk] using (h n).2 + +lemma mul_mem (S : Subring R) (a b : PowerSeries R) + (ha : ∀n,coeff n a∈S) (hb : ∀n,coeff n b∈S) : ∀n,coeff n (a*b)∈S := by + intro n + rw [coeff_mul] + exact S.sum_mem (fun p hp=>S.mul_mem (ha p.1) (hb p.2)) + +lemma factors_graded (P : R →+ R) (A : ℕ → AddSubgroup R) + (h0 : (1:R)∈A 0) + (hmul : ∀m n x y,x∈A m → y∈A n → x*y∈A (m+n)) + (hP : ∀n x,x∈A n → P x∈A n) + (f : PowerSeries R) (hf : ∀n,coeff n f∈A n) : + (∀n,coeff n (leftFactor P f)∈A n) ∧ + (∀n,coeff n (rightFactor P f)∈A n) := by + have h : ∀n,(pairCoefficients P f n).1∈A n ∧ (pairCoefficients P f n).2∈A n := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + cases n with + | zero => simpa only [pairCoefficients] using And.intro h0 h0 + | succ n => + have hc : coeff (n+1) f-∑i : Fin n, + (pairCoefficients P f (i.val+1)).1*(pairCoefficients P f (n-i.val)).2∈A (n+1) := by + apply (A (n+1)).sub_mem (hf (n+1)) + apply (A (n+1)).sum_mem + intro i hi + have hmn : (i.val+1)+(n-i.val)=n+1 := by omega + rw [←hmn] + exact hmul _ _ _ _ (ih (i.val+1) (by omega)).1 (ih (n-i.val) (by omega)).2 + rw [pairCoefficients] + exact ⟨hP _ _ hc,(A _).sub_mem hc (hP _ _ hc)⟩ + constructor + · intro n + simpa only [leftFactor,coeff_mk] using (h n).1 + · intro n + simpa only [rightFactor,coeff_mk] using (h n).2 + +end +end ElementaryPositivity.PowerSeriesSplit +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesSplitLeading.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesSplitLeading.lean new file mode 100644 index 0000000000000000000000000000000000000000..f9c4ec925a84b44d39b290ae6fe69e5cdc6d464e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PowerSeriesSplitLeading.lean @@ -0,0 +1,164 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PowerSeriesThreeFactors + +namespace OAI + +section +section +namespace ElementaryPositivity.PowerSeriesSplit +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] + +lemma pair_congr (P : R →+ R) (f g : PowerSeries R) (n : ℕ) + (h : ∀k≤n,coeff k f=coeff k g) : pairCoefficients P f n=pairCoefficients P g n := by + induction n using Nat.strong_induction_on with + | h n ih => + cases n with + | zero => rw [pairCoefficients,pairCoefficients] + | succ n => + have hs : (∑i : Fin n,(pairCoefficients P f (i.val+1)).1*(pairCoefficients P f (n-i.val)).2)= + ∑i : Fin n,(pairCoefficients P g (i.val+1)).1*(pairCoefficients P g (n-i.val)).2 := by + apply Finset.sum_congr rfl + intro i hi + rw [ih (i.val+1) (by omega) (fun k hk=>h k (by omega)), + ih (n-i.val) (by omega) (fun k hk=>h k (by omega))] + rw [pairCoefficients,pairCoefficients,h (n+1) le_rfl,hs] + +lemma left_coeff_congr (P : R →+ R) (f g : PowerSeries R) (n : ℕ) + (h : ∀k≤n,coeff k f=coeff k g) : coeff n (leftFactor P f)=coeff n (leftFactor P g) := by + simpa only [leftFactor,coeff_mk] using congrArg Prod.fst (pair_congr P f g n h) +lemma right_coeff_congr (P : R →+ R) (f g : PowerSeries R) (n : ℕ) + (h : ∀k≤n,coeff k f=coeff k g) : coeff n (rightFactor P f)=coeff n (rightFactor P g) := by + simpa only [rightFactor,coeff_mk] using congrArg Prod.snd (pair_congr P f g n h) + +lemma leading_difference (P : R →+ R) (f g : PowerSeries R) (n : ℕ) + (h : ∀k≤n,coeff k f=coeff k g) : + coeff (n+1) (leftFactor P f)-coeff (n+1) (leftFactor P g)=P (coeff (n+1) f-coeff (n+1) g) ∧ + coeff (n+1) (rightFactor P f)-coeff (n+1) (rightFactor P g)= + (coeff (n+1) f-coeff (n+1) g)-P (coeff (n+1) f-coeff (n+1) g) := by + have hs : (∑i : Fin n,(pairCoefficients P f (i.val+1)).1*(pairCoefficients P f (n-i.val)).2)= + ∑i : Fin n,(pairCoefficients P g (i.val+1)).1*(pairCoefficients P g (n-i.val)).2 := by + apply Finset.sum_congr rfl + intro i hi + rw [pair_congr P f g (i.val+1) (fun k hk=>h k (by omega)), + pair_congr P f g (n-i.val) (fun k hk=>h k (by omega))] + simp only [leftFactor,rightFactor,coeff_mk] + rw [pairCoefficients,pairCoefficients,hs] + simp only [map_sub] + constructor <;> abel + +lemma zero_leading_difference (P Q : R →+ R) (hQP : ∀x,Q (P x)=0) + (f g : PowerSeries R) (n : ℕ) (h : ∀k≤n,coeff k f=coeff k g) : + coeff (n+1) (zeroFactor P Q f)-coeff (n+1) (zeroFactor P Q g)= + Q (coeff (n+1) f-coeff (n+1) g) := by + have hr : ∀k≤n,coeff k (rightFactor P f)=coeff k (rightFactor P g) := by + intro k hk + exact right_coeff_congr P f g k (fun j hj=>h j (hj.trans hk)) + have hl:= (leading_difference Q (rightFactor P f) (rightFactor P g) n hr).1 + rw [(leading_difference P f g n h).2,map_sub,hQP,sub_zero] at hl + exact hl + +lemma zero_coeff_congr (P Q : R →+ R) (f g : PowerSeries R) (n : ℕ) + (h : ∀k≤n,coeff k f=coeff k g) : coeff n (zeroFactor P Q f)=coeff n (zeroFactor P Q g) := by + apply left_coeff_congr Q _ _ n + intro k hk + exact right_coeff_congr P f g k (fun j hj=>h j (hj.trans hk)) +end +end ElementaryPositivity.PowerSeriesSplit +end +section +namespace ElementaryPositivity.FormalLog +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] + +lemma mul_coeff_congr (a b c d : PowerSeries R) (n : ℕ) + (ha : ∀j≤n,coeff j a=coeff j c) (hb : ∀j≤n,coeff j b=coeff j d) : + coeff n (a*b)=coeff n (c*d) := by + rw [coeff_mul,coeff_mul] + apply Finset.sum_congr rfl + intro p hp + have hh:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + rw [ha _ (by omega),hb _ (by omega)] + +lemma pow_coeff_congr (a b : PowerSeries R) (n k : ℕ) + (h : ∀j≤n,coeff j a=coeff j b) : coeff n (a^k)=coeff n (b^k) := by + induction k generalizing n with + | zero => rfl + | succ k ih => + rw [pow_succ a k,pow_succ b k] + apply mul_coeff_congr + · intro j hj + exact ih j (fun i hi=>h i (hi.trans hj)) + · exact h + +lemma pow_coeff_congr_of_two_le (a b : PowerSeries R) (n k : ℕ) + (ha : constantCoeff a=0) (hb : constantCoeff b=0) (hk : 2≤k) + (h : ∀jh i (hi.trans_lt hn1)),h _ hn2] + +variable [Module ℚ R] + +def log (f : PowerSeries R) : PowerSeries R := + PowerSeries.mk (fun n=>∑k∈Finset.range n, ((-1:ℚ)^k/(k+1:ℕ)) • coeff n ((f-1)^(k+1))) + +@[simp] lemma log_constant (f : PowerSeries R) : constantCoeff (log f)=0 := by + rw [←coeff_zero_eq_constantCoeff_apply] + simp only [log,coeff_mk,Finset.range_zero,Finset.sum_empty] + +lemma log_coeff_congr (f g : PowerSeries R) (n : ℕ) + (h : ∀j≤n,coeff j f=coeff j g) : coeff n (log f)=coeff n (log g) := by + simp only [log,coeff_mk] + apply Finset.sum_congr rfl + intro k hk + congr 1 + apply pow_coeff_congr + intro j hj + rw [map_sub,map_sub,h j hj] + +lemma log_coeff_succ (f : PowerSeries R) (n : ℕ) : + coeff (n+1) (log f)=coeff (n+1) f+ + ∑k∈Finset.range n,((-1:ℚ)^(k+1)/(k+2:ℕ)) • coeff (n+1) ((f-1)^(k+2)) := by + simp only [log,coeff_mk] + rw [Finset.sum_range_succ'] + simp only [pow_zero,Nat.cast_one,one_div,inv_one,zero_add,pow_one,map_sub, + coeff_one,Nat.succ_ne_zero,ite_false,sub_zero,one_smul] + rw [add_comm] + +lemma log_leading_difference (f g : PowerSeries R) (n : ℕ) + (hf : constantCoeff f=1) (hg : constantCoeff g=1) + (h : ∀j≤n,coeff j f=coeff j g) : + coeff (n+1) (log f)-coeff (n+1) (log g)=coeff (n+1) f-coeff (n+1) g := by + rw [log_coeff_succ,log_coeff_succ] + have hs : (∑k∈Finset.range n,((-1:ℚ)^(k+1)/(k+2:ℕ)) • coeff (n+1) ((f-1)^(k+2)))= + ∑k∈Finset.range n,((-1:ℚ)^(k+1)/(k+2:ℕ)) • coeff (n+1) ((g-1)^(k+2)) := by + apply Finset.sum_congr rfl + intro k hk + congr 1 + apply pow_coeff_congr_of_two_le + · simp [hf] + · simp [hg] + · omega + · intro j hj + simp only [map_sub,h j (by omega)] + rw [hs] + abel +end +end ElementaryPositivity.FormalLog +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/Product.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/Product.lean new file mode 100644 index 0000000000000000000000000000000000000000..82731099e47fb232a56af8e1d80fe08243465e97 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/Product.lean @@ -0,0 +1,146 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.CanonicalCard + +namespace OAI + +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] + +def OnSlopeOrZero (c η : I → ℝ) (θ : ℝ) (d : I → ℕ) : Prop := + d = 0 ∨ slope c η d = θ + +lemma onSlopeOrZero_of_mass (c η : I → ℝ) (hc : ∀ i,0 slope c η (d+e) * mass c d) : + d≠0 ∧ e≠0 ∧ slope c η d > slope c η (d+e) := by + have hd : d≠0 := by intro hh; simp [hh] at h + have he : e≠0 := by + intro hh + rw [hh,add_zero,mass_eq c η hc d] at h + exact lt_irrefl _ h + exact ⟨hd,he,(lt_div_iff₀ (mass_pos c hc d hd)).mpr h⟩ + +def CellsOnSlope (c η : I → ℝ) (θ : ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : Prop := + OnSlopeOrZero c η θ d₁ ∧ OnSlopeOrZero c η θ e₁ ∧ + OnSlopeOrZero c η θ d₂ ∧ OnSlopeOrZero c η θ e₂ + +theorem offSlope_destabilizes (c η : I → ℝ) (hc : ∀ i,0 slope c η (d₁+e₁)) ∨ + (d₂≠0 ∧ e₂≠0 ∧ slope c η d₂ > slope c η (d₂+e₂)) := by + let θ := slope c η (d₁+e₁) + by_cases h₁ : mass η d₁ > θ * mass c d₁ + · exact Or.inl (high_mass_destabilizes c η hc d₁ e₁ h₁) + by_cases h₂ : mass η d₂ > θ * mass c d₂ + · exact Or.inr (high_mass_destabilizes c η hc d₂ e₂ (by simpa only [θ,ht] using h₂)) + have hsrc : mass η d₁ + mass η d₂ = θ * (mass c d₁ + mass c d₂) := by + have h := mass_eq c η hc (d₁+d₂) + rwa [mass_add,mass_add,hs] at h + have htar₁ : mass η d₁ + mass η e₁ = θ * (mass c d₁ + mass c e₁) := by + have h := mass_eq c η hc (d₁+e₁) + rwa [mass_add,mass_add] at h + have htar₂ : mass η d₂ + mass η e₂ = θ * (mass c d₂ + mass c e₂) := by + have h := mass_eq c η hc (d₂+e₂) + rwa [mass_add,mass_add,← ht] at h + have hd₁ : mass η d₁ = θ * mass c d₁ := by nlinarith + have hd₂ : mass η d₂ = θ * mass c d₂ := by nlinarith + have he₁ : mass η e₁ = θ * mass c e₁ := by nlinarith + have he₂ : mass η e₂ = θ * mass c e₂ := by nlinarith + exact (hoff ⟨onSlopeOrZero_of_mass c η hc θ d₁ hd₁, + onSlopeOrZero_of_mass c η hc θ e₁ he₁,onSlopeOrZero_of_mass c η hc θ d₂ hd₂, + onSlopeOrZero_of_mass c η hc θ e₂ he₂⟩).elim + +end ElementaryPositivity.SlopeArithmetic + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open ElementaryPositivity.SlopeArithmetic +open scoped TensorProduct +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + +lemma quotient_cellTransfer_offSlope (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(u i).val) (shapeComplement u) (fun i=>(v i).val) (shapeComplement v)) : + quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v) = 0 := by + unfold gridShapeTensor + apply quotientTensor_cast_zero + by_cases hsum : (fun i=>(u i).val) + (fun i=>(v i).val) = d + · apply quotient_cellTransfer_offSlope a c η hc + · rw [(shape_add_complement u).trans (realization_card R), + (shape_add_complement v).trans (realization_card T)] + exact ht + · rw [hsum,(shape_add_complement u).trans (realization_card R)] + exact hs + · rwa [(shape_add_complement u).trans (realization_card R)] + · rw [fourGridPolynomial_zero_of_source_mismatch a f g _ _ _ _ hsum,map_zero,map_zero] + +omit [(index : I) → Fintype (A index)] in +theorem quotient_gridTensor_sameSlope_support (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(u i).val) (shapeComplement u) (fun i=>(v i).val) (shapeComplement v) + then quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v) else 0 := by + classical + simp only [gridTensor,map_sum] + apply Finset.sum_congr rfl + intro u hu + apply Finset.sum_congr rfl + intro v hv + split_ifs with hon + · rfl + · exact quotient_gridShapeTensor_offSlope a c η hc f g p R T u v ht hs hon + +theorem cleared_restriction_sameSlope_support (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(x i).val) (shapeComplement x) (fun i=>(y i).val) (shapeComplement y) + then quotientTensor a (slope c η) α β + (gridShapeTensor a f g (cutRealizationEquiv R u).val + (leftRealization R u) (rightRealization R u) x y) else 0 := by + rw [← map_mul,cleared_restrictTensor a h f g R u,map_smul] + rw [quotient_gridTensor_sameSlope_support a c η hc f g _ _ _ ht hs] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/ProjectionRecursion.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/ProjectionRecursion.lean new file mode 100644 index 0000000000000000000000000000000000000000..b19fe35f5536686a4e2f96a46d53819b569b0fef --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/ProjectionRecursion.lean @@ -0,0 +1,41 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplit + +namespace OAI + +section +namespace ElementaryPositivity.PowerSeriesSplit +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] + +lemma left_coeff_projection (Q : R →+ R) (S : Subring R) + (hQ : ∀x,Q (Q x)=Q x) (hOne : Q 1=1) + (hMem : ∀x∈S,Q x∈S) + (hMul : ∀x∈S,∀y∈S,Q (x*y)=Q x*Q y) + (f : PowerSeries R) (hf : constantCoeff f=1) (hS : ∀n,coeff n f∈S) (n : ℕ) : + coeff n (leftFactor Q f)=Q (coeff n f) := by + have hs:=factors_mem Q S hMem f hS + cases n with + | zero => simp only [coeff_zero_eq_constantCoeff_apply,left_constant,hf,hOne] + | succ n => + conv_lhs => rw [leftFactor,coeff_mk,pairCoefficients] + have hleft (k : ℕ) : coeff k (leftFactor Q f)=(pairCoefficients Q f k).1 := by simp only [leftFactor,coeff_mk] + have hright (k : ℕ) : coeff k (rightFactor Q f)=(pairCoefficients Q f k).2 := by simp only [rightFactor,coeff_mk] + simp only [←hleft,←hright] + change Q (coeff (n+1) f-∑i : Fin n, + coeff (i.val+1) (leftFactor Q f)*coeff (n-i.val) (rightFactor Q f))=Q (coeff (n+1) f) + rw [map_sub,map_sum] + suffices H : (∑i : Fin n,Q (coeff (i.val+1) (leftFactor Q f)* + coeff (n-i.val) (rightFactor Q f)))=0 by rw [H,sub_zero] + apply Finset.sum_eq_zero + intro i hi + rw [hMul _ (hs.1 (i.val+1)) _ (hs.2 (n-i.val))] + have he : n-i.val=(n-i.val-1)+1 := by omega + rw [he,right_killed Q hQ,mul_zero] +end +end ElementaryPositivity.PowerSeriesSplit + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureCoefficient.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureCoefficient.lean new file mode 100644 index 0000000000000000000000000000000000000000..35ef02ad564af5bb9e9f4287092cd9fa9681c730 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureCoefficient.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalTorusFaithful +import OAI.Combinatorics.Chromatic.GradedAlgebra.RationalCenteredAction + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus WallUnits PowerSeries +noncomputable section +variable {K M:Type*} [Field K] [AddCommGroup M] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (k:M →+ ℤ) (p:M) (hp:k p=1) + +lemma ofPowerSeries_negative (f:PowerSeries K) (j:ℤ) (hj:j<0) : + (HahnSeries.ofPowerSeries ℤ K f).coeff j=0 := by + rw [HahnSeries.ofPowerSeries_apply] + apply HahnSeries.embDomain_notin_image_support + rintro ⟨n,_,hn⟩ + have he : (n:ℤ)=j := hn + omega + +include hΩ in +lemma read_pure_monomial_support + (hq:∀n:ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) (b m:M) + (hm:readFiber v Ω k p hp m + (pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.X v Ω b)))≠0) : + ∃j:ℕ,m=b+j • p := by + classical + rw [Torus.X,embed_monomial,pureAction_monomial,map_one,one_mul, + complement_pairing Ω hΩ k p hp b] at hm + change (expandZero ((Finsupp.single (off k p hp b) + (centeredScalar v (k b) (Ω p b)*(pureRatio v (Ω p b):RatFunc K))) + (off k p hp m))).coeff (k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K)≠0 at hm + have ho:off k p hp b=off k p hp m:=by + by_contra hh + simp only [Finsupp.single_apply,ite_eq_right hh,map_zero,HahnSeries.coeff_zero,zero_mul,ne_eq,not_true_eq_false] at hm + rw [Finsupp.single_apply,ite_eq_left ho,map_mul] at hm + rw [show expandZero (centeredScalar v (k b) (Ω p b))= + HahnSeries.single (k b) (↑(v^(-k b*Ω p b)):K) by + simpa using expand_centeredScalar v (k b) (Ω p b) (1:K), + expandedPure_ratio v hq,HahnSeries.coeff_single_mul] at hm + have hk:0≤k m-k b:=by + by_contra hh + rw [ofPowerSeries_negative _ _ (lt_of_not_ge hh),mul_zero,zero_mul] at hm + exact hm rfl + refine ⟨(k m-k b).toNat,split_injective k p hp ?_ ?_⟩ + · simp only [map_add,map_nsmul,nsmul_eq_mul,hp,mul_one,Int.toNat_of_nonneg hk] + omega + · simp only [map_add,map_nsmul,off_p,smul_zero,add_zero] + exact ho.symm +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureComparisonIdentification.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureComparisonIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..bfb780512362b706dc6c9829b34dda871b564618 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureComparisonIdentification.lean @@ -0,0 +1,212 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SimpleIncomingElement +import OAI.Combinatorics.Chromatic.Walls.CompletedPureComparison +import OAI.Combinatorics.Chromatic.Walls.CompletedBiUnit + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +lemma laurent_shiftedElementary_zero : shiftedElementary LaurentRay.vUnit 0= + elementary (HahnSeries.single (2:ℤ) (1:ℚ)) (HahnSeries.single (1:ℤ) (1:ℚ)) := by + rw [shiftedElementary_zero,←zpow_neg_one, LaurentRay.vUnit_zpow,LaurentRay.vUnit_zpow] + rfl +omit [Fintype I] in +include hcoord in +lemma pureDegree_simple_self : pureDegree coord pc (simpleRoot C pc)=1 := by + change coord (simpleRoot C pc) pc=1 + rw [simpleRoot_coordinates C coord hcoord,Pi.single_eq_same] + +lemma completedBiUnit_pure (h : M →+ ℝ) + (hg : ∀N,RayGeneric C N (simpleRoot C pc) h) : + completedBiUnit LaurentRay.vUnit Ω C coord hcoord pc + (chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C))= + oldPureUnit LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) := by + apply Units.ext + apply Subtype.ext + change (chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).val= + raySeries LaurentRay.vUnit Ω (simpleRoot C pc) (shiftedElementary LaurentRay.vUnit 0) + rw [laurent_shiftedElementary_zero] + apply PowerSeries.ext + intro n + exact pure_simple_wall Ω C coord hcoord pc hΩ n h (hg n) n le_rfl +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.BiTruncation +open PowerSeries +variable {R : Type*} [Semiring R] +def Through (N : ℕ) (f g : PowerSeries (PowerSeries R)) : Prop := + ∀d e,d+e≤N → coeff e (coeff d f)=coeff e (coeff d g) +lemma Through.refl (N : ℕ) (f : PowerSeries (PowerSeries R)) : Through N f f := by + intro d e h; rfl +lemma Through.symm {N : ℕ} {f g : PowerSeries (PowerSeries R)} (h : Through N f g) : + Through N g f := by intro d e he; exact (h d e he).symm +lemma Through.trans {N : ℕ} {f g h : PowerSeries (PowerSeries R)} + (hfg : Through N f g) (hgh : Through N g h) : Through N f h := by + intro d e he; exact (hfg d e he).trans (hgh d e he) +lemma Through.mul {N : ℕ} {f f' g g' : PowerSeries (PowerSeries R)} + (hf : Through N f f') (hg : Through N g g') : Through N (f*g) (f'*g') := by + intro d e hde + simp only [coeff_mul,map_sum] + apply Finset.sum_congr rfl + intro ij hij + apply Finset.sum_congr rfl + intro kl hkl + have H1:=Finset.HasAntidiagonal.mem_antidiagonal.mp hij + have H2:=Finset.HasAntidiagonal.mem_antidiagonal.mp hkl + rw [hf ij.1 kl.1 (by omega),hg ij.2 kl.2 (by omega)] +lemma Through.conjugate {N : ℕ} {u w : PowerSeries (PowerSeries R)} + (hu : Through N u 1) (hw : Through N w 1) (f : PowerSeries (PowerSeries R)) : + Through N (u*f*w) f := by + simpa only [one_mul,mul_one] using (hu.mul (Through.refl N f)).mul hw +lemma ext {f g : PowerSeries (PowerSeries R)} (h : ∀N,Through N f g) : f=g := by + apply PowerSeries.ext + intro d + apply PowerSeries.ext + intro e + exact h (d+e) d e le_rfl +end ElementaryPositivity.BiTruncation + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries BiTruncation +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ κ : M →+ ℤ) +local instance biThroughRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance biThroughAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance biThroughAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance biThroughNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance biThroughNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +lemma biRegrade_through {f g : PowerSeries (Torus v Ω)} (N : ℕ) + (h : ∀n≤N,coeff n f=coeff n g) : + Through N (biRegrade v Ω δ κ f) (biRegrade v Ω δ κ g) := by + intro d e he + rw [biRegrade_coeff,biRegrade_coeff,h (d+e) he] +lemma oldLaurent_through {f g : PowerSeries (Torus v Ω)} (N : ℕ) + (h : ∀n≤N,coeff n f=coeff n g) (d e : ℕ) (he : d+e≤N) : + (coeff d (oldLaurent v Ω δ κ f)).coeff (e:ℤ)= + (coeff d (oldLaurent v Ω δ κ g)).coeff (e:ℤ) := by + simp only [oldLaurent,coeff_map,HahnSeries.ofPowerSeries_apply_coeff] + exact biRegrade_through v Ω δ κ N h d e he +lemma oldLaurent_inner_through (u : (biSupportedSubring v Ω δ κ)ˣ) (N : ℕ) + (hv : ∀n≤N,coeff n u.val.val=coeff n 1) + (hi : ∀n≤N,coeff n u.inv.val=coeff n 1) + (f : PowerSeries (PowerSeries (Torus v Ω))) (d e : ℕ) (he : d+e≤N) : + (coeff d (oldLaurent v Ω δ κ u.val.val* + PowerSeries.map (HahnSeries.ofPowerSeries ℤ (Torus v Ω)) f* + oldLaurent v Ω δ κ u.inv.val)).coeff (e:ℤ)=coeff e (coeff d f) := by + have H:=Through.conjugate + (show Through N (biRegrade v Ω δ κ u.val.val) 1 by + simpa only [biRegrade_one] using biRegrade_through v Ω δ κ N hv) + (show Through N (biRegrade v Ω δ κ u.inv.val) 1 by + simpa only [biRegrade_one] using biRegrade_through v Ω δ κ N hi) f d e he + unfold oldLaurent + rw [←map_mul,←map_mul,coeff_map,HahnSeries.ofPowerSeries_apply_coeff] + exact H +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (δ k : M →+ ℤ) (p : M) (hp : k p=1) (B : ℕ) +local instance rationalThroughRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance rationalThroughAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance rationalThroughAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance rationalThroughNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance rationalThroughNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +lemma regrade_congr_through (D : ℕ) {f g : PowerSeries (Torus v Ω)} + (he : ∀n≤B*D,coeff n f=coeff n g) : + ∀d≤D,coeff d (regrade v Ω δ B f)=coeff d (regrade v Ω δ B g) := by + intro d hd + rw [regrade_coeff,regrade_coeff] + apply Finset.sum_congr rfl + intro n hn + rw [he n (by have H:=Finset.mem_range.mp hn; have HH:=Nat.mul_le_mul_left B hd; omega)] +lemma rationalRegrade_congr_through (D : ℕ) {f g : PowerSeries (Torus v Ω)} + (he : ∀n≤B*D,coeff n f=coeff n g) : + ∀d≤D,coeff d (rationalRegrade v Ω hΩ k p hp δ B f)= + coeff d (rationalRegrade v Ω hΩ k p hp δ B g) := by + intro d hd + simp only [rationalRegrade,coeff_map] + rw [regrade_congr_through v Ω δ B D he d hd] +lemma oldUnit_inverse_congr (u w : (biSupportedSubring v Ω δ k)ˣ) (N : ℕ) + (h : ∀n≤N,coeff n u.val.val=coeff n w.val.val) : + ∀n≤N,coeff n u.inv.val=coeff n w.inv.val := by + intro n hn + have HE:=FormalLog.mul_coeff_congr u.inv.val (u.val.val*w.inv.val) + u.inv.val (w.val.val*w.inv.val) n (fun _ _=>rfl) (by + intro j hj + exact FormalLog.mul_coeff_congr _ _ _ _ j (fun t ht=>h t (ht.trans (hj.trans hn))) (fun _ _=>rfl)) + have hu : u.inv.val*u.val.val=1:=congrArg (fun a : biSupportedSubring v Ω δ k=>a.val) u.inv_val + have hw : w.val.val*w.inv.val=1:=congrArg (fun a : biSupportedSubring v Ω δ k=>a.val) w.val_inv + rw [←mul_assoc,hu,one_mul,hw,mul_one] at HE + exact HE.symm +lemma innerHom_coeff_congr {A : Type*} [Ring A] (u w : (PowerSeries A)ˣ) + (f g : PowerSeries A) (N : ℕ) + (hv : ∀n≤N,coeff n u.val=coeff n w.val) + (hi : ∀n≤N,coeff n u.inv=coeff n w.inv) + (hf : ∀n≤N,coeff n f=coeff n g) : + coeff N (innerHom u f)=coeff N (innerHom w g) := by + change coeff N (u.val*f*u.inv)=coeff N (w.val*g*w.inv) + apply FormalLog.mul_coeff_congr + · intro j hj + exact FormalLog.mul_coeff_congr _ _ _ _ j (fun t ht=>hv t (ht.trans hj)) + (fun t ht=>hf t (ht.trans hj)) + · exact hi +lemma comparisonAction_input_congr (c : ComparisonCrossing v Ω δ k B) + (f g : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) + (N : ℕ) (hg : ∀n≤N,coeff n f=coeff n g) : + coeff N (comparisonAction v Ω hΩ δ k p hp B c f)= + coeff N (comparisonAction v Ω hΩ δ k p hp B c g) := by + cases c with + | bounded u hf hi=>exact innerHom_coeff_congr _ _ _ _ N (fun _ _=>rfl) (fun _ _=>rfl) hg + | pure b=> + cases b + · change coeff N (PowerSeries.map (pureAction v (complementOmega k Ω) (complementAlpha k p Ω)).symm.toRingHom f)= + coeff N (PowerSeries.map (pureAction v (complementOmega k Ω) (complementAlpha k p Ω)).symm.toRingHom g) + rw [coeff_map,coeff_map,hg N le_rfl] + · change coeff N (PowerSeries.map (pureAction v (complementOmega k Ω) (complementAlpha k p Ω)).toRingHom f)= + coeff N (PowerSeries.map (pureAction v (complementOmega k Ω) (complementAlpha k p Ω)).toRingHom g) + rw [coeff_map,coeff_map,hg N le_rfl] +lemma bounded_action_congr (D : ℕ) (u w : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hi : RegradeBound v Ω δ B u.inv.val) + (hf' : RegradeBound v Ω δ B w.val.val) (hi' : RegradeBound v Ω δ B w.inv.val) + (he : ∀n≤B*D,coeff n u.val.val=coeff n w.val.val) + (f g : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) + (hg : ∀n≤D,coeff n f=coeff n g) : + ∀d≤D,coeff d (comparisonAction v Ω hΩ δ k p hp B (.bounded u hf hi) f)= + coeff d (comparisonAction v Ω hΩ δ k p hp B (.bounded w hf' hi') g) := by + intro d hd + apply innerHom_coeff_congr + · intro n hn + exact rationalRegrade_congr_through v Ω hΩ δ k p hp B D he n (hn.trans hd) + · intro n hn + exact rationalRegrade_congr_through v Ω hΩ δ k p hp B D + (oldUnit_inverse_congr v Ω δ k u w (B*D) he) n (hn.trans hd) + · exact fun n hn=>hg n (hn.trans hd) +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureFaceLog.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureFaceLog.lean new file mode 100644 index 0000000000000000000000000000000000000000..710b4b785d6723497a5999f7e51511c7958c4a3b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PureFaceLog.lean @@ -0,0 +1,114 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SimpleIncomingData +import OAI.Combinatorics.Chromatic.QuantumTorus.PureFaceProjection + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance pureFaceLogAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommGroup +local instance pureFaceLogAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance pureFaceLogAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance pureFaceLogSub : Sub (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toSub +omit [DecidableEq I] in +lemma graded_series_pow (F : PowerSeries (Torus LaurentRay.vUnit Ω)) + (hF : ∀n,coeff n F∈rootGrade LaurentRay.vUnit Ω C n) (k : ℕ) : + ∀n,coeff n (F^k)∈rootGrade LaurentRay.vUnit Ω C n := by + induction k with + | zero=>simpa only [pow_zero] using FormalLog.graded_one _ (rootGrade_one LaurentRay.vUnit Ω C) + | succ k ih=>simpa only [pow_succ] using FormalLog.graded_multiply _ (rootGrade_mul LaurentRay.vUnit Ω C) _ _ ih hF +include hcoord in +lemma pureFaceSeries_pow (F : PowerSeries (Torus LaurentRay.vUnit Ω)) + (hF : ∀n,coeff n F∈rootGrade LaurentRay.vUnit Ω C n) (k : ℕ) : + pureFaceSeries Ω coord pc (F^k)=(pureFaceSeries Ω coord pc F)^k := by + induction k with + | zero=>simpa only [pow_zero] using pureFaceSeries_one Ω coord pc + | succ k ih=>rw [pow_succ,pureFaceSeries_mul Ω C coord hcoord pc _ _ + (graded_series_pow Ω C F hF k) hF,ih,pow_succ] +lemma zeroProject_rat_smul (h : M →+ ℝ) (a : ℚ) (x : Torus LaurentRay.vUnit Ω) : + zeroProject LaurentRay.vUnit Ω h (a • x)=a • zeroProject LaurentRay.vUnit Ω h x := by + classical + exact map_rat_smul (zeroProject LaurentRay.vUnit Ω h) a x +include hcoord in +lemma pureFaceSeries_log (F : CompletedPositive LaurentRay.vUnit Ω C) : + pureFaceSeries Ω coord pc (FormalLog.log F.val)=FormalLog.log (pureFace Ω C coord pc F).val := by + have hu : ∀n,coeff n (F.val-1)∈rootGrade LaurentRay.vUnit Ω C n:=by + intro n + rw [map_sub] + exact (rootGrade LaurentRay.vUnit Ω C n).sub_mem (F.property.2 n) + (FormalLog.graded_one _ (rootGrade_one LaurentRay.vUnit Ω C) n) + apply PowerSeries.ext + intro n + rw [coeff_pureFaceSeries] + simp only [FormalLog.log,coeff_mk,map_sum] + apply Finset.sum_congr rfl + intro k hk + rw [zeroProject_rat_smul,←coeff_pureFaceSeries,pureFaceSeries_pow Ω C coord hcoord pc _ hu, + pureFaceSeries_sub,pureFaceSeries_one] + rfl +include hcoord in +lemma pureFace_log_chart_apply (h : M →+ ℝ) (hp : h (simpleRoot C pc)=0) + (F : CompletedPositive LaurentRay.vUnit Ω C) (n : ℕ) (m : M) + (hm : nonpDegree coord pc m=0) : + coeff n (FormalLog.log (chartZero LaurentRay.vUnit Ω C h F).val) m= + coeff n (FormalLog.log F.val) m := by + have H:=congrArg (fun D : CompletedPositive LaurentRay.vUnit Ω C=>coeff n (FormalLog.log D.val) m) + (pureFace_chartZero Ω C coord hcoord pc h hp F) + rw [←pureFaceSeries_log Ω C coord hcoord pc,←pureFaceSeries_log Ω C coord hcoord pc] at H + simpa only [pureFaceSeries_apply,hm,ite_true] using H +include hcoord in +lemma pureFace_simpleTransport (hΩ : ∀m,Ω m m=0) : + pureFace Ω C coord pc (simpleTotalTransport Ω C)= + literalIncomingCompleted Ω C (simpleIncomingList C) (simpleIncomingList_allowed C) (simpleRoot C pc) := by + let F:=simpleTotalTransport Ω C + let D:=literalIncomingCompleted Ω C (simpleIncomingList C) (simpleIncomingList_allowed C) (simpleRoot C pc) + apply Subtype.ext + apply PowerSeries.ext + intro N + apply FormalLog.log_injective_through (pureFace Ω C coord pc F).val D.val N + (pureFace Ω C coord pc F).property.1 D.property.1 + intro n hn + apply Finsupp.ext + intro m + rw [←pureFaceSeries_log Ω C coord hcoord pc,pureFaceSeries_apply] + have hdlog : ∀j m,coeff j (FormalLog.log D.val) m≠0→OnPositiveRay (simpleRoot C pc) m:=by + intro j m hm + by_contra hh + exact hm (strict_log_support LaurentRay.vUnit Ω (fun a b ha hb=>ha.add hb) D.val D.property.1 + (literalRootProducts_strictSupport Ω C (OnPositiveRay (simpleRoot C pc)) + (fun a b ha hb=>ha.add hb) + (literalIncomingRay_mem Ω C (simpleIncomingList C) (simpleIncomingList_allowed C) (simpleRoot C pc))) j m hh) + by_cases hz : nonpDegree coord pc m=0 + · rw [ite_eq_left hz] + by_cases hr : HasRootDegree C n m + · cases n with + | zero=>simp only [coeff_zero_eq_constantCoeff_apply,FormalLog.log_constant,Finsupp.zero_apply] + | succ n=> + have hmray : OnPositiveRay (simpleRoot C pc) m:=by + refine ⟨1,n+1,by omega,by omega,?_⟩ + rw [one_nsmul,nonp_zero_root C coord hcoord pc hr hz] + have hp : incomingCovector Ω m (simpleRoot C pc)=0:=by + change (Ω (simpleRoot C pc) m : ℝ)=0 + rw [nonp_zero_root C coord hcoord pc hr hz,map_nsmul,hΩ,nsmul_zero,Int.cast_zero] + rw [←pureFace_log_chart_apply Ω C coord hcoord pc (incomingCovector Ω m) hp F _ m hz] + exact literalTotalTransport_ray_prescription Ω C hΩ _ (simpleIncomingList_allowed C) _ _ _ hmray + · rw [root_graded_log LaurentRay.vUnit Ω C F n m hr,root_graded_log LaurentRay.vUnit Ω C D n m hr] + · rw [ite_eq_right hz] + by_contra hh + have hmr:=hdlog n m (Ne.symm hh) + obtain ⟨a,b,ha,hb,he⟩:=hmr + have HH:=congrArg (nonpDegree coord pc) he + rw [map_nsmul,map_nsmul,nonpDegree_simple_self C coord hcoord,nsmul_zero,nsmul_eq_mul] at HH + exact hz ((mul_eq_zero.mp HH).resolve_left (by exact_mod_cast (Nat.ne_of_gt ha))) + exact Nat.le_refl N +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PurePolynomialCoefficients.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PurePolynomialCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..56a8572fdd3944999662ab9cc959aaa99d475a22 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/PurePolynomialCoefficients.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PureActualCoefficients + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus WallUnits PowerSeries +noncomputable section +variable {K M:Type*} [Field K] [AddCommGroup M] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (k:M →+ ℤ) (p:M) (hp:k p=1) +lemma read_pure_scalar_monomial (b m:M) (c:K) : + readFiber v Ω k p hp m + (pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.monomial v Ω b c)))= + c*readFiber v Ω k p hp m + (pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.X v Ω b))) := by + classical + rw [Torus.X,embed_monomial,embed_monomial,pureAction_monomial,pureAction_monomial,map_one,one_mul] + change (expandZero ((Finsupp.single (off k p hp b) + ((RatFunc.C c*centeredScalar v (k b) (complementAlpha k p Ω (off k p hp b)))* + (pureRatio v (complementAlpha k p Ω (off k p hp b)):RatFunc K))) + (off k p hp m))).coeff (k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K)= + c*((expandZero ((Finsupp.single (off k p hp b) + (centeredScalar v (k b) (complementAlpha k p Ω (off k p hp b))* + (pureRatio v (complementAlpha k p Ω (off k p hp b)):RatFunc K))) + (off k p hp m))).coeff (k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K)) + by_cases ho:off k p hp b=off k p hp m + · simp only [Finsupp.single_apply,ite_eq_left ho] + rw [mul_assoc,map_mul,expandZero_constant] + change ((HahnSeries.single 0 c:HahnSeries ℤ K)*_).coeff (k m)*_=c*(_*_) + rw [HahnSeries.coeff_single_mul,sub_zero,mul_assoc] + · simp only [Finsupp.single_apply,ite_eq_right ho,map_zero,HahnSeries.coeff_zero,zero_mul,mul_zero] +end +end ElementaryPositivity.RationalFiber +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits RationalFiber +noncomputable section +variable {M:Type*} [AddCommGroup M] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) (τ:M →+ ℤ) +local instance purePolynomialCoefficientsRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance purePolynomialCoefficientsAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance purePolynomialCoefficientsAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +include hΩ in +lemma actual_pure_polynomial (k:M →+ ℤ) (p:M) (hp:k p=1) (hτ:τ p=1) + (F:Torus LaurentRay.vUnit Ω) (m:M) : + actualPolynomialAdjointCoefficient Ω τ (normalizedSimple Ω p) F m= + readFiber LaurentRay.vUnit Ω k p hp m + (pureAction LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω) + (embed LaurentRay.vUnit Ω hΩ k p hp F)) := by + classical + induction F using Finsupp.induction_linear with + | zero=>simp [actualPolynomialAdjointCoefficient] + | add F G hF hG=>rw [actualPolynomialAdjointCoefficient_add,map_add,map_add,map_add,hF,hG] + | single b c=> + change actualPolynomialAdjointCoefficient Ω τ (normalizedSimple Ω p) + (Torus.monomial LaurentRay.vUnit Ω b c) m=_ + rw [actualPolynomialAdjointCoefficient_monomial,actual_pure_monomial Ω hΩ τ k p hp hτ] + exact (read_pure_scalar_monomial LaurentRay.vUnit Ω hΩ k p hp b m c).symm +include hΩ in +lemma actual_pure_finite (k:M →+ ℤ) (p:M) (hp:k p=1) (hτ:τ p=1) + (F G:Torus LaurentRay.vUnit Ω) + (h:embed LaurentRay.vUnit Ω hΩ k p hp G= + pureAction LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω) + (embed LaurentRay.vUnit Ω hΩ k p hp F)) (m:M) : + actualPolynomialAdjointCoefficient Ω τ (normalizedSimple Ω p) F m=G m := by + rw [actual_pure_polynomial Ω hΩ τ k p hp hτ,←h] + exact readFiber_embedAdd LaurentRay.vUnit Ω k p hp G m +include hΩ in +lemma actual_pure_order_independent (σ:M →+ ℤ) (p:M) (hτ:τ p=1) (hσ:σ p=1) + (F:Torus LaurentRay.vUnit Ω) (m:M) : + actualPolynomialAdjointCoefficient Ω τ (normalizedSimple Ω p) F m= + actualPolynomialAdjointCoefficient Ω σ (normalizedSimple Ω p) F m := by + rw [actual_pure_polynomial Ω hΩ τ τ p hτ hτ, + actual_pure_polynomial Ω hΩ σ τ p hτ hσ] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/QuantumTorusAlgebra.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/QuantumTorusAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..8290cb3d6c48eed7201d437f2b0d8753bfd822db --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/QuantumTorusAlgebra.lean @@ -0,0 +1,51 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus + +namespace OAI + +section +section +namespace ElementaryPositivity.QuantumTorus.Torus +noncomputable section +variable {S R M : Type*} [CommSemiring S] [CommRing R] [Algebra S R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) + +lemma scalar_one (r : S) : r • (1 : Torus v Ω)=monomial v Ω 0 (r • (1:R)) := by + change r • Finsupp.single 0 (1:R)=Finsupp.single 0 (r • (1:R)) + exact Finsupp.smul_single _ _ _ + +lemma scalar_one_mul (r : S) (f : Torus v Ω) : + (r • (1 : Torus v Ω))*f=r • f := by + classical + induction f using Finsupp.induction_linear with + | zero => simp + | add f g hf hg => rw [mul_add,hf,hg,smul_add] + | single m a => + change (r • (1 : Torus v Ω))*monomial v Ω m a=r • monomial v Ω m a + rw [scalar_one,monomial_mul_monomial] + simp only [map_zero,AddMonoidHom.zero_apply,zpow_zero,Units.val_one,zero_add,_root_.mul_one, + smul_mul_assoc,_root_.one_mul,monomial,Finsupp.smul_single] + +lemma mul_scalar_one (r : S) (f : Torus v Ω) : + f*(r • (1 : Torus v Ω))=r • f := by + classical + induction f using Finsupp.induction_linear with + | zero => simp + | add f g hf hg => rw [add_mul,hf,hg,smul_add] + | single m a => + change monomial v Ω m a*(r • (1 : Torus v Ω))=r • monomial v Ω m a + rw [scalar_one,monomial_mul_monomial] + simp only [map_zero,zpow_zero,Units.val_one,add_zero,_root_.mul_one, + mul_smul_comm,_root_.mul_one,monomial,Finsupp.smul_single] + +instance : Algebra S (Torus v Ω) := by + letI : Module S (Torus v Ω) := inferInstanceAs (Module S (M →₀ R)) + exact @Algebra.ofModule' S (Torus v Ω) _ (Torus.instRing v Ω).toSemiring + (inferInstanceAs (Module S (M →₀ R))) + (scalar_one_mul (S:=S) v Ω) (mul_scalar_one (S:=S) v Ω) +end +end ElementaryPositivity.QuantumTorus.Torus +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/QuantumTorusSignFactors.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/QuantumTorusSignFactors.lean new file mode 100644 index 0000000000000000000000000000000000000000..92be2d693274b2d07f96cd239eeab75cd8aa4e3e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/QuantumTorusSignFactors.lean @@ -0,0 +1,101 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus + +namespace OAI + +section +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) + + def supportedSubring (C : AddSubmonoid M) : Subring (Torus v Ω) where + carrier := {f | ∀m,m∉C → f m=0} + zero_mem' := by intro m hm; rfl + one_mem' := by + intro m hm + change Finsupp.single 0 (1:R) m=0 + exact Finsupp.single_eq_of_ne (fun he=>hm (he ▸ C.zero_mem)) + add_mem' := by intro f g hf hg m hm; change f m+g m=0; rw [hf m hm,hg m hm,add_zero] + neg_mem' := by intro f hf m hm; change -f m=0; rw [hf m hm,neg_zero] + mul_mem' := by + classical + intro f g hf hg m hm + change (Torus.multiply v Ω f g) m=0 + simp only [Torus.multiply,Finsupp.sum,Finsupp.finsetSum_apply] + apply Finset.sum_eq_zero + intro x hx + apply Finset.sum_eq_zero + intro y hy + have hxC : x∈C := by + by_contra hn + exact (Finsupp.mem_support_iff.mp hx) (hf x hn) + have hyC : y∈C := by + by_contra hn + exact (Finsupp.mem_support_iff.mp hy) (hg y hn) + apply Finsupp.single_eq_of_ne + intro he + apply hm + exact he ▸ C.add_mem hxC hyC + +variable (h : M →+ ℝ) + def nonpositiveCone : AddSubmonoid M where + carrier := {m | h m≤0} + zero_mem' := by simp + add_mem' := by + intro a b ha hb + change h a≤0 at ha + change h b≤0 at hb + change h (a+b)≤0 + rw [map_add] + linarith + def positiveProject : Torus v Ω →+ Torus v Ω := + Finsupp.filterAddHom (fun m=>0h m=0) + +lemma nonpositive_iff (f : Torus v Ω) : + f∈supportedSubring v Ω (nonpositiveCone h) ↔ positiveProject v Ω h f=0 := by + classical + change (∀m,¬h m≤0 → f m=0) ↔ Finsupp.filter (fun m=>0f m) hf + simpa only [Finsupp.filter_apply,not_le.mp hm,ite_true,Finsupp.zero_apply] using hh + +lemma positiveProject_idem (f : Torus v Ω) : + positiveProject v Ω h (positiveProject v Ω h f)=positiveProject v Ω h f := by + classical + ext m + change (f.filter (fun m=>0.filter (fun m=>00 rfl +lemma zeroProject_idem (f : Torus v Ω) : + zeroProject v Ω h (zeroProject v Ω h f)=zeroProject v Ω h f := by + classical + ext m + change (f.filter (fun m=>h m=0) |>.filter (fun m=>h m=0)) m = (f.filter (fun m=>h m=0)) m + simp only [Finsupp.filter_apply] + split_ifs <;> rfl +lemma positive_zero_project (f : Torus v Ω) : + positiveProject v Ω h (zeroProject v Ω h f)=0 := by + classical + ext m + change (f.filter (fun m=>h m=0) |>.filter (fun m=>0 first | rfl | linarith + +end +end ElementaryPositivity.QuantumTorus +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalCenteredAction.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalCenteredAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..7925e6351f7fa733cdeae7142cb441743d387b17 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalCenteredAction.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalTorusEmbedding +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationRootMap + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus WallUnits Polynomial +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) +lemma centeredPolynomial_degree_le (t : ℕ) : (centeredPolynomial v t).natDegree≤t := by + unfold centeredPolynomial + have H:=Polynomial.natDegree_prod_le Finset.univ + (fun i : Fin t=>(1+Polynomial.C (↑(v^centeredExponent t i):K)*Polynomial.X)) + have H' := Finset.sum_le_sum (s:=Finset.univ) (fun (i : Fin t) _ => + natDegree_linear_le (↑(v^centeredExponent t i):K)) + exact H.trans (by simpa using H') +lemma centered_eval_ratio (t : ℕ) : + (centeredPolynomial v t).eval₂ RatFunc.C + (RatFunc.C (↑(v^(-(t:ℤ))):K)*RatFunc.X)=(pureRatio v (t:ℤ):RatFunc K) := by + change (Polynomial.eval₂RingHom RatFunc.C + (RatFunc.C (↑(v^(-(t:ℤ))):K)*RatFunc.X)) (centeredPolynomial v t)=_ + rw [centeredPolynomial,map_prod,pureRatio_nat_val,←Fin.prod_univ_eq_prod_range] + change (∏i : Fin t, (1+Polynomial.C (↑(v^centeredExponent t i):K)*Polynomial.X).eval₂ RatFunc.C + (RatFunc.C (↑(v^(-(t:ℤ))):K)*RatFunc.X))=_ + have H (i : Fin t) : + (1+Polynomial.C (↑(v^centeredExponent t i):K)*Polynomial.X).eval₂ RatFunc.C + (RatFunc.C (↑(v^(-(t:ℤ))):K)*RatFunc.X)= + 1+RatFunc.C (↑(v^(-2*((i.rev:ℕ):ℤ)-1)):K)*RatFunc.X := by + simp only [Polynomial.eval₂_add,Polynomial.eval₂_one,Polynomial.eval₂_mul, + Polynomial.eval₂_C,Polynomial.eval₂_X] + rw [←mul_assoc,←map_mul,←Units.val_mul,←zpow_add] + congr 4 + simp only [centeredExponent,Fin.val_rev] + have H:=i.isLt + congr 1 + omega + simp_rw [H] + exact Equiv.prod_comp Fin.revPerm + (fun i : Fin t=>1+RatFunc.C (↑(v^(-2*((i:ℕ):ℤ)-1)):K)*RatFunc.X) + +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +include hΩ in +lemma complement_pairing (m : M) : complementAlpha k p Ω (off k p hp m)=Ω p m := by + change Ω p (m-k m • p)=_ + rw [map_sub,map_zsmul,hΩ,smul_zero,sub_zero] +lemma centeredScalar_shift (n a j : ℤ) : centeredScalar v (n+j) a= + centeredScalar v n a*(RatFunc.C (↑(v^(-a)):K)*RatFunc.X)^j := by + have hz : (RatFunc.X:RatFunc K)≠0:=RatFunc.X_ne_zero + rw [centeredScalar,centeredScalar,mul_zpow,←map_zpow₀, + ←Units.val_zpow_eq_zpow_val,←zpow_mul,zpow_add₀ hz] + rw [show -(n+j)*a= -n*a+(-a)*j by ring,zpow_add,Units.val_mul,map_mul] + ring +include hΩ in +lemma embed_pure_row_term (m : M) (j : ℕ) (a : K) : + embed v Ω hΩ k p hp (Torus.monomial v Ω (m+j • p) a)= + FiberTorus.monomial v _ _ (off k p hp m) + (centeredScalar v (k m) (Ω p m)*RatFunc.C a* + (RatFunc.C (↑(v^(-Ω p m)):K)*RatFunc.X)^j) := by + rw [embed_monomial] + simp only [map_add,map_nsmul,hp,nsmul_eq_mul,mul_one,off_p,smul_zero,add_zero] + rw [complement_pairing Ω hΩ k p hp m,centeredScalar_shift] + rw [zpow_natCast] + congr 1 + ring +include hΩ in +lemma pureAction_centered (m : M) (t : ℕ) (ht : Ω p m=(t:ℤ)) : + pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.X v Ω m))= + embed v Ω hΩ k p hp (centeredCrossing v Ω p m t) := by + rw [Torus.X,embed_monomial,pureAction_monomial,map_one,one_mul, + complement_pairing Ω hΩ k p hp m,ht,←centered_eval_ratio] + rw [centeredCrossing,map_sum] + simp_rw [embed_pure_row_term v Ω hΩ k p hp,ht] + have He := Polynomial.eval₂_eq_sum_range' RatFunc.C + (Nat.lt_succ_of_le (centeredPolynomial_degree_le v t)) + (RatFunc.C (↑(v^(-(t:ℤ))):K)*RatFunc.X) + rw [He,Finset.mul_sum] + rw [←Fin.sum_univ_eq_sum_range] + simp only [FiberTorus.monomial,mul_assoc] + classical + exact (map_sum (Finsupp.singleAddHom (off k p hp m)) _ Finset.univ) +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalLaurentFaithful.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalLaurentFaithful.lean new file mode 100644 index 0000000000000000000000000000000000000000..63169490e90705e50dcc7b204d02c81b76771968 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalLaurentFaithful.lean @@ -0,0 +1,164 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegrade +import OAI.Combinatorics.Chromatic.GradedAlgebra.RationalLaurentScalars +import OAI.Combinatorics.Chromatic.Walls.RationalReadExt + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +local instance rationalLaurentFaithfulRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance rationalLaurentFaithfulNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalSemiring +local instance rationalLaurentFaithfulNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +lemma expandFiber_monomial_coeff (l : k.ker) (a : RatFunc K) (n : ℤ) : + (expandFiber v Ω hΩ k p (FiberTorus.monomial v _ _ l a)).coeff n= + Torus.monomial v Ω (n • p+(l:M)) ((expandZero a).coeff n*(↑(v^(n*Ω p l)):K)) := by + change (expandFiberAdd v Ω hΩ k p (FiberTorus.monomial v _ _ l a)).coeff n=_ + rw [expandFiberAdd_monomial,HahnSeries.coeff_mul_single_zero] + change Torus.monomial v Ω (n • p) ((expandZero a).coeff n)*Torus.X v Ω l=_ + simp only [Torus.X,Torus.monomial_mul_monomial,mul_one,map_zsmul,AddMonoidHom.zsmul_apply, + smul_eq_mul] +lemma expansion_embed_monomial (m : M) (a : K) : + expandFiber v Ω hΩ k p (embed v Ω hΩ k p hp (Torus.monomial v Ω m a))= + HahnSeries.single (k m) (Torus.monomial v Ω m a) := by + rw [embed_monomial] + apply HahnSeries.ext + funext n + rw [expandFiber_monomial_coeff,expand_centeredScalar] + simp only [HahnSeries.coeff_single] + by_cases H : n=k m + · subst n + rw [ite_eq_left rfl,ite_eq_left rfl,split_sum k p hp] + congr 1 + change a*(↑(v^(-k m*complementAlpha k p Ω (off k p hp m))):K)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K)=a + rw [mul_assoc,←Units.val_mul,←zpow_add] + simp + · simp [H,Torus.monomial] +lemma expandFiber_read_monomial (m : M) (l : k.ker) (a : RatFunc K) : + ((expandFiber v Ω hΩ k p (FiberTorus.monomial v _ _ l a)).coeff (k m)) m= + readFiber v Ω k p hp m (FiberTorus.monomial v _ _ l a) := by + classical + rw [expandFiber_monomial_coeff] + change Finsupp.single (k m • p+(l:M)) + ((expandZero a).coeff (k m)*(↑(v^(k m*Ω p l)):K)) m= + (expandZero ((Finsupp.single l a) (off k p hp m))).coeff (k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K) + by_cases H : l=off k p hp m + · subst l + rw [split_sum k p hp,Finsupp.single_eq_same,Finsupp.single_eq_same] + rfl + · have hm : k m • p+(l:M)≠m:=by + intro hh + have HO:=congrArg (off k p hp) hh + simp only [map_add,map_zsmul,off_p,smul_zero,off_complement,zero_add] at HO + exact H HO + rw [Finsupp.single_eq_of_ne (Ne.symm hm),Finsupp.single_eq_of_ne (Ne.symm H),map_zero, + HahnSeries.coeff_zero,zero_mul] +lemma expandFiber_read (f : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) (m : M) : + ((expandFiber v Ω hΩ k p f).coeff (k m)) m=readFiber v Ω k p hp m f := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [_root_.map_add,HahnSeries.coeff_add,Finsupp.add_apply,hf,hg] + | single l a=>exact expandFiber_read_monomial v Ω hΩ k p hp m l a +include hp in +lemma expandFiber_injective : Function.Injective (expandFiber v Ω hΩ k p) := by + intro f g h + apply readFiber_ext v Ω k p hp + intro m + rw [←expandFiber_read v Ω hΩ k p hp f m,←expandFiber_read v Ω hΩ k p hp g m,h] +include hp in +lemma completed_expandFiber_injective : + Function.Injective (PowerSeries.map (expandFiber v Ω hΩ k p)) := by + intro f g h + apply PowerSeries.ext + intro d + apply expandFiber_injective v Ω hΩ k p hp + have H:=congrArg (PowerSeries.coeff d) h + simpa only [PowerSeries.coeff_map] using H +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ κ : M →+ ℤ) +local instance biSupportedRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance biSupportedAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance biSupportedAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def BiSupported (f : PowerSeries (Torus v Ω)) : Prop := + ∀n m,coeff n f m≠0 → 0≤δ m ∧ 0≤κ m ∧ (n:ℤ)=δ m+κ m +lemma BiSupported.zero : BiSupported v Ω δ κ 0 := by intro n m h; simp at h +lemma BiSupported.one : BiSupported v Ω δ κ 1 := by + intro n m hm + have hn : n=0:=by by_contra hn; simp [coeff_one,hn] at hm + subst n + have hm0 : m=0:=by + by_contra hm0 + apply hm + rw [coeff_one,ite_eq_left rfl] + exact Finsupp.single_eq_of_ne hm0 + subst m + simp +lemma BiSupported.add {f g : PowerSeries (Torus v Ω)} (hf : BiSupported v Ω δ κ f) + (hg : BiSupported v Ω δ κ g) : BiSupported v Ω δ κ (f+g) := by + intro n m hm + have H : coeff n f m≠0 ∨ coeff n g m≠0:=by + by_contra hh + push Not at hh + simp [hh.1,hh.2] at hm + exact H.elim (hf n m) (hg n m) +lemma BiSupported.mul {f g : PowerSeries (Torus v Ω)} (hf : BiSupported v Ω δ κ f) + (hg : BiSupported v Ω δ κ g) : BiSupported v Ω δ κ (f*g) := by + intro j r hr + obtain ⟨a,b,m,n,hab,hm,hn,rfl⟩:=series_product_nonzero v Ω f g j r hr + obtain ⟨hdm,hkm,hem⟩:=hf a m hm + obtain ⟨hdn,hkn,hen⟩:=hg b n hn + simp only [map_add] + exact ⟨add_nonneg hdm hdn,add_nonneg hkm hkn,by rw [←hab,Nat.cast_add,hem,hen]; ring⟩ +lemma BiSupported.bi_vanish {f : PowerSeries (Torus v Ω)} (hf : BiSupported v Ω δ κ f) + (d e n : ℕ) (hne : n≠d+e) : coeff e (coeff d (biHomogenize v Ω δ κ (coeff n f)))=0 := by + ext m + rw [biHomogenize_coeff] + split_ifs with hh + · by_contra hz + obtain ⟨hd,hk,he⟩:=hf n m hz + have hD : δ m=(d:ℤ):=by rw [hh.1,Int.toNat_of_nonneg hd] + have hK : κ m=(e:ℤ):=by rw [hh.2,Int.toNat_of_nonneg hk] + apply hne + omega + · rfl +lemma BiSupported.bi_product_vanish {f g : PowerSeries (Torus v Ω)} + (hf : BiSupported v Ω δ κ f) (hg : BiSupported v Ω δ κ g) + (d e a b : ℕ) (ha : d+e + have hu : IsUnit (f (algebraMap (Polynomial K) (RatFunc K) q)):= + (isUnit_iff_ne_zero.mpr (RatFunc.algebraMap_ne_zero hq)).map f + apply hu.mul_right_cancel + rw [←map_mul,div_mul_cancel₀ _ (RatFunc.algebraMap_ne_zero hq),hpoly p,hpoly q, + ←map_mul,div_mul_cancel₀ _ (RatFunc.algebraMap_ne_zero hq)] +def innerHom {A : Type*} [Ring A] (u : Aˣ) : A →+* A where + toFun a:=(↑u:A)*a*(↑(u⁻¹):A) + map_zero':=by simp + map_one':=by simp + map_add' a b:=by simp [mul_add,add_mul] + map_mul' a b:=by simp [mul_assoc] +variable {M : Type*} [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) (p : M) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +def expandScalar : RatFunc K →+* HahnSeries ℤ (Torus v Ω) := + (laurentRayHom v Ω p (hΩ p)).comp expandZero +lemma expandScalar_C (a : K) : + expandScalar v Ω hΩ p (RatFunc.C a)=HahnSeries.single 0 (Torus.monomial v Ω 0 a) := by + simp only [expandScalar,RingHom.comp_apply,expandZero_constant] + change laurentRay v Ω p (HahnSeries.single 0 a)=_ + rw [laurentRay_single,zero_smul] +lemma expandScalar_X : expandScalar v Ω hΩ p RatFunc.X=HahnSeries.single 1 (Torus.X v Ω p) := by + change laurentRay v Ω p (expandZero RatFunc.X)=_ + have H:=expandZero_X_zpow (K:=K) (1:ℤ) + simp only [zpow_one] at H + rw [H,laurentRay_single,one_smul] + rfl +include hΩ in +lemma torus_X_unit (m : M) : Torus.X v Ω m*Torus.X v Ω (-m)=1 := by + rw [Torus.X_mul_X_of_pairing_zero v Ω m (-m) (by simp [hΩ]),add_neg_cancel,Torus.X_zero] +def constUnit (m : M) : (HahnSeries ℤ (Torus v Ω))ˣ where + val:=HahnSeries.single 0 (Torus.X v Ω m) + inv:=HahnSeries.single 0 (Torus.X v Ω (-m)) + val_inv:=by rw [HahnSeries.single_mul_single,zero_add,torus_X_unit v Ω hΩ]; rfl + inv_val:=by + rw [HahnSeries.single_mul_single,zero_add] + have H:=torus_X_unit v Ω hΩ (-m) + simpa using congrArg (HahnSeries.single (0:ℤ)) H +include hΩ in +lemma pairing_swap (a b : M) : Ω a b= -Ω b a := by + have H:=hΩ (a+b) + simp only [map_add,AddMonoidHom.add_apply,hΩ] at H + omega +lemma constUnit_conj_C (m : M) (a : K) : + innerHom (constUnit v Ω hΩ m) (expandScalar v Ω hΩ p (RatFunc.C a))= + expandScalar v Ω hΩ p (RatFunc.C a) := by + rw [expandScalar_C] + dsimp only [innerHom, constUnit, RingHom.coe_mk, MonoidHom.coe_mk, OneHom.coe_mk, Units.val_mk, Units.inv_mk] + rw [HahnSeries.single_mul_single,HahnSeries.single_mul_single] + simp [Torus.X,Torus.monomial_mul_monomial,hΩ] +lemma constUnit_conj_X (m : M) : + innerHom (constUnit v Ω hΩ m) (expandScalar v Ω hΩ p RatFunc.X)= + expandScalar v Ω hΩ p (RatFunc.C (↑(v^(-2*Ω p m)):K)*RatFunc.X) := by + rw [map_mul,expandScalar_C,expandScalar_X] + dsimp only [innerHom, constUnit, RingHom.coe_mk, MonoidHom.coe_mk, OneHom.coe_mk, Units.val_mk, Units.inv_mk] + simp only [HahnSeries.single_mul_single,zero_add,add_zero,Torus.X,Torus.monomial_mul_monomial, + map_add,AddMonoidHom.add_apply,map_neg,hΩ,map_zero,AddMonoidHom.zero_apply, + zpow_zero,Units.val_one,mul_one,one_mul,zero_add] + have he : m+p+-m=p:=by abel + rw [he,←Units.val_mul,←zpow_add,pairing_swap Ω hΩ m p] + congr 3 + ring_nf +lemma scalar_commutation (m : M) (a : RatFunc K) : + HahnSeries.single 0 (Torus.X v Ω m)*expandScalar v Ω hΩ p a= + expandScalar v Ω hΩ p (scale (v^(-2*Ω p m)) a)*HahnSeries.single 0 (Torus.X v Ω m) := by + have HE : (innerHom (constUnit v Ω hΩ m)).comp (expandScalar v Ω hΩ p)= + (expandScalar v Ω hΩ p).comp (scale (v^(-2*Ω p m))) := by + apply ratFunc_hom_ext_ring + have HP : ((innerHom (constUnit v Ω hΩ m)).comp (expandScalar v Ω hΩ p)).comp + (algebraMap (Polynomial K) (RatFunc K))= + ((expandScalar v Ω hΩ p).comp (scale (v^(-2*Ω p m)))).comp + (algebraMap (Polynomial K) (RatFunc K)) := by + apply Polynomial.ringHom_ext + · intro a + change innerHom _ (expandScalar v Ω hΩ p (RatFunc.C a))= + expandScalar v Ω hΩ p (scale _ (RatFunc.C a)) + rw [scale_constant,constUnit_conj_C] + · change innerHom _ (expandScalar v Ω hΩ p RatFunc.X)= + expandScalar v Ω hΩ p (scale _ RatFunc.X) + rw [scale_X,constUnit_conj_X] + exact fun q=>congrArg (fun f : Polynomial K →+* HahnSeries ℤ (Torus v Ω)=>f q) HP + have H:=congrArg (fun f : RatFunc K →+* HahnSeries ℤ (Torus v Ω)=>f a) HE + change ↑(constUnit v Ω hΩ m)*expandScalar v Ω hΩ p a*↑((constUnit v Ω hΩ m)⁻¹)= + expandScalar v Ω hΩ p (scale _ a) at H + have HH:=congrArg (fun x : HahnSeries ℤ (Torus v Ω)=>x*(↑(constUnit v Ω hΩ m):HahnSeries ℤ (Torus v Ω))) H + have hu : (↑((constUnit v Ω hΩ m)⁻¹):HahnSeries ℤ (Torus v Ω))*↑(constUnit v Ω hΩ m)=1 := (constUnit v Ω hΩ m).inv_val + rw [mul_assoc, mul_assoc, hu, mul_one] at HH + exact HH +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +def expandFiberTerm (l : k.ker) : RatFunc K →+ HahnSeries ℤ (Torus v Ω) where + toFun a:=expandScalar v Ω hΩ p a*HahnSeries.single 0 (Torus.X v Ω l) + map_zero':=by simp + map_add' a b:=by simp [add_mul] +def expandFiberAdd : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω) →+ + HahnSeries ℤ (Torus v Ω) := Finsupp.liftAddHom (expandFiberTerm v Ω hΩ k p) +lemma expandFiberAdd_monomial (l : k.ker) (a : RatFunc K) : + expandFiberAdd v Ω hΩ k p (FiberTorus.monomial v _ _ l a)= + expandScalar v Ω hΩ p a*HahnSeries.single 0 (Torus.X v Ω l) := + Finsupp.liftAddHom_apply_single _ _ _ +lemma const_torus_product (m n : M) : + HahnSeries.single (0:ℤ) (Torus.X v Ω m)*HahnSeries.single 0 (Torus.X v Ω n)= + expandScalar v Ω hΩ p (RatFunc.C (↑(v^(Ω m n)):K))* + HahnSeries.single 0 (Torus.X v Ω (m+n)) := by + rw [expandScalar_C] + simp [HahnSeries.single_mul_single,Torus.X,Torus.monomial_mul_monomial] +lemma expandFiberAdd_monomial_mul (l j : k.ker) (a b : RatFunc K) : + expandFiberAdd v Ω hΩ k p (FiberTorus.monomial v _ _ l a*FiberTorus.monomial v _ _ j b)= + expandFiberAdd v Ω hΩ k p (FiberTorus.monomial v _ _ l a)* + expandFiberAdd v Ω hΩ k p (FiberTorus.monomial v _ _ j b) := by + rw [FiberTorus.monomial_mul,expandFiberAdd_monomial,expandFiberAdd_monomial,expandFiberAdd_monomial] + simp only [_root_.map_mul,FiberTorus.twist] + change (expandScalar v Ω hΩ p a*expandScalar v Ω hΩ p (scale (v^(-2*Ω p l)) b)* + expandScalar v Ω hΩ p (RatFunc.C (↑(v^(Ω l j)):K)))* + HahnSeries.single 0 (Torus.X v Ω ((l:M)+(j:M)))=_ + simp only [mul_assoc] + rw [←const_torus_product] + rw [←mul_assoc (expandScalar v Ω hΩ p (scale _ b)),←scalar_commutation] + simp only [mul_assoc] + +lemma expandFiberAdd_mul (f g : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) : + expandFiberAdd v Ω hΩ k p (f*g)=expandFiberAdd v Ω hΩ k p f*expandFiberAdd v Ω hΩ k p g := by + classical + induction f using Finsupp.induction_linear with + | zero=>simp + | add f f' hf hf'=>simp only [_root_.add_mul,map_add,hf,hf'] + | single l a=> + induction g using Finsupp.induction_linear with + | zero=>simp + | add g g' hg hg'=>simp only [_root_.mul_add,map_add,hg,hg'] + | single j b=>exact expandFiberAdd_monomial_mul v Ω hΩ k p l j a b +lemma expandFiberAdd_one : expandFiberAdd v Ω hΩ k p 1=1 := by + change expandFiberAdd v Ω hΩ k p (FiberTorus.monomial v _ _ 0 1)=_ + rw [expandFiberAdd_monomial,map_one,one_mul] + rfl +def expandFiber : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω) →+* + HahnSeries ℤ (Torus v Ω) where + __:=expandFiberAdd v Ω hΩ k p + map_one':=expandFiberAdd_one v Ω hΩ k p + map_mul':=expandFiberAdd_mul v Ω hΩ k p +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalPolynomialDivisibility.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalPolynomialDivisibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..b91416dcea1469ee7f774084a17d25a9bdda66c8 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalPolynomialDivisibility.lean @@ -0,0 +1,140 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.SymbolCoordinates +open MvPolynomial +variable {σ A : Type*} [CommRing A] [Algebra ℚ A] + +noncomputable def coefficientMap (l : A →ₗ[ℚ] ℚ) : + MvPolynomial σ A →ₗ[ℚ] MvPolynomial σ ℚ := + (AddMonoidAlgebra.coeffLinearEquiv ℚ).symm.toLinearMap.comp + ((Finsupp.mapRange.linearMap l).comp (AddMonoidAlgebra.coeffLinearEquiv ℚ).toLinearMap) + +@[simp] lemma coeff_coefficientMap (l : A →ₗ[ℚ] ℚ) (f : MvPolynomial σ A) (m : σ →₀ ℕ) : + (coefficientMap l f).coeff m=l (f.coeff m) := rfl + +lemma coefficientMap_scalar_mul (l : A →ₗ[ℚ] ℚ) (p : MvPolynomial σ ℚ) (f : MvPolynomial σ A) : + coefficientMap l (MvPolynomial.map (algebraMap ℚ A) p * f) = p * coefficientMap l f := by + classical + ext m + simp only [coeff_coefficientMap,coeff_mul,coeff_map,map_sum] + apply Finset.sum_congr rfl + intro x hx + simpa [Algebra.smul_def,smul_eq_mul] using + l.map_smul (p.coeff x.1) (f.coeff x.2) + +variable {ι : Type*} (b : Module.Basis ι ℚ A) + +noncomputable def coordinate (i : ι) : MvPolynomial σ A →ₗ[ℚ] MvPolynomial σ ℚ := + coefficientMap ((Finsupp.lapply i).comp b.repr.toLinearMap) + +@[simp] lemma coeff_coordinate (i : ι) (f : MvPolynomial σ A) (m : σ →₀ ℕ) : + (coordinate b i f).coeff m=b.repr (f.coeff m) i := rfl + +lemma coordinate_scalar_mul (i : ι) (p : MvPolynomial σ ℚ) (f : MvPolynomial σ A) : + coordinate b i (MvPolynomial.map (algebraMap ℚ A) p * f) = p * coordinate b i f := + coefficientMap_scalar_mul _ _ _ + +lemma coordinates_detect (f : MvPolynomial σ A) (h : ∀ i,coordinate b i f=0) : f=0 := by + ext m + apply b.repr.injective + ext i + have hh:=congrArg (fun polynomial : MvPolynomial σ ℚ => polynomial.coeff m) (h i) + simpa using hh + +noncomputable def coordinateSupport (f : MvPolynomial σ A) : Finset ι := by + classical + exact f.support.biUnion (fun m=>(b.repr (f.coeff m)).support) + +lemma coordinate_support_subset (f : MvPolynomial σ A) (m : σ →₀ ℕ) : + (b.repr (f.coeff m)).support ⊆ coordinateSupport b f := by + classical + intro i hi + by_cases hm : m∈f.support + · exact Finset.mem_biUnion.mpr ⟨m,hm,hi⟩ + · have hzero:=notMem_support_iff.mp hm + simp [hzero] at hi + +lemma reconstruct (f : MvPolynomial σ A) : + (∑ i ∈ coordinateSupport b f,C (b i)*MvPolynomial.map (algebraMap ℚ A) (coordinate b i f))=f := by + classical + ext m + simp only [coeff_sum,coeff_C_mul,coeff_map,coeff_coordinate] + calc + (∑ i ∈ coordinateSupport b f,b i * algebraMap ℚ A (b.repr (f.coeff m) i)) = + ∑ i ∈ (b.repr (f.coeff m)).support,b.repr (f.coeff m) i • b i := by + simp only [Algebra.smul_def,mul_comm] + exact (Finset.sum_subset (coordinate_support_subset b f m) (by + intro i hi hni + simp [Finsupp.notMem_support_iff.mp hni])).symm + _ = f.coeff m := b.linearCombination_repr _ + +theorem scalar_mul_eq_zero_iff (p : MvPolynomial σ ℚ) (hp : p≠0) (f : MvPolynomial σ A) : + MvPolynomial.map (algebraMap ℚ A) p * f=0 ↔ f=0 := by + constructor + · intro hf + apply coordinates_detect (Module.Free.chooseBasis ℚ A) + intro i + have h:=congrArg (coordinate (Module.Free.chooseBasis ℚ A) i) hf + rw [coordinate_scalar_mul,map_zero] at h + exact (mul_eq_zero.mp h).resolve_left hp + · rintro rfl + exact mul_zero _ + +theorem scalar_dvd_iff (p : MvPolynomial σ ℚ) (f : MvPolynomial σ A) : + MvPolynomial.map (algebraMap ℚ A) p ∣ f ↔ ∀ i,p ∣ coordinate b i f := by + classical + constructor + · rintro ⟨g,rfl⟩ i + rw [coordinate_scalar_mul] + exact dvd_mul_right p _ + · intro h + choose g hg using h + refine ⟨∑ i ∈ coordinateSupport b f,C (b i)*MvPolynomial.map (algebraMap ℚ A) (g i),?_⟩ + calc + f = ∑ i ∈ coordinateSupport b f,C (b i)*MvPolynomial.map (algebraMap ℚ A) (coordinate b i f) := + (reconstruct b f).symm + _ = _ := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro i hi + rw [hg i,map_mul] + ring + +end ElementaryPositivity.SymbolCoordinates + +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial ElementaryPositivity.SymbolCoordinates +variable {A σ : Type*} [CommRing A] [Algebra ℚ A] + +theorem product_dvd_of_scalar_factors {κ : Type*} (s : Finset κ) + (p : κ → MvPolynomial σ ℚ) (q : MvPolynomial σ A) + (hrel : (s : Set κ).Pairwise (fun i j => IsRelPrime (p i) (p j))) + (h : ∀ i∈s, map (algebraMap ℚ A) (p i) ∣ q) : + map (algebraMap ℚ A) (∏ i∈s,p i) ∣ q := by + let b := Module.Free.chooseBasis ℚ A + apply (scalar_dvd_iff b _ q).mpr + intro k + apply Finset.prod_dvd_of_isRelPrime hrel + intro i hi + exact (scalar_dvd_iff b (p i) q).mp (h i hi) k + +theorem scalar_mul_eq_zero (p : MvPolynomial σ ℚ) (hp : p≠0) + (q : MvPolynomial σ A) (h : map (algebraMap ℚ A) p*q=0) : q=0 := + (scalar_mul_eq_zero_iff p hp q).mp h + +theorem scalar_mul_injective (p : MvPolynomial σ ℚ) (hp : p≠0) : + Function.Injective (fun q : MvPolynomial σ A=>map (algebraMap ℚ A) p*q) := by + intro q r h + dsimp only at h + apply sub_eq_zero.mp + apply scalar_mul_eq_zero p hp + rw [mul_sub,h,sub_self] + +end ElementaryPositivity.CenterCalculus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalPureCoefficients.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalPureCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..49f38807cdaeea4bdfeccee02a6087044e1f1a22 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalPureCoefficients.lean @@ -0,0 +1,141 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalTorusFaithful +import OAI.Combinatorics.Chromatic.GradedAlgebra.RationalCenteredAction +import OAI.Combinatorics.Chromatic.Walls.CenteredUnitRatio + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus WallUnits PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) +def centeredRatio (t : ℤ) : PowerSeries K := + rescale (↑(v^(-t)):K) + (rescale (↑(v^(2*t)):K) (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K))* + (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K))⁻¹) +lemma centeredRatio_eq (t : ℤ) : centeredRatio v t= + rescale (↑(v^t):K) (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K)* + (shiftedElementary v t)⁻¹) := by + have hc := shiftedElementary_constant v t + unfold shiftedElementary at hc + unfold centeredRatio shiftedElementary + rw [map_mul,map_mul,rescale_inv_of_const_one _ _ (constant_elementary _ _), + rescale_inv_of_const_one _ _ hc,rescale_rescale,rescale_rescale] + congr 1 + · rw [←Units.val_mul,←zpow_add] + congr 2 + ring_nf + · rw [←Units.val_mul,←zpow_add] + congr 3 + ring_nf +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +include hΩ in +lemma read_pure_monomial_shift + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) (m : M) (j : ℕ) : + readFiber v Ω k p hp (m+j • p) + (pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.X v Ω m)))=coeff j (centeredRatio v (Ω p m)) := by + rw [Torus.X,embed_monomial,pureAction_monomial,map_one,one_mul, + complement_pairing Ω hΩ k p hp m] + change (expandZero ((Finsupp.single (off k p hp m) + (centeredScalar v (k m) (Ω p m)*(pureRatio v (Ω p m):RatFunc K))) + (off k p hp (m+j • p)))).coeff (k (m+j • p))* + (↑(v^(k (m+j • p)*complementAlpha k p Ω (off k p hp (m+j • p)))):K)=_ + simp only [map_add,map_nsmul,off_p,smul_zero,add_zero,hp,nsmul_eq_mul,mul_one, + Finsupp.single_eq_same,complement_pairing Ω hΩ k p hp m] + rw [map_mul,show expandZero (centeredScalar v (k m) (Ω p m))= + HahnSeries.single (k m) (↑(v^(-k m*Ω p m)):K) by + simpa using expand_centeredScalar v (k m) (Ω p m) (1:K), + expandedPure_ratio v hq] + rw [add_comm (k m),HahnSeries.coeff_single_mul_add,HahnSeries.ofPowerSeries_apply_coeff, + centeredRatio_eq,coeff_rescale] + rw [mul_assoc, mul_comm (coeff j _),←mul_assoc,←Units.val_mul,←zpow_add] + rw [show -k m*Ω p m+((j:ℤ)+k m)*Ω p m=(Ω p m)*(j:ℤ) by ring, + zpow_mul,zpow_natCast,Units.val_pow_eq_pow_val] +include hΩ in +lemma old_pure_coeff (m : M) (j : ℕ) : + coeff j ((rayUnit v Ω p (hΩ p) (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K)) + (constant_elementary _ _)).val*PowerSeries.C (Torus.X v Ω m)* + (rayUnit v Ω p (hΩ p) (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K)) + (constant_elementary _ _)).inv)= + Torus.monomial v Ω (m+j • p) (coeff j (centeredRatio v (Ω p m))) := by + rw [ray_adjoint v Ω hΩ,ray_twisted_coefficient v Ω hΩ] + rfl +include hΩ in +lemma rational_pure_old_coefficient + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) (m : M) (j : ℕ) : + readFiber v Ω k p hp (m+j • p) + (pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.X v Ω m)))= + (coeff j ((rayUnit v Ω p (hΩ p) (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K)) + (constant_elementary _ _)).val*PowerSeries.C (Torus.X v Ω m)* + (rayUnit v Ω p (hΩ p) (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K)) + (constant_elementary _ _)).inv)) (m+j • p) := by + rw [read_pure_monomial_shift v Ω hΩ k p hp hq,old_pure_coeff v Ω hΩ] + exact (Finsupp.single_eq_same).symm +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +lemma mul_X_coeff (f : Torus v Ω) (r m : M) : + (f*Torus.X v Ω m) (r+m)=f r*(↑(v^(Ω r m)):K) := by + classical + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [add_mul,Finsupp.add_apply,hf,hg] + | single t a=> + change (Torus.monomial v Ω t a*Torus.monomial v Ω m 1) (r+m)=_ + rw [Torus.monomial_mul_monomial] + by_cases ht : t=r + · subst t; simp [Torus.monomial] + · simp [Torus.monomial,Ne.symm ht] + +lemma X_mul_coeff (f : Torus v Ω) (r m : M) : + (Torus.X v Ω m*f) (r+m)=f r*(↑(v^(Ω m r)):K) := by + classical + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simpa only [mul_add,Finsupp.add_apply,hf,hg] using (_root_.add_mul (f r) (g r) _).symm + | single t a=> + change (Torus.monomial v Ω m 1*Torus.monomial v Ω t a) (r+m)=_ + rw [Torus.monomial_mul_monomial] + by_cases ht : t=r + · subst t; simp [Torus.monomial,add_comm] + · have hmt : m+t≠r+m:=by intro hh; apply ht; simpa only [add_comm m t,add_right_cancel_iff] using hh + simp [Torus.monomial,Ne.symm ht,Ne.symm hmt] + +include v Ω in +lemma central_support_zero + (hv : Function.Injective (fun z : ℤ=>(↑(v^z):K))) + (hΩ : ∀m,Ω m m=0) (hnd : ∀r≠0,∃m,Ω r m≠0) + (f : Torus v Ω) (hf : ∀m,f*Torus.X v Ω m=Torus.X v Ω m*f) : + ∀r≠0,f r=0 := by + intro r hr + obtain ⟨m,hm⟩:=hnd r hr + have H:=congrArg (fun t : Torus v Ω=>t (r+m)) (hf m) + rw [mul_X_coeff,X_mul_coeff] at H + by_contra hf + have he : Ω r m=Ω m r:=hv (mul_left_cancel₀ hf H) + have hs:=alternating_skew Ω hΩ r m + omega +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalRegrade.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalRegrade.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9afdc7611b62226e812a1be200001e6d71e91be --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalRegrade.lean @@ -0,0 +1,66 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalTorusFaithful +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegradeFaithful + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +variable (δ : M →+ ℤ) (B : ℕ) +def rationalRegrade (f : PowerSeries (Torus v Ω)) : + PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) := + PowerSeries.map (embed v Ω hΩ k p hp) (regrade v Ω δ B f) +def rationalRegradeHom : boundedRegradeSubring v Ω δ B →+* + PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) := + (PowerSeries.map (embed v Ω hΩ k p hp)).comp (regradeHom v Ω δ B) +lemma rationalRegrade_mul {f g : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hg : RegradeBound v Ω δ B g) : + rationalRegrade v Ω hΩ k p hp δ B (f*g)= + rationalRegrade v Ω hΩ k p hp δ B f*rationalRegrade v Ω hΩ k p hp δ B g := by + unfold rationalRegrade + rw [regrade_mul v Ω δ B hf hg,_root_.map_mul] +lemma rationalRegrade_one : rationalRegrade v Ω hΩ k p hp δ B 1=1 := by + unfold rationalRegrade + rw [regrade_one,_root_.map_one] +lemma rationalRegrade_inverse_mul {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hc : constantCoeff f=1) : + rationalRegrade v Ω hΩ k p hp δ B (PowerSeries.invOfUnit f 1)* + rationalRegrade v Ω hΩ k p hp δ B f=1 := by + unfold rationalRegrade + rw [←_root_.map_mul,regrade_inverse_mul v Ω δ B hf hc,_root_.map_one] +lemma rationalRegrade_mul_inverse {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hc : constantCoeff f=1) : + rationalRegrade v Ω hΩ k p hp δ B f* + rationalRegrade v Ω hΩ k p hp δ B (PowerSeries.invOfUnit f 1)=1 := by + unfold rationalRegrade + rw [←_root_.map_mul,regrade_mul_inverse v Ω δ B hf hc,_root_.map_one] +lemma rationalRegrade_read (τ : M →+ ℤ) {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hτ : FullHomogeneous v Ω τ f) + (n : ℕ) (m : M) (hm : τ m=(n:ℤ)) : + readFiber v Ω k p hp m (coeff (δ m).toNat + (rationalRegrade v Ω hΩ k p hp δ B f))=coeff n f m := by + rw [rationalRegrade,coeff_map] + change readFiber v Ω k p hp m (embedAdd v Ω k p hp _)=_ + rw [readFiber_embedAdd,regrade_read v Ω δ B τ hf hτ n m hm] +lemma rationalRegrade_injective (τ : M →+ ℤ) {f g : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω δ B f) (hg : RegradeBound v Ω δ B g) + (hτf : FullHomogeneous v Ω τ f) (hτg : FullHomogeneous v Ω τ g) + (he : rationalRegrade v Ω hΩ k p hp δ B f= + rationalRegrade v Ω hΩ k p hp δ B g) : f=g := by + apply regrade_injective_homogeneous v Ω δ B τ hf hg hτf hτg + apply PowerSeries.ext + intro d + apply embed_injective v Ω hΩ k p hp + have H:=congrArg (coeff d) he + simpa only [rationalRegrade,coeff_map] using H +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalShearCocycle.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalShearCocycle.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf5eb37eefc7ccb5cd0560274207eaab7ed0722a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalShearCocycle.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RationalPureCocycle + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +variable {K : Type*} [Field K] +def coefficientUnit (v : Kˣ) : (RatFunc K)ˣ := Units.map RatFunc.C.toMonoidHom v +def variableUnit : (RatFunc K)ˣ := Units.mk0 RatFunc.X RatFunc.X_ne_zero +@[simp] lemma coefficientUnit_val (v : Kˣ) : (coefficientUnit v:RatFunc K)=RatFunc.C (v:K) := rfl +@[simp] lemma variableUnit_val : (variableUnit (K:=K):RatFunc K)=RatFunc.X := rfl +@[simp] lemma scaleAction_coefficientUnit (v w : Kˣ) (t : ℤ) : + scaleAction v (Multiplicative.ofAdd t) (coefficientUnit w)=coefficientUnit w := by + apply Units.ext + simp +@[simp] lemma scaleAction_variableUnit (v : Kˣ) (t : ℤ) : + scaleAction v (Multiplicative.ofAdd t) variableUnit=coefficientUnit v^(-2*t)*variableUnit := by + apply Units.ext + simp [scale_X,Units.val_zpow_eq_zpow_val,map_zpow₀] + +def shearRatio (v : Kˣ) (t : ℤ) : (RatFunc K)ˣ := + coefficientUnit v^(t*t)*variableUnit^(-t) +@[simp] lemma shearRatio_zero (v : Kˣ) : shearRatio v 0=1 := by simp [shearRatio] +lemma shearRatio_add (v : Kˣ) (t u : ℤ) : + shearRatio v (t+u)=shearRatio v t*scaleAction v (Multiplicative.ofAdd t) (shearRatio v u) := by + simp only [shearRatio,map_mul,map_zpow,scaleAction_coefficientUnit,scaleAction_variableUnit,mul_zpow] + rw [←zpow_mul,show (t+u)*(t+u)=t*t+u*u+(-2*t)*(-u) by ring, + show -(t+u)= -t+ -u by ring,zpow_add,zpow_add,zpow_add] + simp only [mul_assoc, mul_left_comm, mul_comm] +@[simp] lemma shearRatio_val (v : Kˣ) (t : ℤ) : + (shearRatio v t:RatFunc K)=RatFunc.C (↑(v^(t*t)):K)*RatFunc.X^(-t) := by + simp [shearRatio,Units.val_zpow_eq_zpow_val,map_zpow₀] + +def reciprocalUnit : (RatFunc K)ˣ ≃* (RatFunc K)ˣ := Units.mapEquiv reciprocalEquiv.toMulEquiv +@[simp] lemma reciprocalUnit_val (a : (RatFunc K)ˣ) : + (reciprocalUnit a:RatFunc K)=reciprocal (a:RatFunc K) := rfl +lemma reciprocalUnit_scaleAction (v : Kˣ) (t : ℤ) (a : (RatFunc K)ˣ) : + reciprocalUnit (scaleAction v (Multiplicative.ofAdd (-t)) a)= + scaleAction v (Multiplicative.ofAdd t) (reciprocalUnit a) := by + apply Units.ext + simp only [reciprocalUnit_val,scaleAction_val] + have H:=congrArg (fun f : RatFunc K →+* RatFunc K=>f (a:RatFunc K)) (reciprocal_scale (v^(-2*(-t)))) + dsimp only [RingHom.comp_apply] at H + rw [←zpow_neg,show -(-2*(-t))= -2*t by ring] at H + exact H + +def oppositeInverseRatio (v : Kˣ) (t : ℤ) : (RatFunc K)ˣ := reciprocalUnit (pureRatio v (-t))⁻¹ +@[simp] lemma oppositeInverseRatio_zero (v : Kˣ) : oppositeInverseRatio v 0=1 := by simp [oppositeInverseRatio] +lemma oppositeInverseRatio_add (v : Kˣ) (t u : ℤ) : + oppositeInverseRatio v (t+u)= + oppositeInverseRatio v t*scaleAction v (Multiplicative.ofAdd t) (oppositeInverseRatio v u) := by + simp only [oppositeInverseRatio,neg_add,pureRatio_add,map_mul,reciprocalUnit_scaleAction, + mul_inv_rev,map_inv] + exact mul_comm _ _ +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalShearEmbedding.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalShearEmbedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..d47cc4a05de90e12490134e7555f44f37ff69776 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RationalShearEmbedding.lean @@ -0,0 +1,53 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RationalCenteredAction + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +lemma centeredScalar_shear (n t : ℤ) : + centeredScalar v (n-t) t=centeredScalar v n t*(shearRatio v t:RatFunc K) := by + rw [shearRatio_val,centeredScalar,centeredScalar] + rw [show -(n-t)*t= -n*t+t*t by ring,zpow_add,Units.val_mul,map_mul, + sub_eq_add_neg,zpow_add₀ RatFunc.X_ne_zero] + ring +include hΩ in +lemma shearAction_embed_monomial (m : M) (a : K) : + shearActionHom v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.monomial v Ω m a))= + embed v Ω hΩ k p hp (Torus.monomial v Ω (mutationShear Ω p m) a) := by + rw [embed_monomial,embed_monomial] + change FiberTorus.gauge v _ _ _ _ _ (FiberTorus.monomial v _ _ _ _)=_ + rw [FiberTorus.gauge_monomial] + have Hoff : off k p hp (mutationShear Ω p m)=off k p hp m := by + change off k p hp (m-Ω p m • p)=_ + rw [map_sub,map_zsmul,off_p,smul_zero,sub_zero] + have Hk : k (mutationShear Ω p m)=k m-Ω p m := by + change k (m-Ω p m • p)=_ + rw [map_sub,map_zsmul,hp,smul_eq_mul,mul_one] + rw [Hoff,Hk,complement_pairing Ω hΩ k p hp m,centeredScalar_shear] + rw [mul_assoc] +include hΩ in +lemma shearAction_embed (f : Torus v Ω) : + shearActionHom v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp f)= + embed v Ω hΩ k p hp + (Torus.push v Ω Ω (mutationShear Ω p) (mutationShear_pairing Ω hΩ p) f) := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [map_add,hf,hg] + | single m a=> + change _=embed v Ω hΩ k p hp (Torus.push v Ω Ω _ _ (Torus.monomial v Ω m a)) + rw [Torus.push_monomial] + exact shearAction_embed_monomial v Ω hΩ k p hp m a +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RealRootCoordinates.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RealRootCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..bca413e3517f0996952cabbd664bd569152eac5f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RealRootCoordinates.lean @@ -0,0 +1,64 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationCoordinates + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) + +lemma coefficient_simple_expansion (a:I → ℤ) : C a=∑i,a i • simpleRoot C i := by + have ha : a=∑i,a i • (Pi.single i 1:I → ℤ):=by + ext j + simp only [Finset.sum_apply,Pi.smul_apply,smul_eq_mul] + rw [Finset.sum_eq_single j] + · simp + · intro i hi hij; simp [Ne.symm hij] + · simp + conv_lhs=>rw [ha,map_sum] + simp only [map_zsmul,simpleRoot] + +lemma realRootCoordinates_exists (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) : + ∃D:E →ₗ[ℝ] (I → ℝ),∀a,D (e (C a))=fun i=>(a i:ℝ) := by + let f:=Finsupp.linearCombination ℝ (fun i=>e (simpleRoot C i)) + obtain ⟨g,hg⟩:=f.exists_leftInverse_of_injective (LinearMap.ker_eq_bot.mpr hC) + let D:E →ₗ[ℝ] (I → ℝ):=LinearMap.pi (fun i=>(Finsupp.lapply i).comp g) + have hd (i:I) : D (e (simpleRoot C i))=Pi.single i 1:=by + have H:=LinearMap.congr_fun hg (Finsupp.single i 1) + simp only [LinearMap.comp_apply,LinearMap.id_apply,f,Finsupp.linearCombination_single,one_smul] at H + funext j + change g (e (simpleRoot C i)) j=(Pi.single i 1:I → ℝ) j + rw [H] + simp [Finsupp.single_apply,Pi.single_apply,eq_comm] + refine ⟨D,fun a=>?_⟩ + rw [coefficient_simple_expansion C,map_sum,map_sum] + simp only [map_zsmul,hd] + ext j + simp only [Finset.sum_apply,zsmul_eq_mul] + rw [Finset.sum_eq_single j] + · simp + · intro i hi hij; simp [Ne.symm hij] + · simp + +lemma covector_root_eval (h:Module.Dual ℝ E) (hh:∀i,h (e (simpleRoot C i))=1) + {n:ℕ} {m:M} (hm:HasRootDegree C n m) : h (e m)=(n:ℝ) := by + obtain ⟨a,ha,rfl⟩:=hm + rw [coefficient_simple_expansion C,map_sum,map_sum] + simp only [map_zsmul,hh,zsmul_eq_mul,mul_one] + exact_mod_cast ha + +omit [Fintype I] in +lemma real_coordinate_simple (D:E →ₗ[ℝ] (I → ℝ)) + (hD:∀a,D (e (C a))=fun i=>(a i:ℝ)) (i:I) : D (e (simpleRoot C i))=Pi.single i 1 := by + rw [simpleRoot,hD] + ext j + simp [Pi.single_apply] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RegradeLog.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RegradeLog.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fb0a3988ee3db1a5e15e1ddb55fcead7fa2cd8b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RegradeLog.lean @@ -0,0 +1,133 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplitLeading +import OAI.Combinatorics.Chromatic.GradedAlgebra.NoncommSeriesCalculus +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegradeFaithful +import OAI.Combinatorics.Chromatic.GradedAlgebra.QuantumTorusAlgebra + +namespace OAI + +section +namespace ElementaryPositivity.FormalLog +open PowerSeries +noncomputable section +variable {A : Type*} [Ring A] [Algebra ℚ A] +def logPolynomial (F : PowerSeries A) (N : ℕ) : PowerSeries A := + ∑k∈Finset.range N,((-1:ℚ)^k/(k+1:ℕ)) • (F-1)^(k+1) +lemma logPolynomial_coeff (F : PowerSeries A) (hf : constantCoeff F=1) (N n : ℕ) (hn : n≤N) : + coeff n (logPolynomial F N)=coeff n (FormalLog.log F) := by + simp only [logPolynomial,FormalLog.log,coeff_mk,map_sum,coeff_smul] + symm + apply Finset.sum_subset (Finset.range_mono hn) + intro k hk hkn + rw [coeff_power_vanish (F-1) (by simp [hf]) (k+1) n (by + simp only [Finset.mem_range,not_lt] at hkn; omega),smul_zero] +end +end ElementaryPositivity.FormalLog +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ : M →+ ℤ) (B : ℕ) +local instance regradeLogRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance regradeLogNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance regradeLogNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +local instance regradeLogAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance regradeLogAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance regradeLogAddCommGroup : AddCommGroup (Torus v Ω) := (Torus.instRing v Ω).toAddCommGroup +local instance regradeLogSub : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub +lemma homogenize_smul (q : ℚ) (f : Torus v Ω) : + homogenize v Ω δ (q • f)=q • homogenize v Ω δ f := by + ext n m + simp only [homogenize_coeff,coeff_smul,Finsupp.smul_apply] + split_ifs <;> simp + +def regradeLinear : PowerSeries (Torus v Ω) →ₗ[ℚ] PowerSeries (Torus v Ω) where + toFun:=regrade v Ω δ B + map_add' f g:=by + apply PowerSeries.ext + intro n + ext m + simp only [regrade_coeff,nonp_torus_eval_sum,homogenize_coeff,_root_.map_add,Finsupp.add_apply] + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro j hj + split_ifs <;> simp + map_smul' q f:=by + apply PowerSeries.ext + intro n + simp only [regrade_coeff,coeff_smul,homogenize_smul,Finset.smul_sum,RingHom.id_apply] + +omit [Algebra ℚ R] in +lemma RegradeBound.pow {f : PowerSeries (Torus v Ω)} (hf : RegradeBound v Ω δ B f) (k : ℕ) : + RegradeBound v Ω δ B (f^k) := by + induction k with + | zero=>simpa using RegradeBound.one v Ω δ B + | succ k ih=>exact ih.mul v Ω δ B hf + +omit [Algebra ℚ R] in +lemma regrade_pow {F : PowerSeries (Torus v Ω)} (hf : RegradeBound v Ω δ B F) (k : ℕ) : + regrade v Ω δ B (F^k)=(regrade v Ω δ B F)^k := by + induction k with + | zero=>simpa using regrade_one v Ω δ B + | succ k ih=>rw [pow_succ,regrade_mul v Ω δ B (hf.pow v Ω δ B k) hf,ih,pow_succ] +lemma regrade_logPolynomial (F : PowerSeries (Torus v Ω)) (hf : RegradeBound v Ω δ B F) (N : ℕ) : + regrade v Ω δ B (FormalLog.logPolynomial F N)= + FormalLog.logPolynomial (regrade v Ω δ B F) N := by + change regradeLinear v Ω δ B (FormalLog.logPolynomial F N)=_ + rw [FormalLog.logPolynomial,map_sum] + apply Finset.sum_congr rfl + intro k hk + rw [map_smul] + congr 1 + change regrade v Ω δ B ((F-1)^(k+1))=_ + rw [regrade_pow v Ω δ B (by + intro j m hm + by_cases hF : coeff j F m=0 + · apply RegradeBound.one v Ω δ B j m + intro h1 + apply hm + rw [map_sub,sub_eq_add_neg] + change coeff j F m+ -(coeff j (1 : PowerSeries (Torus v Ω)) m)=0 + rw [hF,h1,neg_zero,add_zero] + · exact hf j m hF)] + congr 1 + change regradeLinear v Ω δ B (F-1)=_ + rw [map_sub] + change regrade v Ω δ B F-regrade v Ω δ B 1=_ + rw [regrade_one] +omit [Algebra ℚ R] in +lemma regrade_constant (F : PowerSeries (Torus v Ω)) (hf : constantCoeff F=1) : + constantCoeff (regrade v Ω δ B F)=1 := by + rw [←coeff_zero_eq_constantCoeff_apply,regrade_coeff] + simp only [mul_zero,zero_add,Finset.sum_range_one,coeff_zero_eq_constantCoeff,hf, + homogenize_one,constantCoeff_one] +omit [Algebra ℚ R] in +lemma regrade_coeff_congr (F G : PowerSeries (Torus v Ω)) (d : ℕ) + (H : ∀n≤B*d,coeff n F=coeff n G) : + coeff d (regrade v Ω δ B F)=coeff d (regrade v Ω δ B G) := by + rw [regrade_coeff,regrade_coeff] + apply Finset.sum_congr rfl + intro n hn + rw [H n (by simpa only [Finset.mem_range,Nat.lt_succ_iff] using hn)] +lemma regrade_log (F : PowerSeries (Torus v Ω)) + (hf : RegradeBound v Ω δ B F) (hc : constantCoeff F=1) : + regrade v Ω δ B (FormalLog.log F)=FormalLog.log (regrade v Ω δ B F) := by + apply PowerSeries.ext + intro d + let N:=max d (B*d) + calc + coeff d (regrade v Ω δ B (FormalLog.log F))= + coeff d (regrade v Ω δ B (FormalLog.logPolynomial F N)) := by + apply regrade_coeff_congr + intro n hn + exact (FormalLog.logPolynomial_coeff F hc N n (hn.trans (le_max_right _ _))).symm + _ = coeff d (FormalLog.logPolynomial (regrade v Ω δ B F) N) := by + rw [regrade_logPolynomial v Ω δ B F hf N] + _ = coeff d (FormalLog.log (regrade v Ω δ B F)) := + FormalLog.logPolynomial_coeff _ (regrade_constant v Ω δ B F hc) N d (le_max_left _ _) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootCoefficientLocality.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootCoefficientLocality.lean new file mode 100644 index 0000000000000000000000000000000000000000..19e6e4b11fb8eb589820ab1aab8cc967d3bb9690 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootCoefficientLocality.lean @@ -0,0 +1,102 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RootSectionHalfspace + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) +local instance rootCoefficientLocalityRing : Ring (Torus LaurentRay.vUnit Ω) := + Torus.instRing LaurentRay.vUnit Ω +local instance rootCoefficientLocalityAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance rootCoefficientLocalityAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +include hcoord in +lemma root_interval_orthogonal (base m b r s:M) (d:I → ℕ) + (hm:m=base+C (fun i=>(d i:ℤ))) + (hb:∃k,HasRootDegree C k (b-base)) + (hr:∃k,HasRootDegree C k r) (hs:∃k,HasRootDegree C k s) + (he:r+(s+b)=m) (ho:∀i,0(d i:ℤ)) := by + rw [←map_add,←map_add] + have he':r+(s+(b-base))=C (fun i=>(d i:ℤ)):=by rw [←add_sub_assoc,←add_sub_assoc,he,hm]; abel + rw [he',hcoord] + have hid:∀i,(ar i:ℤ)+(as' i:ℤ)+(ab i:ℤ)=(d i:ℤ):=by + intro i + have H:=congrFun hc i + simp only [Pi.add_apply] at H + rw [hcb,hcr,hcs] at H + omega + rw [root_simple_expansion C coord hcoord hr,map_sum] + simp only [AddMonoidHom.finsetSum_apply,map_zsmul,AddMonoidHom.zsmul_apply,smul_eq_mul] + apply Finset.sum_eq_zero + intro i _ + by_cases hi:0(d i:ℤ))) + (hb:∃k,HasRootDegree C k (b-base)) + (ho:∀i,0(d i:ℤ))) + (F:Torus LaurentRay.vUnit Ω) + (hF:∀b∈F.support,∃k,HasRootDegree C k (b-base)) + (ho:∀i,0F b*x) (actualMonomialAdjoint_locality Ω hΩ C coord hcoord f base m b d hm (hF b hb) ho) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootCoefficients.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d884ef4de5dc1bb8f910ae74ca8e9c90ad20484 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootCoefficients.lean @@ -0,0 +1,48 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegradeFaithful + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M:Type*} [CommRing R] [AddCommGroup M] +variable (v:Rˣ) (Ω:M →+ M →+ ℤ) +local instance rootCoefficientsRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance rootCoefficientsAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance rootCoefficientsAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def actualRootCoefficient (τ:M →+ ℤ) (f:PowerSeries (Torus v Ω)) (m:M) : R := + if 0≤τ m then coeff (τ m).toNat f m else 0 + +lemma actualRootCoefficient_read (τ:M →+ ℤ) (f:PowerSeries (Torus v Ω)) (n:ℕ) (m:M) + (hm:τ m=(n:ℤ)) : actualRootCoefficient v Ω τ f m=coeff n f m := by + simp only [actualRootCoefficient,hm,Int.natCast_nonneg,ite_true,Int.toNat_natCast] + +lemma regrade_actualRootCoefficient (τ δ:M →+ ℤ) (B:ℕ) (f:PowerSeries (Torus v Ω)) + (hf:RegradeBound v Ω δ B f) (hτ:FullHomogeneous v Ω τ f) (m:M) : + actualRootCoefficient v Ω δ (regrade v Ω δ B f) m=actualRootCoefficient v Ω τ f m := by + classical + by_cases ht:0≤τ m + · by_cases hd:0≤δ m + · simp only [actualRootCoefficient,ite_eq_left ht,ite_eq_left hd] + exact regrade_read v Ω δ B τ hf hτ _ m (Int.toNat_of_nonneg ht).symm + · have hz:coeff (τ m).toNat f m=0:=by + by_contra hh + exact hd (hf _ m hh).1 + simp only [actualRootCoefficient,ite_eq_left ht,ite_eq_right hd,hz] + · have hz:∀n,coeff n f m=0:=by + intro n + by_contra hh + have H:=hτ n m hh + exact ht (H ▸ Int.natCast_nonneg n) + simp only [actualRootCoefficient,ite_eq_right ht,regrade_coeff_eval] + split_ifs <;> simp only [hz,Finset.sum_const_zero] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootMutationInventory.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootMutationInventory.lean new file mode 100644 index 0000000000000000000000000000000000000000..e824298835bcddf24b40db1edadb82d5c15e4bbf --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootMutationInventory.lean @@ -0,0 +1,76 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularLevelQueues + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open Classical +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) + +omit [Fintype I] in +include hcoord in +lemma simpleRoot_injective : Function.Injective (simpleRoot C) := by + intro i j h + have H:=congrArg coord h + change coord (C (Pi.single i 1))=coord (C (Pi.single j 1)) at H + rw [hcoord,hcoord] at H + by_contra hn + have HH:=congrFun H i + simp [hn] at HH + +def rootMutation (p r : M) : M := + if r=p then -p else ForwardChain.positiveMutate Ω p r + +include hcoord in +lemma mutatedRoot_inventory (i : I) : + simpleRoot (mutatedRoots Ω C pc) i=rootMutation Ω (simpleRoot C pc) (simpleRoot C i) := by + by_cases hi : i=pc + · subst i + rw [mutatedRoot_p] + simp [rootMutation] + · have hn : simpleRoot C i≠simpleRoot C pc := + fun hh=>hi (simpleRoot_injective C coord hcoord hh) + rw [mutatedRoot_off Ω C pc i hi] + simp only [rootMutation,hn,ite_false,ForwardChain.positiveMutate,mutationPairing,max_comm] + +include hcoord in +lemma mutatedRoot_list (is : List I) : + is.map (simpleRoot (mutatedRoots Ω C pc))= + (is.map (simpleRoot C)).map (rootMutation Ω (simpleRoot C pc)) := by + rw [List.map_map] + exact List.map_congr_left fun i _=>mutatedRoot_inventory Ω C coord hcoord pc i + +lemma rootMutation_map_off (p : M) (l : List M) (hp : p∉l) : + l.map (rootMutation Ω p)=l.map (ForwardChain.positiveMutate Ω p) := by + apply List.map_congr_left + intro r hr + have hn:r≠p:=by intro h; subst r; exact hp hr + simp [rootMutation,hn] + +lemma rootMutation_rotation_perm (p a b c : M) (bs : List M) (hp : p=b-a) + (ha : Ω p a=1) (hb : Ω p b=1) (hc : Ω p c= -1) + (hs : ∀x∈bs,Ω p x=0) (hnd : (ForwardChain.gaps a (b::bs) c).Nodup) : + ((ForwardChain.gaps a (b::bs) c).map (rootMutation Ω p)).Perm + (ForwardChain.gaps a (bs++[c+p]) c) := by + change ((b-a)::ForwardChain.gaps b bs c).Nodup at hnd + have hnot : p∉ForwardChain.gaps b bs c := by rw [hp]; exact (List.nodup_cons.mp hnd).1 + simp only [ForwardChain.gaps,List.map_cons,←hp,rootMutation] + rw [rootMutation_map_off Ω p _ hnot] + exact ForwardChain.gaps_rotation_perm Ω p a b c bs hp ha hb hc hs + +lemma rootMutation_gaps_fixed (p a c : M) (bs : List M) + (ha : Ω p a≤0) (hc : 0≤Ω p c) (hb : ∀b∈bs,Ω p b=0) + (hp : p∉ForwardChain.gaps a bs c) : + (ForwardChain.gaps a bs c).map (rootMutation Ω p)=ForwardChain.gaps a bs c := by + rw [rootMutation_map_off Ω p _ hp] + exact ForwardChain.gaps_mutate_fixed Ω p a c bs ha hc hb +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootSectionHalfspace.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootSectionHalfspace.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fb601e48b9352d12b34aae71013ab888da2abbf --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootSectionHalfspace.lean @@ -0,0 +1,148 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.HalfspacePolynomialCoefficients + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits +open Classical +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) +local instance rootSectionHalfspaceRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance rootSectionHalfspaceAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance rootSectionHalfspaceAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma rootSectionChart_outer (h:M →+ ℝ) : + (rootSectionChart Ω C h).val=invOfUnit + ((chartPositive LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).val* + (chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).val) 1 := by + unfold rootSectionChart + dsimp only + conv_lhs => arg 2; arg 1; rw [←chart_three_factorization LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)] + rw [inverse_mul _ _ (by simp only [map_mul, + (chartPositive LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).property.1, + (chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).property.1,mul_one]) + (chartNegative LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).property.1, + ←mul_assoc,mul_invOfUnit _ 1 (chartNegative LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).property.1,one_mul] + +omit [DecidableEq I] in +lemma chartPositive_nonnegative [DecidableEq I] (h:M →+ ℝ) (F:CompletedPositive LaurentRay.vUnit Ω C) + (k:ℕ) (m:M) (hm:coeff k (chartPositive LaurentRay.vUnit Ω C h F).val m≠0) : 0 ≤ h m := by + cases k with + | zero=> + rw [coeff_zero_eq_constantCoeff,(chartPositive LaurentRay.vUnit Ω C h F).property.1] at hm + have he:m=0:=by + by_contra hn + exact hm (Finsupp.single_eq_of_ne hn) + rw [he,map_zero] + | succ k=> exact (chart_three_support LaurentRay.vUnit Ω C h F).1 k m hm |>.le + +omit [DecidableEq I] in +lemma chartZero_nonnegative [DecidableEq I] (h:M →+ ℝ) (F:CompletedPositive LaurentRay.vUnit Ω C) + (k:ℕ) (m:M) (hm:coeff k (chartZero LaurentRay.vUnit Ω C h F).val m≠0) : 0 ≤ h m := by + cases k with + | zero=> + rw [coeff_zero_eq_constantCoeff,(chartZero LaurentRay.vUnit Ω C h F).property.1] at hm + have he:m=0:=by + by_contra hn + exact hm (Finsupp.single_eq_of_ne hn) + rw [he,map_zero] + | succ k=> rw [(chart_three_support LaurentRay.vUnit Ω C h F).2.1 k m hm] + +lemma rootSectionChart_nonnegative (h:M →+ ℝ) (k:ℕ) (m:M) + (hm:coeff k (rootSectionChart Ω C h).val m≠0) : 0 ≤ h m := by + rw [rootSectionChart_outer] at hm + let P:=nonpositiveCone (-h) + have hs:∀d x,coeff d + ((chartPositive LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).val* + (chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).val) x≠0 → x∈P:=by + intro d x hx + obtain ⟨i,j,a,b,hij,ha,hb,he⟩:=series_product_nonzero LaurentRay.vUnit Ω _ _ d x hx + change (-h) x ≤ 0 + rw [←he,map_add,AddMonoidHom.neg_apply,AddMonoidHom.neg_apply] + linarith [chartPositive_nonnegative Ω C h (simpleTotalTransport Ω C) i a ha, + chartZero_nonnegative Ω C h (simpleTotalTransport Ω C) j b hb] + have H:=inverse_support_addSubmonoid LaurentRay.vUnit Ω P _ hs k m hm + change -h m ≤ 0 at H + linarith +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint +open scoped BigOperators +open Classical +noncomputable section +variable {K M:Type*} [Field K] [AddCommGroup M] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +local instance targetCyclicRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance targetCyclicAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance targetCyclicAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +lemma torus_eval_finset_sum {J:Type*} (s:Finset J) (f:J → Torus v Ω) (m:M) : + (∑j∈s,f j) m=∑j∈s,f j m := by + induction s using Finset.induction_on with + | empty=>rfl + | @insert j s hj ih=> + rw [Finset.sum_insert hj,Finset.sum_insert hj] + change f j m+(∑j∈s,f j) m=_ + rw [ih] +include hΩ + +lemma torus_target_cyclic (F G:Torus v Ω) (m:M) + (h:∀r∈F.support,∀s∈G.support,r+s=m → Ω r m=0) : (F*G) m=(G*F) m := by + change (Torus.multiply v Ω F G) m=(Torus.multiply v Ω G F) m + simp only [Torus.multiply,Finsupp.sum,Finsupp.finsetSum_apply] + conv_rhs => rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro r hr + apply Finset.sum_congr rfl + intro s hs + by_cases he:r+s=m + · have hrs:Ω r s=0 := by + have H:=h r hr s hs he + rw [←he,map_add,hΩ r,zero_add] at H + exact H + have hsr:Ω s r=0 := by rw [alternating_skew Ω hΩ,hrs,neg_zero] + simp only [←he,Finsupp.single_eq_same,add_comm s r,hrs,hsr,zpow_zero, + Units.val_one,mul_comm] + · have he':s+r≠m:=by simpa only [add_comm s r] using he + rw [Finsupp.single_eq_of_ne (Ne.symm he),Finsupp.single_eq_of_ne (Ne.symm he')] + +lemma series_target_cyclic (F G:PowerSeries (Torus v Ω)) (N:ℕ) (m:M) + (h:∀i j,i+j=N → ∀r∈(coeff i F).support,∀s∈(coeff j G).support,r+s=m → Ω r m=0) : + coeff N (F*G) m=coeff N (G*F) m := by + simp only [coeff_mul,torus_eval_finset_sum] + rw [←Finset.Nat.sum_antidiagonal_swap (f:=fun p:ℕ×ℕ=>(coeff p.1 G*coeff p.2 F) m)] + apply Finset.sum_congr rfl + intro p hp + exact torus_target_cyclic v Ω hΩ _ _ m (h p.1 p.2 (Finset.HasAntidiagonal.mem_antidiagonal.mp hp)) + +lemma adjoint_target_cyclic (F:PowerSeries (Torus v Ω)) (b m:M) (N:ℕ) + (hF:constantCoeff F=1) + (h:∀i j,i+j=N → ∀r∈(coeff i F).support, + ∀s∈(coeff j (invOfUnit F 1)).support,r+(s+b)=m → Ω r m=0) : + coeff N (adjoint F (PowerSeries.C (Torus.X v Ω b))) m= + coeff N (PowerSeries.C (Torus.X v Ω b)) m := by + rw [adjoint,mul_assoc] + rw [series_target_cyclic v Ω hΩ F (PowerSeries.C (Torus.X v Ω b)*invOfUnit F 1) N m] + · rw [mul_assoc,invOfUnit_mul F 1 hF,mul_one] + · intro i j hij r hr s hs he + have hs':coeff j (invOfUnit F 1) (s-b)≠0 := by + have H:=Finsupp.mem_support_iff.mp hs + rw [coeff_C_mul] at H + have Hread:=X_mul_coeff v Ω (coeff j (invOfUnit F 1)) (s-b) b + rw [sub_add_cancel] at Hread + rw [Hread] at H + exact (mul_ne_zero_iff.mp H).1 + exact h i j hij r hr (s-b) (Finsupp.mem_support_iff.mpr hs') (by simpa only [sub_add_cancel] using he) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootTruncation.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootTruncation.lean new file mode 100644 index 0000000000000000000000000000000000000000..77231a7289742996be2ed9ceb46b982ebcf2c3d9 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RootTruncation.lean @@ -0,0 +1,105 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.SplitContinuity + +namespace OAI + +section +namespace ElementaryPositivity +namespace RootTruncation +open PowerSeries +noncomputable section +variable {A : Type*} [Ring A] +def cut (N : ℕ) (F : PowerSeries A) : PowerSeries A := + PowerSeries.mk (fun n => if n≤N then coeff n F else 0) +@[simp] lemma coeff_cut (N n : ℕ) (F : PowerSeries A) : + coeff n (cut N F)=if n≤N then coeff n F else 0 := coeff_mk _ _ +lemma coeff_cut_of_le {N n : ℕ} (F : PowerSeries A) (hn : n≤N) : + coeff n (cut N F)=coeff n F := by simp [hn] +@[simp] lemma constant_cut (N : ℕ) (F : PowerSeries A) : + constantCoeff (cut N F)=constantCoeff F := by + rw [←coeff_zero_eq_constantCoeff,coeff_cut,ite_eq_left (Nat.zero_le _),coeff_zero_eq_constantCoeff] +lemma cut_congr {N : ℕ} {F G : PowerSeries A} (h : ∀n≤N,coeff n F=coeff n G) : + cut N F=cut N G := by + ext n + simp only [coeff_cut] + split_ifs with hn + · exact h n hn + · rfl +@[simp] lemma cut_cut (N : ℕ) (F : PowerSeries A) : cut N (cut N F)=cut N F := + cut_congr (fun _ hn=>coeff_cut_of_le F hn) +lemma cut_cut_le {N D : ℕ} (hD : D≤N) (F : PowerSeries A) : + cut D (cut N F)=cut D F := + cut_congr (fun _ hn=>coeff_cut_of_le F (hn.trans hD)) +lemma cut_zeroFactor (P Q : A→+A) (N : ℕ) (F : PowerSeries A) : + cut N (PowerSeriesSplit.zeroFactor P Q (cut N F))= + cut N (PowerSeriesSplit.zeroFactor P Q F) := by + apply cut_congr + intro n hn + exact PowerSeriesSplit.zero_coeff_congr P Q _ _ n (fun j hj=>coeff_cut_of_le F (hj.trans hn)) +lemma cut_mul_cut (N : ℕ) (F G : PowerSeries A) : + cut N (cut N F*cut N G)=cut N (F*G) := by + apply cut_congr + intro n hn + exact FormalLog.mul_coeff_congr _ _ _ _ n + (fun j hj=>coeff_cut_of_le F (hj.trans hn)) (fun j hj=>coeff_cut_of_le G (hj.trans hn)) +lemma cut_list_product {J : Type*} (N : ℕ) (l : List J) (F : J→PowerSeries A) : + cut N (l.map (fun j=>cut N (F j))).prod=cut N (l.map F).prod := by + apply cut_congr + intro n hn + exact PowerSeriesSplit.product_coeff_congr _ _ l n (fun j hj k hk=>coeff_cut_of_le (F j) (hk.trans hn)) +end +end RootTruncation +namespace QuantumTorus +open PowerSeries RootTruncation +noncomputable section +variable {R M I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) +def completedCut (N : ℕ) (F : CompletedPositive v Ω C) : CompletedPositive v Ω C := + ⟨cut N F.val,by simpa using F.property.1,by + intro n + rw [coeff_cut] + split_ifs + · exact F.property.2 n + · intro m hm; rfl⟩ +omit [Algebra ℚ R] in +lemma completedCut_supported (N : ℕ) (F : CompletedPositive v Ω C) (S : AddSubmonoid M) + (hF : ∀n≤N,coeff n F.val∈supportedSubring v Ω S) : + ∀n,coeff n (completedCut v Ω C N F).val∈supportedSubring v Ω S := by + intro n + change coeff n (cut N F.val)∈_ + rw [coeff_cut] + split_ifs with hn + · exact hF n hn + · exact (supportedSubring v Ω S).zero_mem +omit [Algebra ℚ R] in +lemma completedCut_chartZero (N : ℕ) (h : M→+ℝ) (F : CompletedPositive v Ω C) : + cut N (chartZero v Ω C h (completedCut v Ω C N F)).val= + cut N (chartZero v Ω C h F).val := + cut_zeroFactor _ _ _ _ +end +section Continuity +open PowerSeries RootTruncation Filter LaurentPrecision +variable {M I J : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) (l : Filter J) +lemma SeriesGraded.cut (N : ℕ) {F : PowerSeries (Torus v Ω)} (hF : SeriesGraded v Ω C F) : + SeriesGraded v Ω C (cut N F) := by + intro n + rw [coeff_cut] + split_ifs + · exact hF n + · intro m hm; rfl +lemma SeriesConverges.cut (N : ℕ) {f : J→PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) : + SeriesConverges v Ω l (fun j=>cut N (f j)) (cut N F) := by + intro n + simp only [coeff_cut] + by_cases hn : n≤N + · simp only [hn,ite_true]; exact hf n + · simp only [hn,ite_false]; exact torusConverges_const v Ω l 0 +end Continuity +end QuantumTorus +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RotationLocalPolynomials.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RotationLocalPolynomials.lean new file mode 100644 index 0000000000000000000000000000000000000000..443e849fe1fa193c44fd9b6b3b00fe95afc01930 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/RotationLocalPolynomials.lean @@ -0,0 +1,79 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RationalCenteredAction + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open WallUnits +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) + +lemma centeredCrossing_zero (p m : M) : centeredCrossing v Ω p m 0 = Torus.X v Ω m := by + simp [centeredCrossing,centeredPolynomial,Torus.X] + +lemma centeredCrossing_one (p m : M) : centeredCrossing v Ω p m 1 = + Torus.X v Ω m + Torus.X v Ω (m+p) := by + simp [centeredCrossing,centeredPolynomial,centeredExponent,Fin.sum_univ_two,Torus.X,Polynomial.coeff_one] +end +end ElementaryPositivity.QuantumTorus + +namespace ElementaryPositivity.RationalFiber +open QuantumTorus WallUnits +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀ m, Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +include hΩ in +lemma pureAction_pairing_zero (m : M) (hm : Ω p m=0) : + pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.X v Ω m)) = + embed v Ω hΩ k p hp (Torus.X v Ω m) := by + simpa only [centeredCrossing_zero] using pureAction_centered v Ω hΩ k p hp m 0 hm + +include hΩ in +lemma pureAction_pairing_one (m : M) (hm : Ω p m=1) : + pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.X v Ω m)) = + embed v Ω hΩ k p hp (Torus.X v Ω m + Torus.X v Ω (m+p)) := by + simpa only [centeredCrossing_one] using pureAction_centered v Ω hΩ k p hp m 1 hm + +lemma pureRatio_neg_one_cancel : (pureRatio v (-1):RatFunc K) * + (1+RatFunc.C (v:K)*RatFunc.X)=1 := by + have H := congrArg (fun a : (RatFunc K)ˣ => (a:RatFunc K)) (pureRatio_add v (-1) 1) + simp only [neg_add_cancel,pureRatio_zero,Units.val_one,Units.val_mul,scaleAction_val, + pureRatio_one] at H + change 1=(pureRatio v (-1):RatFunc K)* + scale (v^(-2*(-1:ℤ))) (1+RatFunc.C (↑(v⁻¹):K)*RatFunc.X) at H + have HH : scale (v^(-2*(-1:ℤ))) (1+RatFunc.C (↑(v⁻¹):K)*RatFunc.X)= + 1+RatFunc.C (v:K)*RatFunc.X := by + rw [map_add,map_one,map_mul,scale_constant,scale_X,←mul_assoc,←map_mul, + ←Units.val_mul,←zpow_neg_one,←zpow_add] + norm_num + rw [HH] at H + exact H.symm + +include hΩ in +lemma pureAction_pairing_neg_one (m : M) (hm : Ω p m= -1) : + pureAction v (complementOmega k Ω) (complementAlpha k p Ω) + (embed v Ω hΩ k p hp (Torus.X v Ω m + Torus.X v Ω (m+p))) = + embed v Ω hΩ k p hp (Torus.X v Ω m) := by + have H0 := embed_pure_row_term v Ω hΩ k p hp m 0 1 + have H1 := embed_pure_row_term v Ω hΩ k p hp m 1 1 + simp only [zero_smul,add_zero,map_one,mul_one,pow_zero,one_smul,pow_one,hm, + neg_neg,zpow_one] at H0 H1 + rw [map_add,map_add,Torus.X,Torus.X,H0,H1,pureAction_monomial,pureAction_monomial, + complement_pairing Ω hΩ k p hp m,hm,←FiberTorus.monomial_add] + congr 1 + have H := pureRatio_neg_one_cancel v + calc + _ = centeredScalar v (k m) (-1) * + ((pureRatio v (-1):RatFunc K)*(1+RatFunc.C (v:K)*RatFunc.X)) := by ring + _ = _ := by rw [H,mul_one] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SeriesApproximation.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SeriesApproximation.lean new file mode 100644 index 0000000000000000000000000000000000000000..79679777fb07a80881e0a34445d2374e3e10b8ab --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SeriesApproximation.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.SplitContinuity + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries LaurentPrecision Filter +noncomputable section +variable {M ι : Type*} [AddCommGroup M] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M→+M→+ℤ) + +abbrev PrecisionTest := ℕ×M×ℤ + +def TestAgreement (T : Finset (PrecisionTest (M:=M))) + (F G : PowerSeries (Torus v Ω)) : Prop := + ∀t∈T,Agrees t.2.2 ((coeff t.1 F) t.2.1) ((coeff t.1 G) t.2.1) + +def InPrecisionClosure (A : Set (PowerSeries (Torus v Ω))) + (F : PowerSeries (Torus v Ω)) : Prop := + ∀T : Finset (PrecisionTest (M:=M)),∃G∈A,TestAgreement v Ω T G F + +lemma testAgreement_refl (T : Finset (PrecisionTest (M:=M))) (F : PowerSeries (Torus v Ω)) : + TestAgreement v Ω T F F := fun _ _=>agrees_refl _ _ + +lemma TestAgreement.trans {T : Finset (PrecisionTest (M:=M))} + {F G H : PowerSeries (Torus v Ω)} + (hf : TestAgreement v Ω T F G) (hg : TestAgreement v Ω T G H) : + TestAgreement v Ω T F H := fun t ht j hj=>(hf t ht j hj).trans (hg t ht j hj) + +lemma inPrecisionClosure_self {A : Set (PowerSeries (Torus v Ω))} {F : PowerSeries (Torus v Ω)} + (hF : F∈A) : InPrecisionClosure v Ω A F := + fun T=>⟨F,hF,testAgreement_refl v Ω T F⟩ + +lemma InPrecisionClosure.mono {A B : Set (PowerSeries (Torus v Ω))} {F : PowerSeries (Torus v Ω)} + (hF : InPrecisionClosure v Ω A F) (hAB : A⊆B) : InPrecisionClosure v Ω B F := by + intro T + obtain ⟨G,hG,H⟩:=hF T + exact ⟨G,hAB hG,H⟩ + +variable (l : Filter ι) +lemma SeriesConverges.testAgreement {f : ι→PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) (T : Finset (PrecisionTest (M:=M))) : + ∀ᶠi in l,TestAgreement v Ω T (f i) F := by + classical + induction T using Finset.induction_on with + | empty=>exact Eventually.of_forall (by simp [TestAgreement]) + | @insert t T ht ih=> + filter_upwards [ih,hf t.1 t.2.1 t.2.2] with i hi hj + intro a ha + rcases Finset.mem_insert.mp ha with rfl|ha + · exact hj + · exact hi a ha + +lemma InPrecisionClosure.of_converges [l.NeBot] + {A : Set (PowerSeries (Torus v Ω))} {f : ι→PowerSeries (Torus v Ω)} + {F : PowerSeries (Torus v Ω)} (hf : SeriesConverges v Ω l f F) + (hA : ∀ᶠi in l,InPrecisionClosure v Ω A (f i)) : InPrecisionClosure v Ω A F := by + intro T + obtain ⟨i,hi,hAi⟩:=((hf.testAgreement v Ω l T).and hA).exists + obtain ⟨G,hG,H⟩:=hAi T + exact ⟨G,hG,H.trans v Ω hi⟩ + +variable {A : Set (PowerSeries (Torus v Ω))} {F : PowerSeries (Torus v Ω)} +variable (hF : InPrecisionClosure v Ω A F) +def precisionApprox (T : Finset (PrecisionTest (M:=M))) : PowerSeries (Torus v Ω) := + Classical.choose (hF T) + +lemma precisionApprox_mem (T : Finset (PrecisionTest (M:=M))) : precisionApprox v Ω hF T∈A := + (Classical.choose_spec (hF T)).1 + +lemma precisionApprox_agrees (T : Finset (PrecisionTest (M:=M))) : + TestAgreement v Ω T (precisionApprox v Ω hF T) F := + (Classical.choose_spec (hF T)).2 + +lemma precisionApprox_converges : + SeriesConverges v Ω (atTop : Filter (Finset (PrecisionTest (M:=M)))) + (precisionApprox v Ω hF) F := by + classical + intro n m N + apply eventually_atTop.mpr + refine ⟨{(n,m,N)},fun T hT=>?_⟩ + exact precisionApprox_agrees v Ω hF T (n,m,N) (hT (by simp)) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SimpleBinomial.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SimpleBinomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a2f9e2a50a491353feb1562624cb6c22ae43496 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SimpleBinomial.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SimpleIncomingData +import OAI.Combinatorics.Chromatic.Walls.FiniteElementaryAdjoint + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits PowerSeriesAdjoint +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +def normalizedSimple (p : M) : PowerSeries (Torus LaurentRay.vUnit Ω) := + raySeries LaurentRay.vUnit Ω p + (elementary (HahnSeries.single (2:ℤ) (1:ℚ)) (HahnSeries.single (1:ℤ) (1:ℚ))) +omit [Fintype I] in +lemma simpleDatum_value (pc : I) : (simpleDatum C pc).value Ω=normalizedSimple Ω (simpleRoot C pc) := by + apply PowerSeries.ext + intro n + rw [WallUnitDatum.value,coeff_weightedRay] + simp only [simpleDatum,one_dvd,Nat.div_one,UnitSelections.indexedUnit,↓reduceIte, + LaurentRay.elementary_atInfinity,neg_neg,coeff_raySeries,normalizedSimple] +lemma normalizedSimple_constant (p : M) : constantCoeff (normalizedSimple Ω p)=1 := by + rw [←coeff_zero_eq_constantCoeff] + rw [normalizedSimple,coeff_raySeries,zero_nsmul,coeff_zero_eq_constantCoeff,constant_elementary] + rfl +lemma normalizedSimple_inverse (hΩ : ∀m,Ω m m=0) (p : M) : + invOfUnit (normalizedSimple Ω p) 1= + raySeries LaurentRay.vUnit Ω p + (elementary (HahnSeries.single (2:ℤ) (1:ℚ)) (HahnSeries.single (1:ℤ) (1:ℚ)))⁻¹ := by + let U:=rayUnit LaurentRay.vUnit Ω p (hΩ p) + (elementary (HahnSeries.single (2:ℤ) (1:ℚ)) (HahnSeries.single (1:ℤ) (1:ℚ))) (constant_elementary _ _) + change invOfUnit U.val 1=U.inv + calc + _=invOfUnit U.val 1*(U.val*U.inv):=by rw [U.val_inv,mul_one] + _=(invOfUnit U.val 1*U.val)*U.inv:=by rw [mul_assoc] + _=U.inv:=by rw [invOfUnit_mul U.val 1 (normalizedSimple_constant Ω p),one_mul] +lemma laurent_q_nonzero : (HahnSeries.single (2:ℤ) (1:ℚ) : LaurentSeries ℚ)≠0 := by + rw [←LaurentRay.atInfinity_q] + intro hz + exact RationalRay.q_nonzero (LaurentRay.atInfinity_injective (hz.trans (map_zero _).symm)) +lemma laurent_shift_positive (t : ℕ) : + (↑(LaurentRay.vUnit^(2*(t:ℤ))) : LaurentSeries ℚ)= + (HahnSeries.single (2:ℤ) (1:ℚ))⁻¹^t := by + rw [LaurentRay.vUnit_zpow,←LaurentRay.atInfinity_v_pow,←LaurentRay.atInfinity_q,←map_inv₀,←map_pow] + congr 1 + rw [inv_pow,RationalRay.q_pow,←zpow_neg] + congr 1 + ring +lemma laurent_shift_negative (t : ℕ) : + (↑(LaurentRay.vUnit^(2*(-(t:ℤ)))) : LaurentSeries ℚ)= + (HahnSeries.single (2:ℤ) (1:ℚ))^t := by + rw [LaurentRay.vUnit_zpow,←LaurentRay.atInfinity_v_pow,←LaurentRay.atInfinity_q,←map_pow,RationalRay.q_pow] + congr 2 + ring +lemma normalizedSimple_adjoint_support (hΩ : ∀m,Ω m m=0) (p m x : M) (t N : ℕ) + (ht : Ω p m=(t:ℤ)) + (hx : coeff N (adjoint (normalizedSimple Ω p) (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m))) x≠0) : + N≤t ∧ x=m+N • p := by + rw [adjoint,normalizedSimple_inverse Ω hΩ p] at hx + exact elementary_adjoint_support LaurentRay.vUnit Ω hΩ p m x _ _ laurent_q_nonzero + UnitSelections.laurent_q_not_root t N (by rw [ht]; exact laurent_shift_positive t) hx +lemma normalizedSimple_inverse_adjoint_support (hΩ : ∀m,Ω m m=0) (p m x : M) (t N : ℕ) + (ht : Ω p m= -(t:ℤ)) + (hx : coeff N (adjoint (invOfUnit (normalizedSimple Ω p) 1) + (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m))) x≠0) : N≤t ∧ x=m+N • p := by + rw [adjoint_inverse _ _ (normalizedSimple_constant Ω p),normalizedSimple_inverse Ω hΩ p] at hx + exact elementary_inverse_adjoint_support LaurentRay.vUnit Ω hΩ p m x _ _ laurent_q_nonzero + UnitSelections.laurent_q_not_root t N (by rw [ht]; exact laurent_shift_negative t) hx +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SplitContinuity.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SplitContinuity.lean new file mode 100644 index 0000000000000000000000000000000000000000..be56feb920f8be9977baf367000ca53f02266126 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SplitContinuity.lean @@ -0,0 +1,124 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.TorusContinuity + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries LaurentPrecision ElementaryPositivity.PowerSeriesSplit +noncomputable section +variable {M I ι : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) +variable (C : (I → ℤ) →+ M) (l : Filter ι) +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub +attribute [local instance] Classical.propDecidable + +def SeriesConverges (f : ι → PowerSeries (Torus v Ω)) (F : PowerSeries (Torus v Ω)) : Prop := + ∀n,TorusConverges v Ω l (fun i=>coeff n (f i)) (coeff n F) + +def SeriesGraded (F : PowerSeries (Torus v Ω)) : Prop := + ∀n,coeff n F∈rootGrade v Ω C n + +lemma seriesConverges_const (F : PowerSeries (Torus v Ω)) : + SeriesConverges v Ω l (fun _=>F) F := fun _=>torusConverges_const v Ω l _ + +lemma SeriesConverges.sub {f g : ι → PowerSeries (Torus v Ω)} {F G : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) (hg : SeriesConverges v Ω l g G) : + SeriesConverges v Ω l (fun i=>f i-g i) (F-G) := by + intro n + exact (hf n).sub v Ω l (hg n) + +lemma SeriesConverges.mul {f g : ι → PowerSeries (Torus v Ω)} {F G : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) (hg : SeriesConverges v Ω l g G) + (hfg : ∀i,SeriesGraded v Ω C (f i)) (hgg : ∀i,SeriesGraded v Ω C (g i)) + (hF : SeriesGraded v Ω C F) (hG : SeriesGraded v Ω C G) : + SeriesConverges v Ω l (fun i=>f i*g i) (F*G) := by + intro n + simp only [coeff_mul] + apply TorusConverges.sum + intro p hp + exact (hf p.1).mul_graded v Ω C l (hg p.2) p.1 p.2 + (fun i=>hfg i p.1) (fun i=>hgg i p.2) (hF p.1) (hG p.2) + +lemma filter_pair_graded (p : M → Prop) (F : PowerSeries (Torus v Ω)) + (hF : SeriesGraded v Ω C F) (n : ℕ) : + (pairCoefficients (Finsupp.filterAddHom p) F n).1∈rootGrade v Ω C n ∧ + (pairCoefficients (Finsupp.filterAddHom p) F n).2∈rootGrade v Ω C n := by + have H := factors_graded (Finsupp.filterAddHom p) (rootGrade v Ω C) + (rootGrade_one v Ω C) (rootGrade_mul v Ω C) + (fun n x hx=>rootGrade_filter v Ω C p n x hx) F hF + simpa only [leftFactor,rightFactor,coeff_mk] using And.intro (H.1 n) (H.2 n) + +lemma filter_pair_converges (p : M → Prop) + {f : ι → PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) + (hfg : ∀i,SeriesGraded v Ω C (f i)) (hF : SeriesGraded v Ω C F) (n : ℕ) : + TorusConverges v Ω l (fun i=>(pairCoefficients (Finsupp.filterAddHom p) (f i) n).1) + (pairCoefficients (Finsupp.filterAddHom p) F n).1 ∧ + TorusConverges v Ω l (fun i=>(pairCoefficients (Finsupp.filterAddHom p) (f i) n).2) + (pairCoefficients (Finsupp.filterAddHom p) F n).2 := by + induction n using Nat.strong_induction_on with + | h n ih => + cases n with + | zero => simpa only [pairCoefficients] using + And.intro (torusConverges_const v Ω l 1) (torusConverges_const v Ω l 1) + | succ n => + let P : Torus v Ω →+ Torus v Ω := Finsupp.filterAddHom p + have hprod : TorusConverges v Ω l + (fun i=>∑j : Fin n,(pairCoefficients P (f i) (j.val+1)).1 * + (pairCoefficients P (f i) (n-j.val)).2) + (∑j : Fin n,(pairCoefficients P F (j.val+1)).1 * + (pairCoefficients P F (n-j.val)).2) := by + apply TorusConverges.sum + intro j hj + exact (ih (j.val+1) (by omega)).1.mul_graded v Ω C l + (ih (n-j.val) (by omega)).2 (j.val+1) (n-j.val) + (fun i=>(filter_pair_graded v Ω C p (f i) (hfg i) _).1) + (fun i=>(filter_pair_graded v Ω C p (f i) (hfg i) _).2) + (filter_pair_graded v Ω C p F hF _).1 + (filter_pair_graded v Ω C p F hF _).2 + have hr := (hf (n+1)).sub v Ω l hprod + have hp := hr.filter v Ω l p + constructor + · unfold pairCoefficients + exact hp + · unfold pairCoefficients + exact hr.sub v Ω l hp + +lemma filter_factors_converge (p : M → Prop) + {f : ι → PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) + (hfg : ∀i,SeriesGraded v Ω C (f i)) (hF : SeriesGraded v Ω C F) : + SeriesConverges v Ω l (fun i=>leftFactor (Finsupp.filterAddHom p) (f i)) + (leftFactor (Finsupp.filterAddHom p) F) ∧ + SeriesConverges v Ω l (fun i=>rightFactor (Finsupp.filterAddHom p) (f i)) + (rightFactor (Finsupp.filterAddHom p) F) := by + constructor + · intro n + simpa only [leftFactor,coeff_mk] using (filter_pair_converges v Ω C l p hf hfg hF n).1 + · intro n + simpa only [rightFactor,coeff_mk] using (filter_pair_converges v Ω C l p hf hfg hF n).2 + +theorem chart_three_converge (h : M →+ ℝ) + {f : ι → CompletedPositive v Ω C} {F : CompletedPositive v Ω C} + (hf : SeriesConverges v Ω l (fun i=>(f i).val) F.val) : + SeriesConverges v Ω l (fun i=>(chartPositive v Ω C h (f i)).val) + (chartPositive v Ω C h F).val ∧ + SeriesConverges v Ω l (fun i=>(chartZero v Ω C h (f i)).val) + (chartZero v Ω C h F).val ∧ + SeriesConverges v Ω l (fun i=>(chartNegative v Ω C h (f i)).val) + (chartNegative v Ω C h F).val := by + have H := filter_factors_converge v Ω C l (fun m=>0(f i).property.2) F.property.2 + refine ⟨H.1,?_⟩ + exact filter_factors_converge v Ω C l (fun m=>h m=0) H.2 + (fun i=>(chartRemainder v Ω C h (f i)).property.2) + (chartRemainder v Ω C h F).property.2 + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SquarefreeCoefficient.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SquarefreeCoefficient.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7f15a7936f7fcbbdc3eed12f7742b170b5a9dad --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SquarefreeCoefficient.lean @@ -0,0 +1,79 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.OrderedIndependentProduct +import OAI.Combinatorics.Chromatic.Walls.SquarefreeBlocks + +namespace OAI + +section +namespace ElementaryPositivity +open scoped BigOperators +open Classical +noncomputable section +lemma sum_eq_subtype {A R:Type*} [Fintype A] [AddCommMonoid R] + (p:A → Prop) [DecidablePred p] (f:A → R) (hf:∀a,¬p a → f a=0) : + ∑a,f a=∑a:{a // p a},f a.val := by + rw [←Fintype.sum_subtype_add_sum_subtype p f] + have H:(∑a:{a // ¬p a},f a.val)=0:=Finset.sum_eq_zero (fun a _=>hf a.val a.property) + rw [H,add_zero] + +namespace QuantumTorus +variable {K M V:Type*} [Field K] [AddCommGroup M] [Fintype V] [DecidableEq V] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) +local instance squarefreeCoefficientRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance squarefreeCoefficientAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance squarefreeCoefficientAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +variable (c:(V → ℤ) →+ M) (hc:Function.Injective c) +variable {n r:ℕ} (b:Fin n ↪ V) + +omit [Fintype V] in +lemma blockLabels_sum (s:Fin r → Finset V) : + wordExponent (blockLabels (fun x=>c (Pi.single x 1)) s)=c (SquarefreeBlocks.vector s) := by + simp only [wordExponent,blockLabels,SquarefreeBlocks.vector,map_sum] + +include hc in +lemma independent_product_squarefree (a:Fin r → ℕ) : + ((List.ofFn (fun i=>independentElement v Ω (fun x=>c (Pi.single x 1)) (a i))).prod) + (c (SquarefreeBlocks.target b))= + ∑κ:Fin n → Fin r, + if BlockValid Ω (fun x=>c (Pi.single x 1)) a (SquarefreeBlocks.blocks b κ) then + ↑(v^(wordEnergy Ω (blockLabels (fun x=>c (Pi.single x 1)) (SquarefreeBlocks.blocks b κ)))) else 0 := by + rw [independentElement_product] + have hs:∀(s:Finset (Fin r → Finset V)) (f:(Fin r → Finset V) → Torus v Ω), + (∑a∈s,f a) (c (SquarefreeBlocks.target b))=∑a∈s,f a (c (SquarefreeBlocks.target b)):=by + intro s f + induction s using Finset.induction with + | empty=>rfl + | @insert a s ha ih=> + rw [Finset.sum_insert ha,Finset.sum_insert ha] + change f a _+(∑i∈s,f i) _=_ + rw [ih] + rw [hs] + let term (s:Fin r → Finset V):K:= + (if BlockValid Ω (fun x=>c (Pi.single x 1)) a s then + Torus.monomial v Ω (wordExponent (blockLabels (fun x=>c (Pi.single x 1)) s)) + (↑(v^(wordEnergy Ω (blockLabels (fun x=>c (Pi.single x 1)) s)))) else 0) + (c (SquarefreeBlocks.target b)) + change (∑s,term s)=_ + rw [sum_eq_subtype (fun s=>SquarefreeBlocks.vector s=SquarefreeBlocks.target b) term] + · rw [←Equiv.sum_comp (SquarefreeBlocks.equiv b).symm] + apply Finset.sum_congr rfl + intro κ hκ + change term (SquarefreeBlocks.blocks b κ)=_ + unfold term + split_ifs with h + · rw [blockLabels_sum,Torus.monomial,SquarefreeBlocks.blocks_vector] + exact Finsupp.single_eq_same + · rfl + · intro s hs + unfold term + split_ifs + · rw [blockLabels_sum,Torus.monomial] + exact Finsupp.single_eq_of_ne (fun h=>hs (hc h.symm)) + · rfl +end QuantumTorus +end +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/Strict.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/Strict.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b25a42f6cfe0168cc2305139e0c487adb828887 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/Strict.lean @@ -0,0 +1,57 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.TruncatedChart +import OAI.Combinatorics.Chromatic.Walls.RootProducts + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) +lemma predicate_nsmul (P : M→Prop) (hP : ∀a b,P a→P b→P (a+b)) + (m : M) (hm : P m) (n : ℕ) (hn : 0omega + | succ n ih=> + by_cases h0 : n=0 + · subst n; simpa using hm + · rw [succ_nsmul] + exact hP _ _ (ih (by omega)) hm +lemma WallUnitDatum.strictSupport (P : M→Prop) (hP : ∀a b,P a→P b→P (a+b)) + (u : WallUnitDatum M) (hu : u.Allowed C P) (n : ℕ) : + SupportedOn LaurentRay.vUnit Ω P (coeff (n+1) (u.value Ω)) := by + intro m hm + rw [WallUnitDatum.value,coeff_weightedRay] + split_ifs with hd + · change (Finsupp.single (((n+1)/u.degree) • u.root) _) m=0 + apply Finsupp.single_eq_of_ne + intro he + apply hm + rw [he] + exact predicate_nsmul P hP u.root hu.2.2 _ + (Nat.div_pos (Nat.le_of_dvd (by omega) hd) hu.1) + · rfl +lemma literalRootProducts_strictSupport (P : M→Prop) (hP : ∀a b,P a→P b→P (a+b)) + {F : PowerSeries (Torus LaurentRay.vUnit Ω)} (hF : F∈literalRootProducts Ω C P) : + ∀n,SupportedOn LaurentRay.vUnit Ω P (coeff (n+1) F) := by + obtain ⟨l,hl,rfl⟩:=hF + induction l with + | nil=> + intro n + simp only [List.map_nil,List.prod_nil,PowerSeries.coeff_one,Nat.succ_ne_zero,ite_false] + exact SupportedOn.zero _ _ P + | cons u l ih=> + intro n + simp only [List.map_cons,List.prod_cons] + apply strict_mul_through LaurentRay.vUnit Ω P hP _ _ (n+1) + (u.constant Ω) (literalRootProducts_constant Ω C P ⟨l,fun w hw=>hl w (by simp [hw]),rfl⟩) + (fun j hj=>u.strictSupport Ω C P hP (hl u (by simp)) j) + (fun j hj=>ih (fun w hw=>hl w (by simp [hw])) j) n le_rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/StringBackshift.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/StringBackshift.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b96d7f42b3df92f3b8131bee5573f4ef75e50b1 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/StringBackshift.lean @@ -0,0 +1,61 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.StringPositiveFactor + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity RawShuffle EnergyLaurent QuantumTorus WallUnits WeightedTorusSeries +noncomputable section +variable {S I : Type*} [Fintype I] [DecidableEq I] +variable (a : S → ℕ) (t : S → ℕ) (dim : S → (I→ℕ)) (k : S → ℤ) +variable (τ : (I→ℕ) →+ ℤ) (hτ : ∀s,(t s:ℤ)=τ (dim s)) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) + +omit [Fintype I] [DecidableEq I] in +include hτ in +lemma stringEnergy_backshift (d : I→ℕ) (x : StringCounts a dim d) : + stringEnergy a dim (fun s=>k s-2*(t s:ℤ)) d x= + stringEnergy a dim k d x-2*τ d := by + have H:=stringEnergy_shift a t dim τ hτ (fun s=>k s-2*(t s:ℤ)) d x + have hk : (fun s=>k s-2*(t s:ℤ)+2*(t s:ℤ))=k := by funext s; ring + rw [hk] at H + omega + +omit [Fintype I] [DecidableEq I] in +include hτ he in +lemma backshiftString_admissible (d : I→ℕ) : + Admissible (stringEnergy a dim (fun s=>k s-2*(t s:ℤ)) d) := + admissible_injective (admissible_shift (he d) (-(2*τ d))) id Function.injective_id + (fun x=>by simpa only [sub_eq_add_neg,id_eq,Equiv.refl_apply] using + (stringEnergy_backshift a t dim k τ hτ d x).symm) + +omit [Fintype I] [DecidableEq I] in +include hτ he in +lemma backshiftString_series (d : I→ℕ) : + stringSeries a dim (fun s=>k s-2*(t s:ℤ)) + (backshiftString_admissible a t dim k τ hτ he) d= + stringSeries a dim k he d*HahnSeries.single (2*τ d) (1:ℚ) := by + rw [stringSeries,stringSeries,←neg_neg (2*τ d),←series_shift] + apply series_equiv _ _ (Equiv.refl _) + intro x + exact (by simpa only [sub_eq_add_neg,id_eq,Equiv.refl_apply] using (stringEnergy_backshift a t dim k τ hτ d x).symm) + +include hτ he in +lemma backstripString_series (d : I→ℕ) : + stringSeries a dim k he d= + ∑s : DimensionSplit d, + stripSeries a t dim (fun s=>k s-2*(t s:ℤ)) τ hτ + (backshiftString_admissible a t dim k τ hτ he) s.left * + stringSeries a dim (fun s=>k s-2*(t s:ℤ)) + (backshiftString_admissible a t dim k τ hτ he) s.right := by + have H:=stringStrip_series a t dim (fun s=>k s-2*(t s:ℤ)) τ hτ + (backshiftString_admissible a t dim k τ hτ he) d + have hk : (fun s=>k s-2*(t s:ℤ)+2*(t s:ℤ))=k := by funext s; ring + simpa only [hk,stringSeries] using H +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/StringStripSeries.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/StringStripSeries.lean new file mode 100644 index 0000000000000000000000000000000000000000..f35436562407adacdda9adf4aae5fef6742dabca --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/StringStripSeries.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNThreshold +import OAI.Combinatorics.Chromatic.QuantumTorus.StringStripDimension + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity RawShuffle EnergyLaurent +noncomputable section +variable {S I : Type*} [Fintype I] [DecidableEq I] +variable (a : S → ℕ) (t : S → ℕ) (dim : S → (I → ℕ)) (k : S → ℤ) +variable (τ : (I→ℕ) →+ ℤ) (hτ : ∀s,(t s:ℤ)=τ (dim s)) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) + +include hτ he in +omit [Fintype I] [DecidableEq I] in +lemma shiftedString_admissible (d : I → ℕ) : + Admissible (stringEnergy a dim (fun s=>k s+2*(t s:ℤ)) d) := + admissible_injective (admissible_shift (he d) (2*τ d)) id Function.injective_id + (fun x=>(stringEnergy_shift a t dim τ hτ k d x).symm) + +include hτ he in +omit [Fintype I] [DecidableEq I] in +lemma stripEnergy_admissible (d : I → ℕ) : Admissible (stripEnergy a t dim k d) := + admissible_injective (shiftedString_admissible a t dim k τ hτ he d) + (stripInsert a t dim d) (stripInsert_injective a t dim d) (stripInsert_energy a t dim k d) + +def stripSeries (d : I → ℕ) : LaurentSeries ℚ := + series _ (stripEnergy_admissible a t dim k τ hτ he d) + +include hτ he in +lemma stringStrip_series (d : I → ℕ) : + series (stringEnergy a dim (fun s=>k s+2*(t s:ℤ)) d) + (shiftedString_admissible a t dim k τ hτ he d)= + ∑s : DimensionSplit d,stripSeries a t dim k τ hτ he s.left* + series (stringEnergy a dim k s.right) (he s.right) := by + classical + let f (s : DimensionSplit d) (p : StripCounts a t dim s.left × StringCounts a dim s.right) := + stripEnergy a t dim k s.left p.1+stringEnergy a dim k s.right p.2 + have hf : ∀s,Admissible (f s) := fun s=>admissible_prod + (stripEnergy_admissible a t dim k τ hτ he s.left) (he s.right) + rw [series_equiv (shiftedString_admissible a t dim k τ hτ he d) + (admissible_sigma f hf) (stringStripDimensionEquiv a t dim d) + (fun x=>(stringStripDimension_energy a t dim k d x).symm),series_sigma f hf] + apply Finset.sum_congr rfl + intro s hs + exact (series_mul (stripEnergy_admissible a t dim k τ hτ he s.left) (he s.right)).symm + +include hτ he in + +theorem stringStrip_scaled (d : I → ℕ) : + series (stringEnergy a dim k d) (he d)*HahnSeries.single (-(2*τ d)) (1:ℚ)= + ∑s : DimensionSplit d,stripSeries a t dim k τ hτ he s.left* + series (stringEnergy a dim k s.right) (he s.right) := by + rw [←series_shift] + have H : (fun x : StringCounts a dim d=>stringEnergy a dim k d x+2*τ d)= + stringEnergy a dim (fun s=>k s+2*(t s:ℤ)) d := + funext (fun x=>(stringEnergy_shift a t dim τ hτ k d x).symm) + simp only [H] + exact stringStrip_series a t dim k τ hτ he d + +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SupportedConvolution.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SupportedConvolution.lean new file mode 100644 index 0000000000000000000000000000000000000000..febcf2b858cd29785ec6bfb04256cc74b7511c6e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/SupportedConvolution.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.WeightedTorusSeries +import OAI.Combinatorics.Chromatic.Shuffle.SymmetricSpace + +namespace OAI + +section +namespace ElementaryPositivity.WeightedTorusSeries +open ElementaryPositivity.RawShuffle +noncomputable section +attribute [local instance] Classical.propDecidable +variable {I R M : Type*} [Fintype I] [DecidableEq I] [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (P : (I → ℕ) →+ M) + +def Supported (S : Finset I) (d : I → ℕ) : Prop := ∀i,i∉S → d i=0 + +def restrictDim (S : Finset I) (d : I → ℕ) : I → ℕ := fun i=>if i∈S then d i else 0 + +omit [Fintype I] in +lemma restrictDim_supported (S : Finset I) (d : I → ℕ) : Supported S (restrictDim S d) := by + intro i hi + simp [restrictDim,hi] + +omit [Fintype I] in +lemma restrictDim_eq (S : Finset I) (d : I → ℕ) (hd : Supported S d) : restrictDim S d=d := by + funext i + by_cases hi : i∈S <;> simp [restrictDim,hi,hd i] + +omit [Fintype I] in +lemma supported_add (S T : Finset I) (d e : I → ℕ) (hd : Supported S d) (he : Supported T e) : + Supported (S∪T) (d+e) := by + intro i hi + have H : i∉S ∧ i∉T := by simpa only [Finset.mem_union,not_or] using hi + simp [hd i H.1,he i H.2] + +omit [Fintype I] in +lemma restrictDim_split (S T : Finset I) (hST : Disjoint S T) (d : I → ℕ) + (hd : Supported (S∪T) d) : restrictDim S d+restrictDim T d=d := by + funext i + by_cases hS : i∈S + · have hT : i∉T := fun hi=>Finset.disjoint_left.mp hST hS hi + simp [restrictDim,hS,hT] + · by_cases hT : i∈T + · simp [restrictDim,hS,hT] + · simp [restrictDim,hS,hT,hd i (by simp [hS,hT])] + +omit [Fintype I] in +lemma split_left_restrict (S T : Finset I) (hST : Disjoint S T) (d : I → ℕ) + (s : DimensionSplit d) (hs : Supported S s.left) (ht : Supported T s.right) : + s.left=restrictDim S d := by + funext i + by_cases hS : i∈S + · have hT : i∉T := fun hi=>Finset.disjoint_left.mp hST hS hi + have H:=congrFun (DimensionSplit.left_add_right s) i + simp only [Pi.add_apply,ht i hT,add_zero] at H + simp [restrictDim,hS,H] + · simp [restrictDim,hS,hs i hS] + +def supportedCoefficient (S : Finset I) (f : (I → ℕ) → R) (d : I → ℕ) : R := by + classical + exact if Supported S d then f d else 0 + +lemma supported_convolution (S T : Finset I) (hST : Disjoint S T) + (f g : (I → ℕ) → R) (d : I → ℕ) : + convolution v Ω P (supportedCoefficient S f) (supportedCoefficient T g) d= + if Supported (S∪T) d then + f (restrictDim S d)*g (restrictDim T d)*↑(v^(Ω (P (restrictDim S d)) (P (restrictDim T d)))) + else 0 := by + classical + unfold convolution + by_cases hd : Supported (S∪T) d + · rw [ite_eq_left hd] + let s₀:=DimensionSplit.ofPair (restrictDim S d) (restrictDim T d) (restrictDim_split S T hST d hd) + rw [Finset.sum_eq_single s₀] + · simp [s₀,supportedCoefficient,restrictDim_supported] + · intro s hs hne + by_cases hS : Supported S s.left + · by_cases hT : Supported T s.right + · exact (hne (DimensionSplit.ext (split_left_restrict S T hST d s hS hT))).elim + · simp [supportedCoefficient,hT] + · simp [supportedCoefficient,hS] + · simp + · rw [ite_eq_right hd] + apply Finset.sum_eq_zero + intro s hs + by_cases hS : Supported S s.left + · have hT : ¬Supported T s.right := by + intro hT + have H:=supported_add S T s.left s.right hS hT + rw [DimensionSplit.left_add_right] at H + exact hd H + simp [supportedCoefficient,hT] + · simp [supportedCoefficient,hS] + +end +end ElementaryPositivity.WeightedTorusSeries + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TraceLogDerivative.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TraceLogDerivative.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e7e1496d507c568c6dc8a32d283008943ce17ab --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TraceLogDerivative.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplitLeading +import OAI.Combinatorics.Chromatic.GradedAlgebra.NoncommSeriesCalculus + +namespace OAI + +section +namespace ElementaryPositivity.FormalLog +open PowerSeries +noncomputable section +variable {R K : Type*} [Ring R] [Algebra ℚ R] [CommRing K] [Algebra ℚ K] +variable (τ : R→ₗ[ℚ] K) (hτ : ∀a b,τ (a*b)=τ (b*a)) +include hτ in +lemma trace_log_derivative (F : PowerSeries R) (hF : constantCoeff F=1) : + traceSeries τ (ncDerivative (FormalLog.log F))= + traceSeries τ (ncDerivative F*invOfUnit F 1) := by + ext n + simp only [coeff_traceSeries,coeff_ncDerivative,FormalLog.log,coeff_mk, + map_nsmul,map_sum,LinearMap.map_smul,Finset.smul_sum] + rw [geometric_mul_coeff F (ncDerivative F) hF n] + simp only [Finset.mul_sum,map_sum] + apply Finset.sum_congr rfl + intro k hk + have H:=congrArg (coeff n) (trace_derivative_power' τ hτ (F-1) k) + simp only [coeff_traceSeries,coeff_ncDerivative,map_nsmul, + map_sub,ncDerivative_one,sub_zero] at H + rw [smul_comm (n+1) ((-1:ℚ)^k/(k+1:ℕ)),H] + rw [←Nat.cast_smul_eq_nsmul ℚ,smul_smul,div_mul_cancel₀ _ (by positivity : ((k+1:ℕ):ℚ)≠0)] + have Hpow : (-(F-1))^k=(-1:ℚ)^k • (F-1)^k := by + rw [←smul_pow] + simp + rw [Hpow,mul_smul_comm,coeff_smul,LinearMap.map_smul] +end +end ElementaryPositivity.FormalLog + +end +section +namespace ElementaryPositivity.FormalLog +open PowerSeries +noncomputable section +variable {R K : Type*} [Ring R] [Algebra ℚ R] [CommRing K] [Algebra ℚ K] +variable (τ : R→ₗ[ℚ] K) (hτ : ∀a b,τ (a*b)=τ (b*a)) +omit [Algebra ℚ R] in +lemma inverse_product (F G : PowerSeries R) (hF : constantCoeff F=1) + (hG : constantCoeff G=1) : invOfUnit (F*G) 1=invOfUnit G 1*invOfUnit F 1 := by + have H : (F*G)*(invOfUnit G 1*invOfUnit F 1)=1 := by + rw [mul_assoc,←mul_assoc G,PowerSeries.mul_invOfUnit G 1 hG,one_mul, + PowerSeries.mul_invOfUnit F 1 hF] + have H' :=congrArg (fun x : PowerSeries R=>invOfUnit (F*G) 1*x) H + rw [←mul_assoc,PowerSeries.invOfUnit_mul (F*G) 1 (by simp [hF,hG]),one_mul,mul_one] at H' + exact H'.symm + +include hτ in +lemma trace_log_product (F G : PowerSeries R) (hF : constantCoeff F=1) + (hG : constantCoeff G=1) : + traceSeries τ (FormalLog.log (F*G))= + traceSeries τ (FormalLog.log F)+traceSeries τ (FormalLog.log G) := by + have H : traceSeries τ (ncDerivative (FormalLog.log (F*G)))= + traceSeries τ (ncDerivative (FormalLog.log F))+ + traceSeries τ (ncDerivative (FormalLog.log G)) := by + rw [trace_log_derivative τ hτ (F*G) (by simp [hF,hG]),ncDerivative_mul, + inverse_product F G hF hG,add_mul,map_add, + trace_log_derivative τ hτ F hF,trace_log_derivative τ hτ G hG] + congr 1 + · simp only [mul_assoc] + rw [←mul_assoc G,PowerSeries.mul_invOfUnit G 1 hG,one_mul] + · rw [mul_assoc F,traceSeries_cyclic τ hτ] + simp only [mul_assoc] + rw [PowerSeries.invOfUnit_mul F 1 hF,mul_one] + ext n + cases n with + | zero=>simp only [map_add,coeff_traceSeries,coeff_zero_eq_constantCoeff,log_constant, + map_zero,add_zero] + | succ n=> + have HH:=congrArg (coeff n) H + simp only [map_add,coeff_traceSeries,coeff_ncDerivative,map_nsmul] at HH + have HHH : ((n+1:ℕ):ℚ) • τ (coeff (n+1) (FormalLog.log (F*G)))= + ((n+1:ℕ):ℚ) • (τ (coeff (n+1) (FormalLog.log F))+ + τ (coeff (n+1) (FormalLog.log G))) := by + simpa only [Nat.cast_smul_eq_nsmul,nsmul_add] using HH + have hnn : ((n+1:ℕ):ℚ)≠0 :=by positivity + have H4:=congrArg (fun x:K=>(((n+1:ℕ):ℚ)⁻¹) • x) HHH + simpa only [smul_smul,inv_mul_cancel₀ hnn,one_smul,map_add,coeff_traceSeries] using H4 +end +end ElementaryPositivity.FormalLog + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TruncatedChart.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TruncatedChart.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b6b0906d2804af41779c3b2399a1f792e9238bb --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TruncatedChart.lean @@ -0,0 +1,83 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.QuantumTorusChartCompletion +import OAI.Combinatorics.Chromatic.Walls.TruncatedFactorization +import OAI.Combinatorics.Chromatic.GradedAlgebra.KernelTraceLog + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesSplit +noncomputable section +variable {R M I : Type*} [CommRing R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) + +lemma strict_mul_through (V : M→Prop) (hV : ∀a b,V a→V b→V (a+b)) + (a b : PowerSeries (Torus v Ω)) (N : ℕ) + (ha : constantCoeff a=1) (hb : constantCoeff b=1) + (hsA : ∀n,n+1≤N→SupportedOn v Ω V (coeff (n+1) a)) + (hsB : ∀n,n+1≤N→SupportedOn v Ω V (coeff (n+1) b)) : + ∀n,n+1≤N→SupportedOn v Ω V (coeff (n+1) (a*b)) :=by + intro n hn + rw [coeff_mul_succ a b n ha hb] + apply SupportedOn.add v Ω ((hsA n hn).add v Ω (hsB n hn)) + apply SupportedOn.sum v Ω _ _ V + intro i hi + apply (hsA i.val (by omega)).mul v Ω hV + have he : n-i.val=(n-i.val-1)+1:=by omega + rw [he] + exact hsB (n-i.val-1) (by omega) + +lemma chart_three_truncated_unique (h : M→+ℝ) (f : CompletedPositive v Ω C) + (a b c : PowerSeries (Torus v Ω)) (N : ℕ) + (ha0 : constantCoeff a=1) (hb0 : constantCoeff b=1) (hc0 : constantCoeff c=1) + (he : a*b*c=f.val) + (ha : ∀n,n+1≤N→∀m,coeff (n+1) a m≠0→0rw [coeff_zero_eq_constantCoeff,hb0]; exact positiveProject_one v Ω h + | succ n=> + apply (Finsupp.filter_eq_zero_iff _ _).mpr + intro m hm + by_contra hh + have H:=hb n hn m hh + linarith + have hcP : ∀n≤N,positiveProject v Ω h (coeff n c)=0:=by + intro n hn + cases n with + | zero=>rw [coeff_zero_eq_constantCoeff,hc0]; exact positiveProject_one v Ω h + | succ n=> + apply (Finsupp.filter_eq_zero_iff _ _).mpr + intro m hm + by_contra hh + have H:=hc n hn m hh + linarith + have hbQ : ∀n,n+1≤N→zeroProject v Ω h (coeff (n+1) b)=coeff (n+1) b:=by + intro n hn + exact (Finsupp.filter_eq_self_iff _ _).mpr (hb n hn) + have hcQ : ∀n,n+1≤N→zeroProject v Ω h (coeff (n+1) c)=0:=by + intro n hn + apply (Finsupp.filter_eq_zero_iff _ _).mpr + intro m hm + by_contra hh + have H:=hc n hn m hh + linarith + exact three_truncated_unique (positiveProject v Ω h) (zeroProject v Ω h) + (supportedSubring v Ω (nonpositiveCone h)) (nonpositive_iff v Ω h) + f.val a b c N ha0 hb0 hc0 (fun n hn=>congrArg (coeff n) he) haP hbP hcP hbQ hcQ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TruncatedPrecisionClosure.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TruncatedPrecisionClosure.lean new file mode 100644 index 0000000000000000000000000000000000000000..92dc537afa6386e40bc1e24cc4561e91cd22a98c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/TruncatedPrecisionClosure.lean @@ -0,0 +1,117 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RootTruncation +import OAI.Combinatorics.Chromatic.Walls.HNTorusFactor +import OAI.Combinatorics.Chromatic.GradedAlgebra.SeriesApproximation +import OAI.Combinatorics.Chromatic.Walls.RootClosureFacts + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries RootTruncation LaurentPrecision Filter WallUnits +noncomputable section +variable {M I J : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M→+M→+ℤ) +abbrev RootClosedThrough (N : ℕ) (A : Set (PowerSeries (Torus v Ω))) + (F : PowerSeries (Torus v Ω)) : Prop := + InPrecisionClosure v Ω (RootTruncation.cut N '' A) (RootTruncation.cut N F) +lemma RootClosedThrough.congr {N : ℕ} {A : Set (PowerSeries (Torus v Ω))} + {F G : PowerSeries (Torus v Ω)} (hF : RootClosedThrough v Ω N A F) + (he : ∀n≤N,coeff n F=coeff n G) : RootClosedThrough v Ω N A G := by + change InPrecisionClosure v Ω _ _ at hF ⊢ + rw [←cut_congr he] + exact hF +lemma InPrecisionClosure.cut {A : Set (PowerSeries (Torus v Ω))} + {F : PowerSeries (Torus v Ω)} (hF : InPrecisionClosure v Ω A F) (N : ℕ) : + RootClosedThrough v Ω N A F := by + intro T + obtain ⟨G,hG,H⟩:=hF T + refine ⟨RootTruncation.cut N G,⟨G,hG,rfl⟩,?_⟩ + intro t ht + simp only [coeff_cut] + by_cases hn : t.1≤N + · simp only [hn,ite_true]; exact H t ht + · simp only [hn,ite_false]; exact agrees_refl _ _ +lemma rootClosedThrough_self {N : ℕ} {A : Set (PowerSeries (Torus v Ω))} + {F : PowerSeries (Torus v Ω)} (hF : F∈A) : RootClosedThrough v Ω N A F := + inPrecisionClosure_self v Ω ⟨F,hF,rfl⟩ +lemma RootClosedThrough.mono {N : ℕ} {A B : Set (PowerSeries (Torus v Ω))} + {F : PowerSeries (Torus v Ω)} (hF : RootClosedThrough v Ω N A F) (hAB : A⊆B) : + RootClosedThrough v Ω N B F := InPrecisionClosure.mono v Ω hF (Set.image_mono hAB) +variable {N : ℕ} {A : Set (PowerSeries (Torus v Ω))} {F : PowerSeries (Torus v Ω)} +lemma rootClosedThrough_approx_exists (hF : RootClosedThrough v Ω N A F) + (T : Finset (PrecisionTest (M:=M))) : + ∃G∈A,TestAgreement v Ω T (RootTruncation.cut N G) (RootTruncation.cut N F) := by + obtain ⟨G,⟨G',hG,rfl⟩,H⟩:=hF T + exact ⟨G',hG,H⟩ +def rootApprox (hF : RootClosedThrough v Ω N A F) + (T : Finset (PrecisionTest (M:=M))) : PowerSeries (Torus v Ω) := + Classical.choose (rootClosedThrough_approx_exists v Ω hF T) +lemma rootApprox_mem (hF : RootClosedThrough v Ω N A F) + (T : Finset (PrecisionTest (M:=M))) : rootApprox v Ω hF T∈A := + (Classical.choose_spec (rootClosedThrough_approx_exists v Ω hF T)).1 +lemma rootApprox_converges (hF : RootClosedThrough v Ω N A F) : + SeriesConverges v Ω (atTop : Filter (Finset (PrecisionTest (M:=M)))) + (fun T=>RootTruncation.cut N (rootApprox v Ω hF T)) (RootTruncation.cut N F) := by + classical + intro n m K + apply eventually_atTop.mpr + refine ⟨{(n,m,K)},fun T hT=>?_⟩ + exact (Classical.choose_spec (rootClosedThrough_approx_exists v Ω hF T)).2 + (n,m,K) (hT (by simp)) +lemma RootClosedThrough.of_converges (l : Filter J) [l.NeBot] + {f : J→PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l (fun j=>RootTruncation.cut N (f j)) (RootTruncation.cut N F)) + (hA : ∀ᶠj in l,RootClosedThrough v Ω N A (f j)) : RootClosedThrough v Ω N A F := + InPrecisionClosure.of_converges v Ω l hf hA +end + +section ZeroFactor +noncomputable section +open PowerSeries RootTruncation LaurentPrecision Filter WallUnits +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) +variable {N : ℕ} {A B : Set (PowerSeries (Torus LaurentRay.vUnit Ω))} +variable {F : PowerSeries (Torus LaurentRay.vUnit Ω)} +lemma RootClosedThrough.zeroFactor + (hF : RootClosedThrough LaurentRay.vUnit Ω N A F) + (hA : ∀G∈A,SeriesGraded LaurentRay.vUnit Ω C G) + (h : M→+ℝ) + (hB : ∀G∈A,InPrecisionClosure LaurentRay.vUnit Ω B + (PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) G)) : + RootClosedThrough LaurentRay.vUnit Ω N B + (PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) F) := by + let P:=positiveProject LaurentRay.vUnit Ω h + let Q:=zeroProject LaurentRay.vUnit Ω h + let g:=rootApprox LaurentRay.vUnit Ω hF + have hg:=rootApprox_converges LaurentRay.vUnit Ω hF + have hgg : ∀T,SeriesGraded LaurentRay.vUnit Ω C (RootTruncation.cut N (g T)):= + fun T=>(hA _ (rootApprox_mem LaurentRay.vUnit Ω hF T)).cut LaurentRay.vUnit Ω C N + have hFG : SeriesGraded LaurentRay.vUnit Ω C (RootTruncation.cut N F):=by + apply hF.graded Ω C + rintro G ⟨G',hG,rfl⟩ + exact (hA G' hG).cut LaurentRay.vUnit Ω C N + have H:=filter_factors_converge LaurentRay.vUnit Ω C Filter.atTop (fun m=>0h m=0) H.2 + (fun T n=>by + simpa only [PowerSeriesSplit.rightFactor,coeff_mk] using + (filter_pair_graded LaurentRay.vUnit Ω C (fun m=>0by + simpa only [PowerSeriesSplit.rightFactor,coeff_mk] using + (filter_pair_graded LaurentRay.vUnit Ω C (fun m=>0RootTruncation.cut N (PowerSeriesSplit.zeroFactor P Q (RootTruncation.cut N (g T)))) + (RootTruncation.cut N (PowerSeriesSplit.zeroFactor P Q (RootTruncation.cut N F))) at hc + simp only [cut_zeroFactor] at hc + apply RootClosedThrough.of_converges LaurentRay.vUnit Ω Filter.atTop hc + exact Eventually.of_forall (fun T=>(hB _ (rootApprox_mem LaurentRay.vUnit Ω hF T)).cut LaurentRay.vUnit Ω N) +end +end ZeroFactor +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitIndexEnergy.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitIndexEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..61627ffbf8dd1f4a0bbfc34a292202b72703cf3d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitIndexEnergy.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.WeakStrictUnitSelections + +namespace OAI + +section +section +namespace ElementaryPositivity.UnitSelections +open FiniteFunctionValues +noncomputable section + +def weight {n : ℕ} (f : Fin n → ℕ) : ℤ := ∑i,(f i:ℤ) + +lemma twice_staircase (n : ℕ) : 2*(∑i : Fin n,(i.val:ℤ))=(n:ℤ)*((n:ℤ)-1) := by + induction n with + | zero => simp + | succ n ih => + rw [Fin.sum_univ_castSucc] + simp only [Fin.val_castSucc,Fin.val_last,Nat.cast_add,Nat.cast_one] + nlinarith + +lemma staircase_weight (n : ℕ) (f : Weak n) : + 2*weight (staircaseEquiv n f).val=2*weight f.val+(n:ℤ)*((n:ℤ)-1) := by + change 2*(∑i : Fin n,((f.val i+i.val:ℕ):ℤ))=_ + simp only [Nat.cast_add,Finset.sum_add_distrib,mul_add,twice_staircase,weight] + +abbrev UnitIndex (a n : ℕ) := {f : Fin n → ℕ // if a=0 then StrictMono f else Monotone f} + +def weakUnitEquiv (a n : ℕ) : Weak n ≃ UnitIndex a n := by + classical + by_cases h : a=0 + · exact + { toFun := fun f=>⟨(staircaseEquiv n f).val,by simpa only [ite_eq_left h] using (staircaseEquiv n f).property⟩ + invFun := fun g=>(staircaseEquiv n).symm ⟨g.val,by simpa only [ite_eq_left h] using g.property⟩ + left_inv := fun f=>(staircaseEquiv n).symm_apply_apply f + right_inv := fun g=>Subtype.ext (congrArg (fun q : Strict n=>q.val) ((staircaseEquiv n).apply_symm_apply + ⟨g.val,by simpa only [ite_eq_left h] using g.property⟩)) } + · exact + { toFun := fun f=>⟨f.val,by simpa only [ite_eq_right h] using f.property⟩ + invFun := fun g=>⟨g.val,by simpa only [ite_eq_right h] using g.property⟩ + left_inv := fun _=>rfl + right_inv := fun _=>rfl } + +def unitWeight (a n : ℕ) (q : UnitIndex a n) : ℤ := weight q.val + +lemma weakUnit_weight (a n : ℕ) (ha : a≤1) (f : Weak n) : + 2*unitWeight a n (weakUnitEquiv a n f)= + 2*weight f.val+(1-(a:ℤ))*(n:ℤ)*((n:ℤ)-1) := by + by_cases h : a=0 + · subst a + change 2*weight (staircaseEquiv n f).val=2*weight f.val+(1-(0:ℤ))*(n:ℤ)*((n:ℤ)-1) + simpa only [sub_zero,one_mul] using staircase_weight n f + · have he : a=1 := by omega + subst a + change 2*weight f.val=2*weight f.val+(1-(1:ℤ))*(n:ℤ)*((n:ℤ)-1) + simp + +lemma weakSym_weight (n : ℕ) (f : Weak n) : + (((weakSymEquiv n f).val).map (Nat.cast:ℕ→ℤ)).sum=weight f.val := by + change ((values f.val).map (Nat.cast:ℕ→ℤ)).sum=weight f.val + simp only [values,Multiset.map_map,weight] + rfl +end +end ElementaryPositivity.UnitSelections +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitSelectionLaurent.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitSelectionLaurent.lean new file mode 100644 index 0000000000000000000000000000000000000000..634c154e6108640833158e2419f00094b3dab619 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitSelectionLaurent.lean @@ -0,0 +1,77 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.EnergyLaurentSeries +import OAI.Combinatorics.Chromatic.QuantumTorus.WeakUnitRecursion + +namespace OAI + +section +section +namespace ElementaryPositivity.UnitSelections +open EnergyLaurent +open scoped LaurentSeries +noncomputable section + +def weakEnergy (n : ℕ) (k : ℤ) (f : Weak n) : ℤ := (n:ℤ)*k-2*weight f.val + +lemma weakAdmissible (n : ℕ) (k : ℤ) : Admissible (weakEnergy n k) := by + constructor + · refine ⟨n*k,?_⟩ + intro f + have hh : 0≤weight f.val:=Finset.sum_nonneg (fun i _=>Int.natCast_nonneg _) + unfold weakEnergy + linarith + · intro E + let U:=((n:ℤ)*k-E).toNat + let F : {f : Weak n // weakEnergy n k f=E} → (Fin n → Fin (U+1)) := fun f i=> + ⟨f.val.val i,by + have hi : (f.val.val i:ℤ)≤weight f.val.val := + Finset.single_le_sum (fun j _=>Int.natCast_nonneg (f.val.val j)) (Finset.mem_univ i) + have hn : 0≤weight f.val.val := + Finset.sum_nonneg (fun j _=>Int.natCast_nonneg (f.val.val j)) + have he:=f.property + unfold weakEnergy at he + dsimp only [U] + omega⟩ + apply Finite.of_injective F + intro f g h + apply Subtype.ext + apply Subtype.ext + funext i + exact congrArg Fin.val (congrFun h i) + +def weakSeries (n : ℕ) (k : ℤ) : LaurentSeries ℚ := series (weakEnergy n k) (weakAdmissible n k) + +lemma weakSeries_zero (k : ℤ) : weakSeries 0 k=1 := by + let f : Weak 0:=⟨fun i=>Fin.elim0 i,by intro i; exact Fin.elim0 i⟩ + let : Unique (Weak 0):=⟨⟨f⟩,fun g=>Subsingleton.elim _ _⟩ + change (family (weakEnergy 0 k) (weakAdmissible 0 k)).hsum=1 + rw [HahnSeries.SummableFamily.hsum_unique] + change HahnSeries.single (-(weakEnergy 0 k f)) (1:ℚ)=1 + simp only [weakEnergy,weight,Finset.univ_eq_empty,Finset.sum_empty,Int.natCast_zero, + zero_mul,mul_zero,sub_self,neg_zero,HahnSeries.single_zero_one] + +lemma weakSeries_recursion (n : ℕ) (k : ℤ) : + weakSeries (n+1) k=weakSeries n k*HahnSeries.single (-k) (1:ℚ)+ + weakSeries (n+1) k*HahnSeries.single (2*(n+1:ℤ)) (1:ℚ) := by + let he:=admissible_shift (weakAdmissible n k) k + let hf:=admissible_shift (weakAdmissible (n+1) k) (-2*(n+1:ℤ)) + have hh:=series_equiv (admissible_sum he hf) (weakAdmissible (n+1) k) + (weakSplit n).symm (fun p=>by + simpa only [weakEnergy,sub_eq_add_neg,neg_mul] using weakSplit_inv_energy n k p) + rw [series_sum he hf,series_shift (weakAdmissible n k),series_shift (weakAdmissible (n+1) k)] at hh + simpa only [weakSeries,neg_mul,neg_neg] using hh.symm + +lemma weakSeries_recursion_q (n : ℕ) (k : ℤ) : + weakSeries (n+1) k*(1-(HahnSeries.single 2 (1:ℚ))^(n+1))= + HahnSeries.single (-k) (1:ℚ)*weakSeries n k := by + have hh:=weakSeries_recursion n k + rw [HahnSeries.single_pow,one_pow] + have hn : (n+1) • (2:ℤ)=2*(n+1:ℤ) := by simp only [nsmul_eq_mul,Nat.cast_add,Nat.cast_one]; ring + rw [hn] + linear_combination hh +end +end ElementaryPositivity.UnitSelections +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitalProduct.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitalProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..9842ea39ec6eaabac457ebe5d3633cc2d3aca2a4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/UnitalProduct.lean @@ -0,0 +1,122 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.Product + +namespace OAI + +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] + +lemma OnSlopeOrZero.mass_eq {c η : I → ℝ} (hc : ∀ i,0 θ*mass c d) : + d≠0 ∧ e≠0 ∧ slope c η d>slope c η (d+e) := by + have hne : d+e≠0 := by + intro hz + have hd : d=0 := by + funext i + have hi:=congrFun hz i + simp only [Pi.add_apply,Pi.zero_apply] at hi + change d i=0 + omega + simp only [hd,mass_zero,mul_zero,lt_self_iff_false] at h + have hθ := hs.resolve_left hne + exact high_mass_destabilizes c η hc d e (by simpa only [hθ] using h) + +theorem offSlope_destabilizes_onSlope (c η : I → ℝ) (hc : ∀ i,0slope c η (d₁+e₁)) ∨ + (d₂≠0 ∧ e₂≠0 ∧ slope c η d₂>slope c η (d₂+e₂)) := by + by_cases h₁ : mass η d₁>θ*mass c d₁ + · exact Or.inl (high_mass_destabilizes_onSlope c η hc θ d₁ e₁ ht₁ h₁) + by_cases h₂ : mass η d₂>θ*mass c d₂ + · exact Or.inr (high_mass_destabilizes_onSlope c η hc θ d₂ e₂ ht₂ h₂) + have hsrc:=hs.mass_eq hc + have htar₁:=ht₁.mass_eq hc + have htar₂:=ht₂.mass_eq hc + simp only [mass_add] at hsrc htar₁ htar₂ + have hd₁ : mass η d₁=θ*mass c d₁ := by nlinarith + have hd₂ : mass η d₂=θ*mass c d₂ := by nlinarith + have he₁ : mass η e₁=θ*mass c e₁ := by nlinarith + have he₂ : mass η e₂=θ*mass c e₂ := by nlinarith + exact (hoff ⟨onSlopeOrZero_of_mass c η hc θ d₁ hd₁, + onSlopeOrZero_of_mass c η hc θ e₁ he₁,onSlopeOrZero_of_mass c η hc θ d₂ hd₂, + onSlopeOrZero_of_mass c η hc θ e₂ he₂⟩).elim +end ElementaryPositivity.SlopeArithmetic + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open ElementaryPositivity.SlopeArithmetic +open scoped TensorProduct +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + +lemma quotient_cellTransfer_offSlope_unital (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(u i).val) (shapeComplement u) (fun i=>(v i).val) (shapeComplement v)) : + quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v)=0 := by + unfold gridShapeTensor + apply quotientTensor_cast_zero + by_cases hsum : (fun i=>(u i).val)+(fun i=>(v i).val)=d + · apply quotient_cellTransfer_offSlope_unital a c η hc θ + · rwa [(shape_add_complement u).trans (realization_card R)] + · rwa [(shape_add_complement v).trans (realization_card T)] + · rwa [hsum] + · exact hoff + · rw [fourGridPolynomial_zero_of_source_mismatch a f g _ _ _ _ hsum,map_zero,map_zero] + +omit [(index : I) → Fintype (A index)] in +theorem quotient_gridTensor_unital_support (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(u i).val) (shapeComplement u) (fun i=>(v i).val) (shapeComplement v) + then quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v) else 0 := by + classical + simp only [gridTensor,map_sum] + apply Finset.sum_congr rfl + intro u _ + apply Finset.sum_congr rfl + intro v _ + split_ifs with hon + · rfl + · exact quotient_gridShapeTensor_offSlope_unital a c η hc θ f g p R T u v hα hβ hd hon +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/WeightedPushTwist.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/WeightedPushTwist.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d4f04d3de6e18472d305616aff833c29486dfce --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/WeightedPushTwist.lean @@ -0,0 +1,66 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.QuantumTorusTrace +import OAI.Combinatorics.Chromatic.GradedAlgebra.HNSeries + +namespace OAI + +section +namespace ElementaryPositivity.WeightedTorusSeries +open QuantumTorus RawShuffle PowerSeries +noncomputable section +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (w : I → ℕ) [Fact (∀i,0f d*↑(v^(2*Ω (P d) m))) := by + classical + apply PowerSeries.ext + intro n + rw [coeff_mul_C,coeff_C_mul] + simp only [push,coeff_mk,pushCoeff] + rw [torus_sum_mul,torus_mul_sum] + apply Finset.sum_congr rfl + intro d hd + simp only [Torus.X,Torus.monomial_mul_monomial,mul_one,one_mul] + rw [add_comm (P d.val) m,alternating_skew Ω hΩ m (P d.val)] + congr 1 + rw [mul_assoc,←Units.val_mul,←zpow_add] + congr 2 + ring_nf + +lemma convolution_of_isotropic_support (f g : (I→ℕ) → R) + (h : ∀d e,f d≠0 → g e≠0 → Ω (P d) (P e)=0) (d : I→ℕ) : + convolution v Ω P f g d=∑s : DimensionSplit d,f s.left*g s.right := by + classical + apply Finset.sum_congr rfl + intro s hs + by_cases hf : f s.left=0 + · simp only [hf,zero_mul] + by_cases hg : g s.right=0 + · simp only [hg,mul_zero,zero_mul] + rw [h _ _ hf hg,zpow_zero,Units.val_one,mul_one] + +lemma push_adjoint_of_convolution (hΩ : ∀m,Ω m m=0) (m : M) + (f q : (I→ℕ) → R) (hf : f 0=1) + (hq : (fun d=>f d*↑(v^(2*Ω (P d) m)))=convolution v Ω P q f) : + push w v Ω P f*C (Torus.X v Ω m)* + PowerSeries.invOfUnit (push w v Ω P f) 1= + C (Torus.X v Ω m)*push w v Ω P q := by + rw [push_twist w v Ω P hΩ, hq,push_convolution,mul_assoc] + have H : push w v Ω P f*PowerSeries.invOfUnit (push w v Ω P f) 1=1 := by + exact PowerSeries.mul_invOfUnit _ 1 (push_constant w v Ω P f hf) + rw [mul_assoc,H,mul_one] + +end +end ElementaryPositivity.WeightedTorusSeries + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/WeightedTorusSeries.lean b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/WeightedTorusSeries.lean new file mode 100644 index 0000000000000000000000000000000000000000..5efeb91323f6916bdc6f9f8b4030bbb49bc350d7 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/GradedAlgebra/WeightedTorusSeries.lean @@ -0,0 +1,143 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus +import OAI.Combinatorics.Chromatic.Shuffle.DimensionGrid + +namespace OAI + +section +namespace ElementaryPositivity.WeightedTorusSeries +open ElementaryPositivity.RawShuffle ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (w : I → ℕ) [hw : Fact (∀i,0Nat.zero_le (d j*w j)) (Finset.mem_univ i)) + +abbrev Slice (n : ℕ) := {d : I → ℕ // weight w d=n} +instance sliceFinite (n : ℕ) : Finite (Slice w n) := + Finite.of_injective (fun d : Slice w n=>fun i=>(⟨d.val i,by + have H:=coord_le_weight w d.val i + rw [d.property] at H + omega⟩ : Fin (n+1))) (fun x y h=>Subtype.ext (funext (fun i=>congrArg Fin.val (congrArg (fun f=>f i) h)))) + +noncomputable instance sliceFintype (n : ℕ) : Fintype (Slice w n) := Fintype.ofFinite _ + +omit [Fintype I] [DecidableEq I] in +private lemma split_heq {d e : I → ℕ} {s : DimensionSplit d} {t : DimensionSplit e} + (H : d=e) (hs : s.left=t.left) : HEq s t := by + cases H + exact heq_of_eq (DimensionSplit.ext hs) + +def splitSliceEquiv (n : ℕ) : + (Σ d : Slice w n,DimensionSplit d.val) ≃ + {p : (I→ℕ)×(I→ℕ) // weight w p.1+weight w p.2=n} where + toFun x:=⟨(x.2.left,x.2.right),by rw [←map_add,DimensionSplit.left_add_right]; exact x.1.property⟩ + invFun p:=⟨⟨p.val.1+p.val.2,by rw [map_add,p.property]⟩,DimensionSplit.ofPair _ _ rfl⟩ + left_inv x:=by + apply Sigma.ext (Subtype.ext (DimensionSplit.left_add_right x.2)) + exact split_heq (DimensionSplit.left_add_right x.2) rfl + right_inv p:=by apply Subtype.ext; simp + +def pairSliceEquiv (n : ℕ) : + (Σ k : Fin (n+1),Slice w k.val × Slice w (n-k.val)) ≃ + {p : (I→ℕ)×(I→ℕ) // weight w p.1+weight w p.2=n} where + toFun x:=⟨(x.2.1.val,x.2.2.val),by rw [x.2.1.property,x.2.2.property]; omega⟩ + invFun p:=⟨⟨weight w p.val.1,by have H:=p.property; omega⟩,⟨p.val.1,rfl⟩, + ⟨p.val.2,by dsimp only; have H:=p.property; omega⟩⟩ + left_inv x:=by + rcases x with ⟨⟨k,hk⟩,⟨d,hd⟩,⟨e,he⟩⟩ + dsimp only at hd he ⊢ + subst k + rfl + right_inv p:=rfl + +lemma sum_split {A : Type*} [AddCommMonoid A] (n : ℕ) (H : (I→ℕ) → (I→ℕ) → A) : + (∑d : Slice w n,∑s : DimensionSplit d.val,H s.left s.right)= + ∑k : Fin (n+1),∑d : Slice w k.val,∑e : Slice w (n-k.val),H d.val e.val := by + classical + let E := (splitSliceEquiv w n).trans (pairSliceEquiv w n).symm + calc + _ = ∑x : (Σ d : Slice w n,DimensionSplit d.val),H x.2.left x.2.right := + (Fintype.sum_sigma (fun x : (Σ d : Slice w n,DimensionSplit d.val)=>H x.2.left x.2.right)).symm + _ = ∑y : (Σ k : Fin (n+1),Slice w k.val × Slice w (n-k.val)),H y.2.1.val y.2.2.val := + Fintype.sum_equiv E _ _ (fun _=>rfl) + _ = _ := by + rw [Fintype.sum_sigma] + apply Finset.sum_congr rfl + intro k hk + exact Fintype.sum_prod_type _ + +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (P : (I → ℕ) →+ M) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def pushCoeff (f : (I→ℕ) → R) (n : ℕ) : Torus v Ω := + ∑d : Slice w n,Torus.monomial v Ω (P d.val) (f d.val) +def push (f : (I→ℕ) → R) : PowerSeries (Torus v Ω) := mk (pushCoeff w v Ω P f) + +def convolution (f g : (I→ℕ) → R) (d : I→ℕ) : R := + ∑s : DimensionSplit d,f s.left*g s.right*↑(v^(Ω (P s.left) (P s.right))) + +lemma monomial_sum {A : Type*} (s : Finset A) (m : M) (f : A → R) : + Torus.monomial v Ω m (∑i∈s,f i)=∑i∈s,Torus.monomial v Ω m (f i) := by + exact map_sum (Finsupp.singleAddHom m) f s + +lemma torus_sum_mul {A : Type*} (s : Finset A) (f : A → Torus v Ω) (g : Torus v Ω) : + (∑i∈s,f i)*g=∑i∈s,f i*g := by + classical + induction s using Finset.induction_on with + | empty => simp only [Finset.sum_empty,Torus.zero_mul] + | @insert a s ha ih => simp only [Finset.sum_insert ha,Torus.add_mul,ih] + +lemma torus_mul_sum {A : Type*} (s : Finset A) (f : A → Torus v Ω) (g : Torus v Ω) : + g*(∑i∈s,f i)=∑i∈s,g*f i := by + classical + induction s using Finset.induction_on with + | empty => simp only [Finset.sum_empty,Torus.mul_zero] + | @insert a s ha ih => simp only [Finset.sum_insert ha,Torus.mul_add,ih] + +lemma pushCoeff_convolution (f g : (I→ℕ) → R) (n : ℕ) : + pushCoeff w v Ω P (convolution v Ω P f g) n= + ∑k : Fin (n+1),pushCoeff w v Ω P f k.val*pushCoeff w v Ω P g (n-k.val) := by + classical + simp only [pushCoeff,convolution,monomial_sum,torus_sum_mul,torus_mul_sum, + Torus.monomial_mul_monomial] + have H:=sum_split w n (fun d e=>Torus.monomial v Ω (P d+P e) + (f d*g e*↑(v^(Ω (P d) (P e))))) + convert H using 1 + · apply Finset.sum_congr rfl + intro d hd + apply Finset.sum_congr rfl + intro s hs + rw [←map_add,DimensionSplit.left_add_right] + · apply Finset.sum_congr rfl + intro k hk + exact Finset.sum_comm + +lemma push_convolution (f g : (I→ℕ) → R) : + push w v Ω P (convolution v Ω P f g)=push w v Ω P f*push w v Ω P g := by + apply PowerSeries.ext + intro n + simp only [push,coeff_mk,coeff_mul] + rw [Finset.Nat.sum_antidiagonal_eq_sum_range_succ_mk,←Fin.sum_univ_eq_sum_range] + exact pushCoeff_convolution w v Ω P f g n + +end +end ElementaryPositivity.WeightedTorusSeries + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/AnchorEmptyMask.lean b/lean/OAI/Combinatorics/Chromatic/Histories/AnchorEmptyMask.lean new file mode 100644 index 0000000000000000000000000000000000000000..d421b3c41187aae64f9831c0c7c04046a2ad68ea --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/AnchorEmptyMask.lean @@ -0,0 +1,91 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Histories.PacketSortedWords + +namespace OAI + +section +namespace ElementaryPositivity.Packets +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} {A:Type*} [Fintype A] [LinearOrder A] + +omit [Fintype A] [LinearOrder A] in +lemma wordCount_multiset (w:Fin n → A) : (wordCount w).toMultiset=(List.ofFn w:Multiset A) := by + induction n with + | zero=>simp [wordCount] + | succ n ih=> + simp only [wordCount,Fin.sum_univ_succ,map_add,Finsupp.toMultiset_single,one_nsmul,List.ofFn_succ] + rw [←wordCount,ih] + rfl + +omit [Fintype A] in +lemma empty_ascent_iff (w:Fin n → A) : ascentMask (·<·) w=∅ ↔ Antitone w := by + cases n with + | zero=>simp only [Finset.eq_empty_iff_forall_notMem]; exact ⟨fun _ i=>Fin.elim0 i,fun _ t=>Fin.elim0 t⟩ + | succ N=> + rw [Fin.antitone_iff_succ_le] + constructor + · intro h i + by_contra hn + let t:Fin ((N+1)-1):=⟨i.val,by omega⟩ + have ht:t∈ascentMask (·<·) w:=by + apply (mem_ascentMask _ _ _).mpr + exact lt_of_not_ge hn + rw [h] at ht + exact Finset.notMem_empty t ht + · intro h + apply Finset.eq_empty_iff_forall_notMem.mpr + intro t ht + have H:=h ⟨t.val,by omega⟩ + exact (not_lt_of_ge H) ((mem_ascentMask _ _ _).mp ht) + +omit [Fintype A] in +lemma antitone_word_unique (w v:Fin n → A) (hw:Antitone w) (hv:Antitone v) + (hc:wordCount w=wordCount v) : w=v := by + have hm:(List.ofFn w:Multiset A)=(List.ofFn v:Multiset A):=by rw [←wordCount_multiset,←wordCount_multiset,hc] + have hp:(List.ofFn w).Perm (List.ofFn v):=Quotient.exact hm + have hl:List.ofFn w=List.ofFn v:=List.Perm.eq_of_pairwise' (r:=fun a b:A=>a≥b) + (List.pairwise_ofFn.mpr (fun i j hij=>hw hij.le)) + (List.pairwise_ofFn.mpr (fun i j hij=>hv hij.le)) hp + exact List.ofFn_injective hl + +omit [Fintype A] in +lemma exists_antitone_word (μ:A →₀ ℕ) (hμ:μ.degree=n) : + ∃w:Fin n → A,wordCount w=μ ∧ Antitone w := by + let l:=μ.toMultiset.sort (·≥·) + have hl:l.length=n:=by + rw [Multiset.length_sort,Finsupp.card_toMultiset] + exact hμ + have H:∃w:Fin l.length → A,wordCount w=μ ∧ Antitone w:=by + refine ⟨l.get,?_,?_⟩ + · apply Finsupp.orderIsoMultiset.injective + change (wordCount l.get).toMultiset=μ.toMultiset + rw [wordCount_multiset,List.ofFn_get] + exact Multiset.sort_eq _ _ + · intro i j hij + rcases lt_or_eq_of_le hij with hit|rfl + · exact (List.pairwise_iff_get.mp (Multiset.pairwise_sort μ.toMultiset (·≥·))) i j hit + · exact le_rfl + exact hl ▸ H + +abbrev EmptyAnchor (μ:A →₀ ℕ):={w:AnchorWord (n:=n) μ // ascentMask (·<·) w.val=∅} + +def emptyAnchorEquiv (μ:A →₀ ℕ) (hμ:μ.degree=n) : EmptyAnchor (n:=n) μ ≃ PUnit where + toFun _:=PUnit.unit + invFun _:=⟨⟨(exists_antitone_word μ hμ).choose,(exists_antitone_word μ hμ).choose_spec.1⟩, + (empty_ascent_iff _).mpr (exists_antitone_word μ hμ).choose_spec.2⟩ + left_inv w:=by + apply Subtype.ext + apply Subtype.ext + apply antitone_word_unique + · exact (exists_antitone_word μ hμ).choose_spec.2 + · exact (empty_ascent_iff _).mp w.property + · exact (exists_antitone_word μ hμ).choose_spec.1.trans w.val.property.symm + right_inv _:=rfl +end +end ElementaryPositivity.Packets + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/ColorBlockEnergy.lean b/lean/OAI/Combinatorics/Chromatic/Histories/ColorBlockEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..14392578ef41d2748560af1fa042dc03472d8823 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/ColorBlockEnergy.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.OrderedIndependentProduct +import OAI.Combinatorics.Chromatic.Walls.SquarefreeBlocks + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +open Classical +noncomputable section +variable {M V:Type*} [AddCommGroup M] [Fintype V] [DecidableEq V] +variable (Ω:M →+ M →+ ℤ) (u:V → M) +variable {n r:ℕ} (b:Fin n ↪ V) (κ:Fin n → Fin r) + +omit [Fintype V] [DecidableEq V] in +lemma wordEnergy_blocks : + wordEnergy Ω (blockLabels u (SquarefreeBlocks.blocks b κ))= + ∑i:Fin n,∑j:Fin n,if κ i<κ j then Ω (u (b i)) (u (b j)) else 0 := by + have hb:∀c d:Fin r,Ω (blockLabels u (SquarefreeBlocks.blocks b κ) c) + (blockLabels u (SquarefreeBlocks.blocks b κ) d)= + ∑i∈Finset.univ.filter (fun i=>κ i=c),∑j∈Finset.univ.filter (fun j=>κ j=d),Ω (u (b i)) (u (b j)) := by + intro c d + simp only [blockLabels,SquarefreeBlocks.blocks,Finset.sum_map,map_sum,AddMonoidHom.finsetSum_apply] + rw [Finset.sum_comm] + rw [wordEnergy_eq_pairs] + simp only [hb] + calc + (∑c:Fin r,∑d:Fin r,if cκ i=c),∑j∈Finset.univ.filter (fun j=>κ j=d),Ω (u (b i)) (u (b j)) else 0)= + ∑c:Fin r,∑d:Fin r,∑i:Fin n,∑j:Fin n, + if κ i=c ∧ κ j=d ∧ c simp [hh] + · simp [h] + _ = ∑i:Fin n,∑j:Fin n,∑c:Fin r,∑d:Fin r, + if κ i=c ∧ κ j=d ∧ c exact ⟨1,one_ne_zero,by simp⟩ + | @cons i l m hp ih => + by_cases hl : l=[] + · subst l + have hm : m=[] := List.nil_perm.mp hp + subst m + exact ⟨1,one_ne_zero,by simp⟩ + obtain ⟨r,hr,hd⟩ := ih + refine ⟨r,hr,?_⟩ + have hh := wordLengthFiltration_mul b (wordLengthFiltration_letter b i) hd + have he : 1+(l.length-1)=(i::l).length-1 := by + have hn := List.length_pos_iff.mpr hl + simp only [List.length_cons] + omega + rw [he] at hh + simpa only [wordProduct_cons,mul_sub,Algebra.mul_smul_comm] using hh + | swap i j l => + refine ⟨ε j i,hε j i,?_⟩ + have hh := wordLengthFiltration_mul b (hcomm j i) (wordLengthFiltration_word b l l.length le_rfl) + have he : 1+l.length=(j::i::l).length-1 := by simp; omega + rw [he] at hh + simpa only [wordProduct_cons,sub_mul,Algebra.smul_mul_assoc,mul_assoc] using hh + | @trans l m n hlm hmn ihl ihm => + obtain ⟨r,hr,hdl⟩ := ihl + obtain ⟨s,hs,hdm⟩ := ihm + refine ⟨r*s,mul_ne_zero hr hs,?_⟩ + rw [←hlm.length_eq] at hdm + have hh := (wordLengthFiltration b (l.length-1)).add_mem hdl + ((wordLengthFiltration b (l.length-1)).smul_mem r hdm) + simpa only [smul_sub,smul_smul,sub_add_sub_cancel] using hh + +section Ordered +variable [LinearOrder J] + +def ColorAdmissible (l : List J) : Prop := + l.Pairwise (fun i j=>i≤j ∧ (i=j → ε i i=1)) + +lemma colorAdmissible_sorted {l : List J} (h : ColorAdmissible ε l) : l.Pairwise (· ≤ ·) := + h.imp (fun h=>h.1) + +lemma sorted_not_colorAdmissible {l : List J} (hl : l.Pairwise (· ≤ ·)) + (hn : ¬ColorAdmissible ε l) : ∃ i t,ε i i ≠ 1 ∧ l.Perm (i::i::t) := by + induction l with + | nil => exact (hn (by simp [ColorAdmissible])).elim + | cons j l ih => + have hlc := List.pairwise_cons.mp hl + by_cases ht : ColorAdmissible ε l + · have hj : ¬∀ i∈l,j ≤ i ∧ (j=i → ε j j=1) := by + intro hh + exact hn (List.pairwise_cons.mpr ⟨hh,ht⟩) + obtain ⟨i,hi⟩ := not_forall.mp hj + obtain ⟨hi,hbad⟩ := Classical.not_imp.mp hi + have heq : j=i := by + by_contra hne + exact hbad ⟨hlc.1 i hi,fun h=>False.elim (hne h)⟩ + subst i + have he : ε j j ≠ 1 := fun h=>hbad ⟨le_rfl,fun _=>h⟩ + obtain ⟨u,v,rfl⟩ := List.mem_iff_append.mp hi + exact ⟨j,u++v,he,List.Perm.cons j List.perm_middle⟩ + · obtain ⟨i,t,he,hp⟩ := ih hlc.2 ht + refine ⟨i,j::t,he,?_⟩ + exact (hp.cons j).trans ((List.Perm.swap i j (i::t)).trans + (List.Perm.cons i (List.Perm.swap i j t))) + +noncomputable def colorWordSpan : Submodule ℚ A := + Submodule.span ℚ {x | ∃ l : List J,ColorAdmissible ε l ∧ wordProduct b l=x} + +lemma colorWordSpan_admissible (l : List J) (hl : ColorAdmissible ε l) : + wordProduct b l ∈ colorWordSpan b ε := Submodule.subset_span ⟨l,hl,rfl⟩ + +theorem colorWordSpan_word + (hε : ∀ i j,ε i j ≠ 0) + (hcomm : ∀ i j,b i*b j-ε i j • (b j*b i) ∈ wordLengthFiltration b 1) + (hsquare : ∀ i,ε i i ≠ 1 → b i*b i ∈ wordLengthFiltration b 1) + (l : List J) : wordProduct b l ∈ colorWordSpan b ε := by + have hmain : ∀ n,∀ l : List J,l.length=n → wordProduct b l ∈ colorWordSpan b ε := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro l hl + by_cases hn : n=0 + · have hnil : l=[] := List.length_eq_zero_iff.mp (hl.trans hn) + rw [hnil] + exact colorWordSpan_admissible b ε [] (by simp [ColorAdmissible]) + have hlow : wordLengthFiltration b (n-1) ≤ colorWordSpan b ε := by + apply Submodule.span_le.mpr + rintro x ⟨t,ht,rfl⟩ + exact ih t.length (by omega) t rfl + let m := l.insertionSort (· ≤ ·) + have hm : m.Pairwise (· ≤ ·) := List.pairwise_insertionSort _ _ + have hpm : l.Perm m := (List.perm_insertionSort _ l).symm + have htransfer : ∀ t : List J,l.Perm t → wordProduct b t ∈ colorWordSpan b ε → + wordProduct b l ∈ colorWordSpan b ε := by + intro t hp ht + obtain ⟨r,hr,hd⟩ := wordProduct_perm_mod_lower b ε hε hcomm hp + rw [hl] at hd + have hh := (colorWordSpan b ε).add_mem (hlow hd) ((colorWordSpan b ε).smul_mem r ht) + simpa only [sub_add_cancel] using hh + by_cases ha : ColorAdmissible ε m + · exact htransfer m hpm (colorWordSpan_admissible b ε m ha) + · obtain ⟨i,t,hi,hpt⟩ := sorted_not_colorAdmissible ε hm ha + apply htransfer (i::i::t) (hpm.trans hpt) + have hh := wordLengthFiltration_mul b (hsquare i hi) (wordLengthFiltration_word b t t.length le_rfl) + have hlen : 1+t.length=n-1 := by + have he := (hpm.trans hpt).length_eq + simp only [List.length_cons] at he + omega + rw [hlen] at hh + apply hlow + simpa only [wordProduct_cons,mul_assoc] using hh + exact hmain l.length l rfl + +lemma colorWordSpan_top + (hε : ∀ i j,ε i j ≠ 0) + (hcomm : ∀ i j,b i*b j-ε i j • (b j*b i) ∈ wordLengthFiltration b 1) + (hsquare : ∀ i,ε i i ≠ 1 → b i*b i ∈ wordLengthFiltration b 1) + (hgen : Algebra.adjoin ℚ (Set.range b)=⊤) : colorWordSpan b ε=⊤ := by + apply top_unique + have ha := adjoin_le_span_words b + rw [hgen] at ha + apply le_trans ha + apply Submodule.span_le.mpr + rintro x ⟨l,rfl⟩ + exact colorWordSpan_word b ε hε hcomm hsquare l + +end Ordered +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/CommonHistoryLeaves.lean b/lean/OAI/Combinatorics/Chromatic/Histories/CommonHistoryLeaves.lean new file mode 100644 index 0000000000000000000000000000000000000000..adc1a1fdb4df29d1756f94ba8346c97025e701b5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/CommonHistoryLeaves.lean @@ -0,0 +1,160 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogenizedPolynomialSection +import OAI.Combinatorics.Chromatic.Histories.LocalHistoryFormula + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus.LocalHistoryFormula +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit LaurentPositive WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] + +def Leaf : LocalHistoryFormula M E → Type + | .zero=>Empty + | .stop _ _=>Unit + | .add p q=>Sum (Leaf p) (Leaf q) + | .jump _ _ _ _ p=>Leaf p + +instance leafFintype (p:LocalHistoryFormula M E) : Fintype p.Leaf := by + induction p with + | zero=>exact inferInstanceAs (Fintype Empty) + | stop _ _=>exact inferInstanceAs (Fintype Unit) + | add p q ihp ihq=>letI:=ihp; letI:=ihq; exact inferInstanceAs (Fintype (Sum p.Leaf q.Leaf)) + | jump _ _ _ _ p ih=>exact ih + +def leafDegree : (p:LocalHistoryFormula M E) → p.Leaf → ℕ + | .zero,l=>nomatch l + | .stop j _,_=>j + | .add p _,.inl l=>leafDegree p l + | .add _ q,.inr l=>leafDegree q l + | .jump _ _ _ _ p,l=>leafDegree p l + +def leafExponent : (p:LocalHistoryFormula M E) → p.Leaf → M + | .zero,l=>nomatch l + | .stop _ m,_=>m + | .add p _,.inl l=>leafExponent p l + | .add _ q,.inr l=>leafExponent q l + | .jump _ _ _ _ p,l=>leafExponent p l + +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) (e:M →+ E) +variable (F:CompletedPositive LaurentRay.vUnit Ω C) +def leafWeight : (p:LocalHistoryFormula M E) → p.Leaf → LaurentSeries ℚ + | .zero,l=>nomatch l + | .stop _ _,_=>1 + | .add p _,.inl l=>leafWeight p l + | .add _ q,.inr l=>leafWeight q l + | .jump d m r t p,l=>monomialJump Ω (t.operator Ω C e F) d m r*leafWeight p l + +lemma leafWeight_positive (p:LocalHistoryFormula M E) (hp:p.Positive Ω C e F) (l:p.Leaf) : + LaurentPositive.Positive (leafWeight Ω C e F p l) := by + induction p with + | zero=>exact l.elim + | stop j m=>exact positive_one + | add p q ihp ihq=>cases l with + | inl l=>exact ihp hp.1 l + | inr l=>exact ihq hp.2 l + | jump d m r t p ih=>exact hp.1.mul (ih hp.2 l) + +lemma leafBound (b:M) (N:ℕ) (p:LocalHistoryFormula M E) (hp:p.Bounded C b N) (l:p.Leaf) : + p.leafDegree l≤N ∧ HasRootDegree C (p.leafDegree l) (p.leafExponent l-b) := by + induction p generalizing N with + | zero=>exact l.elim + | stop j m=>exact hp + | add p q ihp ihq=>cases l with + | inl l=>exact ihp N hp.1 l + | inr l=>exact ihq N hp.2 l + | jump d m r t p ih=> + obtain ⟨hd,j,hj,hp⟩:=hp + obtain ⟨hl,hr⟩:=ih j hp l + exact ⟨by dsimp [leafDegree]; omega,hr⟩ + +lemma eval_eq_sum_leaves (p:LocalHistoryFormula M E) (A:ℕ → M → LaurentSeries ℚ) : + p.eval Ω C e F A=∑l:p.Leaf,leafWeight Ω C e F p l*A (p.leafDegree l) (p.leafExponent l) := by + induction p with + | zero=> + change 0=∑l:Empty,_ + exact (Finset.sum_eq_zero (fun l _=>l.elim)).symm + | stop j m=> + change A j m=∑l:Unit,_ + rw [Fintype.sum_unique] + simp [leafWeight,leafDegree,leafExponent] + | add p q ihp ihq=> + change p.eval Ω C e F A+q.eval Ω C e F A=∑l:Sum p.Leaf q.Leaf,_ + rw [Fintype.sum_sum_type,ihp,ihq] + rfl + | jump d m r t p ih=> + change monomialJump Ω (t.operator Ω C e F) d m r*p.eval Ω C e F A=∑l:p.Leaf,_ + rw [ih,Finset.mul_sum] + apply Finset.sum_congr rfl + intro l hl + exact (mul_assoc _ _ _).symm +end +end ElementaryPositivity.QuantumTorus.LocalHistoryFormula + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits HahnSeries +open Classical +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) +local instance commonHistoryLeavesRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance commonHistoryLeavesAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance commonHistoryLeavesAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +include hΩ hcoord in +lemma polynomialInitial_value (b:M) (hb:rootOrder coord b=0) + (F:Torus LaurentRay.vUnit Ω) (hF:∀m,F m≠0 → ∃d,HasRootDegree C d (m-b)) + (d:ℕ) (m:M) (hm:HasRootDegree C d (m-b)) (h:M →+ ℝ) : + coeff d (sectionValue LaurentRay.vUnit Ω C (simpleTotalTransport Ω C) h + (polynomialInitial Ω C coord F)) m=polynomialSectionCoefficient Ω C coord h F m := by + unfold polynomialInitial + rw [←rootSectionChart_action] + have H:=rootOrder_eq C coord hcoord hm + rw [map_sub,hb,sub_zero] at H + have he:d=(rootOrder coord m).toNat:=by rw [H,Int.toNat_natCast] + rw [he] + exact homogenize_adjoint_actual Ω hΩ (rootOrder coord) _ F + (conePolynomial_nonnegativeOrder Ω C coord hcoord b hb F hF) m (by rw [H]; omega) + +variable (e:M →+ E) (he:Function.Injective e) +variable (B:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB:∀x,B x x=0) +variable (hcomp:∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include hΩ hcoord he hB hcomp hdeg in +lemma polynomial_common_history (b:M) (hb:rootOrder coord b=0) + (N:ℕ) (r:M) (hr:HasRootDegree C N (r-b)) : + ∃p:LocalHistoryFormula M E, + p.Positive Ω C e (simpleTotalTransport Ω C) ∧ p.Bounded C b N ∧ + ∀F:Torus LaurentRay.vUnit Ω, + (∀m,F m≠0 → ∃d,HasRootDegree C d (m-b)) → + F r=∑l:p.Leaf,p.leafWeight Ω C e (simpleTotalTransport Ω C) l * + polynomialSectionIncoming Ω C coord F (p.leafExponent l) := by + obtain ⟨p,hp,hbnd,hid⟩:=common_history_producer Ω C e he B hB hcomp L hdeg + (simpleTotalTransport Ω C) (simpleTotalTransport_positive_prescription Ω C hΩ) b N (-L) r hr + refine ⟨p,hp,hbnd,?_⟩ + intro F hF + have H:=hid (polynomialInitial Ω C coord F) (polynomialInitial_graded Ω C coord hcoord b hb F hF) + rw [polynomialInitial_value Ω hΩ C coord hcoord b hb F hF N r hr, + polynomialSection_negative Ω hΩ C coord] at H + · rw [LocalHistoryFormula.eval_eq_sum_leaves] at H + rw [←H] + apply Finset.sum_congr rfl + intro l hl + congr 1 + exact polynomialInitial_value Ω hΩ C coord hcoord b hb F hF _ _ + (p.leafBound C b N hbnd l).2 (incomingCovector Ω (p.leafExponent l)) + · intro k hk m hm + change -(L (e m)) < 0 + rw [hdeg k m hm] + exact neg_neg_of_pos (Nat.cast_pos.mpr hk) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/GraphCommonHistory.lean b/lean/OAI/Combinatorics/Chromatic/Histories/GraphCommonHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3bab7d1fd77bd3027bfa876832e17ac9f01d27d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/GraphCommonHistory.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Histories.TriangularCommonHistory +import OAI.Combinatorics.Chromatic.Walls.GraphTriangularEmbedding +import OAI.Combinatorics.Chromatic.QuantumTorus.GraphSquarefreeKernel +import OAI.Combinatorics.Chromatic.Walls.ElementaryMatrixDuality + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization PowerSeries PowerSeriesAdjoint +open scoped BigOperators +open Classical +noncomputable section +variable {n D:ℕ} + +def graphVertex (b:Fin n ↪ Cell D) : Fin n ↪ Vertex D (Cell D):= + ⟨fun i=>Sum.inr (b i),fun _ _ h=>b.injective (Sum.inr.inj h)⟩ + +lemma squarefree_weight (b:Fin n ↪ Vertex D (Cell D)) : + vertexWeight (SquarefreeBlocks.target b)=(n:ℤ) := by + simp only [SquarefreeBlocks.target,map_sum] + have H:∀i:Fin n,vertexWeight (Pi.single (b i) (1:ℤ))=1:=by + intro i + simp [vertexWeight_apply,Pi.single_apply] + simp only [H,Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul,mul_one] + +lemma squarefree_rootDegree (b:Fin n ↪ Vertex D (Cell D)) : + ∃d,HasRootDegree (extendedRoots D) d + (includeVertices (SquarefreeBlocks.target b)-triangularBase n) := by + obtain ⟨d,c,hc,he⟩:=triangularVertex_rootDegree (SquarefreeBlocks.target b) (fun a=>by + rw [SquarefreeBlocks.target_apply] + split_ifs <;> omega) + refine ⟨d,c,hc,?_⟩ + change includeVertices (forwardRoots (fun i=>(c i:ℤ)))=_ + change forwardRoots (fun i=>(c i:ℤ))=_ at he + rw [he,squarefree_weight,map_sub] + rfl + +lemma graphVertex_pair (G:NaturalUnitIntervalGraph n) (b:Fin n ↪ Cell D) + (hb:∀i j,i < j → bridgePositive (b j) (b i)=(if G.Edge i j then 1 else 0) ∧ + bridgePositive (b i) (b j)=0) (i j:Fin n) (hij:i < j) : + extendedOmega D (includeVertices (Pi.single (graphVertex b i) 1)) + (includeVertices (Pi.single (graphVertex b j) 1))= -(if G.Edge i j then 1 else 0) := by + rw [extendedOmega_original] + change matrixPairing (chartMatrix cellLevel triangularBB) + (Pi.single (.inr (b i)) 1) (Pi.single (.inr (b j)) 1)=_ + rw [matrixPairing_single] + change triangularBB (b i) (b j)=_ + rw [triangularBB,(hb i j hij).1,(hb i j hij).2,zero_sub] + +theorem graph_common_history (G:NaturalUnitIntervalGraph n) : + ∃D:ℕ,∃p:LocalHistoryFormula (Extended (Vertex D (Cell D))) + ((Vertex D (Cell D) → ℝ) × (Vertex D (Cell D) → ℝ)), + p.Positive (extendedOmega D) (extendedRoots D) extendedCast + (simpleTotalTransport (extendedOmega D) (extendedRoots D)) ∧ + ∀(r:ℕ) (a:Fin r →₀ ℕ),a.degree=n → + (∑κ:Fin n → Fin r, + if G.Proper κ ∧ (∀i,(Finset.univ.filter (fun j=>κ j=i)).card=a i) then + (↑(LaurentRay.vUnit^(2*(G.coloringInversions κ:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ) else 0)= + ∑l:{l:p.Leaf // AnchoredLeaf n p l}, + p.leafWeight (extendedOmega D) (extendedRoots D) extendedCast + (simpleTotalTransport (extendedOmega D) (extendedRoots D)) l.val * + (∏i:Fin (D+1),MvPolynomial.esymm (Fin r) (LaurentSeries ℚ) (leafProfile n p l i)).coeff a := by + obtain ⟨D,b,hb⟩:=graph_triangular_embedding G + obtain ⟨d,hd⟩:=squarefree_rootDegree (graphVertex b) + obtain ⟨p,hp,hbound,he⟩:=triangular_common_history n d _ hd + refine ⟨D,p,hp,?_⟩ + intro r a ha + have hs:(List.ofFn (fun i=>a i)).sum=n:=by + rw [List.sum_ofFn] + have H:=Finsupp.sum_fintype a (fun _ k=>k) (fun _=>rfl) + exact H.symm.trans ha + let f:ElementaryExpr n:=hs ▸ ElementaryExpr.sequence (List.ofFn (fun i=>a i)) + have hf:triangularExpression f= + (List.ofFn (fun i=>independentElement LaurentRay.vUnit (extendedOmega D) + (fun x=>includeVertices (Pi.single x 1)) (a i))).prod := by + unfold triangularExpression f + rw [ElementaryExpr.eval_cast,ElementaryExpr.sequence_ofFn_eval] + rw [show vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge)= + (fun x:Vertex D (Cell D)=>includeVertices (Pi.single x 1)) from funext initial_vertexDisplay] + have hfo:f.ordinary (σ:=Fin (D+1)) (R:=LaurentSeries ℚ)= + ∏i:Fin r,MvPolynomial.esymm (Fin (D+1)) (LaurentSeries ℚ) (a i):=by + dsimp [f] + rw [ElementaryExpr.ordinary_cast,ElementaryExpr.sequence_ofFn_ordinary] + rw [←G.graph_squarefree_kernel LaurentRay.vUnit (extendedOmega D) extendedOmega_self + includeVertices includeVertices_injective (graphVertex b) (graphVertex_pair G b hb),←hf,he f] + apply Finset.sum_congr rfl + intro l hl + rw [hfo,ElementaryMatrix.duality] +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/KernelEvaluation.lean b/lean/OAI/Combinatorics/Chromatic/Histories/KernelEvaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..84c8d41c79bbc1c869d21e0def83cf81fa24f640 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/KernelEvaluation.lean @@ -0,0 +1,118 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.PointEvaluation +import OAI.Combinatorics.Chromatic.Shuffle.LaurentKernel + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +namespace SplitTree + +noncomputable def leafVarsEquiv : (T : SplitTree I) → + T.Vars ≃ (Σ z : T.Centers, Σ i, Fin (T.leafDimension z i)) + | .leaf d => + { toFun := fun x=>⟨(),x⟩ + invFun := fun x=>x.2 + left_inv := fun _=>rfl + right_inv := fun ⟨z,x⟩=>by cases z; rfl } + | .node l r => + (Equiv.sumCongr (leafVarsEquiv l) (leafVarsEquiv r)).trans + (Equiv.sumSigmaDistrib (fun z : (SplitTree.node l r).Centers=>Σ i,Fin ((SplitTree.node l r).leafDimension z i))).symm + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma leafVarsEquiv_center (T : SplitTree I) (x : T.Vars) : + (T.leafVarsEquiv x).1=T.centerOfVar x := by + induction T with + | leaf d => rfl + | node l r hl hr => cases x with + | inl x => exact congrArg Sum.inl (hl x) + | inr x => exact congrArg Sum.inr (hr x) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma leafVarsEquiv_pack (T : SplitTree I) (x : T.Vars) : + (T.leafVarsEquiv x).2.1=T.packIndex x := by + induction T with + | leaf d => rfl + | node l r hl hr => cases x with + | inl x => exact hl x + | inr x => exact hr x + +noncomputable def pointedTensorRestriction (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + simp only [pointedTensorRestriction,Algebra.TensorProduct.map_tmul,pointedRestrictionB_mk, + RawShuffle.tensorValue_tmul,crossPointEval,map_mul,eval_rename] + simp only [Function.comp_def,Sum.elim_inl,Sum.elim_inr] + simp only [Algebra.algebraMap_eq_smul_one,TensorProduct.smul_tmul, + TensorProduct.tmul_smul,smul_smul,Algebra.TensorProduct.one_def,mul_comm, + mul_smul_comm,smul_smul,Algebra.TensorProduct.tmul_mul_tmul,one_mul] + | add x y hx hy => simp only [map_add,hx,hy] +end SplitTree +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle.SeparationInfinity +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity SplitTree +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma pointed_quotientInverseKernel (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0f.coeff k) + (realize_inverseKernelUnit a L.dim R.dim) + exact congrArg (fun f=>algebraMap ℚ _ (crossPointEval L R v w f)) h + +lemma crossPointEval_inverseKernel (a : I → I → ℕ) (L R : SplitTree I) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) : + Units.map (mapRing (crossPointEval L R v w)).toMonoidHom + (rawInverseKernelUnit a L.dim R.dim)= + ∏ i, ∏ j, ∏ x : Fin (L.dim i), ∏ y : Fin (R.dim j), + affineUnit (w (R.centerOfVar (R.varEquiv.symm ⟨j,y⟩))- + v (L.centerOfVar (L.varEquiv.symm ⟨i,x⟩))) ^ inverseExponent a i j := by + simp only [rawInverseKernelUnit,rawFactor,map_prod,map_zpow,affineUnit_map, + crossPointEval,map_sub,eval_X,Sum.elim_inl,Sum.elim_inr,Function.comp_apply] +end ElementaryPositivity.RawShuffle.SeparationInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/LocalHistoryFormula.lean b/lean/OAI/Combinatorics/Chromatic/Histories/LocalHistoryFormula.lean new file mode 100644 index 0000000000000000000000000000000000000000..fcd4e4f9a2191c0b32c35b7d1e131ae8058a2ac6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/LocalHistoryFormula.lean @@ -0,0 +1,197 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SectionLineProgram + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit LaurentPositive WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] + +inductive LocalHistoryFormula (M E:Type*) [AddCommGroup E] [Module ℝ E] where + | zero + | stop (degree:ℕ) (exponent:M) + | add (left right:LocalHistoryFormula M E) + | jump (degree:ℕ) (source target:M) (transfer:LineTransfer E) (tail:LocalHistoryFormula M E) + +namespace LocalHistoryFormula +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) (e:M →+ E) +variable (F:CompletedPositive LaurentRay.vUnit Ω C) +def eval (A:ℕ → M → LaurentSeries ℚ) : LocalHistoryFormula M E → LaurentSeries ℚ + | .zero=>0 + | .stop j m=>A j m + | .add p q=>eval A p+eval A q + | .jump d m r t p=>monomialJump Ω (t.operator Ω C e F) d m r*eval A p + +def Positive : LocalHistoryFormula M E → Prop + | .zero=>True + | .stop _ _=>True + | .add p q=>Positive p ∧ Positive q + | .jump d m r t p=>LaurentPositive.Positive (monomialJump Ω (t.operator Ω C e F) d m r) ∧ Positive p + +def Bounded (b:M) (N:ℕ) : LocalHistoryFormula M E → Prop + | .zero=>True + | .stop j m=>j≤N ∧ HasRootDegree C j (m-b) + | .add p q=>Bounded b N p ∧ Bounded b N q + | .jump d _ _ _ p=>0.zero + | p::ps=>.add p (sumList ps) + +lemma eval_sumList (A:ℕ → M → LaurentSeries ℚ) (ps:List (LocalHistoryFormula M E)) : + eval Ω C e F A (sumList ps)=(ps.map (eval Ω C e F A)).sum := by + induction ps with + | nil=>rfl + | cons p ps ih=>simp only [sumList,eval,List.map_cons,List.sum_cons,ih] +lemma positive_sumList (ps:List (LocalHistoryFormula M E)) + (hp:∀p∈ps,Positive Ω C e F p) : Positive Ω C e F (sumList ps) := by + induction ps with + | nil=>trivial + | cons p ps ih=>exact ⟨hp p (by simp),ih (fun q hq=>hp q (by simp [hq]))⟩ +lemma bounded_sumList (b:M) (N:ℕ) (ps:List (LocalHistoryFormula M E)) + (hp:∀p∈ps,Bounded C b N p) : Bounded C b N (sumList ps) := by + induction ps with + | nil=>trivial + | cons p ps ih=>exact ⟨hp p (by simp),ih (fun q hq=>hp q (by simp [hq]))⟩ +lemma eval_positive (A:ℕ → M → LaurentSeries ℚ) (p:LocalHistoryFormula M E) + (hp:Positive Ω C e F p) (hA:∀j m,LaurentPositive.Positive (A j m)) : + LaurentPositive.Positive (eval Ω C e F A p) := by + induction p with + | zero=>exact positive_zero + | stop j m=>exact hA j m + | add p q ihp ihq=>exact (ihp hp.1).add (ihq hp.2) + | jump d m r t p ih=>exact hp.1.mul (ih hp.2) +end LocalHistoryFormula +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit LaurentPositive WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +namespace LocalHistoryFormula +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) (e:M →+ E) +variable (F:CompletedPositive LaurentRay.vUnit Ω C) +def finSum {J:Type*} (s:Finset J) (f:J → LocalHistoryFormula M E) : LocalHistoryFormula M E := + sumList (s.toList.map f) +lemma eval_finSum {J:Type*} (s:Finset J) (f:J → LocalHistoryFormula M E) + (A:ℕ → M → LaurentSeries ℚ) : + eval Ω C e F A (finSum s f)=∑j∈s,eval Ω C e F A (f j) := by + rw [finSum,eval_sumList,List.map_map] + simp +lemma positive_finSum {J:Type*} (s:Finset J) (f:J → LocalHistoryFormula M E) + (hp:∀j∈s,Positive Ω C e F (f j)) : Positive Ω C e F (finSum s f) := by + apply positive_sumList + intro p hp' + obtain ⟨j,hj,rfl⟩:=List.mem_map.mp hp' + exact hp j (Finset.mem_toList.mp hj) +lemma bounded_finSum {J:Type*} (s:Finset J) (f:J → LocalHistoryFormula M E) + (b:M) (N:ℕ) (hp:∀j∈s,Bounded C b N (f j)) : Bounded C b N (finSum s f) := by + apply bounded_sumList + intro p hp' + obtain ⟨j,hj,rfl⟩:=List.mem_map.mp hp' + exact hp j (Finset.mem_toList.mp hj) +end LocalHistoryFormula + +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) +variable (e:M →+ E) (he:Function.Injective e) +variable (B:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB:∀x,B x x=0) +variable (hcomp:∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in + +lemma common_history_producer (F:CompletedPositive LaurentRay.vUnit Ω C) + (incoming:PositiveIncomingPrescription Ω C F) (b:M) : + ∀N (h:Module.Dual ℝ E) (r:M),HasRootDegree C N (r-b) → + ∃p:LocalHistoryFormula M E, + p.Positive Ω C e F ∧ p.Bounded C b N ∧ + ∀X:PowerSeries (Torus LaurentRay.vUnit Ω),ShiftGraded LaurentRay.vUnit Ω C b X → + p.eval Ω C e F (fun j m=>coeff j (sectionValue LaurentRay.vUnit Ω C F (incomingCovector Ω m) X) m)= + coeff N (sectionValue LaurentRay.vUnit Ω C F (h.toAddMonoidHom.comp e) X) r := by + have walls:=positive_walls_through Ω C e he B hB hcomp L hdeg F incoming + intro N + induction N using Nat.strong_induction_on with + | h N ih=> + intro h r hr + obtain ⟨ts,hpos,hid⟩:=section_line_program Ω C e he B hB hcomp L hdeg F N (walls N) h r + have HT:∀(t:LineTransfer E) (j:Fin N) (m:{m:M // m∈gradePoints C b j}), + ∃p:LocalHistoryFormula M E,p.Positive Ω C e F ∧ p.Bounded C b j ∧ + ∀X:PowerSeries (Torus LaurentRay.vUnit Ω),ShiftGraded LaurentRay.vUnit Ω C b X → + p.eval Ω C e F (fun k a=>coeff k (sectionValue LaurentRay.vUnit Ω C F (incomingCovector Ω a) X) a)= + coeff j (sectionValue LaurentRay.vUnit Ω C F (t.source.toAddMonoidHom.comp e) X) m := by + intro t j m + exact ih j j.isLt t.source m ((mem_gradePoints C b m j).mp m.property) + choose p hp hb heval using HT + let q (t:LineTransfer E):LocalHistoryFormula M E:= + .finSum Finset.univ (fun j:Fin N=>.finSum (gradePoints C b j).attach (fun m=> + .jump (N-j.val) m.val r t (p t j m))) + have qp:∀t∈ts,(q t).Positive Ω C e F:=by + intro t ht + apply LocalHistoryFormula.positive_finSum + intro j hj + apply LocalHistoryFormula.positive_finSum + intro m hm + exact ⟨hpos t ht (N-j.val) (Nat.sub_le _ _) m.val,hp t j m⟩ + have qb:∀t∈ts,(q t).Bounded C b N:=by + intro t ht + apply LocalHistoryFormula.bounded_finSum + intro j hj + apply LocalHistoryFormula.bounded_finSum + intro m hm + exact ⟨by omega,j.val,by omega,hb t j m⟩ + have qe:∀t (X:PowerSeries (Torus LaurentRay.vUnit Ω)),ShiftGraded LaurentRay.vUnit Ω C b X → + (q t).eval Ω C e F (fun k a=>coeff k (sectionValue LaurentRay.vUnit Ω C F (incomingCovector Ω a) X) a)= + t.delta Ω C e F b X N r := by + intro t X hX + unfold q + rw [LocalHistoryFormula.eval_finSum] + unfold LineTransfer.delta + rw [←Fin.sum_univ_eq_sum_range] + apply Finset.sum_congr rfl + intro j hj + rw [LocalHistoryFormula.eval_finSum] + calc + _=∑m∈(gradePoints C b j).attach, + coeff j (sectionValue LaurentRay.vUnit Ω C F (t.source.toAddMonoidHom.comp e) X) m.val* + monomialJump Ω (t.operator Ω C e F) (N-j.val) m.val r:=by + apply Finset.sum_congr rfl + intro m hm + change monomialJump Ω (t.operator Ω C e F) (N-j.val) m.val r*_= _ + rw [heval t j m X hX,mul_comm] + _= _:=Finset.sum_attach (gradePoints C b j) (fun m=> + coeff j (sectionValue LaurentRay.vUnit Ω C F (t.source.toAddMonoidHom.comp e) X) m* + monomialJump Ω (t.operator Ω C e F) (N-j.val) m r) + let out:LocalHistoryFormula M E:=.add (.stop N r) (.sumList (ts.map q)) + refine ⟨out,⟨trivial,?_⟩,⟨⟨le_rfl,hr⟩,?_⟩,?_⟩ + · apply LocalHistoryFormula.positive_sumList + intro a ha + obtain ⟨t,ht,rfl⟩:=List.mem_map.mp ha + exact qp t ht + · apply LocalHistoryFormula.bounded_sumList + intro a ha + obtain ⟨t,ht,rfl⟩:=List.mem_map.mp ha + exact qb t ht + · intro X hX + change coeff N (sectionValue LaurentRay.vUnit Ω C F (incomingCovector Ω r) X) r+ + LocalHistoryFormula.eval Ω C e F _ (.sumList (ts.map q))=_ + rw [LocalHistoryFormula.eval_sumList,List.map_map] + apply Eq.trans _ (hid b X hX).symm + congr 1 + apply congrArg List.sum + apply List.map_congr_left + intro t ht + exact qe t X hX +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/PacketSortedWords.lean b/lean/OAI/Combinatorics/Chromatic/Histories/PacketSortedWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b45c956cdb1cfe2c10cfc680b36dc04efa4349e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/PacketSortedWords.lean @@ -0,0 +1,177 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ElementaryMatrixDuality +import OAI.Combinatorics.Chromatic.Histories.SortedFiberPerm + +namespace OAI + +section +namespace ElementaryPositivity.Packets +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} {A B:Type*} [Fintype A] [LinearOrder A] [Fintype B] [DecidableEq B] +variable (π:Fin n → B) + +def rows (w:Fin n → A) (b:B):Finset A:=(fiber π b).image w +omit [Fintype A] [Fintype B] in +lemma sorted_injOn (w:Fin n → A) (hw:Sorted π w) (b:B) : Set.InjOn w (fiber π b) := by + intro i hi j hj he + have hh:π i=π j:=(mem_fiber π b i).mp hi |>.trans ((mem_fiber π b j).mp hj).symm + rcases lt_trichotomy i j with h|h|h + · exact False.elim ((ne_of_lt (hw i j hh h)) he) + · exact h + · exact False.elim ((ne_of_lt (hw j i hh.symm h)) he.symm) +omit [Fintype A] [Fintype B] in +lemma rows_card (w:Fin n → A) (hw:Sorted π w) (b:B) : (rows π w b).card=card π b:= + Finset.card_image_of_injOn (sorted_injOn π w hw b) + +def wordCount (w:Fin n → A) : A →₀ ℕ:=∑i,Finsupp.single (w i) 1 +omit [Fintype A] in +lemma wordCount_apply (w:Fin n → A) (a:A) : wordCount w a=(Finset.univ.filter (fun i=>w i=a)).card:=by + simp [wordCount,Finsupp.single_apply,eq_comm] +omit [Fintype A] [LinearOrder A] in +lemma wordCount_degree (w:Fin n → A) : (wordCount w).degree=n := by + simp [wordCount,map_sum] + +omit [Fintype A] in +lemma rows_colCount (w:Fin n → A) (hw:Sorted π w) : ElementaryMatrix.colCount (rows π w)=wordCount w := by + unfold ElementaryMatrix.colCount rows wordCount + conv_lhs=>arg 2; ext b; rw [Finset.sum_image (sorted_injOn π w hw b)] + change (∑b,∑i∈Finset.univ.filter (fun i=>π i=b),Finsupp.single (w i) 1)=_ + rw [Finset.sum_fiberwise] + +abbrev SortedWord:= {w:Fin n → A // Sorted π w} +abbrev RowFamily:= {s:B → Finset A // ∀b,(s b).card=card π b} + +def fromRows (s:RowFamily (A:=A) π) (i:Fin n) : A:= + (s.val (π i)).orderEmbOfFin (s.property (π i)) ((fiberOrder π (π i) rfl).symm ⟨i,rfl⟩) + +omit [Fintype A] [Fintype B] in +lemma fromRows_mem (s:RowFamily (A:=A) π) (i:Fin n) : fromRows π s i∈s.val (π i):= + (s.val (π i)).orderEmbOfFin_mem _ _ + +omit [Fintype A] [Fintype B] in +lemma fromRows_at (s:RowFamily (A:=A) π) (b:B) (i:{i // π i=b}) : + fromRows π s i.val=(s.val b).orderEmbOfFin (s.property b) ((fiberOrder π b rfl).symm i) := by + have hi:=i.property + rcases i with ⟨i,hi⟩ + dsimp only at hi ⊢ + subst b + rfl + +omit [Fintype A] [Fintype B] in +lemma fromRows_sorted (s:RowFamily (A:=A) π) : Sorted π (fromRows π s) := by + intro i j hij hlt + rw [fromRows_at π s (π i) ⟨i,rfl⟩,fromRows_at π s (π i) ⟨j,hij.symm⟩] + exact ((s.val (π i)).orderEmbOfFin _).strictMono + ((fiberOrder π (π i) rfl).symm.strictMono hlt) + +omit [Fintype A] [Fintype B] in +lemma rows_fromRows (s:RowFamily (A:=A) π) : rows π (fromRows π s)=s.val := by + funext b + apply Finset.Subset.antisymm + · intro a ha + obtain ⟨i,hi,rfl⟩:=Finset.mem_image.mp ha + have H:=fromRows_mem π s i + rwa [(mem_fiber π b i).mp hi] at H + · intro a ha + let k:=((s.val b).orderIsoOfFin (s.property b)).symm ⟨a,ha⟩ + let i: {i // π i=b}:=fiberOrder π b rfl k + refine Finset.mem_image.mpr ⟨i.val,(mem_fiber π b i.val).mpr i.property,?_⟩ + rw [fromRows_at π s b i] + dsimp [i] + rw [OrderIso.symm_apply_apply] + exact congrArg Subtype.val (((s.val b).orderIsoOfFin (s.property b)).apply_symm_apply ⟨a,ha⟩) + +omit [Fintype B] in +lemma sorted_rows_unique (w v:Fin n → A) (hw:Sorted π w) (hv:Sorted π v) + (he:rows π w=rows π v) : w=v := by + let iso (u:Fin n → A) (hu:Sorted π u) (b:B) : {i // π i=b} ≃o (rows π u b):= + StrictMono.orderIsoOfSurjective (fun i=>⟨u i,Finset.mem_image.mpr ⟨i,(mem_fiber π b i.val).mpr i.property,rfl⟩⟩) + (fun i j hij=>hu i j (i.property.trans j.property.symm) hij) + (by + rintro ⟨a,ha⟩ + obtain ⟨i,hi,he⟩:=Finset.mem_image.mp ha + exact ⟨⟨i,(mem_fiber π b i).mp hi⟩,Subtype.ext he⟩) + funext i + let vIso:= (iso v hv (π i)).trans (Set.orderIsoOfEq _ _ + (congrArg (fun s:Finset A=>(s:Set A)) (congrFun he.symm (π i)))) + have H:iso w hw (π i)=vIso:=Subsingleton.elim _ _ + exact congrArg (fun q=>(q ⟨i,rfl⟩).val) H + +def rowsEquiv : SortedWord (A:=A) π ≃ RowFamily (A:=A) π where + toFun w:=⟨rows π w.val,rows_card π w.val w.property⟩ + invFun s:=⟨fromRows π s,fromRows_sorted π s⟩ + left_inv w:=Subtype.ext (sorted_rows_unique π _ _ (fromRows_sorted π _) w.property (rows_fromRows π _)) + right_inv s:=Subtype.ext (rows_fromRows π s) +end +end ElementaryPositivity.Packets + +end +section +namespace ElementaryPositivity.Packets +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} {A:Type*} [Fintype A] [LinearOrder A] + +def packetProfile (J:Finset (Fin (n-1))) : Fin (n+1) →₀ ℕ:=wordCount (index J) +lemma packetProfile_apply (J:Finset (Fin (n-1))) (b:Fin (n+1)) : + packetProfile J b=card (index J) b:=wordCount_apply _ _ +lemma packetProfile_degree (J:Finset (Fin (n-1))) : (packetProfile J).degree=n:=wordCount_degree _ + +omit [Fintype A] in +lemma anchor_required_iff (J:Finset (Fin (n-1))) (w:Fin n → A) : + J⊆ascentMask (·<·) w ↔ Sorted (index J) w := by + constructor + · intro hw i j he hij + exact inside_of_required (·<·) (fun _ _ _=>lt_trans) J w hw i j hij he + · intro hw t ht + apply (mem_ascentMask _ _ _).mpr + exact hw (left t) (right t) ((index_left_right J t).mpr ht) (by change t.valby + rw [←packetProfile_apply J b] + exact (ElementaryMatrix.rowCount_eq _ _).mp s.property.1 b⟩ + exact ⟨fromRows (index J) t,by + constructor + · rw [←rows_colCount _ _ (fromRows_sorted _ t),rows_fromRows] + exact s.property.2 + · exact (anchor_required_iff J _).mpr (fromRows_sorted _ t)⟩ + left_inv w:=by + apply Subtype.ext + exact sorted_rows_unique _ _ _ (fromRows_sorted _ _) ((anchor_required_iff J w.val).mp w.property.2) + (rows_fromRows _ _) + right_inv s:=by + apply Subtype.ext + exact rows_fromRows _ _ + +lemma requiredAnchor_card {R:Type*} [CommSemiring R] (μ:A →₀ ℕ) (J:Finset (Fin (n-1))) : + (∏i:A,MvPolynomial.esymm (Fin (n+1)) R (μ i)).coeff (packetProfile J)= + (Fintype.card (RequiredAnchor μ J):R) := by + rw [ElementaryMatrix.duality,ElementaryMatrix.elementary_product_coeff] + rw [Fintype.card_congr (anchorRowsEquiv μ J)] + simp only [Fintype.card_subtype] + rw [←Finset.sum_filter] + simp +end +end ElementaryPositivity.Packets + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/ShuffleLeafFiltration.lean b/lean/OAI/Combinatorics/Chromatic/Histories/ShuffleLeafFiltration.lean new file mode 100644 index 0000000000000000000000000000000000000000..89551f765fa1623c7f56db4d8ba9f2b77741762d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/ShuffleLeafFiltration.lean @@ -0,0 +1,88 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Degree + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open SplitTree +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma translationB_shuffleB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + induction g using Submodule.Quotient.induction_on with + | H g => + exact congrArg (destabilizingSpace a (SlopeArithmetic.slope c η) (d+e)).mkQ + (translation_shufflePolynomial a t f g) + +lemma shuffleB_leaf_degreeCut (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0f i=b) +def card (f:Fin n → B) (b:B):= (fiber f b).card +@[simp] lemma mem_fiber (f:Fin n → B) (b:B) (i:Fin n) : i∈fiber f b ↔ f i=b:=by simp [fiber] +lemma card_eq (f:Fin n → B) (b:B) : card f b=Fintype.card {i // f i=b}:=by simp [card,fiber,Fintype.card_subtype] + +def fiberOrder (f:Fin n → B) (b:B) {k:ℕ} (h:card f b=k) : Fin k ≃o {i // f i=b}:= + ((fiber f b).orderIsoOfFin h).trans + (Set.orderIsoOfEq {i | i∈fiber f b} {i | f i=b} (by ext i; simp)) + +def fiberIso (f g:Fin n → B) (h:∀b,card f b=card g b) (b:B) : + {i // f i=b} ≃o {i // g i=b}:= + (fiberOrder f b rfl).symm.trans (fiberOrder g b (h b).symm) + +def sortedPerm (f g:Fin n → B) (h:∀b,card f b=card g b) : Equiv.Perm (Fin n):= + Equiv.ofFiberEquiv (fun b=>(fiberIso f g h b).toEquiv) +lemma sortedPerm_map (f g:Fin n → B) (h:∀b,card f b=card g b) (i:Fin n) : + g (sortedPerm f g h i)=f i:=Equiv.ofFiberEquiv_map _ _ + +def Sorted {A:Type*} [LT A] (f:Fin n → B) (w:Fin n → A) : Prop:= + ∀i j,f i=f j → i⟨u i,by rw [hu,i.property]⟩) + (fun i j hij=>hs i j (i.property.trans j.property.symm) hij) + (by + intro j + refine ⟨⟨u.symm j,?_⟩,?_⟩ + · rw [←hu,u.apply_symm_apply]; exact j.property + · exact Subtype.ext (u.apply_symm_apply j)) + apply Equiv.ext + intro i + have H:e w hw hsw (f i)=e v hv hsv (f i):=Subsingleton.elim _ _ + exact congrArg (fun q=> (q ⟨i,rfl⟩).val) H + +lemma card_of_perm (f g:Fin n → B) (w:Equiv.Perm (Fin n)) (hw:∀i,g (w i)=f i) : + ∀b,card f b=card g b := by + intro b + rw [card_eq,card_eq] + exact Fintype.card_congr (w.subtypeEquiv (fun i=>by rw [hw])) +end +end ElementaryPositivity.Packets + +end +section +namespace ElementaryPositivity.Packets +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +def left (t:Fin (n-1)):Fin n:=⟨t.val,by omega⟩ +def right (t:Fin (n-1)):Fin n:=⟨t.val+1,by omega⟩ +def ascentMask {A:Type*} (R:A → A → Prop) (w:Fin n → A) : Finset (Fin (n-1)):= + Finset.univ.filter (fun t=>R (w (left t)) (w (right t))) +@[simp] lemma mem_ascentMask {A:Type*} (R:A → A → Prop) (w:Fin n → A) (t:Fin (n-1)) : + t∈ascentMask R w ↔ R (w (left t)) (w (right t)):=by simp [ascentMask] + +def gap (J:Finset (Fin (n-1))) (k:ℕ) : ℕ:=if k∈J.image Fin.val then 0 else 1 +def indexVal (J:Finset (Fin (n-1))) (k:ℕ) : ℕ:=∑t∈Finset.range k,gap J t +lemma indexVal_succ (J:Finset (Fin (n-1))) (k:ℕ) : + indexVal J (k+1)=indexVal J k+gap J k:=by simp [indexVal,Finset.sum_range_succ] +lemma indexVal_mono (J:Finset (Fin (n-1))) : Monotone (indexVal J):=by + apply monotone_nat_of_le_succ + intro k + rw [indexVal_succ] + omega +lemma indexVal_le (J:Finset (Fin (n-1))) (k:ℕ) : indexVal J k≤k:=by + induction k with + | zero=>simp [indexVal] + | succ k ih=>rw [indexVal_succ]; unfold gap; split_ifs <;> omega + +def index (J:Finset (Fin (n-1))) (i:Fin n):Fin (n+1):= + ⟨indexVal J i.val,by have H:=indexVal_le J i.val; omega⟩ +lemma index_mono (J:Finset (Fin (n-1))) : Monotone (index J):=by + intro i j hij + exact indexVal_mono J hij +lemma index_adjacent (J:Finset (Fin (n-1))) (i j:Fin n) (h:i.val+1=j.val) : + index J i=index J j ↔ (⟨i.val,by omega⟩:Fin (n-1))∈J := by + rw [Fin.ext_iff] + change indexVal J i.val=indexVal J j.val ↔ _ + rw [←h,indexVal_succ] + have hm:i.val∈J.image Fin.val ↔ (⟨i.val,by omega⟩:Fin (n-1))∈J:=by + simp only [Finset.mem_image] + constructor + · rintro ⟨t,ht,he⟩ + have H:t=⟨i.val,by omega⟩:=Fin.ext he + simpa only [←H] using ht + · intro ht + exact ⟨⟨i.val,by omega⟩,ht,rfl⟩ + simp only [gap,hm] + split_ifs <;> simp_all +lemma index_left_right (J:Finset (Fin (n-1))) (t:Fin (n-1)) : + index J (left t)=index J (right t) ↔ t∈J := by + exact index_adjacent J _ _ rfl + +lemma inside_of_required {A:Type*} (R:A → A → Prop) + (hR:∀ ⦃first middle last : A⦄, R first middle → R middle last → R first last) + (J:Finset (Fin (n-1))) (w:Fin n → A) (hw:J⊆ascentMask R w) + (i j:Fin n) (hij:iexact Fin.elim0 i + | succ N=> + have H:∀j:Fin (N+1),∀i:Fin (N+1),iintro i hi; exact (not_lt_of_ge (Fin.zero_le i) hi).elim + | succ k ih=> + intro i hij he + have hk:index J k.castSucc=index J k.succ:=by + apply le_antisymm + · exact index_mono J (by simp only [Fin.le_def,Fin.val_castSucc,Fin.val_succ]; omega) + · rw [←he] + exact index_mono J (by + change i.val≤k.val + change i.valhik (Fin.ext H) + have hit:i(μ a:ℤ)) (fun i=>Int.ofNat_le.mpr (hμ i)) + +lemma triangular_common_history (N d:ℕ) (r:Extended (Vertex n (Cell n))) + (hr:HasRootDegree (extendedRoots n) d (r-triangularBase N)) : + ∃p:LocalHistoryFormula (Extended (Vertex n (Cell n))) + ((Vertex n (Cell n) → ℝ) × (Vertex n (Cell n) → ℝ)), + p.Positive (extendedOmega n) (extendedRoots n) extendedCast + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) ∧ + p.Bounded (extendedRoots n) (triangularBase N) d ∧ + ∀f:ElementaryExpr N, triangularExpression f r= + ∑l:{l:p.Leaf // AnchoredLeaf N p l}, + p.leafWeight (extendedOmega n) (extendedRoots n) extendedCast + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) l.val * + (f.ordinary (σ:=Fin (n+1)) (R:=LaurentSeries ℚ)).coeff (leafProfile N p l) := by + obtain ⟨L,hL⟩:=real_covector_prescribe (extendedRoots n) extendedCast extendedRoots_realIndependent (fun _=>1) + obtain ⟨p,hp,hb,he⟩:=polynomial_common_history (extendedOmega n) extendedOmega_self + (extendedRoots n) (extendedCoord n) extendedCoord_roots extendedCast extendedCast_injective + (triangularRealForm n) triangularRealForm_self triangularRealForm_compatible L + (fun _ _ hm=>covector_root_eval (extendedRoots n) extendedCast L hL hm) + (triangularBase N) (triangularBase_order N) d r hr + refine ⟨p,hp,hb,?_⟩ + intro f + rw [he (triangularExpression f) (fun m hm=>triangularSeed_in_rootCone f m (Finsupp.mem_support_iff.mpr hm))] + have hz:∀l:p.Leaf,¬AnchoredLeaf N p l → + polynomialSectionIncoming (extendedOmega n) (extendedRoots n) (extendedCoord n) + (triangularExpression f) (p.leafExponent l)=0 := by + intro l ha + by_contra hh + have hd:=rootCone_dual_zero N (p.leafDegree l) (p.leafExponent l) (p.leafBound _ _ _ hb l).2 + have hm:p.leafExponent l=includeVertices (p.leafExponent l).1:=Prod.ext rfl hd + rw [hm] at hh + obtain ⟨μ,hμ,hdom,hlabel⟩:=triangularExpression_anchorSupported f _ hh + apply ha + exact ⟨μ,hμ,hdom,hm.trans (congrArg includeVertices hlabel)⟩ + rw [←Fintype.sum_subtype_add_sum_subtype (AnchoredLeaf N p)] + have hn:(∑l:{l:p.Leaf // ¬AnchoredLeaf N p l}, + p.leafWeight (extendedOmega n) (extendedRoots n) extendedCast + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) l.val * + polynomialSectionIncoming (extendedOmega n) (extendedRoots n) (extendedCoord n) + (triangularExpression f) (p.leafExponent l.val))=0 := by + apply Finset.sum_eq_zero + intro l hl + rw [hz l.val l.property,mul_zero] + rw [hn,add_zero] + apply Finset.sum_congr rfl + intro l hl + congr 1 + rw [leafProfile_exponent N p l] + exact triangularIncoming_anchorCoeff f _ (leafProfile_dominant N p l) +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Histories/TwoLeafDiagonal.lean b/lean/OAI/Combinatorics/Chromatic/Histories/TwoLeafDiagonal.lean new file mode 100644 index 0000000000000000000000000000000000000000..1111ede8d2232b35057431cc7f0554da041ebd05 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Histories/TwoLeafDiagonal.lean @@ -0,0 +1,203 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.ManyBlockDiagonal + +namespace OAI + +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +variable {A : Type*} [CommRing A] + +noncomputable def ofTwo : Polynomial (Polynomial A) →+* MvPolynomial (Unit ⊕ Unit) A := + Polynomial.eval₂RingHom (Polynomial.toMvPolynomial (Sum.inl ())).toRingHom (X (Sum.inr ())) + +@[simp] lemma ofTwo_C (p : Polynomial A) : ofTwo (Polynomial.C p) = + Polynomial.toMvPolynomial (Sum.inl ()) p := by simp [ofTwo] + +@[simp] lemma ofTwo_X : ofTwo (Polynomial.X : Polynomial (Polynomial A)) = X (Sum.inr ()) := by + simp [ofTwo] + +variable [Algebra ℚ A] + +lemma evalRat_ofTwo (p : Polynomial (Polynomial A)) (v : Unit ⊕ Unit → ℚ) : + evalRat v (ofTwo p) = RawShuffle.evalTwo p (v (Sum.inl ())) (v (Sum.inr ())) := by + induction p using Polynomial.induction_on' with + | add p q hp hq => simp only [map_add,RawShuffle.evalTwo,Polynomial.eval_add] at *; rw [hp,hq] + | monomial n p => + rw [← Polynomial.C_mul_X_pow_eq_monomial] + simp only [map_mul,map_pow,ofTwo_C,ofTwo_X,evalRat_X, + RawShuffle.SplitTree.evalRat_toMvPolynomial,RawShuffle.evalTwo, + Polynomial.eval_mul,Polynomial.eval_C,Polynomial.eval_pow,Polynomial.eval_X] + rw [polynomial_eval_rat_algebraMap] + +end ElementaryPositivity.CenterCalculus + +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.CenterCalculus +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma centeredRestrictionB_two_eval (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 d + | .node l _, Sum.inl i => leafDimension l i + | .node _ r, Sum.inr i => leafDimension r i + +namespace Regroup + +lemma leafDimension {T U : SplitTree I} (e : Regroup T U) (i : T.Centers) : + U.leafDimension (e.centers i) = T.leafDimension i := by + induction e with + | refl T => rfl + | assoc T U V => rcases i with (i|i)|i <;> rfl + | swap T U => cases i <;> rfl + | node e f ihe ihf => cases i with + | inl i => exact ihe i + | inr i => exact ihf i + | trans e f ihe ihf => exact (ihf (e.centers i)).trans (ihe i) + +def assocInv (T U V : SplitTree I) : Regroup (.node T (.node U V)) (.node (.node T U) V) := + (Regroup.swap T (.node U V)).trans + ((Regroup.node (Regroup.swap U V) (Regroup.refl T)).trans + ((Regroup.assoc V U T).trans + ((Regroup.swap V (.node U T)).trans + (Regroup.node (Regroup.swap U T) (Regroup.refl V))))) + +@[simp] lemma assocInv_centers_left (T U V : SplitTree I) (i : T.Centers) : + (assocInv T U V).centers (Sum.inl i) = Sum.inl (Sum.inl i) := rfl + +@[simp] lemma assocInv_centers_mid (T U V : SplitTree I) (i : U.Centers) : + (assocInv T U V).centers (Sum.inr (Sum.inl i)) = Sum.inl (Sum.inr i) := rfl + +lemma isolate_one (T : SplitTree I) (i : T.Centers) : + (∃ d, ∃ e : Regroup T (.leaf d), e.centers i = ()) ∨ + (∃ d U, ∃ e : Regroup T (.node (.leaf d) U), e.centers i = Sum.inl ()) := by + induction T with + | leaf d => + left + exact ⟨d,.refl _,Subsingleton.elim _ _⟩ + | node l r ihl ihr => + cases i with + | inl i => + rcases ihl i with ⟨d,e,he⟩ | ⟨d,U,e,he⟩ + · right + refine ⟨d,r,.node e (.refl r),?_⟩ + exact congrArg Sum.inl he + · right + refine ⟨d,.node U r,(Regroup.node e (.refl r)).trans (Regroup.assoc _ _ _),?_⟩ + change (Equiv.sumAssoc _ _ _) (Sum.inl (e.centers i)) = _ + rw [he] + rfl + | inr i => + rcases ihr i with ⟨d,e,he⟩ | ⟨d,U,e,he⟩ + · right + refine ⟨d,l,(Regroup.swap l r).trans (.node e (.refl l)),?_⟩ + exact congrArg Sum.inl he + · right + refine ⟨d,.node U l,(Regroup.swap l r).trans + ((Regroup.node e (.refl l)).trans (Regroup.assoc _ _ _)),?_⟩ + change (Equiv.sumAssoc _ _ _) (Sum.inl (e.centers i)) = _ + rw [he] + rfl + +lemma isolate_pair (T : SplitTree I) (i j : T.Centers) (hij : i ≠ j) : + (∃ d e, ∃ g : Regroup T (.node (.leaf d) (.leaf e)), + g.centers i = Sum.inl () ∧ g.centers j = Sum.inr ()) ∨ + (∃ d e U, ∃ g : Regroup T (.node (.node (.leaf d) (.leaf e)) U), + g.centers i = Sum.inl (Sum.inl ()) ∧ g.centers j = Sum.inl (Sum.inr ())) := by + rcases isolate_one T i with ⟨d,g,hg⟩ | ⟨d,R,g,hg⟩ + · exact (hij (g.centers.injective (Subsingleton.elim _ _))).elim + · cases hj : g.centers j with + | inl t => + cases t + exact (hij (g.centers.injective (hg.trans hj.symm))).elim + | inr k => + rcases isolate_one R k with ⟨e,h,hh⟩ | ⟨e,U,h,hh⟩ + · left + refine ⟨d,e,g.trans (.node (.refl _) h),?_,?_⟩ + · change (Equiv.sumCongr (Equiv.refl _) h.centers) (g.centers i) = _ + rw [hg] + rfl + · change (Equiv.sumCongr (Equiv.refl _) h.centers) (g.centers j) = _ + rw [hj] + exact congrArg Sum.inr hh + · right + refine ⟨d,e,U,g.trans ((Regroup.node (.refl _) h).trans (assocInv _ _ _)),?_,?_⟩ + · change (assocInv _ _ _).centers + ((Equiv.sumCongr (Equiv.refl _) h.centers) (g.centers i)) = _ + rw [hg] + rfl + · change (assocInv _ _ _).centers + ((Equiv.sumCongr (Equiv.refl _) h.centers) (g.centers j)) = _ + rw [hj] + change (assocInv _ _ _).centers (Sum.inr (h.centers k)) = _ + rw [hh] + rfl + +end Regroup +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Main.lean b/lean/OAI/Combinatorics/Chromatic/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..12abe371e589d0b2ca4548b3c90631afb030aa7f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Main.lean @@ -0,0 +1,37 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallUnitNegative +import OAI.Combinatorics.Chromatic.Shuffle.RestrictionBGraded +import OAI.Combinatorics.Chromatic.Shuffle.SymbolInternalWeight +import OAI.Combinatorics.Chromatic.Shuffle.GradedShuffle +import OAI.Combinatorics.Chromatic.Walls.RootClosureFacts +import OAI.Combinatorics.Chromatic.Walls.MutationEventualIncoming +import OAI.Combinatorics.Chromatic.Walls.FiniteRefinementImport +import OAI.Combinatorics.Chromatic.Walls.GraphBlockPairing +import OAI.Combinatorics.Chromatic.Witness.ElementaryAlphabetRigidity + +namespace OAI + +section +namespace ElementaryPositivity.FiniteSearch +variable {n : ℕ} (G : NaturalUnitIntervalGraph n) + +theorem exists_successful_table : ∃ t : Table n, Test G t := + exists_test G G.historyWitness + +def selectedTable : Table n := Encodable.choose (exists_successful_table G) + +theorem selectedTable_test : Test G (selectedTable G) := + Encodable.choose_spec (exists_successful_table G) + +end ElementaryPositivity.FiniteSearch + +def elementaryPositivityWitness (n : ℕ) + (G : ElementaryPositivity.NaturalUnitIntervalGraph n) : G.PermutationWitness where + theta σ := ElementaryPositivity.FiniteSearch.rowPartition + (ElementaryPositivity.FiniteSearch.selectedTable G σ.val) + expansion r := ElementaryPositivity.FiniteSearch.uniform_expansion_of_test + G G.historyWitness _ (ElementaryPositivity.FiniteSearch.selectedTable_test G) r + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Model.lean b/lean/OAI/Combinatorics/Chromatic/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..88184ce94d0c4462d84cf9756daf52443c48f121 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Model.lean @@ -0,0 +1,58 @@ +import Mathlib + +namespace OAI + +namespace ElementaryPositivity + +structure NaturalUnitIntervalGraph (n : ℕ) where + h : Fin n → Fin n + increasing : Monotone h + extensive : ∀ i, i ≤ h i + +namespace NaturalUnitIntervalGraph + +variable {n : ℕ} (G : NaturalUnitIntervalGraph n) + +def Edge (i j : Fin n) : Prop := + (i < j ∧ j ≤ G.h i) ∨ (j < i ∧ i ≤ G.h j) + +instance (i j : Fin n) : Decidable (G.Edge i j) := + inferInstanceAs (Decidable ((_ ∧ _) ∨ (_ ∧ _))) + +def Nondescent (σ : Equiv.Perm (Fin n)) : Prop := + ∀ i j : Fin n, i.val + 1 = j.val → σ j < σ i → G.Edge (σ i) (σ j) + +instance (σ : Equiv.Perm (Fin n)) : Decidable (G.Nondescent σ) := + inferInstanceAs (Decidable (∀ i j : Fin n, + i.val + 1 = j.val → σ j < σ i → G.Edge (σ i) (σ j))) + +def graphInversions (σ : Equiv.Perm (Fin n)) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ σ ij.2 < σ ij.1 ∧ G.Edge (σ ij.1) (σ ij.2)).card + +def Proper {r : ℕ} (f : Fin n → Fin r) : Prop := + ∀ i j : Fin n, G.Edge i j → f i ≠ f j + +instance {r : ℕ} (f : Fin n → Fin r) : Decidable (G.Proper f) := + inferInstanceAs (Decidable (∀ i j : Fin n, G.Edge i j → f i ≠ f j)) + +def coloringAscents {r : ℕ} (f : Fin n → Fin r) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ G.Edge ij.1 ij.2 ∧ f ij.1 < f ij.2).card + +noncomputable def chromatic (r : ℕ) : MvPolynomial (Fin r) (Polynomial ℕ) := + ∑ f ∈ Finset.univ.filter (G.Proper (r := r)), + MvPolynomial.C (Polynomial.X ^ G.coloringAscents f) * + ∏ i : Fin n, MvPolynomial.X (f i) + +structure PermutationWitness where + theta : {σ : Equiv.Perm (Fin n) // G.Nondescent σ} → Nat.Partition n + expansion : ∀ r : ℕ, G.chromatic r = + ∑ σ : {σ : Equiv.Perm (Fin n) // G.Nondescent σ}, + MvPolynomial.C (Polynomial.X ^ G.graphInversions σ.val) * + MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (theta σ) + +end NaturalUnitIntervalGraph +end ElementaryPositivity + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/Admissible.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/Admissible.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a1b95dca9c46cde8cff39a6ea875d8998ddcdc6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/Admissible.lean @@ -0,0 +1,221 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Model + +namespace OAI + +section +namespace ElementaryPositivity.NaturalUnitIntervalGraph +variable {n : ℕ} (G : ElementaryPositivity.NaturalUnitIntervalGraph n) + +@[simp] theorem edge_comm (a b : Fin n) : G.Edge a b ↔ G.Edge b a := by + simp only [Edge, or_comm] + +@[simp] theorem edge_irrefl (a : Fin n) : ¬ G.Edge a a := by + simp [Edge] + +def Admissible (σ : Equiv.Perm (Fin n)) : Prop := + ∀ i j : Fin n, i.val + 1 = j.val → σ i < σ j → G.Edge (σ i) (σ j) + +instance (σ : Equiv.Perm (Fin n)) : Decidable (G.Admissible σ) := + inferInstanceAs (Decidable (∀ i j : Fin n, + i.val + 1 = j.val → σ i < σ j → G.Edge (σ i) (σ j))) + +def reversePerm (σ : Equiv.Perm (Fin n)) : Equiv.Perm (Fin n) := + Fin.revPerm.trans σ + +@[simp] theorem reversePerm_apply (σ : Equiv.Perm (Fin n)) (i : Fin n) : + reversePerm σ i = σ i.rev := rfl + +@[simp] theorem reversePerm_reverse (σ : Equiv.Perm (Fin n)) : + reversePerm (reversePerm σ) = σ := by + ext i + simp + +lemma rev_adjacent {i j : Fin n} (h : i.val + 1 = j.val) : + j.rev.val + 1 = i.rev.val := by + simp only [Fin.rev] + omega + +theorem nondescent_iff_reverse_admissible (σ : Equiv.Perm (Fin n)) : + G.Nondescent σ ↔ G.Admissible (reversePerm σ) := by + constructor + · intro h i j hij hlt + exact (G.edge_comm _ _).mp (h j.rev i.rev (rev_adjacent hij) hlt) + · intro h i j hij hlt + have he := h j.rev i.rev (rev_adjacent hij) + simpa using he (by simpa using hlt) + +def reversalEquiv : {σ : Equiv.Perm (Fin n) // G.Nondescent σ} ≃ + {w : Equiv.Perm (Fin n) // G.Admissible w} where + toFun σ := ⟨reversePerm σ.val, (G.nondescent_iff_reverse_admissible _).mp σ.property⟩ + invFun w := ⟨reversePerm w.val, + (G.nondescent_iff_reverse_admissible _).mpr (by simpa using w.property)⟩ + left_inv σ := Subtype.ext (reversePerm_reverse _) + right_inv w := Subtype.ext (reversePerm_reverse _) + +def edges : Finset (Fin n × Fin n) := + Finset.univ.filter (fun ab => ab.1 < ab.2 ∧ G.Edge ab.1 ab.2) + +def edgeCount : ℕ := G.edges.card + +def invertedEdges (σ : Equiv.Perm (Fin n)) : Finset (Fin n × Fin n) := + G.edges.filter (fun ab => σ.symm ab.2 < σ.symm ab.1) + +@[simp] lemma mem_edges (ab : Fin n × Fin n) : + ab ∈ G.edges ↔ ab.1 < ab.2 ∧ G.Edge ab.1 ab.2 := by simp [edges] + +@[simp] lemma mem_invertedEdges (σ : Equiv.Perm (Fin n)) (ab : Fin n × Fin n) : + ab ∈ G.invertedEdges σ ↔ + ab.1 < ab.2 ∧ G.Edge ab.1 ab.2 ∧ σ.symm ab.2 < σ.symm ab.1 := by + simp [invertedEdges, and_assoc] + +theorem graphInversions_eq_card_invertedEdges (σ : Equiv.Perm (Fin n)) : + G.graphInversions σ = (G.invertedEdges σ).card := by + unfold graphInversions + apply Finset.card_bij (fun ij _ => (σ ij.2, σ ij.1)) + · rintro ⟨i,j⟩ hij + obtain ⟨hij,hlt,he⟩ := (Finset.mem_filter.mp hij).2 + simp only [mem_invertedEdges, Equiv.symm_apply_apply] + exact ⟨hlt, (G.edge_comm _ _).mp he, hij⟩ + · rintro ⟨i,j⟩ _ ⟨k,l⟩ _ heq + have hj := σ.injective (congrArg Prod.fst heq) + have hi := σ.injective (congrArg Prod.snd heq) + exact Prod.ext hi hj + · rintro ⟨a,b⟩ hab + obtain ⟨hab,he,hpos⟩ := (G.mem_invertedEdges σ _).mp hab + refine ⟨(σ.symm b, σ.symm a), ?_, ?_⟩ + · simp only [Finset.mem_filter, Finset.mem_univ, true_and, + Equiv.apply_symm_apply] + exact ⟨hpos, hab, (G.edge_comm _ _).mp he⟩ + · simp + +@[simp] theorem inverse_reverse_apply (σ : Equiv.Perm (Fin n)) (a : Fin n) : + (reversePerm σ).symm a = (σ.symm a).rev := rfl + +lemma invertedEdges_reverse (σ : Equiv.Perm (Fin n)) : + G.invertedEdges (reversePerm σ) = + G.edges.filter (fun ab => ¬ σ.symm ab.2 < σ.symm ab.1) := by + ext ab + simp only [mem_invertedEdges, Finset.mem_filter, mem_edges, + inverse_reverse_apply, Fin.rev_lt_rev, not_lt] + constructor + · rintro ⟨hab,he,hpos⟩ + exact ⟨⟨hab,he⟩,hpos.le⟩ + · rintro ⟨⟨hab,he⟩,hpos⟩ + refine ⟨hab,he,lt_of_le_of_ne hpos ?_⟩ + exact fun hh => hab.ne (σ.symm.injective hh) + +theorem graphInversions_add_reverse (σ : Equiv.Perm (Fin n)) : + G.graphInversions σ + G.graphInversions (reversePerm σ) = G.edgeCount := by + rw [G.graphInversions_eq_card_invertedEdges, + G.graphInversions_eq_card_invertedEdges, invertedEdges_reverse] + exact Finset.card_filter_add_card_filter_not (s := G.edges) (fun ab => σ.symm ab.2 < σ.symm ab.1) + +theorem graphInversions_le_edges (σ : Equiv.Perm (Fin n)) : + G.graphInversions σ ≤ G.edgeCount := by + have h := G.graphInversions_add_reverse σ + omega + +theorem graphInversions_reverse (σ : Equiv.Perm (Fin n)) : + G.graphInversions (reversePerm σ) = G.edgeCount - G.graphInversions σ := by + have h := G.graphInversions_add_reverse σ + omega + +def coloringInversions {r : ℕ} (f : Fin n → Fin r) : ℕ := + (G.edges.filter (fun ab => f ab.2 < f ab.1)).card + +noncomputable def inversionChromatic (r : ℕ) : MvPolynomial (Fin r) (Polynomial ℕ) := + ∑ f ∈ Finset.univ.filter (G.Proper (r := r)), + MvPolynomial.C (Polynomial.X ^ G.coloringInversions f) * + ∏ i : Fin n, MvPolynomial.X (f i) + +lemma coloringAscents_eq_card {r : ℕ} (f : Fin n → Fin r) : + G.coloringAscents f = (G.edges.filter (fun ab => f ab.1 < f ab.2)).card := by + unfold coloringAscents + congr 1 + ext ab + simp [edges, and_assoc] + +theorem coloringInversions_add_ascents {r : ℕ} (f : Fin n → Fin r) + (hf : G.Proper f) : + G.coloringInversions f + G.coloringAscents f = G.edgeCount := by + rw [coloringInversions, coloringAscents_eq_card] + have hfilter : G.edges.filter (fun ab => f ab.1 < f ab.2) = + G.edges.filter (fun ab => ¬ f ab.2 < f ab.1) := by + apply Finset.filter_congr + intro ab hab + have hne := hf ab.1 ab.2 ((G.mem_edges ab).mp hab).2 + exact ⟨fun h => not_lt.mpr h.le, fun h => lt_of_le_of_ne (not_lt.mp h) hne⟩ + rw [hfilter] + exact Finset.card_filter_add_card_filter_not (s := G.edges) _ + +end ElementaryPositivity.NaturalUnitIntervalGraph + +namespace ElementaryPositivity.CoefficientReflection + +noncomputable def reflectPolynomial (M : ℕ) : Polynomial ℕ →+ Polynomial ℕ where + toFun := Polynomial.reflect M + map_zero' := Polynomial.reflect_zero + map_add' p q := Polynomial.reflect_add p q M + +noncomputable def reflect {α : Type*} (M : ℕ) : + MvPolynomial α (Polynomial ℕ) →+ MvPolynomial α (Polynomial ℕ) := + AddMonoidAlgebra.coeffAddEquiv.symm.toAddMonoidHom.comp + ((Finsupp.mapRange.addMonoidHom (reflectPolynomial M)).comp + AddMonoidAlgebra.coeffAddEquiv.toAddMonoidHom) + +@[simp] theorem coeff_reflect {α : Type*} (M : ℕ) + (P : MvPolynomial α (Polynomial ℕ)) (m : α →₀ ℕ) : + (reflect M P).coeff m = + Polynomial.reflect M (P.coeff m) := rfl + +theorem reflect_C_X_pow_mul_map {α : Type*} (M k : ℕ) (hk : k ≤ M) + (P : MvPolynomial α ℕ) : + reflect M (MvPolynomial.C (Polynomial.X ^ k) * + MvPolynomial.map Polynomial.C P) = + MvPolynomial.C (Polynomial.X ^ (M-k)) * MvPolynomial.map Polynomial.C P := by + ext m + simp only [coeff_reflect, MvPolynomial.coeff_C_mul, MvPolynomial.coeff_map] + rw [mul_comm, Polynomial.reflect_C_mul, Polynomial.reflect_monomial, + Polynomial.revAt_le hk, mul_comm] + +lemma map_esymmPart {α : Type*} [Fintype α] {n : ℕ} (lam : Nat.Partition n) : + MvPolynomial.map (Polynomial.C : ℕ →+* Polynomial ℕ) + (MvPolynomial.esymmPart α ℕ lam) = MvPolynomial.esymmPart α (Polynomial ℕ) lam := by + simp only [MvPolynomial.esymmPart, map_multiset_prod, Multiset.map_map, + Function.comp_def, MvPolynomial.map_esymm] + +theorem reflect_C_X_pow_mul_esymmPart {α : Type*} [Fintype α] + {n : ℕ} (lam : Nat.Partition n) (M k : ℕ) (hk : k ≤ M) : + reflect M (MvPolynomial.C (Polynomial.X ^ k) * + MvPolynomial.esymmPart α (Polynomial ℕ) lam) = + MvPolynomial.C (Polynomial.X ^ (M-k)) * + MvPolynomial.esymmPart α (Polynomial ℕ) lam := by + rw [← map_esymmPart lam] + exact reflect_C_X_pow_mul_map M k hk _ + +end ElementaryPositivity.CoefficientReflection + +namespace ElementaryPositivity.NaturalUnitIntervalGraph +variable {n : ℕ} (G : ElementaryPositivity.NaturalUnitIntervalGraph n) + +theorem reflect_inversionChromatic (r : ℕ) : + CoefficientReflection.reflect G.edgeCount (G.inversionChromatic r) = G.chromatic r := by + unfold inversionChromatic chromatic + rw [map_sum] + apply Finset.sum_congr rfl + intro f hf + have hproper : G.Proper f := (Finset.mem_filter.mp hf).2 + have hc := G.coloringInversions_add_ascents f hproper + have hk : G.coloringInversions f ≤ G.edgeCount := by omega + have he : G.edgeCount - G.coloringInversions f = G.coloringAscents f := by omega + have hm : (∏ i : Fin n, MvPolynomial.X (R := Polynomial ℕ) (f i)) = + MvPolynomial.map Polynomial.C (∏ i : Fin n, MvPolynomial.X (R := ℕ) (f i)) := by + simp + rw [hm, CoefficientReflection.reflect_C_X_pow_mul_map _ _ hk, he] + +end ElementaryPositivity.NaturalUnitIntervalGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ConeSectionDomination.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ConeSectionDomination.lean new file mode 100644 index 0000000000000000000000000000000000000000..c48a5bae63df1b62a3bca1c0d67e7b92cc2ded21 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ConeSectionDomination.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularCommutativity + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits LaurentPositive +open Classical +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) +local instance coneSectionDominationTorusRing : Ring (Torus LaurentRay.vUnit Ω) := + Torus.instRing LaurentRay.vUnit Ω +local instance coneSectionDominationTorusAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance coneSectionDominationTorusAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toAddCommGroup +local instance coneSectionDominationTorusAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance coneSectionDominationTorusSub : Sub (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toSub +local instance coneSectionDominationTorusNonUnitalSemiring : NonUnitalSemiring (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalSemiring +local instance coneSectionDominationTorusNonUnitalNonAssocSemiring : + NonUnitalNonAssocSemiring (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalNonAssocSemiring +variable (F:CompletedPositive LaurentRay.vUnit Ω C) (base:M) + +def coneDelta (d:ℕ) (m:M) (k:ℕ) : Torus LaurentRay.vUnit Ω := + if k=d then Torus.X LaurentRay.vUnit Ω m else 0 +lemma coneDelta_graded (d:ℕ) (m:M) (hm:HasRootDegree C d (m-base)) (k:ℕ) : + coneDelta Ω d m k ∈ shiftRootGrade LaurentRay.vUnit Ω C base k := by + by_cases hk:k=d + · subst k + intro a ha + change (if d=d then Torus.X LaurentRay.vUnit Ω m else 0) a=0 + rw [ite_eq_left rfl] + exact Finsupp.single_eq_of_ne (by intro h; subst a; exact ha hm) + · rw [coneDelta,ite_eq_right hk] + exact (shiftRootGrade LaurentRay.vUnit Ω C base k).zero_mem + +def coneThetaInitial (d:ℕ) (m:M) : PowerSeries (Torus LaurentRay.vUnit Ω) := + sectionSolution LaurentRay.vUnit Ω C F base (coneDelta Ω d m) +def coneThetaValue (d:ℕ) (m:M) (h:M →+ ℝ) : PowerSeries (Torus LaurentRay.vUnit Ω) := + sectionValue LaurentRay.vUnit Ω C F h (coneThetaInitial Ω C F base d m) +lemma coneThetaInitial_graded (d:ℕ) (m:M) (hm:HasRootDegree C d (m-base)) : + ShiftGraded LaurentRay.vUnit Ω C base (coneThetaInitial Ω C F base d m) := + sectionSolution_graded _ _ _ _ _ _ (coneDelta_graded Ω C base d m hm) +lemma coneThetaInitial_prescription (d:ℕ) (m:M) (hm:HasRootDegree C d (m-base)) (k:ℕ) : + sectionIncoming LaurentRay.vUnit Ω C F base k (coneThetaInitial Ω C F base d m)=coneDelta Ω d m k := + sectionSolution_prescription _ _ _ _ _ _ (coneDelta_graded Ω C base d m hm) k + +lemma sectionIncoming_sub (k:ℕ) (X Y:PowerSeries (Torus LaurentRay.vUnit Ω)) : + sectionIncoming LaurentRay.vUnit Ω C F base k (X-Y)= + sectionIncoming LaurentRay.vUnit Ω C F base k X-sectionIncoming LaurentRay.vUnit Ω C F base k Y := by + apply Finsupp.ext + intro m + simp only [sectionIncoming_apply,torus_sub_apply] + split_ifs + · simp only [sectionValue,adjoint_sub,map_sub,torus_sub_apply] + · exact (sub_self (0:LaurentSeries ℚ)).symm +variable (e:M →+ E) (he:Function.Injective e) +variable (B:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB:∀x,B x x=0) +variable (hcomp:∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in +lemma coneThetaValue_positive (incoming:PositiveIncomingPrescription Ω C F) + (d:ℕ) (m:M) (hm:HasRootDegree C d (m-base)) (h:Module.Dual ℝ E) : + IntegralPositive Ω (coneThetaValue Ω C F base d m (h.toAddMonoidHom.comp e)) := by + intro j + apply positive_sections Ω C e he B hB hcomp L hdeg F incoming base + (coneThetaInitial Ω C F base d m) (coneThetaInitial_graded Ω C F base d m hm) _ j h + intro k + rw [coneThetaInitial_prescription Ω C F base d m hm,coneDelta] + split_ifs + · exact torusPositive_monomial Ω m 1 positive_one + · exact torusPositive_zero Ω + +include he hB hcomp hdeg in + +lemma coneTheta_domination (incoming:PositiveIncomingPrescription Ω C F) + (X:PowerSeries (Torus LaurentRay.vUnit Ω)) (hX:ShiftGraded LaurentRay.vUnit Ω C base X) + (d:ℕ) (m:M) (hm:HasRootDegree C d (m-base)) + (hinc:∀k,TorusPositive Ω + (sectionIncoming LaurentRay.vUnit Ω C F base k X-coneDelta Ω d m k)) + (h:Module.Dual ℝ E) : + IntegralPositive Ω (sectionValue LaurentRay.vUnit Ω C F (h.toAddMonoidHom.comp e) X- + coneThetaValue Ω C F base d m (h.toAddMonoidHom.comp e)) := by + have H:=positive_sections Ω C e he B hB hcomp L hdeg F incoming base + (X-coneThetaInitial Ω C F base d m) + (hX.sub _ _ _ (coneThetaInitial_graded Ω C F base d m hm)) + (by + intro k + rw [sectionIncoming_sub,coneThetaInitial_prescription Ω C F base d m hm] + exact hinc k) + simpa only [IntegralPositive,sectionValue,adjoint_sub,coneThetaValue] using (fun k=>H k h) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/CovectorPrescriptions.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/CovectorPrescriptions.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad22d403db15745ab608122a1082da5319f6cd19 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/CovectorPrescriptions.lean @@ -0,0 +1,28 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RealRootCoordinates + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (C:(I → ℤ) →+ M) (e:M →+ E) +lemma real_covector_prescribe (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) (w:I → ℝ) : + ∃J:Module.Dual ℝ E,∀i,J (e (simpleRoot C i))=w i := by + classical + obtain ⟨D,hD⟩:=realRootCoordinates_exists C e hC + refine ⟨∑i,w i • (LinearMap.proj i).comp D,fun i=>?_⟩ + simp only [LinearMap.sum_apply,LinearMap.smul_apply,LinearMap.comp_apply, + real_coordinate_simple C e D hD,LinearMap.proj_apply,smul_eq_mul,Pi.single_apply] + rw [Finset.sum_eq_single i] + · simp + · intro j hj hji; simp [hji] + · simp +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ExpressionAdditiveOperations.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ExpressionAdditiveOperations.lean new file mode 100644 index 0000000000000000000000000000000000000000..c43b07cbfd5fd2d0c1a5e5196bbdaabc590f0733 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ExpressionAdditiveOperations.lean @@ -0,0 +1,118 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularAnchorProjection +import OAI.Combinatorics.Chromatic.QuantumTorus.OrdinaryExpressionNaturality + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +noncomputable section + +def ElementaryExpr.nscale {N:ℕ} (k:ℕ) (f:ElementaryExpr N) : ElementaryExpr N := + match k with + | 0=>.zero N + | k+1=>.add (nscale k f) f + +def ElementaryExpr.zscale {N:ℕ} (z:ℤ) (f:ElementaryExpr N) : ElementaryExpr N := + match z with + | .ofNat k=>nscale k f + | .negSucc k=>.neg (nscale (k+1) f) + +def ElementaryExpr.sumList {N:ℕ} : List (ElementaryExpr N) → ElementaryExpr N + | []=>.zero N + | f::fs=>.add f (sumList fs) + +variable {σ:Type*} [Fintype σ] {R:Type*} [CommRing R] +lemma ElementaryExpr.ordinary_nscale {N:ℕ} (f:ElementaryExpr N) (k:ℕ) : + (nscale k f).ordinary (σ:=σ) (R:=R)=k • f.ordinary := by + induction k with + | zero=>simp [nscale,ordinary] + | succ k ih=>simp only [nscale,ordinary,ih,add_nsmul,one_nsmul] +lemma ElementaryExpr.ordinary_zscale {N:ℕ} (f:ElementaryExpr N) (z:ℤ) : + (zscale z f).ordinary (σ:=σ) (R:=R)=z • f.ordinary := by + cases z with + | ofNat k=>simpa [zscale] using ordinary_nscale (σ:=σ) (R:=R) f k + | negSucc k=>simp only [zscale,ordinary,ordinary_nscale,negSucc_zsmul] +lemma ElementaryExpr.ordinary_sumList {N:ℕ} (fs:List (ElementaryExpr N)) : + (sumList fs).ordinary (σ:=σ) (R:=R)=(fs.map (fun f=>f.ordinary (σ:=σ) (R:=R))).sum := by + induction fs with + | nil=>rfl + | cons f fs ih=>simp only [sumList,ordinary,List.map_cons,List.sum_cons,ih] +lemma ElementaryExpr.ordinary_symmetric {N:ℕ} (f:ElementaryExpr N) : + (f.ordinary (σ:=σ) (R:=R)).IsSymmetric := by + induction f with + | zero=>intro e; exact map_zero _ + | one=>intro e; exact map_one _ + | atom k=>exact MvPolynomial.esymm_isSymmetric σ R k + | add f g hf hg=>intro e; simp only [ordinary,map_add,hf e,hg e] + | neg f hf=>intro e; simp only [ordinary,map_neg,hf e] + | mul f g hf hg=>intro e; simp only [ordinary,map_mul,hf e,hg e] +end +end ElementaryPositivity.QuantumTorus +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization PowerSeries PowerSeriesAdjoint +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} +local instance expressionAdditiveOperationsRing : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance expressionAdditiveOperationsAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommMonoid +local instance expressionAdditiveOperationsAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup +local instance expressionAdditiveOperationsAddGroup : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup +local instance expressionAdditiveOperationsSub : Sub (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toSub +lemma triangularExpression_nscale {N:ℕ} (f:ElementaryExpr N) (k:ℕ) : + triangularExpression (n:=n) (f.nscale k)=k • triangularExpression f := by + induction k with + | zero=>simp [ElementaryExpr.nscale,triangularExpression,ElementaryExpr.eval] + | succ k ih=> + change triangularExpression (f.nscale k)+triangularExpression f=_ + rw [ih] + apply Finsupp.ext + intro m + simp only [Finsupp.add_apply,Finsupp.smul_apply,add_smul,one_smul] +lemma triangularExpression_zscale {N:ℕ} (f:ElementaryExpr N) (z:ℤ) : + triangularExpression (n:=n) (f.zscale z)=z • triangularExpression f := by + apply Finsupp.ext + intro m + cases z with + | ofNat k=> + change triangularExpression (f.nscale k) m=_ + rw [triangularExpression_nscale] + simp [Finsupp.smul_apply] + | negSucc k=> + change -(triangularExpression (f.nscale (k+1)) m)=_ + rw [triangularExpression_nscale] + simp only [Finsupp.smul_apply,negSucc_zsmul] +lemma triangularExpression_sumList {N:ℕ} (fs:List (ElementaryExpr N)) : + triangularExpression (n:=n) (.sumList fs)=(fs.map (triangularExpression (n:=n))).sum := by + induction fs with + | nil=>rfl + | cons f fs ih=>change triangularExpression f+triangularExpression (.sumList fs)=_; rw [ih]; rfl + +lemma triangularExpression_ordinary_equal {N:ℕ} (f g:ElementaryExpr N) + (h:f.ordinary (σ:=Fin (n+1)) (R:=ℤ)=g.ordinary) : triangularExpression (n:=n) f=triangularExpression g := by + have h':f.ordinary (σ:=Fin (n+1)) (R:=LaurentSeries ℚ)=g.ordinary:=by + rw [←ElementaryExpr.ordinary_map f (Int.castRingHom _),h,ElementaryExpr.ordinary_map] + apply triangularPure_equal + intro μ + by_cases hn:∀a,0≤μ a + · let d:Fin (n+1) →₀ ℕ:=Finsupp.equivFunOnFinite.symm (fun a=>(μ a).toNat) + have hd:∀a,(d a:ℤ)=μ a:=fun a=>Int.toNat_of_nonneg (hn a) + have he:includeVertices (pureAnchor μ)=anchorExponent d:=by + change includeVertices (pureAnchor μ)=includeVertices (pureAnchor (fun a=>(d a:ℤ))) + rw [show (fun a=>(d a:ℤ))=μ from funext hd] + rw [he,triangularExpression_anchorCoeff,triangularExpression_anchorCoeff,h'] + · obtain ⟨a,ha⟩:=not_forall.mp hn + have hz:∀e:ElementaryExpr N,triangularExpression e (includeVertices (pureAnchor μ))=0:=by + intro e + by_contra hh + have H:0≤pureAnchor μ (.inl a):=triangularSeed_nonneg e _ (Finsupp.mem_support_iff.mpr hh) (.inl a) + exact ha (by simpa only [pureAnchor_apply_anchor] using H) + rw [hz,hz] +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GeometricMutation.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GeometricMutation.lean new file mode 100644 index 0000000000000000000000000000000000000000..e4331323d1493b43a36f7a2edc526c0e831c307e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GeometricMutation.lean @@ -0,0 +1,115 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.IncomingEquality + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] +variable (Ω : M →+ M →+ ℤ) (e : M →+ E) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (p : M) +variable (hS : ∀x,S x x=0) (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) + +def realShearCovector (h : Module.Dual ℝ E) : Module.Dual ℝ E := h+(h (e p)) • S (e p) +def realShearCovectorInverse (h : Module.Dual ℝ E) : Module.Dual ℝ E := h-(h (e p)) • S (e p) +include hS in +lemma realShearCovector_at_p (h : Module.Dual ℝ E) : + realShearCovector e S p h (e p)=h (e p) := by + simp [realShearCovector,hS] +include hS in +lemma realShearCovectorInverse_at_p (h : Module.Dual ℝ E) : + realShearCovectorInverse e S p h (e p)=h (e p) := by + simp [realShearCovectorInverse,hS] +include hS in +lemma realShearCovector_left_inverse (h : Module.Dual ℝ E) : + realShearCovectorInverse e S p (realShearCovector e S p h)=h := by + rw [realShearCovectorInverse,realShearCovector_at_p e S p hS] + exact add_sub_cancel_right h _ +include hS in +lemma realShearCovector_right_inverse (h : Module.Dual ℝ E) : + realShearCovector e S p (realShearCovectorInverse e S p h)=h := by + rw [realShearCovector,realShearCovectorInverse_at_p e S p hS] + exact sub_add_cancel h _ + +def realMutationCovector (h : Module.Dual ℝ E) : Module.Dual ℝ E := + if 0≤h (e p) then h else realShearCovector e S p h +def realMutationCovectorInverse (h : Module.Dual ℝ E) : Module.Dual ℝ E := + if 0≤h (e p) then h else realShearCovectorInverse e S p h +include hS in +lemma realMutationCovector_at_p (h : Module.Dual ℝ E) : + realMutationCovector e S p h (e p)=h (e p) := by + unfold realMutationCovector + split_ifs <;> first | rfl | exact realShearCovector_at_p e S p hS h +include hS in +lemma realMutationCovectorInverse_at_p (h : Module.Dual ℝ E) : + realMutationCovectorInverse e S p h (e p)=h (e p) := by + unfold realMutationCovectorInverse + split_ifs <;> first | rfl | exact realShearCovectorInverse_at_p e S p hS h +include hS in +lemma realMutationCovector_left_inverse (h : Module.Dual ℝ E) : + realMutationCovectorInverse e S p (realMutationCovector e S p h)=h := by + unfold realMutationCovectorInverse + rw [realMutationCovector_at_p e S p hS] + unfold realMutationCovector + split_ifs <;> first | rfl | exact realShearCovector_left_inverse e S p hS h +include hS in +lemma realMutationCovector_right_inverse (h : Module.Dual ℝ E) : + realMutationCovector e S p (realMutationCovectorInverse e S p h)=h := by + unfold realMutationCovector + rw [realMutationCovectorInverse_at_p e S p hS] + unfold realMutationCovectorInverse + split_ifs <;> first | rfl | exact realShearCovector_right_inverse e S p hS h + +def realMutationCovectorEquiv : Module.Dual ℝ E ≃ Module.Dual ℝ E where + toFun:=realMutationCovector e S p + invFun:=realMutationCovectorInverse e S p + left_inv:=realMutationCovector_left_inverse e S p hS + right_inv:=realMutationCovector_right_inverse e S p hS + +include hcomp in +lemma realShearCovector_lattice (h : Module.Dual ℝ E) : + (realShearCovector e S p h).toAddMonoidHom.comp e=shearCovector Ω p (h.toAddMonoidHom.comp e) := by + ext m + change h (e m)+h (e p)*S (e p) (e m)=h (e (m+Ω p m • p)) + rw [hcomp,map_add,map_zsmul,map_add,map_zsmul] + simp only [zsmul_eq_mul] + ring +include hcomp in +lemma realMutationCovector_lattice (h : Module.Dual ℝ E) : + (realMutationCovector e S p h).toAddMonoidHom.comp e= + mutationCovector Ω p (h.toAddMonoidHom.comp e) := by + unfold realMutationCovector mutationCovector + change (if 0≤h (e p) then h else realShearCovector e S p h).toAddMonoidHom.comp e= + if 0≤h (e p) then h.toAddMonoidHom.comp e else shearCovector Ω p (h.toAddMonoidHom.comp e) + split_ifs <;> first | rfl | exact realShearCovector_lattice Ω e S p hcomp h + +include hS hcomp in +lemma realMutationCovector_incoming (r : M) : + realMutationCovector e S p (S.flip (e r))=S.flip (e (mutationIncomingLabel Ω p r)) := by + have hs : ∀a b,S a b= -S b a:=by + intro a b + have H:=hS (a+b) + simp only [map_add,LinearMap.add_apply,hS] at H + linarith + ext x + by_cases hp : (0:ℝ)≤S (e p) (e r) + · have hp' : 0≤Ω p r:=by rw [hcomp] at hp; exact_mod_cast hp + have hflip : 0≤(S.flip (e r)) (e p):=hp + rw [realMutationCovector,ite_eq_left hflip,mutationIncomingLabel_nonnegative Ω p r hp'] + · have hp' : Ω p r≤0:=by + have hh : S (e p) (e r)≤0:=le_of_lt (lt_of_not_ge hp) + rw [hcomp] at hh + exact_mod_cast hh + have hflip : ¬0≤(S.flip (e r)) (e p):=hp + rw [realMutationCovector,ite_eq_right hflip,mutationIncomingLabel_nonpositive Ω p r hp'] + change S x (e r)+S (e p) (e r)*S (e p) x=S x (e (r-Ω p r • p)) + rw [map_sub,map_zsmul,map_sub,map_zsmul,hcomp,hs x (e p)] + simp only [zsmul_eq_mul] + ring +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GlobalFiberBound.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GlobalFiberBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..24cb0b10da8581b20257cb9dd8b8c69ee200c2fe --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GlobalFiberBound.lean @@ -0,0 +1,79 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.UpstreamSimpleFiber + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) +include hcoord he hB hcomp hdeg in +theorem simple_fiber_bound_through (N : ℕ) (hN : 0 + intro q d hd hdq b hb s hs + apply global_simple_fiber_step Ω C coord hcoord pc e he B hB hcomp L hdeg N hN (n:ℤ) ?_ + q d hd hdq b hb s hs + intro q' d' hd' hdq' b' hb' s' hs' j hj m hm hn + have hw : 0≤nonpDegree coord pc m:=nonpDegree_root_nonneg C coord hcoord pc + (chart_root_of_ne LaurentRay.vUnit Ω C _ j m hm) + exact ih (nonpDegree coord pc m).toNat (by omega) q' d' hd' hdq' b' hb' s' hs' + j hj m hm (by omega) + intro j hj m hm + have hw : 0≤nonpDegree coord pc m:=nonpDegree_root_nonneg C coord hcoord pc + (chart_root_of_ne LaurentRay.vUnit Ω C _ j m hm) + exact H (nonpDegree coord pc m).toNat r dr hdr hrd h hg pos hside j hj m hm (by omega) + +include hcoord he hB hcomp hdeg in +theorem simple_fiber_bound (r : M) (dr : ℕ) (hdr : 0m∈P) + (fun a b ha hb=>P.add_mem ha hb) _ (chartZero _ _ _ _ _).property.1 + (fun j m hh=>by by_contra hm; exact hh (HH (j+1) m hm)) j m hn) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GraphRationalModel.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GraphRationalModel.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4c5e46353f8f6a1eebb1d6687cb2b2ecf177a19 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GraphRationalModel.lean @@ -0,0 +1,64 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Model +import OAI.Combinatorics.Chromatic.Walls.RationalIntervalModel + +namespace OAI + +section +namespace ElementaryPositivity.NaturalUnitIntervalGraph +variable {n:ℕ} (G:ElementaryPositivity.NaturalUnitIntervalGraph n) + +def extendedH (i:ℕ) : ℕ := if hi:i < n then (G.h ⟨i,hi⟩).val else i +lemma extendedH_monotone : Monotone G.extendedH := by + intro i j hij + unfold extendedH + split_ifs with hi hj + · exact G.increasing hij + · have hv: (G.h ⟨i,hi⟩).val < n := (G.h ⟨i,hi⟩).isLt + omega + · omega + · exact hij + +lemma rational_model : ∃t:Fin n → ℚ, (∀i,0 < t i) ∧ StrictMono t ∧ + ∀i j,i < j → (j≤G.h i → t j < t i+1) ∧ (G.h i < j → t i+1 < t j) := by + obtain ⟨t,ht,he⟩:=ElementaryPositivity.rational_interval_prefix G.extendedH G.extendedH_monotone n + refine ⟨fun i=>t i.val,fun i=>ht i.val i.isLt,?_,?_⟩ + · intro i j hij + exact (he i.val j.val hij j.isLt).1 + · intro i j hij + have H: G.extendedH i.val=(G.h i).val:=by simp [extendedH,i.isLt] + change (j.val≤(G.h i).val → _) ∧ ((G.h i).val < j.val → _) + simpa only [H] using (he i.val j.val hij j.isLt).2 +end ElementaryPositivity.NaturalUnitIntervalGraph + +namespace ElementaryPositivity +structure PhaseLabel (n:ℕ) where + val:Fin n + deriving DecidableEq, Fintype + +lemma phase_rank {n:ℕ} (f:Fin n → ℚ) : ∃r:Equiv.Perm (Fin n), + ∀i j,r i < r j ↔ f i < f j ∨ (f i=f j ∧ i < j) := by + let key:PhaseLabel n → Lex (ℚ×Fin n):=fun a=>toLex (f a.val,a.val) + have hkey:Function.Injective key:=by + intro a b h + have hh:=congrArg (fun p:Lex (ℚ×Fin n)=>(ofLex p).2) h + cases a; cases b; congr 1 + let : LinearOrder (PhaseLabel n):=LinearOrder.lift' key hkey + let e:Fin n ≃o PhaseLabel n:=Fintype.orderIsoFinOfCardEq (k:=n) (PhaseLabel n) (by + let e:PhaseLabel n ≃ Fin n:={toFun:=PhaseLabel.val,invFun:=PhaseLabel.mk,left_inv:=fun _=>rfl,right_inv:=fun _=>rfl} + exact (Fintype.card_congr e).trans (Fintype.card_fin n)) + let r:Equiv.Perm (Fin n):={ + toFun:=fun i=>e.symm ⟨i⟩ + invFun:=fun i=>(e i).val + left_inv:=fun i=>congrArg PhaseLabel.val (e.apply_symm_apply ⟨i⟩) + right_inv:=fun i=>e.symm_apply_apply i } + refine ⟨r,fun i j=>?_⟩ + change e.symm (PhaseLabel.mk i) < e.symm (PhaseLabel.mk j) ↔ _ + rw [e.symm.lt_iff_lt] + change key (PhaseLabel.mk i) < key (PhaseLabel.mk j) ↔ _ + exact Prod.Lex.lt_iff +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GraphSquarefreeKernel.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GraphSquarefreeKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..e28661b5cc15a526c46e3cede9d42aaef8416827 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/GraphSquarefreeKernel.lean @@ -0,0 +1,81 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousElementaryExpressions +import OAI.Combinatorics.Chromatic.Model +import OAI.Combinatorics.Chromatic.GradedAlgebra.SquarefreeCoefficient +import OAI.Combinatorics.Chromatic.QuantumTorus.OrdinaryElementaryExpressions +import OAI.Combinatorics.Chromatic.Walls.GraphBlockPairing + +namespace OAI + +section +namespace ElementaryPositivity.NaturalUnitIntervalGraph +open QuantumTorus +open scoped BigOperators +open Classical +noncomputable section +variable {n r:ℕ} (G:NaturalUnitIntervalGraph n) +variable {K M V:Type*} [Field K] [AddCommGroup M] [Fintype V] [DecidableEq V] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +local instance graphSquarefreeKernelRing : Ring (Torus v Ω) := Torus.instRing v Ω +variable (c:(V → ℤ) →+ M) (hc:Function.Injective c) (b:Fin n ↪ V) +variable (hp:∀i j,i < j → Ω (c (Pi.single (b i) 1)) (c (Pi.single (b j) 1))= -(if G.Edge i j then 1 else 0)) + +include hΩ hc hp in +lemma graph_squarefree_kernel (a:Fin r → ℕ) : + ((List.ofFn (fun i=>independentElement v Ω (fun x=>c (Pi.single x 1)) (a i))).prod) + (c (SquarefreeBlocks.target b))= + ∑κ:Fin n → Fin r, + if G.Proper κ ∧ (∀i,(Finset.univ.filter (fun j=>κ j=i)).card=a i) then + ↑(v^(2*(G.coloringInversions κ:ℤ)-(G.edgeCount:ℤ))) else 0 := by + rw [independent_product_squarefree v Ω c hc b] + apply Finset.sum_congr rfl + intro κ hκ + rw [G.blockValid_iff Ω hΩ _ b hp] + split_ifs with h + · rw [G.blocks_energy Ω hΩ _ b hp κ h.1] + · rfl +end +end ElementaryPositivity.NaturalUnitIntervalGraph + +end +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +open Classical +noncomputable section + +def ElementaryExpr.sequence : (a:List ℕ) → ElementaryExpr a.sum + | []=>.one + | k::a=>.mul (.atom k) (sequence a) + +variable {M V:Type*} [AddCommGroup M] [Fintype V] [DecidableEq V] +variable (v:(LaurentSeries ℚ)ˣ) (Ω:M →+ M →+ ℤ) +local instance graphSquarefreeSequenceRing : Ring (Torus v Ω) := Torus.instRing v Ω +lemma ElementaryExpr.sequence_eval (u:V → M) (a:List ℕ) : + (sequence a).eval v Ω u=(a.map (independentElement v Ω u)).prod := by + induction a with + | nil=>rfl + | cons k a ih=>change independentElement v Ω u k*(sequence a).eval v Ω u=_; rw [ih]; rfl +lemma ElementaryExpr.eval_cast {N K:ℕ} (h:N=K) (f:ElementaryExpr N) (u:V → M) : + (h ▸ f).eval v Ω u=f.eval v Ω u := by subst K; rfl +variable {R σ:Type*} [CommRing R] [Fintype σ] +lemma ElementaryExpr.sequence_ordinary (a:List ℕ) : + (sequence a).ordinary (σ:=σ) (R:=R)=(a.map (MvPolynomial.esymm σ R)).prod := by + induction a with + | nil=>rfl + | cons k a ih=>change MvPolynomial.esymm σ R k*(sequence a).ordinary=_; rw [ih]; rfl + +lemma ElementaryExpr.sequence_ofFn_eval (u:V → M) {r:ℕ} (a:Fin r → ℕ) : + (sequence (List.ofFn a)).eval v Ω u=(List.ofFn (fun i=>independentElement v Ω u (a i))).prod := by + rw [sequence_eval,List.map_ofFn] + rfl +lemma ElementaryExpr.sequence_ofFn_ordinary {r:ℕ} (a:Fin r → ℕ) : + (sequence (List.ofFn a)).ordinary (σ:=σ) (R:=R)=∏i:Fin r,MvPolynomial.esymm σ R (a i) := by + rw [sequence_ordinary,List.map_ofFn,List.prod_ofFn] + rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentElement.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentElement.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec4fcc7367edcd8fed4bf14f44f13093128c6c73 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentElement.lean @@ -0,0 +1,50 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.IndependentSetElements + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +open Classical +noncomputable section +variable {K M V:Type*} [Field K] [AddCommGroup M] [Fintype V] [DecidableEq V] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) + +include hΩ in +omit [Fintype V] in +lemma independentTerm_singleton (w:V → M) (x:V) : + independentTerm v Ω w 1 {x}=Torus.X v Ω (w x) := by + have hi:IsIndependent Ω w {x}:=by + intro a ha b hb + simp only [Finset.mem_singleton] at ha hb + subst a; subst b + exact hΩ _ + simp only [independentTerm,hi,Finset.card_singleton,and_self,ite_true,setMonomial,Finset.sum_singleton] + +include hΩ in +lemma independentElement_one (w:V → M) : + independentElement v Ω w 1=∑x,Torus.X v Ω (w x) := by + symm + unfold independentElement + apply Finset.sum_bij_ne_zero (fun x _ _=>({x}:Finset V)) + · intros; exact Finset.mem_univ _ + · intro x _ _ y _ _ h + exact Finset.singleton_injective h + · intro s _ hs + unfold independentTerm at hs + split_ifs at hs with H + · obtain ⟨x,rfl⟩:=Finset.card_eq_one.mp H.2 + refine ⟨x,Finset.mem_univ _,?_,rfl⟩ + intro hh + have Hx:=congrArg (fun F:Torus v Ω=>F (w x)) hh + simp [Torus.X,Torus.monomial] at Hx + · exact (hs rfl).elim + · intro x _ _ + exact (independentTerm_singleton v Ω hΩ w x).symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentElementReindex.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentElementReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..5834ef809150eefa606ad161802e7afc9783c2e1 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentElementReindex.lean @@ -0,0 +1,46 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.IndependentSetElements + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open Classical +open scoped BigOperators +noncomputable section +variable {K M V W : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) + +lemma independent_map [DecidableEq V] [DecidableEq W] + (u : W → M) (e : V ↪ W) (s : Finset V) : + IsIndependent Ω u (s.map e) ↔ IsIndependent Ω (u∘e) s := by + simp [IsIndependent] + +lemma independentTerm_map [DecidableEq V] [DecidableEq W] + (u : W → M) (e : V ↪ W) (s : Finset V) (k : ℕ) : + independentTerm v Ω u k (s.map e)=independentTerm v Ω (u∘e) k s := by + simp only [independentTerm,independent_map,Finset.card_map,setMonomial,Finset.sum_map] + rfl + +lemma independentElement_reindex [Fintype V] [DecidableEq V] [Fintype W] [DecidableEq W] + (u : W → M) (e : V ≃ W) (k : ℕ) : + independentElement v Ω u k=independentElement v Ω (u∘e) k := by + unfold independentElement + rw [←Equiv.sum_comp e.finsetCongr] + apply Finset.sum_congr rfl + intro s _ + exact independentTerm_map v Ω u e.toEmbedding s k + +def embeddingSumCompl (e : V ↪ W) : V ⊕ {w : W // w∉Set.range e} ≃ W := + ((Equiv.ofInjective e e.injective).sumCongr (Equiv.refl _)).trans + (Equiv.sumCompl (fun w=>w∈Set.range e)) +@[simp] lemma embeddingSumCompl_inl (e : V ↪ W) (x : V) : + embeddingSumCompl e (.inl x)=e x := rfl +@[simp] lemma embeddingSumCompl_inr (e : V ↪ W) (x : {w : W // w∉Set.range e}) : + embeddingSumCompl e (.inr x)=x.val := rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentSetElements.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentSetElements.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c100959e309b8f28a9d376737d29e70702fa226 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndependentSetElements.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.QuantumTorusTrace + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +open Classical +noncomputable section +variable {K M V W : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) + +def IsIndependent (u : V → M) (s : Finset V) : Prop := + ∀ x ∈ s, ∀ y ∈ s, Ω (u x) (u y)=0 + +def setMonomial (u : V → M) (s : Finset V) : Torus v Ω := + Torus.X v Ω (∑ x ∈ s,u x) + +def independentTerm [DecidableEq V] (u : V → M) (k : ℕ) (s : Finset V) : Torus v Ω := + if IsIndependent Ω u s ∧ s.card=k then setMonomial v Ω u s else 0 + +def independentElement [Fintype V] [DecidableEq V] (u : V → M) (k : ℕ) : Torus v Ω := + ∑ s : Finset V, independentTerm v Ω u k s + +lemma independent_sum_iff (hΩ : ∀m,Ω m m=0) (u : V → M) (w : W → M) + (s : Finset V) (t : Finset W) : + IsIndependent Ω (Sum.elim u w) (s.disjSum t) ↔ + IsIndependent Ω u s ∧ IsIndependent Ω w t ∧ + ∀x∈s,∀y∈t,Ω (u x) (w y)=0 := by + constructor + · intro h + refine ⟨?_,?_,?_⟩ + · intro x hx y hy + exact h (.inl x) (by simpa) (.inl y) (by simpa) + · intro x hx y hy + exact h (.inr x) (by simpa) (.inr y) (by simpa) + · intro x hx y hy + exact h (.inl x) (by simpa) (.inr y) (by simpa) + · rintro ⟨hs,ht,hst⟩ x hx y hy + cases x with + | inl x => + cases y with + | inl y => exact hs x (by simpa using hx) y (by simpa using hy) + | inr y => exact hst x (by simpa using hx) y (by simpa using hy) + | inr x => + cases y with + | inl y => + have H:=alternating_skew Ω hΩ (w x) (u y) + rw [hst y (by simpa using hy) x (by simpa using hx)] at H + simpa using H + | inr y => exact ht x (by simpa using hx) y (by simpa using hy) + +lemma sum_labels_disjSum (u : V → M) (w : W → M) (s : Finset V) (t : Finset W) : + (∑ x ∈ s.disjSum t,Sum.elim u w x)=(∑x∈s,u x)+(∑y∈t,w y) := by + simp + +lemma independent_sum_decomposition [Fintype V] [DecidableEq V] + [Fintype W] [DecidableEq W] (u : V → M) (w : W → M) (k : ℕ) : + independentElement v Ω (Sum.elim u w) k = + ∑ t : Finset W,∑ s : Finset V, independentTerm v Ω (Sum.elim u w) k (s.disjSum t) := by + unfold independentElement + rw [←Equiv.sum_comp (Finset.sumEquiv : Finset (V⊕W) ≃o Finset V×Finset W).symm.toEquiv] + simp only [Fintype.sum_prod_type] + rw [Finset.sum_comm] + rfl + +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +open Classical +noncomputable section +variable {K M W : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) + +abbrev Compatible (a : M) (w : W → M) (t : Finset W) : Prop := + ∀ y∈t,Ω a (w y)=0 + +lemma compatible_add (a b : M) (w : W → M) (t : Finset W) + (hb : Compatible Ω b w t) : Compatible Ω (a+b) w t ↔ Compatible Ω a w t := by + unfold Compatible at * + simp only [map_add,AddMonoidHom.add_apply] + constructor <;> intro h y hy + · have H:=h y hy + simpa only [hb y hy,add_zero] using H + · simpa only [hb y hy,add_zero] using h y hy + +lemma finset_fin_three : (Finset.univ : Finset (Finset (Fin 3))) = + {∅,{0},{1},{2},{0,1},{0,2},{1,2},{0,1,2}} := by decide + +lemma independent_triple_sum [DecidableEq W] + (hΩ : ∀m,Ω m m=0) (a b c : M) + (hab : Ω a b≠0) (hbc : Ω b c≠0) (hac : Ω a c=0) + (w : W → M) (t : Finset W) (k : ℕ) : + (∑ s : Finset (Fin 3), + independentTerm v Ω (Sum.elim ![a,b,c] w) k (s.disjSum t)) = + if IsIndependent Ω w t then + (if t.card=k then Torus.X v Ω (∑y∈t,w y) else 0) + + (if t.card+1=k ∧ Compatible Ω a w t then Torus.X v Ω (a+∑y∈t,w y) else 0) + + (if t.card+1=k ∧ Compatible Ω b w t then Torus.X v Ω (b+∑y∈t,w y) else 0) + + (if t.card+1=k ∧ Compatible Ω c w t then Torus.X v Ω (c+∑y∈t,w y) else 0) + + (if t.card+2=k ∧ Compatible Ω a w t ∧ Compatible Ω c w t then + Torus.X v Ω (a+c+∑y∈t,w y) else 0) + else 0 := by + have hca : Ω c a=0 := by rw [alternating_skew Ω hΩ c a,hac,neg_zero] + rw [finset_fin_three] + simp (disch := decide) only [Finset.sum_insert,Finset.sum_singleton] + simp only [independentTerm,independent_sum_iff Ω hΩ,Finset.card_disjSum, + setMonomial,sum_labels_disjSum] + by_cases H : IsIndependent Ω w t + all_goals + simp only [IsIndependent] at H + simp [IsIndependent,Compatible,hΩ,hab,hbc,hac,hca,H, + and_assoc,and_comm,Nat.add_comm,add_assoc] + simp only [iff_true_intro H,and_true,ite_true] + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndexedUnit.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndexedUnit.lean new file mode 100644 index 0000000000000000000000000000000000000000..b49e5b3841f3af96c4a5c957b66b3439378717aa --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/IndexedUnit.lean @@ -0,0 +1,48 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SignedMultiplicity +import OAI.Combinatorics.Chromatic.GradedAlgebra.CompleteUnit + +namespace OAI + +section +section +namespace ElementaryPositivity.UnitSelections +open EnergyLaurent WallUnits PowerSeries +open scoped LaurentSeries +noncomputable section + +def strictUnitEquiv (a n : ℕ) (h : a=0) : Strict n ≃ UnitIndex a n := + Equiv.subtypeEquivRight (fun f=>by simp only [ite_eq_left h]) + +def weakUnitEquivSame (a n : ℕ) (h : a≠0) : Weak n ≃ UnitIndex a n := + Equiv.subtypeEquivRight (fun f=>by simp only [ite_eq_right h]) + +lemma unitAdmissible (a n : ℕ) (k : ℤ) : Admissible (unitEnergy a n k) := by + by_cases h : a=0 + · exact admissible_equiv (strictAdmissible n k) (strictUnitEquiv a n h) (fun _=>rfl) + · exact admissible_equiv (weakAdmissible n k) (weakUnitEquivSame a n h) (fun _=>rfl) + +def indexedUnitSeries (a n : ℕ) (k : ℤ) : LaurentSeries ℚ := + series (unitEnergy a n k) (unitAdmissible a n k) + +def indexedUnit (a : ℕ) (k : ℤ) : PowerSeries (RatFunc ℚ) := + if a=0 then elementary RationalRay.q (RationalRay.v^k) + else complete RationalRay.q (RationalRay.v^k) + +theorem indexedUnit_literal_expansion (a n : ℕ) (k : ℤ) : + LaurentRay.atInfinity (coeff n (indexedUnit a k))=indexedUnitSeries a n k := by + unfold indexedUnit + by_cases h : a=0 + · rw [ite_eq_left h,elementary_literal_expansion] + exact series_equiv (strictAdmissible n k) (unitAdmissible a n k) + (strictUnitEquiv a n h) (fun _=>rfl) + · rw [ite_eq_right h,complete_literal_expansion] + exact series_equiv (weakAdmissible n k) (unitAdmissible a n k) + (weakUnitEquivSame a n h) (fun _=>rfl) + +end +end ElementaryPositivity.UnitSelections +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/InfinityExpansionFaithful.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/InfinityExpansionFaithful.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8d57112ce750eeba73c9db77e6fc197d6a60108 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/InfinityExpansionFaithful.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteFiberInfinity +import OAI.Combinatorics.Chromatic.Walls.CompletedInfinityCut + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +lemma expandFiberInfinity_monomial_coeff (l : k.ker) (a : RatFunc K) (n : ℤ) : + (expandFiberInfinity v Ω hΩ k p (FiberTorus.monomial v _ _ l a)).coeff n= + Torus.monomial v Ω (n • (-p)+(l:M)) ((expandInfinity a).coeff n*(↑(v^(n*Ω (-p) l)):K)) := by + change (expandFiber v Ω hΩ k (-p) (fiberReciprocalAdd v (complementOmega k Ω) + (complementAlpha k p Ω) (complementAlpha k (-p) Ω) (FiberTorus.monomial v _ _ l a))).coeff n=_ + rw [fiberReciprocalAdd_monomial,expandFiber_monomial_coeff] + rfl + +lemma expandFiberInfinity_read_monomial (m : M) (l : k.ker) (a : RatFunc K) : + ((expandFiberInfinity v Ω hΩ k p (FiberTorus.monomial v _ _ l a)).coeff (-k m)) m= + readFiberInfinity v Ω k p hp m (FiberTorus.monomial v _ _ l a) := by + classical + rw [expandFiberInfinity_monomial_coeff] + simp only [neg_smul,smul_neg,neg_neg,map_neg,AddMonoidHom.neg_apply,neg_mul_neg] + change Finsupp.single (k m • p+(l:M)) + ((expandInfinity a).coeff (-k m)*(↑(v^(k m*Ω p l)):K)) m= + (expandInfinity ((Finsupp.single l a) (off k p hp m))).coeff (-k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K) + by_cases H : l=off k p hp m + · subst l + rw [split_sum k p hp,Finsupp.single_eq_same,Finsupp.single_eq_same] + rfl + · have hm : k m • p+(l:M)≠m:=by + intro hh + have HO:=congrArg (off k p hp) hh + simp only [map_add,map_zsmul,off_p,smul_zero,off_complement,zero_add] at HO + exact H HO + rw [Finsupp.single_eq_of_ne (Ne.symm hm),Finsupp.single_eq_of_ne (Ne.symm H),map_zero, + HahnSeries.coeff_zero,zero_mul] +lemma expandFiberInfinity_read (f : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) (m : M) : + ((expandFiberInfinity v Ω hΩ k p f).coeff (-k m)) m=readFiberInfinity v Ω k p hp m f := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [_root_.map_add,HahnSeries.coeff_add,Finsupp.add_apply,hf,hg] + | single l a=>exact expandFiberInfinity_read_monomial v Ω hΩ k p hp m l a + +lemma readFiberInfinity_ext {f g : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)} + (h : ∀m,readFiberInfinity v Ω k p hp m f=readFiberInfinity v Ω k p hp m g) : f=g := by + apply Finsupp.ext + intro l + apply expandInfinity_injective + apply HahnSeries.ext + funext n + have H:=h ((-n) • p+(l:M)) + change (expandInfinity (f (off k p hp ((-n) • p+(l:M))))).coeff (-k ((-n) • p+(l:M)))* + (↑(v^(k ((-n) • p+(l:M))*complementAlpha k p Ω (off k p hp ((-n) • p+(l:M))))):K)= + (expandInfinity (g (off k p hp ((-n) • p+(l:M))))).coeff (-k ((-n) • p+(l:M)))* + (↑(v^(k ((-n) • p+(l:M))*complementAlpha k p Ω (off k p hp ((-n) • p+(l:M))))):K) at H + have hl : k (l:M)=0:=l.property + simp only [map_add,map_zsmul,off_p,smul_zero,off_complement,zero_add,hp, + smul_eq_mul,mul_one,hl,add_zero,neg_neg] at H + exact mul_right_cancel₀ (Units.ne_zero _) H + +include hp in +lemma expandFiberInfinity_injective : Function.Injective (expandFiberInfinity v Ω hΩ k p) := by + intro f g h + apply readFiberInfinity_ext v Ω k p hp + intro m + rw [←expandFiberInfinity_read v Ω hΩ k p hp f m,←expandFiberInfinity_read v Ω hΩ k p hp g m,h] +include hp in +lemma completed_expandFiberInfinity_injective : + Function.Injective (PowerSeries.map (expandFiberInfinity v Ω hΩ k p)) := by + intro f g h + apply PowerSeries.ext + intro d + apply expandFiberInfinity_injective v Ω hΩ k p hp + have H:=congrArg (PowerSeries.coeff d) h + simpa only [PowerSeries.coeff_map] using H +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/InfinityUnitAlgebra.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/InfinityUnitAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a0c4799b9ee29b949e4131c872805e305277cca --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/InfinityUnitAlgebra.lean @@ -0,0 +1,38 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplitLeading +import OAI.Combinatorics.Chromatic.Walls.CompletedPureComparison + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {A B : Type*} [Ring A] [Ring B] + +lemma innerHom_foldr (l : List Bˣ) (x : B) : + l.foldr (fun u y=>innerHom u y) x=innerHom l.prod x := by + induction l with + | nil=>simp only [List.foldr_nil,List.prod_nil,innerHom_one] + | cons a l ih=>simp only [List.foldr_cons,List.prod_cons,ih,innerHom_mul] + +lemma mapped_unit_square (F : A →+* B) (u : Aˣ) (w : Bˣ) + (h : F u.val=w.val) (x : A) : innerHom w (F x)=F (innerHom u x) := by + have H : Units.map F u=w := Units.ext h + rw [map_innerHom,H] + +lemma coeff_commute_of_adjoints (u : (PowerSeries B)ˣ) (x : PowerSeries B) (D : ℕ) + (h : ∀d≤D,coeff d (innerHom u x)=coeff d x) : + coeff D (u.val*x)=coeff D (x*u.val) := by + have H : coeff D (innerHom u x*u.val)=coeff D (x*u.val) := by + apply ElementaryPositivity.FormalLog.mul_coeff_congr + · exact h + · exact fun _ _=>rfl + change coeff D (((u.val*x)*u.inv)*u.val)=coeff D (x*u.val) at H + simpa only [mul_assoc,u.inv_val,mul_one] using H +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/LatticeHahn.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/LatticeHahn.lean new file mode 100644 index 0000000000000000000000000000000000000000..80b9b65cc66ef4c9a59c292d98dad5d3f9907a19 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/LatticeHahn.lean @@ -0,0 +1,66 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentHomogenize +import OAI.Combinatorics.Chromatic.Walls.CompletedInverse + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries HahnSeries PowerSeriesAdjoint +noncomputable section +variable {R M:Type*} [CommRing R] [AddCommGroup M] +variable (v:Rˣ) (Ω:M →+ M →+ ℤ) (τ:M →+ ℤ) +local instance latticeHahnRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance latticeHahnAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance latticeHahnAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance latticeHahnNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance latticeHahnNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +def latticeHahn : Torus v Ω →+* HahnSeries ℤ (Torus v Ω) where + toFun F:=constantCoeff (laurentHomogenize v Ω 0 τ F) + map_zero':=by simp + map_add' F G:=by rw [_root_.map_add,_root_.map_add] + map_one':=by rw [laurentHomogenize_one,map_one] + map_mul' F G:=by rw [laurentHomogenize_mul v Ω 0 τ F G (by simp) (by simp),map_mul] + +lemma latticeHahn_monomial (b:M) (c:R) : + latticeHahn v Ω τ (Torus.monomial v Ω b c)= + HahnSeries.single (τ b) (Torus.monomial v Ω b c) := by + change constantCoeff (laurentHomogenize v Ω 0 τ (Torus.monomial v Ω b c))=_ + rw [laurentHomogenize_monomial] + simp only [AddMonoidHom.zero_apply,Int.toNat_zero,monomial_zero_eq_C_apply,constantCoeff_C] + +lemma latticeHahn_coeff (F:Torus v Ω) (j:ℤ) (m:M) : + (latticeHahn v Ω τ F).coeff j m=if j=τ m then F m else 0 := by + change (constantCoeff (laurentHomogenize v Ω 0 τ F)).coeff j m=_ + rw [←coeff_zero_eq_constantCoeff,laurentHomogenize_coeff] + simp + +lemma latticeHahn_injective : Function.Injective (latticeHahn v Ω τ) := by + intro f g h + apply Finsupp.ext + intro m + have H:=congrArg (fun f:HahnSeries ℤ (Torus v Ω)=>f.coeff (τ m) m) h + simpa only [latticeHahn_coeff,ite_true] using H + +lemma hahn_single_shift_adjoint (f:PowerSeries (Torus v Ω)) (j:ℤ) (F:Torus v Ω) : + HahnSeries.ofPowerSeries ℤ (Torus v Ω) f * HahnSeries.single j F * + HahnSeries.ofPowerSeries ℤ (Torus v Ω) (invOfUnit f 1)= + HahnSeries.single j (1:Torus v Ω)* + HahnSeries.ofPowerSeries ℤ (Torus v Ω) (adjoint f (PowerSeries.C F)) := by + have H (g:HahnSeries ℤ (Torus v Ω)): + g*HahnSeries.single j (1:Torus v Ω)=HahnSeries.single j (1:Torus v Ω)*g:=by + apply HahnSeries.ext + funext n + rw [HahnSeries.coeff_mul_single,HahnSeries.coeff_single_mul,mul_one,one_mul] + rw [adjoint,map_mul,map_mul,HahnSeries.ofPowerSeries_C] + have HS:HahnSeries.single j F=HahnSeries.single j (1:Torus v Ω)*HahnSeries.C F:=by + change HahnSeries.single j F=HahnSeries.single j (1:Torus v Ω)*HahnSeries.single 0 F + rw [HahnSeries.single_mul_single,add_zero,one_mul] + rw [HS,←mul_assoc,H, mul_assoc,mul_assoc,mul_assoc] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MonomialConjugation.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MonomialConjugation.lean new file mode 100644 index 0000000000000000000000000000000000000000..2331f6add7132729558855b7dc5cd0e5e65a77f4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MonomialConjugation.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RationalPureCoefficients +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegradeFaithful + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {K M:Type*} [Field K] [AddCommGroup M] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +local instance monomialConjugationRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance monomialConjugationAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance monomialConjugationAddGroup : AddGroup (Torus v Ω) := + (Torus.instRing v Ω).toAddGroup + +include hΩ +lemma X_mul_X_neg (b:M) : Torus.X v Ω b*Torus.X v Ω (-b)=1 := by + rw [Torus.X_mul_X_of_pairing_zero v Ω b (-b) (by simp only [map_neg,hΩ,neg_zero])] + simp only [add_neg_cancel] + rfl + +def monomialConjugate (b:M) (f:PowerSeries (Torus v Ω)) : PowerSeries (Torus v Ω):= + PowerSeries.C (Torus.X v Ω b)*f*PowerSeries.C (Torus.X v Ω (-b)) + +lemma monomialConjugate_coeff (b:M) (f:PowerSeries (Torus v Ω)) (n:ℕ) (r:M) : + coeff n (monomialConjugate v Ω b f) r=coeff n f r*(↑(v^(2*Ω b r)):K) := by + rw [monomialConjugate,coeff_mul_C,coeff_C_mul] + have H:=mul_X_coeff v Ω (Torus.X v Ω b*coeff n f) (r+b) (-b) + rw [add_neg_cancel_right,X_mul_coeff] at H + rw [H,map_add,AddMonoidHom.add_apply,map_neg,map_neg,hΩ,neg_zero,add_zero, + alternating_skew Ω hΩ r b,neg_neg,mul_assoc,←Units.val_mul,←zpow_add] + congr 3 + ring + +lemma monomialConjugate_coeff_ne_iff (b:M) (f:PowerSeries (Torus v Ω)) (n:ℕ) (r:M) : + coeff n (monomialConjugate v Ω b f) r≠0 ↔ coeff n f r≠0 := by + rw [monomialConjugate_coeff v Ω hΩ] + exact mul_ne_zero_iff.trans (and_iff_left (Units.ne_zero _)) + +lemma monomialConjugate_one (b:M) : monomialConjugate v Ω b 1=1 := by + rw [monomialConjugate,mul_one,←map_mul,X_mul_X_neg v Ω hΩ,map_one] + +lemma monomialConjugate_mul (b:M) (f g:PowerSeries (Torus v Ω)) : + monomialConjugate v Ω b (f*g)=monomialConjugate v Ω b f*monomialConjugate v Ω b g := by + have H:PowerSeries.C (Torus.X v Ω (-b))*PowerSeries.C (Torus.X v Ω b)= + (1:PowerSeries (Torus v Ω)):=by + rw [←map_mul] + simpa only [neg_neg,map_one] using congrArg + (PowerSeries.C : Torus v Ω → PowerSeries (Torus v Ω)) (X_mul_X_neg v Ω hΩ (-b)) + simp only [monomialConjugate] + calc + _=PowerSeries.C (Torus.X v Ω b)*f*1*g*PowerSeries.C (Torus.X v Ω (-b)):=by simp only [mul_one,mul_assoc] + _= _ :=by rw [←H]; simp only [mul_assoc] + +lemma monomialConjugate_regradeBound (b:M) (δ:M →+ ℤ) (B:ℕ) {f:PowerSeries (Torus v Ω)} + (hf:RegradeBound v Ω δ B f) : RegradeBound v Ω δ B (monomialConjugate v Ω b f) := by + intro n m hm + exact hf n m ((monomialConjugate_coeff_ne_iff v Ω hΩ b f n m).mp hm) + +lemma regrade_monomialConjugate (b:M) (δ:M →+ ℤ) (B:ℕ) (f:PowerSeries (Torus v Ω)) : + regrade v Ω δ B (monomialConjugate v Ω b f)= + monomialConjugate v Ω b (regrade v Ω δ B f) := by + classical + apply PowerSeries.ext + intro d + ext r + rw [regrade_coeff_eval,monomialConjugate_coeff v Ω hΩ,regrade_coeff_eval] + split_ifs + · simp only [monomialConjugate_coeff v Ω hΩ,Finset.sum_mul] + · rw [zero_mul] + +end +end ElementaryPositivity.QuantumTorus +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] +variable (v:(LaurentSeries ℚ)ˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +include hΩ in +lemma monomialConjugate_graded (C:(I → ℤ) →+ M) (b:M) {f:PowerSeries (Torus v Ω)} + (hf:SeriesGraded v Ω C f) : SeriesGraded v Ω C (monomialConjugate v Ω b f) := by + intro n m hm + rw [monomialConjugate_coeff v Ω hΩ,hf n m hm,zero_mul] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedCanonicalCharts.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedCanonicalCharts.lean new file mode 100644 index 0000000000000000000000000000000000000000..267291f84f67a4f5ceb7f35950c806f93950863c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedCanonicalCharts.lean @@ -0,0 +1,84 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutatedEndpoint + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +include hnd in +lemma mutatedTransport_chart_three (N : ℕ) (h : M →+ ℝ) + {a b x y : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (HX : RegularCovector C e x) (HY : RegularCovector C e y) + (hA : ∀n,n+1≤N → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → + 0h m<0) (fun u w hu hw=>by simpa only [map_add] using add_neg hu hw) N HA HX + (by intro n hn m hm hh; exact Or.inl ⟨hA n hn m hm,(hX n hn m hm).2 (le_of_not_gt hh)⟩) + have ha:=mutatedTransport_endpoint_support Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd + (fun m=>0by simpa only [map_add] using add_pos hu hw) N HY HB + (by intro n hn m hm hh; exact Or.inr ⟨(hY n hn m hm).2 (le_of_not_gt hh),hB n hn m hm⟩) + have hb:=mutatedTransport_endpoint_support Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd + (fun m=>h m=0) (fun u w hu hw=>by rw [map_add,hu,hw,add_zero]) N HX HY + (by + intro n hn m hm hh + rcases lt_or_gt_of_ne hh with hp|hp + · exact Or.inr ⟨(hX n hn m hm).1 hp,(hY n hn m hm).2 hp.le⟩ + · exact Or.inl ⟨(hX n hn m hm).2 hp.le,(hY n hn m hm).1 hp⟩) + apply chart_three_truncated_unique LaurentRay.vUnit Ω (mutatedRoots Ω C pc) h + (T a b HA HB) (T y b HY HB).val (T x y HX HY).val (T a x HA HX).val N + (T y b HY HB).property.1 (T x y HX HY).property.1 (T a x HA HX).property.1 + · have h1:=mutatedTransport_trans Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd HA HX HY + have h2:=mutatedTransport_trans Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd HA HY HB + dsimp [T] + rw [mul_assoc,←h1,←h2] + · intro n hn m hm + by_contra hh + exact hm (ha n hn m hh) + · intro n hn m hm + by_contra hh + exact hm (hb n hn m hh) + · intro n hn m hm + by_contra hh + exact hm (hc n hn m hh) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedNegativeCharts.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedNegativeCharts.lean new file mode 100644 index 0000000000000000000000000000000000000000..dee6280b10c517070d48988e031ec8b6d5ef9722 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedNegativeCharts.lean @@ -0,0 +1,117 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedHalfspaceTransport +import OAI.Combinatorics.Chromatic.QuantumTorus.MutatedCanonicalCharts +import OAI.Combinatorics.Chromatic.Walls.IncomingTransportTrace + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +include hnd in +lemma mutatedTransport_chartNegative (N : ℕ) {a b x : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) (HX : RegularCovector C e x) + (hA : ∀n,n+1≤N → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → + 0lt_of_le_of_ne hh (Ne.symm (hx j hj m hm))⟩) + (by intro j hj m hm; exact ⟨id,fun hh=>lt_of_le_of_ne hh (hx j hj m hm)⟩) + n hn).2.2 + +include hnd in +lemma mutatedTransport_negative_ratio (N : ℕ) {a b x y : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (HX : RegularCovector C e x) (HY : RegularCovector C e y) + (hA : ∀n,n+1≤N → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → + 0Hy j (hj.trans hn)) (fun j hj=>Hi j (hj.trans hn)) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry RationalFiber +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) +include hnd in +lemma mutatedTransport_nocut (pos : Bool) {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (ha : cutSide pos (a.toAddMonoidHom.comp e) (simpleRoot C pc)) + (hb : cutSide pos (b.toAddMonoidHom.comp e) (simpleRoot C pc)) : + RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) + (negativeCovectorUnit Ω C coord hcoord pc e b* + (negativeCovectorUnit Ω C coord hcoord pc e a)⁻¹).val.val ∧ + (mutatedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HB).val= + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit + (negativeCovectorUnit Ω C coord hcoord pc e b* + (negativeCovectorUnit Ω C coord hcoord pc e a)⁻¹).val.val := by + obtain ⟨p,hp⟩:=generic_path_exists_onCutSide C pc e pos a b HA HB ha hb + obtain ⟨hbound,heq⟩:=mutatedPathCompletion_nocut Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg pos p hp + exact ⟨hbound,(mutatedTransport_eq_path Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd HA HB p).trans heq⟩ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedSystemIdentification.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedSystemIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..d589e470268a44e66245db472e8551c05d6c5daa --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutatedSystemIdentification.lean @@ -0,0 +1,126 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedIncomingNonpureRoot + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd:∀r≠0,∃m,Ω r m≠0) +include hnd in +lemma mutatedTransport_eq_simple + (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (hA:∀n,0e (simpleRoot C i))) (N:ℕ) + {x y:Module.Dual ℝ E} (HX:RegularCovector C e x) (HY:RegularCovector C e y) + (hx:∀n,n+1≤N → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → + realMutationCovector e S (simpleRoot C pc) x (e m)≠0) + (hy:∀n,n+1≤N → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → + realMutationCovector e S (simpleRoot C pc) y (e m)≠0) : + ∀n≤N,coeff n (mutatedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HX HY).val= + coeff n ((chartNegative LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + ((realMutationCovector e S (simpleRoot C pc) y).toAddMonoidHom.comp e) + (simpleTotalTransport Ω (mutatedRoots Ω C pc))).val * + invOfUnit (chartNegative LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + ((realMutationCovector e S (simpleRoot C pc) x).toAddMonoidHom.comp e) + (simpleTotalTransport Ω (mutatedRoots Ω C pc))).val 1) := by + obtain ⟨a,b,HA,HB,hA,hB⟩:=mutated_regular_anchors Ω C pc e S hS hC + have H:=mutatedTransport_negative_ratio Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd + N HA HB HX HY (fun n _ m hm=>hA _ (by omega) m hm) + (fun n _ m hm=>hB _ (by omega) m hm) hx hy + rw [mutatedTransport_eq_simple Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd hC HA HB hA hB] at H + exact H +include hnd in +lemma mutatedTransport_canonical + (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + {x y:Module.Dual ℝ E} (HX:RegularCovector C e x) (HY:RegularCovector C e y) + (hx:∀n,0hx _ (by omega) m hm) + (fun j _ m hm=>hy _ (by omega) m hm) n le_rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutationConvexSigns.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutationConvexSigns.lean new file mode 100644 index 0000000000000000000000000000000000000000..92b202ad160b2a7e02611c2021fdd3cccd87bf52 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutationConvexSigns.lean @@ -0,0 +1,110 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.GeometricMutation + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] +variable (e : M →+ E) (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (p : M) + +def realShearVector (x : E) : E := x+S (e p) x • e p +lemma realShearCovector_eval (h : Module.Dual ℝ E) (x : E) : + realShearCovector e S p h x=h (realShearVector e S p x) := by + simp only [realShearCovector,realShearVector,LinearMap.add_apply,LinearMap.smul_apply, + map_add,map_smul,smul_eq_mul] + ring + +lemma mutated_pos_of_nonneg (h : Module.Dual ℝ E) (x : E) (hc : 0≤S (e p) x) : + 0⟨hh,lt_of_lt_of_le hh (le_add_of_nonneg_right (mul_nonneg hp hc))⟩,And.left⟩ + · rw [heq,hw] + have hm : h (e p)*S (e p) x≤0:=mul_nonpos_of_nonpos_of_nonneg (le_of_lt (lt_of_not_ge hp)) hc + exact ⟨fun hh=>⟨by linarith,hh⟩,And.right⟩ + +lemma mutated_pos_of_nonpos (h : Module.Dual ℝ E) (x : E) (hc : S (e p) x≤0) : + 0 linarith + · rw [heq,hw] + have hm : 0≤h (e p)*S (e p) x:=mul_nonneg_of_nonpos_of_nonpos (le_of_lt (lt_of_not_ge hp)) hc + constructor + · exact Or.inr + · rintro (hh|hh) <;> linarith + +lemma real_convex_pos (a b t : ℝ) (ha : 0Ω (simpleRoot C pc) (simpleRoot C i) +include hcoord in +lemma root_simple_expansion {n : ℕ} {m : M} (hm : HasRootDegree C n m) : + m=∑i,(coord m i) • simpleRoot C i := by + obtain ⟨d,hd,hc,he⟩:=root_coordinates C coord hcoord hm + have hsplit : (fun i=>(d i:ℤ))=∑i,((d i:ℤ) • (Pi.single i 1 : I → ℤ)) := by + ext j + simp only [Finset.sum_apply,Pi.smul_apply,smul_eq_mul] + rw [Finset.sum_eq_single j] + · simp + · intro i hi hij; simp [Ne.symm hij] + · simp + calc + m=∑i,(d i:ℤ) • simpleRoot C i:=by + rw [←he,hsplit,map_sum] + simp only [map_zsmul,simpleRoot] + _=∑i,coord m i • simpleRoot C i:=by simp only [hc] +include hcoord in +lemma root_pairing_coordinates (hΩ : ∀m,Ω m m=0) {n : ℕ} {m : M} + (hm : HasRootDegree C n m) : + Ω (simpleRoot C pc) m=∑i∈Finset.univ.erase pc,mutationPairing Ω C pc i*coord m i := by + have HH:=congrArg (Ω (simpleRoot C pc)) (root_simple_expansion C coord hcoord hm) + rw [map_sum] at HH + simp only [map_zsmul,smul_eq_mul] at HH + rw [←Finset.sum_erase_add _ _ (Finset.mem_univ pc)] at HH + simp only [hΩ,mul_zero,add_zero] at HH + rw [HH] + apply Finset.sum_congr (by ext i; simp) + intro i hi + exact mul_comm _ _ +lemma max_zero_neg (a : ℤ) : max 0 a=max 0 (-a)+a := by + by_cases ha : 0≤a + · rw [max_eq_right ha,max_eq_left (by omega)]; omega + · rw [max_eq_left (by omega),max_eq_right (by omega)]; omega +lemma fiberUpper_flip (α : I → ℤ) (σ : ℤ) (m : M) : + fiberUpper coord pc α (-σ) m=fiberUpper coord pc α σ m+ + σ*(∑i∈Finset.univ.erase pc,α i*coord m i) := by + change (∑i∈Finset.univ.erase pc,max 0 (-(-σ)*α i)*coord m i)= + (∑i∈Finset.univ.erase pc,max 0 (-σ*α i)*coord m i)+σ*(∑i∈Finset.univ.erase pc,α i*coord m i) + rw [Finset.mul_sum,←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i hi + rw [neg_neg,max_zero_neg] + have he : -(σ*α i)= -σ*α i:=by ring + rw [he] + ring +include hcoord in +lemma fiberUpper_simple (α : I → ℤ) (σ : ℤ) : fiberUpper coord pc α σ (simpleRoot C pc)=0 := by + change (∑i∈Finset.univ.erase pc,max 0 (-σ*α i)*coord (simpleRoot C pc) i)=0 + apply Finset.sum_eq_zero + intro i hi + rw [simpleRoot_coordinates C coord hcoord] + simp [(Finset.mem_erase.mp hi).1] +include hcoord in +lemma fiber_shift_bound (hΩ : ∀m,Ω m m=0) {n : ℕ} {m : M} (hm : HasRootDegree C n m) + (σ : ℤ) (j : ℕ) (hj : (j:ℤ)≤σ*Ω (simpleRoot C pc) m) + (hP : m∈fiberCone coord pc (mutationPairing Ω C pc) σ) : + m+j • simpleRoot C pc∈fiberCone coord pc (mutationPairing Ω C pc) (-σ) := by + have hc : coord (m+j • simpleRoot C pc) pc=coord m pc+(j:ℤ):=by + simp only [map_add,map_nsmul,Pi.add_apply,Pi.smul_apply] + rw [simpleRoot_coordinates C coord hcoord] + simp + have hu : fiberUpper coord pc (mutationPairing Ω C pc) (-σ) (m+j • simpleRoot C pc)= + fiberUpper coord pc (mutationPairing Ω C pc) σ m+σ*Ω (simpleRoot C pc) m:=by + rw [map_add,map_nsmul,fiberUpper_simple C coord hcoord,nsmul_zero,add_zero,fiberUpper_flip, + ←root_pairing_coordinates Ω C coord hcoord pc hΩ hm] + change 0≤coord (m+j • simpleRoot C pc) pc ∧ + coord (m+j • simpleRoot C pc) pc≤fiberUpper coord pc (mutationPairing Ω C pc) (-σ) (m+j • simpleRoot C pc) + rw [hc,hu] + exact ⟨add_nonneg hP.1 (Int.natCast_nonneg j),add_le_add hP.2 hj⟩ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutationInfinityBound.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutationInfinityBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a7e6e0d6e2432a6df93fd6b0e5d20a1d347a38a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/MutationInfinityBound.lean @@ -0,0 +1,49 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationDegreeBound +import OAI.Combinatorics.Chromatic.Walls.LaurentCompletion + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +include hcoord in +lemma mutation_infinity_lower_bound {n : ℕ} {m : M} + (hm : HasRootDegree (mutatedRoots Ω C pc) n m) : + -(mutationSize Ω C pc:ℤ)*nonpDegree (mutatedCoordinates Ω C coord pc) pc m ≤ + -pureDegree coord pc m := by + obtain ⟨d,hd,hc,hC⟩:=root_coordinates (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) hm + have hn (i : I) : 0 ≤ mutatedCoordinates Ω C coord pc m i := by + rw [hc] + exact Int.natCast_nonneg _ + have hs : (∑i∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc i)* + mutatedCoordinates Ω C coord pc m i) ≤ + (mutationSize Ω C pc:ℤ)*nonpDegree (mutatedCoordinates Ω C coord pc) pc m := by + change _ ≤ (mutationSize Ω C pc:ℤ)*(∑i∈Finset.univ.erase pc, + mutatedCoordinates Ω C coord pc m i) + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro i hi + apply mul_le_mul_of_nonneg_right _ (hn i) + exact (max_le (abs_nonneg _) (neg_le_abs _)).trans + (mutationSize_bound Ω C pc i (Finset.mem_erase.mp hi).1) + have hk : pureDegree coord pc m = -mutatedCoordinates Ω C coord pc m pc+ + ∑i∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc i)* + mutatedCoordinates Ω C coord pc m i := by + have H:=congrArg (fun f : I → ℤ => f pc) + (mutatedCoefficientMap_involutive pc (mutationPairing Ω C pc) (coord m)) + rw [mutatedCoefficientMap_at] at H + exact H.symm + have hp:=hn pc + nlinarith +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NearCutGeometry.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NearCutGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..a75125b882451f84ad8bd5199ca3a19a30a09fdd --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NearCutGeometry.lean @@ -0,0 +1,170 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedAnchors +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousElementaryExpressions +import OAI.Combinatorics.Chromatic.QuantumTorus.CovectorPrescriptions +import OAI.Combinatorics.Chromatic.Walls.GenericAffineProbes + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) (pc:I) (e:M →+ E) + +omit [FiniteDimensional ℝ E] in +lemma nearCut_convex {a b:Module.Dual ℝ E} (ha:NearCut Ω C pc e a) (hb:NearCut Ω C pc e b) + (t:ℝ) (ht:0≤t) (ht':t≤1) : NearCut Ω C pc e ((1-t) • a+t • b) := by + by_cases ht1:t=1 + · subst t + simpa using hb + have htt:0<1-t:=sub_pos.mpr (lt_of_le_of_ne ht' ht1) + constructor + · rw [LinearMap.add_apply,LinearMap.smul_apply,LinearMap.smul_apply,smul_eq_mul,smul_eq_mul] + have A:=abs_lt.mp ha.1 + have B:=abs_lt.mp hb.1 + apply abs_lt.mpr + constructor + · nlinarith [mul_pos htt (sub_pos.mpr A.1),mul_nonneg ht (sub_nonneg.mpr B.1.le)] + · nlinarith [mul_pos htt (sub_pos.mpr A.2),mul_nonneg ht (sub_nonneg.mpr B.2.le)] + · intro i hi + simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] + nlinarith [mul_pos htt (sub_pos.mpr (ha.2 i hi)), + mul_nonneg ht (sub_nonneg.mpr (hb.2 i hi).le)] + +def nearCutProbes : Finset (ℝ×E) := by + classical + exact (Finset.univ.erase pc).image (fun i=>(1,e (simpleRoot C i))) ∪ + {(-1/((mutationSize Ω C pc:ℝ)+1),e (simpleRoot C pc)), + (1/((mutationSize Ω C pc:ℝ)+1),e (simpleRoot C pc))} + +omit [FiniteDimensional ℝ E] in +lemma nearCut_of_probes (J k h:Module.Dual ℝ E) (hJ:∀i,J (e (simpleRoot C i))=1) + (hk:NearCut Ω C pc e k) + (hh:∀x∈nearCutProbes Ω C pc e, + (0<(k+x.1 • J) x.2 → 0<(h+x.1 • J) x.2) ∧ + ((k+x.1 • J) x.2<0 → (h+x.1 • J) x.2<0)) : NearCut Ω C pc e h := by + classical + have Hp: (1/((mutationSize Ω C pc:ℝ)+1),e (simpleRoot C pc))∈nearCutProbes Ω C pc e:=by + simp [nearCutProbes] + have Hn: (-1/((mutationSize Ω C pc:ℝ)+1),e (simpleRoot C pc))∈nearCutProbes Ω C pc e:=by + simp [nearCutProbes] + have Hk:=abs_lt.mp hk.1 + constructor + · apply abs_lt.mpr + have A:0<(h+(1/((mutationSize Ω C pc:ℝ)+1)) • J) (e (simpleRoot C pc)):=by + apply (hh _ Hp).1 + simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul,hJ,mul_one] + linarith + have B:(h+(-1/((mutationSize Ω C pc:ℝ)+1)) • J) (e (simpleRoot C pc))<0:=by + apply (hh _ Hn).2 + simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul,hJ,mul_one,neg_div] + linarith + simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul,hJ,mul_one,neg_div] at A B + constructor <;> linarith + · intro i hi + have Hi:(1,e (simpleRoot C i))∈nearCutProbes Ω C pc e:=by + exact Finset.mem_union_left _ (Finset.mem_image.mpr ⟨i,Finset.mem_erase.mpr ⟨hi,Finset.mem_univ i⟩,rfl⟩) + have A:(h+(1:ℝ) • J) (e (simpleRoot C i))<0:=by + apply (hh _ Hi).2 + simp only [one_smul,LinearMap.add_apply,hJ] + linarith [hk.2 i hi] + simp only [one_smul,LinearMap.add_apply,hJ] at A + linarith + +lemma nearCut_path (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (ha:NearCut Ω C pc e a) (hb:NearCut Ω C pc e b) : + ∃p:GenericLinePath C e a b,p.InRegion C e {h | NearCut Ω C pc e h} := by + obtain ⟨J,hJ⟩:=real_covector_prescribe C e hC (fun _=>1) + apply generic_region_path_via_probes C e a b a (nearCutProbes Ω C pc e) J HA HB + intro h hh + have Hh:=nearCut_of_probes Ω C pc e J a h hJ ha hh + exact ⟨fun t ht ht'=>nearCut_convex Ω C pc e ha Hh t ht ht', + fun t ht ht'=>nearCut_convex Ω C pc e Hh hb t ht ht'⟩ + +lemma nearCut_regular_point (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) (pos:Bool) : + ∃h:Module.Dual ℝ E,RegularCovector C e h ∧ NearCut Ω C pc e h ∧ + cutSide pos (h.toAddMonoidHom.comp e) (simpleRoot C pc) := by + classical + let ε:ℝ:=1/((mutationSize Ω C pc:ℝ)+1) + have hep:0<ε:=by dsimp [ε]; positivity + obtain ⟨J,hJ⟩:=real_covector_prescribe C e hC (fun _=>1) + obtain ⟨k,hk⟩:=real_covector_prescribe C e hC (fun i=>if i=pc then if pos then ε/2 else -ε/2 else -2) + have hkn:NearCut Ω C pc e k:=by + constructor + · rw [hk]; simp only [ite_true] + cases pos <;> simp only [Bool.false_eq_true,ite_false,ite_true,abs_div,abs_of_pos hep, + abs_neg,abs_of_pos (show (0:ℝ)<2 by norm_num)] + all_goals change _<ε; linarith + · intro i hi; rw [hk,ite_eq_right hi]; norm_num + let P:=insert ((0:ℝ),e (simpleRoot C pc)) (nearCutProbes Ω C pc e) + obtain ⟨h,Ha,Hb,HP⟩:=generic_for_two_directions_with_probes (realRootsThrough e C) 0 0 k P J + have Hreg:RegularCovector C e h:=by + intro N s hs hn + exact (Ha N).avoid s hs (by simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using hn) + refine ⟨h,Hreg,nearCut_of_probes Ω C pc e J k h hJ hkn + (fun x hx=>HP x (Finset.mem_insert_of_mem hx)),?_⟩ + have Hcut:=HP ((0:ℝ),e (simpleRoot C pc)) (Finset.mem_insert_self _ _) + simp only [zero_smul,add_zero] at Hcut + cases pos + · change h (e (simpleRoot C pc))<0 + apply Hcut.2 + rw [hk]; simp only [ite_true,Bool.false_eq_true,ite_false] + linarith + · change 0 + let data:=lineRayData C e he L hdeg v k H a ha + have HC:=nearCut_noncut_wall Ω C coord hcoord pc e he S hS hcomp L hdeg (k+a • v) hh + data.root data.degree data.degree_pos data.root_degree data.generic + (decide (0<(k+a • v) (e (simpleRoot C pc)))) + (cutSide_decide ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc) hp) + rw [HC] + have HO:∀b,orientPowerSeries b (1:PowerSeries (Torus LaurentRay.vUnit Ω))=1:=by + intro b + apply PowerSeries.ext + intro n + exact orientPowerSeries_trivial b 1 n (fun _ _=>rfl) n le_rfl + simp only [HO,mutationCompletion_one] + · rfl + +omit [FiniteDimensional ℝ E] in +include hcoord hS hcomp in +lemma nearCut_mutated_product (lo hi:ℝ) (hlohi:loif k (e (simpleRoot C pc))+a*v (e (simpleRoot C pc))=0 then + orientPowerSeries (!(decide (v (e (simpleRoot C pc))<0))) + (normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) pc)) else 1):=by + apply List.map_congr_left + intro a ha + simpa only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] using + nearCut_mutated_factor Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a + (hh a (Finset.mem_filter.mp ((Finset.mem_sort _).mp ha)).2.1.le + (Finset.mem_filter.mp ((Finset.mem_sort _).mp ha)).2.2.le) + rw [HE] + apply pureCut_telescope _ (normalizedSimple_constant Ω _) + (k (e (simpleRoot C pc))) (v (e (simpleRoot C pc))) lo hi hlohi + (Or.inl (RationalFiber.line_cut_offset_ne C pc e L hdeg v k H)) + · exact fun hz=>hlo (RationalFiber.line_cut_event C pc e L hdeg v k H lo hz) + · exact fun hz=>hhi (RationalFiber.line_cut_event C pc e L hdeg v k H hi hz) + · exact fun a ha=>(Finset.mem_filter.mp ha).2 + · intro a hla hah hz + exact Finset.mem_filter.mpr ⟨lineEvents_mono (realRootsThrough_mono C e hN) v k + (RationalFiber.line_cut_event C pc e L hdeg v k H a hz),hla,hah⟩ + +omit [FiniteDimensional ℝ E] in +include hcoord hS hcomp in +lemma nearCut_mutated_completion (lo hi:ℝ) (hlohi:lorfl + +omit [FiniteDimensional ℝ E] in +include hcoord hS hcomp in +lemma nearCut_mutated_path {a b:Module.Dual ℝ E} (p:GenericLinePath C e a b) + (hh:p.InRegion C e {h | NearCut Ω C pc e h}) : + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p * + pureCutGauge (normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) pc)) + (decide (0rw [mutatedPathCompletion,one_mul] + | append s p ih=> + rw [mutatedPathCompletion,mul_assoc,ih hh.2] + exact nearCut_mutated_completion Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi s.ordered (s.start_regular 1) (s.finish_regular 1) hh.1 + +variable (hnd:∀r≠0,∃m,Ω r m≠0) +include hnd in +lemma nearCut_mutated_transport (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (ha:NearCut Ω C pc e a) (hb:NearCut Ω C pc e b) + (hap:a (e (simpleRoot C pc))<0) (hbp:0e (simpleRoot C i))) (pos:Bool) : + ∃h:Module.Dual ℝ E,RegularCovector C e h ∧ NearCut Ω C pc e h ∧ + cutSide pos (h.toAddMonoidHom.comp e) (simpleRoot C pc) ∧ + (∀n,01) + obtain ⟨k,hk⟩:=real_covector_prescribe C e hC (fun i=>if i=pc then if pos then ε/2 else -ε/2 else -2) + have hkn:NearCut Ω C pc e k:=by + constructor + · rw [hk]; simp only [ite_true] + cases pos <;> simp only [Bool.false_eq_true,ite_false,ite_true,abs_div,abs_of_pos hep, + abs_neg,abs_of_pos (show (0:ℝ)<2 by norm_num)] + all_goals change _<ε; linarith + · intro i hi; rw [hk,ite_eq_right hi]; norm_num + let P:=insert ((0:ℝ),e (simpleRoot C pc)) (nearCutProbes Ω C pc e) + let T:ℕ → Finset E:=fun N=>realRootsThrough e C N ∪ + (realRootsThrough e (mutatedRoots Ω C pc) N).image + (fun x=>if pos then x else realShearVector e S (simpleRoot C pc) x) + obtain ⟨h,Ha,Hb,HP⟩:=generic_for_two_directions_with_probes T 0 0 k P J + have Hreg:RegularCovector C e h:=by + intro N s hs hn + exact (Ha N).avoid s (Finset.mem_union_left _ hs) + (by simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using hn) + have Hcut:=HP ((0:ℝ),e (simpleRoot C pc)) (Finset.mem_insert_self _ _) + simp only [zero_smul,add_zero] at Hcut + have Hside:cutSide pos (h.toAddMonoidHom.comp e) (simpleRoot C pc):=by + cases pos + · change h (e (simpleRoot C pc))<0 + apply Hcut.2 + rw [hk]; simp only [ite_true,Bool.false_eq_true,ite_false] + linarith + · change 0HP x (Finset.mem_insert_of_mem hx)),Hside,?_⟩ + intro n hn m hm + obtain ⟨J',hJ'⟩:=mutated_degree_covector Ω C pc e hC + have hm0:e m≠0:=by + have H:=covector_root_pos (mutatedRoots Ω C pc) e J' (fun i=>by rw [hJ']; norm_num) hn hm + intro h0 + rw [h0,map_zero] at H + exact lt_irrefl _ H + have hv:(if pos then e m else realShearVector e S (simpleRoot C pc) (e m))≠0:=by + cases pos + · exact realShearVector_ne_zero C pc e S hS hm0 + · exact hm0 + have HT:(if pos then e m else realShearVector e S (simpleRoot C pc) (e m))∈T n:= + Finset.mem_union_right _ (Finset.mem_image.mpr ⟨e m,realRoot_mem e _ n n le_rfl m hm,rfl⟩) + have HH:=(Ha n).avoid _ HT (by simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using hv) + rw [realMutationCovector_eq_side e S _ pos h (by cases pos <;> exact le_of_lt Hside)] + cases pos + · simpa only [realSideCovector,Bool.false_eq_true,ite_false,realShearCovector_eval] using HH + · exact HH +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NearCutPolynomialSeeds.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NearCutPolynomialSeeds.lean new file mode 100644 index 0000000000000000000000000000000000000000..3918d7511883845f8fc35419363f4b7c80e649d3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NearCutPolynomialSeeds.lean @@ -0,0 +1,158 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.NearCutSectionCharts +import OAI.Combinatorics.Chromatic.Walls.FinitePureMutation + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits RationalFiber FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +local instance nearCutPolynomialSeedsRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance nearCutPolynomialSeedsAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance nearCutPolynomialSeedsAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +def PureInitialRelation (F F':Torus LaurentRay.vUnit Ω) : Prop := + embed LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) F= + pureAction LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω) + (embed LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) F') + +include hcoord in +lemma rootOrder_simple : rootOrder coord (simpleRoot C pc)=1 := + rootOrder_eq C coord hcoord (simpleRoot_degree C pc) + +include he hdeg hS hcomp in +lemma nearCut_old_positive_seed (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (ha:NearCut Ω C pc e a) (hb:NearCut Ω C pc e b) + (hap:a (e (simpleRoot C pc))<0) (hbp:0e (simpleRoot C i))) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (ha:NearCut Ω C pc e a) (hb:NearCut Ω C pc e b) + (hap:a (e (simpleRoot C pc))<0) (hbp:0e (simpleRoot C i))) + (F F':Torus LaurentRay.vUnit Ω) (hF:PureInitialRelation Ω hΩ C coord hcoord pc F F') + (pos:Bool) (h:Module.Dual ℝ E) (HH:RegularCovector C e h) + (hs:cutSide pos (h.toAddMonoidHom.comp e) (simpleRoot C pc)) + (HH':∀n,0e (simpleRoot C i))) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (ha:NearCut Ω C pc e a) (hb:NearCut Ω C pc e b) + (hap:a (e (simpleRoot C pc))<0) (hbp:0u.val.val) H + change (rootChartRatio Ω C (a.toAddMonoidHom.comp e) (b.toAddMonoidHom.comp e)).val= + raySeries LaurentRay.vUnit Ω (simpleRoot C pc) (shiftedElementary LaurentRay.vUnit 0)⁻¹ at HH + rw [laurent_shiftedElementary_zero,←normalizedSimple_inverse Ω hΩ] at HH + rw [rootChartRatio_section,rootSectionChart_negative Ω C (a.toAddMonoidHom.comp e) (nearCut_old_negative Ω C pc e ha hap)] at HH + have hi:invOfUnit (1:PowerSeries (Torus LaurentRay.vUnit Ω)) 1=1:=by + simpa using mul_invOfUnit (1:PowerSeries (Torus LaurentRay.vUnit Ω)) 1 (by simp) + simpa only [hi,mul_one] using HH + +omit [FiniteDimensional ℝ E] in +lemma nearCut_new_section_one {b:Module.Dual ℝ E} (hb:NearCut Ω C pc e b) + (hbp:0e (simpleRoot C i))) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (ha:NearCut Ω C pc e a) (hb:NearCut Ω C pc e b) + (hap:a (e (simpleRoot C pc))<0) (hbp:0invOfUnit f 1) H + rwa [inverse_inverse _ (rootSectionChart Ω _ _).property.1] at HH +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NormalizedMonomialAction.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NormalizedMonomialAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..034c8a1ea1fbc9623e46e3aaf9c67c6656062a59 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/NormalizedMonomialAction.lean @@ -0,0 +1,64 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.MonomialConjugation + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint +noncomputable section +variable {K M:Type*} [Field K] [AddCommGroup M] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def normalizedMonomialAction (f:PowerSeries (Torus v Ω)) (b:M) : PowerSeries (Torus v Ω):= + f*monomialConjugate v Ω b (invOfUnit f 1) + +include hΩ in +lemma adjoint_monomial_normalized (f:PowerSeries (Torus v Ω)) (b:M) : + adjoint f (PowerSeries.C (Torus.X v Ω b))= + normalizedMonomialAction v Ω f b*PowerSeries.C (Torus.X v Ω b) := by + have H:PowerSeries.C (Torus.X v Ω (-b))*PowerSeries.C (Torus.X v Ω b)= + (1:PowerSeries (Torus v Ω)):=by + rw [←map_mul] + simpa only [neg_neg,map_one] using congrArg + (PowerSeries.C : Torus v Ω → PowerSeries (Torus v Ω)) (X_mul_X_neg v Ω hΩ (-b)) + simp only [normalizedMonomialAction,monomialConjugate,adjoint,mul_assoc,H,mul_one] + +include hΩ in +lemma normalizedMonomialAction_bound (δ:M →+ ℤ) (B:ℕ) (f:PowerSeries (Torus v Ω)) (b:M) + (hf:RegradeBound v Ω δ B f) : RegradeBound v Ω δ B (normalizedMonomialAction v Ω f b) := + hf.mul v Ω δ B (monomialConjugate_regradeBound v Ω hΩ b δ B (hf.invOfUnit v Ω δ B)) + +include hΩ in +lemma normalizedMonomialAction_constant (f:PowerSeries (Torus v Ω)) (b:M) + (hf:constantCoeff f=1) : constantCoeff (normalizedMonomialAction v Ω f b)=1 := by + rw [normalizedMonomialAction,map_mul,hf,one_mul] + rw [monomialConjugate,map_mul,map_mul,constantCoeff_C,constantCoeff_C,constantCoeff_invOfUnit] + simp only [inv_one,Units.val_one,mul_one,X_mul_X_neg v Ω hΩ] + +include hΩ in +lemma adjoint_monomial_coeff (f:PowerSeries (Torus v Ω)) (b r:M) (n:ℕ) : + coeff n (adjoint f (PowerSeries.C (Torus.X v Ω b))) (r+b)= + coeff n (normalizedMonomialAction v Ω f b) r*(↑(v^(Ω r b)):K) := by + rw [adjoint_monomial_normalized v Ω hΩ,coeff_mul_C,mul_X_coeff] +end +end ElementaryPositivity.QuantumTorus +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] +variable (v:(LaurentSeries ℚ)ˣ) (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +include hΩ in +lemma normalizedMonomialAction_graded (C:(I → ℤ) →+ M) (f:CompletedPositive v Ω C) (b:M) : + SeriesGraded v Ω C (normalizedMonomialAction v Ω f.val b) := + SeriesGraded.mul v Ω C f.property.2 (monomialConjugate_graded v Ω hΩ C b + (SeriesGraded.inverse v Ω C f.property.2)) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrbitMonomialSymmetric.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrbitMonomialSymmetric.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d91cc48f3e434d251bacef24944cf4c76c959ba --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrbitMonomialSymmetric.lean @@ -0,0 +1,146 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.OrbitMonomial +open scoped BigOperators +open Classical +noncomputable section +variable {σ:Type*} [Fintype σ] [DecidableEq σ] {R:Type*} [CommRing R] + +def exponentOrbit (μ:σ →₀ ℕ) : Finset (σ →₀ ℕ) := + Finset.univ.image (fun e:Equiv.Perm σ=>μ.mapDomain e) + +def polynomial (μ:σ →₀ ℕ) : MvPolynomial σ R := + ∑d∈exponentOrbit μ,MvPolynomial.monomial d 1 + +lemma exponentOrbit_self (μ:σ →₀ ℕ) : μ∈exponentOrbit μ := by + refine Finset.mem_image.mpr ⟨Equiv.refl σ,Finset.mem_univ _,?_⟩ + exact Finsupp.mapDomain_id + +lemma exponentOrbit_map (μ:σ →₀ ℕ) (e:Equiv.Perm σ) (d:σ →₀ ℕ) + (hd:d∈exponentOrbit μ) : d.mapDomain e∈exponentOrbit μ := by + obtain ⟨f,_,rfl⟩:=Finset.mem_image.mp hd + refine Finset.mem_image.mpr ⟨f.trans e,Finset.mem_univ _,?_⟩ + exact Finsupp.mapDomain_comp (v:=μ) (f:=f) (g:=e) + +lemma exponentOrbit_map_iff (μ:σ →₀ ℕ) (e:Equiv.Perm σ) (d:σ →₀ ℕ) : + d.mapDomain e∈exponentOrbit μ ↔ d∈exponentOrbit μ := by + constructor + · intro h + have H:=exponentOrbit_map μ e.symm _ h + simpa only [←Finsupp.mapDomain_comp,Equiv.symm_comp_self,Finsupp.mapDomain_id] using H + · exact exponentOrbit_map μ e d + +lemma coeff_polynomial (μ d:σ →₀ ℕ) : (polynomial μ: MvPolynomial σ R).coeff d= + if d∈exponentOrbit μ then 1 else 0 := by + simp [polynomial,MvPolynomial.coeff_monomial,eq_comm] + +lemma polynomial_symmetric (μ:σ →₀ ℕ) : (polynomial μ:MvPolynomial σ R).IsSymmetric := by + intro e + apply MvPolynomial.ext + intro d + let d':=d.mapDomain e.symm + have he:d'.mapDomain e=d:=by + simp only [d',←Finsupp.mapDomain_comp,Equiv.self_comp_symm,Finsupp.mapDomain_id] + rw [←he,MvPolynomial.coeff_rename_mapDomain e e.injective,coeff_polynomial,coeff_polynomial] + simp only [exponentOrbit_map_iff] + +lemma polynomial_homogeneous (μ:σ →₀ ℕ) : + (polynomial μ:MvPolynomial σ R).IsHomogeneous μ.degree := by + apply MvPolynomial.IsHomogeneous.sum + intro d hd + obtain ⟨e,_,rfl⟩:=Finset.mem_image.mp hd + exact MvPolynomial.isHomogeneous_monomial 1 (Finsupp.degree_mapDomain e μ) + +lemma dominant_orbit_unique {n:ℕ} (μ ν:Fin (n+1) →₀ ℕ) + (hμ:∀i:Fin n,μ i.succ ≤ μ i.castSucc) (hν:∀i:Fin n,ν i.succ ≤ ν i.castSucc) + (h:ν∈exponentOrbit μ) : ν=μ := by + obtain ⟨e,_,rfl⟩:=Finset.mem_image.mp h + have hfun:(fun i=>(μ.mapDomain e) i)=(fun i=>μ (e.symm i)):=by + funext i + let a:=e.symm i + have H:=Finsupp.mapDomain_apply_of_injective e.injective μ a + simpa only [a,Equiv.apply_symm_apply] using H + have hp:(List.ofFn (fun i=>(μ.mapDomain e) i)).Perm (List.ofFn (fun i=>μ i)):=by + rw [hfun] + exact Equiv.Perm.ofFn_comp_perm (e.symm : Equiv.Perm _) _ + have H:=List.Perm.eq_of_pairwise' (r:=fun a b:ℕ=>b ≤ a) + (List.pairwise_ofFn.mpr (fun i j hij=>(Fin.antitone_iff_succ_le.mpr hν) (le_of_lt hij))) + (List.pairwise_ofFn.mpr (fun i j hij=>(Fin.antitone_iff_succ_le.mpr hμ) (le_of_lt hij))) hp + exact DFunLike.coe_injective (List.ofFn_injective H) + +lemma dominant_coeff {n:ℕ} (μ ν:Fin (n+1) →₀ ℕ) + (hμ:∀i:Fin n,μ i.succ ≤ μ i.castSucc) (hν:∀i:Fin n,ν i.succ ≤ ν i.castSucc) : + (polynomial μ:MvPolynomial (Fin (n+1)) R).coeff ν=if ν=μ then 1 else 0 := by + rw [coeff_polynomial] + congr 1 + exact propext ⟨dominant_orbit_unique μ ν hμ hν,fun h=>h ▸ exponentOrbit_self μ⟩ +end +end ElementaryPositivity.OrbitMonomial + +end +section +namespace ElementaryPositivity.OrbitMonomial +open scoped BigOperators +open Classical +noncomputable section +variable {σ:Type*} [Fintype σ] [DecidableEq σ] {R:Type*} [CommRing R] + +lemma exponentOrbit_symm {μ d:σ →₀ ℕ} (h:d∈exponentOrbit μ) : μ∈exponentOrbit d := by + obtain ⟨e,_,rfl⟩:=Finset.mem_image.mp h + have H:=exponentOrbit_map (μ.mapDomain e) e.symm _ (exponentOrbit_self _) + simpa only [←Finsupp.mapDomain_comp,Equiv.symm_comp_self,Finsupp.mapDomain_id] using H +lemma exponentOrbit_trans {μ d k:σ →₀ ℕ} (hd:d∈exponentOrbit μ) (hk:k∈exponentOrbit d) : + k∈exponentOrbit μ := by + obtain ⟨e,_,rfl⟩:=Finset.mem_image.mp hk + exact exponentOrbit_map μ e d hd +lemma symmetric_coeff_orbit (p:MvPolynomial σ R) (hp:p.IsSymmetric) (μ d:σ →₀ ℕ) + (hd:d∈exponentOrbit μ) : p.coeff d=p.coeff μ := by + obtain ⟨e,_,rfl⟩:=Finset.mem_image.mp hd + have H := MvPolynomial.coeff_rename_mapDomain e e.injective p μ + simpa only [hp e] using H + +lemma dominant_representative {n:ℕ} (d:Fin (n+1) →₀ ℕ) : + ∃μ:Fin (n+1) →₀ ℕ,(∀i:Fin n,μ i.succ ≤ μ i.castSucc) ∧ d∈exponentOrbit μ := by + let e:Equiv.Perm (Fin (n+1)):=Tuple.sort (α:=OrderDual ℕ) (fun i=>d i) + let μ:=d.mapDomain e.symm + have H:∀i,μ i=d (e i):=by + intro i + simpa only [μ,Equiv.symm_apply_apply] using (Finsupp.mapDomain_apply_of_injective e.symm.injective d (e i)) + refine ⟨μ,?_,exponentOrbit_symm (exponentOrbit_map d e.symm d (exponentOrbit_self d))⟩ + intro i + rw [H,H] + have hm := Tuple.monotone_sort (α:=OrderDual ℕ) (fun j : Fin (n+1) => d j) + exact hm (Fin.castSucc_le_succ i) + +lemma symmetric_orbit_decomposition {n:ℕ} (p:MvPolynomial (Fin (n+1)) R) (hp:p.IsSymmetric) : + p=∑μ∈p.support.filter (fun μ=>∀i:Fin n,μ i.succ ≤ μ i.castSucc), + MvPolynomial.C (p.coeff μ)*polynomial μ := by + apply MvPolynomial.ext + intro d + obtain ⟨μ,hμ,hd⟩:=dominant_representative d + rw [MvPolynomial.coeff_sum] + simp only [MvPolynomial.coeff_C_mul,coeff_polynomial] + symm + rw [Finset.sum_eq_single μ] + · rw [ite_eq_left hd,mul_one] + exact (symmetric_coeff_orbit p hp μ d hd).symm + · intro ν hν hne + obtain ⟨_,hν⟩:=Finset.mem_filter.mp hν + have hn:d∉exponentOrbit ν:=by + intro hv + exact hne (dominant_orbit_unique μ ν hμ hν (exponentOrbit_trans hd (exponentOrbit_symm hv))) + rw [ite_eq_right hn,mul_zero] + · intro h + have hh:p.coeff μ=0:=by + by_contra hh + exact h (Finset.mem_filter.mpr ⟨MvPolynomial.mem_support_iff.mpr hh,hμ⟩) + rw [hh,zero_mul] +end +end ElementaryPositivity.OrbitMonomial + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrderedIndependentProduct.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrderedIndependentProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..58150ada8fc5508b05f0b1432d738762e3421298 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrderedIndependentProduct.lean @@ -0,0 +1,119 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.IndependentSetElements + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +open Classical +noncomputable section +variable {K M V:Type*} [Field K] [AddCommGroup M] [Fintype V] [DecidableEq V] +variable (v:Kˣ) (Ω:M →+ M →+ ℤ) +local instance orderedIndependentProductRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance orderedIndependentProductAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance orderedIndependentProductAddGroup : AddGroup (Torus v Ω) := + (Torus.instRing v Ω).toAddGroup +local instance orderedIndependentProductNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalSemiring +local instance orderedIndependentProductNonUnitalNonAssocSemiring : + NonUnitalNonAssocSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +local instance orderedIndependentProductAddCommGroup : AddCommGroup (Torus v Ω) := + (Torus.instRing v Ω).toAddCommGroup +local instance orderedIndependentProductAddMonoid : AddMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddMonoid +local instance orderedIndependentProductSemiring : Semiring (Torus v Ω) := + (Torus.instRing v Ω).toSemiring +local instance orderedIndependentProductNonAssocSemiring : NonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonAssocSemiring +local instance orderedIndependentProductDistrib : Distrib (Torus v Ω) := + (Torus.instRing v Ω).toDistrib +local instance orderedIndependentProductMonoid : Monoid (Torus v Ω) := + (Torus.instRing v Ω).toMonoid +variable (u:V → M) + +def wordExponent {r:ℕ} (a:Fin r → M) : M:=∑i,a i + +def wordEnergy : {r:ℕ} → (Fin r → M) → ℤ + | 0,_=>0 + | _+1,a=>Ω (a 0) (wordExponent (fun i=>a i.succ))+wordEnergy (fun i=>a i.succ) + +lemma wordEnergy_eq_pairs {r:ℕ} (a:Fin r → M) : + wordEnergy Ω a=∑i:Fin r,∑j:Fin r,if i < j then Ω (a i) (a j) else 0 := by + induction r with + | zero=>simp [wordEnergy] + | succ r ih=> + rw [wordEnergy,ih,Fin.sum_univ_succ] + simp only [Fin.sum_univ_succ,Fin.not_lt_zero,ite_false,zero_add,Fin.succ_lt_succ_iff, + Fin.succ_pos,ite_true] + rw [wordExponent,map_sum] + +lemma ordered_monomial_product {r:ℕ} (a:Fin r → M) : + (List.ofFn (fun i=>Torus.X v Ω (a i))).prod= + Torus.monomial v Ω (wordExponent a) (↑(v^(wordEnergy Ω a))) := by + induction r with + | zero=>simp [wordEnergy,wordExponent,Torus.X,Torus.monomial]; rfl + | succ r ih=> + rw [List.ofFn_succ,List.prod_cons,ih] + change Torus.monomial v Ω (a 0) 1 * _=_ + rw [Torus.monomial_mul_monomial,wordEnergy] + simp only [wordExponent,Fin.sum_univ_succ,zpow_add,Units.val_mul] + congr 1 + rw [one_mul,mul_comm] + +def BlockValid {r:ℕ} (a:Fin r → ℕ) (s:Fin r → Finset V) : Prop := + ∀i,IsIndependent Ω u (s i) ∧ (s i).card=a i + +def blockLabels {r:ℕ} (s:Fin r → Finset V) : Fin r → M:=fun i=>∑x∈s i,u x + +omit [Fintype V] in +lemma independentTerm_product {r:ℕ} (a:Fin r → ℕ) (s:Fin r → Finset V) : + (List.ofFn (fun i=>independentTerm v Ω u (a i) (s i))).prod= + if BlockValid Ω u a s then + Torus.monomial v Ω (wordExponent (blockLabels u s)) (↑(v^(wordEnergy Ω (blockLabels u s)))) else 0 := by + by_cases h:BlockValid Ω u a s + · rw [ite_eq_left h] + have H:(fun i=>independentTerm v Ω u (a i) (s i))=(fun i=>Torus.X v Ω (blockLabels u s i)):=by + funext i + exact ite_eq_left (h i) + rw [H,ordered_monomial_product] + · rw [ite_eq_right h] + obtain ⟨i,hi⟩:=not_forall.mp h + apply List.prod_eq_zero + apply List.mem_ofFn.mpr + exact ⟨i,by simp only [independentTerm,ite_eq_right hi]⟩ + +lemma independentElement_product {r:ℕ} (a:Fin r → ℕ) : + (List.ofFn (fun i=>independentElement v Ω u (a i))).prod= + ∑s:Fin r → Finset V, + if BlockValid Ω u a s then + Torus.monomial v Ω (wordExponent (blockLabels u s)) (↑(v^(wordEnergy Ω (blockLabels u s)))) else 0 := by + have H:∀r:ℕ,∀a:Fin r → ℕ, + (List.ofFn (fun i=>independentElement v Ω u (a i))).prod= + ∑s:Fin r → Finset V,(List.ofFn (fun i=>independentTerm v Ω u (a i) (s i))).prod := by + intro r + induction r with + | zero=>intro a; simp + | succ r ih=> + intro a + rw [List.ofFn_succ,List.prod_cons,ih,independentElement] + erw [Finset.sum_mul] + simp only [Finset.mul_sum] + rw [←Equiv.sum_comp (Fin.consEquiv (fun _ : Fin (r+1)=>Finset V)),Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro t ht + apply Finset.sum_congr rfl + intro s hs + rw [List.ofFn_succ,List.prod_cons] + rfl + rw [H] + apply Finset.sum_congr rfl + intro s hs + exact independentTerm_product v Ω u a s +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrdinaryElementaryExpressions.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrdinaryElementaryExpressions.lean new file mode 100644 index 0000000000000000000000000000000000000000..7cbc3ef3070888aa63ac4a62be76e69b2c1333f4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrdinaryElementaryExpressions.lean @@ -0,0 +1,137 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousElementaryExpressions + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +open Classical +noncomputable section + +variable {σ : Type*} [Fintype σ] {R : Type*} [CommRing R] + +def ElementaryExpr.ordinary : {N:ℕ} → ElementaryExpr N → MvPolynomial σ R + | _,.zero _ => 0 + | _,.one => 1 + | _,.atom k => MvPolynomial.esymm σ R k + | _,.add f g => ordinary f+ordinary g + | _,.neg f => -ordinary f + | _,.mul f g => ordinary f*ordinary g + +lemma elementary_isHomogeneous (k:ℕ) : (MvPolynomial.esymm σ R k).IsHomogeneous k := by + unfold MvPolynomial.esymm + apply MvPolynomial.IsHomogeneous.sum + intro s hs + have hc:s.card=k:=(Finset.mem_powersetCard_univ.mp hs) + simpa [hc] using MvPolynomial.IsHomogeneous.prod s (fun a:σ=>MvPolynomial.X (R:=R) a) + (fun _=>1) (fun a _=>MvPolynomial.isHomogeneous_X R a) + +lemma ElementaryExpr.ordinary_homogeneous {N:ℕ} (f:ElementaryExpr N) : + (f.ordinary (σ:=σ) (R:=R)).IsHomogeneous N := by + induction f with + | zero N => exact MvPolynomial.isHomogeneous_zero σ R N + | one => exact MvPolynomial.isHomogeneous_one σ R + | atom k => exact elementary_isHomogeneous k + | add f g hf hg=>exact hf.add hg + | neg f hf=>exact hf.neg + | mul f g hf hg=>exact hf.mul hg + +lemma ElementaryExpr.ordinary_cast {N K:ℕ} (h:N=K) (f:ElementaryExpr N) : + (h ▸ f).ordinary (σ:=σ) (R:=R)=f.ordinary := by subst K; rfl + +def ElementaryExpr.natural : ℕ → ElementaryExpr 0 + | 0=>.zero 0 + | k+1=>.add (natural k) .one + +def ElementaryExpr.integer : ℤ → ElementaryExpr 0 + | .ofNat k => natural k + | .negSucc k => .neg (natural (k+1)) + +lemma ElementaryExpr.ordinary_natural (k:ℕ) : + (ElementaryExpr.natural k).ordinary (σ:=σ) (R:=R)=MvPolynomial.C (k:R) := by + induction k with + | zero=>simp [natural,ordinary] + | succ k ih=>simp [natural,ordinary,ih,Nat.cast_add,Nat.cast_one] + +lemma ElementaryExpr.ordinary_integer (z:ℤ) : + (ElementaryExpr.integer z).ordinary (σ:=σ) (R:=R)=MvPolynomial.C (z:R) := by + cases z with + | ofNat k=>simpa [integer] using ordinary_natural (σ:=σ) (R:=R) k + | negSucc k=>simp [integer,ordinary,ordinary_natural,Int.cast_negSucc] + +lemma ElementaryExpr.exists_power {k:ℕ} (f:ElementaryExpr k) (e:ℕ) : + ∃g:ElementaryExpr (k*e),g.ordinary (σ:=σ) (R:=R)=f.ordinary^e := by + induction e with + | zero=>exact ⟨.one,rfl⟩ + | succ e ih=> + obtain ⟨g,hg⟩:=ih + rw [Nat.mul_succ] + refine ⟨.mul g f,?_⟩ + change g.ordinary*f.ordinary=f.ordinary^(e+1) + rw [hg,pow_succ] + +lemma ElementaryExpr.exists_product {ι:Type*} (s:Finset ι) (k:ι → ℕ) + (f:∀a,ElementaryExpr (k a)) : + ∃g:ElementaryExpr (∑a∈s,k a),g.ordinary (σ:=σ) (R:=R)=∏a∈s,(f a).ordinary := by + induction s using Finset.induction with + | empty=>exact ⟨.one,rfl⟩ + | @insert a s ha ih=> + obtain ⟨g,hg⟩:=ih + rw [Finset.sum_insert ha,Finset.prod_insert ha] + refine ⟨.mul (f a) g,?_⟩ + change (f a).ordinary*g.ordinary=_ + rw [hg] + +lemma homogeneousExpression_representation {N:ℕ} (p:MvPolynomial σ ℤ) + (hp:p.IsSymmetric) (hN:p.IsHomogeneous N) : + ∃f:ElementaryExpr N,f.ordinary=p := by + let m:=Fintype.card σ + obtain ⟨q,hq⟩:=MvPolynomial.esymmAlgHom_surjective (σ:=σ) ℤ (n:=m) le_rfl ⟨p,hp⟩ + let E:=MvPolynomial.esymmAlgHom σ ℤ m + have he:∀d:Fin m →₀ ℕ,∀z:ℤ,∃K,∃f:ElementaryExpr K, + f.ordinary=(E (MvPolynomial.monomial d z):MvPolynomial σ ℤ):=by + intro d z + choose g hg using fun a:Fin m=>ElementaryExpr.exists_power (σ:=σ) (R:=ℤ) (.atom (a.val+1)) (d a) + obtain ⟨f,hf⟩:=ElementaryExpr.exists_product (σ:=σ) (R:=ℤ) Finset.univ + (fun a:Fin m=>(a.val+1)*d a) g + refine ⟨_,.mul (.integer z) f,?_⟩ + change ((ElementaryExpr.integer z).ordinary)*f.ordinary=_ + rw [ElementaryExpr.ordinary_integer,hf] + simp only [hg,ElementaryExpr.ordinary] + simp [E,MvPolynomial.esymmAlgHom,MvPolynomial.aeval_monomial,Finsupp.prod_fintype] + have hterm:∀d:Fin m →₀ ℕ,∃f:ElementaryExpr N,f.ordinary= + MvPolynomial.homogeneousComponent N (E (MvPolynomial.monomial d (q.coeff d)):MvPolynomial σ ℤ):=by + intro d + obtain ⟨K,f,hf⟩:=he d (q.coeff d) + rw [←hf,MvPolynomial.homogeneousComponent_of_mem f.ordinary_homogeneous] + by_cases h:N=K + · refine ⟨h.symm ▸ f,?_⟩ + simp only [h,ite_true,ElementaryExpr.ordinary_cast] + · exact ⟨.zero N,by simp [h,ElementaryExpr.ordinary]⟩ + have hs:∀s:Finset (Fin m →₀ ℕ),∃f:ElementaryExpr N,f.ordinary= + ∑d∈s,MvPolynomial.homogeneousComponent N (E (MvPolynomial.monomial d (q.coeff d)):MvPolynomial σ ℤ):=by + intro s + induction s using Finset.induction with + | empty=>exact ⟨.zero N,by simp [ElementaryExpr.ordinary]⟩ + | @insert d s hd ih=> + obtain ⟨f,hf⟩:=hterm d + obtain ⟨g,hg⟩:=ih + exact ⟨.add f g,by simp [ElementaryExpr.ordinary,hf,hg,Finset.sum_insert hd]⟩ + obtain ⟨f,hf⟩:=hs q.support + refine ⟨f,?_⟩ + rw [←map_sum] at hf + have H:(∑d∈q.support,(E (MvPolynomial.monomial d (q.coeff d)):MvPolynomial σ ℤ))=p:=by + let E' : MvPolynomial (Fin m) ℤ →ₐ[ℤ] MvPolynomial σ ℤ := + (MvPolynomial.symmetricSubalgebra σ ℤ).val.comp E + change (∑d∈q.support,E' (MvPolynomial.monomial d (q.coeff d)))=p + rw [←map_sum,←MvPolynomial.as_sum] + exact congrArg Subtype.val hq + rw [H,MvPolynomial.homogeneousComponent_eq_self hN] at hf + exact hf +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrdinaryExpressionNaturality.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrdinaryExpressionNaturality.lean new file mode 100644 index 0000000000000000000000000000000000000000..401cf740aaa7516be1f814c6430406ef8eb77935 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/OrdinaryExpressionNaturality.lean @@ -0,0 +1,38 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.OrbitMonomialSymmetric +import OAI.Combinatorics.Chromatic.QuantumTorus.OrdinaryElementaryExpressions +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousElementaryExpressions + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open scoped BigOperators +open Classical +noncomputable section +variable {σ:Type*} [Fintype σ] {R S:Type*} [CommRing R] [CommRing S] +lemma ElementaryExpr.ordinary_map {N:ℕ} (f:ElementaryExpr N) (φ:R →+* S) : + MvPolynomial.map φ (f.ordinary (σ:=σ) (R:=R))=f.ordinary (σ:=σ) (R:=S) := by + induction f with + | zero=>exact map_zero _ + | one=>exact map_one _ + | atom k=>simp [ordinary,MvPolynomial.esymm] + | add f g hf hg=>simp only [ordinary,map_add,hf,hg] + | neg f hf=>simp only [ordinary,map_neg,hf] + | mul f g hf hg=>simp only [ordinary,map_mul,hf,hg] +end +end ElementaryPositivity.QuantumTorus +namespace ElementaryPositivity.OrbitMonomial +open scoped BigOperators +open Classical +noncomputable section +variable {σ:Type*} [Fintype σ] [DecidableEq σ] {R S:Type*} [CommRing R] [CommRing S] +lemma polynomial_map (μ:σ →₀ ℕ) (φ:R →+* S) : + MvPolynomial.map φ (polynomial μ:MvPolynomial σ R)=(polynomial μ:MvPolynomial σ S) := by + simp only [polynomial,map_sum,MvPolynomial.map_monomial,map_one] +end +end ElementaryPositivity.OrbitMonomial + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PolynomialThetaIdentification.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PolynomialThetaIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a1e0387677b456cd978c59d5e133e15d9cc6a4e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PolynomialThetaIdentification.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogenizedPolynomialSection + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits +open Classical +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +include hΩ hcoord in +lemma polynomialInitial_delta_prescription (base:M) (hb:rootOrder coord base=0) + (F:Torus LaurentRay.vUnit Ω) (hF:∀m,F m≠0 → ∃d,HasRootDegree C d (m-base)) + (hdelta:∀m,polynomialSectionIncoming Ω C coord F m=if m=base then 1 else 0) : + ∀d,sectionIncoming LaurentRay.vUnit Ω C (simpleTotalTransport Ω C) base d + (polynomialInitial Ω C coord F)=coeff d (PowerSeries.C (Torus.X LaurentRay.vUnit Ω base)) := by + intro d + apply Finsupp.ext + intro m + by_cases hm:HasRootDegree C d (m-base) + · rw [polynomialInitial_incoming Ω hΩ C coord hcoord base hb F hF d m hm,hdelta] + by_cases he:m=base + · subst m + have H:=rootOrder_eq C coord hcoord hm + rw [sub_self,map_zero] at H + have hd:d=0:=by omega + rw [hd] + simp [Torus.X,Torus.monomial] + · rw [ite_eq_right he,coeff_C] + split_ifs <;> simp [Torus.X,Torus.monomial,Ne.symm he] + · rw [sectionIncoming_apply,ite_eq_right hm] + exact (ShiftGraded.monomial LaurentRay.vUnit Ω C base d m hm).symm + +include hΩ hcoord in +lemma polynomialInitial_eq_theta (base:M) (hb:rootOrder coord base=0) + (F:Torus LaurentRay.vUnit Ω) (hF:∀m,F m≠0 → ∃d,HasRootDegree C d (m-base)) + (hdelta:∀m,polynomialSectionIncoming Ω C coord F m=if m=base then 1 else 0) : + polynomialInitial Ω C coord F=thetaInitial LaurentRay.vUnit Ω C (simpleTotalTransport Ω C) base := by + have hp:=polynomialInitial_delta_prescription Ω hΩ C coord hcoord base hb F hF hdelta + let X:{X:PowerSeries (Torus LaurentRay.vUnit Ω) // ShiftGraded LaurentRay.vUnit Ω C base X}:= + ⟨polynomialInitial Ω C coord F,polynomialInitial_graded Ω C coord hcoord base hb F hF⟩ + have U:=(existsUnique_section LaurentRay.vUnit Ω C (simpleTotalTransport Ω C) base + (fun d=>coeff d (PowerSeries.C (Torus.X LaurentRay.vUnit Ω base))) + (ShiftGraded.monomial LaurentRay.vUnit Ω C base)) + let Y:{X:PowerSeries (Torus LaurentRay.vUnit Ω) // ShiftGraded LaurentRay.vUnit Ω C base X}:= + ⟨thetaInitial LaurentRay.vUnit Ω C (simpleTotalTransport Ω C) base, + thetaInitial_graded LaurentRay.vUnit Ω C (simpleTotalTransport Ω C) base⟩ + have he:X=Y:=U.unique hp (thetaInitial_prescription LaurentRay.vUnit Ω C + (simpleTotalTransport Ω C) base) + exact congrArg Subtype.val he + +include hΩ hcoord in +lemma polynomialSection_eq_thetaValue (base:M) (hb:rootOrder coord base=0) + (F:Torus LaurentRay.vUnit Ω) (hF:∀m,F m≠0 → ∃d,HasRootDegree C d (m-base)) + (hdelta:∀m,polynomialSectionIncoming Ω C coord F m=if m=base then 1 else 0) + (h:M →+ ℝ) : + adjoint (rootSectionChart Ω C h).val (homogenize LaurentRay.vUnit Ω (rootOrder coord) F)= + thetaValue LaurentRay.vUnit Ω C (simpleTotalTransport Ω C) base h := by + rw [rootSectionChart_action] + change sectionValue _ _ _ _ _ (polynomialInitial Ω C coord F)=_ + rw [polynomialInitial_eq_theta Ω hΩ C coord hcoord base hb F hF hdelta] + rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ProductUnitFiltration.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ProductUnitFiltration.lean new file mode 100644 index 0000000000000000000000000000000000000000..be4b14344ad3dabee91c71e3c6dead90598e281e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/ProductUnitFiltration.lean @@ -0,0 +1,105 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.Product +import OAI.Combinatorics.Chromatic.Shuffle.UnitalFiltration + +namespace OAI + +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] +lemma OnSlopeOrZero.compatible {c η : I → ℝ} {θ : ℝ} {d e : I → ℕ} + (hd : OnSlopeOrZero c η θ d) (he : OnSlopeOrZero c η θ e) : + d=0 ∨ e=0 ∨ slope c η d=slope c η e := by + rcases hd with hd|hd + · exact Or.inl hd + rcases he with he|he + · exact Or.inr (Or.inl he) + exact Or.inr (Or.inr (hd.trans he.symm)) + +lemma OnSlopeOrZero.add {c η : I → ℝ} (hc : ∀ i,0 + refine ⟨constantCoeff f.val,?_⟩ + change quotientAlg a μ 0 f=constantCoeff f.val • (1 : B a μ 0) + have h:=congrArg (quotientAlg a μ 0) (S_zero_eq_scalar f) + simpa only [map_smul,map_one] using h + +lemma shuffleBUnit_one_left (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + change shuffleBUnit a c η hc 0 d hs (quotientAlg a (slope c η) 0 1) + (quotientAlg a (slope c η) d f)=_ + change quotientAlg a (slope c η) (0+d) (shufflePolynomial a 1 f)=_ + rw [shufflePolynomial_unit_left,←castB_mk] + rfl + +lemma shuffleBUnit_one_right (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + change shuffleBUnit a c η hc d 0 hs (quotientAlg a (slope c η) d f) + (quotientAlg a (slope c η) 0 1)=_ + change quotientAlg a (slope c η) (d+0) (shufflePolynomial a f 1)=_ + rw [shufflePolynomial_unit_right,←castB_mk] + rfl + +lemma shuffleBUnit_filtered_zero_left (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0f a*x) z=(l.map f).prod*z := by + induction l with + | nil=>simp + | cons a l ih=>simp only [List.foldr_cons,List.map_cons,List.prod_cons,ih,mul_assoc] +omit [Ring A] in +lemma foldr_identity (l:List J) (x:A) : l.foldr (fun _ y=>y) x=x := by + induction l <;> simp_all + +lemma pureCut_local (f:PowerSeries A) (hf:constantCoeff f=1) (u v t:ℝ) + (hne:u≠0 ∨ v≠0) (x:PowerSeries A) : + (if u+t*v=0 then orientPowerSeries (!(decide (v<0))) f else 1)* + (pureCutGauge f (AffineCut.beforeSide u v t)*x)= + pureCutGauge f (AffineCut.afterSide u v t)*x := by + by_cases hz:u+t*v=0 + · have hv:v≠0:=by rintro rfl; simp_all + rw [ite_eq_left hz,(AffineCut.sides_at_zero u v t hz).1,(AffineCut.sides_at_zero u v t hz).2] + rcases lt_or_gt_of_ne hv with hn|hp + · simp only [hn,decide_true,Bool.not_true,pureCutGauge,ite_true, + show ¬0if u+t*v=0 then + orientPowerSeries (!(decide (v<0))) f else 1)).prod * + pureCutGauge f (decide (0x) + (fun t x=>(if u+t*v=0 then orientPowerSeries (!(decide (v<0))) f else 1)*x) + (fun side x=>pureCutGauge f side*x) T lo hi hlohi hmem hcut + (fun t _ x=>pureCut_local f hf u v t hne x) 1 + rw [(AffineCut.sides_eq_of_ne u v lo hlo).2,(AffineCut.sides_eq_of_ne u v hi hhi).1, + foldr_identity,mul_one,mul_one,foldr_left_mul] at HH + exact HH +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (α β : M →+ ℤ) (hβ : ∀m,β m= -α m) + +def fiberReciprocalTerm (m : M) : RatFunc K →+ FiberTorus v Ω β where + toFun a:=FiberTorus.monomial v Ω β m (reciprocal a) + map_zero':=by simp + map_add' a b:=by simp only [map_add,FiberTorus.monomial_add] +def fiberReciprocalAdd : FiberTorus v Ω α →+ FiberTorus v Ω β := + Finsupp.liftAddHom (fiberReciprocalTerm v Ω β) +lemma fiberReciprocalAdd_monomial (m : M) (a : RatFunc K) : + fiberReciprocalAdd v Ω α β (FiberTorus.monomial v Ω α m a)= + FiberTorus.monomial v Ω β m (reciprocal a) := Finsupp.liftAddHom_apply_single _ _ _ +include hβ in +lemma reciprocal_twist (m : M) (a : RatFunc K) : + reciprocal (FiberTorus.twist v α m a)=FiberTorus.twist v β m (reciprocal a) := by + have H:=congrArg (fun F : RatFunc K →+* RatFunc K=>F a) (reciprocal_scale (v^(-2*α m))) + change reciprocal (scale (v^(-2*α m)) a)=scale (v^(-2*β m)) (reciprocal a) + rw [hβ] + have he : (v^(-2*α m))⁻¹=v^(-2*(-α m)):=by + rw [←zpow_neg] + congr 1 + ring + simpa only [RingHom.coe_comp,Function.comp_apply,he] using H +include hβ in +lemma fiberReciprocalAdd_mul (f g : FiberTorus v Ω α) : + fiberReciprocalAdd v Ω α β (f*g)=fiberReciprocalAdd v Ω α β f*fiberReciprocalAdd v Ω α β g := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f f' hf hf'=>simp only [_root_.add_mul,map_add,hf,hf'] + | single m a=> + induction g using Finsupp.induction_linear with + | zero=>simp + | add g g' hg hg'=>simp only [_root_.mul_add,map_add,hg,hg'] + | single n b=> + change fiberReciprocalAdd v Ω α β + (FiberTorus.monomial v Ω α m a*FiberTorus.monomial v Ω α n b)= + fiberReciprocalAdd v Ω α β (FiberTorus.monomial v Ω α m a)* + fiberReciprocalAdd v Ω α β (FiberTorus.monomial v Ω α n b) + rw [FiberTorus.monomial_mul,fiberReciprocalAdd_monomial, + fiberReciprocalAdd_monomial,fiberReciprocalAdd_monomial,FiberTorus.monomial_mul] + simp only [map_mul,reciprocal_constant,reciprocal_twist v α β hβ] +def fiberReciprocal : FiberTorus v Ω α →+* FiberTorus v Ω β where + __:=fiberReciprocalAdd v Ω α β + map_one':=by + change fiberReciprocalAdd v Ω α β (FiberTorus.monomial v Ω α 0 1)=_ + rw [fiberReciprocalAdd_monomial,map_one] + rfl + map_mul':=fiberReciprocalAdd_mul v Ω α β hβ + +lemma fiberReciprocal_oppositeInverse (f : FiberTorus v Ω α) : + fiberReciprocal v Ω α β hβ (oppositeInverseActionHom v Ω α f)= + pureActionInvHom v Ω β (fiberReciprocal v Ω α β hβ f) := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [map_add,hf,hg] + | single m a=> + change fiberReciprocalAdd v Ω α β (FiberTorus.gaugeAdd v Ω α _ + (FiberTorus.monomial v Ω α m a))= + FiberTorus.gaugeAdd v Ω β _ (fiberReciprocalAdd v Ω α β (FiberTorus.monomial v Ω α m a)) + rw [FiberTorus.gaugeAdd_monomial,fiberReciprocalAdd_monomial, + fiberReciprocalAdd_monomial,FiberTorus.gaugeAdd_monomial] + congr 1 + rw [map_mul,hβ] + congr 1 + simp only [oppositeInverseRatio,Units.val_inv_eq_inv_val,reciprocalUnit_val,map_inv₀] + have H:=congrArg (fun F : RatFunc K →+* RatFunc K=>F (↑(pureRatio v (-α m)):RatFunc K)) + reciprocal_involutive + change reciprocal (reciprocal (↑(pureRatio v (-α m)):RatFunc K))=_ at H + rw [H] + rfl + +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PureFaceProjection.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PureFaceProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..1faab5720e605e3fe61d3325a53af7f22a3df2d3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PureFaceProjection.lean @@ -0,0 +1,132 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.GradedFormalLog +import OAI.Combinatorics.Chromatic.Walls.HNTorusFactor +import OAI.Combinatorics.Chromatic.QuantumTorus.TorusProjection +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationCoordinates + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance pureFaceProjectionAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommGroup +local instance pureFaceProjectionAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance pureFaceProjectionAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance pureFaceProjectionSub : Sub (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toSub + +def pureFaceCovector : M →+ ℝ := -(Int.castAddHom ℝ).comp (nonpDegree coord pc) +lemma pureFaceCovector_apply (m : M) : pureFaceCovector coord pc m= -(nonpDegree coord pc m : ℝ) := rfl +lemma pureFaceCovector_zero_iff (m : M) : pureFaceCovector coord pc m=0 ↔ nonpDegree coord pc m=0 := by + rw [pureFaceCovector_apply,neg_eq_zero,Int.cast_eq_zero] + +def pureFaceSeries (F : PowerSeries (Torus LaurentRay.vUnit Ω)) : PowerSeries (Torus LaurentRay.vUnit Ω) := + PowerSeries.mk (fun n=>zeroProject LaurentRay.vUnit Ω (pureFaceCovector coord pc) (coeff n F)) +lemma coeff_pureFaceSeries (F : PowerSeries (Torus LaurentRay.vUnit Ω)) (n : ℕ) : + coeff n (pureFaceSeries Ω coord pc F)=zeroProject LaurentRay.vUnit Ω (pureFaceCovector coord pc) (coeff n F) := coeff_mk _ _ +lemma pureFaceSeries_apply (F : PowerSeries (Torus LaurentRay.vUnit Ω)) (n : ℕ) (m : M) : + coeff n (pureFaceSeries Ω coord pc F) m=if nonpDegree coord pc m=0 then coeff n F m else 0 := by + rw [coeff_pureFaceSeries] + change (coeff n F).filter (fun m=>pureFaceCovector coord pc m=0) m=_ + simp only [Finsupp.filter_apply,pureFaceCovector_zero_iff] +lemma pureFaceSeries_one : pureFaceSeries Ω coord pc 1=1 := by + apply PowerSeries.ext + intro n + rw [coeff_pureFaceSeries,coeff_one] + split_ifs with hn + · exact zeroProject_one _ _ _ + · exact map_zero _ +lemma pureFaceSeries_sub (F G : PowerSeries (Torus LaurentRay.vUnit Ω)) : + pureFaceSeries Ω coord pc (F-G)=pureFaceSeries Ω coord pc F-pureFaceSeries Ω coord pc G := by + apply PowerSeries.ext + intro n + simp only [coeff_pureFaceSeries,map_sub] +include hcoord in +lemma rootGrade_nonpositive_face (n : ℕ) (x : Torus LaurentRay.vUnit Ω) + (hx : x∈rootGrade LaurentRay.vUnit Ω C n) : + x∈supportedSubring LaurentRay.vUnit Ω (nonpositiveCone (pureFaceCovector coord pc)) := by + intro m hm + by_contra hh + have hroot : HasRootDegree C n m:=by by_contra hk; exact hh (hx m hk) + have hpos:=nonpDegree_root_nonneg C coord hcoord pc hroot + exact hm (show pureFaceCovector coord pc m≤0 by rw [pureFaceCovector_apply]; exact neg_nonpos.mpr (by exact_mod_cast hpos)) +include hcoord in +lemma pureFaceSeries_mul (F G : PowerSeries (Torus LaurentRay.vUnit Ω)) + (hF : ∀n,coeff n F∈rootGrade LaurentRay.vUnit Ω C n) + (hG : ∀n,coeff n G∈rootGrade LaurentRay.vUnit Ω C n) : + pureFaceSeries Ω coord pc (F*G)=pureFaceSeries Ω coord pc F*pureFaceSeries Ω coord pc G := by + apply PowerSeries.ext + intro n + rw [coeff_pureFaceSeries,coeff_mul,coeff_mul,map_sum] + apply Finset.sum_congr rfl + intro p hp + rw [coeff_pureFaceSeries,coeff_pureFaceSeries] + exact zeroProject_mul_nonpositive _ _ _ _ _ + (rootGrade_nonpositive_face Ω C coord hcoord pc _ _ (hF _)) + (rootGrade_nonpositive_face Ω C coord hcoord pc _ _ (hG _)) +lemma pureFaceSeries_graded (F : PowerSeries (Torus LaurentRay.vUnit Ω)) + (hF : ∀n,coeff n F∈rootGrade LaurentRay.vUnit Ω C n) : + ∀n,coeff n (pureFaceSeries Ω coord pc F)∈rootGrade LaurentRay.vUnit Ω C n := by + intro n m hm + rw [pureFaceSeries_apply] + split_ifs <;> simp only [hF n m hm] +def pureFace (F : CompletedPositive LaurentRay.vUnit Ω C) : CompletedPositive LaurentRay.vUnit Ω C := + ⟨pureFaceSeries Ω coord pc F.val,by + constructor + · rw [←coeff_zero_eq_constantCoeff_apply,coeff_pureFaceSeries,coeff_zero_eq_constantCoeff_apply,F.property.1] + exact zeroProject_one _ _ _ + · exact pureFaceSeries_graded Ω C coord pc F.val F.property.2⟩ +include hcoord in +lemma pureFaceSeries_chart_sides (h : M →+ ℝ) (hp : h (simpleRoot C pc)=0) + (F : CompletedPositive LaurentRay.vUnit Ω C) : + (pureFace Ω C coord pc (chartPositive LaurentRay.vUnit Ω C h F)).val=1 ∧ + (pureFace Ω C coord pc (chartNegative LaurentRay.vUnit Ω C h F)).val=1 := by + have HS:=chart_three_support LaurentRay.vUnit Ω C h F + constructor + all_goals + apply PowerSeries.ext + intro n + cases n with + | zero => simpa only [coeff_zero_eq_constantCoeff_apply,map_one] using (pureFace _ _ _ _ _).property.1 + | succ n => + rw [coeff_one,ite_eq_right (by omega)] + apply Finsupp.ext + intro m + change coeff (n+1) (pureFaceSeries Ω coord pc _) m=0 + rw [pureFaceSeries_apply] + split_ifs with hz + · by_contra hh + have hm : HasRootDegree C (n+1) m:=by + by_contra hn + first | exact hh ((chartPositive _ _ _ _ F).property.2 _ m hn) | exact hh ((chartNegative _ _ _ _ F).property.2 _ m hn) + have hm0 : h m=0:=by rw [nonp_zero_root C coord hcoord pc hm hz,map_nsmul,hp,nsmul_zero] + first + | have he:=HS.1 n m hh; rw [hm0] at he; exact lt_irrefl _ he + | have he:=HS.2.2 n m hh; rw [hm0] at he; exact lt_irrefl _ he + · rfl +include hcoord in +lemma pureFace_chartZero (h : M →+ ℝ) (hp : h (simpleRoot C pc)=0) + (F : CompletedPositive LaurentRay.vUnit Ω C) : + pureFace Ω C coord pc (chartZero LaurentRay.vUnit Ω C h F)=pureFace Ω C coord pc F := by + apply Subtype.ext + have H:=congrArg (pureFaceSeries Ω coord pc) (chart_three_factorization LaurentRay.vUnit Ω C h F) + rw [pureFaceSeries_mul Ω C coord hcoord pc _ _ + (FormalLog.graded_multiply _ (rootGrade_mul LaurentRay.vUnit Ω C) _ _ + (chartPositive _ _ _ _ F).property.2 (chartZero _ _ _ _ F).property.2) + (chartNegative _ _ _ _ F).property.2, + pureFaceSeries_mul Ω C coord hcoord pc _ _ + (chartPositive _ _ _ _ F).property.2 (chartZero _ _ _ _ F).property.2] at H + have HH:=pureFaceSeries_chart_sides Ω C coord hcoord pc h hp F + change (pureFace _ _ _ _ (chartPositive _ _ _ _ F)).val* + (pureFace _ _ _ _ (chartZero _ _ _ _ F)).val* + (pureFace _ _ _ _ (chartNegative _ _ _ _ F)).val=(pureFace _ _ _ _ F).val at H + simpa only [HH.1,HH.2,one_mul,mul_one] using H +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PureProductSplit.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PureProductSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa90dfc75c6f637a8a68b6c07425a199a1be7084 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/PureProductSplit.lean @@ -0,0 +1,157 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SimpleAdjointFiber +import OAI.Combinatorics.Chromatic.Walls.SimpleIncomingElement + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) + +lemma ordered_filter_partition {A : Type*} (P : A → Prop) [DecidablePred P] (l : List A) + (hl : l.Pairwise (fun a b=>P b → P a)) : + l.filter (fun a=>decide (P a)) ++ l.filter (fun a=>decide (¬P a))=l := by + induction l with + | nil=>rfl + | cons a l ih=> + have HH:=List.pairwise_cons.mp hl + by_cases ha : P a + · simpa [List.filter_cons,ha] using congrArg (List.cons a) (ih HH.2) + · have hz : l.filter (fun a=>decide (P a))=[]:=by + apply List.filter_eq_nil_iff.mpr + intro b hb + simpa using (fun hp=>ha (HH.1 b hb hp) : ¬ P b) + have IH:=ih HH.2 + rw [hz,List.nil_append] at IH + simp [ha,hz] + intro b hb hp + exact ha (HH.1 b hb hp) +lemma alternating_int_swap (hΩ : ∀m,Ω m m=0) (a b : M) : Ω a b= -Ω b a := by + have H:=hΩ (a+b) + simp only [map_add,AddMonoidHom.add_apply,hΩ,zero_add,add_zero] at H + omega +include hcoord in +lemma ordered_pure_partition (hΩ : ∀m,Ω m m=0) (pos : Bool) (l : List M) + (hl : l.Pairwise (fun a b=>0<Ω a b)) + (hroot : ∀q∈l,∃d,0decide (nonpDegree coord pc q=0)) ++ + l.filter (fun q=>decide (nonpDegree coord pc q≠0)) + else + l.filter (fun q=>decide (nonpDegree coord pc q≠0)) ++ + l.filter (fun q=>decide (nonpDegree coord pc q=0)))=l := by + cases pos + · simp only [Bool.false_eq_true,ite_false] + suffices H : l.Pairwise (fun a b => nonpDegree coord pc b ≠ 0 → + nonpDegree coord pc a ≠ 0) from by + simpa only [not_not] using ordered_filter_partition (fun q=>nonpDegree coord pc q≠0) l H + apply hl.imp_of_mem + intro a b ha hb hab hnb hpa + obtain ⟨d,hd,hr⟩:=hroot a ha + rw [nonp_zero_root C coord hcoord pc hr hpa,map_nsmul] at hab + have HH:=htrend b hb + simp only [sideSign,Bool.false_eq_true,ite_false,neg_one_mul] at HH + have hdZ : 0<(d:ℤ):=by exact_mod_cast hd + change 0<(d:ℤ)*Ω (simpleRoot C pc) b at hab + nlinarith + · simp only [ite_true] + apply ordered_filter_partition (fun q=>nonpDegree coord pc q=0) l + apply hl.imp_of_mem + intro a b ha hb hab hpb + obtain ⟨d,hd,hr⟩:=hroot b hb + rw [nonp_zero_root C coord hcoord pc hr hpb,map_nsmul] at hab + have HH:=htrend a ha + simp only [sideSign,ite_true,one_mul] at HH + rw [alternating_int_swap Ω hΩ a (simpleRoot C pc)] at hab + have hdZ : 0<(d:ℤ):=by exact_mod_cast hd + change 0<(d:ℤ)*(-Ω (simpleRoot C pc) a) at hab + exact (by nlinarith : False).elim + +lemma ray_nonp_zero {q m : M} (hq : nonpDegree coord pc q=0) (hm : OnPositiveRay q m) : + nonpDegree coord pc m=0 := by + obtain ⟨a,b,ha,hb,he⟩:=hm + have H:=congrArg (nonpDegree coord pc) he + rw [map_nsmul,map_nsmul,hq,nsmul_zero,nsmul_eq_mul] at H + exact (mul_eq_zero.mp H).resolve_left (by exact_mod_cast Nat.ne_of_gt ha) +lemma ray_nonp_pos {q m : M} (hq : 0simpa only [coeff_zero_eq_constantCoeff_apply,map_one] using (pureFace _ _ _ _ F).property.1 + | succ j=> + rw [coeff_one,ite_eq_right (by omega)] + apply Finsupp.ext + intro m + change coeff (j+1) (pureFaceSeries Ω coord pc F.val) m=0 + rw [pureFaceSeries_apply] + split_ifs with hh + · by_contra hn + have HG:=hF j m hn + omega + · rfl +lemma pureFace_of_strict_zero (F : CompletedPositive LaurentRay.vUnit Ω C) + (hF : ∀j m,coeff (j+1) F.val m≠0 → nonpDegree coord pc m=0) : + (pureFace Ω C coord pc F).val=F.val := by + apply PowerSeries.ext + intro j + apply pureFaceSeries_eq_through Ω coord pc F.val j ?_ j le_rfl + intro k hk m hm + cases k with + | zero=> + rw [coeff_zero_eq_constantCoeff_apply,F.property.1] at hm + have hm0 : m=0:=by by_contra hh; exact hm (Finsupp.single_eq_of_ne hh) + rw [hm0,map_zero] + | succ k=>exact hF k m hm + +lemma pureFace_list_nonpure (_hcoord : ∀d,coord (C d)=d) (pc : I) + (l : List M) (F : M → CompletedPositive LaurentRay.vUnit Ω C) + (hl : ∀q∈l,00by simpa only [map_add] using add_pos ha hb) (j+1) ?_ j le_rfl m hn + intro q hq k hk m hm + by_contra hv + exact hm (ray_nonp_pos coord pc (hl q hq) (hF q hq k m hv)) +lemma pureFace_list_pure (_hcoord : ∀d,coord (C d)=d) (pc : I) + (l : List M) (F : M → CompletedPositive LaurentRay.vUnit Ω C) + (hl : ∀q∈l,nonpDegree coord pc q=0) + (hF : ∀q∈l,∀j m,coeff (j+1) (F q).val m≠0 → OnPositiveRay q m) : + (pureFace Ω C coord pc (completedListProduct LaurentRay.vUnit Ω C l F)).val= + (completedListProduct LaurentRay.vUnit Ω C l F).val := by + apply pureFace_of_strict_zero Ω C coord pc + intro j m hm + by_contra hn + apply hm + apply strict_list_product_through LaurentRay.vUnit Ω C l F + (fun m=>nonpDegree coord pc m=0) + (fun a b ha hb=>by simp only [map_add,ha,hb,add_zero]) (j+1) ?_ j le_rfl m hn + intro q hq k hk m hm + by_contra hv + exact hm (ray_nonp_zero coord pc (hl q hq) (hF q hq k m hv)) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/QuantumTorus.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/QuantumTorus.lean new file mode 100644 index 0000000000000000000000000000000000000000..7f1e756cc63719a9531c25e7a9f7ac2a6665c4ff --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/QuantumTorus.lean @@ -0,0 +1,135 @@ +import Mathlib + +namespace OAI + +section +section +namespace ElementaryPositivity.QuantumTorus + +variable {R M : Type*} [CommRing R] [AddCommGroup M] + +@[reducible] def Torus (_ : Rˣ) (_ : M →+ M →+ ℤ) := M →₀ R + +namespace Torus +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) + +noncomputable instance : AddCommGroup (Torus v Ω) := inferInstanceAs (AddCommGroup (M →₀ R)) +noncomputable instance : Module R (Torus v Ω) := inferInstanceAs (Module R (M →₀ R)) + +noncomputable def monomial (m : M) (r : R) : Torus v Ω := Finsupp.single m r +noncomputable def multiply (f g : Torus v Ω) : Torus v Ω := + Finsupp.sum f fun m a => Finsupp.sum g fun n b => + Finsupp.single (m+n) (a*b*↑(v^(Ω m n))) + +noncomputable instance : Mul (Torus v Ω) := ⟨multiply v Ω⟩ +noncomputable instance : One (Torus v Ω) := ⟨monomial v Ω 0 1⟩ + +@[simp] lemma monomial_zero (m : M) : monomial v Ω m (0 : R) = 0 := Finsupp.single_zero _ +@[simp] lemma monomial_add (m : M) (a b : R) : + monomial v Ω m (a+b) = monomial v Ω m a + monomial v Ω m b := Finsupp.single_add .. +lemma monomial_smul (m : M) (a b : R) : + monomial v Ω m (a*b) = a • monomial v Ω m b := by + simp only [monomial, Finsupp.smul_single, smul_eq_mul] + +@[simp] lemma mul_zero (f : Torus v Ω) : f*0 = 0 := by simp [HMul.hMul, Mul.mul, multiply] +@[simp] lemma zero_mul (f : Torus v Ω) : (0 : Torus v Ω)*f = 0 := by + simp [HMul.hMul, Mul.mul, multiply] + +lemma add_mul (f g h : Torus v Ω) : (f+g)*h = f*h+g*h := by + classical + change multiply v Ω (f+g) h = multiply v Ω f h + multiply v Ω g h + simp only [multiply] + rw [Finsupp.sum_add_index'] + · intro m + simp + · intro m a b + simp only [_root_.add_mul, Finsupp.single_add, Finsupp.sum_add] + +lemma mul_add (f g h : Torus v Ω) : f*(g+h) = f*g+f*h := by + classical + change multiply v Ω f (g+h) = multiply v Ω f g + multiply v Ω f h + simp only [multiply] + rw [← Finsupp.sum_add] + apply Finsupp.sum_congr + intro m hm + rw [Finsupp.sum_add_index'] + · intro n + simp + · intro n a b + simp only [_root_.mul_add, _root_.add_mul, Finsupp.single_add] + +@[simp] lemma monomial_mul_monomial (m n : M) (a b : R) : + monomial v Ω m a * monomial v Ω n b = + monomial v Ω (m+n) (a*b*↑(v^(Ω m n))) := by + classical + change multiply v Ω (Finsupp.single m a) (Finsupp.single n b) = _ + simp only [multiply, monomial, Finsupp.sum_single_index, MulZeroClass.zero_mul, + MulZeroClass.mul_zero, Finsupp.single_zero] + +lemma mul_assoc (f g h : Torus v Ω) : (f*g)*h=f*(g*h) := by + classical + induction f using Finsupp.induction_linear with + | zero => simp + | add f f' hf hf' => simp only [add_mul, hf, hf'] + | single m a => + induction g using Finsupp.induction_linear with + | zero => simp + | add g g' hg hg' => simp only [mul_add, add_mul, hg, hg'] + | single n b => + induction h using Finsupp.induction_linear with + | zero => simp + | add h h' hh hh' => simp only [mul_add, hh, hh'] + | single p c => + change (monomial v Ω m a * monomial v Ω n b) * monomial v Ω p c = + monomial v Ω m a * (monomial v Ω n b * monomial v Ω p c) + simp only [monomial_mul_monomial, map_add, AddMonoidHom.add_apply, add_assoc] + congr 1 + simp only [zpow_add, Units.val_mul] + ring + +@[simp] lemma one_mul (f : Torus v Ω) : (1 : Torus v Ω)*f=f := by + classical + induction f using Finsupp.induction_linear with + | zero => simp + | add f g hf hg => rw [mul_add, hf, hg] + | single m a => + change monomial v Ω 0 1 * monomial v Ω m a = monomial v Ω m a + simp only [monomial_mul_monomial, map_zero, AddMonoidHom.zero_apply, + zero_add, _root_.one_mul, zpow_zero, Units.val_one, _root_.mul_one] + +@[simp] lemma mul_one (f : Torus v Ω) : f*(1 : Torus v Ω)=f := by + classical + induction f using Finsupp.induction_linear with + | zero => simp + | add f g hf hg => rw [add_mul, hf, hg] + | single m a => + change monomial v Ω m a * monomial v Ω 0 1 = monomial v Ω m a + simp only [monomial_mul_monomial, map_zero, add_zero, _root_.mul_one, zpow_zero, Units.val_one] + +noncomputable instance : Ring (Torus v Ω) := + Ring.ofMinimalAxioms _root_.add_assoc _root_.zero_add _root_.neg_add_cancel + (mul_assoc v Ω) (one_mul v Ω) (mul_one v Ω) (mul_add v Ω) (add_mul v Ω) + +noncomputable def X (m : M) : Torus v Ω := monomial v Ω m 1 + +@[simp] lemma X_zero : X v Ω 0 = 1 := rfl +lemma X_mul_X (m n : M) : X v Ω m * X v Ω n = (↑(v^(Ω m n)) : R) • X v Ω (m+n) := by + simp only [X, monomial_mul_monomial, _root_.one_mul] + simpa only [_root_.mul_one] using monomial_smul v Ω (m+n) (↑(v^(Ω m n)) : R) 1 + +lemma X_mul_X_of_pairing_zero (m n : M) (h : Ω m n = 0) : + X v Ω m * X v Ω n = X v Ω (m+n) := by + simp [X_mul_X, h] + +lemma X_commute (m n : M) (h₁ : Ω m n = 0) (h₂ : Ω n m = 0) : + Commute (X v Ω m) (X v Ω n) := by + show X v Ω m * X v Ω n = X v Ω n * X v Ω m + simp only [X_mul_X_of_pairing_zero v Ω m n h₁, + X_mul_X_of_pairing_zero v Ω n m h₂, add_comm] + +end Torus +end ElementaryPositivity.QuantumTorus +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalFiberTorus.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalFiberTorus.lean new file mode 100644 index 0000000000000000000000000000000000000000..74bb12a0b6e105378b6efa6c12fc2bebe079fb87 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalFiberTorus.lean @@ -0,0 +1,173 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RationalFiberScale + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +@[reducible] def FiberTorus (_v : Kˣ) (_Ω : M →+ M →+ ℤ) (_α : M →+ ℤ) := M →₀ RatFunc K +namespace FiberTorus +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (α : M →+ ℤ) +instance : AddCommGroup (FiberTorus v Ω α) := inferInstanceAs (AddCommGroup (M →₀ RatFunc K)) +def monomial (m : M) (a : RatFunc K) : FiberTorus v Ω α := Finsupp.single m a +def twist (m : M) : RatFunc K →+* RatFunc K := scale (v^(-2*α m)) +lemma twist_add (m n : M) (a : RatFunc K) : twist v α (m+n) a=twist v α m (twist v α n a) := by + change scale (v^(-2*α (m+n))) a=((scale (v^(-2*α m))).comp (scale (v^(-2*α n)))) a + rw [scale_mul,map_add,mul_add,zpow_add] +@[simp] lemma twist_constant (m : M) (a : K) : twist v α m (RatFunc.C a)=RatFunc.C a := scale_constant _ _ +@[simp] lemma twist_zero (a : RatFunc K) : twist v α 0 a=a := by simp [twist] +def multiply (f g : FiberTorus v Ω α) : FiberTorus v Ω α := + Finsupp.sum f fun m a=>Finsupp.sum g fun n b=> + Finsupp.single (m+n) (a*twist v α m b*RatFunc.C (↑(v^(Ω m n)):K)) +instance : Mul (FiberTorus v Ω α) := ⟨multiply v Ω α⟩ +instance : One (FiberTorus v Ω α) := ⟨monomial v Ω α 0 1⟩ +@[simp] lemma monomial_zero (m : M) : monomial v Ω α m 0=0 := Finsupp.single_zero _ +@[simp] lemma monomial_add (m : M) (a b : RatFunc K) : + monomial v Ω α m (a+b)=monomial v Ω α m a+monomial v Ω α m b := Finsupp.single_add .. +@[simp] lemma mul_zero (f : FiberTorus v Ω α) : f*0=0 := by simp [HMul.hMul,Mul.mul,multiply] +@[simp] lemma zero_mul (f : FiberTorus v Ω α) : (0 : FiberTorus v Ω α)*f=0 := by simp [HMul.hMul,Mul.mul,multiply] +lemma add_mul (f g h : FiberTorus v Ω α) : (f+g)*h=f*h+g*h := by + classical + change multiply v Ω α (f+g) h=multiply v Ω α f h+multiply v Ω α g h + simp only [multiply] + rw [Finsupp.sum_add_index'] + · intro m; simp + · intro m a b + simp only [_root_.add_mul,Finsupp.single_add,Finsupp.sum_add] +lemma mul_add (f g h : FiberTorus v Ω α) : f*(g+h)=f*g+f*h := by + classical + change multiply v Ω α f (g+h)=multiply v Ω α f g+multiply v Ω α f h + simp only [multiply] + rw [←Finsupp.sum_add] + apply Finsupp.sum_congr + intro m ha + rw [Finsupp.sum_add_index'] + · intro n; simp + · intro n a b + simp only [map_add,_root_.mul_add,_root_.add_mul,Finsupp.single_add] +@[simp] lemma monomial_mul (m n : M) (a b : RatFunc K) : + monomial v Ω α m a*monomial v Ω α n b= + monomial v Ω α (m+n) (a*twist v α m b*RatFunc.C (↑(v^(Ω m n)):K)) := by + classical + change multiply v Ω α (Finsupp.single m a) (Finsupp.single n b)=_ + simp only [multiply,monomial,Finsupp.sum_single_index,MulZeroClass.zero_mul, + MulZeroClass.mul_zero,map_zero,Finsupp.single_zero] +lemma mul_assoc (f g h : FiberTorus v Ω α) : (f*g)*h=f*(g*h) := by + classical + induction f using Finsupp.induction_linear with + | zero=>simp + | add f f' hf hf'=>simp only [add_mul,hf,hf'] + | single m a=> + induction g using Finsupp.induction_linear with + | zero=>simp + | add g g' hg hg'=>simp only [mul_add,add_mul,hg,hg'] + | single n b=> + induction h using Finsupp.induction_linear with + | zero=>simp + | add h h' hh hh'=>simp only [mul_add,hh,hh'] + | single p c=> + change (monomial v Ω α m a*monomial v Ω α n b)*monomial v Ω α p c= + monomial v Ω α m a*(monomial v Ω α n b*monomial v Ω α p c) + simp only [monomial_mul,map_add,AddMonoidHom.add_apply,add_assoc] + congr 1 + simp only [zpow_add,Units.val_mul,map_mul,twist_constant,twist_add] + ring +@[simp] lemma one_mul (f : FiberTorus v Ω α) : (1 : FiberTorus v Ω α)*f=f := by + classical + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>rw [mul_add,hf,hg] + | single m a=> + change monomial v Ω α 0 1*monomial v Ω α m a=monomial v Ω α m a + simp only [monomial_mul,map_zero,AddMonoidHom.zero_apply,zero_add, + _root_.one_mul,zpow_zero,Units.val_one,map_one,_root_.mul_one,twist_zero] +@[simp] lemma mul_one (f : FiberTorus v Ω α) : f*(1 : FiberTorus v Ω α)=f := by + classical + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>rw [add_mul,hf,hg] + | single m a=> + change monomial v Ω α m a*monomial v Ω α 0 1=monomial v Ω α m a + simp only [monomial_mul,map_zero,add_zero,_root_.mul_one,zpow_zero,Units.val_one,map_one] +instance : Ring (FiberTorus v Ω α) := + Ring.ofMinimalAxioms _root_.add_assoc _root_.zero_add _root_.neg_add_cancel + (mul_assoc v Ω α) (one_mul v Ω α) (mul_one v Ω α) (mul_add v Ω α) (add_mul v Ω α) +def coefficient (a : RatFunc K) : FiberTorus v Ω α := monomial v Ω α 0 a +def X (m : M) : FiberTorus v Ω α := monomial v Ω α m 1 +lemma rational_commutation (m : M) (f : RatFunc K) : + X v Ω α m*coefficient v Ω α f=coefficient v Ω α (twist v α m f)*X v Ω α m := by + simp [X,coefficient,monomial_mul] +end FiberTorus +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +def off : M →+ k.ker where + toFun m:=⟨m-(k m) • p,by simp [map_sub,map_zsmul,hp]⟩ + map_zero':=by ext; simp + map_add' m n:=by ext; simp [map_add,add_smul]; abel +@[simp] lemma off_val (m : M) : (off k p hp m : M)=m-k m • p := rfl +lemma split_sum (m : M) : k m • p+(off k p hp m : M)=m := by rw [off_val]; abel +@[simp] lemma off_p : off k p hp p=0 := by ext; simp [hp] +@[simp] lemma off_complement (m : k.ker) : off k p hp m=m := by + ext + have hm : k m=0:=m.property + simp [hm] +def complementAlpha (Ω : M →+ M →+ ℤ) : k.ker →+ ℤ := (Ω p).comp k.ker.subtype +def complementOmega (Ω : M →+ M →+ ℤ) : k.ker →+ k.ker →+ ℤ where + toFun m:=(Ω m).comp k.ker.subtype + map_zero':=by ext; simp + map_add' m n:=by ext; simp +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +include hΩ in +lemma split_pairing (m n : M) : Ω m n= + k m*complementAlpha k p Ω (off k p hp n)- + k n*complementAlpha k p Ω (off k p hp m)+ + complementOmega k Ω (off k p hp m) (off k p hp n) := by + have hs (a b : M) : Ω a b= -Ω b a := by + have H:=hΩ (a+b) + simp only [map_add,AddMonoidHom.add_apply,hΩ] at H + omega + change Ω m n=k m*Ω p (off k p hp n)-k n*Ω p (off k p hp m)+ + Ω (off k p hp m : M) (off k p hp n : M) + conv_lhs=>rw [←split_sum k p hp m,←split_sum k p hp n] + simp only [map_add,AddMonoidHom.add_apply,map_zsmul,AddMonoidHom.zsmul_apply,hΩ, + smul_eq_mul] + rw [hs (off k p hp m : M) p] + ring + +def centeredScalar (v : Kˣ) (n a : ℤ) : RatFunc K := + RatFunc.C (↑(v^(-n*a)):K)*RatFunc.X^n +lemma centeredScalar_mul (v : Kˣ) (n l a b c : ℤ) : + centeredScalar v n a*scale (v^(-2*a)) (centeredScalar v l b)* + RatFunc.C (↑(v^c):K)= + RatFunc.C (↑(v^(n*b-l*a+c)):K)*centeredScalar v (n+l) (a+b) := by + have hv : (v:K)≠0:=Units.ne_zero v + have hz : (RatFunc.X : RatFunc K)≠0:=RatFunc.X_ne_zero + simp only [centeredScalar,map_mul,scale_constant,map_zpow₀,scale_X,mul_zpow] + simp only [←map_zpow₀,←Units.val_zpow_eq_zpow_val,←zpow_mul] + have hleft : + RatFunc.C (↑(v^(-n*a)):K)*RatFunc.X^n* + (RatFunc.C (↑(v^(-l*b)):K)*(RatFunc.C (↑(v^(-2*a*l)):K)*RatFunc.X^l))* + RatFunc.C (↑(v^c):K)= + RatFunc.C (↑(v^(-n*a)):K)*RatFunc.C (↑(v^(-l*b)):K)* + RatFunc.C (↑(v^(-2*a*l)):K)*RatFunc.C (↑(v^c):K)* + (RatFunc.X^n*RatFunc.X^l) := by ring + rw [hleft,←map_mul,←map_mul,←map_mul,←Units.val_mul,←Units.val_mul,←Units.val_mul, + ←zpow_add,←zpow_add,←zpow_add,←zpow_add₀ hz] + rw [←mul_assoc,←map_mul,←Units.val_mul,←zpow_add] + congr 3 + ring_nf +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalPureAction.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalPureAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..ceba65b67cfe589d624ad2ef88d30cd1d7456963 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalPureAction.lean @@ -0,0 +1,116 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalFiberTorus +import OAI.Combinatorics.Chromatic.Walls.RationalPureCocycle + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (α : M →+ ℤ) +namespace FiberTorus + +def gaugeMonomial (c : ℤ → RatFunc K) (m : M) : RatFunc K →+ FiberTorus v Ω α where + toFun a:=monomial v Ω α m (a*c (α m)) + map_zero':=by simp + map_add' a b:=by simp only [_root_.add_mul,monomial_add] +def gaugeAdd (c : ℤ → RatFunc K) : FiberTorus v Ω α →+ FiberTorus v Ω α := + Finsupp.liftAddHom (gaugeMonomial v Ω α c) +@[simp] lemma gaugeAdd_monomial (c : ℤ → RatFunc K) (m : M) (a : RatFunc K) : + gaugeAdd v Ω α c (monomial v Ω α m a)=monomial v Ω α m (a*c (α m)) := + Finsupp.liftAddHom_apply_single _ _ _ +lemma gaugeAdd_mul (c : ℤ → RatFunc K) (hc : ∀t u,c (t+u)=c t*scale (v^(-2*t)) (c u)) + (f g : FiberTorus v Ω α) : + gaugeAdd v Ω α c (f*g)=gaugeAdd v Ω α c f*gaugeAdd v Ω α c g := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f f' hf hf'=>simp only [add_mul,map_add,hf,hf'] + | single m a=> + induction g using Finsupp.induction_linear with + | zero=>simp + | add g g' hg hg'=>simp only [mul_add,map_add,hg,hg'] + | single n b=> + change gaugeAdd v Ω α c (monomial v Ω α m a*monomial v Ω α n b)= + gaugeAdd v Ω α c (monomial v Ω α m a)*gaugeAdd v Ω α c (monomial v Ω α n b) + rw [monomial_mul,gaugeAdd_monomial,gaugeAdd_monomial,gaugeAdd_monomial,monomial_mul] + simp only [map_add,hc,map_mul] + congr 1 + change a*twist v α m b*RatFunc.C (↑(v^(Ω m n)):K)* + (c (α m)*twist v α m (c (α n)))= + (a*c (α m))*(twist v α m b*twist v α m (c (α n)))*RatFunc.C (↑(v^(Ω m n)):K) + ring +lemma gaugeAdd_one (c : ℤ → RatFunc K) (hc : c 0=1) : gaugeAdd v Ω α c 1=1 := by + change gaugeAdd v Ω α c (monomial v Ω α 0 1)=monomial v Ω α 0 1 + rw [gaugeAdd_monomial,map_zero,hc,_root_.mul_one] +def gauge (c : ℤ → RatFunc K) (hc0 : c 0=1) + (hc : ∀t u,c (t+u)=c t*scale (v^(-2*t)) (c u)) : FiberTorus v Ω α →+* FiberTorus v Ω α where + __:=gaugeAdd v Ω α c + map_one':=gaugeAdd_one v Ω α c hc0 + map_mul':=gaugeAdd_mul v Ω α c hc +@[simp] lemma gauge_monomial (c : ℤ → RatFunc K) (hc0 : c 0=1) + (hc : ∀t u,c (t+u)=c t*scale (v^(-2*t)) (c u)) (m : M) (a : RatFunc K) : + gauge v Ω α c hc0 hc (monomial v Ω α m a)=monomial v Ω α m (a*c (α m)) := + gaugeAdd_monomial v Ω α c m a +lemma gauge_comp (c d : ℤ → RatFunc K) (f : FiberTorus v Ω α) : + gaugeAdd v Ω α c (gaugeAdd v Ω α d f)=gaugeAdd v Ω α (fun t=>d t*c t) f := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [map_add,hf,hg] + | single m a=> + change gaugeAdd v Ω α c (gaugeAdd v Ω α d (monomial v Ω α m a))= + gaugeAdd v Ω α (fun t=>d t*c t) (monomial v Ω α m a) + simp only [gaugeAdd_monomial,_root_.mul_assoc] +lemma gaugeAdd_trivial (f : FiberTorus v Ω α) : gaugeAdd v Ω α (fun _=>1) f=f := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [map_add,hf,hg] + | single m a=> + change gaugeAdd v Ω α (fun _=>1) (monomial v Ω α m a)=monomial v Ω α m a + rw [gaugeAdd_monomial,_root_.mul_one] +end FiberTorus + +lemma pureRatio_val_add (t u : ℤ) : (pureRatio v (t+u):RatFunc K)= + (pureRatio v t:RatFunc K)*scale (v^(-2*t)) (pureRatio v u:RatFunc K) := by + rw [pureRatio_add,Units.val_mul,scaleAction_val] + rfl +lemma pureRatio_inv_val_add (t u : ℤ) : (↑((pureRatio v (t+u))⁻¹):RatFunc K)= + (↑((pureRatio v t)⁻¹):RatFunc K)*scale (v^(-2*t)) (↑((pureRatio v u)⁻¹):RatFunc K) := by + simp only [Units.val_inv_eq_inv_val,pureRatio_val_add,map_inv₀,mul_inv_rev] + exact mul_comm _ _ +def pureActionHom : FiberTorus v Ω α →+* FiberTorus v Ω α := + FiberTorus.gauge v Ω α (fun t=>(pureRatio v t:RatFunc K)) (by simp) (pureRatio_val_add v) +def pureActionInvHom : FiberTorus v Ω α →+* FiberTorus v Ω α := + FiberTorus.gauge v Ω α (fun t=>(↑((pureRatio v t)⁻¹):RatFunc K)) (by simp) (pureRatio_inv_val_add v) +lemma pureAction_cancel (f : FiberTorus v Ω α) : + pureActionHom v Ω α (pureActionInvHom v Ω α f)=f := by + change FiberTorus.gaugeAdd v Ω α _ (FiberTorus.gaugeAdd v Ω α _ f)=_ + rw [FiberTorus.gauge_comp] + simpa using FiberTorus.gaugeAdd_trivial v Ω α f +lemma pureActionInv_cancel (f : FiberTorus v Ω α) : + pureActionInvHom v Ω α (pureActionHom v Ω α f)=f := by + change FiberTorus.gaugeAdd v Ω α _ (FiberTorus.gaugeAdd v Ω α _ f)=_ + rw [FiberTorus.gauge_comp] + simpa using FiberTorus.gaugeAdd_trivial v Ω α f +def pureAction : FiberTorus v Ω α ≃+* FiberTorus v Ω α := + RingEquiv.ofRingHom (pureActionHom v Ω α) (pureActionInvHom v Ω α) + (RingHom.ext (pureAction_cancel v Ω α)) (RingHom.ext (pureActionInv_cancel v Ω α)) +@[simp] lemma pureAction_monomial (m : M) (a : RatFunc K) : + pureAction v Ω α (FiberTorus.monomial v Ω α m a)= + FiberTorus.monomial v Ω α m (a*(pureRatio v (α m):RatFunc K)) := + FiberTorus.gaugeAdd_monomial v Ω α (fun t=>(pureRatio v t:RatFunc K)) m a +@[simp] lemma pureAction_coefficient (a : RatFunc K) : + pureAction v Ω α (FiberTorus.coefficient v Ω α a)=FiberTorus.coefficient v Ω α a := by + simp [FiberTorus.coefficient] + +def completedPureAction : PowerSeries (FiberTorus v Ω α) ≃+* PowerSeries (FiberTorus v Ω α) := + RingEquiv.ofRingHom (PowerSeries.map (pureAction v Ω α).toRingHom) + (PowerSeries.map (pureAction v Ω α).symm.toRingHom) + (by apply RingHom.ext; intro f; ext n; simp [PowerSeries.coeff_map]) + (by apply RingHom.ext; intro f; ext n; simp [PowerSeries.coeff_map]) +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalTorusEmbedding.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalTorusEmbedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1f818769ceae10eb204152dd40ed8ee8e0b9df6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalTorusEmbedding.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalFiberTorus + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) + +def embeddedMonomial (m : M) : K →+ + FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω) where + toFun a:=FiberTorus.monomial v _ _ (off k p hp m) + (RatFunc.C a*centeredScalar v (k m) (complementAlpha k p Ω (off k p hp m))) + map_zero':=by simp + map_add' a b:=by simp [add_mul] +def embedAdd : Torus v Ω →+ + FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω) := + Finsupp.liftAddHom (embeddedMonomial v Ω k p hp) +@[simp] lemma embedAdd_monomial (m : M) (a : K) : + embedAdd v Ω k p hp (Torus.monomial v Ω m a)= + FiberTorus.monomial v _ _ (off k p hp m) + (RatFunc.C a*centeredScalar v (k m) (complementAlpha k p Ω (off k p hp m))) := + Finsupp.liftAddHom_apply_single _ _ _ +include hΩ in +lemma embeddedMonomial_mul (m n : M) (a b : K) : + embedAdd v Ω k p hp (Torus.monomial v Ω m a*Torus.monomial v Ω n b)= + embedAdd v Ω k p hp (Torus.monomial v Ω m a)* + embedAdd v Ω k p hp (Torus.monomial v Ω n b) := by + rw [Torus.monomial_mul_monomial,embedAdd_monomial,embedAdd_monomial,embedAdd_monomial, + FiberTorus.monomial_mul] + simp only [map_add] + congr 1 + simp only [map_mul,FiberTorus.twist_constant] + let am:=complementAlpha k p Ω (off k p hp m) + let an:=complementAlpha k p Ω (off k p hp n) + let c:=complementOmega k Ω (off k p hp m) (off k p hp n) + change RatFunc.C a*RatFunc.C b*RatFunc.C (↑(v^(Ω m n)):K)* + centeredScalar v (k m+k n) (am+an)= + (RatFunc.C a*centeredScalar v (k m) am)* + (RatFunc.C b*scale (v^(-2*am)) (centeredScalar v (k n) an))*RatFunc.C (↑(v^c):K) + have H:=centeredScalar_mul v (k m) (k n) am an c + rw [←split_pairing k p hp Ω hΩ m n] at H + calc + _ = RatFunc.C a*RatFunc.C b*(RatFunc.C (↑(v^(Ω m n)):K)* + centeredScalar v (k m+k n) (am+an)) := by ring + _ = RatFunc.C a*RatFunc.C b*(centeredScalar v (k m) am* + scale (v^(-2*am)) (centeredScalar v (k n) an)*RatFunc.C (↑(v^c):K)) := by rw [H] + _ = _ := by ring +include hΩ in +lemma embedAdd_mul (f g : Torus v Ω) : + embedAdd v Ω k p hp (f*g)=embedAdd v Ω k p hp f*embedAdd v Ω k p hp g := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f f' hf hf'=>simp only [add_mul,map_add,hf,hf'] + | single m a=> + induction g using Finsupp.induction_linear with + | zero=>simp + | add g g' hg hg'=>simp only [mul_add,map_add,hg,hg'] + | single n b=>exact embeddedMonomial_mul v Ω hΩ k p hp m n a b +lemma embedAdd_one : embedAdd v Ω k p hp 1=1 := by + change embedAdd v Ω k p hp (Torus.monomial v Ω 0 1)=FiberTorus.monomial v _ _ 0 1 + simp [embedAdd_monomial,centeredScalar] +def embed : Torus v Ω →+* FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω) where + __:=embedAdd v Ω k p hp + map_one':=embedAdd_one v Ω k p hp + map_mul':=embedAdd_mul v Ω hΩ k p hp +@[simp] lemma embed_monomial (m : M) (a : K) : + embed v Ω hΩ k p hp (Torus.monomial v Ω m a)= + FiberTorus.monomial v _ _ (off k p hp m) + (RatFunc.C a*centeredScalar v (k m) (complementAlpha k p Ω (off k p hp m))) := + embedAdd_monomial v Ω k p hp m a +@[simp] lemma embed_p : embed v Ω hΩ k p hp (Torus.X v Ω p)= + FiberTorus.coefficient v _ _ RatFunc.X := by + simp [Torus.X,embed_monomial,hp,centeredScalar,FiberTorus.coefficient] +@[simp] lemma embed_complement (m : k.ker) : + embed v Ω hΩ k p hp (Torus.X v Ω m)=FiberTorus.X v _ _ m := by + have hm : k m=0:=m.property + simp [Torus.X,embed_monomial,hm,centeredScalar,FiberTorus.X] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalTorusFaithful.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalTorusFaithful.lean new file mode 100644 index 0000000000000000000000000000000000000000..30db14583ea471c87c29d6ab01a984676715eeb7 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/RationalTorusFaithful.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalTorusEmbedding +import OAI.Combinatorics.Chromatic.Walls.RationalFiberReciprocal + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +lemma expand_centeredScalar (n a : ℤ) (b : K) : + expandZero (RatFunc.C b*centeredScalar v n a)= + HahnSeries.single n (b*(↑(v^(-n*a)):K)) := by + rw [centeredScalar,←mul_assoc,←map_mul,map_mul,expandZero_constant,expandZero_X_zpow] + simp [HahnSeries.C] + +def readFiber (m : M) : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω) →+ K where + toFun f:=(expandZero (f (off k p hp m))).coeff (k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K) + map_zero':=by simp + map_add' f g:=by simp [add_mul] +lemma split_injective {m n : M} (hk : k m=k n) (ho : off k p hp m=off k p hp n) : m=n := by + rw [←split_sum k p hp m,←split_sum k p hp n,hk,ho] +lemma readFiber_monomial (m n : M) (a : K) : + readFiber v Ω k p hp m (embedAdd v Ω k p hp (Torus.monomial v Ω n a))= + (Torus.monomial v Ω n a) m := by + classical + rw [embedAdd_monomial] + change (expandZero ((Finsupp.single (off k p hp n) + (RatFunc.C a*centeredScalar v (k n) (complementAlpha k p Ω (off k p hp n)))) + (off k p hp m))).coeff (k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K)=Finsupp.single n a m + by_cases ho : off k p hp n=off k p hp m + · rw [Finsupp.single_apply,ite_eq_left ho,expand_centeredScalar] + by_cases hk : k n=k m + · have hn : n=m:=split_injective k p hp hk ho + subst n + rw [HahnSeries.coeff_single,ite_eq_left rfl,Finsupp.single_eq_same] + rw [mul_assoc,←Units.val_mul,←zpow_add] + simp + · have hn : n≠m:=fun h=>hk (congrArg k h) + simp [Ne.symm hk,Finsupp.single_eq_of_ne (Ne.symm hn)] + · have hn : n≠m:=fun h=>ho (congrArg (off k p hp) h) + rw [Finsupp.single_apply,ite_eq_right ho] + simp [Finsupp.single_eq_of_ne (Ne.symm hn)] +lemma readFiber_embedAdd (f : Torus v Ω) (m : M) : + readFiber v Ω k p hp m (embedAdd v Ω k p hp f)=f m := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp [map_add,hf,hg] + | single n a=>exact readFiber_monomial v Ω k p hp m n a +lemma embed_injective : Function.Injective (embed v Ω hΩ k p hp) := by + intro f g h + ext m + have H:=congrArg (readFiber v Ω k p hp m) h + change readFiber v Ω k p hp m (embedAdd v Ω k p hp f)= + readFiber v Ω k p hp m (embedAdd v Ω k p hp g) at H + simpa only [readFiber_embedAdd] using H +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionCharts.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionCharts.lean new file mode 100644 index 0000000000000000000000000000000000000000..d4b62f051ab9d3952b442b8f6ec29bcd418d6d1c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionCharts.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ChartRefinement +import OAI.Combinatorics.Chromatic.Walls.TranslatedCompletion +import OAI.Combinatorics.Chromatic.QuantumTorus.SectionTrace + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesSplit PowerSeriesAdjoint +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +lemma negative_sign_congr_through (h k : M →+ ℝ) (F : CompletedPositive v Ω C) (N : ℕ) + (hs : ∀n,0(hs (n+1) (by omega) hn m (chart_root_of_ne v Ω C _ _ _ hm)).1 (H.1 n m hm)) + (fun n hn m hm=>(hs (n+1) (by omega) hn m (chart_root_of_ne v Ω C _ _ _ hm)).2.1 (H.2.1 n m hm)) + (fun n hn m hm=>(hs (n+1) (by omega) hn m (chart_root_of_ne v Ω C _ _ _ hm)).2.2 (H.2.2 n m hm)) + exact fun n hn=>(HU n hn).2.2 +lemma section_sign_congr_through (h k : M →+ ℝ) (F : CompletedPositive v Ω C) + (X : PowerSeries (Torus v Ω)) (N : ℕ) + (hs : ∀n,0negative_sign_congr_through v Ω C h k F N hs j (hj.trans hn)) (fun _ _=>rfl) +lemma section_refinement_through (h k H : M →+ ℝ) (F : CompletedPositive v Ω C) + (X : PowerSeries (Torus v Ω)) (N : ℕ) + (hs : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h k H m) : + ∀n≤N,coeff n (sectionValue v Ω C F H X)= + coeff n (adjoint (chartNegative v Ω C k (chartZero v Ω C h F)).val + (sectionValue v Ω C F h X)) := by + intro n hn + unfold sectionValue + rw [←adjoint_mul _ _ _ (chartNegative v Ω C k (chartZero v Ω C h F)).property.1 + (chartNegative v Ω C h F).property.1] + exact adjoint_coeff_congr _ _ _ _ n + (fun j hj=>chart_negative_refinement v Ω C h k H F N hs j (hj.trans hn)) (fun _ _=>rfl) +lemma section_incoming_perturbation (hΩ : ∀m,Ω m m=0) (r : M) (k H : M →+ ℝ) + (F : CompletedPositive v Ω C) (X : PowerSeries (Torus v Ω)) (N : ℕ) + (hs : ∀n≤N,∀m,HasRootDegree C n m → LexSigns (incomingCovector Ω r) k H m) : + (coeff N (sectionValue v Ω C F H X)) r= + (coeff N (sectionValue v Ω C F (incomingCovector Ω r) X)) r := by + rw [section_refinement_through v Ω C _ _ _ F X N hs N le_rfl] + apply adjoint_coefficient_trace v Ω hΩ r _ _ N + (chartNegative v Ω C k (chartZero v Ω C (incomingCovector Ω r) F)).property.1 + have hker:=chartThree_supported v Ω C k (incomingCovector Ω r).ker.toAddSubmonoid + (chartZero v Ω C (incomingCovector Ω r) F) (chartZero_supported_kernel v Ω C _ F) + intro n hn m hm + apply hker.2.2 n m + intro hh + apply hm + change (Ω m r:ℝ)=0 at hh + exact_mod_cast hh +lemma chartNegative_of_positive_through (h : M →+ ℝ) (F : CompletedPositive v Ω C) (N : ℕ) + (hpos : ∀n,n+1≤N → ∀m,coeff (n+1) F.val m≠0 → 0(H n hn).2.2.symm +lemma chartNegative_of_negative_through (h : M →+ ℝ) (F : CompletedPositive v Ω C) (N : ℕ) + (hneg : ∀n,n+1≤N → ∀m,coeff (n+1) F.val m≠0 → h m<0) : + ∀n≤N,coeff n (chartNegative v Ω C h F).val=coeff n F.val := by + have H:=chart_three_truncated_unique v Ω C h F 1 1 F.val N (by simp) (by simp) + F.property.1 (by simp) (by intro n hn m hm; simp at hm) (by intro n hn m hm; simp at hm) hneg + exact fun n hn=>(H n hn).2.2.symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionMonomialExpansion.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionMonomialExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..09a9d1e92bffe6c841e0a62418599c9fb36b0847 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionMonomialExpansion.lean @@ -0,0 +1,55 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TorusAdjointExpansion + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) +local instance sectionMonomialExpansionAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance sectionMonomialExpansionAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommGroup +local instance sectionMonomialExpansionAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance sectionMonomialExpansionSub : Sub (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toSub + +def gradePoints (b:M) (j:ℕ) : Finset M := (shiftRootGrade_finite C b j).toFinset +lemma mem_gradePoints (b m:M) (j:ℕ) : m∈gradePoints C b j ↔ HasRootDegree C j (m-b) := by + simp only [gradePoints,Set.Finite.mem_toFinset,Set.mem_ofPred_eq] + +def monomialJump (W:PowerSeries (Torus LaurentRay.vUnit Ω)) (d:ℕ) (m r:M) : LaurentSeries ℚ := + coeff d (adjoint W (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m))) r + +lemma adjoint_graded_torus_expansion (W:PowerSeries (Torus LaurentRay.vUnit Ω)) + (b:M) (j d:ℕ) (f:Torus LaurentRay.vUnit Ω) (hf:f∈shiftRootGrade LaurentRay.vUnit Ω C b j) (r:M) : + coeff d (adjoint W (PowerSeries.C f)) r = + ∑m∈gradePoints C b j,f m*monomialJump Ω W d m r := by + rw [adjoint_torus_expansion] + apply Finset.sum_subset + · intro m hm + apply (mem_gradePoints C b m j).mpr + by_contra hh + exact (Finsupp.mem_support_iff.mp hm) (hf m hh) + · intro m hm hn + rw [Finsupp.notMem_support_iff.mp hn,zero_mul] + +lemma adjoint_lower_grade_expansion (W X:PowerSeries (Torus LaurentRay.vUnit Ω)) + (hW:constantCoeff W=1) (b:M) (hX:ShiftGraded LaurentRay.vUnit Ω C b X) (N:ℕ) (r:M) : + coeff N (adjoint W X) r = coeff N X r + + ∑j∈Finset.range N,∑m∈gradePoints C b j,coeff j X m*monomialJump Ω W (N-j) m r := by + rw [coeff_adjoint_lower W X hW N] + change coeff N X r+(∑j∈Finset.range N,coeff (N-j) (adjoint W (PowerSeries.C (coeff j X)))) r=_ + rw [torus_ring_eval_sum] + congr 1 + apply Finset.sum_congr rfl + intro j hj + exact adjoint_graded_torus_expansion Ω C W b j (N-j) (coeff j X) (hX j) r +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionTrace.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..316718bb8d3c3c871ed883a215cd894cbb22509e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SectionTrace.lean @@ -0,0 +1,52 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.QuantumTorusTrace +import OAI.Combinatorics.Chromatic.Walls.CompletedInverse + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +local instance sectionTraceAddCommGroup : AddCommGroup (Torus v Ω) := (Torus.instRing v Ω).toAddCommGroup +local instance sectionTraceAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance sectionTraceSub : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub +lemma torus_eval_sum {J : Type*} (s : Finset J) (f : J → Torus v Ω) (r : M) : + (∑j∈s,f j) r=∑j∈s,f j r := by + classical + induction s using Finset.induction_on with + | empty => rfl + | @insert j s hj ih => + rw [Finset.sum_insert hj,Finset.sum_insert hj] + change f j r+(∑j∈s,f j) r=_ + rw [ih] +include hΩ in +lemma series_coefficient_trace (r : M) (F X : PowerSeries (Torus v Ω)) (N : ℕ) + (hF : ∀n≤N,∀m,Ω m r≠0 → (coeff n F) m=0) : + (coeff N (F*X)) r=(coeff N (X*F)) r := by + classical + rw [coeff_mul,coeff_mul] + change (∑p∈Finset.HasAntidiagonal.antidiagonal N, ((coeff p.1 F)*(coeff p.2 X) : Torus v Ω)) r = + (∑p∈Finset.HasAntidiagonal.antidiagonal N, ((coeff p.1 X)*(coeff p.2 F) : Torus v Ω)) r + rw [torus_eval_sum,torus_eval_sum] + rw [←Finset.Nat.sum_antidiagonal_swap (f:=fun p=>((coeff p.1 X)*(coeff p.2 F)) r)] + apply Finset.sum_congr rfl + intro p hp + apply coefficient_trace v Ω hΩ r + exact hF p.1 (by have H:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp; omega) +include hΩ in +lemma adjoint_coefficient_trace (r : M) (F X : PowerSeries (Torus v Ω)) (N : ℕ) + (hF0 : constantCoeff F=1) + (hF : ∀n≤N,∀m,Ω m r≠0 → (coeff n F) m=0) : + (coeff N (adjoint F X)) r=(coeff N X) r := by + unfold adjoint + rw [mul_assoc,series_coefficient_trace v Ω hΩ r F (X*invOfUnit F 1) N hF, + mul_assoc,invOfUnit_mul F 1 hF0,mul_one] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SimplePlaneGeometry.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SimplePlaneGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a8938ac9d868bf78532a405d3b3b8bea03e4b18 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SimplePlaneGeometry.lean @@ -0,0 +1,222 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PureCutFactorization + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +include he hB hcomp in +lemma plane_lattice_relation (p r q : M) (hq : e q∈Submodule.span ℝ {e p,e r}) : + (Ω p r) • q=(Ω q r) • p+(Ω p q) • r := by + apply he + rw [map_zsmul,map_add,map_zsmul,map_zsmul] + simp only [←Int.cast_smul_eq_zsmul ℝ] + rw [←hcomp,←hcomp,←hcomp] + obtain ⟨a,b,hq⟩:=Submodule.mem_span_pair.mp hq + rw [←hq] + simp only [map_add,LinearMap.add_apply,map_smul,LinearMap.smul_apply,smul_eq_mul,hB, + mul_zero,zero_add,add_zero,smul_add,smul_smul] + congr 1 <;> congr 1 <;> ring +include hcoord he hB hcomp in +lemma plane_nonp_relation (r q : M) (hq : q∈planeRoots e (e (simpleRoot C pc)) (e r)) : + Ω (simpleRoot C pc) r*nonpDegree coord pc q= + Ω (simpleRoot C pc) q*nonpDegree coord pc r := by + have H:=congrArg (nonpDegree coord pc) + (plane_lattice_relation Ω e he B hB hcomp (simpleRoot C pc) r q hq) + simpa only [map_add,map_zsmul,smul_eq_mul,nonpDegree_simple_self C coord hcoord,mul_zero,zero_add] using H +include hcoord he hB hcomp in +lemma plane_simple_pairing_sign (pos : Bool) (r q : M) + (hr : 0by nlinarith,fun hh=>by nlinarith,?_⟩ + have ht : Ω (simpleRoot C pc) r≠0:=by intro hz; rw [hz,mul_zero] at htrend; omega + constructor + · intro hh + rw [hh,mul_zero] at H + exact (mul_eq_zero.mp H.symm).resolve_right (ne_of_gt hr) + · intro hh + rw [hh,zero_mul] at H + exact (mul_eq_zero.mp H).resolve_left ht +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries RootTruncation WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) +include hcoord he hB hcomp hdeg in +lemma cut_planar_fiber (N : ℕ) (n : ℤ) (pos : Bool) + (r : M) (hr : 0decide (nonpDegree coord pc q≠0)) + let A:=completedListProduct LaurentRay.vUnit Ω C lA K + have hcut (a : M →+ ℝ) : ∀j≤N,coeff j (chartZero LaurentRay.vUnit Ω C a Jc).val= + coeff j (chartZero LaurentRay.vUnit Ω C a J).val:= + chartZero_congr_through LaurentRay.vUnit Ω C a Jc J N (fun j hj=>coeff_cut_of_le J.val hj) + have hKray : ∀q∈l,∀j m,coeff (j+1) (K q).val m≠0 → OnPositiveRay q m:=by + intro q hq j m hm + change coeff (j+1) (cut N (chartZero LaurentRay.vUnit Ω C (incomingCovector Ω q) Jc).val) m≠0 at hm + rw [coeff_cut] at hm + split_ifs at hm with hj + · exact hRay q hq j hj m hm + · exact False.elim (hm rfl) + have hltrend : ∀q∈l,0≤ sideSign pos*Ω p q:=by + intro q hq + obtain ⟨d,hd,hdN,hdq,hqP⟩:=hl q hq + exact (plane_simple_pairing_sign Ω C coord hcoord pc e he B hB hcomp pos r q hr ht hqP).1 + (nonpDegree_root_nonneg C coord hcoord pc hdq) + have hAframe : ∀j,coeff j A.val∈supportedSubring LaurentRay.vUnit Ω Q:=by + apply completed_list_supported + intro q hq + have hq':=List.mem_filter.mp hq + obtain ⟨d,hd,hdN,hdq,hqP⟩:=hl q hq'.1 + have hnq : 0 simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] <;> rw [hev] + · have hh : (Ω p q:ℝ)<0:=by + have : Ω p q<0:=by simpa [sideSign] using htq + exact_mod_cast this + exact mul_neg_of_pos_of_neg (by positivity) hh + · have hh : 0<(Ω p q:ℝ):=by + have : 0<Ω p q:=by simpa [sideSign] using htq + exact_mod_cast this + exact mul_pos (by positivity) hh + · rw [heq j hj,←hcut _ j hj]; exact hv + have hAplane : ∀j,coeff j A.val∈supportedSubring LaurentRay.vUnit Ω (planeRoots e (e p) (e r)):=by + apply completed_list_supported + intro q hq + apply completedCut_supported + intro j hj + exact (chartThree_supported LaurentRay.vUnit Ω C (incomingCovector Ω q) _ Jc hplane).2.1 j + have hAtrend : ∀j≤N,∀m,coeff j A.val m≠0 → 0≤ sideSign pos*Ω p m:=by + intro j hj m hm + have hmP : m∈planeRoots e (e p) (e r):=by by_contra hh; exact hm (hAplane j m hh) + exact (plane_simple_pairing_sign Ω C coord hcoord pc e he B hB hcomp pos r m hr ht hmP).1 + (nonpDegree_root_nonneg C coord hcoord pc (chart_root_of_ne LaurentRay.vUnit Ω C A j m hm)) + have hface : ∀j≤N,coeff j (pureFace Ω C coord pc Jc).val= + coeff j (simpleCompleted Ω C coord hcoord pc).val:=by + intro j hj + change coeff j (pureFaceSeries Ω coord pc Jc.val)=_ + rw [coeff_pureFaceSeries] + change zeroProject LaurentRay.vUnit Ω (pureFaceCovector coord pc) (coeff j (cut N J.val))=_ + rw [coeff_cut_of_le J.val hj,←coeff_pureFaceSeries] + change coeff j (pureFace Ω C coord pc J).val=_ + rw [pureFace_chartZero Ω C coord hcoord pc kM hkp F,pureFace_simpleTransport_value Ω C coord hcoord pc hΩ] + rfl + have hprod : ∀j≤N,coeff j Jc.val=coeff j + (if pos then (normalizedSimple Ω p)*A.val else A.val*(normalizedSimple Ω p)):=by + apply ordered_pure_factor_through Ω C coord hcoord pc hΩ pos l K hpair + (fun q hq=>by obtain ⟨d,hd,_,hr,_⟩:=hl q hq; exact ⟨d,hd,hr⟩) hltrend hKray + Jc (simpleCompleted Ω C coord hcoord pc) N ?_ hface + intro j hj + refine (hfact j hj).trans ?_ + exact completedListProduct_congr_through LaurentRay.vUnit Ω C l _ K N + (fun q _ a ha=>(coeff_cut_of_le _ ha).symm) j hj + have hside : cutSide (!pos) (-incomingCovector Ω r) p:=by + cases pos <;> simp only [cutSide,Bool.not_false,Bool.not_true,ite_true,Bool.false_eq_true,ite_false, + AddMonoidHom.neg_apply,incomingCovector] <;> + norm_num only [Int.cast_neg,neg_pos,neg_lt_zero] + · have H : Ω p r<0:=by simpa [sideSign] using ht + change (Ω p r:ℝ)<0 + exact_mod_cast H + · have H : 0<Ω p r:=by simpa [sideSign] using ht + change 0<(Ω p r:ℝ) + exact_mod_cast H + have HB:=simple_cut_chart_bound Ω C coord hcoord pc hΩ pos A Jc N n hprod hAtrend + (by + intro j hj m hm hn + have H : m∈Q:=by by_contra hh; exact hm (hAframe j m hh) + exact H.2 hn) + (-incomingCovector Ω r) hside + intro j hj m hm hn + exact HB j hj m (by rwa [hcut _ j hj]) hn +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringLiteralClosure.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringLiteralClosure.lean new file mode 100644 index 0000000000000000000000000000000000000000..86edc9fd738dd5b24167c73cacec69728b70953b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringLiteralClosure.lean @@ -0,0 +1,53 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.SeriesApproximation +import OAI.Combinatorics.Chromatic.QuantumTorus.StringSumPush +import OAI.Combinatorics.Chromatic.Walls.WeightedCompletion + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity RawShuffle EnergyLaurent QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {S I : Type*} [Fintype I] [DecidableEq I] +variable (a : S→ℕ) (dim : S→(I→ℕ)) (k : S→ℤ) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) +variable (D : AddSubmonoid (I→ℕ)) (hdim : ∀s,dim s∈D) (h0 : ∀s,dim s≠0) +variable (w : I→ℕ) [Fact (∀i,0a s.val) (fun s:T=>dim s.val) + (fun s:T=>k s.val) (finiteStart_admissible a dim k he T) D (fun s=>hdim s.val) + (fun s=>h0 s.val) w Ω P hiso + refine ⟨l.map Subtype.val,hl.map Subtype.val_injective,?_⟩ + rw [List.map_map] + change push w LaurentRay.vUnit Ω P (stringSeries (fun s:T=>a s.val) + (fun s:T=>dim s.val) (fun s:T=>k s.val) (finiteStart_admissible a dim k he T)) = + (l.map (stringLiteralUnit (fun s:T=>a s.val) (fun s:T=>dim s.val) + (fun s:T=>k s.val) w Ω P)).prod + exact H + +include h0 hdim hiso in + +theorem stringLiteral_closure : + InPrecisionClosure LaurentRay.vUnit Ω (finiteStringProducts a dim k w Ω P) + (push w LaurentRay.vUnit Ω P (stringSeries a dim k he)) := by + apply InPrecisionClosure.of_converges LaurentRay.vUnit Ω (Filter.atTop : Filter (Finset S)) + (push_converges w LaurentRay.vUnit Ω P Filter.atTop + (finiteStartSeries_converges a dim k he)) + exact Filter.Eventually.of_forall (fun T=>inPrecisionClosure_self LaurentRay.vUnit Ω + (finiteStart_literal a dim k he D hdim h0 w Ω P hiso T)) +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringStripDimension.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringStripDimension.lean new file mode 100644 index 0000000000000000000000000000000000000000..64bb0d8cfeb40b9a96ad8a0ff698fde2479b1a6d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringStripDimension.lean @@ -0,0 +1,81 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.DimensionGrid +import OAI.Combinatorics.Chromatic.Shuffle.SymmetricSpace +import OAI.Combinatorics.Chromatic.Walls.StringStrip + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity RawShuffle +noncomputable section +variable {S I : Type*} (a : S → ℕ) (t : S → ℕ) (dim : S → (I → ℕ)) + +abbrev StringCounts (d : I → ℕ) := + DimensionCounts (fun x : S×ℕ=>a x.1≠0) (fun x=>dim x.1) d +abbrev StripCounts (d : I → ℕ) := + DimensionCounts (fun x : HeadLevel t=>a x.1≠0) (fun x=>dim x.1) d + +def stringStripDimensionEquiv (d : I → ℕ) : + StringCounts a dim d ≃ Σs : DimensionSplit d,StripCounts a t dim s.left × StringCounts a dim s.right := + ((stringStripEquiv a t).subtypeEquiv (fun _=>by + rw [countDimension,stringStrip_dimension] + rfl)).trans (dimensionProduct (countDimension _ (fun x : HeadLevel t=>dim x.1)) + (countDimension _ (fun x : S×ℕ=>dim x.1)) d).symm + +def stringEnergy (k : S → ℤ) (d : I → ℕ) (x : StringCounts a dim d) : ℤ := + countEnergy _ (fun x=>k x.1-2*(x.2:ℤ)) x.val + +def stripEnergy (k : S → ℤ) (d : I → ℕ) (x : StripCounts a t dim d) : ℤ := + countEnergy _ (fun x=>k x.1+2*(t x.1:ℤ)-2*(x.2.val:ℤ)) x.val + +lemma stringStripDimension_energy (k : S → ℤ) (d : I → ℕ) (x : StringCounts a dim d) : + stringEnergy a dim (fun s=>k s+2*(t s:ℤ)) d x= + stripEnergy a t dim k (stringStripDimensionEquiv a t dim d x).1.left + (stringStripDimensionEquiv a t dim d x).2.1+ + stringEnergy a dim k (stringStripDimensionEquiv a t dim d x).1.right + (stringStripDimensionEquiv a t dim d x).2.2 := + stringStrip_energy a t k x.val + +lemma stringEnergy_shift (τ : (I→ℕ) →+ ℤ) (hτ : ∀s,(t s:ℤ)=τ (dim s)) + (k : S → ℤ) (d : I → ℕ) (x : StringCounts a dim d) : + stringEnergy a dim (fun s=>k s+2*(t s:ℤ)) d x= + stringEnergy a dim k d x+2*τ d := by + have H : (fun x : S×ℕ=>k x.1+2*(t x.1:ℤ)-2*(x.2:ℤ))= + (fun x=>k x.1-2*(x.2:ℤ)+(2 • τ) (dim x.1)) := by + funext x + rw [hτ] + simp only [AddMonoidHom.nsmul_apply,nsmul_eq_mul] + ring + change countEnergy _ _ x.val=_ + rw [H,countEnergy_shift,x.property] + rfl + +def stripInsert (d : I → ℕ) (x : StripCounts a t dim d) : StringCounts a dim d := + ⟨(stringStripEquiv a t).symm (x.val,zeroCount _),by + change (_:S×ℕ→₀ℕ).sum _=d + rw [stringStrip_dimension a t dim] + simp only [Equiv.apply_symm_apply,zeroCount,Finsupp.sum_zero_index,add_zero] + exact x.property⟩ + +lemma stripInsert_injective (d : I → ℕ) : Function.Injective (stripInsert a t dim d) := by + intro x y H + apply Subtype.ext + have H':=congrArg (fun z : StringCounts a dim d=> (stringStripEquiv a t z.val).1) H + simpa only [stripInsert,Equiv.apply_symm_apply] using H' + +lemma stripInsert_energy (k : S → ℤ) (d : I → ℕ) (x : StripCounts a t dim d) : + stringEnergy a dim (fun s=>k s+2*(t s:ℤ)) d (stripInsert a t dim d x)= + stripEnergy a t dim k d x := by + change ((stringStripEquiv a t).symm (x.val,zeroCount _)).val.sum + (fun z n=>n • (k z.1+2*(t z.1:ℤ)-2*(z.2:ℤ)))=_ + rw [stringStrip_energy a t k] + simp only [Equiv.apply_symm_apply,zeroCount,Finsupp.sum_zero_index,add_zero] + rfl + +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringSumProduct.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringSumProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..0019187f1a2335e25c26dda437b690dc18069ae2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringSumProduct.lean @@ -0,0 +1,81 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CountSumDimension +import OAI.Combinatorics.Chromatic.Walls.StringPositiveFactor + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity EnergyLaurent RawShuffle +noncomputable section +variable {A B I : Type*} +variable (a : A→ℕ) (b : B→ℕ) (da : A→(I→ℕ)) (db : B→(I→ℕ)) +variable (ka : A→ℤ) (kb : B→ℤ) + +def stringSumEven (x : (A×ℕ)⊕(B×ℕ)) : Prop := + Sum.elim (fun y:A×ℕ=>a y.1≠0) (fun y:B×ℕ=>b y.1≠0) x + +lemma stringSumEven_iff (x : (A⊕B)×ℕ) : + Sum.elim a b x.1≠0 ↔ stringSumEven a b (Equiv.sumProdDistrib A B ℕ x) := by + rcases x with ⟨x,j⟩ + cases x <;> rfl + +def stringSumCounts (d : I→ℕ) : + StringCounts (Sum.elim a b) (Sum.elim da db) d ≃ + DimensionCounts (stringSumEven a b) + (Sum.elim (fun x:A×ℕ=>da x.1) (fun x:B×ℕ=>db x.1)) d := + (countReindex (Equiv.sumProdDistrib A B ℕ) _ _ (stringSumEven_iff a b)).subtypeEquiv (fun f=>by + change f.val.sum _=d ↔ (countReindex _ _ _ (stringSumEven_iff a b) f).val.sum _=d + rw [countReindex_sum] + have H : ∀x:(A⊕B)×ℕ,Sum.elim (fun x:A×ℕ=>da x.1) (fun x:B×ℕ=>db x.1) + (Equiv.sumProdDistrib A B ℕ x)=Sum.elim da db x.1 := by + intro x + rcases x with ⟨x,j⟩ + cases x <;> rfl + simp_rw [H]) + +lemma stringSumCounts_energy (d : I→ℕ) (f : StringCounts (Sum.elim a b) (Sum.elim da db) d) : + countEnergy (stringSumEven a b) + (Sum.elim (fun x:A×ℕ=>ka x.1-2*(x.2:ℤ)) (fun x:B×ℕ=>kb x.1-2*(x.2:ℤ))) + (stringSumCounts a b da db d f).val= + stringEnergy (Sum.elim a b) (Sum.elim da db) (Sum.elim ka kb) d f := by + change (countReindex _ _ _ (stringSumEven_iff a b) f.val).val.sum _=_ + rw [countReindex_sum] + dsimp only [stringEnergy,countEnergy] + apply Finsupp.sum_congr + intro x hx + rcases x with ⟨x,j⟩ + cases x <;> rfl + +variable [Fintype I] [DecidableEq I] +variable (ha : ∀d,Admissible (stringEnergy a da ka d)) +variable (hb : ∀d,Admissible (stringEnergy b db kb d)) +include ha hb in +lemma stringSum_admissible (d : I→ℕ) : + Admissible (stringEnergy (Sum.elim a b) (Sum.elim da db) (Sum.elim ka kb) d) := + admissible_injective + (countSum_admissible (fun x:A×ℕ=>a x.1≠0) (fun x:B×ℕ=>b x.1≠0) + (fun x=>da x.1) (fun x=>db x.1) + (fun x=>ka x.1-2*(x.2:ℤ)) (fun x=>kb x.1-2*(x.2:ℤ)) ha hb d) + (stringSumCounts a b da db d) (stringSumCounts a b da db d).injective + (stringSumCounts_energy a b da db ka kb d) + +lemma stringSum_series (d : I→ℕ) : + stringSeries (Sum.elim a b) (Sum.elim da db) (Sum.elim ka kb) + (stringSum_admissible a b da db ka kb ha hb) d= + ∑s : DimensionSplit d,stringSeries a da ka ha s.left*stringSeries b db kb hb s.right := by + rw [stringSeries,series_equiv _ + (countSum_admissible (fun x:A×ℕ=>a x.1≠0) (fun x:B×ℕ=>b x.1≠0) + (fun x=>da x.1) (fun x=>db x.1) + (fun x=>ka x.1-2*(x.2:ℤ)) (fun x=>kb x.1-2*(x.2:ℤ)) ha hb d) + (stringSumCounts a b da db d) + (stringSumCounts_energy a b da db ka kb d)] + exact countSum_series (fun x:A×ℕ=>a x.1≠0) (fun x:B×ℕ=>b x.1≠0) + (fun x=>da x.1) (fun x=>db x.1) + (fun x=>ka x.1-2*(x.2:ℤ)) (fun x=>kb x.1-2*(x.2:ℤ)) ha hb d +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringSumPush.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringSumPush.lean new file mode 100644 index 0000000000000000000000000000000000000000..263e4db6f8209332b0ef2c587df57a112ae4920b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/StringSumPush.lean @@ -0,0 +1,185 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.StringSumProduct +import OAI.Combinatorics.Chromatic.GradedAlgebra.EnergyLimit +import OAI.Combinatorics.Chromatic.Walls.StringRay + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity EnergyLaurent RawShuffle QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {A B I : Type*} [Fintype I] [DecidableEq I] +variable (a : A→ℕ) (b : B→ℕ) (da : A→(I→ℕ)) (db : B→(I→ℕ)) +variable (ka : A→ℤ) (kb : B→ℤ) +variable (ha : ∀d,Admissible (stringEnergy a da ka d)) +variable (hb : ∀d,Admissible (stringEnergy b db kb d)) +variable (D : AddSubmonoid (I→ℕ)) (hda : ∀s,da s∈D) (hdb : ∀s,db s∈D) +variable (w : I→ℕ) [Fact (∀i,0 + hiso d (stringSeries_support a da ka ha D hda d hd) + e (stringSeries_support b db kb hb D hdb e he))] + exact stringSum_series a b da db ka kb ha hb d +end +end ElementaryPositivity.UnitSelections + +end +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity EnergyLaurent RawShuffle QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {A I : Type*} [Fintype I] [DecidableEq I] +variable (a : Option A→ℕ) (dim : Option A→(I→ℕ)) (k : Option A→ℤ) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) +variable (D : AddSubmonoid (I→ℕ)) (hdim : ∀s,dim s∈D) +variable (w : I→ℕ) [Fact (∀i,0none,fun _ _ _=>Subsingleton.elim _ _⟩ +abbrev someEmbedding : A ↪ Option A := ⟨some,Option.some_injective _⟩ + +lemma option_pullback {T : Type*} (f : Option A→T) : + (fun s:A⊕PUnit.{1}=>f ((Equiv.optionEquivSumPUnit A).symm s))= + Sum.elim (fun s=>f (some s)) (fun _=>f none) := by + funext s + cases s <;> rfl + +include hdim hiso in +lemma stringOption_push (h0 : dim none≠0) : + push w LaurentRay.vUnit Ω P (stringSeries a dim k he)= + push w LaurentRay.vUnit Ω P + (stringSeries (fun s=>a (some s)) (fun s=>dim (some s)) (fun s=>k (some s)) + (stringEmbedding_admissible a dim k he someEmbedding))* + weightedRay LaurentRay.vUnit Ω (WeightedTorusSeries.weight w (dim none)) (P (dim none)) + (PowerSeries.map LaurentRay.atInfinity (indexedUnit (a none) (k none))) := by + have H:=funext (stringSeries_reindex a dim k he (Equiv.optionEquivSumPUnit A : Option A ≃ A⊕PUnit.{1}).symm) + let ha:=stringEmbedding_admissible a dim k he someEmbedding + let hb:=stringEmbedding_admissible a dim k he noneEmbedding + let hs:=stringSum_admissible (fun s=>a (some s)) (fun _:PUnit.{1}=>a none) + (fun s=>dim (some s)) (fun _:PUnit.{1}=>dim none) + (fun s=>k (some s)) (fun _:PUnit.{1}=>k none) ha hb + have HC:=stringSeries_congr _ _ _ + (stringReindex_admissible (Equiv.optionEquivSumPUnit A : Option A ≃ A⊕PUnit.{1}).symm a dim k he) + _ _ _ hs (option_pullback a) (option_pullback dim) (option_pullback k) + rw [←(HC.symm.trans H)] + have HH:=stringSum_push (fun s=>a (some s)) (fun _:PUnit.{1}=>a none) + (fun s=>dim (some s)) (fun _:PUnit.{1}=>dim none) + (fun s=>k (some s)) (fun _:PUnit.{1}=>k none) ha hb D + (fun s=>hdim (some s)) (fun _=>hdim none) w Ω P hiso + rw [HH,oneString_push_literal (a none) (dim none) (k none) h0 hb w Ω P] +end +end ElementaryPositivity.UnitSelections + +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity EnergyLaurent RawShuffle QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {S I : Type*} [Fintype I] [DecidableEq I] [IsEmpty S] +variable (a : S→ℕ) (dim : S→(I→ℕ)) (k : S→ℤ) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) +variable (w : I→ℕ) [Fact (∀i,0 + rw [coeff_zero_eq_constantCoeff,push_constant w LaurentRay.vUnit Ω P _ + (stringSeries_zero a dim k he (fun s=>isEmptyElim s))] + simp + | succ n=> + simp only [push,coeff_mk,pushCoeff,coeff_one,show n+1≠0 from Nat.succ_ne_zero n,ite_false] + apply Finset.sum_eq_zero + intro d hd + have H : d.val≠0 := by + intro hz + have HH:=d.property + rw [hz,map_zero] at HH + omega + rw [stringSeries_empty a dim k he d.val H,Torus.monomial_zero] +end +end ElementaryPositivity.UnitSelections + +end +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity EnergyLaurent RawShuffle QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +universe u +variable {S : Type u} {I : Type*} [Fintype I] [DecidableEq I] +variable (a : S→ℕ) (dim : S→(I→ℕ)) (k : S→ℤ) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) +variable (D : AddSubmonoid (I→ℕ)) (hdim : ∀s,dim s∈D) (h0 : ∀s,dim s≠0) +variable (w : I→ℕ) [Fact (∀i,0 + intro a dim k he hdim h0 + let heA:=stringReindex_admissible e a dim k he + obtain ⟨l,hl,hall,H⟩:=ih (fun s=>a (e s)) (fun s=>dim (e s)) (fun s=>k (e s)) + heA (fun s=>hdim (e s)) (fun s=>h0 (e s)) + refine ⟨l.map e,hl.map e.injective,?_,?_⟩ + · intro s + exact List.mem_map.mpr ⟨e.symm s,hall (e.symm s),e.apply_symm_apply s⟩ + · rw [List.map_map] + change push w LaurentRay.vUnit Ω P (stringSeries a dim k he) = + (l.map (stringLiteralUnit (fun s=>a (e s)) (fun s=>dim (e s)) + (fun s=>k (e s)) w Ω P)).prod + rw [←H] + congr 1 + exact (funext (stringSeries_reindex a dim k he e)).symm + | h_empty => + intro a dim k he hdim h0 + refine ⟨[],by simp,fun s=>isEmptyElim s,?_⟩ + simpa using stringEmpty_push a dim k he w Ω P + | @h_option A inst ih => + intro a dim k he hdim h0 + let heA:=stringEmbedding_admissible a dim k he someEmbedding + obtain ⟨l,hl,hall,H⟩:=ih (fun s=>a (some s)) (fun s=>dim (some s)) (fun s=>k (some s)) + heA (fun s=>hdim (some s)) (fun s=>h0 (some s)) + refine ⟨l.map some++[none],?_,?_,?_⟩ + · rw [List.nodup_append] + refine ⟨hl.map (Option.some_injective _),by simp,?_⟩ + simp + · intro s + cases s with + | none=>simp + | some s=>simp [hall s] + · rw [stringOption_push a dim k he D hdim w Ω P hiso (h0 none)] + rw [H,List.map_append,List.prod_append,List.map_map,List.map_singleton,List.prod_singleton] + rfl +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SymplecticTorusMap.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SymplecticTorusMap.lean new file mode 100644 index 0000000000000000000000000000000000000000..11489f7acc40138323788a257cf37737be73c5eb --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/SymplecticTorusMap.lean @@ -0,0 +1,45 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus.Torus +noncomputable section +variable {K M N : Type*} [CommRing K] [AddCommGroup M] [AddCommGroup N] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (Ω' : N →+ N →+ ℤ) +variable (L : M →+ N) (hL : ∀a b,Ω' (L a) (L b)=Ω a b) +def pushAdd : Torus v Ω →+ Torus v Ω' where + toFun:=Finsupp.mapDomain L + map_zero':=Finsupp.mapDomain_zero + map_add' _ _:=Finsupp.mapDomain_add +@[simp] lemma pushAdd_monomial (m : M) (a : K) : + pushAdd v Ω Ω' L (monomial v Ω m a)=monomial v Ω' (L m) a := Finsupp.mapDomain_single +include hL in +lemma pushAdd_mul (f g : Torus v Ω) : + pushAdd v Ω Ω' L (f*g)=pushAdd v Ω Ω' L f*pushAdd v Ω Ω' L g := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [add_mul,map_add,hf,hg] + | single m a=> + induction g using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [mul_add,map_add,hf,hg] + | single n b=> + change pushAdd v Ω Ω' L (monomial v Ω m a*monomial v Ω n b)= + pushAdd v Ω Ω' L (monomial v Ω m a)*pushAdd v Ω Ω' L (monomial v Ω n b) + rw [monomial_mul_monomial,pushAdd_monomial,pushAdd_monomial,pushAdd_monomial, + monomial_mul_monomial,hL,map_add] +def push : Torus v Ω →+* Torus v Ω' where + __:=pushAdd v Ω Ω' L + map_one':=by change pushAdd v Ω Ω' L (monomial v Ω 0 1)=monomial v Ω' 0 1; rw [pushAdd_monomial,map_zero] + map_mul':=pushAdd_mul v Ω Ω' L hL +@[simp] lemma push_monomial (m : M) (a : K) : + push v Ω Ω' L hL (monomial v Ω m a)=monomial v Ω' (L m) a := pushAdd_monomial v Ω Ω' L m a +@[simp] lemma push_X (m : M) : push v Ω Ω' L hL (X v Ω m)=X v Ω' (L m) := push_monomial v Ω Ω' L hL m 1 +end +end ElementaryPositivity.QuantumTorus.Torus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/TorusContinuity.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/TorusContinuity.lean new file mode 100644 index 0000000000000000000000000000000000000000..696c2f7571579e87b90a4cb119ceda50ad3ecb2e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/TorusContinuity.lean @@ -0,0 +1,104 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.IncomingSystem +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentContinuity + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries LaurentPrecision ElementaryPositivity.PowerSeriesSplit +noncomputable section +variable {M I ι : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) +variable (C : (I → ℤ) →+ M) (l : Filter ι) +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub +attribute [local instance] Classical.propDecidable + +def TorusConverges (f : ι → Torus v Ω) (F : Torus v Ω) : Prop := + ∀m,Converges l (fun i=>f i m) (F m) + +lemma torusConverges_const (F : Torus v Ω) : TorusConverges v Ω l (fun _=>F) F := + fun m=>converges_const l (F m) + +lemma TorusConverges.add {f g : ι → Torus v Ω} {F G : Torus v Ω} + (hf : TorusConverges v Ω l f F) (hg : TorusConverges v Ω l g G) : + TorusConverges v Ω l (fun i=>f i+g i) (F+G) := + fun m=>(hf m).add l (hg m) + +lemma TorusConverges.sub {f g : ι → Torus v Ω} {F G : Torus v Ω} + (hf : TorusConverges v Ω l f F) (hg : TorusConverges v Ω l g G) : + TorusConverges v Ω l (fun i=>f i-g i) (F-G) := by + intro m + simp only [torus_sub_apply] + exact (hf m).sub l (hg m) + +lemma TorusConverges.sum {α : Type*} (s : Finset α) + {f : α → ι → Torus v Ω} {F : α → Torus v Ω} + (h : ∀a∈s,TorusConverges v Ω l (f a) (F a)) : + TorusConverges v Ω l (fun i=>∑a∈s,f a i) (∑a∈s,F a) := by + intro m + simp only [Finsupp.finsetSum_apply] + exact LaurentPrecision.Converges.sum l s (fun a ha=>h a ha m) + +lemma torus_mul_finite (S T : Finset M) (f g : Torus v Ω) + (hf : f.support⊆S) (hg : g.support⊆T) (m : M) : + (f*g) m=∑x∈S,∑y∈T, + (Finsupp.single (x+y) (f x*g y*(↑(v^(Ω x y)) : LaurentSeries ℚ)) : Torus v Ω) m := by + change Torus.multiply v Ω f g m=_ + unfold Torus.multiply + rw [Finsupp.sum_of_support_subset f hf _ (by intros; simp)] + rw [Finsupp.finsetSum_apply] + apply Finset.sum_congr rfl + intro x hx + rw [Finsupp.sum_of_support_subset g hg _ (by intros; simp),Finsupp.finsetSum_apply] + +lemma TorusConverges.mul_of_support {f g : ι → Torus v Ω} {F G : Torus v Ω} + (hf : TorusConverges v Ω l f F) (hg : TorusConverges v Ω l g G) + (S T : Finset M) (hS : ∀i,(f i).support⊆S) (hT : ∀i,(g i).support⊆T) + (hSF : F.support⊆S) (hTG : G.support⊆T) : + TorusConverges v Ω l (fun i=>f i*g i) (F*G) := by + intro m + simp only [torus_mul_finite v Ω S T _ _ (hS _) (hT _) m, + torus_mul_finite v Ω S T F G hSF hTG m] + apply LaurentPrecision.Converges.sum l S + intro x hx + apply LaurentPrecision.Converges.sum l T + intro y hy + by_cases hxy : x+y=m + · simp only [hxy,Finsupp.single_eq_same] + exact ((hf x).mul l (hg y)).mul l (converges_const l _) + · simp only [Finsupp.single_eq_of_ne (Ne.symm hxy)] + exact converges_const l 0 + +lemma rootGrade_support (n : ℕ) (f : Torus v Ω) (hf : f∈rootGrade v Ω C n) : + f.support⊆(rootDegree_finite C n).toFinset := by + intro m hm + apply (rootDegree_finite C n).mem_toFinset.mpr + by_contra h + exact (Finsupp.mem_support_iff.mp hm) (hf m h) + +lemma TorusConverges.mul_graded {f g : ι → Torus v Ω} {F G : Torus v Ω} + (hf : TorusConverges v Ω l f F) (hg : TorusConverges v Ω l g G) + (n k : ℕ) (hfn : ∀i,f i∈rootGrade v Ω C n) (hgk : ∀i,g i∈rootGrade v Ω C k) + (hFn : F∈rootGrade v Ω C n) (hGk : G∈rootGrade v Ω C k) : + TorusConverges v Ω l (fun i=>f i*g i) (F*G) := + hf.mul_of_support v Ω l hg (rootDegree_finite C n).toFinset (rootDegree_finite C k).toFinset + (fun i=>rootGrade_support v Ω C n _ (hfn i)) + (fun i=>rootGrade_support v Ω C k _ (hgk i)) + (rootGrade_support v Ω C n F hFn) (rootGrade_support v Ω C k G hGk) + +lemma TorusConverges.filter {f : ι → Torus v Ω} {F : Torus v Ω} + (hf : TorusConverges v Ω l f F) (p : M → Prop) : + TorusConverges v Ω l (fun i=>(f i).filter p) (F.filter p) := by + intro m + by_cases h : p m + · simpa only [Finsupp.filter_apply,ite_eq_left h] using hf m + · simpa only [Finsupp.filter_apply,ite_eq_right h] using converges_const l (0 : LaurentSeries ℚ) + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/TorusProjection.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/TorusProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..6fba61519efede791137aee3bc92fcc0da803191 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/TorusProjection.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PowerSeriesThreeFactors +import OAI.Combinatorics.Chromatic.GradedAlgebra.HNSeries +import OAI.Combinatorics.Chromatic.GradedAlgebra.ProjectionRecursion + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries ElementaryPositivity.WeightedTorusSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (h : M →+ ℝ) +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid + +lemma sum_monomials (f : Torus v Ω) : + (∑m∈f.support,Torus.monomial v Ω m (f m))=f := Finsupp.sum_single f + +lemma zeroProject_monomial (m : M) (r : R) : + zeroProject v Ω h (Torus.monomial v Ω m r)= + if h m=0 then Torus.monomial v Ω m r else 0 := filter_monomial v Ω _ m r + +lemma zeroProject_monomial_mul (a b : M) (x y : R) (ha : h a≤0) (hb : h b≤0) : + zeroProject v Ω h (Torus.monomial v Ω a x*Torus.monomial v Ω b y)= + zeroProject v Ω h (Torus.monomial v Ω a x)* + zeroProject v Ω h (Torus.monomial v Ω b y) := by + classical + rw [Torus.monomial_mul_monomial] + simp only [zeroProject_monomial,map_add] + by_cases ha0 : h a=0 + · by_cases hb0 : h b=0 + · simp only [ha0,hb0,add_zero,ite_true,Torus.monomial_mul_monomial] + · have hab : h a+h b≠0 := by simpa only [ha0,zero_add] using hb0 + simp only [ha0,zero_add,hb0,ite_true,ite_false,Torus.mul_zero] + · have hab : h a+h b≠0 := by intro H; exact ha0 (by linarith) + simp only [ha0,hab,ite_false,Torus.zero_mul] + +lemma zeroProject_mul_nonpositive (f g : Torus v Ω) + (hf : f∈supportedSubring v Ω (nonpositiveCone h)) + (hg : g∈supportedSubring v Ω (nonpositiveCone h)) : + zeroProject v Ω h (f*g)=zeroProject v Ω h f*zeroProject v Ω h g := by + classical + have H : zeroProject v Ω h ((∑m∈f.support,Torus.monomial v Ω m (f m))* + (∑n∈g.support,Torus.monomial v Ω n (g n)))= + zeroProject v Ω h (∑m∈f.support,Torus.monomial v Ω m (f m))* + zeroProject v Ω h (∑n∈g.support,Torus.monomial v Ω n (g n)) := by + simp only [torus_sum_mul,torus_mul_sum,map_sum] + apply Finset.sum_congr rfl + intro m hm + apply Finset.sum_congr rfl + intro n hn + apply zeroProject_monomial_mul + · by_contra H + exact (Finsupp.mem_support_iff.mp hn) (hf n H) + · by_contra H + exact (Finsupp.mem_support_iff.mp hm) (hg m H) + simpa only [sum_monomials] using H + +lemma zeroProject_one : zeroProject v Ω h (1 : Torus v Ω)=1 := by + classical + change (Finsupp.filterAddHom (fun m=>h m=0) : Torus v Ω →+ Torus v Ω) + (Torus.monomial v Ω 0 1)=Torus.monomial v Ω 0 1 + rw [filter_monomial,map_zero,ite_eq_left rfl] + +lemma zeroFactor_coeff_projection (f : PowerSeries (Torus v Ω)) (n : ℕ) : + coeff n (PowerSeriesSplit.zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) f)= + zeroProject v Ω h (coeff n (PowerSeriesSplit.rightFactor (positiveProject v Ω h) f)) := by + apply PowerSeriesSplit.left_coeff_projection (zeroProject v Ω h) + (supportedSubring v Ω (nonpositiveCone h)) (zeroProject_idem v Ω h) (zeroProject_one v Ω h) + · intro x hx + exact (nonpositive_iff v Ω h _).mpr (positive_zero_project v Ω h x) + · intro x hx y hy + exact zeroProject_mul_nonpositive v Ω h x y hx hy + · exact PowerSeriesSplit.right_constant _ _ + · intro k + cases k with + | zero => rw [coeff_zero_eq_constantCoeff_apply,PowerSeriesSplit.right_constant]; exact Subring.one_mem _ + | succ k => + exact (nonpositive_iff v Ω h _).mpr + (PowerSeriesSplit.right_killed _ (positiveProject_idem v Ω h) f k) + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UnitRowSelection.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UnitRowSelection.lean new file mode 100644 index 0000000000000000000000000000000000000000..d86033bfbc9c56802bf3646e660089c206216aaf --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UnitRowSelection.lean @@ -0,0 +1,135 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SignedMultiplicity + +namespace OAI + +section +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity +noncomputable section + +def unitSigmaSubtype (a : ℕ) : (Σn,UnitIndex a n) ≃ + {q : Σn,Fin n → ℕ // if a=0 then StrictMono q.2 else Monotone q.2} where + toFun q:=⟨⟨q.1,q.2.val⟩,q.2.property⟩ + invFun q:=⟨q.val.1,⟨q.val.2,q.property⟩⟩ + left_inv _:=rfl + right_inv _:=rfl + +lemma ofFn_signed_iff (a n : ℕ) (f : Fin n → ℕ) : + (if a=0 then StrictMono f else Monotone f) ↔ + (List.ofFn f).Pairwise (·≤·) ∧ + (List.ofFn f).Pairwise (fun x y=>x=y → a≠0) := by + rw [List.pairwise_ofFn,List.pairwise_ofFn] + by_cases h : a=0 + · simp only [ite_eq_left h] + constructor + · intro hf + exact ⟨fun i j hij=>(hf hij).le,fun i j hij he=>False.elim ((hf hij).ne he)⟩ + · rintro ⟨hl,he⟩ i j hij + exact lt_of_le_of_ne (hl hij) (fun hx=>he hij hx h) + · simp only [ite_eq_right h] + constructor + · intro hf + exact ⟨fun i j hij=>hf hij.le,fun _ _ _ _=>h⟩ + · rintro ⟨hl,_⟩ i j hij + rcases hij.eq_or_lt with he|hlt + · subst j; rfl + · exact hl hlt + +def unitWordEquiv (a : ℕ) : (Σn,UnitIndex a n) ≃ Word (fun _ : ℕ=>a≠0) := + (unitSigmaSubtype a).trans + (List.equivSigmaTuple.symm.subtypeEquiv (fun q=>ofFn_signed_iff a q.1 q.2)) + +def unitRowSelection (a : ℕ) : (Σn,UnitIndex a n) ≃ Selection (fun _ : ℕ=>a≠0) := + (unitWordEquiv a).trans (wordSelectionEquiv _) + +def unitRowCount (a : ℕ) : (Σn,UnitIndex a n) ≃ CountSelection (fun _ : ℕ=>a≠0) := + (unitWordEquiv a).trans (wordCountEquiv _) + +lemma unitRowSelection_val (a n : ℕ) (f : UnitIndex a n) : + (unitRowSelection a ⟨n,f⟩).val=(List.ofFn f.val:Multiset ℕ) := rfl + +lemma unitRowSelection_card (a n : ℕ) (f : UnitIndex a n) : + (unitRowSelection a ⟨n,f⟩).val.card=n := by + rw [unitRowSelection_val,Multiset.coe_card,List.length_ofFn] + +lemma unitRowSelection_energy (a n : ℕ) (k : ℤ) (f : UnitIndex a n) : + (((unitRowSelection a ⟨n,f⟩).val).map (fun j:ℕ=>k-2*(j:ℤ))).sum=unitEnergy a n k f := by + rw [unitRowSelection_val,Multiset.map_coe,Multiset.sum_coe,List.map_ofFn,List.sum_ofFn] + simp only [Function.comp_def,Finset.sum_sub_distrib,Finset.sum_const,Finset.card_univ, + Fintype.card_fin,nsmul_eq_mul,←Finset.mul_sum,unitEnergy,unitWeight,weight] +end +end ElementaryPositivity.UnitSelections +end +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity +noncomputable section + +lemma multiset_count_energy {A : Type*} [DecidableEq A] (m : Multiset A) (e : A → ℤ) : + m.toFinsupp.sum (fun x n=>n • e x)=(m.map e).sum := by + induction m using Multiset.induction_on with + | empty => simp + | cons x m ih => + change (({x}:Multiset A)+m).toFinsupp.sum _=((({x}:Multiset A)+m).map e).sum + rw [Multiset.toFinsupp_add] + rw [Finsupp.sum_add_index' (h:=fun x n=>n • e x) (by simp) (by intro a b c; exact add_nsmul (e a) b c)] + simp only [Multiset.toFinsupp_singleton,Multiset.map_add,Multiset.sum_add, + Multiset.map_singleton,Multiset.sum_singleton,ih] + rw [Finsupp.sum_single_index (h:=fun x n=>n • e x) (by simp),one_nsmul] + +lemma unitRowCount_energy (a n : ℕ) (k : ℤ) (f : UnitIndex a n) : + (unitRowCount a ⟨n,f⟩).val.sum (fun j r=>r • (k-2*(j:ℤ)))=unitEnergy a n k f := by + change ((unitRowSelection a ⟨n,f⟩).val).toFinsupp.sum _=_ + rw [multiset_count_energy,unitRowSelection_energy] + +section FiniteRows +variable {S : Type*} [Fintype S] [DecidableEq S] +variable (a : S → ℕ) + +abbrev ColumnSelection := {f : (Σ_ : S,ℕ) →₀ ℕ // ∀s j,¬(a s≠0) → f ⟨s,j⟩≤1} + +def columnRowEquiv : ColumnSelection a ≃ (∀s,CountSelection (fun _ : ℕ=>a s≠0)) := + ((Finsupp.sigmaFinsuppEquivPiFinsupp (ιs:=fun _ : S=>ℕ) (α:=ℕ)).subtypeEquiv + (fun f=>(show (∀s j,¬(a s≠0) → f ⟨s,j⟩≤1) ↔ + (∀s,∀j,¬(a s≠0) → Finsupp.sigmaFinsuppEquivPiFinsupp f s j≤1) from Iff.rfl))).trans + (Equiv.subtypePiEquivPi (p:=fun s (f:ℕ→₀ℕ)=>∀j,¬(a s≠0) → f j≤1)) + +def unitRowsEquiv : (∀s,Σn,UnitIndex (a s) n) ≃ ColumnSelection a := + (Equiv.piCongrRight (fun s=>unitRowCount (a s))).trans (columnRowEquiv a).symm + +omit [DecidableEq S] in +lemma unitRows_split (f : ∀s,Σn,UnitIndex (a s) n) (s : S) : + Finsupp.split (unitRowsEquiv a f).val s=(unitRowCount (a s) (f s)).val := by + change (((columnRowEquiv a) ((columnRowEquiv a).symm + (fun s=>unitRowCount (a s) (f s)))) s).val=_ + rw [Equiv.apply_symm_apply] + +omit [DecidableEq S] in +lemma sigma_sum_univ (f : (Σ_ : S,ℕ) →₀ ℕ) (e : (Σ_ : S,ℕ) → ℤ) : + f.sum (fun x r=>r • e x)=∑s,(Finsupp.split f s).sum (fun j r=>r • e ⟨s,j⟩) := by + rw [Finsupp.sigma_sum] + apply Finset.sum_subset (Finset.subset_univ _) + intro s _ hs + have hz : Finsupp.split f s=0 := by + by_contra hn + exact hs ((Finsupp.mem_splitSupport_iff_nonzero f s).mpr hn) + simp only [hz,Finsupp.sum_zero_index] + +omit [DecidableEq S] in +lemma unitRows_energy (k : S → ℤ) (f : ∀s,Σn,UnitIndex (a s) n) : + (unitRowsEquiv a f).val.sum (fun q r=>r • (k q.1-2*(q.2:ℤ)))= + ∑s,unitEnergy (a s) (f s).1 (k s) (f s).2 := by + rw [sigma_sum_univ] + apply Finset.sum_congr rfl + intro s _ + rw [unitRows_split] + exact unitRowCount_energy (a s) (f s).1 (k s) (f s).2 +end FiniteRows +end +end ElementaryPositivity.UnitSelections +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UpstreamFiber.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UpstreamFiber.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca899565c3e7ea48613457a8ab828f0ab4178e0a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UpstreamFiber.lean @@ -0,0 +1,157 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallLineInitial +import OAI.Combinatorics.Chromatic.Walls.OffCutJoint + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries RootTruncation FiniteRayGeometry FiniteEventTraversal +noncomputable section +variable {R M E I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] + [AddCommGroup E] [Module ℝ E] [Fintype I] [DecidableEq I] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) +include hcoord he hB hcomp hdeg in +lemma upstream_fiber_induction (N : ℕ) (hN : 0 simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hside ⊢ + · exact HH.2 hside + · exact HH.1 hside + have hsidea (a : ℝ) (ha : 0≤a) : + cutSide pos ((k+a • vR).toAddMonoidHom.comp e) (simpleRoot C pc):=by + have heval : ((k+a • vR).toAddMonoidHom.comp e) (simpleRoot C pc)= + k (e (simpleRoot C pc))+a*(Ω (simpleRoot C pc) r:ℝ):=by + change k (e (simpleRoot C pc))+a*B (e (simpleRoot C pc)) (e r)=_ + rw [hcomp] + cases pos <;> simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hsidek htrend ⊢ <;> rw [heval] + · have ht : (Ω (simpleRoot C pc) r:ℝ)≤0:=by exact_mod_cast htrend + have hk : k (e (simpleRoot C pc))<0:=hsidek + nlinarith + · have ht : 0≤(Ω (simpleRoot C pc) r:ℝ):=by exact_mod_cast htrend + have hk : 0Hgen.2 j hj hjN m hm hkm) hD hpres + have Href:=chart_zero_refinement v Ω C (incomingCovector Ω r) (k.toAddMonoidHom.comp e) + ((k+b • vR).toAddMonoidHom.comp e) F N (by + intro j hj m hm + have HH:=far_line_lex S vR k b hbound (e m) (realRoot_mem e C N j hj m hm) + simp only [vR,LinearMap.flip_apply,hcomp] at HH + exact HH) + refine ⟨b,hb.le,hbound,?_⟩ + intro j hj m hm hn + apply hDP j hj m ?_ hn + rw [Href j hj,Hinc j hj] at hm + exact hm + have hcell : ∀a b,0≤a → 0≤b → a∉events → b∉events → + (∀z∈events,a0,∀δ : ℝ,0<δ → δ<ε → Q (a+δ) → Q (a-δ):=by + intro a ha ha0 + obtain ⟨s,hs,hsv,hsa⟩:=(mem_lineEvents_iff S vR k a).mp ha + have hrs : B (e r) s≠0:=by + rw [PlanarRayOrder.alternating_swap B hB] + exact neg_ne_zero.mpr hsv + let ka:=k+a • vR + let kaM:=ka.toAddMonoidHom.comp e + have hkr : ka (e r)=0:=by + change k (e r)+a*B (e r) (e r)=0 + rw [Hk.on_ray,hB,mul_zero,add_zero] + have hzero:=joint_roots_plane C e B N r k Hk a s hs hsv hsa + obtain ⟨εp,hεp,Hεp⟩:=root_lex_epsilon C N kaM (incomingCovector Ω r) + obtain ⟨εm,hεm,Hεm⟩:=root_lex_epsilon C N kaM (-incomingCovector Ω r) + refine ⟨min εp εm,lt_min hεp hεm,?_⟩ + intro δ hδ hδε hright + have hrefp:=chart_zero_refinement v Ω C kaM (incomingCovector Ω r) + (kaM+δ • incomingCovector Ω r) F N (Hεp δ hδ (lt_of_lt_of_le hδε (min_le_left _ _))) + have hrefm:=chart_zero_refinement v Ω C kaM (-incomingCovector Ω r) + (kaM+δ • (-incomingCovector Ω r)) F N (Hεm δ hδ (lt_of_lt_of_le hδε (min_le_right _ _))) + have hlp : ((k+(a+δ) • vR).toAddMonoidHom.comp e)=kaM+δ • incomingCovector Ω r:=by + ext m; change k (e m)+(a+δ)*B (e m) (e r)=k (e m)+a*B (e m) (e r)+δ*(Ω m r:ℝ) + rw [hcomp]; ring + have hlm : ((k+(a-δ) • vR).toAddMonoidHom.comp e)=kaM+δ • (-incomingCovector Ω r):=by + ext m; change k (e m)+(a-δ)*B (e m) (e r)=k (e m)+a*B (e m) (e r)+δ* -(Ω m r:ℝ) + rw [hcomp]; ring + have HH:=offcut_planar_support v Ω C coord hcoord pc e he B hB hcomp L hdeg N hN n P pos r dr hdr hrd + s hrs ka hkr hsa hzero (hsidea a ha0.le) F HI (by + intro j hj m hm hn + apply hright j hj m ?_ hn + rw [hlp,hrefp j hj] + exact hm) + intro j hj m hm hn + rw [hlm,hrefm j hj] at hm + exact HH j hj m hm hn + have HK : ∀j≤N,∀m,coeff j (chartZero v Ω C (k.toAddMonoidHom.comp e) F).val m≠0 → + nonpDegree coord pc m=n → m∈P:=by + have HH:=descend events Q hstart hcell hstep 0 (le_refl 0) h0 + simpa only [Q,zero_smul,add_zero] using HH + have Hchart:=chart_sign_congr_through v Ω C (h.toAddMonoidHom.comp e) (k.toAddMonoidHom.comp e) F N (by + intro j hj hjN m hm + have HS:=Hsign (e m) (realRoot_mem e C N j hjN m hm) + refine ⟨HS.1,?_,HS.2⟩ + intro hh + exact ((hg.2 j hj hjN m hm hh).eval (k.toAddMonoidHom.comp e)).2.1.mpr Hk.on_ray) + intro j hj m hm hn + apply HK j hj m ?_ hn + rwa [←Hchart j hj] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UpstreamSimpleFiber.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UpstreamSimpleFiber.lean new file mode 100644 index 0000000000000000000000000000000000000000..de6e92a35c0bb4fb334388c262bcdc920d8470c9 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/UpstreamSimpleFiber.lean @@ -0,0 +1,275 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.SimplePlaneGeometry +import OAI.Combinatorics.Chromatic.QuantumTorus.UpstreamFiber + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) +include hcoord he hB hcomp hdeg in +lemma upstream_simple_fiber (N : ℕ) (hN : 0ha.add hb) (literalIncomingRay_mem Ω C + (simpleIncomingList C) (simpleIncomingList_allowed C) r) j m hh)) + (fun j _ m hm=>literalTotalTransport_ray_prescription Ω C hΩ + (simpleIncomingList C) (simpleIncomingList_allowed C) r j m hm) ?_ HI h hg hside ?_ + · intro j hj m hm hn + by_contra hh + exact hm (simpleIncomingCompleted_fiber Ω C coord hcoord pc r hr + (mutationPairing Ω C pc) (sideSign pos) j m hh) + · cases pos <;> simpa [sideSign] using htrend +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries RootTruncation FiniteRayGeometry FiniteEventTraversal WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) +include hcoord he hB hcomp hdeg in +lemma global_simple_fiber_step (N : ℕ) (hN : 0 simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hside + · exact ne_of_lt hside + · exact ne_of_gt hside + have hr : 0 simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hs + · exact ne_of_lt hs + · exact ne_of_gt hs + exact upstream_simple_fiber Ω C coord hcoord pc e he B hB hcomp L hdeg N hN n side q d hd hdq hqn + (fun q d hd hr b hb hs=>HI q d hd hr b hb side hs) b hb hs ht.le j hj m hm (by omega) + let S:=realRootsThrough e C N + let vR:=B.flip (e r) + obtain ⟨k,Hk,Hsign⟩:=exists_generic_offset S (e r) vR h hg.1 + let events:=lineEvents S vR k + let P (side : Bool):=fiberCone coord pc (mutationPairing Ω C pc) (sideSign side) + let Q (a : ℝ):=∀side : Bool,cutSide side ((k+a • vR).toAddMonoidHom.comp e) p → + ∀j≤N,∀m,coeff j (chartZero LaurentRay.vUnit Ω C ((k+a • vR).toAddMonoidHom.comp e) F).val m≠0 → + nonpDegree coord pc m=n → m∈P side + have h0 : (0:ℝ)∉events:=by + intro hevent + obtain ⟨s,hs,hv,hs0⟩:=(mem_lineEvents_iff S vR k 0).mp hevent + have hn : s∉Submodule.span ℝ {e r}:=by + intro hmem + obtain ⟨c,hc⟩:=Submodule.mem_span_singleton.mp hmem + apply hv + rw [←hc,map_smul] + change c*B (e r) (e r)=0 + rw [hB,mul_zero] + apply Hk.avoid s hs hn + simpa only [zero_smul,add_zero] using hs0 + have hstart : ∃b,0≤b ∧ (∀a∈events,aHgen.2 j hj hjN m hm hkm) + (by intro j m hm; by_contra hh; exact hm (literalRootProducts_strictSupport Ω C (OnPositiveRay r) + (fun a b ha hb=>ha.add hb) (literalIncomingRay_mem Ω C (simpleIncomingList C) (simpleIncomingList_allowed C) r) j m hh)) + (fun j _ m hm=>literalTotalTransport_ray_prescription Ω C hΩ (simpleIncomingList C) + (simpleIncomingList_allowed C) r j m hm) + have Href:=chart_zero_refinement LaurentRay.vUnit Ω C (incomingCovector Ω r) (k.toAddMonoidHom.comp e) + ((k+b • vR).toAddMonoidHom.comp e) F N (by + intro j hj m hm + have HH:=far_line_lex S vR k b hbound (e m) (realRoot_mem e C N j hj m hm) + simp only [vR,LinearMap.flip_apply,hcomp] at HH + exact HH) + refine ⟨b,hb.le,hbound,?_⟩ + intro side hs j hj m hm hn + by_contra hh + apply hm + rw [Href j hj,Hinc j hj] + exact simpleIncomingCompleted_fiber Ω C coord hcoord pc r hr (mutationPairing Ω C pc) (sideSign side) j m hh + have hcell : ∀a b,0≤a → 0≤b → a∉events → b∉events → + (∀z∈events,aHsigns (e m) (realRoot_mem e C N j hjN m hm)) + have hs' : cutSide side ((k+a • vR).toAddMonoidHom.comp e) p:=by + have HH:=line_cell_signs S vR k b a hbS haS (fun z hz=>(Hside z hz).symm) + (e p) (realRoot_mem e C N 1 hN p (simpleRoot_degree C pc)) + cases side <;> simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hs ⊢ + · exact HH.2.2 hs + · exact HH.1 hs + apply Hpa side hs' j hj m ?_ hn + rwa [Hchart j hj] + have hstep : ∀a∈events,00,∀δ : ℝ,0<δ → δ<ε → Q (a+δ) → Q (a-δ):=by + intro a ha ha0 + obtain ⟨s,hs,hsv,hsa⟩:=(mem_lineEvents_iff S vR k a).mp ha + have hrs : B (e r) s≠0:=by + rw [PlanarRayOrder.alternating_swap B hB] + exact neg_ne_zero.mpr hsv + let ka:=k+a • vR + let kaM:=ka.toAddMonoidHom.comp e + have hkr : ka (e r)=0:=by + change k (e r)+a*B (e r) (e r)=0 + rw [Hk.on_ray,hB,mul_zero,add_zero] + have hzero:=joint_roots_plane C e B N r k Hk a s hs hsv hsa + obtain ⟨εp,hεp,Hεp⟩:=root_lex_epsilon C N kaM (incomingCovector Ω r) + obtain ⟨εm,hεm,Hεm⟩:=root_lex_epsilon C N kaM (-incomingCovector Ω r) + refine ⟨min εp εm,lt_min hεp hεm,?_⟩ + intro δ hδ hδε hright side hsideδ j hj m hm hn + have hδp : δ<εp:=lt_of_lt_of_le hδε (min_le_left _ _) + have hδm : δ<εm:=lt_of_lt_of_le hδε (min_le_right _ _) + have hrefp:=chart_zero_refinement LaurentRay.vUnit Ω C kaM (incomingCovector Ω r) + (kaM+δ • incomingCovector Ω r) F N (Hεp δ hδ hδp) + have hrefm:=chart_zero_refinement LaurentRay.vUnit Ω C kaM (-incomingCovector Ω r) + (kaM+δ • (-incomingCovector Ω r)) F N (Hεm δ hδ hδm) + have hlp : ((k+(a+δ) • vR).toAddMonoidHom.comp e)=kaM+δ • incomingCovector Ω r:=by + ext m; change k (e m)+(a+δ)*B (e m) (e r)=k (e m)+a*B (e m) (e r)+δ*(Ω m r:ℝ) + rw [hcomp]; ring + have hlm : ((k+(a-δ) • vR).toAddMonoidHom.comp e)=kaM+δ • (-incomingCovector Ω r):=by + ext m; change k (e m)+(a-δ)*B (e m) (e r)=k (e m)+a*B (e m) (e r)+δ* -(Ω m r:ℝ) + rw [hcomp]; ring + rw [hlm,hrefm j hj] at hm + by_cases hkp : kaM p=0 + · have hpr : Ω p r≠0:=by + intro hz + have hkp' : k (e p)=0:=by + change k (e p)+a*B (e p) (e r)=0 at hkp + simpa only [hcomp,hz,Int.cast_zero,mul_zero,add_zero] using hkp + have Hgen:=offset_ray_generic C e he L hdeg N dr r hdr hrd vR k Hk + exact positive_nonp_not_simple_ray C coord hcoord pc r hr + (Hgen.2 1 Nat.zero_lt_one hN p (simpleRoot_degree C pc) hkp') + have hprR : B (e p) (e r)≠0:=by rw [hcomp]; exact_mod_cast hpr + have hzero' : ∀d,d≤N → ∀m,HasRootDegree C d m → ka (e m)=0 → + m∈planeRoots e (e p) (e r):=by + intro d hd m hm hz + have HG:=joint_roots_plane C e B N r k Hk a (e p) + (realRoot_mem e C N 1 hN p (simpleRoot_degree C pc)) hprR hkp d hd m hm hz + change e m∈Submodule.span ℝ {e p,e r} + simpa only [Set.pair_comm (e r) (e p)] using HG + have ht : 0 simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hsideδ <;> + rw [hev] at hsideδ + · have HP : 0<(Ω p r:ℝ):=by nlinarith + simpa [sideSign] using (show 0<Ω p r from by exact_mod_cast HP) + · have HP : (Ω p r:ℝ)<0:=by nlinarith + simpa [sideSign] using (show Ω p r<0 from by exact_mod_cast HP) + have HH:=cut_planar_fiber Ω C coord hcoord pc e he B hB hcomp L hdeg N n (!side) + r hr ht ka hkp hkr hzero' (HU (!side)) j hj m hm (le_of_eq hn) + change m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign side) + simpa only [sideSign_neg,neg_neg] using HH + · have hsignp:=Hεp δ hδ hδp 1 hN p (simpleRoot_degree C pc) + have hsignm:=Hεm δ hδ hδm 1 hN p (simpleRoot_degree C pc) + have hs0 : cutSide side kaM p:=by + rw [hlm] at hsideδ + cases side <;> simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hsideδ ⊢ + · by_contra hh + have hp : 0 simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hs0 ⊢ + · exact hsignp.2.1 hs0 + · exact hsignp.1 hs0 + exact offcut_planar_support LaurentRay.vUnit Ω C coord hcoord pc e he B hB hcomp L hdeg N hN n + (P side) side r dr hdr hrd s hrs ka hkr hsa hzero hs0 F + (fun q d hd hr b hb hs=>HI q d hd hr b hb side hs) + (by + intro j hj m hm hn + apply hright side hsplus j hj m ?_ hn + rw [hlp,hrefp j hj]; exact hm) j hj m hm hn + have HK : Q 0:=descend events Q hstart hcell hstep 0 (le_refl 0) h0 + have hsidek : cutSide pos (k.toAddMonoidHom.comp e) p:=by + have HH:=Hsign (e p) (realRoot_mem e C N 1 hN p (simpleRoot_degree C pc)) + cases pos <;> simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hside ⊢ + · exact HH.2 hside + · exact HH.1 hside + have Hchart:=chart_sign_congr_through LaurentRay.vUnit Ω C (h.toAddMonoidHom.comp e) + (k.toAddMonoidHom.comp e) F N (by + intro j hj hjN m hm + have HS:=Hsign (e m) (realRoot_mem e C N j hjN m hm) + refine ⟨HS.1,?_,HS.2⟩ + intro hh + exact ((hg.2 j hj hjN m hm hh).eval (k.toAddMonoidHom.comp e)).2.1.mpr Hk.on_ray) + intro j hj m hm hn + have HK':=HK pos (by simpa only [zero_smul,add_zero] using hsidek) j hj m + apply HK' ?_ hn + simpa only [zero_smul,add_zero] using (show coeff j (chartZero LaurentRay.vUnit Ω C + (k.toAddMonoidHom.comp e) F).val m≠0 from by rwa [←Hchart j hj]) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/WeakStrictUnitSelections.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/WeakStrictUnitSelections.lean new file mode 100644 index 0000000000000000000000000000000000000000..82c841c54957831a2fe9c0c236aa1bd3c196ff45 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/WeakStrictUnitSelections.lean @@ -0,0 +1,88 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RayLaurentExpansion + +namespace OAI + +section +section +namespace ElementaryPositivity.UnitSelections +open FiniteFunctionValues +noncomputable section +abbrev Weak (n : ℕ) := {f : Fin n → ℕ // Monotone f} +abbrev Strict (n : ℕ) := {f : Fin n → ℕ // StrictMono f} + +def weakValues (n : ℕ) (f : Weak n) : Sym ℕ n := + ⟨values f.val,by rw [values_card,Fintype.card_fin]⟩ + +lemma weakValues_injective (n : ℕ) : Function.Injective (weakValues n) := by + intro f g he + have hm : (List.ofFn f.val:Multiset ℕ)=(List.ofFn g.val:Multiset ℕ) := by + simpa only [weakValues,values_fin] using congrArg Subtype.val he + have hf : (List.ofFn f.val).Pairwise (·≤·) := List.pairwise_ofFn.mpr (fun _ _ h=>f.property h.le) + have hg : (List.ofFn g.val).Pairwise (·≤·) := List.pairwise_ofFn.mpr (fun _ _ h=>g.property h.le) + have hfg : List.ofFn f.val=List.ofFn g.val := List.Perm.eq_of_pairwise' hf hg (Quotient.exact hm) + apply Subtype.ext + exact List.ofFn_inj.mp hfg + +lemma weakValues_surjective (n : ℕ) : Function.Surjective (weakValues n) := by + rintro ⟨m,hm⟩ + let l:=m.sort (·≤·) + have hl : l.length=n := (Multiset.length_sort (s:=m) (·≤·)).trans hm + have he : (l:Multiset ℕ)=m := Multiset.sort_eq _ _ + have hp : l.Pairwise (·≤·) := Multiset.pairwise_sort _ _ + cases hl + refine ⟨⟨l.get,fun _ _ h=>hp.rel_get_of_le h⟩,?_⟩ + apply Subtype.ext + change values l.get=m + rw [values_fin,List.ofFn_get] + exact he + +def weakSymEquiv (n : ℕ) : Weak n ≃ Sym ℕ n := + Equiv.ofBijective (weakValues n) ⟨weakValues_injective n,weakValues_surjective n⟩ + +lemma strict_index_le {n : ℕ} (g : Strict n) (i : Fin n) : i.val≤g.val i := by + cases n with + | zero => exact Fin.elim0 i + | succ n => + induction i using Fin.induction with + | zero => exact Nat.zero_le _ + | succ i ih => + have h:=g.property (Fin.castSucc_lt_succ (i:=i)) + change i.val≤g.val i.castSucc at ih + change i.val+1≤g.val i.succ + omega + +def staircaseEquiv (n : ℕ) : Weak n ≃ Strict n where + toFun f:=⟨fun i=>f.val i+i.val,by + intro i j hij + have h:=f.property hij.le + have hi : i.valg.val i-i.val,by + cases n with + | zero => intro i; exact Fin.elim0 i + | succ n => + apply Fin.monotone_iff_le_succ.mpr + intro i + have h:=g.property (Fin.castSucc_lt_succ (i:=i)) + have hb:=strict_index_le g i.castSucc + change g.val i.castSucc-i.val≤g.val i.succ-(i.val+1) + omega⟩ + left_inv f:=by ext i; simp + right_inv g:=by + apply Subtype.ext + funext i + change g.val i-i.val+i.val=g.val i + exact Nat.sub_add_cancel (strict_index_le g i) + +lemma staircase_sum (n : ℕ) (f : Weak n) : + (∑i,(staircaseEquiv n f).val i)=(∑i,f.val i)+(∑i:Fin n,i.val) := by + change (∑ i : Fin n, (f.val i + i.val)) = _ + exact Finset.sum_add_distrib +end +end ElementaryPositivity.UnitSelections +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/QuantumTorus/WeakUnitRecursion.lean b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/WeakUnitRecursion.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ef3dfe1972bc70405c16071ff4db7ed52b2bb1c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/QuantumTorus/WeakUnitRecursion.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.UnitIndexEnergy + +namespace OAI + +section +section +namespace ElementaryPositivity.UnitSelections +noncomputable section + +def prependZero (n : ℕ) (f : Weak n) : Weak (n+1) := + ⟨Fin.cons 0 f.val,by + intro i j + refine Fin.cases (fun _=>Nat.zero_le _) (fun i=>?_) i + refine Fin.cases ?_ (fun j hij=>f.property (Fin.succ_le_succ_iff.mp hij)) j + intro hij + simp at hij⟩ + +def deleteZeroEquiv (n : ℕ) : {f : Weak (n+1) // f.val 0=0} ≃ Weak n where + toFun f:=⟨fun i=>f.val.val i.succ,fun _ _ h=>f.val.property (Fin.succ_le_succ_iff.mpr h)⟩ + invFun f:=⟨prependZero n f,rfl⟩ + left_inv f:=by + apply Subtype.ext + apply Subtype.ext + funext i + refine Fin.cases ?_ (fun i=>rfl) i + exact f.property.symm + right_inv f:=rfl + +lemma weak_first_le (n : ℕ) (f : Weak (n+1)) (i : Fin (n+1)) : f.val 0≤f.val i := + f.property (Fin.zero_le i) + +def shiftOne (n : ℕ) (f : Weak n) : Weak n := + ⟨fun i=>f.val i+1,fun _ _ h=>Nat.add_le_add_right (f.property h) 1⟩ + +def subtractOneEquiv (n : ℕ) : {f : Weak (n+1) // f.val 0≠0} ≃ Weak (n+1) where + toFun f:=⟨fun i=>f.val.val i-1,fun _ _ h=>Nat.sub_le_sub_right (f.val.property h) 1⟩ + invFun f:=⟨shiftOne (n+1) f,by simp [shiftOne]⟩ + left_inv f:=by + apply Subtype.ext + apply Subtype.ext + funext i + change f.val.val i-1+1=f.val.val i + have h:=weak_first_le n f.val i + have h0:=f.property + omega + right_inv f:=by + apply Subtype.ext + funext i + change f.val i+1-1=f.val i + omega + +def weakSplit (n : ℕ) : Weak (n+1) ≃ Weak n ⊕ Weak (n+1) := + (Equiv.sumCompl (fun f : Weak (n+1)=>f.val 0=0)).symm.trans + (Equiv.sumCongr (deleteZeroEquiv n) (subtractOneEquiv n)) + +lemma weight_prependZero (n : ℕ) (f : Weak n) : weight (prependZero n f).val=weight f.val := by + rw [weight,Fin.sum_univ_succ] + simp only [prependZero,Fin.cons_zero,Fin.cons_succ,Nat.cast_zero,zero_add] + rfl + +lemma weight_shiftOne (n : ℕ) (f : Weak n) : weight (shiftOne n f).val=weight f.val+n := by + simp [weight,shiftOne,Finset.sum_add_distrib] + +lemma weakSplit_inv_energy (n : ℕ) (k : ℤ) (p : Weak n ⊕ Weak (n+1)) : + ((n+1:ℕ):ℤ)*k-2*weight (weakSplit n |>.symm p).val= + Sum.elim (fun f : Weak n=>(n:ℤ)*k-2*weight f.val+k) + (fun f : Weak (n+1)=>((n+1:ℕ):ℤ)*k-2*weight f.val-2*(n+1)) p := by + cases p with + | inl f => + change ((n+1:ℕ):ℤ)*k-2*weight (prependZero n f).val=_ + rw [weight_prependZero] + simp only [Sum.elim_inl,Nat.cast_add,Nat.cast_one] + ring + | inr f => + change ((n+1:ℕ):ℤ)*k-2*weight (shiftOne (n+1) f).val=_ + rw [weight_shiftOne] + simp only [Sum.elim_inr,Nat.cast_add,Nat.cast_one] + ring +end +end ElementaryPositivity.UnitSelections +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/AllPairDiagonal.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/AllPairDiagonal.lean new file mode 100644 index 0000000000000000000000000000000000000000..415c5b15c97d952639acb5a8061ce66b178b074b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/AllPairDiagonal.lean @@ -0,0 +1,130 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Histories.TwoLeafDiagonal + +namespace OAI + +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +open ElementaryPositivity.RawShuffle.SplitTree +variable {A D α β : Type*} [CommRing A] [CommRing D] [Algebra ℚ A] [Algebra ℚ D] + +lemma mapLinear_extendPolynomial (f : A →ₐ[ℚ] D) (e : α ≃ β) + (l : A →ₗ[ℚ] A) (m : D →ₗ[ℚ] D) (h : ∀ x, m (f x) = f (l x)) + (p : MvPolynomial α A) : + mapLinear m (extendPolynomial f e p) = extendPolynomial f e (mapLinear l p) := by + ext z + obtain ⟨z,rfl⟩ := Finsupp.mapDomain_surjective e.surjective z + simp only [coeff_mapLinear,Regroup.extendPolynomial_coeff] + exact h _ + +lemma extendPolynomial_symm (f : A ≃ₐ[ℚ] D) (e : α ≃ β) (p : MvPolynomial α A) : + extendPolynomial f.symm.toAlgHom e.symm (extendPolynomial f.toAlgHom e p) = p := by + induction p using MvPolynomial.induction_on with + | C a => simp only [extendPolynomial_C,AlgEquiv.coe_toAlgHom, + AlgEquiv.symm_apply_apply] + | add p q hp hq => simp only [map_add,hp,hq] + | mul_X p i hp => simp only [map_mul,hp,extendPolynomial_X,Equiv.symm_apply_apply] + +end ElementaryPositivity.CenterCalculus + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.CenterCalculus +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma dimensionEquivB_mem_sourceFiltration (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + change (taylorB a μ d (quotientAlg a μ d f)).eval _ = + quotientAlg a μ d (translationS d t f) + rw [taylorB_mk,eval_map_rat,taylorS_eval] + +omit [Fintype I] [DecidableEq I] in +lemma tensorValue_translation (d e : I → ℕ) (t : ℚ) (x : S d ⊗[ℚ] S e) : + tensorValue d e (TensorProduct.map (translationS d t) (translationS e t) x)= + translation t (tensorValue d e x) := by + induction x using TensorProduct.inductionOn with + | tmul f g => + simp only [TensorProduct.map_tmul,tensorValue_tmul,map_mul,translation_rename] + rfl + | add x y hx hy => simp only [map_add,hx,hy] + +lemma restrictTensor_translation {d e : I → ℕ} (A : Cut d e) (t : ℚ) (f : S (d+e)) : + restrictTensor A (translationS (d+e) t f)= + TensorProduct.map (translationS d t) (translationS e t) (restrictTensor A f) := by + apply tensorValue_injective + rw [tensorValue_translation,tensorValue_restrictTensor,tensorValue_restrictTensor,translation_rename] + rfl + +lemma restrictionB_translation (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + change restrictionB a c η hc hs A (quotientAlg a _ (d+e) (translationS (d+e) t f))= + TensorProduct.map (translationB a (SlopeArithmetic.slope c η) d t) + (translationB a (SlopeArithmetic.slope c η) e t) + (restrictionB a c η hc hs A (quotientAlg a _ (d+e) f)) + rw [restrictionB_mk,restrictionB_mk,restrictTensor_translation] + generalize restrictTensor A f=x + induction x using TensorProduct.inductionOn with + | tmul x y => rfl + | add x y hx hy => simp only [map_add,hx,hy] + +@[simp] lemma polynomialMapLinear_monomial {A D : Type*} [CommRing A] [CommRing D] + [Algebra ℚ A] [Algebra ℚ D] (l : A →ₗ[ℚ] D) (n : ℕ) (a : A) : + polynomialMapLinear l (Polynomial.monomial n a)=Polynomial.monomial n (l a) := by + ext m + simp only [polynomialMapLinear_coeff,Polynomial.coeff_monomial] + split_ifs <;> simp + +lemma polynomialMapLinear_eval_rat {A D : Type*} [CommRing A] [CommRing D] + [Algebra ℚ A] [Algebra ℚ D] (l : A →ₗ[ℚ] D) (p : Polynomial A) (t : ℚ) : + (polynomialMapLinear l p).eval (algebraMap ℚ D t)=l (p.eval (algebraMap ℚ A t)) := by + induction p using Polynomial.induction_on' with + | add p q hp hq => simp only [map_add,Polynomial.eval_add,hp,hq] + | monomial n a => + rw [polynomialMapLinear_monomial,Polynomial.eval_monomial,Polynomial.eval_monomial] + rw [← map_pow,← map_pow,mul_comm (l a),mul_comm a,← Algebra.smul_def,← Algebra.smul_def,map_smul] + +noncomputable def bothTaylorB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + B a μ d ⊗[ℚ] B a μ e →ₐ[ℚ] Polynomial (Polynomial (B a μ d ⊗[ℚ] B a μ e)) := + let L : B a μ d →ₐ[ℚ] Polynomial (Polynomial (B a μ d ⊗[ℚ] B a μ e)) := (Polynomial.CAlgHom : Polynomial (B a μ d ⊗[ℚ] B a μ e) →ₐ[ℚ] Polynomial (Polynomial (B a μ d ⊗[ℚ] B a μ e))).comp + ((Polynomial.mapAlgHom (Algebra.TensorProduct.includeLeft : + B a μ d →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e)).comp (taylorB a μ d)) + let R : B a μ e →ₐ[ℚ] Polynomial (Polynomial (B a μ d ⊗[ℚ] B a μ e)) := (Polynomial.mapAlgHom ((Polynomial.CAlgHom : (B a μ d ⊗[ℚ] B a μ e) →ₐ[ℚ] Polynomial (B a μ d ⊗[ℚ] B a μ e)).comp + (Algebra.TensorProduct.includeRight : B a μ e →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e))).comp (taylorB a μ e) + Algebra.TensorProduct.lift (S:=ℚ) L R (by + let : CommRing (Polynomial (B a μ d ⊗[ℚ] B a μ e)) := inferInstance + intro x y + exact mul_comm (L x) (R y)) + +noncomputable def evalTwo {A : Type*} [CommRing A] [Algebra ℚ A] + (p : Polynomial (Polynomial A)) (z w : ℚ) : A := + (p.eval (algebraMap ℚ (Polynomial A) w)).eval (algebraMap ℚ A z) + +lemma bothTaylorB_eval (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (x : B a μ d ⊗[ℚ] B a μ e) (z w : ℚ) : + evalTwo (bothTaylorB a μ d e x) z w= + TensorProduct.map (translationB a μ d z) (translationB a μ e w) x := by + induction x using TensorProduct.inductionOn with + | tmul f g => + change evalTwo + (Polynomial.C (Polynomial.map (Algebra.TensorProduct.includeLeft : + B a μ d →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e).toRingHom (taylorB a μ d f)) * + Polynomial.map ((Polynomial.CAlgHom : (B a μ d ⊗[ℚ] B a μ e) →ₐ[ℚ] Polynomial (B a μ d ⊗[ℚ] B a μ e)).comp + (Algebra.TensorProduct.includeRight : B a μ e →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e)).toRingHom + (taylorB a μ e g)) z w = _ + simp only [evalTwo,Polynomial.eval_mul,Polynomial.eval_C,eval_map_rat,taylorB_eval, + AlgHom.comp_apply,Polynomial.CAlgHom_apply,Polynomial.eval_C,TensorProduct.map_tmul] + change (translationB a μ d z f ⊗ₜ[ℚ] 1)*(1 ⊗ₜ[ℚ] translationB a μ e w g)=_ + rw [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + | add x y hx hy => simp only [map_add,evalTwo,Polynomial.eval_add] at *; rw [hx,hy] + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma relativeTaylorB_eval (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (x : B a μ d ⊗[ℚ] B a μ e) (z : ℚ) : + (relativeTaylorB a μ d e x).eval (algebraMap ℚ (B a μ d ⊗[ℚ] B a μ e) z)= + TensorProduct.map (translationB a μ d z) (LinearMap.id : B a μ e →ₗ[ℚ] B a μ e) x := by + induction x using TensorProduct.inductionOn with + | tmul f g => + change (Polynomial.map (Algebra.TensorProduct.includeLeft : + B a μ d →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e).toRingHom (taylorB a μ d f) * + Polynomial.C (1 ⊗ₜ[ℚ] g)).eval _ = _ + rw [Polynomial.eval_mul,eval_map_rat,taylorB_eval,Polynomial.eval_C] + change (translationB a μ d z f ⊗ₜ[ℚ] 1)*(1 ⊗ₜ[ℚ] g)=_ + rw [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + rfl + | add x y hx hy => simp only [map_add,Polynomial.eval_add,hx,hy] + +lemma evalTwo_ext {A : Type*} [CommRing A] [Algebra ℚ A] + (p q : Polynomial (Polynomial A)) (h : ∀ z w : ℚ,evalTwo p z w=evalTwo q z w) : p=q := by + apply polynomial_eq_of_rat_evals + intro w + apply polynomial_eq_of_rat_evals + intro z + exact h z w + +noncomputable def bothLeading (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 simp only [TensorProduct.map_tmul,LinearMap.id_apply,translationB_add] + | add x y hx hy => simp only [map_add,hx,hy] + +theorem bothLeading_diagonal_divisible (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + simp [canonicalLeftCut,canonicalRightCut,sumPackCut,embedPackCut,left] at hx hy + rw [Finset.card_union_of_disjoint hd] + simp [canonicalLeftCut,canonicalRightCut,sumPackCut,embedPackCut,left] + +lemma fourGridPolynomial_zero_of_source_mismatch (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g : S e) (d₁ e₁ d₂ e₂ : I → ℕ) (hd : d₁+d₂ ≠ d) : + fourGridPolynomial a f g d₁ e₁ d₂ e₂ = 0 := by + have hf : labeledPolynomial f (fun i=>left (canonicalLeftCut d₁ e₁ d₂ e₂) i ∪ + left (canonicalRightCut d₁ e₁ d₂ e₂) i) = 0 := by + apply dite_eq_right + intro h + apply hd + funext i + exact (canonical_source_card d₁ e₁ d₂ e₂ i).symm.trans (h i) + simp [fourGridPolynomial,canonicalGridPolynomial,gridPolynomial,hf] + +omit [∀ i,Fintype (A i)] in +lemma quotient_gridShapeTensor_zero (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 slope c η α) : + quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v) = 0 := by + unfold gridShapeTensor + apply quotientTensor_cast_zero + by_cases hsum : (fun i=>(u i).val) + (fun i=>(v i).val) = d + · apply quotient_cellTransfer_zero + apply destabilized_target c η hc + · rw [(shape_add_complement u).trans (realization_card R), + (shape_add_complement v).trans (realization_card T)] + exact hα + · rw [hsum]; exact hd + · rw [hsum,(shape_add_complement u).trans (realization_card R)] + exact hμ + · rw [fourGridPolynomial_zero_of_source_mismatch a f g _ _ _ _ hsum,map_zero,map_zero] + +omit [∀ i,Fintype (A i)] in +lemma quotient_gridTensor_zero (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 slope c η α) : + quotientTensor a (slope c η) α β (gridTensor a f g p R T) = 0 := by + simp only [gridTensor,map_sum] + apply Finset.sum_eq_zero + intro u hu + apply Finset.sum_eq_zero + intro v hv + exact quotient_gridShapeTensor_zero a c η hc f g p R T u v hd hα hμ + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + +noncomputable def crossSign (d e : I → ℕ) : ℚ := + ∏ i, ∏ _ : Fin (d i), ∏ _ : Fin (e i), (-1:ℚ) + +omit [DecidableEq I] [∀ i,Fintype (A i)] in +lemma sameDen_realization {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) : + sameDen (left p) (right p) = + ∏ i,∏ x : Fin (d i), ∏ y : Fin (e i), + (X (realizationMap T ⟨i,y⟩) - X (realizationMap R ⟨i,x⟩)) := by + unfold sameDen + apply Finset.prod_congr rfl + intro i hi + rw [← PackEnumeration.map_univ (R i),← PackEnumeration.map_univ (T i)] + simp only [Finset.prod_map,diagonal,realizationMap] + rfl + +omit [DecidableEq I] [∀ i,Fintype (A i)] in +lemma targetEmbedding_crossDifference {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) : + rename (targetEmbedding p R T) (crossDifference d e) = + C (crossSign d e) * sameDen (left p) (right p) := by + rw [sameDen_realization p R T] + simp only [crossDifference,map_prod,map_sub,rename_X,crossSign,map_neg,map_one] + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i hi + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro x hx + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro y hy + change X (realizationMap R ⟨i,x⟩) - X (realizationMap T ⟨i,y⟩) = + -1 * (X (realizationMap T ⟨i,y⟩) - X (realizationMap R ⟨i,x⟩)) + ring + +omit [∀ i,Fintype (A i)] in +lemma targetValueAt_crossTensor {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) : + targetValueAt p R T (crossTensor d e) = crossSign d e • + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (sameDen (left p) (right p)) := by + change renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (algebraMap (MvPolynomial (CellVars d e) ℚ) (FractionRing (MvPolynomial (CellVars d e) ℚ)) + (tensorValue d e (crossTensor d e))) = _ + rw [tensorValue_crossTensor] + have hh := targetEmbedding_algebraMap p R T (crossDifference d e) + calc + _ = _ := hh + _ = _ := by + rw [targetEmbedding_crossDifference, ← smul_eq_C_mul] + exact map_rat_smul (algebraMap (MvPolynomial (Σi,A i) ℚ) + (FractionRing (MvPolynomial (Σi,A i) ℚ))).toAddMonoidHom _ _ + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +lemma targetValueAt_smul {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) + (r : ℚ) (t : S d ⊗[ℚ] S e) : + targetValueAt p R T (r • t) = r • targetValueAt p R T t := + map_rat_smul (targetValueAt p R T) r t + +lemma cleared_restrictTensor (a : I → I → ℕ) {d e α β : I → ℕ} (h : d+e=α+β) + (f : S d) (g : S e) {s : Pack (A:=A)} (R : Realization (α+β) s) (u : Cut α β) : + crossTensor α β * restrictTensor u (castS h (shufflePolynomial a f g)) = + crossSign α β • gridTensor a f g (cutRealizationEquiv R u).val + (leftRealization R u) (rightRealization R u) := by + apply targetValueAt_injective (cutRealizationEquiv R u).val (leftRealization R u) (rightRealization R u) + rw [targetValueAt_mul,targetValueAt_crossTensor,targetValueAt_restrictTensor, + targetValueAt_smul,targetValueAt_gridTensor,labeledValue_cast] + exact smul_mul_assoc _ _ _ + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def relativeTaylorB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + B a μ d ⊗[ℚ] B a μ e →ₐ[ℚ] Polynomial (B a μ d ⊗[ℚ] B a μ e) := + let L : B a μ d →ₐ[ℚ] Polynomial (B a μ d ⊗[ℚ] B a μ e) := + (Polynomial.mapAlgHom (Algebra.TensorProduct.includeLeft : B a μ d →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e)).comp (taylorB a μ d) + let R : B a μ e →ₐ[ℚ] Polynomial (B a μ d ⊗[ℚ] B a μ e) := + Polynomial.CAlgHom.comp (Algebra.TensorProduct.includeRight : B a μ e →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e) + Algebra.TensorProduct.lift (S:=ℚ) L R (fun x y => mul_comm (L x) (R y)) + +@[simp] lemma relativeTaylorB_tmul (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (f : B a μ d) (g : B a μ e) : + relativeTaylorB a μ d e (f ⊗ₜ[ℚ] g) = + Polynomial.map (Algebra.TensorProduct.includeLeft : B a μ d →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e).toRingHom (taylorB a μ d f) * + Polynomial.C ((1 : B a μ d) ⊗ₜ[ℚ] g) := by + simp only [relativeTaylorB] + rfl + +lemma quotientTensor_tmul (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (f : S d) (g : S e) : + quotientTensor a μ d e (f ⊗ₜ[ℚ] g) = quotientAlg a μ d f ⊗ₜ[ℚ] quotientAlg a μ e g := rfl + +lemma relativeTaylor_quotient (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (t : S d ⊗[ℚ] S e) : + Polynomial.map (quotientTensor a μ d e).toRingHom (relativeTaylor d e t) = + relativeTaylorB a μ d e (quotientTensor a μ d e t) := by + induction t using TensorProduct.inductionOn with + | tmul f g => + rw [relativeTaylor_tmul,quotientTensor_tmul,relativeTaylorB_tmul,taylorB_mk, + Polynomial.map_mul,Polynomial.map_C] + have hr : (quotientTensor a μ d e).toRingHom (1 ⊗ₜ[ℚ] g) = 1 ⊗ₜ[ℚ] quotientAlg a μ e g := by + change quotientAlg a μ d 1 ⊗ₜ[ℚ] quotientAlg a μ e g = _ + rw [map_one] + rw [hr] + congr 1 + rw [Polynomial.map_map,Polynomial.map_map] + congr 1 + | add f g hf hg => simp only [map_add,Polynomial.map_add,hf,hg] + +lemma quotient_relativeTaylor_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (t : S d ⊗[ℚ] S e) (h : quotientTensor a μ d e t = 0) : + Polynomial.map (quotientTensor a μ d e).toRingHom (relativeTaylor d e t) = 0 := by + rw [relativeTaylor_quotient,h,map_zero] + +lemma quotient_crossTensor_cancel (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (t : S d ⊗[ℚ] S e) (h : quotientTensor a μ d e (crossTensor d e * t) = 0) : + quotientTensor a μ d e t = 0 := by + have ht := quotient_relativeTaylor_zero a μ d e (crossTensor d e * t) h + rw [map_mul,Polynomial.map_mul] at ht + have hz : Polynomial.map (quotientTensor a μ d e).toRingHom (relativeTaylor d e t) = 0 := + (crossClearing_cancel a μ d e _).mp ht + have he := congrArg (fun p : Polynomial (B a μ d ⊗[ℚ] B a μ e) => p.eval 0) hz + rw [← show algebraMap ℚ (B a μ d ⊗[ℚ] B a μ e) 0 = 0 from map_zero _] at he + rw [eval_map_rat,relativeTaylor_eval] at he + have htr : TensorProduct.map (translationS d 0) (LinearMap.id : S e →ₗ[ℚ] S e) t = t := by + clear h ht hz he + induction t using TensorProduct.inductionOn with + | tmul f g => simp [translationS] + | add f g hf hg => simp only [map_add,hf,hg] + simpa only [htr,Polynomial.eval_zero,Polynomial.coeff_zero] using he + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/CellLeadingSum.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/CellLeadingSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..7140f0ce34fc9f20fdc71ed9037df994d4b9c6dc --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/CellLeadingSum.lean @@ -0,0 +1,177 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.TwoTargetFiltration + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.SlopeArithmetic +open ElementaryPositivity.PackConvolution HahnSeries SeparationInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] clearBTensorB clearBTensorBA Classical.propDecidable + +noncomputable local instance cellLeadTensorN (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + NonUnitalNonAssocSemiring (B a μ d⊗[ℚ]B a μ e) := + (clearBTensorB a μ d e).toNonUnitalNonAssocSemiring + +noncomputable def cellLeadingB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0hd hm.1), + fourGridPolynomial_zero_of_source_mismatch a f g _ _ _ _ hd] + simp only [map_zero,sub_zero] + exact Submodule.zero_mem _ + +noncomputable def castBTensor (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e d' e' : I → ℕ} (h : d=d') (k : e=e') : + B a μ d⊗[ℚ]B a μ e ≃ₗ[ℚ] B a μ d'⊗[ℚ]B a μ e' := by + subst d' + subst e' + exact LinearEquiv.refl ℚ _ + +lemma castBTensor_sub (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e d' e' : I → ℕ} (h : d=d') (k : e=e') + (x y : B a μ d⊗[ℚ]B a μ e) : + castBTensor a μ h k (x-y)=castBTensor a μ h k x-castBTensor a μ h k y := by + subst d' + subst e' + rfl + +lemma clearedConstantB_castTensor (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e d' e' : I → ℕ} (h : d=d') (k : e=e') (x : S d⊗[ℚ]S e) : + clearedConstantB a μ d' e' (quotientTensor a μ d' e' (castTensor h k x))= + castBTensor a μ h k (clearedConstantB a μ d e (quotientTensor a μ d e x)) := by + subst d' + subst e' + rfl + +lemma castBTensor_mem_unitalSource (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(u i).val) (shapeComplement u) + (fun i=>(v i).val) (shapeComplement v)) : B a (slope c η) α⊗[ℚ]B a (slope c η) β := + castBTensor a (slope c η) ((shape_add_complement u).trans (realization_card R)) + ((shape_add_complement v).trans (realization_card T)) + (cellLeadingB a c η hc θ _ _ _ _ hon f g) + +omit [∀ i, Fintype (A i)] in +lemma clearedConstantB_gridShape_leading (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(u i).val) (shapeComplement u) + (fun i=>(v i).val) (shapeComplement v)) : + clearedConstantB a (slope c η) α β (quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v))- + gridShapeLeadingB a c η hc θ f g p R T u v hon∈ + unitalSourceTensorFiltration a c η hc θ α β (U+V+1) := by + unfold gridShapeTensor gridShapeLeadingB + rw [clearedConstantB_castTensor,←castBTensor_sub] + apply castBTensor_mem_unitalSource + apply clearedConstantB_cell_leading a c η hc θ hχ _ _ _ _ hon _ U V f g hf hg + rw [(shape_add_complement u).trans (realization_card R), + (shape_add_complement v).trans (realization_card T)] + exact h + +noncomputable def gridLeadingB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(u i).val) (shapeComplement u) + (fun i=>(v i).val) (shapeComplement v) + then gridShapeLeadingB a c η hc θ f g p R T u v hon else 0 + +omit [∀ i, Fintype (A i)] in +lemma clearedConstantB_grid_leading (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0a j i) e₁ d₂ (crossingColumnAlg d₁ e₁ d₂ e₂))⁻¹).val + +lemma fourGrid_relativeTaylor_factor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S (d₁+d₂)) (g : S (e₁+e₂)) : + fourRelativeTaylor d₁ e₁ d₂ e₂ + (separateFour d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂))= + Polynomial.map (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom + (relativeTaylor d₁ d₂ (restrictTensor (firstCut d₁ d₂) f)) * + Polynomial.map (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom + (relativeTaylor e₁ e₂ (restrictTensor (firstCut e₁ e₂) g)) * + fourRelativeTaylor d₁ e₁ d₂ e₂ (fourCrossTensor a d₁ e₁ d₂ e₂) := by + rw [separateFour_grid_factor a d₁ e₁ d₂ e₂ (firstCut d₁ d₂) (firstCut e₁ e₂)] + rw [←fourColumns_product d₁ e₁ d₂ e₂] + simp only [map_mul,←firstColumn_relativeTaylor,←secondColumn_relativeTaylor] + +lemma polynomial_mapped_product {R S T : Type*} [CommRing R] [CommRing S] [CommRing T] + (f : R →+* T) (g : S →+* T) (p : Polynomial R) (q : Polynomial S) (r : Polynomial T) : + polynomial (Polynomial.map f p * Polynomial.map g q * r)= + mapRing f (polynomial p)*mapRing g (polynomial q)*polynomial r := by + rw [polynomial.map_mul,polynomial.map_mul,←polynomial_map,←polynomial_map] + +omit [Fintype I] [DecidableEq I] in +private lemma fourPolynomial_mapped_product_pair (d₁ e₁ d₂ e₂ : I → ℕ) + (p : Polynomial (S d₁⊗[ℚ]S d₂)) (q : Polynomial (S e₁⊗[ℚ]S e₂)) : + polynomial (Polynomial.map (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom p * + Polynomial.map (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom q)= + mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom (polynomial p)* + mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom (polynomial q) := + (polynomial.map_mul _ _).trans + (congrArg₂ (fun x y => x * y) + (polynomial_map (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom p).symm + (polynomial_map (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom q).symm) + +omit [Fintype I] [DecidableEq I] in +lemma fourPolynomial_mapped_product (d₁ e₁ d₂ e₂ : I → ℕ) + (p : Polynomial (S d₁⊗[ℚ]S d₂)) (q : Polynomial (S e₁⊗[ℚ]S e₂)) + (r : Polynomial ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂))) : + polynomial (Polynomial.map (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom p * + Polynomial.map (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom q * r)= + mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom (polynomial p)* + mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom (polynomial q)*polynomial r := by + calc + _ = polynomial (Polynomial.map (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom p * + Polynomial.map (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom q) * polynomial r := + polynomial.map_mul _ _ + _ = _ := congrArg (fun t => t * polynomial r) + (fourPolynomial_mapped_product_pair d₁ e₁ d₂ e₂ p q) + +lemma fourGrid_taylor_factor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S (d₁+d₂)) (g : S (e₁+e₂)) : + polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ + (separateFour d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂)))= + mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom + (polynomial (relativeTaylor d₁ d₂ (restrictTensor (firstCut d₁ d₂) f))) * + mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom + (polynomial (relativeTaylor e₁ e₂ (restrictTensor (firstCut e₁ e₂) g))) * + polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ (fourCrossTensor a d₁ e₁ d₂ e₂)) := by + rw [fourGrid_relativeTaylor_factor] + exact fourPolynomial_mapped_product d₁ e₁ d₂ e₂ _ _ _ + +lemma negative_unit_word_rat {R : Type*} [CommRing R] [Algebra ℚ R] + (n : ℤ) (A B D : (LaurentSeries R)ˣ) : + ((-1)^n*(A*B*D)).val=HahnSeries.C (algebraMap ℚ R ((-1 : ℚ)^n))*(A.val*B.val*D.val) := by + rw [Units.val_mul,negative_unit_rat,Units.val_mul,Units.val_mul] + +lemma fourTensorKernelRHS_scalar (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (fourTensorKernelRHS a d₁ e₁ d₂ e₂).val= + HahnSeries.C (algebraMap ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) ((-1 : ℚ)^eulerForm a d₂ e₁)) * + ((fourFirstInverseUnit a d₁ e₁ d₂ e₂).val * + (fourSecondInverseUnit a d₁ e₁ d₂ e₂).val * + (fourCrossingInverseUnit a d₁ e₁ d₂ e₂ * + (fourCrossingInverseUnit (fun i j=>a j i) d₁ e₁ d₂ e₂)⁻¹).val) := by + unfold fourTensorKernelRHS + rw [Units.val_mul, negative_unit_rat] + rfl + +lemma kernel_product_rearrange {R : Type*} [CommRing R] + (K L A B C D P Q r : R) (h : K*L*C=r*(A*B*D)) : + K*L*(P*Q*C)=r*((A*P)*(B*Q)*D) := by + calc + _ = (K*L*C)*(P*Q) := by ring + _ = _ := by rw [h]; ring + +omit [Fintype I] [DecidableEq I] in +lemma four_rat_smul_series (d₁ e₁ d₂ e₂ : I → ℕ) (r : ℚ) + (x : LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂))) : + r • x=HahnSeries.C (algebraMap ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) r)*x := + @rat_smul_series ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) + (cancelFourRing d₁ e₁ d₂ e₂) (cancelFourAlg d₁ e₁ d₂ e₂) r x + +lemma firstColumn_tensorSeparationSeries (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S (d₁+d₂)) : + mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom (tensorSeparationSeries a d₁ d₂ f)= + (fourFirstInverseUnit a d₁ e₁ d₂ e₂).val * + mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom + (polynomial (relativeTaylor d₁ d₂ (restrictTensor (firstCut d₁ d₂) f))) := + (mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom).map_mul _ _ + +lemma secondColumn_tensorSeparationSeries (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (g : S (e₁+e₂)) : + mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom (tensorSeparationSeries a e₁ e₂ g)= + (fourSecondInverseUnit a d₁ e₁ d₂ e₂).val * + mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom + (polynomial (relativeTaylor e₁ e₂ (restrictTensor (firstCut e₁ e₂) g))) := + (mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom).map_mul _ _ + +lemma fourInputSeries_factor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S (d₁+d₂)) (g : S (e₁+e₂)) : + fourInputSeries a d₁ e₁ d₂ e₂ f g= + ((fourFirstInverseUnit a d₁ e₁ d₂ e₂).val * + mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom + (polynomial (relativeTaylor d₁ d₂ (restrictTensor (firstCut d₁ d₂) f)))) * + ((fourSecondInverseUnit a d₁ e₁ d₂ e₂).val * + mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom + (polynomial (relativeTaylor e₁ e₂ (restrictTensor (firstCut e₁ e₂) g)))) * + (fourCrossingInverseUnit a d₁ e₁ d₂ e₂ * + (fourCrossingInverseUnit (fun i j=>a j i) d₁ e₁ d₂ e₂)⁻¹).val := by + exact congrArg₂ + (fun x y : LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) => + x * y * (fourCrossingInverseUnit a d₁ e₁ d₂ e₂ * + (fourCrossingInverseUnit (fun i j=>a j i) d₁ e₁ d₂ e₂)⁻¹).val) + (firstColumn_tensorSeparationSeries a d₁ e₁ d₂ e₂ f) + (secondColumn_tensorSeparationSeries a d₁ e₁ d₂ e₂ g) + +lemma kernel_product_rearrange_with_factors {R : Type*} [CommRing R] + (K L A B C D P Q r X Y : R) (h : K*L*C=r*(A*B*D)) + (hX : X=P*Q*C) (hY : Y=(A*P)*(B*Q)*D) : K*L*X=r*Y := by + rw [hX,hY] + exact kernel_product_rearrange K L A B C D P Q r h + +lemma fourGrid_normalized_algebra (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S (d₁+d₂)) (g : S (e₁+e₂)) + (K L r : LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂))) + (h : K*L*polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ (fourCrossTensor a d₁ e₁ d₂ e₂))= + r*((fourFirstInverseUnit a d₁ e₁ d₂ e₂).val * + (fourSecondInverseUnit a d₁ e₁ d₂ e₂).val * + (fourCrossingInverseUnit a d₁ e₁ d₂ e₂ * + (fourCrossingInverseUnit (fun i j=>a j i) d₁ e₁ d₂ e₂)⁻¹).val)) : + K*L*polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ + (separateFour d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂)))= + r*fourInputSeries a d₁ e₁ d₂ e₂ f g := + @kernel_product_rearrange_with_factors + (LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂))) (cancelSeriesRing d₁ e₁ d₂ e₂) + K L _ _ _ _ _ _ r _ _ h + (fourGrid_taylor_factor a d₁ e₁ d₂ e₂ f g) (fourInputSeries_factor a d₁ e₁ d₂ e₂ f g) + +lemma fourGrid_normalized (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) + (f : S (d₁+d₂)) (g : S (e₁+e₂)) : + (mappedInverseKernel a (d₁+e₁) (d₂+e₂) (restrictRows d₁ e₁ d₂ e₂ A B)).val * + ((mappedInverseKernel (fun _ _ : I=>0) (d₁+e₁) (d₂+e₂) (restrictRows d₁ e₁ d₂ e₂ A B))⁻¹).val * + polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ + (separateFour d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂)))= + ((-1 : ℚ)^eulerForm a d₂ e₁) • fourInputSeries a d₁ e₁ d₂ e₂ f g := by + apply (fourGrid_normalized_algebra a d₁ e₁ d₂ e₂ f g _ _ _ + ((fourTensorKernel_cancellation a d₁ e₁ d₂ e₂ A B).trans + (fourTensorKernelRHS_scalar a d₁ e₁ d₂ e₂))).trans + exact (four_rat_smul_series d₁ e₁ d₂ e₂ _ _).symm + +end ElementaryPositivity.RawShuffle + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/CellTransferSeparation.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/CellTransferSeparation.lean new file mode 100644 index 0000000000000000000000000000000000000000..67a25482cdd7378fa7759de9659523a3899eaa67 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/CellTransferSeparation.lean @@ -0,0 +1,157 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CenterLineSpecialization +import OAI.Combinatorics.Chromatic.Shuffle.SymbolDetection +import OAI.Combinatorics.Chromatic.Shuffle.CellSeparation + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial HahnSeries +open ElementaryPositivity.LaurentAtInfinity SeparationInfinity +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] cancelTensorRing cancelTensorAlg cancelFourRing cancelFourAlg +attribute [local instance] cancelTensorSelf cancelTensorNonUnital cancelFourNonUnital cancelSeriesRing +attribute [local instance] cellSepTensorSemiring cellSepTensorNonAssoc cellSepFourSemiring cellSepFourNonAssoc cellSepFourModule + +lemma mappedInverseKernel_ratio {R : Type*} [CommRing R] [Algebra ℚ R] + (a b : I → I → ℕ) (d e : I → ℕ) (f : S d⊗[ℚ]S e →ₐ[ℚ]R) : + mapRing f.toRingHom ((inverseKernelUnit a d e)*(inverseKernelUnit b d e)⁻¹).val= + (mappedInverseKernel a d e f).val * ((mappedInverseKernel b d e f)⁻¹).val := by + rw [Units.val_mul,map_mul] + rfl + +lemma cellTransfer_normalized (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S (d₁+d₂)) (g : S (e₁+e₂)) : + ((inverseKernelUnit a (d₁+e₁) (d₂+e₂))* + (inverseKernelUnit (fun _ _ : I=>0) (d₁+e₁) (d₂+e₂))⁻¹).val * + polynomial (relativeTaylor (d₁+e₁) (d₂+e₂) + (cellTransfer a d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂)))= + ((-1 : ℚ)^eulerForm a d₂ e₁) • + mapLinear (twoTargetTransfer a d₁ e₁ d₂ e₂) (fourInputSeries a d₁ e₁ d₂ e₂ f g) := by + rw [cellTransfer,LinearMap.comp_apply,←twoTarget_polynomial_relativeTaylor, + ←twoTarget_Laurent_projection a d₁ e₁ d₂ e₂ (firstCut d₁ e₁) (firstCut d₂ e₂), + mappedInverseKernel_ratio,fourGrid_normalized] + exact (mapLinear (twoTargetTransfer a d₁ e₁ d₂ e₂)).map_smul _ _ + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity +open SplitTree +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +lemma eulerForm_transpose (a : I → I → ℕ) (d e : I → ℕ) : + eulerForm (fun i j=>a j i) d e=eulerForm a e d := by + unfold eulerForm + congr 1 + · exact Finset.sum_congr rfl (fun i hi=>mul_comm _ _) + · rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + ring + +namespace SeparationInfinity + +noncomputable def mixedInverseKernelUnit (a b : I → I → ℕ) + (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + (LaurentSeries (B a μ d⊗[ℚ] B a μ e))ˣ := + Units.map (mapRing (R:=S d⊗[ℚ]S e) (S:=B a μ d⊗[ℚ]B a μ e) + (Algebra.TensorProduct.map (quotientAlg a μ d) (quotientAlg a μ e)).toRingHom).toMonoidHom + (inverseKernelUnit b d e) + +lemma pointed_mixedInverseKernel (a b : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0f.coeff k) + (realize_inverseKernelUnit b L.dim R.dim) + exact congrArg (fun f=>algebraMap ℚ _ (crossPointEval L R v w f)) h + +lemma refined_mixedKernel_degreeZero (a b : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0a j i) μ d e)⁻¹ + +end SeparationInfinity + +namespace SplitTree +omit [DecidableEq I] in +lemma scalarCrossKernel_transpose (a : I → I → ℕ) (c η : I → ℝ) + (θ : ℝ) (hχ : SlopeEulerSymmetric a c η θ) (L R : SplitTree I) + (hL : L.OnSlope c η θ) (hR : R.OnSlope c η θ) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) : + scalarCrossKernel (fun i j=>a j i) L R v w=scalarCrossKernel a L R v w := by + unfold scalarCrossKernel + apply Finset.prod_congr rfl + intro z hz + apply Finset.prod_congr rfl + intro t ht + rw [eulerForm_transpose] + congr 1 + obtain ⟨hz,hzs⟩:=L.leafDimension_onSlope c η θ hL z + obtain ⟨ht,hts⟩:=R.leafDimension_onSlope c η θ hR t + exact (hχ _ _ hz ht hzs hts).symm +end SplitTree +namespace SeparationInfinity +lemma refined_braidingRatio_degreeZero (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0a j i) (SlopeArithmetic.slope c η) L.dim R.dim) := by + apply Units.ext + change H _=H _ + dsimp only [H,RingHom.comp_apply] + rw [refined_mixedKernel_degreeZero,refined_mixedKernel_degreeZero, + scalarCrossKernel_transpose a c η θ hχ L R hL hR] + have hh : Φ (braidingRatioUnit a (SlopeArithmetic.slope c η) L.dim R.dim)=1 := by + rw [braidingRatioUnit,map_mul,map_inv,he,mul_inv_cancel] + exact congrArg Units.val hh +end SeparationInfinity +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/CellVars.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/CellVars.lean new file mode 100644 index 0000000000000000000000000000000000000000..daa97b51df8ab3526530762c6b67de1af6393c12 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/CellVars.lean @@ -0,0 +1,199 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ShuffleTensorLinear + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.SeparatedSymmetry +open scoped TensorProduct +variable {I : Type*} + +abbrev CellVars (d e : I → ℕ) := (Σi,Fin (d i)) ⊕ (Σi,Fin (e i)) +abbrev CellGroup (d e : I → ℕ) := + (∀ i,Equiv.Perm (Fin (d i))) × (∀ i,Equiv.Perm (Fin (e i))) + +def cellAction (d e : I → ℕ) : CellGroup d e →* Equiv.Perm (CellVars d e) := + sumAction (packAction (fun i=>Fin (d i))) (packAction (fun i=>Fin (e i))) + +noncomputable def fourValue (d₁ e₁ d₂ e₂ : I → ℕ) : + (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂) →ₗ[ℚ] + MvPolynomial (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) ℚ := + (tensorEquivSum ℚ _ _ ℚ).toLinearMap ∘ₗ + TensorProduct.map (tensorValue d₁ e₁) (tensorValue d₂ e₂) + +@[simp] lemma fourValue_tmul (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S d₁ ⊗[ℚ] S e₁) (g : S d₂ ⊗[ℚ] S e₂) : + fourValue d₁ e₁ d₂ e₂ (f ⊗ₜ[ℚ] g) = + rename Sum.inl (tensorValue d₁ e₁ f) * rename Sum.inr (tensorValue d₂ e₂ g) := + tensorEquivSum_tmul _ _ + +variable [Fintype I] [DecidableEq I] + +noncomputable def separateFour (d₁ e₁ d₂ e₂ : I → ℕ) : + MvPolynomial (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) ℚ →ₗ[ℚ] + (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂) := + TensorProduct.map (separateTensor d₁ e₁) (separateTensor d₂ e₂) ∘ₗ + (tensorEquivSum ℚ _ _ ℚ).symm.toLinearMap + +@[simp] lemma separateFour_product (d₁ e₁ d₂ e₂ : I → ℕ) + (f : MvPolynomial (CellVars d₁ e₁) ℚ) (g : MvPolynomial (CellVars d₂ e₂) ℚ) : + separateFour d₁ e₁ d₂ e₂ (rename Sum.inl f * rename Sum.inr g) = + separateTensor d₁ e₁ f ⊗ₜ[ℚ] separateTensor d₂ e₂ g := by + rw [← tensorEquivSum_tmul] + simp [separateFour] + +lemma fourValue_separateFour (d₁ e₁ d₂ e₂ : I → ℕ) + (p : MvPolynomial (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) ℚ) + (hp : ∀ σ, rename (sumAction (cellAction d₁ e₁) (cellAction d₂ e₂) σ) p = p) : + fourValue d₁ e₁ d₂ e₂ (separateFour d₁ e₁ d₂ e₂ p) = p := by + have hh := invariant_separated_span (cellAction d₁ e₁) (cellAction d₂ e₂) p hp + clear hp + induction hh using Submodule.span_induction with + | mem p hp => + obtain ⟨f,g,hf,hg,rfl⟩ := hp + rw [separateFour_product,fourValue_tmul, + tensorValue_separateTensor d₁ e₁ f hf,tensorValue_separateTensor d₂ e₂ g hg] + | zero => rw [(separateFour d₁ e₁ d₂ e₂).map_zero, (fourValue d₁ e₁ d₂ e₂).map_zero] + | add f g hf hg ihf ihg => simp only [map_add,ihf,ihg] + | smul c f hf ih => simp only [map_smul,ih] + +@[simp] lemma separateFour_fourValue (d₁ e₁ d₂ e₂ : I → ℕ) + (p : (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂)) : + separateFour d₁ e₁ d₂ e₂ (fourValue d₁ e₁ d₂ e₂ p) = p := by + induction p using TensorProduct.inductionOn with + | tmul f g => simp only [fourValue_tmul,separateFour_product,separateTensor_tensorValue] + | add f g hf hg => simp only [map_add,hf,hg] + +lemma fourValue_injective (d₁ e₁ d₂ e₂ : I → ℕ) : + Function.Injective (fourValue d₁ e₁ d₂ e₂) := + Function.LeftInverse.injective (separateFour_fourValue d₁ e₁ d₂ e₂) + +noncomputable def cellTransfer (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + MvPolynomial (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) ℚ →ₗ[ℚ] + S (d₁+e₁) ⊗[ℚ] S (d₂+e₂) := + twoTargetTransfer a d₁ e₁ d₂ e₂ ∘ₗ separateFour d₁ e₁ d₂ e₂ + +lemma quotient_cellTransfer_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d₁ e₁ d₂ e₂ : I → ℕ) + (h : (d₁≠0 ∧ e₁≠0 ∧ μ d₁ > μ (d₁+e₁)) ∨ + (d₂≠0 ∧ e₂≠0 ∧ μ d₂ > μ (d₂+e₂))) + (p : MvPolynomial (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) ℚ) : + quotientTensor a μ (d₁+e₁) (d₂+e₂) (cellTransfer a d₁ e₁ d₂ e₂ p) = 0 := + quotient_twoTargetTransfer_zero a μ d₁ e₁ d₂ e₂ h _ + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.SeparatedSymmetry +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def renameInjFraction {α β : Type*} (f : α → β) (hf : Function.Injective f) : + FractionRing (MvPolynomial α ℚ) →+* FractionRing (MvPolynomial β ℚ) := + IsFractionRing.lift (g := (algebraMap (MvPolynomial β ℚ) + (FractionRing (MvPolynomial β ℚ))).comp (rename f).toRingHom) + ((IsFractionRing.injective (MvPolynomial β ℚ) _).comp (MvPolynomial.rename_injective f hf)) + +@[simp] lemma renameInjFraction_algebraMap {α β : Type*} (f : α → β) (hf : Function.Injective f) + (p : MvPolynomial α ℚ) : + renameInjFraction f hf (algebraMap _ (FractionRing (MvPolynomial α ℚ)) p) = + algebraMap _ (FractionRing (MvPolynomial β ℚ)) (rename f p) := by + exact IsFractionRing.lift_algebraMap (g := (algebraMap (MvPolynomial β ℚ) + (FractionRing (MvPolynomial β ℚ))).comp (rename f).toRingHom) _ _ + +noncomputable def localizeTensor (d e : I → ℕ) : + S d ⊗[ℚ] S e →ₗ[ℚ] FractionRing (MvPolynomial (CellVars d e) ℚ) where + toFun f := algebraMap _ _ (tensorValue d e f) + map_add' := by intro f g; rw [map_add,map_add] + map_smul' := by + intro r f + rw [map_smul] + exact map_rat_smul (algebraMap (MvPolynomial (CellVars d e) ℚ) + (FractionRing (MvPolynomial (CellVars d e) ℚ))) r _ + +lemma localizeTensor_injective (d e : I → ℕ) : Function.Injective (localizeTensor d e) := by + intro f g h + apply tensorValue_injective d e + exact IsFractionRing.injective _ (FractionRing (MvPolynomial (CellVars d e) ℚ)) h + +noncomputable def cutKernel (a : I → I → ℕ) {d e : I → ℕ} (A : Cut d e) : + FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ) := + algebraMap _ _ (∏ i, ∏ j,cutFactor A i j (a i j)) / + algebraMap _ _ (cutDenominator A) + +lemma tensorShuffle_kernel (a : I → I → ℕ) {d e : I → ℕ} + (p : MvPolynomial (CellVars d e) ℚ) : tensorShuffle a p = + ∑ A : Cut d e, algebraMap _ _ (rename (cutSplit A) p) * cutKernel a A := by + simp only [tensorShuffle,LinearMap.coe_mk,AddHom.coe_mk,map_mul,cutKernel,mul_div_assoc] + +noncomputable def doubleTensorShuffle (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + MvPolynomial (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) ℚ →ₗ[ℚ] + FractionRing (MvPolynomial (CellVars (d₁+e₁) (d₂+e₂)) ℚ) where + toFun p := ∑ A : Cut d₁ e₁, ∑ B : Cut d₂ e₂, + algebraMap _ _ (rename (Sum.map (cutSplit A) (cutSplit B)) p) * + renameInjFraction Sum.inl Sum.inl_injective (cutKernel a A) * + renameInjFraction Sum.inr Sum.inr_injective (cutKernel a B) + map_add' := by + intro p q + simp only [map_add,add_mul,Finset.sum_add_distrib] + map_smul' := by + let : DistribSMul ℚ (FractionRing (MvPolynomial (CellVars (d₁+e₁) (d₂+e₂)) ℚ)) := + (inferInstance : Module ℚ (FractionRing (MvPolynomial (CellVars (d₁+e₁) (d₂+e₂)) ℚ))).toDistribMulAction.toDistribSMul + intro r p + simp only [map_smul,map_rat_smul,smul_mul_assoc,Finset.smul_sum,RingHom.id_apply] + +lemma doubleTensorShuffle_product (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : MvPolynomial (CellVars d₁ e₁) ℚ) (g : MvPolynomial (CellVars d₂ e₂) ℚ) : + doubleTensorShuffle a d₁ e₁ d₂ e₂ (rename Sum.inl f * rename Sum.inr g) = + renameInjFraction Sum.inl Sum.inl_injective (tensorShuffle a f) * + renameInjFraction Sum.inr Sum.inr_injective (tensorShuffle a g) := by + rw [tensorShuffle_kernel,tensorShuffle_kernel] + simp only [map_sum,map_mul,renameInjFraction_algebraMap, + Finset.sum_mul,Finset.mul_sum,doubleTensorShuffle,LinearMap.coe_mk,AddHom.coe_mk, + rename_rename] + conv_rhs => rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro A hA + apply Finset.sum_congr rfl + intro B hB + change + (algebraMap _ _ (rename (Sum.inl ∘ cutSplit A) f) * + algebraMap _ _ (rename (Sum.inr ∘ cutSplit B) g)) * _ * _ = _ + ring + +lemma doubleTensorShuffle_fourValue (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂)) : + doubleTensorShuffle a d₁ e₁ d₂ e₂ (fourValue d₁ e₁ d₂ e₂ f) = + localizeTensor (d₁+e₁) (d₂+e₂) (twoTargetTransfer a d₁ e₁ d₂ e₂ f) := by + induction f using TensorProduct.inductionOn with + | tmul f g => + rw [fourValue_tmul,doubleTensorShuffle_product,tensorShuffle_tensorValue, + tensorShuffle_tensorValue] + simp only [localizeS_apply, + twoTargetTransfer,TensorProduct.map_tmul,localizeTensor,LinearMap.coe_mk,AddHom.coe_mk, + tensorValue_tmul,map_mul] + exact congrArg₂ (· * ·) + (renameInjFraction_algebraMap Sum.inl Sum.inl_injective _) + (renameInjFraction_algebraMap Sum.inr Sum.inr_injective _) + | add f g hf hg => + rw [(fourValue d₁ e₁ d₂ e₂).map_add, + (doubleTensorShuffle a d₁ e₁ d₂ e₂).map_add, + (twoTargetTransfer a d₁ e₁ d₂ e₂).map_add, + (localizeTensor (d₁+e₁) (d₂+e₂)).map_add,hf,hg] + +lemma doubleTensorShuffle_invariant (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (p : MvPolynomial (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) ℚ) + (hp : ∀ σ, rename (sumAction (cellAction d₁ e₁) (cellAction d₂ e₂) σ) p = p) : + doubleTensorShuffle a d₁ e₁ d₂ e₂ p = + localizeTensor (d₁+e₁) (d₂+e₂) (cellTransfer a d₁ e₁ d₂ e₂ p) := by + change _ = localizeTensor _ _ (twoTargetTransfer _ _ _ _ _ (separateFour _ _ _ _ p)) + rw [← doubleTensorShuffle_fourValue, fourValue_separateFour d₁ e₁ d₂ e₂ p hp] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/Centers.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/Centers.lean new file mode 100644 index 0000000000000000000000000000000000000000..283b2bd90c5aacf565a47351ebde5999f2271c9a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/Centers.lean @@ -0,0 +1,229 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Regroup + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma extendPolynomial_comp {A B C α β γ : Type*} [CommRing A] [CommRing B] [CommRing C] + [Algebra ℚ A] [Algebra ℚ B] [Algebra ℚ C] + (f : A →ₐ[ℚ] B) (g : B →ₐ[ℚ] C) (j : α → β) (k : β → γ) (p : MvPolynomial α A) : + extendPolynomial g k (extendPolynomial f j p)=extendPolynomial (g.comp f) (k∘j) p := by + simp only [extendPolynomial,AlgHom.comp_apply,AlgHom.restrictScalars_apply,mapAlgHom_apply, + map_rename,rename_rename,map_map] + rfl + +namespace Regroup +noncomputable def centers {T U : SplitTree I} : Regroup T U → T.Centers ≃ U.Centers + | .refl _ => Equiv.refl _ + | .assoc _ _ _ => Equiv.sumAssoc _ _ _ + | .swap _ _ => Equiv.sumComm _ _ + | .node f g => Equiv.sumCongr f.centers g.centers + | .trans f g => f.centers.trans g.centers + +omit [Fintype I] [DecidableEq I] in +lemma centerTranslation_natural (A : (I → ℕ) → CommAlgCat.{u} ℚ) + (τ : ∀ d,A d →ₐ[ℚ] Polynomial (A d)) {T U : SplitTree I} + (e : Regroup T U) (x : tensor A T) : + centerTranslation A τ U (e.equivalence A x)= + extendPolynomial (e.equivalence A).toAlgHom e.centers (centerTranslation A τ T x) := by + induction e with + | refl T => + change centerTranslation A τ T x= + rename id (map (RingHom.id _) (centerTranslation A τ T x)) + simp only [map_id,rename_id,AlgHom.id_apply] + | assoc T U V => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x z => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [TensorProduct.add_tmul,map_add,hx,hy] + | tmul x y => + change centerTranslation A τ (.node T (.node U V)) (x ⊗ₜ[ℚ] (y ⊗ₜ[ℚ] z))=_ + rw [centerTranslation_tmul A τ T (.node U V),centerTranslation_tmul A τ U V, + centerTranslation_tmul A τ (.node T U) V,centerTranslation_tmul A τ T U] + simp only [map_mul,extendPolynomial_comp] + rw [mul_assoc] + congr 1 + | swap T U => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => + change centerTranslation A τ (.node U T) (y ⊗ₜ[ℚ] x)=_ + rw [centerTranslation_tmul A τ U T,centerTranslation_tmul A τ T U,map_mul, + extendPolynomial_comp,extendPolynomial_comp,mul_comm] + congr 1 + | node e g ihe ihg => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => + change centerTranslation A τ (.node _ _) (e.equivalence A x ⊗ₜ[ℚ] g.equivalence A y)=_ + rw [centerTranslation_tmul,ihe,ihg,centerTranslation_tmul,map_mul, + extendPolynomial_comp,extendPolynomial_comp,extendPolynomial_comp,extendPolynomial_comp] + congr 1 <;> congr 2 <;> apply AlgHom.ext <;> intro t + · change e.equivalence A t ⊗ₜ[ℚ] (1 : tensor A _) = + e.equivalence A t ⊗ₜ[ℚ] g.equivalence A 1 + rw [map_one] + · change (1 : tensor A _) ⊗ₜ[ℚ] g.equivalence A t = + e.equivalence A 1 ⊗ₜ[ℚ] g.equivalence A t + rw [map_one] + | trans e g ihe ihg => + change centerTranslation A τ _ (g.equivalence A (e.equivalence A x))=_ + rw [ihg,ihe,extendPolynomial_comp] + rfl + +end Regroup +end ElementaryPositivity.RawShuffle.SplitTree + +namespace ElementaryPositivity.RawShuffle.SplitTree.Regroup +open MvPolynomial +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma centeredRestrictionB_natural (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 Equiv.refl _ + | .assoc _ _ _ => Equiv.prodAssoc _ _ _ + | .swap _ _ => Equiv.prodComm _ _ + | .node f g => Equiv.prodCongr f.degrees g.degrees + | .trans f g => f.degrees.trans g.degrees + +omit [Fintype I] [DecidableEq I] in +lemma totalDegree {T U : SplitTree I} (e : Regroup T U) (k : T.Degrees) : + U.totalDegree (e.degrees k)=T.totalDegree k := by + induction e with + | refl T => rfl + | assoc T U V => exact (add_assoc _ _ _).symm + | swap T U => exact add_comm _ _ + | node e f ihe ihf => exact congrArg₂ (·+·) (ihe k.1) (ihf k.2) + | trans e f ihe ihf => exact (ihf (e.degrees k)).trans (ihe k) + +omit [DecidableEq I] in +lemma doubleShift (a : I → I → ℕ) {T U : SplitTree I} (e : Regroup T U) : + U.doubleShift a=T.doubleShift a := by + induction e with + | refl T => rfl + | assoc T U V => exact (add_assoc _ _ _).symm + | swap T U => exact add_comm _ _ + | node e f ihe ihf => exact congrArg₂ (·+·) ihe ihf + | trans e f ihe ihf => exact ihf.trans ihe + +omit [DecidableEq I] in +lemma onSlope (c η : I → ℝ) (θ : ℝ) {T U : SplitTree I} (e : Regroup T U) : + T.OnSlope c η θ → U.OnSlope c η θ := by + induction e with + | refl T => exact id + | assoc T U V => exact fun h=>⟨h.1.1,h.1.2,h.2⟩ + | swap T U => exact fun h=>⟨h.2,h.1⟩ + | node e f ihe ihf => exact fun h=>⟨ihe h.1,ihf h.2⟩ + | trans e f ihe ihf => exact ihf∘ihe + +lemma componentTensor_natural (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {T U : SplitTree I} (e : Regroup T U) (k : T.Degrees) + (x : tensor (quotientFamily a μ) T) : + e.equivalence (quotientFamily a μ) (componentTensor a μ T k x)= + componentTensor a μ U (e.degrees k) (e.equivalence (quotientFamily a μ) x) := by + induction e with + | refl T => rfl + | assoc T U V => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x z => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [TensorProduct.add_tmul,map_add,hx,hy] + | tmul x y => rfl + | swap T U => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => rfl + | node e g ihe ihg => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => + change e.equivalence (quotientFamily a μ) (componentTensor a μ _ k.1 x) ⊗ₜ[ℚ] + g.equivalence (quotientFamily a μ) (componentTensor a μ _ k.2 y)= + componentTensor a μ _ (e.degrees k.1) (e.equivalence (quotientFamily a μ) x) ⊗ₜ[ℚ] + componentTensor a μ _ (g.degrees k.2) (g.equivalence (quotientFamily a μ) y) + rw [ihe,ihg] + | trans e g ihe ihg => + change g.equivalence (quotientFamily a μ) + (e.equivalence (quotientFamily a μ) (componentTensor a μ _ k x))=_ + rw [ihe,ihg] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma append_ordered (T : SplitTree I) (hT : T.IsOrderedList) + (U : SplitTree I) (hU : U.IsOrderedList) : + ∃ V : SplitTree I,V.IsOrderedList ∧ Nonempty (Regroup (.node T U) V) := by + induction T with + | leaf d => exact ⟨.node (.leaf d) U,hU,⟨.refl _⟩⟩ + | node l r ihl ihr => + cases l with + | node l₁ l₂ => exact False.elim hT + | leaf d => + obtain ⟨V,hV,⟨e⟩⟩ := ihr hT + exact ⟨.node (.leaf d) V,hV,⟨(Regroup.assoc _ _ _).trans (.node (.refl _) e)⟩⟩ + +omit [Fintype I] [DecidableEq I] in +lemma ordered_normalization (T : SplitTree I) : + ∃ U : SplitTree I,U.IsOrderedList ∧ Nonempty (Regroup T U) := by + induction T with + | leaf d => exact ⟨.leaf d,True.intro,⟨.refl _⟩⟩ + | node l r ihl ihr => + obtain ⟨L,hL,⟨e⟩⟩ := ihl + obtain ⟨R,hR,⟨f⟩⟩ := ihr + obtain ⟨V,hV,⟨g⟩⟩ := append_ordered L hL R hR + exact ⟨V,hV,⟨(Regroup.node e f).trans g⟩⟩ + +end Regroup +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/ClearedSeparationB.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/ClearedSeparationB.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c37b8fb80566522dc109dc9978eff614e6d1746 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/ClearedSeparationB.lean @@ -0,0 +1,121 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.TensorColumnSeriesFiltration +import OAI.Combinatorics.Chromatic.GradedAlgebra.ClearedSeparation + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.SlopeArithmetic +open SeparationInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +noncomputable local instance clearBTensorS (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance clearBTensorSA (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance clearBTensorB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + CommRing (B a μ d⊗[ℚ]B a μ e) := inferInstance +noncomputable local instance clearBTensorBA (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Algebra ℚ (B a μ d⊗[ℚ]B a μ e) := inferInstance + +noncomputable def clearedSeparationB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + B a μ d⊗[ℚ]B a μ e →ₗ[ℚ] LaurentSeries (B a μ d⊗[ℚ]B a μ e) := + (mulPolynomial (mixedInverseKernelUnit a a μ d e * + (mixedInverseKernelUnit a (fun _ _ : I=>0) μ d e)⁻¹).val).comp + (relativeTaylorB a μ d e).toLinearMap + +lemma mapRing_ratio_val {R T : Type*} [CommRing R] [CommRing T] + (f : R →+* T) (u v : (LaurentSeries R)ˣ) : + mapRing f (u*v⁻¹).val= + (Units.map (mapRing f).toMonoidHom u*(Units.map (mapRing f).toMonoidHom v)⁻¹).val := by + rw [Units.val_mul,map_mul] + rfl + +lemma clearedSeparationB_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (x : S d⊗[ℚ]S e) : + clearedSeparationB a μ d e (quotientTensor a μ d e x)= + mapRing (quotientTensor a μ d e).toRingHom + ((inverseKernelUnit a d e*(inverseKernelUnit (fun _ _ : I=>0) d e)⁻¹).val * + polynomial (relativeTaylor d e x)) := by + rw [mapRing_mul_polynomial,mapRing_ratio_val,relativeTaylor_quotient] + rfl + +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] +lemma unitalSeparationSeries_shuffle_grid (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,00) d e).val= + ∏ i,∏ x : Fin (d i),∏ y : Fin (e i), + (affineUnit (X (Sum.inr ⟨i,y⟩)-X (Sum.inl ⟨i,x⟩) : MvPolynomial (CellVars d e) ℚ)).val := by + have h : SeparationInfinity.rawInverseKernelUnit (fun _ _ : I=>0) d e= + rectangular (fun i j : I=>if i=j then 1 else 0) + (fun i j x y=>affineUnit (X (Sum.inr ⟨j,y⟩)-X (Sum.inl ⟨i,x⟩) : MvPolynomial (CellVars d e) ℚ)) := by + simp only [SeparationInfinity.rawInverseKernelUnit,SeparationInfinity.rawFactor, + SeparationInfinity.inverseExponent,Nat.cast_zero,sub_zero,rectangular] + rw [h,rectangular_diagonal] + simp only [Units.coe_prod] + +lemma polynomial_crossDifference (d e : I → ℕ) : + polynomial (relativeRaw d e (crossDifference d e))= + crossSign d e • (SeparationInfinity.rawInverseKernelUnit (fun _ _ : I=>0) d e).val := by + rw [relativeRaw_crossDifference,rawInverseKernel_zero] + rw [rat_smul_series] + simp only [map_prod,crossSign,←Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i hi + apply Finset.prod_congr rfl + intro x hx + apply Finset.prod_congr rfl + intro y hy + simp only [map_add,polynomial_X,polynomial_C,affineUnit_val,map_neg,map_one,neg_one_mul] + simp only [map_sub] + ring + +lemma polynomial_crossTensor (d e : I → ℕ) : + polynomial (relativeTaylor d e (crossTensor d e))= + crossSign d e • (SeparationInfinity.inverseKernelUnit (fun _ _ : I=>0) d e).val := by + apply SeparationInfinity.realize_injective d e + rw [polynomial_map,map_relativeTaylor,tensorValue_crossTensor] + rw [mapRing_rat_smul, + SeparationInfinity.realize_inverseKernelUnit,polynomial_crossDifference] + +omit [DecidableEq I] in +lemma crossSign_sq (d e : I → ℕ) : crossSign d e * crossSign d e=1 := by + rw [crossSign,←Finset.prod_mul_distrib] + simp only [←Finset.prod_mul_distrib,neg_mul_neg,one_mul,Finset.prod_const_one] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/ColumnTaylor.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/ColumnTaylor.lean new file mode 100644 index 0000000000000000000000000000000000000000..e31ea948a0ab1c4d8a4e1862485f09dfc26d7169 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/ColumnTaylor.lean @@ -0,0 +1,139 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.LaurentLinearNaturality +import OAI.Combinatorics.Chromatic.Shuffle.ShuffleProjection +import OAI.Combinatorics.Chromatic.Shuffle.FourColumns + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.CommonTranslation +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +noncomputable local instance colTaylorTensorRing (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance colTaylorTensorAlg (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance colTaylorFourRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance +noncomputable local instance colTaylorFourAlg (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance + +omit [Fintype I] [DecidableEq I] in +lemma translationS_one (d : I → ℕ) (t : ℚ) : translationS d t (1 : S d)=1 := by + apply Subtype.ext + exact map_one (translation t) + +omit [Fintype I] [DecidableEq I] in +lemma firstColumn_relativeTaylor (d₁ e₁ d₂ e₂ : I → ℕ) (x : S d₁⊗[ℚ]S d₂) : + Polynomial.map (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom (relativeTaylor d₁ d₂ x)= + fourRelativeTaylor d₁ e₁ d₂ e₂ (firstColumnAlg d₁ e₁ d₂ e₂ x) := by + apply polynomial_eq_of_rat_evals + intro t + rw [eval_map_rat,relativeTaylor_eval,fourRelativeTaylor_eval] + have h : (firstColumnAlg d₁ e₁ d₂ e₂).toLinearMap ∘ₗ + TensorProduct.map (translationS d₁ t) LinearMap.id= + TensorProduct.map (TensorProduct.map (translationS d₁ t) (translationS e₁ t)) LinearMap.id ∘ₗ + (firstColumnAlg d₁ e₁ d₂ e₂).toLinearMap := by + apply TensorProduct.ext' + intro u v + change ((translationS d₁ t u)⊗ₜ[ℚ](1 : S e₁))⊗ₜ[ℚ](v⊗ₜ[ℚ](1 : S e₂))= + ((translationS d₁ t u)⊗ₜ[ℚ](translationS e₁ t 1))⊗ₜ[ℚ](v⊗ₜ[ℚ](1 : S e₂)) + rw [translationS_one] + exact LinearMap.congr_fun h x + +omit [Fintype I] [DecidableEq I] in +lemma secondColumn_relativeTaylor (d₁ e₁ d₂ e₂ : I → ℕ) (x : S e₁⊗[ℚ]S e₂) : + Polynomial.map (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom (relativeTaylor e₁ e₂ x)= + fourRelativeTaylor d₁ e₁ d₂ e₂ (secondColumnAlg d₁ e₁ d₂ e₂ x) := by + apply polynomial_eq_of_rat_evals + intro t + rw [eval_map_rat,relativeTaylor_eval,fourRelativeTaylor_eval] + have h : (secondColumnAlg d₁ e₁ d₂ e₂).toLinearMap ∘ₗ + TensorProduct.map (translationS e₁ t) LinearMap.id= + TensorProduct.map (TensorProduct.map (translationS d₁ t) (translationS e₁ t)) LinearMap.id ∘ₗ + (secondColumnAlg d₁ e₁ d₂ e₂).toLinearMap := by + apply TensorProduct.ext' + intro u v + change ((1 : S d₁)⊗ₜ[ℚ](translationS e₁ t u))⊗ₜ[ℚ]((1 : S d₂)⊗ₜ[ℚ]v)= + ((translationS d₁ t 1)⊗ₜ[ℚ](translationS e₁ t u))⊗ₜ[ℚ]((1 : S d₂)⊗ₜ[ℚ]v) + rw [translationS_one] + exact LinearMap.congr_fun h x + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.CommonTranslation ElementaryPositivity.LaurentAtInfinity +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable local instance naturalTaylorTensorRing (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance naturalTaylorTensorAlg (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance naturalTaylorFourRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance +noncomputable local instance naturalTaylorFourAlg (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance + +lemma restrictRows_relativeTaylor {d₁ e₁ d₂ e₂ : I → ℕ} + (A : Cut d₁ e₁) (B : Cut d₂ e₂) (x : S (d₁+e₁)⊗[ℚ]S (d₂+e₂)) : + Polynomial.map (restrictRows d₁ e₁ d₂ e₂ A B).toRingHom + (relativeTaylor (d₁+e₁) (d₂+e₂) x)= + fourRelativeTaylor d₁ e₁ d₂ e₂ (restrictRows d₁ e₁ d₂ e₂ A B x) := by + apply polynomial_eq_of_rat_evals + intro t + rw [eval_map_rat,relativeTaylor_eval,fourRelativeTaylor_eval] + have h : (restrictRows d₁ e₁ d₂ e₂ A B).toLinearMap ∘ₗ + TensorProduct.map (translationS (d₁+e₁) t) LinearMap.id= + TensorProduct.map (TensorProduct.map (translationS d₁ t) (translationS e₁ t)) LinearMap.id ∘ₗ + (restrictRows d₁ e₁ d₂ e₂ A B).toLinearMap := by + apply TensorProduct.ext' + intro u v + change restrictTensor A (translationS (d₁+e₁) t u)⊗ₜ[ℚ]restrictTensor B v= + TensorProduct.map (translationS d₁ t) (translationS e₁ t) (restrictTensor A u)⊗ₜ[ℚ]restrictTensor B v + rw [restrictTensor_translation] + exact LinearMap.congr_fun h x + +lemma shuffleTensor_translation (a : I → I → ℕ) (d e : I → ℕ) (t : ℚ) + (x : S d⊗[ℚ]S e) : + shuffleTensorLinear a d e (TensorProduct.map (translationS d t) (translationS e t) x)= + translationS (d+e) t (shuffleTensorLinear a d e x) := by + have h : shuffleTensorLinear a d e ∘ₗ TensorProduct.map (translationS d t) (translationS e t)= + translationS (d+e) t ∘ₗ shuffleTensorLinear a d e := by + apply TensorProduct.ext' + intro u v + simp only [LinearMap.comp_apply,TensorProduct.map_tmul,shuffleTensorLinear_tmul] + exact (translation_shufflePolynomial a t u v).symm + exact LinearMap.congr_fun h x + +lemma twoTarget_relativeTaylor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (x : (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) : + polynomialMapLinear (twoTargetTransfer a d₁ e₁ d₂ e₂) (fourRelativeTaylor d₁ e₁ d₂ e₂ x)= + relativeTaylor (d₁+e₁) (d₂+e₂) (twoTargetTransfer a d₁ e₁ d₂ e₂ x) := by + apply polynomial_eq_of_rat_evals + intro t + rw [polynomialMapLinear_eval_rat,fourRelativeTaylor_eval,relativeTaylor_eval] + have h : twoTargetTransfer a d₁ e₁ d₂ e₂ ∘ₗ + TensorProduct.map (TensorProduct.map (translationS d₁ t) (translationS e₁ t)) LinearMap.id= + TensorProduct.map (translationS (d₁+e₁) t) LinearMap.id ∘ₗ + twoTargetTransfer a d₁ e₁ d₂ e₂ := by + apply TensorProduct.ext' + intro u v + change shuffleTensorLinear a d₁ e₁ (TensorProduct.map (translationS d₁ t) (translationS e₁ t) u)⊗ₜ[ℚ] + shuffleTensorLinear a d₂ e₂ v= + translationS (d₁+e₁) t (shuffleTensorLinear a d₁ e₁ u)⊗ₜ[ℚ]shuffleTensorLinear a d₂ e₂ v + rw [shuffleTensor_translation] + exact LinearMap.congr_fun h x + +lemma twoTarget_polynomial_relativeTaylor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (x : (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) : + mapLinear (twoTargetTransfer a d₁ e₁ d₂ e₂) (polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ x))= + polynomial (relativeTaylor (d₁+e₁) (d₂+e₂) (twoTargetTransfer a d₁ e₁ d₂ e₂ x)) := by + rw [polynomial_mapLinear,twoTarget_relativeTaylor] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/ComponentB.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/ComponentB.lean new file mode 100644 index 0000000000000000000000000000000000000000..7afcc86808383b1abe1dfe74f5a9b6adb7093684 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/ComponentB.lean @@ -0,0 +1,222 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.RestrictionB +import OAI.Combinatorics.Chromatic.Shuffle.EulerForm + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.Homogeneity +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def componentB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k : ℤ) : B a μ d →ₗ[ℚ] B a μ d := + (destabilizingSpace a μ d).mapQ (destabilizingSpace a μ d) (componentS d k) + (fun f hf=>componentS_destabilizing_mem a μ d k f hf) + +@[simp] lemma componentB_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k : ℤ) (f : S d) : + componentB a μ d k ((destabilizingSpace a μ d).mkQ f) = + (destabilizingSpace a μ d).mkQ (componentS d k f) := rfl + +omit [Fintype I] [DecidableEq I] in +lemma componentS_componentS (d : I → ℕ) (k l : ℤ) (f : S d) : + componentS d k (componentS d l f) = if k=l then componentS d l f else 0 := + componentS_of_homogeneous _ _ (componentS_homogeneous _ _ _) _ + +lemma componentB_componentB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k l : ℤ) (f : B a μ d) : + componentB a μ d k (componentB a μ d l f) = + if k=l then componentB a μ d l f else 0 := by + induction f using Submodule.Quotient.induction_on with + | H f => + change (destabilizingSpace a μ d).mkQ (componentS d k (componentS d l f)) = + if k=l then (destabilizingSpace a μ d).mkQ (componentS d l f) else 0 + rw [componentS_componentS] + split_ifs <;> simp + +@[simp] lemma componentB_idempotent (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k : ℤ) (f : B a μ d) : + componentB a μ d k (componentB a μ d k f) = componentB a μ d k f := by + rw [componentB_componentB,ite_eq_left rfl] + +lemma componentB_negative (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k : ℤ) (hk : k<0) (f : B a μ d) : componentB a μ d k f = 0 := by + induction f using Submodule.Quotient.induction_on with + | H f => + change (destabilizingSpace a μ d).mkQ (componentS d k f) = 0 + have hs : componentS d k f=0 := Subtype.ext + (homogeneous_negative_eq_zero _ (componentS_homogeneous d k f) hk) + rw [hs,map_zero] + +theorem componentB_finite_decomposition (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (f : B a μ d) : + ∃ s : Finset ℤ, (∀ k∉s,componentB a μ d k f=0) ∧ + (∑ k ∈ s,componentB a μ d k f)=f := by + classical + induction f using Submodule.Quotient.induction_on with + | H f => + refine ⟨degreeSet f.val,?_,?_⟩ + · intro k hk + change (destabilizingSpace a μ d).mkQ (componentS d k f) = 0 + have hs : componentS d k f=0 := by + apply Subtype.ext + apply weightedHomogeneousComponent_eq_zero' + intro x hx + exact fun h=>hk (Finset.mem_image.mpr ⟨x,hx,h⟩) + rw [hs,map_zero] + · change (∑ k ∈ degreeSet f.val,(destabilizingSpace a μ d).mkQ (componentS d k f)) = + (destabilizingSpace a μ d).mkQ f + rw [← map_sum,sum_componentS] + +noncomputable def gradeB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k : ℤ) : Submodule ℚ (B a μ d) := LinearMap.range (componentB a μ d k) + +lemma mem_gradeB_iff (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k : ℤ) (f : B a μ d) : + f ∈ gradeB a μ d k ↔ componentB a μ d k f=f := by + constructor + · rintro ⟨g,rfl⟩ + exact componentB_idempotent a μ d k g + · intro h + exact ⟨f,h⟩ + +lemma componentB_on_grade (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k l : ℤ) (f : B a μ d) (hf : f∈gradeB a μ d l) : + componentB a μ d k f = if k=l then f else 0 := by + obtain ⟨g,rfl⟩ := hf + exact componentB_componentB a μ d k l g + +theorem gradeB_finite_independent (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (s : Finset ℤ) (f : ℤ → B a μ d) + (hf : ∀ k∈s,f k∈gradeB a μ d k) (hz : ∑ k ∈ s,f k=0) : + ∀ k∈s,f k=0 := by + classical + intro k hk + have h := congrArg (componentB a μ d k) hz + rw [map_sum,map_zero] at h + have heq : ∑ l ∈ s,componentB a μ d k (f l) = f k := by + rw [Finset.sum_eq_single k] + · exact (mem_gradeB_iff a μ d k _).mp (hf k hk) + · intro l hl hlk + rw [componentB_on_grade a μ d k l _ (hf l hl),ite_eq_right (Ne.symm hlk)] + · exact fun hn=>(hn hk).elim + rwa [heq] at h + +end ElementaryPositivity.RawShuffle +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma dimensionCast_trans {d e b : I → ℕ} (h : d=e) (j : e=b) (f : S d) : + dimensionCast j (dimensionCast h f) = dimensionCast (h.trans j) f := by + subst e; subst b; rfl + +lemma shuffle_assoc_cast (a : I → I → ℕ) {d e b : I → ℕ} + (f : S d) (g : S e) (h : S b) : + dimensionCast (add_assoc d e b) (shufflePolynomial a (shufflePolynomial a f g) h) = + shufflePolynomial a f (shufflePolynomial a g h) := by + rw [dimensionCast_eq_castS] + exact shufflePolynomial_assoc a f g h + +lemma shuffle_assoc_cast_symm (a : I → I → ℕ) {d e b : I → ℕ} + (f : S d) (g : S e) (h : S b) : + shufflePolynomial a (shufflePolynomial a f g) h = + dimensionCast (add_assoc d e b).symm (shufflePolynomial a f (shufflePolynomial a g h)) := by + rw [← shuffle_assoc_cast,dimensionCast_trans] + rfl + +@[simp] lemma shufflePolynomial_zero_left (a : I → I → ℕ) (d e : I → ℕ) (g : S e) : + shufflePolynomial a (0 : S d) g = 0 := by + exact LinearMap.congr_fun (map_zero (shuffleLinear a d e)) g +@[simp] lemma shufflePolynomial_zero_right (a : I → I → ℕ) (d e : I → ℕ) (f : S d) : + shufflePolynomial a f (0 : S e) = 0 := (shuffleLinear a d e f).map_zero + +lemma destabilizing_shuffle_left (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + obtain ⟨u,v,h,f₁,g',hu,hv,hμ,rfl⟩ := hF + subst d + refine Submodule.subset_span ⟨u,v+e,(add_assoc u v e).symm,f₁, + shufflePolynomial a g' g,hu,add_ne_zero_left v e hv,?_,?_⟩ + · rw [slope_add_same c η hc hs] + exact hμ + · exact shuffle_assoc_cast_symm a f₁ g' g + | zero => simp + | add f f' hf hf' ih ih' => + simpa only [shufflePolynomial_add_left] using + (destabilizingSpace a (slope c η) (d+e)).add_mem ih ih' + | smul r f hf ih => + simpa only [shufflePolynomial_smul_left] using + (destabilizingSpace a (slope c η) (d+e)).smul_mem r ih + +lemma destabilizing_shuffle_right (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + obtain ⟨u,v,h,g',h',hu,hv,hμ,rfl⟩ := hg + subst e + refine Submodule.subset_span ⟨d+u,v,add_assoc d u v, + shufflePolynomial a f g',h',add_ne_zero_right d u hu,hv,?_,?_⟩ + · rw [slope_add_same c η hc hs] + apply slope_add_gt c η hc hu (mass_eq c η hc d) + rwa [hs] + · exact (shuffle_assoc_cast a f g' h').symm + | zero => simp + | add g g' hg hg' ih ih' => + simpa only [shufflePolynomial_add_right] using + (destabilizingSpace a (slope c η) (d+e)).add_mem ih ih' + | smul r g hg ih => + simpa only [shufflePolynomial_smul_right] using + (destabilizingSpace a (slope c η) (d+e)).smul_mem r ih + +noncomputable def shuffleB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 (destabilizingSpace a (slope c η) e).mapQ J + (shuffleLinear a d e f) (by + intro g hg + exact destabilizing_shuffle_right a c η hc hs f hg) + map_add' := by + intro f g + apply LinearMap.ext + intro x + induction x using Submodule.Quotient.induction_on with + | H x => exact congrArg J.mkQ (shufflePolynomial_add_left a f g x) + map_smul' := by + intro r f + apply LinearMap.ext + intro x + induction x using Submodule.Quotient.induction_on with + | H x => exact congrArg J.mkQ (shufflePolynomial_smul_left a r f x) } + exact (destabilizingSpace a (slope c η) d).liftQ L (by + intro f hf + apply LinearMap.mem_ker.mpr + apply LinearMap.ext + intro g + induction g using Submodule.Quotient.induction_on with + | H g => + exact (Submodule.Quotient.mk_eq_zero _).mpr + (destabilizing_shuffle_left a c η hc hs hf g)) + +@[simp] lemma shuffleB_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0separationCoefficient_filtration a c η hc θ d e hs w 0) (fun _ _ h=>h) W x hx + +noncomputable def tensorSeparationLeft (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0tensorSeparationLeft_filtration a c η hc θ d e f hs W x.val x.property) + +namespace SplitTree +open MvPolynomial ElementaryPositivity.CenterCalculus + +lemma normalizedTripleSymbol_tmul_eq (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,01) (fun _=>0)) + (totalLeadingPolynomial a c η hc θ (.node L R) ⟨hL,hR⟩ W f)) = polynomial p := by + obtain ⟨q,hq⟩:=totalLeadingPolynomial_denominator_divisible a c η hc θ (.node L R) ⟨hL,hR⟩ + W f hf (crossPairs L R) (crossPairs_ne L R) (crossPairs_norev L R) + (crossPairs_symmetric a c η θ hχ L R hL hR) + refine ⟨(crossPolynomial a L R v w Int.toNat).map + (algebraMap ℚ (tensor (quotientFamily a (SlopeArithmetic.slope c η)) (.node L R))) * + lineSpecialization (Sum.elim v w) (Sum.elim (fun _=>1) (fun _=>0)) q, ?_⟩ + rw [hq,map_mul,lineSpecialization_map_algebra,centerDenominator_crossPairs_line, + map_mul,←polynomial_map,←mul_assoc,←map_mul,scalarCrossKernel_denominator, + polynomial_map,map_mul] + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossDifference.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossDifference.lean new file mode 100644 index 0000000000000000000000000000000000000000..9298a718d96d044d1679c276b4f927d569c46f61 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossDifference.lean @@ -0,0 +1,158 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.QuotientAlg + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.SeparatedSymmetry +open ElementaryPositivity.CommonTranslation +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def crossDifference (d e : I → ℕ) : + MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ := + ∏ i, ∏ x : Fin (d i), ∏ y : Fin (e i), + (X (Sum.inl ⟨i,x⟩) - X (Sum.inr ⟨i,y⟩)) + +lemma prod_sub_perm {α β R : Type*} [Fintype α] [Fintype β] [CommRing R] + (σ : Equiv.Perm α) (τ : Equiv.Perm β) (l : α → R) (r : β → R) : + (∏ x : α, (∏ y : β, (l (σ x) - r (τ y)))) = ∏ x : α, (∏ y : β, (l x - r y)) := by + calc + _ = ∏ x : α, (∏ y : β, (l (σ x) - r y)) := by + apply Finset.prod_congr rfl + intro x hx + exact Equiv.prod_comp τ (fun y => l (σ x) - r y) + _ = _ := Equiv.prod_comp σ (fun x => ∏ y : β, (l x - r y)) + +omit [DecidableEq I] in +lemma rename_crossDifference (d e : I → ℕ) + (h : ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) → ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i)))) : + rename h (crossDifference d e) = + ∏ i,∏ x : Fin (d i),∏ y : Fin (e i), (X (h (Sum.inl ⟨i,x⟩))-X (h (Sum.inr ⟨i,y⟩))) := by + simp only [crossDifference,map_prod,map_sub,rename_X] + +omit [DecidableEq I] in +lemma crossDifference_symmetric (d e : I → ℕ) (σ : (∀ i,Equiv.Perm (Fin (d i))) × + (∀ i,Equiv.Perm (Fin (e i)))) : + rename (sumAction (packAction (fun i=>Fin (d i))) (packAction (fun i=>Fin (e i))) σ) + (crossDifference d e) = crossDifference d e := by + refine (rename_crossDifference d e _).trans ?_ + exact Finset.prod_congr rfl (fun i hi => + prod_sub_perm (R := MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ) + (σ.1 i) (σ.2 i) (fun x => X (Sum.inl ⟨i,x⟩)) (fun y => X (Sum.inr ⟨i,y⟩))) + +noncomputable def crossTensor (d e : I → ℕ) : S d ⊗[ℚ] S e := + separateTensor d e (crossDifference d e) + +@[simp] lemma tensorValue_crossTensor (d e : I → ℕ) : + tensorValue d e (crossTensor d e) = crossDifference d e := + tensorValue_separateTensor d e _ (crossDifference_symmetric d e) + +noncomputable def relativeRaw (d e : I → ℕ) : + MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ →ₐ[ℚ] + Polynomial (MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ) := + aeval (Sum.elim (fun x => Polynomial.C (X (Sum.inl x)) + Polynomial.X) + (fun y => Polynomial.C (X (Sum.inr y)))) + +omit [Fintype I] [DecidableEq I] in +lemma relativeRaw_left (d e : I → ℕ) (f : MvPolynomial (Σi,Fin (d i)) ℚ) : + relativeRaw d e (rename Sum.inl f) = + Polynomial.map (rename (R:=ℚ) Sum.inl).toRingHom (taylor f) := by + induction f using MvPolynomial.induction_on with + | C r => simp [relativeRaw] + | add f g hf hg => simp only [map_add,Polynomial.map_add,hf,hg] + | mul_X f i hf => + simp only [map_mul,rename_X,taylor_X,Polynomial.map_mul,hf] + congr 1 + simp [relativeRaw] + +omit [Fintype I] [DecidableEq I] in +lemma relativeRaw_right (d e : I → ℕ) (f : MvPolynomial (Σi,Fin (e i)) ℚ) : + relativeRaw d e (rename Sum.inr f) = Polynomial.C (rename Sum.inr f) := by + induction f using MvPolynomial.induction_on with + | C r => simp [relativeRaw] + | add f g hf hg => simp only [map_add,hf,hg] + | mul_X f i hf => + simp only [map_mul,rename_X,hf] + congr 1 + simp [relativeRaw] + +omit [Fintype I] [DecidableEq I] in +lemma map_taylorS_left (d e : I → ℕ) (f : S d) : + Polynomial.map (tensorValueAlg d e).toRingHom + (Polynomial.map (Algebra.TensorProduct.includeLeft : S d →ₐ[ℚ] S d ⊗[ℚ] S e).toRingHom + (taylorS d f)) = + Polynomial.map (rename (R:=ℚ) Sum.inl).toRingHom (taylor f.val) := by + rw [← map_taylorS d f,Polynomial.map_map,Polynomial.map_map] + congr 1 + apply RingHom.ext + intro g + change tensorValue d e (g ⊗ₜ[ℚ] 1) = rename Sum.inl g.val + simp + +omit [Fintype I] [DecidableEq I] in +lemma map_relativeTaylor (d e : I → ℕ) (f : S d ⊗[ℚ] S e) : + Polynomial.map (tensorValueAlg d e).toRingHom (relativeTaylor d e f) = + relativeRaw d e (tensorValue d e f) := by + induction f using TensorProduct.inductionOn with + | tmul f g => + rw [relativeTaylor_tmul,Polynomial.map_mul,map_taylorS_left, + Polynomial.map_C,tensorValue_tmul,map_mul,relativeRaw_left,relativeRaw_right] + congr 1 + change Polynomial.C (tensorValue d e (1 ⊗ₜ[ℚ] g)) = _ + simp + | add f g hf hg => simp only [map_add,Polynomial.map_add,hf,hg] + +omit [DecidableEq I] in +lemma relativeRaw_crossDifference (d e : I → ℕ) : + relativeRaw d e (crossDifference d e) = + ∏ i, ∏ x : Fin (d i), ∏ y : Fin (e i), + (Polynomial.X + Polynomial.C (X (Sum.inl ⟨i,x⟩) - X (Sum.inr ⟨i,y⟩))) := by + simp only [crossDifference,map_prod,map_sub] + apply Finset.prod_congr rfl + intro i hi + apply Finset.prod_congr rfl + intro x hx + apply Finset.prod_congr rfl + intro y hy + simp [relativeRaw] + ring + +omit [DecidableEq I] in +lemma relativeRaw_crossDifference_monic (d e : I → ℕ) : + (relativeRaw d e (crossDifference d e)).Monic := by + rw [relativeRaw_crossDifference] + apply Polynomial.monic_prod_of_monic + intro i hi + apply Polynomial.monic_prod_of_monic + intro x hx + apply Polynomial.monic_prod_of_monic + intro y hy + exact Polynomial.monic_X_add_C _ + +lemma relativeTaylor_crossTensor_monic (d e : I → ℕ) : + (relativeTaylor d e (crossTensor d e)).Monic := by + apply Polynomial.monic_of_injective (f := (tensorValueAlg d e).toRingHom) (tensorValue_injective d e) + rw [map_relativeTaylor,tensorValue_crossTensor] + exact relativeRaw_crossDifference_monic d e + +noncomputable def crossClearing (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Polynomial (B a μ d ⊗[ℚ] B a μ e) := + Polynomial.map (quotientTensor a μ d e).toRingHom (relativeTaylor d e (crossTensor d e)) + +lemma crossClearing_monic (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + (crossClearing a μ d e).Monic := + (relativeTaylor_crossTensor_monic d e).map _ + +lemma crossClearing_cancel (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (f : Polynomial (B a μ d ⊗[ℚ] B a μ e)) : + crossClearing a μ d e * f = 0 ↔ f = 0 := + (crossClearing_monic a μ d e).mul_right_eq_zero_iff + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossKernelExplicit.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossKernelExplicit.lean new file mode 100644 index 0000000000000000000000000000000000000000..a645381baf90dc41ffe09779c9ca0a725c63fe57 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossKernelExplicit.lean @@ -0,0 +1,164 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNExpansion + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + +omit [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma sameDen_reverse_eq (s t : Pack (A:=A)) : + sameDen t s = (-1 : MvPolynomial (Σi,A i) ℚ) ^ (∑ i,(s i).card*(t i).card) * sameDen s t := by + unfold sameDen + calc + _ = ∏ i,∏ x∈s i,∏ y∈t i, + (-1 : MvPolynomial (Σi,A i) ℚ)*diagonal ⟨i,x⟩ ⟨i,y⟩ := by + apply Finset.prod_congr rfl + intro i hi + rw [Finset.prod_comm] + apply Finset.prod_congr rfl + intro x hx + apply Finset.prod_congr rfl + intro y hy + unfold diagonal + ring + _ = _ := by + simp only [Finset.prod_mul_distrib,Finset.prod_const,←pow_mul] + rw [Finset.prod_pow_eq_pow_sum] + congr 2 + apply Finset.sum_congr rfl + intro i hi + exact Nat.mul_comm _ _ + +omit [∀ i,Fintype (A i)] in +lemma crossKernelPolynomial_explicit (a : I → I → ℕ) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (q : PackConvolution.Cut (left p)) + (r : PackConvolution.Cut (right p)) : + crossKernelPolynomial a p q r = + (-1 : MvPolynomial (Σi,A i) ℚ) ^ (∑ i,(right q i).card*(left r i).card) * + sameDen (left q) (left r) * sameDen (right q) (right r) * + arrowNum a (left q) (right r) * arrowNum a (left r) (right q) := by + apply (IsFractionRing.injective (MvPolynomial (Σi,A i) ℚ) + (FractionRing (MvPolynomial (Σi,A i) ℚ))) + rw [←crossKernelPolynomial_spec,kernel_polynomial_ratio,kernel_polynomial_ratio] + have hq : (fun i=>left q i ∪ right q i)=left p := funext fun i=>(q i).property.2 + have hr : (fun i=>left r i ∪ right r i)=right p := funext fun i=>(r i).property.2 + have hd : sameDen (left p) (right p)= + sameDen (left q) (left r)*sameDen (left q) (right r)* + ((-1 : MvPolynomial (Σi,A i) ℚ) ^ (∑ i,(right q i).card*(left r i).card)* + sameDen (left r) (right q))*sameDen (right q) (right r) := by + conv_lhs => rw [←hq,←hr] + rw [sameDen_union_left (left q) (right q) (fun i=>left r i ∪ right r i) (fun i=>(q i).property.1), + sameDen_union_right (left q) (left r) (right r) (fun i=>(r i).property.1), + sameDen_union_right (right q) (left r) (right r) (fun i=>(r i).property.1)] + rw [sameDen_reverse_eq (left r) (right q)] + have he : (∑ i,(left r i).card*(right q i).card)=∑ i,(right q i).card*(left r i).card := by + apply Finset.sum_congr rfl + intro i hi + exact Nat.mul_comm _ _ + rw [he] + ring + have hne := crossDen_ne_zero p q r + have h₁ : algebraMap (MvPolynomial (Σi,A i) ℚ) (FractionRing (MvPolynomial (Σi,A i) ℚ)) + (sameDen (left q) (right r))≠0 := by + simpa only [map_zero] using + (IsFractionRing.injective (MvPolynomial (Σi,A i) ℚ) (FractionRing (MvPolynomial (Σi,A i) ℚ))).ne + (mul_ne_zero_iff.mp hne).1 + have h₂ : algebraMap (MvPolynomial (Σi,A i) ℚ) (FractionRing (MvPolynomial (Σi,A i) ℚ)) + (sameDen (left r) (right q))≠0 := by + simpa only [map_zero] using + (IsFractionRing.injective (MvPolynomial (Σi,A i) ℚ) (FractionRing (MvPolynomial (Σi,A i) ℚ))).ne + (mul_ne_zero_iff.mp hne).2 + rw [hd] + simp only [map_mul,map_pow,map_neg,map_one] + field_simp + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def fourForwardDifference (d₁ e₁ d₂ e₂ : I → ℕ) + (i j : I) (x : Fin (d₁ i)⊕Fin (e₁ i)) (y : Fin (d₂ j)⊕Fin (e₂ j)) : + MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ := + X (Sum.inr ((Equiv.sigmaSumDistrib _ _) ⟨j,y⟩)) - + X (Sum.inl ((Equiv.sigmaSumDistrib _ _) ⟨i,x⟩)) + +omit [DecidableEq I] in +lemma fourSameDen11 (d₁ e₁ d₂ e₂ : I → ℕ) : + rename (fourPackEquiv d₁ e₁ d₂ e₂) (sameDen (left (canonicalLeftCut d₁ e₁ d₂ e₂)) (left (canonicalRightCut d₁ e₁ d₂ e₂)))= + ∏ i,∏ x:Fin (d₁ i),∏ y:Fin (d₂ i),fourForwardDifference d₁ e₁ d₂ e₂ i i (.inl x) (.inl y) := by + simp only [sameDen,map_prod,canonicalLeftCut,canonicalRightCut,embedPackCut, + sumPackCut,left,right,Finset.prod_map,ShufflePolynomiality.diagonal,map_sub,rename_X] + rfl + +omit [DecidableEq I] in +lemma fourSameDen22 (d₁ e₁ d₂ e₂ : I → ℕ) : + rename (fourPackEquiv d₁ e₁ d₂ e₂) (sameDen (right (canonicalLeftCut d₁ e₁ d₂ e₂)) (right (canonicalRightCut d₁ e₁ d₂ e₂)))= + ∏ i,∏ x:Fin (e₁ i),∏ y:Fin (e₂ i),fourForwardDifference d₁ e₁ d₂ e₂ i i (.inr x) (.inr y) := by + simp only [sameDen,map_prod,canonicalLeftCut,canonicalRightCut,embedPackCut, + sumPackCut,left,right,Finset.prod_map,ShufflePolynomiality.diagonal,map_sub,rename_X] + rfl + +omit [DecidableEq I] in +lemma fourArrow12 (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + rename (fourPackEquiv d₁ e₁ d₂ e₂) (arrowNum a (left (canonicalLeftCut d₁ e₁ d₂ e₂)) (right (canonicalRightCut d₁ e₁ d₂ e₂)))= + ∏ i,∏ j,∏ x:Fin (d₁ i),∏ y:Fin (e₂ j),fourForwardDifference d₁ e₁ d₂ e₂ i j (.inl x) (.inr y)^a i j := by + simp only [arrowNum,map_prod,map_pow,canonicalLeftCut,canonicalRightCut,embedPackCut, + sumPackCut,left,right,Finset.prod_map,ShufflePolynomiality.diagonal,map_sub,rename_X] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma fourReverseDifference (d₁ e₁ d₂ e₂ : I → ℕ) (i j : I) + (x : Fin (d₂ i)) (y : Fin (e₁ j)) : + rename (fourPackEquiv d₁ e₁ d₂ e₂) + (ShufflePolynomiality.diagonal ⟨i,Sum.inr (Sum.inl x)⟩ ⟨j,Sum.inl (Sum.inr y)⟩)= + -fourForwardDifference d₁ e₁ d₂ e₂ j i (.inr y) (.inl x) := by + simp only [ShufflePolynomiality.diagonal,map_sub,rename_X] + unfold fourForwardDifference + rw [neg_sub] + rfl + +omit [DecidableEq I] in +lemma fourArrow21 (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + rename (fourPackEquiv d₁ e₁ d₂ e₂) (arrowNum a (left (canonicalRightCut d₁ e₁ d₂ e₂)) (right (canonicalLeftCut d₁ e₁ d₂ e₂)))= + ∏ i,∏ j,∏ x:Fin (d₂ i),∏ y:Fin (e₁ j),(-fourForwardDifference d₁ e₁ d₂ e₂ j i (.inr y) (.inl x))^a i j := by + simp only [arrowNum,map_prod,map_pow,canonicalLeftCut,canonicalRightCut,embedPackCut, + sumPackCut,left,right,Finset.prod_map] + apply Finset.prod_congr rfl + intro i hi + apply Finset.prod_congr rfl + intro j hj + apply Finset.prod_congr rfl + intro x hx + apply Finset.prod_congr rfl + intro y hy + congr 1 + exact fourReverseDifference d₁ e₁ d₂ e₂ i j x y + +lemma fourCrossPolynomial_explicit (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + fourCrossPolynomial a d₁ e₁ d₂ e₂ = + (-1 : MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ) ^ (∑ i,e₁ i*d₂ i) * + (∏ i,∏ x:Fin (d₁ i),∏ y:Fin (d₂ i),fourForwardDifference d₁ e₁ d₂ e₂ i i (.inl x) (.inl y)) * + (∏ i,∏ x:Fin (e₁ i),∏ y:Fin (e₂ i),fourForwardDifference d₁ e₁ d₂ e₂ i i (.inr x) (.inr y)) * + (∏ i,∏ j,∏ x:Fin (d₁ i),∏ y:Fin (e₂ j),fourForwardDifference d₁ e₁ d₂ e₂ i j (.inl x) (.inr y)^a i j) * + (∏ i,∏ j,∏ x:Fin (d₂ i),∏ y:Fin (e₁ j),(-fourForwardDifference d₁ e₁ d₂ e₂ j i (.inr y) (.inl x))^a i j) := by + rw [fourCrossPolynomial,crossKernelPolynomial_explicit] + simp only [map_mul,map_pow,map_neg,map_one,fourSameDen11,fourSameDen22,fourArrow12,fourArrow21] + congr 5 + simp only [canonicalLeftCut,canonicalRightCut,embedPackCut,sumPackCut,left,right, + Finset.card_map,Finset.card_univ,Fintype.card_fin] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossPolynomiality.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossPolynomiality.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b9053e8d71ffe5b445873bfb1c52ef2bf1af535 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossPolynomiality.lean @@ -0,0 +1,97 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.CrossScalar +import OAI.Combinatorics.Chromatic.Walls.CenterLineSpecialization +import OAI.Combinatorics.Chromatic.Shuffle.SymbolDetection +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentAffineCancellation + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open ElementaryPositivity.CenterCalculus ElementaryPositivity.ShufflePolynomiality +open ElementaryPositivity.LaurentAtInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +noncomputable def crossPairs (L R : SplitTree I) : Finset ((L.node R).Centers×(L.node R).Centers) := + Finset.univ.image (fun p : L.Centers×R.Centers=>(Sum.inl p.1,Sum.inr p.2)) + +omit [Fintype I] [DecidableEq I] in +lemma crossPairs_injective (L R : SplitTree I) : + Function.Injective (fun p : L.Centers×R.Centers=>((Sum.inl p.1,Sum.inr p.2) : (L.node R).Centers×(L.node R).Centers)) := by + intro p q h + exact Prod.ext (Sum.inl.inj (congrArg Prod.fst h)) (Sum.inr.inj (congrArg Prod.snd h)) + +omit [Fintype I] [DecidableEq I] in +lemma crossPairs_ne (L R : SplitTree I) (p : (L.node R).Centers×(L.node R).Centers) + (hp : p∈crossPairs L R) : p.1≠p.2 := by + obtain ⟨⟨x,y⟩,_,rfl⟩:=Finset.mem_image.mp hp + exact Sum.inl_ne_inr + +omit [Fintype I] [DecidableEq I] in +lemma crossPairs_norev (L R : SplitTree I) (p : (L.node R).Centers×(L.node R).Centers) + (hp : p∈crossPairs L R) : (p.2,p.1)∉crossPairs L R := by + obtain ⟨⟨x,y⟩,_,rfl⟩:=Finset.mem_image.mp hp + intro h + obtain ⟨⟨z,t⟩,_,h⟩:=Finset.mem_image.mp h + exact Sum.inl_ne_inr (congrArg Prod.fst h) + +omit [DecidableEq I] in +lemma crossPairs_symmetric (a : I → I → ℕ) (c η : I → ℝ) (θ : ℝ) + (hχ : SlopeEulerSymmetric a c η θ) (L R : SplitTree I) + (hL : L.OnSlope c η θ) (hR : R.OnSlope c η θ) + (p : (L.node R).Centers×(L.node R).Centers) (hp : p∈crossPairs L R) : + eulerForm a ((L.node R).leafDimension p.1) ((L.node R).leafDimension p.2)= + eulerForm a ((L.node R).leafDimension p.2) ((L.node R).leafDimension p.1) := by + obtain ⟨⟨x,y⟩,_,rfl⟩:=Finset.mem_image.mp hp + obtain ⟨hx,hsx⟩:=L.leafDimension_onSlope c η θ hL x + obtain ⟨hy,hsy⟩:=R.leafDimension_onSlope c η θ hR y + exact hχ _ _ hx hy hsx hsy + +noncomputable def crossPolynomial (a : I → I → ℕ) (L R : SplitTree I) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) (e : ℤ → ℕ) : Polynomial ℚ := + ∏ z : L.Centers,∏ t : R.Centers, + affinePolynomial (w t-v z) ^ e (eulerForm a (L.leafDimension z) (R.leafDimension t)) + +omit [DecidableEq I] in +lemma centerDenominator_crossPairs_line (a : I → I → ℕ) (L R : SplitTree I) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) : + lineSpecialization (Sum.elim v w) (Sum.elim (fun _=>1) (fun _=>0)) + (centerDenominator a (L.node R) (crossPairs L R))= + crossPolynomial a L R v w (fun e=>(-e).toNat) := by + classical + unfold centerDenominator crossPairs + rw [Finset.prod_image (fun p _ q _ h=>crossPairs_injective L R h)] + simp only [map_prod,map_pow] + rw [Fintype.prod_prod_type] + unfold crossPolynomial + apply Finset.prod_congr rfl + intro z hz + apply Finset.prod_congr rfl + intro t ht + congr 1 + simp only [diagonal,map_sub,lineSpecialization_X,Sum.elim_inl,Sum.elim_inr, + _root_.map_zero,_root_.map_one,zero_mul,one_mul,add_zero,Algebra.algebraMap_self_apply, + affinePolynomial] + ring + +omit [DecidableEq I] in +lemma scalarCrossKernel_denominator (a : I → I → ℕ) (L R : SplitTree I) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) : + (scalarCrossKernel a L R v w : LaurentSeries ℚ)* + polynomial (crossPolynomial a L R v w (fun e=>(-e).toNat))= + polynomial (crossPolynomial a L R v w Int.toNat) := by + unfold scalarCrossKernel crossPolynomial + simp only [map_prod,Units.coe_prod] + rw [←Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro z hz + rw [←Finset.prod_mul_distrib] + exact Finset.prod_congr rfl fun t ht=>affineUnit_zpow_cancel _ _ + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossScalar.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossScalar.lean new file mode 100644 index 0000000000000000000000000000000000000000..76489f11ddfe38d65068d5d555f2ea328b05262a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/CrossScalar.lean @@ -0,0 +1,140 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Histories.KernelEvaluation +import OAI.Combinatorics.Chromatic.Walls.EulerFiniteProduct + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open ElementaryPositivity.LaurentAtInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +lemma prod_packVariables {M : Type*} [CommMonoid M] (T : SplitTree I) + (f : T.Centers → I → M) : + (∏ i, ∏ x : Fin (T.dim i),f (T.centerOfVar (T.varEquiv.symm ⟨i,x⟩)) i)= + ∏ z : T.Centers,∏ i,∏ _x : Fin (T.leafDimension z i),f z i := by + classical + have h:=Equiv.prod_comp (T.varEquiv.symm.trans T.leafVarsEquiv) + (fun p : Σ z : T.Centers,Σ i,Fin (T.leafDimension z i)=>f p.1 p.2.1) + simpa only [Fintype.prod_sigma,Equiv.trans_apply,leafVarsEquiv_center, + leafVarsEquiv_pack,varEquiv_symm_packIndex] using h + +noncomputable def scalarCrossKernel (a : I → I → ℕ) (L R : SplitTree I) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) : (LaurentSeries ℚ)ˣ := + ∏ z : L.Centers, ∏ t : R.Centers, + affineUnit (w t-v z) ^ eulerForm a (L.leafDimension z) (R.leafDimension t) + +lemma packProduct_eq_scalarCrossKernel (a : I → I → ℕ) (L R : SplitTree I) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) : + (∏ i, ∏ j, ∏ x : Fin (L.dim i), ∏ y : Fin (R.dim j), + affineUnit (w (R.centerOfVar (R.varEquiv.symm ⟨j,y⟩))- + v (L.centerOfVar (L.varEquiv.symm ⟨i,x⟩))) ^ SeparationInfinity.inverseExponent a i j)= + scalarCrossKernel a L R v w := by + classical + conv_lhs => + arg 2 + ext i + rw [Finset.prod_comm] + rw [prod_packVariables L (fun z i=>∏ j,∏ y : Fin (R.dim j), + affineUnit (w (R.centerOfVar (R.varEquiv.symm ⟨j,y⟩))-v z) ^ SeparationInfinity.inverseExponent a i j)] + conv_lhs => + arg 2 + ext z + arg 2 + ext i + arg 2 + ext x + rw [prod_packVariables R (fun t j=>affineUnit (w t-v z)^SeparationInfinity.inverseExponent a i j)] + unfold scalarCrossKernel + apply Finset.prod_congr rfl + intro z hz + conv_lhs => + arg 2 + ext i + rw [Finset.prod_comm] + rw [Finset.prod_comm] + apply Finset.prod_congr rfl + intro t ht + conv_lhs => + arg 2 + ext i + rw [Finset.prod_comm] + exact ElementaryPositivity.inverseEuler_unit_product a (L.leafDimension z) (R.leafDimension t) _ +end ElementaryPositivity.RawShuffle.SplitTree + +namespace ElementaryPositivity.RawShuffle.SeparationInfinity +open ElementaryPositivity.LaurentAtInfinity SplitTree +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +lemma crossPointEval_inverseKernel_scalar (a : I → I → ℕ) (L R : SplitTree I) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) : + Units.map (mapRing (crossPointEval L R v w)).toMonoidHom + (rawInverseKernelUnit a L.dim R.dim)=scalarCrossKernel a L R v w := by + rw [crossPointEval_inverseKernel,packProduct_eq_scalarCrossKernel] +end ElementaryPositivity.RawShuffle.SeparationInfinity + +end +section +namespace ElementaryPositivity.CoefficientIdeals +open MvPolynomial +variable {R σ : Type*} [CommRing R] + +lemma map_quotient_eq_zero_iff (J : Ideal R) (p : MvPolynomial σ R) : + MvPolynomial.map (Ideal.Quotient.mk J) p=0 ↔ ∀ z,p.coeff z∈J := by + constructor + · intro hp z + have h:=congrArg (fun polynomial=>AddMonoidAlgebra.coeff polynomial z) hp + simpa only [coeff_map,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply, + Ideal.Quotient.eq_zero_iff_mem] using h + · intro hp + ext z + simpa only [coeff_map,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply, + Ideal.Quotient.eq_zero_iff_mem] using hp z + +lemma coeff_mul_mem (J : Ideal R) (p q : MvPolynomial σ R) + (hp : ∀ z,p.coeff z∈J) (z : σ →₀ ℕ) : (p*q).coeff z∈J := by + apply (map_quotient_eq_zero_iff J (p*q)).mp _ z + rw [map_mul,(map_quotient_eq_zero_iff J p).mpr hp,zero_mul] + +end ElementaryPositivity.CoefficientIdeals + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.CoefficientIdeals +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma sourceFiltration_mul_mem (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 (g i).finsetCongr.subtypeEquiv (fun s => by + simp [Equiv.finsetCongr_apply])) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma cutPerm_val (g : ∀ i, Equiv.Perm (Fin (d i + e i))) (A : Cut d e) (i : I) : + (cutPerm g A i).val = (A i).val.map (g i).toEmbedding := rfl + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma mem_cutPerm (g : ∀ i, Equiv.Perm (Fin (d i + e i))) (A : Cut d e) + (i : I) (a : Fin (d i + e i)) : + g i a ∈ (cutPerm g A i).val ↔ a ∈ (A i).val := by + simp + +noncomputable def leftEnum (A : Cut d e) (i : I) : Fin (d i) ≃ (A i).val := + ((A i).val.orderIsoOfFin (A i).property).toEquiv + +omit [Fintype I] [DecidableEq I] in +lemma right_card (A : Cut d e) (i : I) : (A i).valᶜ.card = e i := by + rw [Finset.card_compl, Fintype.card_fin, (A i).property, Nat.add_sub_cancel_left] + +noncomputable def rightEnum (A : Cut d e) (i : I) : Fin (e i) ≃ ↥((A i).valᶜ) := + ((A i).valᶜ.orderIsoOfFin (right_card A i)).toEquiv + +noncomputable def leftInput (A : Cut d e) : (Σ i,Fin (d i)) → (Σ i,Fin (d i + e i)) := + fun a => ⟨a.1, leftEnum A a.1 a.2⟩ + +noncomputable def rightInput (A : Cut d e) : (Σ i,Fin (e i)) → (Σ i,Fin (d i + e i)) := + fun a => ⟨a.1, rightEnum A a.1 a.2⟩ + +noncomputable def leftImageEquiv (g : ∀ i, Equiv.Perm (Fin (d i + e i))) + (A : Cut d e) (i : I) : (A i).val ≃ (cutPerm g A i).val := + (g i).subtypeEquiv (fun _ => (mem_cutPerm g A i _).symm) + +noncomputable def rightImageEquiv (g : ∀ i, Equiv.Perm (Fin (d i + e i))) + (A : Cut d e) (i : I) : ↥((A i).valᶜ) ≃ ↥((cutPerm g A i).valᶜ) := + (g i).subtypeEquiv (by intro a; simp only [Finset.mem_compl, mem_cutPerm]) + +noncomputable def leftReindex (g : ∀ i, Equiv.Perm (Fin (d i + e i))) + (A : Cut d e) (i : I) : Equiv.Perm (Fin (d i)) := + (leftEnum A i).trans ((leftImageEquiv g A i).trans (leftEnum (cutPerm g A) i).symm) + +noncomputable def rightReindex (g : ∀ i, Equiv.Perm (Fin (d i + e i))) + (A : Cut d e) (i : I) : Equiv.Perm (Fin (e i)) := + (rightEnum A i).trans ((rightImageEquiv g A i).trans (rightEnum (cutPerm g A) i).symm) + +omit [Fintype I] [DecidableEq I] in +lemma leftInput_reindex (g : ∀ i, Equiv.Perm (Fin (d i + e i))) (A : Cut d e) : + leftInput (cutPerm g A) ∘ packAction (fun i => Fin (d i)) (leftReindex g A) = + packAction (fun i => Fin (d i + e i)) g ∘ leftInput A := by + funext ⟨i,a⟩ + change (⟨i, ↑(leftEnum (cutPerm g A) i (leftReindex g A i a))⟩ : Σi,Fin (d i + e i)) = + ⟨i,g i ↑(leftEnum A i a)⟩ + simp only [leftReindex, Equiv.trans_apply, Equiv.apply_symm_apply] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma rightInput_reindex (g : ∀ i, Equiv.Perm (Fin (d i + e i))) (A : Cut d e) : + rightInput (cutPerm g A) ∘ packAction (fun i => Fin (e i)) (rightReindex g A) = + packAction (fun i => Fin (d i + e i)) g ∘ rightInput A := by + funext ⟨i,a⟩ + change (⟨i, ↑(rightEnum (cutPerm g A) i (rightReindex g A i a))⟩ : Σi,Fin (d i + e i)) = + ⟨i,g i ↑(rightEnum A i a)⟩ + simp only [rightReindex, Equiv.trans_apply, Equiv.apply_symm_apply] + rfl + +def PackSymmetric (d : I → ℕ) (f : MvPolynomial (Σ i,Fin (d i)) ℚ) : Prop := + ∀ g : ∀i, Equiv.Perm (Fin (d i)), rename (packAction (fun i => Fin (d i)) g) f = f + +omit [Fintype I] [DecidableEq I] in +lemma rename_leftInput (f : MvPolynomial (Σ i,Fin (d i)) ℚ) (hf : PackSymmetric d f) + (g : ∀ i, Equiv.Perm (Fin (d i + e i))) (A : Cut d e) : + rename (packAction (fun i => Fin (d i + e i)) g) (rename (leftInput A) f) = + rename (leftInput (cutPerm g A)) f := by + rw [MvPolynomial.rename_rename, ← leftInput_reindex, ← MvPolynomial.rename_rename, hf] + +omit [Fintype I] [DecidableEq I] in +lemma rename_rightInput (f : MvPolynomial (Σ i,Fin (e i)) ℚ) (hf : PackSymmetric e f) + (g : ∀ i, Equiv.Perm (Fin (d i + e i))) (A : Cut d e) : + rename (packAction (fun i => Fin (d i + e i)) g) (rename (rightInput A) f) = + rename (rightInput (cutPerm g A)) f := by + rw [MvPolynomial.rename_rename, ← rightInput_reindex, ← MvPolynomial.rename_rename, hf] + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma cutPerm_compl (g : ∀ i, Equiv.Perm (Fin (d i + e i))) + (A : Cut d e) (i : I) : + (cutPerm g A i).valᶜ = (A i).valᶜ.map (g i).toEmbedding := by + ext b + obtain ⟨a,rfl⟩ := (g i).surjective b + simp + +local notation "P" => MvPolynomial (Σ i, Fin (d i + e i)) ℚ +local notation "K" => FractionRing (MvPolynomial (Σ i, Fin (d i + e i)) ℚ) + +noncomputable def cutFactor (A : Cut d e) (i j : I) (k : ℕ) : P := + ∏ a ∈ (A i).val, ∏ b ∈ (A j).valᶜ, (diagonal ⟨i,a⟩ ⟨j,b⟩)^k + +omit [Fintype I] [DecidableEq I] in +lemma rename_cutFactor (g : ∀ i, Equiv.Perm (Fin (d i + e i))) + (A : Cut d e) (i j : I) (k : ℕ) : + rename (packAction (fun i => Fin (d i + e i)) g) (cutFactor A i j k) = + cutFactor (cutPerm g A) i j k := by + simp only [cutFactor] + rw [cutPerm_compl, cutPerm_val] + simp only [map_prod, map_pow, diagonal, map_sub, rename_X, + Finset.prod_map, Function.Embedding.coeFn_mk] + rfl + +noncomputable def cutDenominator (A : Cut d e) : P := ∏ i, cutFactor A i i 1 + +noncomputable def cutNumerator (a : I → I → ℕ) (A : Cut d e) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : P := + rename (leftInput A) f * rename (rightInput A) g * ∏ i, ∏ j, cutFactor A i j (a i j) + +omit [DecidableEq I] in +lemma rename_cutDenominator (g : ∀ i, Equiv.Perm (Fin (d i + e i))) (A : Cut d e) : + rename (packAction (fun i => Fin (d i + e i)) g) (cutDenominator A) = + cutDenominator (cutPerm g A) := by + simp only [cutDenominator, map_prod, rename_cutFactor] + +omit [DecidableEq I] in +lemma rename_cutNumerator (a : I → I → ℕ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (hf : PackSymmetric d f) + (g : MvPolynomial (Σi,Fin (e i)) ℚ) (hg : PackSymmetric e g) + (σ : ∀ i, Equiv.Perm (Fin (d i + e i))) (A : Cut d e) : + rename (packAction (fun i => Fin (d i + e i)) σ) (cutNumerator a A f g) = + cutNumerator a (cutPerm σ A) f g := by + simp only [cutNumerator, map_mul, map_prod, rename_cutFactor, + rename_leftInput f hf, rename_rightInput g hg] + +lemma cutDenominator_dvd (A : Cut d e) : + cutDenominator A ∣ naturalVandermonde (fun i => d i + e i) (fun _ => True) := by + change (∏i,cutFactor A i i 1) ∣ _ + have he : ∀ i, cutFactor A i i 1 = + ∏ ab ∈ ((A i).val ×ˢ (A i).valᶜ), diagonal (⟨i,ab.1⟩ : Σi,Fin (d i+e i)) ⟨i,ab.2⟩ := by + intro i + simp only [cutFactor, pow_one, Finset.prod_product] + simp_rw [he] + apply packed_pairs_product_dvd + · intro i ab hab heq + have hm := Finset.mem_product.mp hab + exact (Finset.mem_compl.mp hm.2) (heq ▸ hm.1) + · intro i ab hab hba + have h1 := Finset.mem_product.mp hab + have h2 := Finset.mem_product.mp hba + exact (Finset.mem_compl.mp h1.2) h2.1 + · intro i ab hab + apply diagonal_dvd_naturalVandermonde + intro heq + have hm := Finset.mem_product.mp hab + exact (Finset.mem_compl.mp hm.2) (heq ▸ hm.1) + +lemma cutDenominator_ne_zero (A : Cut d e) : cutDenominator A ≠ 0 := + ne_zero_of_dvd_ne_zero (naturalVandermonde_ne_zero _ (fun _ => True)) + (cutDenominator_dvd A) + +noncomputable def rawShuffle (a : I → I → ℕ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : K := + ∑ A : Cut d e, algebraMap P K (cutNumerator a A f g) / + algebraMap P K (cutDenominator A) + +lemma rawShuffle_symmetric (a : I → I → ℕ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (hf : PackSymmetric d f) + (g : MvPolynomial (Σi,Fin (e i)) ℚ) (hg : PackSymmetric e g) + (σ : ∀ i, Equiv.Perm (Fin (d i + e i))) : + renameFraction (packAction (fun i => Fin (d i + e i)) σ) (rawShuffle a f g) = + rawShuffle a f g := by + simp only [rawShuffle, map_sum, map_div₀, renameFraction_algebraMap, + rename_cutNumerator a f hf g hg, rename_cutDenominator] + exact Equiv.sum_comp (cutPerm σ) (fun A : Cut d e => + algebraMap P K (cutNumerator a A f g) / algebraMap P K (cutDenominator A)) + +lemma rawShuffle_regular (a : I → I → ℕ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + ∃ N : P, algebraMap P K (naturalVandermonde (fun i => d i + e i) (fun _ => True)) * + rawShuffle a f g = algebraMap P K N := by + have hterms (A : Cut d e) : ∃ N : P, + algebraMap P K (naturalVandermonde (fun i => d i + e i) (fun _ => True)) * + (algebraMap P K (cutNumerator a A f g) / algebraMap P K (cutDenominator A)) = + algebraMap P K N := by + obtain ⟨b,hb⟩ := cutDenominator_dvd A + refine ⟨b * cutNumerator a A f g, ?_⟩ + have hne : algebraMap P K (cutDenominator A) ≠ 0 := + by + intro hz + apply cutDenominator_ne_zero A + exact (IsFractionRing.injective P K) (by simpa using hz) + rw [hb, map_mul, map_mul] + field_simp + choose N hN using hterms + refine ⟨∑A,N A, ?_⟩ + simp only [rawShuffle, Finset.mul_sum, hN, map_sum] + +theorem rawShuffle_polynomial (a : I → I → ℕ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (hf : PackSymmetric d f) + (g : MvPolynomial (Σi,Fin (e i)) ℚ) (hg : PackSymmetric e g) : + ∃ h : P, PackSymmetric (fun i => d i + e i) h ∧ + rawShuffle a f g = algebraMap P K h := by + obtain ⟨h,hh⟩ := invariant_fraction_regular _ (rawShuffle a f g) + (rawShuffle_symmetric a f hf g hg) (rawShuffle_regular a f g) + refine ⟨h,?_,hh⟩ + intro σ + apply IsFractionRing.injective P K + rw [← renameFraction_algebraMap, ← hh, rawShuffle_symmetric a f hf g hg σ] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/CutoffGrid.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/CutoffGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..6cbad4a90af3c67f2856790648806af6a3cd91de --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/CutoffGrid.lean @@ -0,0 +1,207 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNDiagonalConstant +import OAI.Combinatorics.Chromatic.GradedAlgebra.CutoffRow + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.PackConvolution +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(v i).val)=0)) : + quotientTensor a (clippedSlope c η κ) α β (gridShapeTensor a f g p R T u v)=0 := by + unfold gridShapeTensor + apply quotientTensor_cast_zero + by_cases hsum : (fun i=>(u i).val)+(fun i=>(v i).val)=d + · apply clipped_cell_nonhead_zero a c η hc κ + · rwa [(shape_add_complement u).trans (realization_card R)] + · rwa [(shape_add_complement v).trans (realization_card T)] + · rwa [hsum] + · rwa [(shape_add_complement u).trans (realization_card R),hsum] + · rwa [(shape_add_complement u).trans (realization_card R),hsum] + · exact hne + · rw [fourGridPolynomial_zero_of_source_mismatch a f g _ _ _ _ hsum,map_zero,map_zero] + +omit [∀ i, Fintype (A i)] in +lemma clipped_gridShape_wrong_source (κ : ℝ) + {d e α β : I → ℕ} (f : S d) (g : S e) {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (R : Realization α (left p)) (T : Realization β (right p)) + (u : CutShape (left p)) (v : CutShape (right p)) (hd : d≠0) + (hk : κ < slope c η α) (ht : slope c η β ≤ κ) + (hs : slope c η α ≤ slope c η d) + (hm : slope c η d=slope c η α → mass c α ≤ mass c d) (hne : d≠α) : + quotientTensor a (clippedSlope c η κ) α β (gridShapeTensor a f g p R T u v)=0 := by + by_cases hsum : (fun i=>(u i).val)+(fun i=>(v i).val)=d + · apply clipped_gridShape_nonhead_zero a c η hc κ f g p R T u v hd hk ht hs hm + rintro ⟨hu,hv⟩ + have he := (shape_add_complement u).trans (realization_card R) + rw [hu,add_zero] at he + rw [hv,add_zero,he] at hsum + exact hne hsum.symm + · unfold gridShapeTensor + rw [fourGridPolynomial_zero_of_source_mismatch a f g _ _ _ _ hsum,map_zero,map_zero,map_zero] + +omit [∀ i, Fintype (A i)] in +lemma clipped_grid_wrong_source (κ : ℝ) + {d e α β : I → ℕ} (f : S d) (g : S e) {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (R : Realization α (left p)) (T : Realization β (right p)) (hd : d≠0) + (hk : κ < slope c η α) (ht : slope c η β ≤ κ) + (hs : slope c η α ≤ slope c η d) + (hm : slope c η d=slope c η α → mass c α ≤ mass c d) (hne : d≠α) : + quotientTensor a (clippedSlope c η κ) α β (gridTensor a f g p R T)=0 := by + simp only [gridTensor,map_sum] + apply Finset.sum_eq_zero + intro u _ + apply Finset.sum_eq_zero + intro v _ + exact clipped_gridShape_wrong_source a c η hc κ f g p R T u v hd hk ht hs hm hne +omit [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in + +theorem clipped_restrict_wrong_head (κ : ℝ) + {d e α β : I → ℕ} (h : d+e=α+β) (f : S d) (g : S e) (u : Cut α β) (hd : d≠0) + (hk : κ < slope c η α) (ht : slope c η β ≤ κ) + (hs : slope c η α ≤ slope c η d) + (hm : slope c η d=slope c η α → mass c α ≤ mass c d) (hne : d≠α) : + quotientTensor a (clippedSlope c η κ) α β + (restrictTensor u (castS h (shufflePolynomial a f g)))=0 := by + apply quotient_crossTensor_cancel + let s : Pack (A:=fun i=>Fin ((α+β) i)) := fun _=>Finset.univ + let R : Realization (α+β) s := defaultRealization (by intro i; simp [s]) + rw [cleared_restrictTensor a h f g R u,map_smul, + clipped_grid_wrong_source a c η hc κ f g _ _ _ hd hk ht hs hm hne,smul_zero] +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial HahnSeries +open ElementaryPositivity.LaurentAtInfinity SeparationInfinity +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.PackConvolution +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] clearBTensorB clearBTensorBA + +noncomputable def headRestriction (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + S (d+e) →ₗ[ℚ] B a μ d⊗[ℚ]B a μ e := + ((coeff.linearMap (R:=ℚ) 0).comp + ((mulPolynomial (mixedInverseKernelUnit a a μ d e).val).comp + (relativeTaylorB a μ d e).toLinearMap)).comp + ((quotientTensor a μ d e).toLinearMap.comp (restrictTensorAlg (firstCut d e)).toLinearMap) + +lemma headRestriction_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (f : S (d+e)) : + headRestriction a μ d e f= + quotientTensor a μ d e ((tensorSeparationSeries a d e f).coeff 0) := by + change _=(mapRing (R:=S d⊗[ℚ]S e) (S:=B a μ d⊗[ℚ]B a μ e) (quotientTensor a μ d e).toRingHom (tensorSeparationSeries a d e f)).coeff 0 + rw [tensorSeparationSeries,mapRing_mul_polynomial,relativeTaylor_quotient] + rfl + +lemma headRestriction_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (f : S (d+e)) (hf : quotientTensor a μ d e (restrictTensor (firstCut d e) f)=0) : + headRestriction a μ d e f=0 := by + unfold headRestriction + simp only [LinearMap.comp_apply,AlgHom.toLinearMap_apply] + change (coeff.linearMap (R:=ℚ) 0) + (mulPolynomial (mixedInverseKernelUnit a a μ d e).val + (relativeTaylorB a μ d e (quotientTensor a μ d e (restrictTensor (firstCut d e) f))))=0 + rw [hf,map_zero,map_zero,map_zero] + +lemma headRestriction_ideal (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0Fin.last (s i).card +noncomputable def zeroShape (s : Pack (A:=A)) : CutShape s := fun _=>0 +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma shapeComplement_full (s : Pack (A:=A)) : shapeComplement (fullShape s)=0 := by + funext i; simp [shapeComplement,fullShape] +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma zeroShape_val (s : Pack (A:=A)) : (fun i=>(zeroShape s i).val)=0 := rfl +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma eq_fullShape_of_complement {s : Pack (A:=A)} (u : CutShape s) + (hu : shapeComplement u=0) : u=fullShape s := by + funext i; apply Fin.ext + have h := congrFun hu i + have hh := (u i).isLt + change (s i).card-(u i).val=0 at h + change (u i).val=(s i).card + omega +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma eq_zeroShape_of_val {s : Pack (A:=A)} (u : CutShape s) + (hu : (fun i=>(u i).val)=0) : u=zeroShape s := by + funext i; apply Fin.ext; exact congrFun hu i + +omit [∀ i, Fintype (A i)] in +lemma clipped_grid_constant_head (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0le_rfl),map_zero] + rintro ⟨_,h⟩ + exact hv (eq_zeroShape_of_val v h) + · intro h; exact (h (Finset.mem_univ _)).elim + · intro u _ hu + apply Finset.sum_eq_zero + intro v _ + rw [clipped_gridShape_nonhead_zero a c η hc κ f g p R T u v hd hk ht le_rfl (fun _=>le_rfl),map_zero] + rintro ⟨h,_⟩ + exact hu (eq_fullShape_of_complement u h) + · intro h; exact (h (Finset.mem_univ _)).elim + +omit [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in + +theorem headRestriction_shuffle_head (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0Fin ((d+e) i)) := fun _=>Finset.univ + let R : Realization (d+e) s := defaultRealization (by intro i; simp [s]) + have h := headRestriction_shuffle_grid a (clippedSlope c η κ) rfl f g R + rw [castS_rfl] at h + rw [h] + exact clipped_grid_constant_head a c η hc κ f g _ _ _ hd hk ht +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/Degree.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/Degree.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a6471362941c758a5421d0a81867fd5468c17a6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/Degree.lean @@ -0,0 +1,208 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.DegreeIdeals +import OAI.Combinatorics.Chromatic.GradedAlgebra.IntegerHomogeneous + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.Homogeneity +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +omit [Fintype I] [DecidableEq I] in +lemma componentS_zero (d : I → ℕ) (f : S d) : + componentS d 0 f=algebraMap ℚ (S d) (constantCoeff f.val) := by + apply Subtype.ext + exact constantWeight_component_zero f.val + +omit [Fintype I] [DecidableEq I] in +lemma componentS_zero_mul (d : I → ℕ) (f g : S d) : + componentS d 0 (f*g)=componentS d 0 f*componentS d 0 g := by + rw [componentS_zero,componentS_zero,componentS_zero] + change algebraMap ℚ (S d) (constantCoeff (f.val*g.val))=_ + rw [map_mul,map_mul] + +noncomputable def degreeZeroB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + B a μ d →ₐ[ℚ] B a μ d where + toFun := componentB a μ d 0 + map_zero' := (componentB a μ d 0).map_zero + map_add' := (componentB a μ d 0).map_add + map_one' := by + change componentB a μ d 0 (quotientAlg a μ d 1)=quotientAlg a μ d 1 + change quotientAlg a μ d (componentS d 0 1)=_ + rw [componentS_zero] + change quotientAlg a μ d (algebraMap ℚ (S d) (constantCoeff 1))=_ + simp only [map_one] + map_mul' x y := by + induction x using Submodule.Quotient.induction_on with + | H f => + induction y using Submodule.Quotient.induction_on with + | H g => + change componentB a μ d 0 (quotientAlg a μ d f*quotientAlg a μ d g)=_ + rw [←map_mul] + change quotientAlg a μ d (componentS d 0 (f*g))= + quotientAlg a μ d (componentS d 0 f)*quotientAlg a μ d (componentS d 0 g) + rw [componentS_zero_mul,map_mul] + commutes' q := by + change componentB a μ d 0 (quotientAlg a μ d (algebraMap ℚ (S d) q))= + quotientAlg a μ d (algebraMap ℚ (S d) q) + change quotientAlg a μ d (componentS d 0 (algebraMap ℚ (S d) q))=_ + rw [componentS_zero] + change quotientAlg a μ d (algebraMap ℚ (S d) (constantCoeff (C q)))=_ + rw [constantCoeff_C] + +@[simp] lemma degreeZeroB_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (f : S d) : + degreeZeroB a μ d (quotientAlg a μ d f)=algebraMap ℚ (B a μ d) (constantCoeff f.val) := by + change quotientAlg a μ d (componentS d 0 f)=_ + rw [componentS_zero,AlgHom.commutes] + +namespace SplitTree +@[reducible] def zeroDegrees : (T : SplitTree I) → T.Degrees + | .leaf _ => 0 + | .node l r => (l.zeroDegrees,r.zeroDegrees) + +omit [Fintype I] [DecidableEq I] in +lemma totalDegree_zeroDegrees (T : SplitTree I) : T.totalDegree T.zeroDegrees=0 := by + induction T with + | leaf d => rfl + | node l r hl hr => simp only [totalDegree,hl,hr,add_zero] + +omit [Fintype I] [DecidableEq I] in +lemma nonnegativeDegree_zeroDegrees (T : SplitTree I) : T.NonnegativeDegree T.zeroDegrees := by + induction T with + | leaf d => exact le_rfl + | node l r hl hr => exact ⟨hl,hr⟩ + +omit [Fintype I] [DecidableEq I] in +lemma nonnegative_totalDegree_zero (T : SplitTree I) (k : T.Degrees) + (hn : T.NonnegativeDegree k) (hk : T.totalDegree k=0) : k=T.zeroDegrees := by + induction T with + | leaf d => exact hk + | node l r hl hr => + have hL:=l.totalDegree_nonnegative k.1 hn.1 + have hR:=r.totalDegree_nonnegative k.2 hn.2 + change l.totalDegree k.1+r.totalDegree k.2=0 at hk + exact Prod.ext (hl k.1 hn.1 (by omega)) (hr k.2 hn.2 (by omega)) + +noncomputable def degreeZeroTensor (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) : tensor (quotientFamily a μ) T →ₐ[ℚ] tensor (quotientFamily a μ) T := + tensorMap (quotientFamily a μ) (quotientFamily a μ) (degreeZeroB a μ) T + +lemma degreeZeroTensor_apply (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (x : tensor (quotientFamily a μ) T) : + degreeZeroTensor a μ T x=componentTensor a μ T T.zeroDegrees x := by + induction T with + | leaf d => rfl + | node l r hl hr => + induction x using TensorProduct.inductionOn with + | tmul x y => + change degreeZeroTensor a μ l x⊗ₜ[ℚ]degreeZeroTensor a μ r y=_ + rw [hl,hr] + rfl + | add x y hx hy => simp only [map_add,hx,hy] + +lemma sub_degreeZero_mem (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (x : tensor (quotientFamily a μ) T) : + x-degreeZeroTensor a μ T x∈degreeCutSubmodule a μ T (T.doubleShift a+1) := by + intro k hk + rw [degreeZeroTensor_apply,map_sub,componentTensor_componentTensor] + by_cases hn : T.NonnegativeDegree k + · have hnn:=T.totalDegree_nonnegative k hn + have hz : k=T.zeroDegrees := nonnegative_totalDegree_zero T k hn (by omega) + simp only [hz,ite_true,sub_self] + · have hne : k≠T.zeroDegrees := by + intro h + apply hn + simpa only [h] using T.nonnegativeDegree_zeroDegrees + simp only [ite_eq_right hne,componentTensor_negative a μ T k hn,LinearMap.zero_apply,sub_zero] +end SplitTree +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.CenterCalculus +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +namespace SplitTree + +lemma translationAtB_add (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (v w : T.Centers → ℚ) (x : tensor (quotientFamily a μ) T) : + translationAtB a μ T v (translationAtB a μ T w x)= + translationAtB a μ T (fun s=>v s+w s) x := by + induction T with + | leaf d => exact translationB_add a μ d (v ()) (w ()) x + | node l r hl hr => + induction x using TensorProduct.inductionOn with + | tmul x y => + change translationAtB a μ l (v ∘ Sum.inl) (translationAtB a μ l (w ∘ Sum.inl) x) ⊗ₜ[ℚ] + translationAtB a μ r (v ∘ Sum.inr) (translationAtB a μ r (w ∘ Sum.inr) y)=_ + rw [hl,hr] + rfl + | add x y hx hy => simp only [map_add,hx,hy] + +lemma restrictionB_translationAt (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0t) (restrictionB a c η hc θ T hT f) := by + induction T with + | leaf d => rfl + | node l r hl hr => + change (Algebra.TensorProduct.map (restrictionB a c η hc θ l hT.1) + (restrictionB a c η hc θ r hT.2)) + (RawShuffle.restrictionB a c η hc ((slope_dim c η hc hT.1).trans (slope_dim c η hc hT.2).symm) (firstCut l.dim r.dim) + (translationB a (SlopeArithmetic.slope c η) (l.dim+r.dim) t f))=_ + rw [RawShuffle.restrictionB_translation] + simp only [restrictionB,AlgHom.comp_apply] + generalize RawShuffle.restrictionB a c η hc ((slope_dim c η hc hT.1).trans (slope_dim c η hc hT.2).symm) (firstCut l.dim r.dim) f=x + induction x using TensorProduct.inductionOn with + | tmul x y => + change restrictionB a c η hc θ l hT.1 (translationB a (SlopeArithmetic.slope c η) l.dim t x) ⊗ₜ[ℚ] + restrictionB a c η hc θ r hT.2 (translationB a (SlopeArithmetic.slope c η) r.dim t y)=_ + rw [hl,hr] + rfl + | add x y hx hy => simp only [map_add,hx,hy] + +lemma centeredRestrictionB_translate_eval (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0v s+t) (centeredRestrictionB a c η hc θ T hT f) := by + change evalRat v (centerTranslation _ _ T + (restrictionB a c η hc θ T hT (translationB a (SlopeArithmetic.slope c η) T.dim t f)))=_ + rw [centerTranslation_evalRat,restrictionB_translationAt,translationAtB_add] + exact (centerTranslation_evalRat _ _ _ _ _).symm +end SplitTree + +lemma sourceFiltration_translation_mem (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 AddMonoidAlgebra.coeff polynomial z) h1 + change P ((SplitTree.centeredRestrictionB a c η hc θ T hs + (translationB a (SlopeArithmetic.slope c η) T.dim t f)).coeff z)=0 + simpa only [coeff_mapLinear,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply] using he + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/DegreeIdeals.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/DegreeIdeals.lean new file mode 100644 index 0000000000000000000000000000000000000000..10d3ef591e023834324571a519b6d5691a5feb33 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/DegreeIdeals.lean @@ -0,0 +1,179 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.ManyBlockPolynomiality + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.Homogeneity +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma componentB_mul_components (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k i j : ℤ) (x y : B a μ d) : + componentB a μ d k (componentB a μ d i x * componentB a μ d j y)= + if k=i+j then componentB a μ d i x * componentB a μ d j y else 0 := by + obtain ⟨f,hf,hqf⟩:=gradeB_homogeneous_representative a μ d i _ ⟨x,rfl⟩ + obtain ⟨g,hg,hqg⟩:=gradeB_homogeneous_representative a μ d j _ ⟨y,rfl⟩ + rw [←hqf,←hqg] + change componentB a μ d k (quotientAlg a μ d f * quotientAlg a μ d g)=_ + rw [←map_mul] + change quotientAlg a μ d (componentS d k (f*g))=_ + rw [componentS_of_homogeneous d (f*g) (hf.mul hg)] + split_ifs + · exact (quotientAlg a μ d).map_mul f g + · exact (quotientAlg a μ d).map_zero + +namespace SplitTree +@[reducible] def addDegrees : (T : SplitTree I) → T.Degrees → T.Degrees → T.Degrees + | .leaf _, i,j => i+j + | .node l r, i,j => (l.addDegrees i.1 j.1,r.addDegrees i.2 j.2) + +omit [Fintype I] [DecidableEq I] in +lemma totalDegree_addDegrees (T : SplitTree I) (i j : T.Degrees) : + T.totalDegree (T.addDegrees i j)=T.totalDegree i+T.totalDegree j := by + induction T with + | leaf d => rfl + | node l r hl hr => + simp only [totalDegree,hl,hr] + omega + +lemma componentTensor_mul_components (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (k i j : T.Degrees) (x y : tensor (quotientFamily a μ) T) : + componentTensor a μ T k (componentTensor a μ T i x * componentTensor a μ T j y)= + if k=T.addDegrees i j then componentTensor a μ T i x * componentTensor a μ T j y else 0 := by + induction T with + | leaf d => + change componentB a μ d k (componentB a μ d i x * componentB a μ d j y)=_ + have hb:=componentB_mul_components a μ d k i j x y + split_ifs with h + · rw [ite_eq_left h] at hb + exact hb + · rw [ite_eq_right h] at hb + exact hb + | node l r hl hr => + have hp (xl yl : tensor (quotientFamily a μ) l) (xr yr : tensor (quotientFamily a μ) r) : + componentTensor a μ (.node l r) k + (componentTensor a μ (.node l r) i (xl ⊗ₜ[ℚ] xr) * + componentTensor a μ (.node l r) j (yl ⊗ₜ[ℚ] yr))= + if k=(.node l r : SplitTree I).addDegrees i j then + componentTensor a μ (.node l r) i (xl ⊗ₜ[ℚ] xr) * + componentTensor a μ (.node l r) j (yl ⊗ₜ[ℚ] yr) else 0 := by + simp only [componentTensor,TensorProduct.map_tmul,Algebra.TensorProduct.tmul_mul_tmul,hl,hr] + rcases k with ⟨kl,kr⟩ + by_cases hL : kl=l.addDegrees i.1 j.1 <;> + by_cases hR : kr=r.addDegrees i.2 j.2 <;> simp [addDegrees,hL,hR] + induction x using TensorProduct.inductionOn with + | tmul xl xr => + induction y using TensorProduct.inductionOn with + | tmul yl yr => simpa only using hp xl yl xr yr + | add y z hy hz => + simp only [map_add,mul_add,hy,hz] + split_ifs <;> simp + | add x z hx hz => + simp only [map_add,add_mul,hx,hz] + split_ifs <;> simp + +noncomputable def degreeCutSubmodule (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (W : ℤ) : Submodule ℚ (tensor (quotientFamily a μ) T) where + carrier := {x | ∀ k,2*T.totalDegree k+T.doubleShift a rw [←hxs,←hyt] + simp only [Finset.sum_mul,Finset.mul_sum,map_sum] + apply Finset.sum_eq_zero + intro j hj + apply Finset.sum_eq_zero + intro i hi + rw [componentTensor_mul_components] + split_ifs with heq + · by_cases hj0 : T.NonnegativeDegree j + · have hjnn:=T.totalDegree_nonnegative j hj0 + have hiw : 2*T.totalDegree i+T.doubleShift a rw [←hxs,←hyt] + simp only [Finset.sum_mul,Finset.mul_sum,map_sum] + apply Finset.sum_eq_zero + intro j hj + apply Finset.sum_eq_zero + intro i hi + rw [componentTensor_mul_components] + split_ifs with heq + · by_cases hiw : 2*T.totalDegree i+T.doubleShift a simp [identify] + | add p q hp hq => + convert dvd_add hp hq using 1 + simp only [map_add] + ring + | mul_X p k hp => + have hx : diagonal i j ∣ X k - identify i j (X k) := by + by_cases hk : k = j + · subst k + simp [identify, diagonal] + · simp [identify, merge, hk] + convert dvd_add (dvd_mul_of_dvd_left hp (X k)) + (dvd_mul_of_dvd_right hx (identify i j p)) using 1 + simp only [map_mul] + ring + +lemma diagonal_dvd_iff_identify_eq_zero (i j : α) (f : MvPolynomial α ℚ) : + diagonal i j ∣ f ↔ identify i j f = 0 := by + constructor + · intro h + simpa using map_dvd (identify i j) h + · intro h + simpa [h] using diagonal_dvd_sub_identify i j f + +lemma ker_identify (i j : α) : + RingHom.ker (identify i j) = Ideal.span {diagonal i j} := by + ext f + simp [RingHom.mem_ker, Ideal.mem_span_singleton, diagonal_dvd_iff_identify_eq_zero] + +omit [DecidableEq α] in +lemma diagonal_ne_zero {i j : α} (hij : i ≠ j) : diagonal i j ≠ 0 := by + simpa [diagonal, sub_eq_zero, MvPolynomial.X_inj] using hij.symm + +lemma diagonal_prime {i j : α} (hij : i ≠ j) : Prime (diagonal i j) := by + apply (Ideal.span_singleton_prime (diagonal_ne_zero hij)).mp + rw [← ker_identify] + exact RingHom.ker_isPrime _ + +section Ordered +variable [LinearOrder α] + +lemma merge_equal_for_ordered_pair {i j a b : α} (hij : i < j) (hab : a < b) + (h : merge i j a = merge i j b) : a = i ∧ b = j := by + by_cases ha : a = j + · subst a + by_cases hb : b = j + · subst b + exact (lt_irrefl _ hab).elim + · simp only [merge, ite_eq_right hb] at h + subst b + exact (lt_asymm hij hab).elim + · by_cases hb : b = j + · subst b + simpa [merge, ha] using h + · simp only [merge, ite_eq_right ha, ite_eq_right hb] at h + exact (hab.ne h).elim + +lemma diagonals_not_dvd {i j a b : α} (hij : i < j) (hab : a < b) + (hne : (i,j) ≠ (a,b)) : ¬ diagonal i j ∣ diagonal a b := by + intro h + have hz := (diagonal_dvd_iff_identify_eq_zero i j _).mp h + have hm : merge i j a = merge i j b := by + have hrev : merge i j b = merge i j a := by + simpa [identify, diagonal, sub_eq_zero, MvPolynomial.X_inj] using hz + exact hrev.symm + obtain ⟨ha, hb⟩ := merge_equal_for_ordered_pair hij hab hm + exact hne (by simp [ha, hb]) + +lemma diagonals_isRelPrime {i j a b : α} (hij : i < j) (hab : a < b) + (hne : (i,j) ≠ (a,b)) : IsRelPrime (diagonal i j) (diagonal a b) := by + exact (diagonal_prime hij.ne).irreducible.isRelPrime_iff_not_dvd.mpr + (diagonals_not_dvd hij hab hne) + +theorem diagonal_powers_product_dvd (s : Finset (α × α)) + (hs : ∀ ij ∈ s, ij.1 < ij.2) (e : α × α → ℕ) (f : MvPolynomial α ℚ) + (hf : ∀ ij ∈ s, diagonal ij.1 ij.2 ^ e ij ∣ f) : + (∏ ij ∈ s, diagonal ij.1 ij.2 ^ e ij) ∣ f := by + apply Finset.prod_dvd_of_isRelPrime _ hf + intro ij hij kl hkl hne + exact (diagonals_isRelPrime (hs ij hij) (hs kl hkl) hne).pow + +end Ordered + +lemma merge_swap (i j : α) : merge i j ∘ Equiv.swap i j = merge i j := by + funext x + by_cases hi : x = i + · subst x + simp + · by_cases hj : x = j + · subst x + simp + · simp [Equiv.swap_apply_of_ne_of_ne hi hj, Function.comp_apply] + +theorem diagonal_dvd_of_antisymmetric (i j : α) (f : MvPolynomial α ℚ) + (hf : rename (Equiv.swap i j) f = -f) : diagonal i j ∣ f := by + apply (diagonal_dvd_iff_identify_eq_zero i j f).mpr + have h := congrArg (identify i j) hf + simp only [identify, MvPolynomial.rename_rename, merge_swap, map_neg] at h + have hh : (2 : ℚ) • (rename (merge i j) f) = 0 := by + rw [two_smul] + exact add_eq_zero_iff_eq_neg.mpr h + exact (smul_eq_zero.mp hh).resolve_left (by norm_num) + +theorem vandermonde_dvd [LinearOrder α] (s : Finset α) (f : MvPolynomial α ℚ) + (hf : ∀ i ∈ s, ∀ j ∈ s, i < j → rename (Equiv.swap i j) f = -f) : + (∏ ij ∈ (s ×ˢ s).filter (fun ij => ij.1 < ij.2), diagonal ij.1 ij.2) ∣ f := by + let t := (s ×ˢ s).filter (fun ij => ij.1 < ij.2) + have ht : ∀ ij ∈ t, ij.1 < ij.2 := by + intro ij hij + exact (Finset.mem_filter.mp hij).2 + simpa using diagonal_powers_product_dvd t ht (fun _ => 1) f (by + intro ij hij + obtain ⟨hij, hlt⟩ := Finset.mem_filter.mp hij + obtain ⟨hi,hj⟩ := Finset.mem_product.mp hij + simpa using diagonal_dvd_of_antisymmetric ij.1 ij.2 f (hf ij.1 hi ij.2 hj hlt)) + +section Alternation +variable {G : Type*} [Group G] [Fintype G] + +noncomputable def alternate (ρ : G →* Equiv.Perm α) (χ : G →* ℤˣ) + (f : MvPolynomial α ℚ) : MvPolynomial α ℚ := + ∑ g : G, (χ g : ℤ) • rename (ρ g) f + +omit [DecidableEq α] in +lemma rename_alternate_of_sign_neg (ρ : G →* Equiv.Perm α) (χ : G →* ℤˣ) + (f : MvPolynomial α ℚ) (t : G) (ht : χ t = -1) : + rename (ρ t) (alternate ρ χ f) = -alternate ρ χ f := by + rw [alternate, map_sum] + calc + (∑ g : G, rename (ρ t) ((χ g : ℤ) • rename (ρ g) f)) = + -(∑ g : G, (χ (t*g) : ℤ) • rename (ρ (t*g)) f) := by + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro g _ + simp only [map_zsmul, MvPolynomial.rename_rename, map_mul, + Equiv.Perm.coe_mul, ht, neg_one_mul, Units.val_neg, neg_smul, neg_neg] + _ = -alternate ρ χ f := by + simpa [alternate] using congrArg Neg.neg + (Equiv.sum_comp (Equiv.mulLeft t) (fun g => (χ g : ℤ) • rename (ρ g) f)) + +lemma diagonal_dvd_alternate (ρ : G →* Equiv.Perm α) (χ : G →* ℤˣ) + (f : MvPolynomial α ℚ) (i j : α) (t : G) + (hρ : ρ t = Equiv.swap i j) (hχ : χ t = -1) : + diagonal i j ∣ alternate ρ χ f := by + apply diagonal_dvd_of_antisymmetric + rw [← hρ] + exact rename_alternate_of_sign_neg ρ χ f t hχ + +theorem same_pack_alternation_polynomial [Fintype α] [LinearOrder α] + (f : MvPolynomial α ℚ) : + ∃ q : MvPolynomial α ℚ, + alternate (MonoidHom.id (Equiv.Perm α)) Equiv.Perm.sign f = + (∏ ij ∈ (Finset.univ ×ˢ Finset.univ).filter + (fun ij : α × α => ij.1 < ij.2), diagonal ij.1 ij.2) * q := by + apply vandermonde_dvd Finset.univ + intro i _ j _ hij + apply rename_alternate_of_sign_neg (MonoidHom.id (Equiv.Perm α)) Equiv.Perm.sign + f (Equiv.swap i j) + exact Equiv.Perm.sign_swap hij.ne + +end Alternation + +section UnorderedPairs + +lemma merge_equal_pair {i j a b : α} (hab : a ≠ b) + (h : merge i j a = merge i j b) : + (a = i ∧ b = j) ∨ (a = j ∧ b = i) := by + by_cases ha : a = j + · subst a + by_cases hb : b = j + · exact (hab hb.symm).elim + · simp only [merge, ite_eq_right hb] at h + exact Or.inr ⟨rfl, h.symm⟩ + · by_cases hb : b = j + · subst b + simp only [merge, ite_eq_right ha] at h + exact Or.inl ⟨h, rfl⟩ + · simp only [merge, ite_eq_right ha, ite_eq_right hb] at h + exact (hab h).elim + +lemma independent_diagonals {i j a b : α} (hij : i ≠ j) (hab : a ≠ b) + (h₁ : (i,j) ≠ (a,b)) (h₂ : (i,j) ≠ (b,a)) : + IsRelPrime (diagonal i j) (diagonal a b) := by + apply (diagonal_prime hij).irreducible.isRelPrime_iff_not_dvd.mpr + intro hd + have hz := (diagonal_dvd_iff_identify_eq_zero i j _).mp hd + have he : merge i j b = merge i j a := by + simpa [identify, diagonal, sub_eq_zero, MvPolynomial.X_inj] using hz + obtain (⟨ha,hb⟩ | ⟨ha,hb⟩) := merge_equal_pair hab he.symm + · exact h₁ (by simp [ha, hb]) + · exact h₂ (by simp [ha, hb]) + +theorem pair_powers_product_dvd (s : Finset (α × α)) + (hs : ∀ ij ∈ s, ij.1 ≠ ij.2) + (hrev : ∀ ij ∈ s, (ij.2,ij.1) ∉ s) + (e : α × α → ℕ) (f : MvPolynomial α ℚ) + (hf : ∀ ij ∈ s, diagonal ij.1 ij.2 ^ e ij ∣ f) : + (∏ ij ∈ s, diagonal ij.1 ij.2 ^ e ij) ∣ f := by + apply Finset.prod_dvd_of_isRelPrime _ hf + intro ij hij kl hkl hne + apply (independent_diagonals (hs ij hij) (hs kl hkl) hne _).pow + intro hr + apply hrev ij hij + have heq : (ij.2,ij.1) = kl := by + simpa only [Prod.swap, Prod.eta] using congrArg Prod.swap hr + rwa [heq] + +end UnorderedPairs + +section Packs + +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (V : I → Type*) [∀ i, Fintype (V i)] [∀ i, DecidableEq (V i)] + +def packAction : (∀ i, Equiv.Perm (V i)) →* Equiv.Perm (Σ i, V i) where + toFun g := Equiv.sigmaCongrRight g + map_one' := by apply Equiv.ext; rintro ⟨i,a⟩; rfl + map_mul' g h := by apply Equiv.ext; rintro ⟨i,a⟩; rfl + +def packSign (E : I → Prop) [DecidablePred E] : + (∀ i, Equiv.Perm (V i)) →* ℤˣ where + toFun g := ∏ i, if E i then Equiv.Perm.sign (g i) else 1 + map_one' := by simp + map_mul' g h := by + simp only [Pi.mul_apply, map_mul] + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + split_ifs <;> simp + +omit [Fintype I] [∀ i, Fintype (V i)] in +lemma packAction_transposition (i : I) (a b : V i) : + packAction V (Function.update 1 i (Equiv.swap a b)) = + Equiv.swap (⟨i,a⟩ : Σ i,V i) ⟨i,b⟩ := by + apply Equiv.ext + rintro ⟨j,c⟩ + by_cases hj : j = i + · subst j + change (⟨i, (Function.update (1 : ∀ i, Equiv.Perm (V i)) i (Equiv.swap a b)) i c⟩ : Σ i,V i) = _ + rw [Function.update_self] + simp only [Equiv.swap_apply_def, Sigma.mk.inj_iff, heq_eq_eq, true_and] + split_ifs <;> rfl + · change (⟨j, (Function.update (1 : ∀ i, Equiv.Perm (V i)) i (Equiv.swap a b)) j c⟩ : Σ i,V i) = _ + rw [Function.update_of_ne hj] + exact (Equiv.swap_apply_of_ne_of_ne + (fun h => hj (congrArg Sigma.fst h)) + (fun h => hj (congrArg Sigma.fst h))).symm + +lemma packSign_transposition (E : I → Prop) [DecidablePred E] + (i : I) (a b : V i) (hi : E i) (hab : a ≠ b) : + packSign V E (Function.update 1 i (Equiv.swap a b)) = -1 := by + change (∏ j, if E j then + Equiv.Perm.sign ((Function.update (1 : ∀ i, Equiv.Perm (V i)) i + (Equiv.swap a b)) j) else 1) = -1 + rw [Fintype.prod_eq_single i] + · simp [hi, Equiv.Perm.sign_swap hab] + · intro j hji + simp [Function.update_of_ne hji] + +lemma pack_alternate_diagonal (E : I → Prop) [DecidablePred E] + (f : MvPolynomial (Σ i,V i) ℚ) (i : I) (a b : V i) + (hi : E i) (hab : a ≠ b) : + diagonal ⟨i,a⟩ ⟨i,b⟩ ∣ alternate (packAction V) (packSign V E) f := by + apply diagonal_dvd_alternate (packAction V) (packSign V E) f + ⟨i,a⟩ ⟨i,b⟩ (Function.update 1 i (Equiv.swap a b)) + · exact packAction_transposition V i a b + · exact packSign_transposition V E i a b hi hab + +noncomputable def packPairs (E : I → Prop) [DecidablePred E] : + Finset ((Σ i,V i) × (Σ i,V i)) := by + classical + exact (Finset.univ ×ˢ Finset.univ).filter (fun ij => + ij.1.1 = ij.2.1 ∧ E ij.1.1 ∧ + Fintype.equivFin (Σ i,V i) ij.1 < Fintype.equivFin (Σ i,V i) ij.2) + +noncomputable def packVandermonde (E : I → Prop) [DecidablePred E] : + MvPolynomial (Σ i,V i) ℚ := + ∏ ij ∈ packPairs V E, diagonal ij.1 ij.2 + +theorem pack_alternation_polynomial (E : I → Prop) [DecidablePred E] + (f : MvPolynomial (Σ i,V i) ℚ) : + ∃ q : MvPolynomial (Σ i,V i) ℚ, + alternate (packAction V) (packSign V E) f = packVandermonde V E * q := by + classical + change packVandermonde V E ∣ alternate (packAction V) (packSign V E) f + unfold packVandermonde + have hi (ij) (hij : ij ∈ packPairs V E) : + ij.1.1 = ij.2.1 ∧ E ij.1.1 ∧ + Fintype.equivFin (Σ i,V i) ij.1 < Fintype.equivFin (Σ i,V i) ij.2 := + (Finset.mem_filter.mp hij).2 + have hn (ij) (hij : ij ∈ packPairs V E) : ij.1 ≠ ij.2 := by + intro h + exact (hi ij hij).2.2.ne (congrArg (Fintype.equivFin (Σ i,V i)) h) + have hr (ij) (hij : ij ∈ packPairs V E) : (ij.2,ij.1) ∉ packPairs V E := by + intro hrev + exact lt_asymm (hi ij hij).2.2 (hi _ hrev).2.2 + simpa using pair_powers_product_dvd (packPairs V E) hn hr (fun _ => 1) + (alternate (packAction V) (packSign V E) f) (by + rintro ⟨⟨i,a⟩,⟨j,b⟩⟩ hij + have he : i = j := (hi _ hij).1 + subst j + have hab : a ≠ b := by + intro h + exact hn _ hij (by cases h; rfl) + simpa using pack_alternate_diagonal V E f i a b (hi _ hij).2.1 hab) + +end Packs + +section FinPacks +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (n : I → ℕ) (E : I → Prop) [DecidablePred E] + +noncomputable def naturalVandermonde : MvPolynomial (Σ i, Fin (n i)) ℚ := + ∏ i, if E i then (Matrix.vandermonde (fun a : Fin (n i) => + (X ⟨i,a⟩ : MvPolynomial (Σ i, Fin (n i)) ℚ))).det else 1 + +def finPackPair (a : Σ i, Fin (n i) × Fin (n i)) : + (Σ i, Fin (n i)) × (Σ i, Fin (n i)) := + (⟨a.1,a.2.1⟩, ⟨a.1,a.2.2⟩) + +omit [Fintype I] [DecidableEq I] in +lemma finPackPair_injective : Function.Injective (finPackPair n) := by + rintro ⟨i,a,b⟩ ⟨j,c,d⟩ h + have hij : i = j := congrArg (fun p => p.1.1) h + subst j + simp only [finPackPair, Prod.mk.injEq, Sigma.mk.inj_iff, heq_eq_eq, true_and] at h + obtain ⟨rfl,rfl⟩ := h + rfl + +noncomputable def naturalPairs : Finset (Σ i, Fin (n i) × Fin (n i)) := + Finset.univ.sigma (fun i => (Finset.univ ×ˢ Finset.univ).filter + (fun ab : Fin (n i) × Fin (n i) => E i ∧ ab.1 < ab.2)) + +omit [DecidableEq I] in +lemma naturalVandermonde_product : naturalVandermonde n E = + ∏ a ∈ naturalPairs n E, diagonal (finPackPair n a).1 (finPackPair n a).2 := by + rw [naturalVandermonde, naturalPairs, Finset.prod_sigma] + apply Finset.prod_congr rfl + intro i _ + by_cases hi : E i + · simp only [hi, ite_true, Matrix.det_vandermonde, true_and] + rw [Finset.prod_filter, Finset.prod_product] + apply Finset.prod_congr rfl + intro a _ + simp only [← Finset.filter_lt_eq_Ioi, Finset.prod_filter, diagonal, finPackPair] + · simp [hi] + +omit [DecidableEq I] in +lemma rename_naturalVandermonde (g : ∀ i, Equiv.Perm (Fin (n i))) : + rename (packAction (fun i => Fin (n i)) g) (naturalVandermonde n E) = + (packSign (fun i => Fin (n i)) E g : ℤ) • naturalVandermonde n E := by + rw [naturalVandermonde, map_prod] + simp only [packSign, MonoidHom.coe_mk, OneHom.coe_mk, Units.coe_prod, + zsmul_eq_mul, Int.cast_prod] + rw [← Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro i _ + by_cases hi : E i + · simp only [hi, ite_true] + change ((rename (packAction (fun i => Fin (n i)) g)).toRingHom) + (Matrix.vandermonde (fun a : Fin (n i) => X ⟨i,a⟩)).det = _ + rw [RingHom.map_det] + have hm : (rename (packAction (fun i => Fin (n i)) g)).toRingHom.mapMatrix + (Matrix.vandermonde (fun a : Fin (n i) => + (X ⟨i,a⟩ : MvPolynomial (Σ i, Fin (n i)) ℚ))) = + (Matrix.vandermonde (fun a : Fin (n i) => + (X ⟨i,a⟩ : MvPolynomial (Σ i, Fin (n i)) ℚ))).submatrix (g i) id := by + ext a b + simp [Matrix.vandermonde, Matrix.submatrix_apply, packAction] + rw [hm, Matrix.det_permute] + · simp [hi] + +lemma naturalVandermonde_dvd_alternate (f : MvPolynomial (Σ i, Fin (n i)) ℚ) : + naturalVandermonde n E ∣ + alternate (packAction (fun i => Fin (n i))) (packSign (fun i => Fin (n i)) E) f := by + rw [naturalVandermonde_product] + apply Finset.prod_dvd_of_isRelPrime + · rintro ⟨i,a,b⟩ hi ⟨j,c,d⟩ hj hne + change (⟨i,(a,b)⟩ : Σ i, Fin (n i) × Fin (n i)) ∈ naturalPairs n E at hi + change (⟨j,(c,d)⟩ : Σ i, Fin (n i) × Fin (n i)) ∈ naturalPairs n E at hj + simp only [naturalPairs, Finset.mem_sigma, Finset.mem_univ, Finset.mem_filter, + Finset.mem_product, true_and] at hi hj + have hab : (⟨i,a⟩ : Σ i,Fin (n i)) ≠ ⟨i,b⟩ := by simpa using hi.2.ne + have hcd : (⟨j,c⟩ : Σ i,Fin (n i)) ≠ ⟨j,d⟩ := by simpa using hj.2.ne + apply independent_diagonals hab hcd + · exact fun h => hne (finPackPair_injective n h) + · intro hr + have hij : i = j := congrArg (fun p => p.1.1) hr + subst j + simp only [Prod.mk.injEq, Sigma.mk.inj_iff, heq_eq_eq, true_and] at hr + obtain ⟨rfl,rfl⟩ := hr + exact lt_asymm hi.2 hj.2 + · rintro ⟨i,a,b⟩ ha + simp only [naturalPairs, Finset.mem_sigma, Finset.mem_univ, Finset.mem_filter, + Finset.mem_product, true_and] at ha + exact pack_alternate_diagonal (fun i => Fin (n i)) E f i a b ha.1 ha.2.ne + +end FinPacks + +section FractionRename +variable {α : Type*} [DecidableEq α] + +end FractionRename +end ElementaryPositivity.ShufflePolynomiality +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/DimensionColumnLeading.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/DimensionColumnLeading.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8ff8ac95f4b1d349a343b0e7eb7b581fb0767f5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/DimensionColumnLeading.lean @@ -0,0 +1,174 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.UnitalProduct +import OAI.Combinatorics.Chromatic.Shuffle.SignedCoproductGridGrade + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +lemma sum_subtype_of_zero_off {X M : Type*} [Fintype X] [AddCommMonoid M] + (p : X → Prop) [DecidablePred p] (f : X → M) (hf : ∀ x,¬p x → f x=0) : + ∑ x,f x=∑ x : {x // p x},f x.val := by + rw [←Fintype.sum_subtype_add_sum_subtype p f] + have hzero : ∑ x : {x // ¬p x},f x.val=0 := by + apply Finset.sum_eq_zero + intro x _ + exact hf x.val x.property + rw [hzero,add_zero] + +lemma dimensionRowLeadingB_zero_of_mismatch (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0left s.1+left s.2=d ∧ right s.1+right s.2=e) + (fun s=>F s.1 s.2) (fun s hs=>hz s.1 s.2 hs)] + exact sum_transposeDimensionGrid_congr d e α β (fun s=>F s.val.1 s.val.2) G hg + +theorem dimensionLeadingB_eq_column_sum (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0dimensionRowLeadingB_zero_of_mismatch a c η hc θ f g u v h) + (fun s=>(dimensionColumnLeadingB_transpose a c η hc θ f g s).symm) + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.PackConvolution +open ElementaryPositivity.LinearFiltration +open HahnSeries SeparationInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] +attribute [local instance] Classical.propDecidable + +omit [∀ i,Fintype (A i)] in +lemma clearedConstantB_grid_unital_support (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(u i).val) (shapeComplement u) (fun i=>(v i).val) (shapeComplement v) + then clearedConstantB a (slope c η) α β + (quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v)) else 0 := by + rw [quotient_gridTensor_unital_support a c η hc θ f g p R T hα hβ hd] + simp only [map_sum,apply_ite,(clearedConstantB a (slope c η) α β).map_zero] + +omit [∀ i,Fintype (A i)] in +lemma clearedConstantB_grid_leading_unital (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0Equiv.cast (congrArg Fin (congrFun h i)))) f.val := by + subst e + change f.val=rename id f.val + simp only [rename_id,AlgHom.id_apply] + +@[reducible] def Vars : SplitTree I → Type u + | .leaf d => Σ i,Fin (d i) + | .node l r => l.Vars ⊕ r.Vars + +noncomputable def varEquiv : (T : SplitTree I) → T.Vars ≃ (Σ i,Fin (T.dim i)) + | .leaf _ => Equiv.refl _ + | .node l r => (Equiv.sumCongr (varEquiv l) (varEquiv r)).trans + (cutSplit (firstCut l.dim r.dim)) + +noncomputable def tensorValue : (T : SplitTree I) → tensor rawFamily T →ₐ[ℚ] MvPolynomial T.Vars ℚ + | .leaf d => (symmetricSpace d).val + | .node l r => (tensorEquivSum ℚ _ _ ℚ).toAlgHom.comp + (Algebra.TensorProduct.map (tensorValue l) (tensorValue r)) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma tensorValue_tmul (l r : SplitTree I) (x : tensor rawFamily l) (y : tensor rawFamily r) : + tensorValue (.node l r) (x ⊗ₜ[ℚ] y)= + rename Sum.inl (tensorValue l x)*rename Sum.inr (tensorValue r y) := by + exact RawShuffle.tensorEquivSum_tmul _ _ + +omit [Fintype I] [DecidableEq I] in +lemma tensorValue_injective (T : SplitTree I) : Function.Injective (tensorValue T) := by + induction T with + | leaf d => exact Subtype.val_injective + | node l r ihl ihr => + exact (tensorEquivSum ℚ _ _ ℚ).injective.comp + (TensorProduct.map_injective_of_flat_flat (tensorValue l).toLinearMap + (tensorValue r).toLinearMap ihl ihr) + +lemma tensorValue_rawRestriction (T : SplitTree I) (f : S T.dim) : + tensorValue T (rawRestriction T f)=rename T.varEquiv.symm f.val := by + induction T with + | leaf d => + change f.val=rename id f.val + simp only [rename_id,AlgHom.id_apply] + | node l r ihl ihr => + have h : ∀ x : S l.dim ⊗[ℚ] S r.dim, + tensorValue (.node l r) (Algebra.TensorProduct.map (rawRestriction l) (rawRestriction r) x)= + rename (Sum.map l.varEquiv.symm r.varEquiv.symm) (RawShuffle.tensorValue l.dim r.dim x) := by + intro x + induction x using TensorProduct.inductionOn with + | tmul x y => + rw [Algebra.TensorProduct.map_tmul,tensorValue_tmul,ihl,ihr, + RawShuffle.tensorValue_tmul,map_mul,rename_rename,rename_rename,rename_rename,rename_rename] + rfl + | add x y hx hy => simp only [map_add,hx,hy] + change tensorValue (.node l r) (Algebra.TensorProduct.map (rawRestriction l) (rawRestriction r) + (restrictTensor (firstCut l.dim r.dim) f)) = _ + rw [h,RawShuffle.tensorValue_restrictTensor,rename_rename] + rfl + +lemma rawRestriction_regroup {T U : SplitTree I} (h : T.dim=U.dim) + (e : T.Vars ≃ U.Vars) + (he : ∀ x, U.varEquiv (e x)=Equiv.sigmaCongrRight + (fun i=>Equiv.cast (congrArg Fin (congrFun h i))) (T.varEquiv x)) + (f : S T.dim) : + rename e (tensorValue T (rawRestriction T f))= + tensorValue U (rawRestriction U ((dimensionEquivS h) f)) := by + rw [tensorValue_rawRestriction,tensorValue_rawRestriction,dimensionEquivS_val, + rename_rename,rename_rename] + congr 2 + funext x + apply U.varEquiv.injective + simp only [Function.comp_apply,he,Equiv.apply_symm_apply] + +noncomputable def packFiberEquiv (d : I → ℕ) (i : I) : + {x : (Σ j,Fin (d j)) // x.1=i} ≃ Fin (d i) where + toFun x := x.property ▸ x.val.2 + invFun x := ⟨⟨i,x⟩,rfl⟩ + left_inv x := by + rcases x with ⟨⟨j,x⟩,h⟩ + dsimp at h + subst j + rfl + right_inv x := rfl + +omit [Fintype I] [DecidableEq I] in +lemma pack_equiv_eq_packAction (d : I → ℕ) (e : Equiv.Perm (Σ i,Fin (d i))) + (h : ∀ x,(e x).1=x.1) : + ∃ σ : ∀ i,Equiv.Perm (Fin (d i)), ShufflePolynomiality.packAction (fun i=>Fin (d i)) σ=e := by + let E : ∀ i,{x : (Σ j,Fin (d j)) // x.1=i} ≃ {x : (Σ j,Fin (d j)) // x.1=i} := + fun i => e.subtypeEquiv (by intro x; simp only [h x]) + let σ : ∀ i,Equiv.Perm (Fin (d i)) := fun i => + (packFiberEquiv d i).symm.trans ((E i).trans (packFiberEquiv d i)) + refine ⟨σ,?_⟩ + apply Equiv.ext + rintro ⟨i,x⟩ + exact congrArg Subtype.val ((packFiberEquiv d i).symm_apply_apply + (E i ⟨⟨i,x⟩,rfl⟩)) + +omit [Fintype I] [DecidableEq I] in +lemma rename_pack_preserving (d : I → ℕ) (e : Equiv.Perm (Σ i,Fin (d i))) + (h : ∀ x,(e x).1=x.1) (f : S d) : rename e f.val=f.val := by + obtain ⟨σ,rfl⟩ := pack_equiv_eq_packAction d e h + exact f.property σ + +lemma rawRestriction_regroup_permuted {T U : SplitTree I} (h : T.dim=U.dim) + (e : T.Vars ≃ U.Vars) (σ : Equiv.Perm (Σ i,Fin (T.dim i))) + (hσ : ∀ x,(σ x).1=x.1) + (he : ∀ x, U.varEquiv (e x)=Equiv.sigmaCongrRight + (fun i=>Equiv.cast (congrArg Fin (congrFun h i))) (σ (T.varEquiv x))) + (f : S T.dim) : + rename e (tensorValue T (rawRestriction T f))= + tensorValue U (rawRestriction U (dimensionEquivS h f)) := by + rw [tensorValue_rawRestriction,tensorValue_rawRestriction,dimensionEquivS_val,rename_rename] + have hf := rename_pack_preserving T.dim σ hσ f + conv_rhs => arg 2; rw [← hf] + rw [rename_rename,rename_rename] + congr 2 + funext x + apply U.varEquiv.injective + simp only [Function.comp_apply,he,Equiv.apply_symm_apply] + +@[reducible] def packIndex : (T : SplitTree I) → T.Vars → I + | .leaf _, x => x.1 + | .node l _, .inl x => l.packIndex x + | .node _ r, .inr x => r.packIndex x + +omit [Fintype I] [DecidableEq I] in +lemma varEquiv_fst (T : SplitTree I) (x : T.Vars) : (T.varEquiv x).1=T.packIndex x := by + induction T with + | leaf d => rfl + | node l r ihl ihr => + cases x with + | inl x => exact ihl x + | inr x => exact ihr x + +omit [Fintype I] [DecidableEq I] in +lemma varEquiv_symm_packIndex (T : SplitTree I) (x : Σ i,Fin (T.dim i)) : + T.packIndex (T.varEquiv.symm x)=x.1 := by + rw [← varEquiv_fst,Equiv.apply_symm_apply] + +lemma rawRestriction_regroup_of_pack_preserving {T U : SplitTree I} (h : T.dim=U.dim) + (e : T.Vars ≃ U.Vars) (he : ∀ x,U.packIndex (e x)=T.packIndex x) + (f : S T.dim) : + rename e (tensorValue T (rawRestriction T f))= + tensorValue U (rawRestriction U (dimensionEquivS h f)) := by + let C : (Σ i,Fin (T.dim i)) ≃ (Σ i,Fin (U.dim i)) := + Equiv.sigmaCongrRight (fun i=>Equiv.cast (congrArg Fin (congrFun h i))) + let σ : Equiv.Perm (Σ i,Fin (T.dim i)) := + T.varEquiv.symm.trans (e.trans (U.varEquiv.trans C.symm)) + have hσ : ∀ x,(σ x).1=x.1 := by + intro x + change (U.varEquiv (e (T.varEquiv.symm x))).1=x.1 + rw [varEquiv_fst,he,varEquiv_symm_packIndex] + apply rawRestriction_regroup_permuted h e σ hσ + intro x + change U.varEquiv (e x)=C (C.symm (U.varEquiv (e (T.varEquiv.symm (T.varEquiv x))))) + rw [Equiv.symm_apply_apply,Equiv.apply_symm_apply] + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/DimensionGrid.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/DimensionGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..e5f7f89a7c641a8de91e26ea276b628b2bcd9421 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/DimensionGrid.lean @@ -0,0 +1,163 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +variable {I : Type*} + +abbrev DimensionSplit (d : I → ℕ) := ∀ i, Fin (d i + 1) + +namespace DimensionSplit + +def left {d : I → ℕ} (s : DimensionSplit d) : I → ℕ := fun i => (s i).val +def right {d : I → ℕ} (s : DimensionSplit d) : I → ℕ := fun i => d i - (s i).val + +@[simp] lemma left_add_right {d : I → ℕ} (s : DimensionSplit d) : left s + right s = d := by + funext i + have hi := (s i).isLt + simp only [Pi.add_apply, left, right] + omega + +@[ext] lemma ext {d : I → ℕ} {s t : DimensionSplit d} (h : left s = left t) : s = t := by + funext i + exact Fin.ext (congrFun h i) + +def ofPair (a b : I → ℕ) {d : I → ℕ} (h : a+b=d) : DimensionSplit d := + fun i => ⟨a i, by have hi := congrFun h i; simp only [Pi.add_apply] at hi; omega⟩ + +@[simp] lemma left_ofPair (a b : I → ℕ) {d : I → ℕ} (h : a+b=d) : + left (ofPair a b h) = a := rfl + +@[simp] lemma right_ofPair (a b : I → ℕ) {d : I → ℕ} (h : a+b=d) : + right (ofPair a b h) = b := by + funext i + have hi := congrFun h i + simp only [Pi.add_apply] at hi + simp only [right, ofPair] + omega + +@[simp] lemma ofPair_left_right {d : I → ℕ} (s : DimensionSplit d) : + ofPair (left s) (right s) (left_add_right s) = s := by + apply ext + rfl + +def pairEquiv (d : I → ℕ) : DimensionSplit d ≃ {p : (I→ℕ) × (I→ℕ) // p.1+p.2=d} where + toFun s := ⟨(left s,right s),left_add_right s⟩ + invFun p := ofPair p.val.1 p.val.2 p.property + left_inv := ofPair_left_right + right_inv p := by apply Subtype.ext; simp + +end DimensionSplit + +open DimensionSplit + +abbrev RowDimensionGrid (d e α β : I → ℕ) := + {s : DimensionSplit α × DimensionSplit β // + left s.1 + left s.2 = d ∧ right s.1 + right s.2 = e} + +abbrev ColumnDimensionGrid (d e α β : I → ℕ) := + {s : DimensionSplit d × DimensionSplit e // + left s.1 + left s.2 = α ∧ right s.1 + right s.2 = β} + +def transposeDimensionGrid (d e α β : I → ℕ) : + RowDimensionGrid d e α β ≃ ColumnDimensionGrid d e α β where + toFun s := ⟨(ofPair (left s.val.1) (left s.val.2) s.property.1, + ofPair (right s.val.1) (right s.val.2) s.property.2), by simp⟩ + invFun s := ⟨(ofPair (left s.val.1) (left s.val.2) s.property.1, + ofPair (right s.val.1) (right s.val.2) s.property.2), by simp⟩ + left_inv s := by + apply Subtype.ext + apply Prod.ext + · apply DimensionSplit.ext + simp + · apply DimensionSplit.ext + simp + right_inv s := by + apply Subtype.ext + apply Prod.ext + · apply DimensionSplit.ext + simp + · apply DimensionSplit.ext + simp + +@[simp] lemma transposeDimensionGrid_first_left (d e α β : I → ℕ) + (s : RowDimensionGrid d e α β) : + left (transposeDimensionGrid d e α β s).val.1 = left s.val.1 := rfl + +@[simp] lemma transposeDimensionGrid_first_right (d e α β : I → ℕ) + (s : RowDimensionGrid d e α β) : + right (transposeDimensionGrid d e α β s).val.1 = left s.val.2 := + right_ofPair _ _ s.property.1 + +@[simp] lemma transposeDimensionGrid_second_left (d e α β : I → ℕ) + (s : RowDimensionGrid d e α β) : + left (transposeDimensionGrid d e α β s).val.2 = right s.val.1 := rfl + +@[simp] lemma transposeDimensionGrid_second_right (d e α β : I → ℕ) + (s : RowDimensionGrid d e α β) : + right (transposeDimensionGrid d e α β s).val.2 = right s.val.2 := + right_ofPair _ _ s.property.2 + +attribute [local instance] Classical.propDecidable + +lemma sum_transposeDimensionGrid [Fintype I] [DecidableEq I] (d e α β : I → ℕ) + {M : Type*} [AddCommMonoid M] (F : ColumnDimensionGrid d e α β → M) : + ∑ s : RowDimensionGrid d e α β, F (transposeDimensionGrid d e α β s) = + ∑ s : ColumnDimensionGrid d e α β, F s := by + classical + exact Equiv.sum_comp (transposeDimensionGrid d e α β) F + +lemma sum_transposeDimensionGrid_congr [Fintype I] [DecidableEq I] (d e α β : I → ℕ) + {M : Type*} [AddCommMonoid M] (F : RowDimensionGrid d e α β → M) + (G : ColumnDimensionGrid d e α β → M) + (h : ∀ s,F s=G (transposeDimensionGrid d e α β s)) : + ∑ s : RowDimensionGrid d e α β,F s=∑ s : ColumnDimensionGrid d e α β,G s := by + classical + calc + _=∑ s : RowDimensionGrid d e α β,G (transposeDimensionGrid d e α β s) := by + apply Finset.sum_congr rfl + intro s _ + exact h s + _=_ := sum_transposeDimensionGrid d e α β G + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +noncomputable section +variable {I A B : Type*} (δ : A → I → ℕ) (ε : B → I → ℕ) + +private lemma subtypePair_heq {p q : A → Prop} {r s : B → Prop} + (hp : p=q) (hr : r=s) (x : A) (y : B) + (hx : p x) (hy : r y) (hx' : q x) (hy' : s y) : + HEq ((⟨x,hx⟩ : Subtype p),(⟨y,hy⟩ : Subtype r)) + ((⟨x,hx'⟩ : Subtype q),(⟨y,hy'⟩ : Subtype s)) := by + cases hp + cases hr + rfl + +def dimensionProduct (d : I → ℕ) : + (Σ s : DimensionSplit d,{x : A // δ x=s.left} × {y : B // ε y=s.right}) ≃ + {p : A×B // δ p.1+ε p.2=d} where + toFun x:=⟨(x.2.1.val,x.2.2.val),by rw [x.2.1.property,x.2.2.property,DimensionSplit.left_add_right]⟩ + invFun p:=⟨DimensionSplit.ofPair (δ p.val.1) (ε p.val.2) p.property, + ⟨p.val.1,rfl⟩,⟨p.val.2,(DimensionSplit.right_ofPair _ _ _).symm⟩⟩ + right_inv p:=rfl + left_inv x:=by + rcases x with ⟨s,⟨x,hx⟩,⟨y,hy⟩⟩ + dsimp only + have hs : DimensionSplit.ofPair (δ x) (ε y) (by rw [hx,hy,DimensionSplit.left_add_right])=s := by + apply DimensionSplit.ext + exact hx + apply Sigma.ext hs + exact subtypePair_heq (congrArg (fun t : DimensionSplit d=>fun z=>δ z=t.left) hs) + (congrArg (fun t : DimensionSplit d=>fun z=>ε z=t.right) hs) x y _ _ _ _ + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/EulerForm.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/EulerForm.lean new file mode 100644 index 0000000000000000000000000000000000000000..b78003c87999a3deaf4c6ae230b0cfd21f38cd15 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/EulerForm.lean @@ -0,0 +1,218 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SymmetricSpace +import OAI.Combinatorics.Chromatic.GradedAlgebra.DegreeSet + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.Homogeneity +variable {I : Type*} [Fintype I] [DecidableEq I] + +def eulerForm (a : I → I → ℕ) (d e : I → ℕ) : ℤ := + (∑ i,(d i:ℤ)*e i) - ∑ i, ∑ j,(a i j:ℤ)*d i*e j + +lemma diagonal_homogeneous {σ : Type*} (i j : σ) : + (diagonal i j : MvPolynomial σ ℚ).IsWeightedHomogeneous (fun _=>(1:ℤ)) 1 := + (isWeightedHomogeneous_X ℚ (fun _=>(1:ℤ)) j).sub + (isWeightedHomogeneous_X ℚ (fun _=>(1:ℤ)) i) + +omit [Fintype I] [DecidableEq I] in +lemma cutFactor_homogeneous {d e : I → ℕ} (A : Cut d e) (i j : I) (k : ℕ) : + (cutFactor A i j k).IsWeightedHomogeneous (fun _=>(1:ℤ)) ((d i:ℤ)*e j*k) := by + classical + unfold cutFactor + have h := IsWeightedHomogeneous.prod (A i).val _ _ (fun x _=> + IsWeightedHomogeneous.prod (A j).valᶜ _ _ + (fun y _=> (diagonal_homogeneous (⟨i,x⟩ : Σi,Fin (d i+e i)) ⟨j,y⟩).pow k)) + convert h using 1 + simp only [Finset.sum_const,nsmul_eq_mul,mul_one,(A i).property,right_card] + ring + +omit [DecidableEq I] in +lemma cutDenominator_homogeneous {d e : I → ℕ} (A : Cut d e) : + (cutDenominator A).IsWeightedHomogeneous (fun _=>(1:ℤ)) (∑ i,(d i:ℤ)*e i) := by + unfold cutDenominator + simpa only [Nat.cast_one,mul_one] using IsWeightedHomogeneous.prod Finset.univ _ _ + (fun i _=> cutFactor_homogeneous A i i 1) + +omit [DecidableEq I] in +lemma cutNumerator_homogeneous (a : I → I → ℕ) {d e : I → ℕ} (A : Cut d e) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) + {m n : ℤ} (hf : f.IsWeightedHomogeneous (fun _=>(1:ℤ)) m) + (hg : g.IsWeightedHomogeneous (fun _=>(1:ℤ)) n) : + (cutNumerator a A f g).IsWeightedHomogeneous (fun _=>(1:ℤ)) + (m+n+ ∑ i, ∑ j,(a i j:ℤ)*d i*e j) := by + unfold cutNumerator + have h := (constantWeight_rename (leftInput A) f hf).mul + (constantWeight_rename (rightInput A) g hg) + have hk := IsWeightedHomogeneous.prod Finset.univ _ _ (fun i _=> + IsWeightedHomogeneous.prod Finset.univ _ _ + (fun j _=> cutFactor_homogeneous A i j (a i j))) + have heq : (∑ i, ∑ j,(d i:ℤ)*e j*a i j) = + ∑ i, ∑ j,(a i j:ℤ)*d i*e j := by + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + ring + rw [heq] at hk + exact h.mul hk + +omit [DecidableEq I] in +lemma naturalVandermonde_homogeneous (d : I → ℕ) : + (naturalVandermonde d (fun _=>True)).IsWeightedHomogeneous (fun _=>(1:ℤ)) + (naturalPairs d (fun _=>True)).card := by + classical + rw [naturalVandermonde_product] + simpa using IsWeightedHomogeneous.prod (naturalPairs d (fun _=>True)) _ _ + (fun p _=> diagonal_homogeneous (finPackPair d p).1 (finPackPair d p).2) + +theorem shufflePolynomial_homogeneous (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g : S e) {m n : ℤ} + (hf : f.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) m) + (hg : g.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) n) : + (shufflePolynomial a f g).val.IsWeightedHomogeneous (fun _=>(1:ℤ)) + (m+n-eulerForm a d e) := by + classical + let V := naturalVandermonde (d+e) (fun _=>True) + let v : ℤ := (naturalPairs (d+e) (fun _=>True)).card + have hV : V.IsWeightedHomogeneous (fun _=>(1:ℤ)) v := naturalVandermonde_homogeneous _ + have hV0 : V≠0 := naturalVandermonde_ne_zero _ _ + have hb : ∀ A : Cut d e, ∃ b, V = cutDenominator A * b := fun A=> cutDenominator_dvd A + choose b hb using hb + have hbhome (A : Cut d e) : (b A).IsWeightedHomogeneous (fun _=>(1:ℤ)) + (v- ∑ i,(d i:ℤ)*e i) := + Homogeneity.of_mul (cutDenominator A) (b A) (cutDenominator_homogeneous A) + (cutDenominator_ne_zero A) (by rw [← hb]; exact hV) + have hclear : V*(shufflePolynomial a f g).val = ∑ A : Cut d e,b A*cutNumerator a A f.val g.val := by + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + rw [map_mul,shufflePolynomial_eq,rawShuffle,Finset.mul_sum,map_sum] + apply Finset.sum_congr rfl + intro A hA + rw [hb A,map_mul,map_mul] + have hden : algebraMap _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + (cutDenominator A) ≠ 0 := + by + intro hz + apply cutDenominator_ne_zero A + exact (IsFractionRing.injective (MvPolynomial (Σi,Fin (d i+e i)) ℚ) + (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ))) (by simpa only [map_zero] using hz) + let φ := algebraMap (MvPolynomial (Σi,Fin (d i+e i)) ℚ) + (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + change (φ (cutDenominator A) * φ (b A)) * + (φ (cutNumerator a A f.val g.val) / φ (cutDenominator A)) = + φ (b A) * φ (cutNumerator a A f.val g.val) + change φ (cutDenominator A) ≠ 0 at hden + field_simp + have hhom : (V*(shufflePolynomial a f g).val).IsWeightedHomogeneous + (fun _=>(1:ℤ)) (v+(m+n-eulerForm a d e)) := by + rw [hclear] + apply IsWeightedHomogeneous.sum + intro A hA + convert (hbhome A).mul (cutNumerator_homogeneous a A f.val g.val hf hg) using 1 + simp only [eulerForm] + ring + have hh := Homogeneity.of_mul V (shufflePolynomial a f g).val hV hV0 hhom + simpa only [add_sub_cancel_left] using hh + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.Homogeneity +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def componentS (d : I → ℕ) (k : ℤ) : S d →ₗ[ℚ] S d where + toFun f := ⟨weightedHomogeneousComponent (fun _=>(1:ℤ)) k f.val, by + intro σ + rw [constantWeight_component_rename,f.property σ]⟩ + map_add' f g := Subtype.ext (map_add _ _ _) + map_smul' r f := Subtype.ext (map_smul _ _ _) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma componentS_val (d : I → ℕ) (k : ℤ) (f : S d) : + (componentS d k f).val = weightedHomogeneousComponent (fun _=>(1:ℤ)) k f.val := rfl + +omit [Fintype I] [DecidableEq I] in +lemma componentS_homogeneous (d : I → ℕ) (k : ℤ) (f : S d) : + (componentS d k f).val.IsWeightedHomogeneous (fun _=>(1:ℤ)) k := + weightedHomogeneousComponent_isWeightedHomogeneous _ _ + +omit [Fintype I] [DecidableEq I] in +lemma sum_componentS (d : I → ℕ) (f : S d) : + ∑ k ∈ degreeSet f.val,componentS d k f = f := by + apply Subtype.ext + change (symmetricSpace d).val (∑ k ∈ degreeSet f.val,componentS d k f) = f.val + rw [map_sum] + exact sum_components f.val + +omit [Fintype I] [DecidableEq I] in +lemma componentS_of_homogeneous (d : I → ℕ) (f : S d) {m : ℤ} + (hf : f.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) m) (k : ℤ) : + componentS d k f = if k=m then f else 0 := by + classical + apply Subtype.ext + change weightedHomogeneousComponent (fun _=>(1:ℤ)) k f.val = _ + rw [weightedHomogeneousComponent_of_mem hf] + split_ifs <;> rfl + +omit [Fintype I] [DecidableEq I] in +lemma componentS_dimensionCast {d e : I → ℕ} (h : d=e) (k : ℤ) (f : S d) : + componentS e k (dimensionCast h f) = dimensionCast h (componentS d k f) := by + subst e + rfl + +omit [Fintype I] [DecidableEq I] in +lemma homogeneous_dimensionCast {d e : I → ℕ} (h : d=e) (f : S d) {k : ℤ} + (hf : f.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) k) : + (dimensionCast h f).val.IsWeightedHomogeneous (fun _=>(1:ℤ)) k := by + subst e + exact hf + +lemma shuffleLinear_apply (a : I → I → ℕ) (d e : I → ℕ) (f : S d) (g : S e) : + shuffleLinear a d e f g = shufflePolynomial a f g := rfl + +lemma shuffle_sum_components (a : I → I → ℕ) {d e : I → ℕ} (f : S d) (g : S e) : + shufflePolynomial a f g = + ∑ k ∈ degreeSet f.val, ∑ l ∈ degreeSet g.val, + shufflePolynomial a (componentS d k f) (componentS e l g) := by + change shuffleLinear a d e f g = _ + conv_lhs => rw [← sum_componentS d f,← sum_componentS e g] + simp only [map_sum,LinearMap.sum_apply,shuffleLinear_apply] + rw [Finset.sum_comm] + +theorem componentS_destabilizing_mem (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k : ℤ) (f : S d) (hf : f ∈ destabilizingSpace a μ d) : + componentS d k f ∈ destabilizingSpace a μ d := by + classical + apply Submodule.span_induction (p:=fun x _=> componentS d k x ∈ destabilizingSpace a μ d) + ?_ ?_ ?_ ?_ hf + · intro F hF + obtain ⟨u,v,h,f,g,hu,hv,hμ,rfl⟩ := hF + rw [shuffle_sum_components a f g,map_sum,map_sum] + apply Submodule.sum_mem + intro i hi + rw [map_sum,map_sum] + apply Submodule.sum_mem + intro j hj + have hhom := homogeneous_dimensionCast h + (shufflePolynomial a (componentS u i f) (componentS v j g)) + (shufflePolynomial_homogeneous a _ _ (componentS_homogeneous u i f) + (componentS_homogeneous v j g)) + rw [componentS_of_homogeneous _ _ hhom] + split_ifs + · apply Submodule.subset_span + exact ⟨u,v,h,componentS u i f,componentS v j g,hu,hv,hμ,rfl⟩ + · exact Submodule.zero_mem _ + · simp + · intro x y hx hy hxc hyc + simpa only [map_add] using (destabilizingSpace a μ d).add_mem hxc hyc + · intro r x hx hxc + simpa only [map_smul] using (destabilizingSpace a μ d).smul_mem r hxc + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/ExtendPolynomial.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/ExtendPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..c83e71cba31d18a3e0c6a4e9937c81c473ac89a4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/ExtendPolynomial.lean @@ -0,0 +1,134 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.RestrictionB + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct + +noncomputable def extendPolynomial {A B α β : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (f : A →ₐ[ℚ] B) (j : α → β) : + MvPolynomial α A →ₐ[ℚ] MvPolynomial β B := + ((rename j).restrictScalars ℚ).comp (mapAlgHom f) + +@[simp] lemma extendPolynomial_C {A B α β : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (f : A →ₐ[ℚ] B) (j : α → β) (a : A) : + extendPolynomial f j (C a) = C (f a) := by + simp [extendPolynomial] + +@[simp] lemma extendPolynomial_X {A B α β : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (f : A →ₐ[ℚ] B) (j : α → β) (i : α) : + extendPolynomial f j (X i) = X (j i) := by + simp [extendPolynomial] + +lemma extendPolynomial_map {A B C α β : Type*} [CommRing A] [CommRing B] [CommRing C] + [Algebra ℚ A] [Algebra ℚ B] [Algebra ℚ C] + (f : A →ₐ[ℚ] B) (g : B →ₐ[ℚ] C) (j : α → β) (p : MvPolynomial α A) : + map g.toRingHom (extendPolynomial f j p) = extendPolynomial (g.comp f) j p := by + simp only [extendPolynomial,AlgHom.comp_apply,AlgHom.restrictScalars_apply, + mapAlgHom_apply,map_rename,map_map,AlgHom.toRingHom_eq_coe] + rfl + +lemma extendPolynomial_preMap {A B C α β : Type*} [CommRing A] [CommRing B] [CommRing C] + [Algebra ℚ A] [Algebra ℚ B] [Algebra ℚ C] + (f : A →ₐ[ℚ] B) (g : B →ₐ[ℚ] C) (j : α → β) (p : MvPolynomial α A) : + extendPolynomial g j (map f.toRingHom p) = extendPolynomial (g.comp f) j p := by + simp only [extendPolynomial,AlgHom.comp_apply,AlgHom.restrictScalars_apply, + mapAlgHom_apply,map_map,AlgHom.toRingHom_eq_coe] + rfl + +lemma toMvPolynomial_map {A B α : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (f : A →ₐ[ℚ] B) (i : α) (p : Polynomial A) : + map f.toRingHom (Polynomial.toMvPolynomial i p) = + Polynomial.toMvPolynomial i (Polynomial.map f.toRingHom p) := by + induction p using Polynomial.induction_on' with + | add p q hp hq => simp only [map_add,Polynomial.map_add,hp,hq] + | monomial n a => simp [← Polynomial.C_mul_X_pow_eq_monomial] + +end ElementaryPositivity.RawShuffle.SplitTree + +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +@[reducible] def Centers : SplitTree I → Type + | .leaf _ => Unit + | .node l r => l.Centers ⊕ r.Centers + +noncomputable def centerTranslation (A : (I → ℕ) → CommAlgCat.{u} ℚ) + (τ : ∀ d, A d →ₐ[ℚ] Polynomial (A d)) : + (T : SplitTree I) → tensor A T →ₐ[ℚ] MvPolynomial T.Centers (tensor A T) + | .leaf d => ((Polynomial.toMvPolynomial ()).restrictScalars ℚ).comp (τ d) + | .node l r => + let L := (extendPolynomial (Algebra.TensorProduct.includeLeft : + tensor A l →ₐ[ℚ] tensor A l ⊗[ℚ] tensor A r) Sum.inl).comp (centerTranslation A τ l) + let R := (extendPolynomial (Algebra.TensorProduct.includeRight : + tensor A r →ₐ[ℚ] tensor A l ⊗[ℚ] tensor A r) Sum.inr).comp (centerTranslation A τ r) + Algebra.TensorProduct.lift (S:=ℚ) L R (fun x y => mul_comm (L x) (R y)) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma centerTranslation_tmul (A : (I → ℕ) → CommAlgCat.{u} ℚ) + (τ : ∀ d, A d →ₐ[ℚ] Polynomial (A d)) (l r : SplitTree I) + (x : tensor A l) (y : tensor A r) : + centerTranslation A τ (.node l r) (x ⊗ₜ[ℚ] y) = + extendPolynomial (Algebra.TensorProduct.includeLeft : + tensor A l →ₐ[ℚ] tensor A l ⊗[ℚ] tensor A r) Sum.inl (centerTranslation A τ l x) * + extendPolynomial (Algebra.TensorProduct.includeRight : + tensor A r →ₐ[ℚ] tensor A l ⊗[ℚ] tensor A r) Sum.inr (centerTranslation A τ r y) := by + rfl + +omit [Fintype I] [DecidableEq I] in +lemma centerTranslation_natural (A C : (I → ℕ) → CommAlgCat.{u} ℚ) + (f : ∀ d, A d →ₐ[ℚ] C d) + (τ : ∀ d, A d →ₐ[ℚ] Polynomial (A d)) (υ : ∀ d, C d →ₐ[ℚ] Polynomial (C d)) + (h : ∀ d x, Polynomial.map (f d).toRingHom (τ d x) = υ d (f d x)) + (T : SplitTree I) (x : tensor A T) : + map (tensorMap A C f T).toRingHom (centerTranslation A τ T x) = + centerTranslation C υ T (tensorMap A C f T x) := by + induction T with + | leaf d => + change map (f d).toRingHom (Polynomial.toMvPolynomial () (τ d x)) = + Polynomial.toMvPolynomial () (υ d (f d x)) + rw [toMvPolynomial_map,h] + | node l r ihl ihr => + induction x using TensorProduct.inductionOn with + | tmul x y => + change map (Algebra.TensorProduct.map (tensorMap A C f l) (tensorMap A C f r)).toRingHom + (centerTranslation A τ (.node l r) (x ⊗ₜ[ℚ] y)) = + centerTranslation C υ (.node l r) (tensorMap A C f l x ⊗ₜ[ℚ] tensorMap A C f r y) + erw [centerTranslation_tmul,centerTranslation_tmul,map_mul] + rw [extendPolynomial_map,extendPolynomial_map,← ihl x,← ihr y, + extendPolynomial_preMap,extendPolynomial_preMap] + rw [Algebra.TensorProduct.map_comp_includeLeft, Algebra.TensorProduct.map_comp_includeRight] + | add x y hx hy => simp only [map_add,hx,hy] + +noncomputable def rawCenteredRestriction (T : SplitTree I) : + S T.dim →ₐ[ℚ] MvPolynomial T.Centers (tensor rawFamily T) := + (centerTranslation rawFamily taylorS T).comp (rawRestriction T) + +noncomputable def centeredRestrictionB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0Polynomial.C (X (Sum.inl x))+Polynomial.X) + (fun y=>Polynomial.C (X (Sum.inr y)))) + +noncomputable def fourAffine (d₁ e₁ d₂ e₂ : I → ℕ) + (i j : I) (x : Fin (d₁ i)⊕Fin (e₁ i)) (y : Fin (d₂ j)⊕Fin (e₂ j)) := + affineUnit (fourForwardDifference d₁ e₁ d₂ e₂ i j x y) + +omit [Fintype I] [DecidableEq I] in +lemma polynomial_fourRelative_difference (d₁ e₁ d₂ e₂ : I → ℕ) + (i j : I) (x : Fin (d₁ i)⊕Fin (e₁ i)) (y : Fin (d₂ j)⊕Fin (e₂ j)) : + polynomial (fourRelativeRaw d₁ e₁ d₂ e₂ (fourForwardDifference d₁ e₁ d₂ e₂ i j x y))= + (fourAffine d₁ e₁ d₂ e₂ i j x y).val := by + simp only [fourAffine,affineUnit_val,fourForwardDifference,fourRelativeRaw, + map_sub,aeval_X,Sum.elim_inl,Sum.elim_inr,map_add,polynomial_C,polynomial_X] + ring + +noncomputable def fourClearingUnit (d₁ e₁ d₂ e₂ : I → ℕ) := + rectangular (fun i j : I=>if i=j then 1 else 0) (fourAffine d₁ e₁ d₂ e₂) + +noncomputable def fourTotalInverseUnit (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) := + rectangular (SeparationInfinity.inverseExponent a) (fourAffine d₁ e₁ d₂ e₂) + +noncomputable def fourCrossAffineUnit (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) := + (-1 : (LaurentSeries (MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ))ˣ) ^ (∑ i,e₁ i*d₂ i) * + rectangular (fun i j : I=>if i=j then 1 else 0) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inl x) (.inl y)) * + rectangular (fun i j : I=>if i=j then 1 else 0) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inr y)) * + rectangular (fun i j=>(a i j:ℤ)) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inl x) (.inr y)) * + rectangular (fun i j=>(a i j:ℤ)) + (fun i j x y=>-fourAffine d₁ e₁ d₂ e₂ j i (.inr y) (.inl x)) + +lemma polynomial_fourRelative_cross (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + polynomial (fourRelativeRaw d₁ e₁ d₂ e₂ (fourCrossPolynomial a d₁ e₁ d₂ e₂))= + (fourCrossAffineUnit a d₁ e₁ d₂ e₂).val := by + rw [fourCrossPolynomial_explicit] + simp only [map_mul,map_pow,map_neg,map_one,map_prod,polynomial_fourRelative_difference] + unfold fourCrossAffineUnit + rw [rectangular_diagonal,rectangular_diagonal] + simp only [rectangular,zpow_natCast,Units.val_mul,Units.val_pow_eq_pow_val,Units.val_neg, + Units.val_one,Units.coe_prod] + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity +open scoped TensorProduct + +lemma tensor_map_projection {K A B A' B' : Type*} [CommSemiring K] + [CommRing A] [CommRing B] [CommRing A'] [CommRing B'] + [Algebra K A] [Algebra K B] [Algebra K A'] [Algebra K B'] + (T : A →ₗ[K] B) (U : A' →ₗ[K] B') (ι : B →ₐ[K] A) (κ : B' →ₐ[K] A') + (hT : ∀ b x,T (ι b*x)=b*T x) (hU : ∀ b x,U (κ b*x)=b*U x) + (b : B⊗[K]B') (x : A⊗[K]A') : + TensorProduct.map T U (Algebra.TensorProduct.map ι κ b*x)= + b*TensorProduct.map T U x := by + induction b using TensorProduct.inductionOn with + | add b c hb hc => simp only [map_add,add_mul,hb,hc] + | tmul b c => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [mul_add,map_add,hx,hy] + | tmul x y => + simp only [Algebra.TensorProduct.map_tmul,Algebra.TensorProduct.tmul_mul_tmul, + TensorProduct.map_tmul,hT,hU] + +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/FourBraiding.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/FourBraiding.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0eae9f4ed52c3b697756a8cccb61d08f0030818 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/FourBraiding.lean @@ -0,0 +1,212 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalFiltration +import OAI.Combinatorics.Chromatic.Walls.TensorMiddleFiltration + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open HahnSeries SeparationInfinity +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.LinearDetection +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +noncomputable local instance braidFourTensor (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + CommRing (B a μ d⊗[ℚ]B a μ e) := inferInstance +noncomputable local instance braidFourTensorAlg (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Algebra ℚ (B a μ d⊗[ℚ]B a μ e) := inferInstance +noncomputable local instance braidFourRing (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂)) := inferInstance +noncomputable local instance braidFourAlg (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂)) := inferInstance + +noncomputable local instance braidFourTensorN (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + NonUnitalNonAssocSemiring (B a μ d⊗[ℚ]B a μ e) := (braidFourTensor a μ d e).toNonUnitalNonAssocSemiring +noncomputable local instance braidFourTensorM (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Module (B a μ d⊗[ℚ]B a μ e) (B a μ d⊗[ℚ]B a μ e) := Semiring.toModule +noncomputable local instance braidFourN (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + NonUnitalNonAssocSemiring ((B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂)) := + (braidFourRing a μ d₁ e₁ d₂ e₂).toNonUnitalNonAssocSemiring +noncomputable local instance braidFourM (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Module ((B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂)) + ((B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂)) := Semiring.toModule + +noncomputable def crossingColumnBAlg (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + B a μ e₁⊗[ℚ]B a μ d₂ →ₐ[ℚ](B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂) := + middleEmbedding + +noncomputable def fourUnitalFiltration (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0braidingDifference_coeff_mul_unital_next a c η hc θ hχ e₁ d₂ + (v+w) (f⊗ₜ[ℚ]g) (tmul_mem_additiveTensorFiltration _ _ (le_refl _) hf hg) j) W x hx + +lemma map_sub_one_mul {R T : Type*} [Ring R] [Ring T] (f : R →+* T) (x : R) (y : T) : + f (x-1)*y=f x*y-y := by rw [map_sub,map_one,sub_mul,one_mul] + +lemma fourBraiding_coeff_next (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + obtain ⟨u,v,f,g,hw,hf,hg,rfl⟩:=hx + rw [TensorProduct.map_tmul,LinearMap.id_apply] + exact tmul_mem_additiveTensorFiltration _ _ hw + (unitalSourceFiltration_translation_mem a c η hc θ d u f hf t) hg + | zero => rw [map_zero]; exact Submodule.zero_mem _ + | add x y _ _ hx hy => rw [map_add]; exact Submodule.add_mem _ hx hy + | smul q x _ hx => rw [map_smul]; exact Submodule.smul_mem _ q hx + +noncomputable def unitalRestrictionRelativeB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0.resolve_left he + rw [unitalSourceFiltration_nonzero a c η hc θ (d+e) hde W] at hf + rw [unitalSourceTensorFiltration_nonzero a c η hc θ d e hd he] + have hn := separationCoefficient_negative_filtration a c η hc θ hχ d e hs' W (-j) (by omega) f hf + have heq : unitalRestrictionRelativeB a c η hc hs=restrictionRelativeB a c η hc hs' (firstCut d e) := by + unfold unitalRestrictionRelativeB restrictionRelativeB + congr 1 + simp only [unitalSeparationSeries,LinearMap.comp_apply,heq] + simpa only [separationCoefficient_eq_coeff,neg_neg,separationSeries,LinearMap.comp_apply] using hn +end SeparationInfinity +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/FourColumns.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/FourColumns.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e95d7e9a40cdc5dfd33f74e189b0573c791ea93 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/FourColumns.lean @@ -0,0 +1,278 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.BothTaylorB +import OAI.Combinatorics.Chromatic.Shuffle.FourAffineKernel + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.RectangularKernel +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable local instance columnTensorRing (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance columnTensorAlgebra (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance columnFourRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance +noncomputable local instance columnFourAlgebra (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance + +noncomputable def firstColumnAlg (d₁ e₁ d₂ e₂ : I → ℕ) : + S d₁⊗[ℚ] S d₂ →ₐ[ℚ] (S d₁⊗[ℚ] S e₁)⊗[ℚ](S d₂⊗[ℚ] S e₂) := + Algebra.TensorProduct.map Algebra.TensorProduct.includeLeft Algebra.TensorProduct.includeLeft + +noncomputable def secondColumnAlg (d₁ e₁ d₂ e₂ : I → ℕ) : + S e₁⊗[ℚ] S e₂ →ₐ[ℚ] (S d₁⊗[ℚ] S e₁)⊗[ℚ](S d₂⊗[ℚ] S e₂) := + Algebra.TensorProduct.map Algebra.TensorProduct.includeRight Algebra.TensorProduct.includeRight + +noncomputable def crossingColumnAlg (d₁ e₁ d₂ e₂ : I → ℕ) : + S e₁⊗[ℚ] S d₂ →ₐ[ℚ] (S d₁⊗[ℚ] S e₁)⊗[ℚ](S d₂⊗[ℚ] S e₂) := + Algebra.TensorProduct.map Algebra.TensorProduct.includeRight Algebra.TensorProduct.includeLeft + +def crossingColumnVars (d₁ e₁ d₂ e₂ : I → ℕ) : + CellVars e₁ d₂ → CellVars d₁ e₁⊕CellVars d₂ e₂ := + Sum.elim (Sum.inl ∘ Sum.inr) (Sum.inr ∘ Sum.inl) + +omit [Fintype I] [DecidableEq I] in +lemma fourValue_firstColumn (d₁ e₁ d₂ e₂ : I → ℕ) (x : S d₁⊗[ℚ]S d₂) : + fourValueAlg d₁ e₁ d₂ e₂ (firstColumnAlg d₁ e₁ d₂ e₂ x)= + rename (firstColumnVars d₁ e₁ d₂ e₂) (tensorValue d₁ d₂ x) := by + have h : ((fourValueAlg d₁ e₁ d₂ e₂).comp (firstColumnAlg d₁ e₁ d₂ e₂)).toLinearMap= + ((rename (firstColumnVars d₁ e₁ d₂ e₂)).comp (tensorValueAlg d₁ d₂)).toLinearMap := by + apply TensorProduct.ext' + intro u v + change fourValue d₁ e₁ d₂ e₂ ((u⊗ₜ[ℚ]1)⊗ₜ[ℚ](v⊗ₜ[ℚ]1))= + rename (firstColumnVars d₁ e₁ d₂ e₂) (tensorValue d₁ d₂ (u⊗ₜ[ℚ]v)) + simp only [fourValue_tmul,tensorValue_tmul,OneMemClass.coe_one,map_one,mul_one, + map_mul,rename_rename] + rfl + exact LinearMap.congr_fun h x + +omit [Fintype I] [DecidableEq I] in +lemma fourValue_secondColumn (d₁ e₁ d₂ e₂ : I → ℕ) (x : S e₁⊗[ℚ]S e₂) : + fourValueAlg d₁ e₁ d₂ e₂ (secondColumnAlg d₁ e₁ d₂ e₂ x)= + rename (secondColumnVars d₁ e₁ d₂ e₂) (tensorValue e₁ e₂ x) := by + have h : ((fourValueAlg d₁ e₁ d₂ e₂).comp (secondColumnAlg d₁ e₁ d₂ e₂)).toLinearMap= + ((rename (secondColumnVars d₁ e₁ d₂ e₂)).comp (tensorValueAlg e₁ e₂)).toLinearMap := by + apply TensorProduct.ext' + intro u v + change fourValue d₁ e₁ d₂ e₂ ((1⊗ₜ[ℚ]u)⊗ₜ[ℚ](1⊗ₜ[ℚ]v))= + rename (secondColumnVars d₁ e₁ d₂ e₂) (tensorValue e₁ e₂ (u⊗ₜ[ℚ]v)) + simp only [fourValue_tmul,tensorValue_tmul,OneMemClass.coe_one,map_one,one_mul, + map_mul,rename_rename] + rfl + exact LinearMap.congr_fun h x + +omit [Fintype I] [DecidableEq I] in +lemma fourValue_crossingColumn (d₁ e₁ d₂ e₂ : I → ℕ) (x : S e₁⊗[ℚ]S d₂) : + fourValueAlg d₁ e₁ d₂ e₂ (crossingColumnAlg d₁ e₁ d₂ e₂ x)= + rename (crossingColumnVars d₁ e₁ d₂ e₂) (tensorValue e₁ d₂ x) := by + have h : ((fourValueAlg d₁ e₁ d₂ e₂).comp (crossingColumnAlg d₁ e₁ d₂ e₂)).toLinearMap= + ((rename (crossingColumnVars d₁ e₁ d₂ e₂)).comp (tensorValueAlg e₁ d₂)).toLinearMap := by + apply TensorProduct.ext' + intro u v + change fourValue d₁ e₁ d₂ e₂ ((1⊗ₜ[ℚ]u)⊗ₜ[ℚ](v⊗ₜ[ℚ]1))= + rename (crossingColumnVars d₁ e₁ d₂ e₂) (tensorValue e₁ d₂ (u⊗ₜ[ℚ]v)) + simp only [fourValue_tmul,tensorValue_tmul,OneMemClass.coe_one,map_one,one_mul,mul_one, + map_mul,rename_rename] + rfl + exact LinearMap.congr_fun h x + +lemma fourColumns_product (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S d₁⊗[ℚ]S d₂) (g : S e₁⊗[ℚ]S e₂) : + firstColumnAlg d₁ e₁ d₂ e₂ f * secondColumnAlg d₁ e₁ d₂ e₂ g= + fourInterchange d₁ e₁ d₂ e₂ (f⊗ₜ[ℚ]g) := by + apply fourValue_injective + change fourValueAlg d₁ e₁ d₂ e₂ (_*_)=_ + rw [map_mul,fourValue_firstColumn,fourValue_secondColumn,fourValue_interchange] + +lemma rawKernel_rename {σ : Type*} (a : I → I → ℕ) (d e : I → ℕ) + (L : (Σ i,Fin (d i)) → σ) (R : (Σ i,Fin (e i)) → σ) : + Units.map (mapRing (rename (Sum.elim L R)).toRingHom).toMonoidHom + (SeparationInfinity.rawInverseKernelUnit a d e)= + rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>affineUnit (X (R ⟨j,y⟩)-X (L ⟨i,x⟩))) := by + simp only [SeparationInfinity.rawInverseKernelUnit,SeparationInfinity.rawFactor, + rectangular,map_prod,map_zpow,affineUnit_map,AlgHom.toRingHom_eq_coe,RingHom.coe_coe, + map_sub,rename_X,Sum.elim_inl,Sum.elim_inr] + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.TensorPolynomials +open scoped TensorProduct +variable {A B : Type*} [CommRing A] [CommRing B] [Algebra ℚ A] [Algebra ℚ B] + +noncomputable def tensorPolynomial (f : A →ₐ[ℚ] Polynomial A) (g : B →ₐ[ℚ] Polynomial B) : + A⊗[ℚ]B →ₐ[ℚ] Polynomial (A⊗[ℚ]B) := + let L := (Polynomial.mapAlgHom (Algebra.TensorProduct.includeLeft : A →ₐ[ℚ] A⊗[ℚ]B)).comp f + let R := (Polynomial.mapAlgHom (Algebra.TensorProduct.includeRight : B →ₐ[ℚ] A⊗[ℚ]B)).comp g + Algebra.TensorProduct.lift (S:=ℚ) L R (fun x y=>mul_comm (L x) (R y)) + +lemma tensorPolynomial_tmul (f : A →ₐ[ℚ] Polynomial A) (g : B →ₐ[ℚ] Polynomial B) + (x : A) (y : B) : + tensorPolynomial f g (x⊗ₜ[ℚ]y)= + Polynomial.map (Algebra.TensorProduct.includeLeft : A →ₐ[ℚ] A⊗[ℚ]B).toRingHom (f x)* + Polynomial.map (Algebra.TensorProduct.includeRight : B →ₐ[ℚ] A⊗[ℚ]B).toRingHom (g y) := by + rfl + +lemma eval_map {C D : Type*} [Semiring C] [Semiring D] [Algebra ℚ C] [Algebra ℚ D] + (φ : C →ₐ[ℚ] D) (p : Polynomial C) (t : ℚ) : + (Polynomial.map φ.toRingHom p).eval (algebraMap ℚ D t)=φ (p.eval (algebraMap ℚ C t)) := by + rw [Polynomial.eval_map] + calc + _ = Polynomial.eval₂ φ.toRingHom (φ (algebraMap ℚ C t)) p := + congrArg (fun x=>Polynomial.eval₂ φ.toRingHom x p) (φ.commutes t).symm + _ = _ := Polynomial.eval₂_at_apply φ.toRingHom (algebraMap ℚ C t) + +lemma tensorPolynomial_eval (f : A →ₐ[ℚ] Polynomial A) (g : B →ₐ[ℚ] Polynomial B) + (t : ℚ) (F : A →ₗ[ℚ] A) (G : B →ₗ[ℚ] B) + (hf : ∀ x,(f x).eval (algebraMap ℚ A t)=F x) + (hg : ∀ y,(g y).eval (algebraMap ℚ B t)=G y) (x : A⊗[ℚ]B) : + (tensorPolynomial f g x).eval (algebraMap ℚ (A⊗[ℚ]B) t)=TensorProduct.map F G x := by + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,Polynomial.eval_add,hx,hy] + | tmul x y => + rw [tensorPolynomial_tmul,Polynomial.eval_mul,eval_map,eval_map,hf,hg] + simp + +end ElementaryPositivity.TensorPolynomials + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.CommonTranslation ElementaryPositivity.TensorPolynomials +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable local instance taylorTensorRing (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance taylorTensorAlgebra (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance taylorFourRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance +noncomputable local instance taylorFourAlgebra (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance + +noncomputable local instance taylorTensorNonUnital (d e : I → ℕ) : + NonUnitalNonAssocSemiring (S d⊗[ℚ]S e) := (taylorTensorRing d e).toNonUnitalNonAssocSemiring +noncomputable local instance taylorFourNonUnital (d₁ e₁ d₂ e₂ : I → ℕ) : + NonUnitalNonAssocSemiring ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := + (taylorFourRing d₁ e₁ d₂ e₂).toNonUnitalNonAssocSemiring + +noncomputable def commonTaylorTensor (d e : I → ℕ) : + S d⊗[ℚ]S e →ₐ[ℚ] Polynomial (S d⊗[ℚ]S e) := + tensorPolynomial (taylorS d) (taylorS e) + +omit [Fintype I] [DecidableEq I] in +lemma commonTaylorTensor_eval (d e : I → ℕ) (t : ℚ) (x : S d⊗[ℚ]S e) : + (commonTaylorTensor d e x).eval (algebraMap ℚ (S d⊗[ℚ]S e) t)= + TensorProduct.map (translationS d t) (translationS e t) x := + tensorPolynomial_eval _ _ t _ _ (fun x=>taylorS_eval d x t) (fun y=>taylorS_eval e y t) x + +omit [Fintype I] [DecidableEq I] in +lemma map_commonTaylorTensor (d e : I → ℕ) (x : S d⊗[ℚ] S e) : + Polynomial.map (tensorValueAlg d e).toRingHom (commonTaylorTensor d e x)= + taylor (tensorValue d e x) := by + apply polynomial_eq_of_rat_evals + intro t + rw [eval_map_rat,commonTaylorTensor_eval] + change tensorValue d e (TensorProduct.map (translationS d t) (translationS e t) x)= + (taylor (tensorValue d e x)).eval (C t) + rw [tensorValue_translation,taylor_eval] + rfl + +noncomputable def fourRelativeTaylor (d₁ e₁ d₂ e₂ : I → ℕ) : + (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂) →ₐ[ℚ] + Polynomial ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := + tensorPolynomial (commonTaylorTensor d₁ e₁) Polynomial.CAlgHom + +omit [Fintype I] [DecidableEq I] in +lemma fourRelativeTaylor_eval (d₁ e₁ d₂ e₂ : I → ℕ) (t : ℚ) + (x : (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) : + (fourRelativeTaylor d₁ e₁ d₂ e₂ x).eval (algebraMap ℚ _ t)= + TensorProduct.map (TensorProduct.map (translationS d₁ t) (translationS e₁ t)) + (LinearMap.id : (S d₂⊗[ℚ]S e₂) →ₗ[ℚ] (S d₂⊗[ℚ]S e₂)) x := + tensorPolynomial_eval _ _ t _ _ (commonTaylorTensor_eval d₁ e₁ t) + (fun _=>Polynomial.eval_C) x + +omit [Fintype I] [DecidableEq I] in +lemma fourRelativeTaylor_tmul (d₁ e₁ d₂ e₂ : I → ℕ) + (x : S d₁⊗[ℚ]S e₁) (y : S d₂⊗[ℚ]S e₂) : + fourRelativeTaylor d₁ e₁ d₂ e₂ (x⊗ₜ[ℚ]y)= + Polynomial.map (Algebra.TensorProduct.includeLeft : (S d₁⊗[ℚ]S e₁) →ₐ[ℚ] + (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)).toRingHom (commonTaylorTensor d₁ e₁ x)* + Polynomial.C ((1 : S d₁⊗[ℚ]S e₁)⊗ₜ[ℚ]y) := by + change tensorPolynomial (commonTaylorTensor d₁ e₁) Polynomial.CAlgHom (x⊗ₜ[ℚ]y)=_ + rw [tensorPolynomial_tmul] + congr 1 + change Polynomial.map _ (Polynomial.C y)=Polynomial.C _ + rw [Polynomial.map_C] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma fourRelativeRaw_left (d₁ e₁ d₂ e₂ : I → ℕ) (f : MvPolynomial (CellVars d₁ e₁) ℚ) : + fourRelativeRaw d₁ e₁ d₂ e₂ (rename Sum.inl f)= + Polynomial.map (rename (R:=ℚ) Sum.inl).toRingHom (taylor f) := by + induction f using MvPolynomial.induction_on with + | C r => simp [fourRelativeRaw] + | add f g hf hg => simp only [map_add,Polynomial.map_add,hf,hg] + | mul_X f i hf => + simp only [map_mul,rename_X,taylor_X,Polynomial.map_mul,hf] + congr 1 + simp [fourRelativeRaw] + +omit [Fintype I] [DecidableEq I] in +lemma fourRelativeRaw_right (d₁ e₁ d₂ e₂ : I → ℕ) (f : MvPolynomial (CellVars d₂ e₂) ℚ) : + fourRelativeRaw d₁ e₁ d₂ e₂ (rename Sum.inr f)=Polynomial.C (rename Sum.inr f) := by + induction f using MvPolynomial.induction_on with + | C r => simp [fourRelativeRaw] + | add f g hf hg => simp only [map_add,hf,hg] + | mul_X f i hf => + simp only [map_mul,rename_X,hf] + congr 1 + simp [fourRelativeRaw] + +omit [Fintype I] [DecidableEq I] in +lemma map_commonTaylorTensor_left (d₁ e₁ d₂ e₂ : I → ℕ) (x : S d₁⊗[ℚ]S e₁) : + Polynomial.map (fourValueAlg d₁ e₁ d₂ e₂).toRingHom + (Polynomial.map (Algebra.TensorProduct.includeLeft : (S d₁⊗[ℚ]S e₁) →ₐ[ℚ] + (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)).toRingHom (commonTaylorTensor d₁ e₁ x))= + Polynomial.map (rename (R:=ℚ) Sum.inl).toRingHom (taylor (tensorValue d₁ e₁ x)) := by + rw [←map_commonTaylorTensor d₁ e₁ x,Polynomial.map_map,Polynomial.map_map] + congr 1 + apply RingHom.ext + intro g + change fourValue d₁ e₁ d₂ e₂ (g⊗ₜ[ℚ]1)=rename Sum.inl (tensorValue d₁ e₁ g) + rw [fourValue_tmul] + change _*rename Sum.inr (tensorValueAlg d₂ e₂ 1)=_ + rw [map_one,map_one,mul_one] + +omit [Fintype I] [DecidableEq I] in +lemma map_fourRelativeTaylor (d₁ e₁ d₂ e₂ : I → ℕ) + (x : (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) : + Polynomial.map (fourValueAlg d₁ e₁ d₂ e₂).toRingHom (fourRelativeTaylor d₁ e₁ d₂ e₂ x)= + fourRelativeRaw d₁ e₁ d₂ e₂ (fourValue d₁ e₁ d₂ e₂ x) := by + have H : ((Polynomial.mapAlgHom (fourValueAlg d₁ e₁ d₂ e₂)).comp + (fourRelativeTaylor d₁ e₁ d₂ e₂)).toLinearMap= + ((fourRelativeRaw d₁ e₁ d₂ e₂).comp (fourValueAlg d₁ e₁ d₂ e₂)).toLinearMap := by + apply TensorProduct.ext' + intro u v + change Polynomial.map (fourValueAlg d₁ e₁ d₂ e₂).toRingHom + (fourRelativeTaylor d₁ e₁ d₂ e₂ (u⊗ₜ[ℚ]v))= + fourRelativeRaw d₁ e₁ d₂ e₂ (fourValue d₁ e₁ d₂ e₂ (u⊗ₜ[ℚ]v)) + rw [fourRelativeTaylor_tmul,Polynomial.map_mul,map_commonTaylorTensor_left, + Polynomial.map_C,fourValue_tmul,map_mul,fourRelativeRaw_left,fourRelativeRaw_right] + congr 1 + change Polynomial.C (fourValue d₁ e₁ d₂ e₂ (1⊗ₜ[ℚ]v))=_ + rw [fourValue_tmul] + change Polynomial.C (rename Sum.inl (tensorValueAlg d₁ e₁ 1)*_)=_ + rw [map_one,map_one,one_mul] + exact LinearMap.congr_fun H x + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/FourKernelCancellation.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/FourKernelCancellation.lean new file mode 100644 index 0000000000000000000000000000000000000000..70116949a62b8d1ca55a7273aacce3e036d71cca --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/FourKernelCancellation.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.FourAffineKernel +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentSigns + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.RectangularKernel +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +lemma fourReverseRectangle (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + rectangular (fun i j=>(a i j:ℤ)) + (fun i j x y=>-fourAffine d₁ e₁ d₂ e₂ j i (.inr y) (.inl x))= + (-1 : (LaurentSeries (MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ))ˣ) ^ + (∑ i,∑ j,(a i j:ℤ)*(d₂ i:ℤ)*(e₁ j:ℤ)) * + rectangular (fun i j=>(a j i:ℤ)) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inl y)) := by + conv_lhs => arg 2; ext i j x y; rw [←neg_one_mul] + rw [rectangular_scalar_mul] + simp only [Fintype.card_fin] + congr 1 + exact rectangular_transpose (fun i j=>(a j i:ℤ)) _ + +lemma fourCrossAffineUnit_signed (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + fourCrossAffineUnit a d₁ e₁ d₂ e₂= + (-1 : (LaurentSeries (MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ))ˣ) ^ eulerForm a d₂ e₁ * + (rectangular (fun i j : I=>if i=j then 1 else 0) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inl x) (.inl y)) * + rectangular (fun i j : I=>if i=j then 1 else 0) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inr y)) * + rectangular (fun i j=>(a i j:ℤ)) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inl x) (.inr y)) * + rectangular (fun i j=>(a j i:ℤ)) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inl y))) := by + rw [fourCrossAffineUnit,fourReverseRectangle] + have he : ((∑ i,e₁ i*d₂ i : ℕ):ℤ)-(∑ i,∑ j,(a i j:ℤ)*(d₂ i:ℤ)*(e₁ j:ℤ))=eulerForm a d₂ e₁ := by + simp only [eulerForm,Nat.cast_sum,Nat.cast_mul] + congr 1 + exact Finset.sum_congr rfl (fun i hi=>mul_comm _ _) + rw [←he,←unit_neg_one_zpow_sub,zpow_natCast] + exact mul_sign_collect (G := (LaurentSeries (MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ))ˣ) _ _ _ _ _ _ + +lemma fourKernel_cancellation (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + fourTotalInverseUnit a d₁ e₁ d₂ e₂ * (fourClearingUnit d₁ e₁ d₂ e₂)⁻¹ * + fourCrossAffineUnit a d₁ e₁ d₂ e₂= + (-1 : (LaurentSeries (MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ))ˣ) ^ eulerForm a d₂ e₁ * + (rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inl x) (.inl y)) * + rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inr y)) * + (rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inl y)) * + (rectangular (SeparationInfinity.inverseExponent (fun i j=>a j i)) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inl y)))⁻¹)) := by + rw [fourCrossAffineUnit_signed] + rw [mul_left_comm] + apply congrArg (_ * ·) + exact four_rectangle_cancellation (fun i j : I=>if i=j then 1 else 0) + (fun i j=>(a i j:ℤ)) (fourAffine d₁ e₁ d₂ e₂) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/FourTensorKernel.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/FourTensorKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ba490f96c306299cfacb1701e975530e0e21348 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/FourTensorKernel.lean @@ -0,0 +1,328 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.ShuffleProjection +import OAI.Combinatorics.Chromatic.Shuffle.FourColumns +import OAI.Combinatorics.Chromatic.Shuffle.FourKernelCancellation + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial HahnSeries +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.RectangularKernel +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable local instance kernelTensorRing (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance kernelTensorDistrib (d e : I → ℕ) : + DistribSMul (S d⊗[ℚ]S e) (S d⊗[ℚ]S e) where + smul_add := mul_add +noncomputable local instance kernelTensorAlg (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance kernelFourRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance +noncomputable local instance kernelFourAlg (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance + +noncomputable local instance kernelTensorSelf (d e : I → ℕ) : + Module (S d⊗[ℚ]S e) (S d⊗[ℚ]S e) := Semiring.toModule +noncomputable local instance kernelTensorNonUnital (d e : I → ℕ) : + NonUnitalNonAssocSemiring (S d⊗[ℚ]S e) := (kernelTensorRing d e).toNonUnitalNonAssocSemiring +noncomputable local instance kernelFourNonUnital (d₁ e₁ d₂ e₂ : I → ℕ) : + NonUnitalNonAssocSemiring ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := + (kernelFourRing d₁ e₁ d₂ e₂).toNonUnitalNonAssocSemiring + +lemma realize_inverseKernelUnit_unit (a : I → I → ℕ) (d e : I → ℕ) : + Units.map (mapRing (tensorValueAlg d e).toRingHom).toMonoidHom + (SeparationInfinity.inverseKernelUnit a d e)=SeparationInfinity.rawInverseKernelUnit a d e := by + apply Units.ext + exact SeparationInfinity.realize_inverseKernelUnit a d e + +lemma fourKernel_lift_naturality (a : I → I → ℕ) (d e d₁ e₁ d₂ e₂ : I → ℕ) + (F : S d⊗[ℚ]S e →ₐ[ℚ] (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) + (r : CellVars d e → CellVars d₁ e₁⊕CellVars d₂ e₂) + (h : ∀ x,fourValueAlg d₁ e₁ d₂ e₂ (F x)=rename r (tensorValue d e x)) : + Units.map (mapRing (R:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (S:=MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ) (fourValueAlg d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (Units.map (mapRing (R:=S d⊗[ℚ]S e) (S:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) F.toRingHom).toMonoidHom (SeparationInfinity.inverseKernelUnit a d e))= + Units.map (mapRing (rename r).toRingHom).toMonoidHom (SeparationInfinity.rawInverseKernelUnit a d e) := by + apply Units.ext + apply HahnSeries.ext + funext k + change fourValueAlg d₁ e₁ d₂ e₂ (F ((SeparationInfinity.inverseKernelUnit a d e).val.coeff k))= + rename r ((SeparationInfinity.rawInverseKernelUnit a d e).val.coeff k) + rw [h] + have hr := congrArg (fun x : LaurentSeries (MvPolynomial (CellVars d e) ℚ)=>x.coeff k) + (SeparationInfinity.realize_inverseKernelUnit a d e) + exact congrArg (rename r) hr + +lemma fourKernel_restrictRows (a : I → I → ℕ) {d₁ e₁ d₂ e₂ : I → ℕ} + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + Units.map (mapRing (R:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (S:=MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ) (fourValueAlg d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (Units.map (mapRing (R:=S (d₁+e₁)⊗[ℚ]S (d₂+e₂)) (S:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (restrictRows d₁ e₁ d₂ e₂ A B).toRingHom).toMonoidHom + (SeparationInfinity.inverseKernelUnit a (d₁+e₁) (d₂+e₂)))= + fourTotalInverseUnit a d₁ e₁ d₂ e₂ := by + rw [fourKernel_lift_naturality a _ _ _ _ _ _ _ _ (fourValue_restrictRows A B)] + exact rowSplit_inverseKernel a A B + +lemma fourKernel_firstColumn (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Units.map (mapRing (R:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (S:=MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ) (fourValueAlg d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (Units.map (mapRing (R:=S d₁⊗[ℚ]S d₂) (S:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (SeparationInfinity.inverseKernelUnit a d₁ d₂))= + rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inl x) (.inl y)) := by + refine Eq.trans (fourKernel_lift_naturality a d₁ d₂ d₁ e₁ d₂ e₂ + ( firstColumnAlg d₁ e₁ d₂ e₂ ) _ (fourValue_firstColumn d₁ e₁ d₂ e₂)) ?_ + have he : firstColumnVars d₁ e₁ d₂ e₂ = + Sum.elim (Sum.inl ∘ Sum.inl) (Sum.inr ∘ Sum.inl) := by + funext x; cases x <;> rfl + rw [he] + have h := rawKernel_rename (σ:=CellVars d₁ e₁⊕CellVars d₂ e₂) a d₁ d₂ + (Sum.inl ∘ Sum.inl) (Sum.inr ∘ Sum.inl) + simpa only [fourAffine,fourForwardDifference,Function.comp_apply, + Equiv.sigmaSumDistrib_apply,Sum.map_inl,Sum.map_inr,firstColumnVars,secondColumnVars,crossingColumnVars] using h + +lemma fourKernel_secondColumn (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Units.map (mapRing (R:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (S:=MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ) (fourValueAlg d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (Units.map (mapRing (R:=S e₁⊗[ℚ]S e₂) (S:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (SeparationInfinity.inverseKernelUnit a e₁ e₂))= + rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inr y)) := by + refine Eq.trans (fourKernel_lift_naturality a e₁ e₂ d₁ e₁ d₂ e₂ + ( secondColumnAlg d₁ e₁ d₂ e₂ ) _ (fourValue_secondColumn d₁ e₁ d₂ e₂)) ?_ + have he : secondColumnVars d₁ e₁ d₂ e₂ = + Sum.elim (Sum.inl ∘ Sum.inr) (Sum.inr ∘ Sum.inr) := by + funext x; cases x <;> rfl + rw [he] + have h := rawKernel_rename (σ:=CellVars d₁ e₁⊕CellVars d₂ e₂) a e₁ e₂ + (Sum.inl ∘ Sum.inr) (Sum.inr ∘ Sum.inr) + simpa only [fourAffine,fourForwardDifference,Function.comp_apply, + Equiv.sigmaSumDistrib_apply,Sum.map_inl,Sum.map_inr,firstColumnVars,secondColumnVars,crossingColumnVars] using h + +lemma fourKernel_crossingColumn (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Units.map (mapRing (R:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (S:=MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ) (fourValueAlg d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (Units.map (mapRing (R:=S e₁⊗[ℚ]S d₂) (S:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (crossingColumnAlg d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (SeparationInfinity.inverseKernelUnit a e₁ d₂))= + rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inl y)) := by + refine Eq.trans (fourKernel_lift_naturality a e₁ d₂ d₁ e₁ d₂ e₂ + ( crossingColumnAlg d₁ e₁ d₂ e₂ ) _ (fourValue_crossingColumn d₁ e₁ d₂ e₂)) ?_ + have h := rawKernel_rename (σ:=CellVars d₁ e₁⊕CellVars d₂ e₂) a e₁ d₂ + (Sum.inl ∘ Sum.inr) (Sum.inr ∘ Sum.inl) + simpa only [fourAffine,fourForwardDifference,Function.comp_apply, + Equiv.sigmaSumDistrib_apply,Sum.map_inl,Sum.map_inr,firstColumnVars,secondColumnVars,crossingColumnVars] using h + +lemma fourTensor_cross_realize (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + mapRing (R:= (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) (S:=MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ) (fourValueAlg d₁ e₁ d₂ e₂).toRingHom + (polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ (fourCrossTensor a d₁ e₁ d₂ e₂)))= + (fourCrossAffineUnit a d₁ e₁ d₂ e₂).val := by + rw [polynomial_map,map_fourRelativeTaylor,fourValue_fourCrossTensor,polynomial_fourRelative_cross] + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial HahnSeries +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.RectangularKernel +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +noncomputable local instance cancelTensorRing (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance cancelTensorDistrib (d e : I → ℕ) : + DistribSMul (S d⊗[ℚ]S e) (S d⊗[ℚ]S e) where + smul_add := mul_add +noncomputable local instance cancelTensorAlg (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance cancelFourRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance +noncomputable local instance cancelFourAlg (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance + +noncomputable def mappedInverseKernel {R : Type*} [CommRing R] [Algebra ℚ R] + (a : I → I → ℕ) (d e : I → ℕ) (f : S d⊗[ℚ]S e →ₐ[ℚ] R) : (LaurentSeries R)ˣ := + Units.map (mapRing f.toRingHom).toMonoidHom (SeparationInfinity.inverseKernelUnit a d e) + +noncomputable local instance cancelTensorSelf (d e : I → ℕ) : + Module (S d⊗[ℚ]S e) (S d⊗[ℚ]S e) := Semiring.toModule +noncomputable local instance cancelTensorNonUnital (d e : I → ℕ) : + NonUnitalNonAssocSemiring (S d⊗[ℚ]S e) := (cancelTensorRing d e).toNonUnitalNonAssocSemiring +noncomputable local instance cancelFourNonUnital (d₁ e₁ d₂ e₂ : I → ℕ) : + NonUnitalNonAssocSemiring ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := + (cancelFourRing d₁ e₁ d₂ e₂).toNonUnitalNonAssocSemiring + +noncomputable local instance cancelSeriesRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing (LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂))) := inferInstance + +noncomputable def fourRowsInverseUnit (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : (LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)))ˣ := + mappedInverseKernel a (d₁+e₁) (d₂+e₂) (restrictRows d₁ e₁ d₂ e₂ A B) + +noncomputable def fourFirstInverseUnit (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)))ˣ := + mappedInverseKernel a d₁ d₂ (firstColumnAlg d₁ e₁ d₂ e₂) + +noncomputable def fourSecondInverseUnit (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)))ˣ := + mappedInverseKernel a e₁ e₂ (secondColumnAlg d₁ e₁ d₂ e₂) + +noncomputable def fourCrossingInverseUnit (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)))ˣ := + mappedInverseKernel a e₁ d₂ (crossingColumnAlg d₁ e₁ d₂ e₂) + +lemma fourTotalInverseUnit_zero (d₁ e₁ d₂ e₂ : I → ℕ) : + fourTotalInverseUnit (fun _ _ : I=>0) d₁ e₁ d₂ e₂=fourClearingUnit d₁ e₁ d₂ e₂ := by + unfold fourTotalInverseUnit fourClearingUnit + congr 1 + funext i j + simp only [SeparationInfinity.inverseExponent,Nat.cast_zero,sub_zero] + +noncomputable def fourSeriesValue (d₁ e₁ d₂ e₂ : I → ℕ) : + LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) →+* + LaurentSeries (MvPolynomial (CellVars d₁ e₁⊕CellVars d₂ e₂) ℚ) := + mapRing (fourValueAlg d₁ e₁ d₂ e₂).toRingHom + +lemma fourSeriesValue_injective (d₁ e₁ d₂ e₂ : I → ℕ) : + Function.Injective (fourSeriesValue d₁ e₁ d₂ e₂) := + mapRing_injective (fourValueAlg d₁ e₁ d₂ e₂).toRingHom (fourValue_injective d₁ e₁ d₂ e₂) + +lemma fourSeriesValue_rows (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + Units.map (fourSeriesValue d₁ e₁ d₂ e₂).toMonoidHom (fourRowsInverseUnit a d₁ e₁ d₂ e₂ A B)= + fourTotalInverseUnit a d₁ e₁ d₂ e₂ := fourKernel_restrictRows a A B + +lemma fourSeriesValue_first (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Units.map (fourSeriesValue d₁ e₁ d₂ e₂).toMonoidHom (fourFirstInverseUnit a d₁ e₁ d₂ e₂)= + rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inl x) (.inl y)) := + fourKernel_firstColumn a d₁ e₁ d₂ e₂ + +lemma fourSeriesValue_second (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Units.map (fourSeriesValue d₁ e₁ d₂ e₂).toMonoidHom (fourSecondInverseUnit a d₁ e₁ d₂ e₂)= + rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inr y)) := + fourKernel_secondColumn a d₁ e₁ d₂ e₂ + +lemma fourSeriesValue_crossing (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Units.map (fourSeriesValue d₁ e₁ d₂ e₂).toMonoidHom (fourCrossingInverseUnit a d₁ e₁ d₂ e₂)= + rectangular (SeparationInfinity.inverseExponent a) + (fun i j x y=>fourAffine d₁ e₁ d₂ e₂ i j (.inr x) (.inl y)) := + fourKernel_crossingColumn a d₁ e₁ d₂ e₂ + +lemma fourSeriesValue_cross (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + fourSeriesValue d₁ e₁ d₂ e₂ + (polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ (fourCrossTensor a d₁ e₁ d₂ e₂)))= + (fourCrossAffineUnit a d₁ e₁ d₂ e₂).val := fourTensor_cross_realize a d₁ e₁ d₂ e₂ + +lemma units_map_neg_one {R S : Type*} [Ring R] [Ring S] (f : R →+* S) : + Units.map f.toMonoidHom (-1 : Rˣ)=(-1 : Sˣ) := by + apply Units.ext + change f (-1) = -1 + rw [map_neg,map_one] + +lemma ring_map_unit_val {R S : Type*} [Ring R] [Ring S] (f : R →+* S) (u : Rˣ) : + f u.val = (Units.map f.toMonoidHom u).val := rfl + +lemma ring_map_inv_unit_val {R S : Type*} [Ring R] [Ring S] (f : R →+* S) (u : Rˣ) : + f (u⁻¹).val = ((Units.map f.toMonoidHom u)⁻¹).val := rfl + +lemma ring_map_signedUnits {R S : Type*} [CommRing R] [CommRing S] + (f : R →+* S) (A B C D : Rˣ) (w : ℤ) : + f (((-1)^w*(A*B*(C*D⁻¹))).val)= + ((-1)^w*(Units.map f.toMonoidHom A*Units.map f.toMonoidHom B* + (Units.map f.toMonoidHom C*(Units.map f.toMonoidHom D)⁻¹))).val := by + rw [ring_map_unit_val] + simp only [map_mul,map_inv,map_zpow,units_map_neg_one] + +lemma unitKernelCancellation_lift {R S : Type*} [CommRing R] [CommRing S] + (f : R →+* S) (hf : Function.Injective f) + (K L A B C D : Rˣ) (P : R) (k l a b c d p : Sˣ) + (hK : Units.map f.toMonoidHom K=k) (hL : Units.map f.toMonoidHom L=l) + (hA : Units.map f.toMonoidHom A=a) (hB : Units.map f.toMonoidHom B=b) + (hC : Units.map f.toMonoidHom C=c) (hD : Units.map f.toMonoidHom D=d) + (hP : f P=p.val) (w : ℤ) + (h : k*l⁻¹*p=(-1)^w*(a*b*(c*d⁻¹))) : + K.val*(L⁻¹).val*P=((-1)^w*(A*B*(C*D⁻¹))).val := by + apply hf + rw [map_mul,map_mul,hP] + simp only [ring_map_unit_val,map_mul,map_inv,map_zpow,units_map_neg_one,hK,hL,hA,hB,hC,hD] + exact congrArg Units.val h + +lemma unitKernelCancellation_lift2 {R S : Type*} [CommRing R] [CommRing S] + (f : R →+* S) (hf : Function.Injective f) + (K L A B C D : Rˣ) (P : R) (p : Sˣ) (hP : f P=p.val) (w : ℤ) + (h : Units.map f.toMonoidHom K*(Units.map f.toMonoidHom L)⁻¹*p= + (-1)^w*(Units.map f.toMonoidHom A*Units.map f.toMonoidHom B* + (Units.map f.toMonoidHom C*(Units.map f.toMonoidHom D)⁻¹))) : + K.val*(L⁻¹).val*P=((-1)^w*(A*B*(C*D⁻¹))).val := + unitKernelCancellation_lift f hf K L A B C D P _ _ _ _ _ _ p rfl rfl rfl rfl rfl rfl hP w h + +lemma fourSeriesValue_rows_val (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + fourSeriesValue d₁ e₁ d₂ e₂ (fourRowsInverseUnit a d₁ e₁ d₂ e₂ A B).val= + (fourTotalInverseUnit a d₁ e₁ d₂ e₂).val := + congrArg Units.val (fourSeriesValue_rows a d₁ e₁ d₂ e₂ A B) + +lemma fourSeriesValue_rows_inv_val (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + fourSeriesValue d₁ e₁ d₂ e₂ ((fourRowsInverseUnit a d₁ e₁ d₂ e₂ A B)⁻¹).val= + ((fourTotalInverseUnit a d₁ e₁ d₂ e₂)⁻¹).val := + congrArg (fun u=> (u⁻¹).val) (fourSeriesValue_rows a d₁ e₁ d₂ e₂ A B) + +noncomputable def fourTensorKernelRHS (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)))ˣ := + (-1)^eulerForm a d₂ e₁ * + (fourFirstInverseUnit a d₁ e₁ d₂ e₂ * fourSecondInverseUnit a d₁ e₁ d₂ e₂ * + (fourCrossingInverseUnit a d₁ e₁ d₂ e₂ * + (fourCrossingInverseUnit (fun i j=>a j i) d₁ e₁ d₂ e₂)⁻¹)) + +lemma fourSeriesValue_kernelRHS (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Units.map (fourSeriesValue d₁ e₁ d₂ e₂).toMonoidHom + (fourTensorKernelRHS a d₁ e₁ d₂ e₂)= + fourTotalInverseUnit a d₁ e₁ d₂ e₂ * (fourClearingUnit d₁ e₁ d₂ e₂)⁻¹ * + fourCrossAffineUnit a d₁ e₁ d₂ e₂ := by + apply Units.ext + change fourSeriesValue d₁ e₁ d₂ e₂ (fourTensorKernelRHS a d₁ e₁ d₂ e₂).val = _ + unfold fourTensorKernelRHS + rw [ring_map_signedUnits] + apply congrArg Units.val + refine Eq.trans ?_ (fourKernel_cancellation a d₁ e₁ d₂ e₂).symm + apply congrArg ((-1)^eulerForm a d₂ e₁ * ·) + exact congrArg₂ (· * ·) + (congrArg₂ (· * ·) (fourSeriesValue_first a d₁ e₁ d₂ e₂) + (fourSeriesValue_second a d₁ e₁ d₂ e₂)) + (congrArg₂ (· * ·) (fourSeriesValue_crossing a d₁ e₁ d₂ e₂) + (congrArg Inv.inv (fourSeriesValue_crossing (fun i j=>a j i) d₁ e₁ d₂ e₂))) + +lemma fourSeriesValue_kernelRHS_val (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + fourSeriesValue d₁ e₁ d₂ e₂ (fourTensorKernelRHS a d₁ e₁ d₂ e₂).val= + (fourTotalInverseUnit a d₁ e₁ d₂ e₂ * (fourClearingUnit d₁ e₁ d₂ e₂)⁻¹ * + fourCrossAffineUnit a d₁ e₁ d₂ e₂).val := + congrArg Units.val (fourSeriesValue_kernelRHS a d₁ e₁ d₂ e₂) + +lemma fourSeriesValue_kernelLHS (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + fourSeriesValue d₁ e₁ d₂ e₂ + ((fourRowsInverseUnit a d₁ e₁ d₂ e₂ A B).val * + ((fourRowsInverseUnit (fun _ _ : I=>0) d₁ e₁ d₂ e₂ A B)⁻¹).val * + polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ (fourCrossTensor a d₁ e₁ d₂ e₂)))= + (fourTotalInverseUnit a d₁ e₁ d₂ e₂ * (fourClearingUnit d₁ e₁ d₂ e₂)⁻¹ * + fourCrossAffineUnit a d₁ e₁ d₂ e₂).val := by + rw [(fourSeriesValue d₁ e₁ d₂ e₂).map_mul,(fourSeriesValue d₁ e₁ d₂ e₂).map_mul, + fourSeriesValue_rows_val,fourSeriesValue_rows_inv_val,fourTotalInverseUnit_zero,fourSeriesValue_cross] + rfl + +lemma fourTensorKernel_cancellation (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + (fourRowsInverseUnit a d₁ e₁ d₂ e₂ A B).val * + ((fourRowsInverseUnit (fun _ _ : I=>0) d₁ e₁ d₂ e₂ A B)⁻¹).val * + polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ (fourCrossTensor a d₁ e₁ d₂ e₂))= + (((-1 : (LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)))ˣ)^eulerForm a d₂ e₁) * + (fourFirstInverseUnit a d₁ e₁ d₂ e₂ * + fourSecondInverseUnit a d₁ e₁ d₂ e₂ * + (fourCrossingInverseUnit a d₁ e₁ d₂ e₂ * + (fourCrossingInverseUnit (fun i j=>a j i) d₁ e₁ d₂ e₂)⁻¹))).val := by + apply fourSeriesValue_injective d₁ e₁ d₂ e₂ + exact (fourSeriesValue_kernelLHS a d₁ e₁ d₂ e₂ A B).trans + (fourSeriesValue_kernelRHS_val a d₁ e₁ d₂ e₂).symm + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GeometricRootClosure.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GeometricRootClosure.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e7730a8e7ace17c40903b479deb24b7e86c5b6e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GeometricRootClosure.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.PrimitiveRootClosure +import OAI.Combinatorics.Chromatic.Shuffle.InputProduct + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {I J M : Type*} [Fintype I] [DecidableEq I] [Fintype J] [AddCommGroup M] +variable (Ω : M→+M→+ℤ) (hΩ : ∀p,Ω p p=0) +variable (p : I→M) (κ : I→ℤ) (ε : I→Bool) +variable (w : I→ℕ) [Fact (∀i,00≤Ω (p i) (p j))) +variable (C : (J→ℤ)→+M) (hroot : ∀d,HasRootDegree C (weight w d) (rootSum p d)) +variable (h : M→+ℝ) (θ : ℝ) (hh : ∀d,h (rootSum p d)=slopeValue c η θ d) +variable (V : M→Prop) (hv : ∀d∈slopeDimensions c η hc θ,V (rootSum p d)) + +include hΩ hc hp hn hall hl hroot hh hv in +theorem geometric_zero_rootClosure : + InPrecisionClosure LaurentRay.vUnit Ω (literalRootProducts Ω C V) + (PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) + ((l.map (literalAxis κ ε Ω (rootSum p) w)).prod)) := by + let a:=geometricQuiver Ω p ε + let : Fact (∀θ,SlopeEulerSymmetric a c η θ) := + ⟨geometricQuiver_symmetric Ω p ε hΩ c η hc t hp⟩ + have H:=literalInput_ordered a κ ε Ω (rootSum p) w + (geometricQuiver_euler Ω p ε hΩ) l hn hall + (geometricQuiver_pairwise Ω p ε hΩ l hn hl) + rw [←H] + exact finiteInput_zero_rootClosure a κ c η hc w Ω (rootSum p) C + (geometricQuiver_euler Ω p ε hΩ) hroot θ V hv h hh ε + (geometricQuiver_diag Ω p ε) +end +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic QuantumTorus WeightedTorusSeries WallUnits +noncomputable section +variable {I J M : Type*} [Fintype I] [DecidableEq I] [Fintype J] [AddCommGroup M] +variable (p : I→M) (w : I→ℕ) (C : (J→ℤ)→+M) + +lemma rootDegree_finset_sum {A : Type*} (s : Finset A) (n : A→ℕ) (m : A→M) + (h : ∀i∈s,HasRootDegree C (n i) (m i)) : + HasRootDegree C (∑i∈s,n i) (∑i∈s,m i) := by + classical + induction s using Finset.induction_on with + | empty=>simpa using rootDegree_zero C + | @insert a s ha ih=> + simp only [Finset.sum_insert ha] + exact rootDegree_add C (h a (by simp)) (ih (fun i hi=>h i (by simp [hi]))) + +omit [DecidableEq I] in +lemma rootSum_rootDegree (hp : ∀i,HasRootDegree C (w i) (p i)) (d : I→ℕ) : + HasRootDegree C (weight w d) (rootSum p d) := by + exact rootDegree_finset_sum C Finset.univ (fun i=>d i*w i) (fun i=>d i • p i) + (fun i _=>rootDegree_nsmul C (hp i) (d i)) + +omit [DecidableEq I] in +lemma rootSum_mem (V : AddSubmonoid M) (hp : ∀i,p i∈V) (d : I→ℕ) : rootSum p d∈V := by + exact V.sum_mem (fun i _=>V.nsmul_mem (hp i) (d i)) + +omit [DecidableEq I] in +lemma rootSum_slope_zero (h : M→+ℝ) (c : I→ℝ) (d : I→ℕ) : + h (rootSum p d)=slopeValue c (fun i=>h (p i)) 0 d := by + simp only [rootSum,AddMonoidHom.coe_mk,ZeroHom.coe_mk,map_sum,map_nsmul, + slopeValue,zero_mul,sub_zero,mass,nsmul_eq_mul] +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalConvolutionQuotient.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalConvolutionQuotient.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7de86d87bbd1520c7e37859194eeef0686c7d5f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalConvolutionQuotient.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalShuffleCoalgebra + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0by + change convVanishes a c η hc θ n (f*g) + simpa only [zero_add] using convVanishes_mul a c η hc θ + (convVanishes_zero a c η hc θ f) hg) + (fun {f g} hf=>by + change convVanishes a c η hc θ n (f*g) + simpa only [add_zero] using convVanishes_mul a c η hc θ hf + (convVanishes_zero a c η hc θ g)) + +abbrev ConvolutionQuotient (n : ℕ) := (convolutionIdeal a c η hc θ (A := A) n).ringCon.Quotient + +noncomputable def convolutionProjection (n : ℕ) : + WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A) →ₐ[ℚ] ConvolutionQuotient a c η hc θ (A := A) n := + (convolutionIdeal a c η hc θ n).ringCon.mkₐ ℚ + +lemma convolutionProjection_eq_zero_iff (n : ℕ) + (f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)) : + convolutionProjection a c η hc θ n f=0 ↔ convVanishes a c η hc θ n f := by + have h := (convolutionIdeal a c η hc θ (A := A) n).ringCon.eq (a := f) (b := 0) + change convolutionProjection a c η hc θ n f=0 ↔ _ at h + apply h.trans + rw [←TwoSidedIdeal.mem_iff] + exact TwoSidedIdeal.mem_mk' _ _ _ _ _ _ f + +lemma convolutionProjection_eq_iff (n : ℕ) + (f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)) : + convolutionProjection a c η hc θ n f=convolutionProjection a c η hc θ n g ↔ + ∀ k : SlopeWeight c η hc θ, dimensionSize k.1.val < n → + ∀ x : unitalComponent a c η hc θ k, + f.ofConv (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x)= + g.ofConv (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x) := by + rw [←sub_eq_zero,←map_sub,convolutionProjection_eq_zero_iff] + simp only [convVanishes,WithConv.ofConv_sub,LinearMap.sub_apply,sub_eq_zero] + +lemma convolutionProjection_nilpotent (n : ℕ) + {f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hf : convVanishes a c η hc θ 1 f) : + (convolutionProjection a c η hc θ n f)^n=0 := by + rw [←map_pow,convolutionProjection_eq_zero_iff] + exact convVanishes_pow a c η hc θ hf n + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalConvolutionSeries.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalConvolutionSeries.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d24142d79bc717eb9aaa310b42cc503867e5af2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalConvolutionSeries.lean @@ -0,0 +1,194 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalConvolutionQuotient +import OAI.Combinatorics.Chromatic.GradedAlgebra.NilpotentLogarithm +import OAI.Combinatorics.Chromatic.GradedAlgebra.ConvolutionPostcomposition + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped DirectSum +open WithConv ElementaryPositivity.FiniteLog +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0∑ r ∈ Finset.range (dimensionSize k.1.val+1), + PowerSeries.coeff r p • (f^r).ofConv.comp (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k))) + +lemma convSeries_lof (f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)) + (p : PowerSeries ℚ) (k : SlopeWeight c η hc θ) (x : unitalComponent a c η hc θ k) : + (convSeries a c η hc θ f p).ofConv (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x)= + ∑ r ∈ Finset.range (dimensionSize k.1.val+1), PowerSeries.coeff r p • + (f^r).ofConv (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x) := by + rw [convSeries,ofConv_toConv,DirectSum.toModule_lof] + simp only [LinearMap.sum_apply,LinearMap.smul_apply,LinearMap.comp_apply] + +lemma convolutionProjection_series (n : ℕ) + {f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hf : convVanishes a c η hc θ 1 f) (p : PowerSeries ℚ) : + convolutionProjection a c η hc θ n (convSeries a c η hc θ f p)= + nilEval (convolutionProjection a c η hc θ n f) p := by + rw [nilEval_eq_sum (convolutionProjection_nilpotent a c η hc θ n hf)] + simp only [←map_pow,←map_smul,←map_sum] + rw [convolutionProjection_eq_iff] + intro k hk x + rw [convSeries_lof] + simp only [ofConv_sum,ofConv_smul,LinearMap.sum_apply,LinearMap.smul_apply] + apply Finset.sum_subset (Finset.range_mono (by omega)) + intro r hr hsmall + rw [Finset.mem_range,not_lt] at hsmall + rw [convVanishes_pow a c η hc θ hf r k (by omega) x,smul_zero] + +lemma convolutionProjection_jointly_injective + (f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)) + (h : ∀ n, convolutionProjection a c η hc θ n f=convolutionProjection a c η hc θ n g) : f=g := by + apply ofConv_injective + apply DirectSum.linearMap_ext + intro k + ext x + exact (convolutionProjection_eq_iff a c η hc θ (dimensionSize k.1.val+1) f g).mp + (h _) k (by omega) x + +lemma convSeries_post (φ : A →ₐ[ℚ] B) + (f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)) (p : PowerSeries ℚ) : + convPost φ (convSeries a c η hc θ f p)=convSeries a c η hc θ (convPost φ f) p := by + apply ofConv_injective + apply DirectSum.linearMap_ext + intro k + ext x + simp only [LinearMap.comp_apply] + rw [convPost_apply,convSeries_lof,convSeries_lof] + simp only [map_sum,map_smul,←map_pow,convPost_apply] + +lemma convSeries_order_one + {f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} (p : PowerSeries ℚ) + (hp : PowerSeries.constantCoeff p=0) : convVanishes a c η hc θ 1 (convSeries a c η hc θ f p) := by + intro k hk x + have hd : dimensionSize k.1.val=0 := by omega + rw [convSeries_lof,hd] + simp only [zero_add,Finset.sum_range_one,PowerSeries.coeff_zero_eq_constantCoeff,hp,zero_smul] + +lemma convVanishes_one_add_product {f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hf : convVanishes a c η hc θ 1 f) (hg : convVanishes a c η hc θ 1 g) : + convVanishes a c η hc θ 1 ((1+f)*(1+g)-1) := by + rw [show (1+f)*(1+g)-1=f+g+f*g by noncomm_ring] + exact convVanishes_add a c η hc θ (convVanishes_add a c η hc θ hf hg) + (convVanishes_mono a c η hc θ (by omega : 1 ≤ 1+1) (convVanishes_mul a c η hc θ hf hg)) + +lemma convSeries_log_product {f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hfg : Commute f g) (hf : convVanishes a c η hc θ 1 f) (hg : convVanishes a c η hc θ 1 g) : + convSeries a c η hc θ ((1+f)*(1+g)-1) (PowerSeries.log ℚ)= + convSeries a c η hc θ f (PowerSeries.log ℚ)+convSeries a c η hc θ g (PowerSeries.log ℚ) := by + apply convolutionProjection_jointly_injective a c η hc θ + intro n + rw [convolutionProjection_series a c η hc θ n (convVanishes_one_add_product a c η hc θ hf hg), + map_add,convolutionProjection_series a c η hc θ n hf, + convolutionProjection_series a c η hc θ n hg] + simp only [map_sub,map_mul,map_add,map_one] + exact nilEval_log_mul_of_commute (hfg.map (convolutionProjection a c η hc θ n)) + ⟨n,convolutionProjection_nilpotent a c η hc θ n hf⟩ + ⟨n,convolutionProjection_nilpotent a c η hc θ n hg⟩ + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy] + | ht k l x y => + rw [signedMapProduct_tmul,signedTensor_mul_eq,LinearMap.mul'_apply,signedLeft_apply,signedLeft_apply,signedLeft_apply] + rw [globalUnit,globalSignedTensorMultiply_tmul_lof] + change ((-1:ℚ)^eulerForm a 0 l.1.val) • ((_ * _)⊗ₜ[ℚ]((1:UnitalShuffle a c η hc θ)*1))=(_ * _)⊗ₜ[ℚ]1 + simp only [eulerForm,Pi.zero_apply,Int.natCast_zero,zero_mul,mul_zero,Finset.sum_const_zero,sub_zero,zpow_zero,one_smul] + exact congrArg₂ (fun x y : UnitalShuffle a c η hc θ=>x⊗ₜ[ℚ]y) rfl (one_mul _) + +lemma signedRight_product (t : UnitalShuffle a c η hc θ⊗[ℚ]UnitalShuffle a c η hc θ) : + signedMapProduct a c η hc θ (signedRight a c η hc θ) (signedRight a c η hc θ) t= + signedRight a c η hc θ (LinearMap.mul' ℚ (UnitalShuffle a c η hc θ) t) := by + induction t using globalTensor_induction a c η hc θ with + | hz => simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy] + | ht k l x y => + rw [signedMapProduct_tmul,signedTensor_mul_eq,LinearMap.mul'_apply,signedRight_apply,signedRight_apply,signedRight_apply] + rw [globalUnit,globalSignedTensorMultiply_tmul_lof] + change ((-1:ℚ)^eulerForm a k.1.val 0) • (((1:UnitalShuffle a c η hc θ)*1)⊗ₜ[ℚ](_ * _))=1⊗ₜ[ℚ](_ * _) + simp only [eulerForm,Pi.zero_apply,Int.natCast_zero,mul_zero,Finset.sum_const_zero,sub_zero,zpow_zero,one_smul] + exact congrArg₂ (fun x y : UnitalShuffle a c η hc θ=>x⊗ₜ[ℚ]y) (one_mul _) rfl + +lemma signedLeftRight_product (t : UnitalShuffle a c η hc θ⊗[ℚ]UnitalShuffle a c η hc θ) : + signedMapProduct a c η hc θ (signedLeft a c η hc θ) (signedRight a c η hc θ) t=t := by + induction t using globalTensor_induction a c η hc θ with + | hz => simp only [map_zero]; rfl + | ha x y hx hy => simp only [map_add,hx,hy]; rfl + | ht k l x y => + rw [signedMapProduct_tmul,signedTensor_mul_eq,signedLeft_apply,signedRight_apply] + rw [globalUnit,globalSignedTensorMultiply_tmul_lof] + change ((-1:ℚ)^eulerForm a 0 0) • ((_ * 1)⊗ₜ[ℚ](1 * _))=_ + simp only [eulerForm,Pi.zero_apply,Int.natCast_zero,mul_zero,Finset.sum_const_zero,sub_zero,zpow_zero,one_smul] + exact congrArg₂ (fun x y : UnitalShuffle a c η hc θ=>x⊗ₜ[ℚ]y) (mul_one _) (one_mul _) + +lemma signedRightLeft_product (t : UnitalShuffle a c η hc θ⊗[ℚ]UnitalShuffle a c η hc θ) : + signedMapProduct a c η hc θ (signedRight a c η hc θ) (signedLeft a c η hc θ) t= + globalSignedComm a c η hc θ t := by + induction t using globalTensor_induction a c η hc θ with + | hz => simp only [map_zero]; rfl + | ha x y hx hy => simp only [map_add,hx,hy]; rfl + | ht k l x y => + rw [signedMapProduct_tmul,signedTensor_mul_eq,signedRight_apply,signedLeft_apply] + rw [globalUnit,globalSignedTensorMultiply_tmul_lof] + change ((-1:ℚ)^eulerForm a k.1.val l.1.val) • ((1 * _)⊗ₜ[ℚ](_ * 1))=_ + rw [globalSignedComm,LinearMap.comp_apply,globalSignOperator_tmul_lof,map_smul] + simp only [LinearEquiv.coe_coe,TensorProduct.comm_tmul] + exact congrArg (fun t=>((-1:ℚ)^eulerForm a k.1.val l.1.val) • t) + (congrArg₂ (fun x y : UnitalShuffle a c η hc θ=>x⊗ₜ[ℚ]y) (one_mul _) (mul_one _)) + +noncomputable def signedLeftAlgHom : UnitalShuffle a c η hc θ →ₐ[ℚ] SignedGlobalTensor a c η hc θ := + AlgHom.ofLinearMap (signedLeft a c η hc θ) rfl + (fun x y=>(signedLeft_product a c η hc θ (x⊗ₜ[ℚ]y)).symm) +noncomputable def signedRightAlgHom : UnitalShuffle a c η hc θ →ₐ[ℚ] SignedGlobalTensor a c η hc θ := + AlgHom.ofLinearMap (signedRight a c η hc θ) rfl + (fun x y=>(signedRight_product a c η hc θ (x⊗ₜ[ℚ]y)).symm) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductCoassociative.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductCoassociative.lean new file mode 100644 index 0000000000000000000000000000000000000000..b793b4f93e87cbf3bad3f5e08ee29ef63561172f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductCoassociative.lean @@ -0,0 +1,322 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalCoproductCocommutative +import OAI.Combinatorics.Chromatic.Shuffle.GlobalTripleGradeInclusion +import OAI.Combinatorics.Chromatic.Shuffle.GlobalCoproductIteration + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +noncomputable def globalTripleCoproduct (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(globalTensorGradeInclusion a c η hc θ d e u).comp + ((unitalGradeCoproduct a c η hc θ d.val e.val (d.property.compatible e.property) u).comp + (unitalGradeCast a c η hc θ (rfl : d.val+e.val=d.val+e.val) (rfl : u=u)).toLinearMap) : + (u : ℤ) → FGrade (unitalSourceFiltration a c η hc θ (d.val+e.val)) u →ₗ[ℚ] + UnitalShuffle a c η hc θ⊗[ℚ]UnitalShuffle a c η hc θ)= + (fun u=>(globalTensorGradeInclusion a c η hc θ d e u).comp + (unitalGradeCoproduct a c η hc θ d.val e.val (d.property.compatible e.property) u)) := rfl + +lemma globalTripleGrade_left_cast_natural (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(globalTensorGradeInclusion a c η hc θ d e u).comp + ((unitalGradeCoproduct a c η hc θ d.val e.val (d.property.compatible e.property) u).comp + (unitalGradeCast a c η hc θ rfl rfl).toLinearMap)) + (fun v=>DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (f,v)) W x)= + TensorProduct.assoc ℚ _ _ _ (globalTripleGradeLeft a c η hc θ d e f W + (unitalTensorCoproductLeft a c η hc θ d.val e.val f.val (d.property.compatible e.property) W x)) := by + rw [globalTensorGrade_coproduct_family_cast] + exact congrArg (TensorProduct.assoc ℚ _ _ _) (globalTripleGrade_left_natural a c η hc θ d e f W x).symm + +lemma globalTripleGrade_right_cast_natural (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (d,v)) + (fun u=>(globalTensorGradeInclusion a c η hc θ e f u).comp + ((unitalGradeCoproduct a c η hc θ e.val f.val (e.property.compatible f.property) u).comp + (unitalGradeCast a c η hc θ rfl rfl).toLinearMap)) W x= + globalTripleGradeRight a c η hc θ d e f W + (unitalTensorCoproductRight a c η hc θ d.val e.val f.val (e.property.compatible f.property) W x) := by + rw [globalTensorGrade_coproduct_family_cast] + exact (globalTripleGrade_right_natural a c η hc θ d e f W x).symm + +lemma globalIteratedLeftSplit_dimensions (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(globalTensorGradeInclusion a c η hc θ ⟨d,hds⟩ ⟨e,hes⟩ u).comp + ((unitalGradeCoproduct a c η hc θ d e (hds.compatible hes) u).comp + (unitalGradeCast a c η hc θ hde.symm rfl).toLinearMap)) + (fun v=>DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (⟨f,hfs⟩,v)) k.2 + (unitalGradeCoproduct a c η hc θ b f (hbs.compatible hfs) k.2 + (unitalGradeCast a c η hc θ hbf.symm rfl x)) := by + subst b; subst d; subst e; subst f + rfl + +lemma globalIteratedRightSplit_dimensions (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (⟨d,hds⟩,v)) + (fun u=>(globalTensorGradeInclusion a c η hc θ ⟨e,hes⟩ ⟨f,hfs⟩ u).comp + ((unitalGradeCoproduct a c η hc θ e f (hes.compatible hfs) u).comp + (unitalGradeCast a c η hc θ hef.symm rfl).toLinearMap)) k.2 + (unitalGradeCoproduct a c η hc θ d b (hds.compatible hbs) k.2 + (unitalGradeCast a c η hc θ hdb.symm rfl x)) := by + subst b; subst d; subst e; subst f + rfl + +lemma globalIteratedLeftSplit_natural (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0globalTripleCoproduct a c η hc θ k p x) + +theorem globalCoproduct_coassociative (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero] + | add x y hx hy => simp only [map_add,hx,hy] + | of k x => exact globalCoproduct_coassociative_lof a c η hc θ hχ k x +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductCocommutative.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductCocommutative.lean new file mode 100644 index 0000000000000000000000000000000000000000..fbf701bca1b012937f08dcd62b038ab86be6f7ef --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductCocommutative.lean @@ -0,0 +1,131 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalTensorGradeProduct + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +lemma unitalGradeCast_trans (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero,smul_zero] + | ha x y hx hy => simp only [map_add,smul_add,hx,hy] + | ht u x y => rw [globalTensorGradeInclusion_part,globalSignOperator_tmul_lof] + +lemma globalPairCoproduct_swap (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero] + | add x y hx hy => simp only [map_add,hx,hy] + | of k x => + change globalSignedComm a c η hc θ + (globalCoproduct a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x))= + globalCoproduct a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x) + rw [globalCoproduct_lof] + simp only [map_sum] + calc + _=∑ s : SlopeSplit c η hc θ k.1.val, + globalSplitCoproduct a c η hc θ k (slopeSplitSwap c η hc θ k.1.val s) x := + Finset.sum_congr rfl (fun s _=>(globalSplitCoproduct_swap a c η hc θ hχ k s x).symm) + _=_ := Equiv.sum_comp (slopeSplitSwap c η hc θ k.1.val) + (fun s : SlopeSplit c η hc θ k.1.val => globalSplitCoproduct a c η hc θ k s x) +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductIteration.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..c0cf85fdfa292985193b65a25519caa9908b69d1 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalCoproductIteration.lean @@ -0,0 +1,158 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TensorGradeFiniteSum + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +noncomputable def globalGradeLof (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0globalSplitGradeCoproduct a c η hc θ d s u) + (fun v=>globalGradeLof a c η hc θ e v) W x := by + have hh : (fun u=>(globalCoproduct a c η hc θ).comp + (globalGradeLof a c η hc θ d u))= + (fun u=>∑ s : SlopeSplit c η hc θ d.val,globalSplitGradeCoproduct a c η hc θ d s u) := by + funext u + apply LinearMap.ext + intro y + change globalCoproduct a c η hc θ (globalGradeLof a c η hc θ d u y)=_ + exact (globalCoproduct_lof a c η hc θ (d,u) y).trans + (LinearMap.sum_apply Finset.univ (fun s : SlopeSplit c η hc θ d.val=> + globalSplitCoproduct a c η hc θ (d,u) s) y).symm + have H := tensorGradeLift_comp + (unitalSourceFiltration a c η hc θ d.val) (unitalSourceFiltration a c η hc θ e.val) + (unitalSourceFiltration_antitone a c η hc θ d.val) + (unitalSourceFiltration_antitone a c η hc θ e.val) + (fun u=>globalGradeLof a c η hc θ d u) + (fun v=>globalGradeLof a c η hc θ e v) + (globalCoproduct a c η hc θ) LinearMap.id W x + simp only [LinearMap.id_comp,hh] at H + exact H.trans (tensorGradeLift_sum_left _ _ _ _ + (fun s u=>globalSplitGradeCoproduct a c η hc θ d s u) + (fun v=>globalGradeLof a c η hc θ e v) W x) + +lemma globalCoproduct_tensor_right (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0globalGradeLof a c η hc θ d v) + (fun u=>globalSplitGradeCoproduct a c η hc θ e s u) W x := by + have hh : (fun u=>(globalCoproduct a c η hc θ).comp + (globalGradeLof a c η hc θ e u))= + (fun u=>∑ s : SlopeSplit c η hc θ e.val,globalSplitGradeCoproduct a c η hc θ e s u) := by + funext u + apply LinearMap.ext + intro y + change globalCoproduct a c η hc θ (globalGradeLof a c η hc θ e u y)=_ + exact (globalCoproduct_lof a c η hc θ (e,u) y).trans + (LinearMap.sum_apply Finset.univ (fun s : SlopeSplit c η hc θ e.val=> + globalSplitCoproduct a c η hc θ (e,u) s) y).symm + have H := tensorGradeLift_comp + (unitalSourceFiltration a c η hc θ d.val) (unitalSourceFiltration a c η hc θ e.val) + (unitalSourceFiltration_antitone a c η hc θ d.val) + (unitalSourceFiltration_antitone a c η hc θ e.val) + (fun u=>globalGradeLof a c η hc θ d u) + (fun v=>globalGradeLof a c η hc θ e v) + LinearMap.id (globalCoproduct a c η hc θ) W x + simp only [LinearMap.id_comp,hh] at H + exact H.trans (tensorGradeLift_sum_right _ _ _ _ + (fun v=>globalGradeLof a c η hc θ d v) + (fun s u=>globalSplitGradeCoproduct a c η hc θ e s u) W x) + +noncomputable def globalIteratedLeftSplit (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0globalSplitCoproduct a c η hc θ (⟨left s.val,s.property.1⟩,u) t) + (fun v=>DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (⟨right s.val,s.property.2⟩,v)) k.2).comp + ((unitalGradeCoproduct a c η hc θ (left s.val) (right s.val) + (s.property.1.compatible s.property.2) k.2).comp + (unitalGradeCast a c η hc θ (left_add_right s.val).symm rfl).toLinearMap) + +noncomputable def globalIteratedRightSplit (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (⟨left s.val,s.property.1⟩,v)) + (fun u=>globalSplitCoproduct a c η hc θ (⟨right s.val,s.property.2⟩,u) t) k.2).comp + ((unitalGradeCoproduct a c η hc θ (left s.val) (right s.val) + (s.property.1.compatible s.property.2) k.2).comp + (unitalGradeCast a c η hc θ (left_add_right s.val).symm rfl).toLinearMap) + +lemma globalCoproduct_iterated_left_lof (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x⊗ₜ[ℚ]z) + (globalLof_gradeOne_cast a c η hc θ (k.2-k.2) (sub_self _).symm) + +lemma globalCoproduct_counit_left_lof (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero,TensorProduct.tmul_zero] + | add x y hx hy => simp only [map_add,hx,hy,TensorProduct.tmul_add] + | of k x => exact globalCoproduct_counit_left_lof a c η hc θ k x + +lemma globalCoproduct_counit_right (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero,TensorProduct.zero_tmul] + | add x y hx hy => simp only [map_add,hx,hy,TensorProduct.add_tmul] + | of k x => exact globalCoproduct_counit_right_lof a c η hc θ k x + +lemma globalCoproduct_unit (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + globalSplitCoproduct a c η hc θ (0,0) s (unitalGradeOne a c η hc θ)) + rw [hh] + · exact globalSplitCoproduct_zero_left a c η hc θ 0 _ + · intro s _ hs + have hz : left s.val=0 := by + funext i + have hi := congrFun (left_add_right s.val) i + change left s.val i+right s.val i=0 at hi + exact (Nat.add_eq_zero_iff.mp hi).1 + exact False.elim ((slopeSplit_ne_left_zero c η hc θ 0 s hs) hz) + · intro hs + exact False.elim (hs (Finset.mem_univ _)) +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalHilbertGrading.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalHilbertGrading.lean new file mode 100644 index 0000000000000000000000000000000000000000..590c4c809280c1d7568e908433b523cb8828b9f9 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalHilbertGrading.lean @@ -0,0 +1,178 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousBasisFibre +import OAI.Combinatorics.Chromatic.Shuffle.UnitalOriginalDegree + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped DirectSum +open ElementaryPositivity.SlopeArithmetic +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0i.1.val) + +noncomputable def stringPBWGrade (l : StringPBWIndex a c η hc θ) : SlopeWeight c η hc θ × ℤ := + (wordWeight c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val) l.val, + wordPolynomialDegree a c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val) + (globalStringPolynomialDegree a c η hc θ) l.val) + +abbrev StringPBWGradedIndex (k : SlopeWeight c η hc θ) (m : ℤ) := + {l : StringPBWIndex a c η hc θ // stringPBWGrade a c η hc θ l=(k,m)} + +lemma stringPBWBasis_component (k : SlopeWeight c η hc θ ×ℤ) (l : StringPBWIndex a c η hc θ) : + globalOriginalComponent a c η hc θ k.1 k.2 (globalStringPBWBasis a c η hc θ l)= + if stringPBWGrade a c η hc θ l=k then globalStringPBWBasis a c η hc θ l else 0 := by + rcases k with ⟨k,n⟩ + simpa [stringPBWGrade] using + globalOriginalComponent_of_mem a c η hc θ (globalStringPBWBasis_original a c η hc θ l) n + +noncomputable def stringPBWGradedBasis (k : SlopeWeight c η hc θ) (m : ℤ) : + Module.Basis (StringPBWGradedIndex a c η hc θ k m) ℚ + (LinearMap.range (globalOriginalComponent a c η hc θ k m)) := + ElementaryPositivity.homogeneousBasisFibre (globalStringPBWBasis a c η hc θ) + (stringPBWGrade a c η hc θ) (fun k=>globalOriginalComponent a c η hc θ k.1 k.2) + (stringPBWBasis_component a c η hc θ) (k,m) + +lemma stringPBWGradedIndex_finite (k : SlopeWeight c η hc θ) (m : ℤ) : + Finite (StringPBWGradedIndex a c η hc θ k m) := by + let := globalOriginalComponent_finite a c η hc θ k m + exact Module.Finite.finite_basis (stringPBWGradedBasis a c η hc θ k m) + +lemma globalOriginalComponent_rank (k : SlopeWeight c η hc θ) (m : ℤ) : + Module.finrank ℚ (LinearMap.range (globalOriginalComponent a c η hc θ k m))= + Module.finrank ℚ (unitalOriginalHomogeneous a c η hc θ k.1.val k.2 m) := by + rw [globalOriginalComponent_range] + exact (Submodule.equivMapOfInjective (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k) + (DirectSum.of_injective k) (unitalOriginalHomogeneous a c η hc θ k.1.val k.2 m)).finrank_eq.symm + +theorem stringPBWHilbert_coefficient (k : SlopeWeight c η hc θ) (m : ℤ) : + Module.finrank ℚ (unitalOriginalHomogeneous a c η hc θ k.1.val k.2 m)= + Nat.card (StringPBWGradedIndex a c η hc θ k m) := by + rw [←globalOriginalComponent_rank] + let := stringPBWGradedIndex_finite a c η hc θ k m + let := Fintype.ofFinite (StringPBWGradedIndex a c η hc θ k m) + rw [Module.finrank_eq_card_basis (stringPBWGradedBasis a c η hc θ k m),Nat.card_eq_fintype_card] +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0Module.finrank ℚ N) E) + +theorem sourcePBWHilbert_coefficient (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) + (k : ℤ) (n : ℕ) (hn : 2*k+eulerForm a d d < -interaction a d d+n) : + Module.finrank ℚ (gradeB a (slope c η) d k)= + ∑ j∈Finset.range n, Nat.card (StringPBWGradedIndex a c η hc θ + (⟨d,Or.inr hs⟩,-interaction a d d+j) k) := by + rw [←sourceHilbert_filtration a c η hc θ d hd hs k n hn] + apply Finset.sum_congr rfl + intro j hj + rw [←unitalOriginalNonzero_rank a c η hc θ d hd] + exact stringPBWHilbert_coefficient a c η hc θ (⟨d,Or.inr hs⟩,-interaction a d d+j) k +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalLocalPrimitives.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalLocalPrimitives.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d36f0b671d80e23834a0c422b4e270df76fe35f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalLocalPrimitives.lean @@ -0,0 +1,273 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.PrimitiveOperators +import OAI.Combinatorics.Chromatic.Shuffle.OriginalDegree +import OAI.Combinatorics.Chromatic.Shuffle.GlobalTensorDetection +import OAI.Combinatorics.Chromatic.Walls.UnitalGradeComparison + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open DimensionSplit ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ)) (m-1) := by + rw [derivativeS_val] + exact D_homogeneous _ _ (componentS_homogeneous d m f) + rw [componentS_componentS,componentS_of_homogeneous d _ hh] + by_cases h : ℓ=m + · subst m + simp + · simp only [ite_eq_right h,ite_eq_right (by omega : ℓ-1≠m-1),map_zero] + +lemma derivativeB_component (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (ℓ : ℤ) (f : B a μ d) : + derivativeB a μ d (componentB a μ d ℓ f)=componentB a μ d (ℓ-1) (derivativeB a μ d f) := by + induction f using Submodule.Quotient.induction_on with + | H f => + change derivativeB a μ d (quotientAlg a μ d (componentS d ℓ f))= + componentB a μ d (ℓ-1) (derivativeB a μ d (quotientAlg a μ d f)) + rw [derivativeB_mk,derivativeB_mk] + change quotientAlg a μ d (derivativeS d (componentS d ℓ f))= + quotientAlg a μ d (componentS d (ℓ-1) (derivativeS d f)) + rw [derivativeS_component] + +omit [DecidableEq I] in +lemma meanS_homogeneous (d : I → ℕ) : + (meanS d).val.IsWeightedHomogeneous (fun _=>(1:ℤ)) 1 := by + classical + apply (weightedHomogeneousSubmodule ℚ (fun _ : (Σ i,Fin (d i))=>(1:ℤ)) 1).smul_mem + exact IsWeightedHomogeneous.sum _ _ 1 (fun v _=>isWeightedHomogeneous_X ℚ (fun _=>(1:ℤ)) v) + +omit [DecidableEq I] in +lemma componentS_mean (d : I → ℕ) (ℓ : ℤ) (f : S d) : + componentS d (ℓ+1) (meanS d*f)=meanS d*componentS d ℓ f := by + apply Subtype.ext + change weightedHomogeneousComponent (fun _=>(1:ℤ)) (ℓ+1) ((meanS d).val*f.val)=_ + rw [add_comm ℓ 1,Homogeneity.component_mul _ _ (meanS_homogeneous d) ℓ] + rfl + +lemma meanMultiplyB_component (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (ℓ : ℤ) (f : B a μ d) : + componentB a μ d (ℓ+1) (meanMultiplyB a μ d f)=meanMultiplyB a μ d (componentB a μ d ℓ f) := by + induction f using Submodule.Quotient.induction_on with + | H f => + change componentB a μ d (ℓ+1) (quotientAlg a μ d (meanS d)*quotientAlg a μ d f)= + quotientAlg a μ d (meanS d)*quotientAlg a μ d (componentS d ℓ f) + rw [←map_mul,←map_mul] + change quotientAlg a μ d (componentS d (ℓ+1) (meanS d*f))=_ + rw [componentS_mean] + +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + apply congrArg (LinearFiltration.mk (sourceFiltration a c η hc θ d W) (sourceFiltration a c η hc θ d (W+1))) + apply Subtype.ext + exact derivativeB_component a (SlopeArithmetic.slope c η) d ℓ f.val + +lemma gradeMeanMultiply_component (d : I → ℕ) (W ℓ : ℤ) (f : SourceAssociatedGrade a c η hc θ d W) : + associatedComponent a c η hc θ d W (ℓ+1) (gradeMeanMultiply a c η hc θ d W f)= + gradeMeanMultiply a c η hc θ d W (associatedComponent a c η hc θ d W ℓ f) := by + induction f using Submodule.Quotient.induction_on with + | H f => + apply congrArg (LinearFiltration.mk (sourceFiltration a c η hc θ d W) (sourceFiltration a c η hc θ d (W+1))) + apply Subtype.ext + exact meanMultiplyB_component a (SlopeArithmetic.slope c η) d ℓ f.val + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 simpa only [Nat.cast_zero,add_zero,pow_zero,Module.End.one_apply] using hx + | succ n ih => + rw [Nat.cast_succ,←add_assoc,pow_succ',Module.End.mul_apply,primitiveMeanMultiply_component,ih] + +noncomputable def homogeneousPrimitiveStringBasis (hd : d≠0) : + Module.Basis (Σ _ : ℕ,StringBaseIndex a c η hc θ hχ d W) ℚ + (primitiveSpace a c η hc θ hχ d W) := + (Finsupp.basis (fun _ : ℕ=>homogeneousStringBaseBasis a c η hc θ hχ d W)).map + (primitiveStringDecomposition a c η hc θ hχ d hd W) + +lemma homogeneousPrimitiveStringBasis_apply (hd : d≠0) + (i : Σ _ : ℕ,StringBaseIndex a c η hc θ hχ d W) : + homogeneousPrimitiveStringBasis a c η hc θ hχ d W hd i= + (primitiveMeanMultiply a c η hc θ hχ d W^i.1) (homogeneousStringBaseBasis a c η hc θ hχ d W i.2).val := by + rw [homogeneousPrimitiveStringBasis,Module.Basis.map_apply,Finsupp.coe_basis] + exact PrimitiveStrings.evaluate_single _ _ _ _ + +lemma homogeneousPrimitiveStringBasis_degree (hd : d≠0) + (i : Σ _ : ℕ,StringBaseIndex a c η hc θ hχ d W) : + primitiveComponent a c η hc θ hχ d W (stringBaseDegree a c η hc θ hχ d W i.2+i.1) + (homogeneousPrimitiveStringBasis a c η hc θ hχ d W hd i)= + homogeneousPrimitiveStringBasis a c η hc θ hχ d W hd i := by + rw [homogeneousPrimitiveStringBasis_apply] + exact primitiveMeanMultiply_pow_component a c η hc θ hχ d W _ _ _ + (stringBaseDegree_spec a c η hc θ hχ d W i.2) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPBWBasis.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPBWBasis.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b6ea030a2b42a771f07d9c9af41fb6dccab127b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPBWBasis.lean @@ -0,0 +1,230 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalPBWIndependent +import OAI.Combinatorics.Chromatic.Histories.ColorWordReordering + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0Algebra.subset_adjoin hx + apply top_unique + rw [←globalPrimitiveLog_adjoin a c η hc θ] + apply Algebra.adjoin_le + rintro x ⟨y,rfl⟩ + exact hp ((mem_globalPrimitives a c η hc θ _).mpr (globalPrimitiveLog_primitive a c η hc θ y)) + +lemma primitive_mem_wordLength_one {x : UnitalShuffle a c η hc θ} + (hx : x ∈ globalPrimitives a c η hc θ) : + x ∈ wordLengthFiltration (homogeneousPrimitiveFamily a c η hc θ) 1 := by + apply wordLengthFiltration_span_range + rwa [homogeneousPrimitiveFamily_span] + +lemma homogeneousPrimitiveWords_span : + Submodule.span ℚ (Set.range (fun l : PBWWord a c η hc θ (homogeneousPrimitiveWeight a c η hc θ)=> + primitiveWord a c η hc θ (homogeneousPrimitiveFamily a c η hc θ) l.val))=⊤ := by + let b := homogeneousPrimitiveFamily a c η hc θ + let w := homogeneousPrimitiveWeight a c η hc θ + let ε := fun i j=>globalColorSign a c η hc θ (w i) (w j) + have he : ∀ i j,ε i j ≠ 0 := by + intro i j h + have hh := globalColorSign_sq a c η hc θ (w i) (w j) + change ε i j*ε i j=1 at hh + rw [h,zero_mul] at hh + exact zero_ne_one hh + have hcomm : ∀ i j,b i*b j-ε i j • (b j*b i) ∈ wordLengthFiltration b 1 := by + intro i j + exact primitive_mem_wordLength_one a c η hc θ + (globalPrimitive_bracket a c η hc θ (homogeneousPrimitiveFamily_weight a c η hc θ i) + (homogeneousPrimitiveFamily_weight a c η hc θ j) + (homogeneousPrimitiveFamily_primitive a c η hc θ i) + (homogeneousPrimitiveFamily_primitive a c η hc θ j)) + have hsquare : ∀ i,ε i i ≠ 1 → b i*b i ∈ wordLengthFiltration b 1 := by + intro i hi + have hs : ε i i= -1 := (mul_self_eq_one_iff.mp (globalColorSign_sq a c η hc θ (w i) (w i))).resolve_left hi + exact primitive_mem_wordLength_one a c η hc θ + (globalPrimitive_odd_square a c η hc θ (homogeneousPrimitiveFamily_weight a c η hc θ i) + (homogeneousPrimitiveFamily_primitive a c η hc θ i) hs) + have ht := colorWordSpan_top b ε he hcomm hsquare (homogeneousPrimitiveFamily_adjoin a c η hc θ) + convert ht using 1 + unfold colorWordSpan + congr 1 + ext x + constructor + · rintro ⟨l,rfl⟩ + exact ⟨l.val,l.property,rfl⟩ + · rintro ⟨l,hl,rfl⟩ + exact ⟨⟨l,hl⟩,rfl⟩ + +noncomputable def globalPBWBasis : + Module.Basis (PBWWord a c η hc θ (homogeneousPrimitiveWeight a c η hc θ)) ℚ + (UnitalShuffle a c η hc θ) := + Module.Basis.mk (homogeneousPrimitiveWords_independent a c η hc θ) + (le_of_eq (homogeneousPrimitiveWords_span a c η hc θ).symm) + +lemma globalPBWBasis_apply (l : PBWWord a c η hc θ (homogeneousPrimitiveWeight a c η hc θ)) : + globalPBWBasis a c η hc θ l= + primitiveWord a c η hc θ (homogeneousPrimitiveFamily a c η hc θ) l.val := + Module.Basis.mk_apply _ _ _ + +lemma globalPBWBasis_homogeneous (l : PBWWord a c η hc θ (homogeneousPrimitiveWeight a c η hc θ)) : + globalPBWBasis a c η hc θ l ∈ globalHomogeneous a c η hc θ + (wordWeight c η hc θ (homogeneousPrimitiveWeight a c η hc θ) l.val) := by + rw [globalPBWBasis_apply] + exact primitiveWord_homogeneous a c η hc θ _ _ (homogeneousPrimitiveFamily_weight a c η hc θ) l.val + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable Classical.decEq +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0by + rw [hspan] + exact (mem_globalPrimitives a c η hc θ _).mpr (globalPrimitiveLog_primitive a c η hc θ x)) + +omit [LinearOrder J] in +lemma primitiveBasisRetraction_unit : + primitiveBasisRetraction a c η hc θ b hspan (globalUnit a c η hc θ)=0 := by + apply Subtype.ext + change globalPrimitiveLog a c η hc θ (globalUnit a c η hc θ)=0 + exact congrArg (fun x : globalPrimitives a c η hc θ=>x.val) (globalPrimitiveProjection_unit a c η hc θ) + +include hp in +omit [LinearOrder J] in +lemma primitiveBasisRetraction_apply (j : J) : + primitiveBasisRetraction a c η hc θ b hspan (b j)=(Module.Basis.span hli) j := by + apply Subtype.ext + rw [Module.Basis.span_apply] + exact globalPrimitiveLog_on_primitive a c η hc θ (hp j) + +noncomputable def primitiveBasisDual (j : J) : UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ := + (Module.Basis.span hli).coord j ∘ₗ primitiveBasisRetraction a c η hc θ b hspan + +omit [LinearOrder J] in +lemma primitiveBasisDual_unit (j : J) : + primitiveBasisDual a c η hc θ b hspan hli j (globalUnit a c η hc θ)=0 := by + change (Module.Basis.span hli).coord j (primitiveBasisRetraction a c η hc θ b hspan _)=0 + rw [primitiveBasisRetraction_unit,map_zero] + +include hp in +omit [LinearOrder J] in +lemma primitiveBasisDual_apply (i j : J) : + primitiveBasisDual a c η hc θ b hspan hli i (b j)=if i=j then 1 else 0 := by + change (Module.Basis.span hli).coord i (primitiveBasisRetraction a c η hc θ b hspan _)=_ + rw [primitiveBasisRetraction_apply a c η hc θ b hp hspan hli,Module.Basis.coord_apply, + Module.Basis.repr_self_apply] + congr 1 + exact propext eq_comm + +include hw hp hspan hli in +lemma primitiveBasisFamilyWords_independent : + LinearIndependent ℚ (fun l : PBWWord a c η hc θ w=>primitiveWord a c η hc θ b l.val) := + globalPBW_independent a c η hc θ w b hw hp _ + (primitiveBasisDual_unit a c η hc θ b hspan hli) + (primitiveBasisDual_apply a c η hc θ b hp hspan hli) + +include hspan in +omit [LinearOrder J] in +lemma primitiveBasisFamily_adjoin : + Algebra.adjoin ℚ (Set.range (b))=⊤ := by + have hp : globalPrimitives a c η hc θ ≤ + (Algebra.adjoin ℚ (Set.range (b))).toSubmodule := by + rw [←hspan] + apply Submodule.span_le.mpr + exact fun _ hx=>Algebra.subset_adjoin hx + apply top_unique + rw [←globalPrimitiveLog_adjoin a c η hc θ] + apply Algebra.adjoin_le + rintro x ⟨y,rfl⟩ + exact hp ((mem_globalPrimitives a c η hc θ _).mpr (globalPrimitiveLog_primitive a c η hc θ y)) + +include hspan in +omit [LinearOrder J] in +lemma primitiveBasisFamily_wordLength {x : UnitalShuffle a c η hc θ} + (hx : x ∈ globalPrimitives a c η hc θ) : + x ∈ wordLengthFiltration (b) 1 := by + apply wordLengthFiltration_span_range + rwa [hspan] + +include hw hp hspan in +lemma primitiveBasisFamilyWords_span : + Submodule.span ℚ (Set.range (fun l : PBWWord a c η hc θ (w)=> + primitiveWord a c η hc θ (b) l.val))=⊤ := by + let ε := fun i j=>globalColorSign a c η hc θ (w i) (w j) + have he : ∀ i j,ε i j ≠ 0 := by + intro i j h + have hh := globalColorSign_sq a c η hc θ (w i) (w j) + change ε i j*ε i j=1 at hh + rw [h,zero_mul] at hh + exact zero_ne_one hh + have hcomm : ∀ i j,b i*b j-ε i j • (b j*b i) ∈ wordLengthFiltration b 1 := by + intro i j + exact primitiveBasisFamily_wordLength a c η hc θ b hspan + (globalPrimitive_bracket a c η hc θ (hw i) + (hw j) + (hp i) + (hp j)) + have hsquare : ∀ i,ε i i ≠ 1 → b i*b i ∈ wordLengthFiltration b 1 := by + intro i hi + have hs : ε i i= -1 := (mul_self_eq_one_iff.mp (globalColorSign_sq a c η hc θ (w i) (w i))).resolve_left hi + exact primitiveBasisFamily_wordLength a c η hc θ b hspan + (globalPrimitive_odd_square a c η hc θ (hw i) + (hp i) hs) + have ht := colorWordSpan_top b ε he hcomm hsquare (primitiveBasisFamily_adjoin a c η hc θ b hspan) + convert ht using 1 + unfold colorWordSpan + congr 1 + ext x + constructor + · rintro ⟨l,rfl⟩ + exact ⟨l.val,l.property,rfl⟩ + · rintro ⟨l,hl,rfl⟩ + exact ⟨⟨l,hl⟩,rfl⟩ + +noncomputable def primitiveBasisPBW : Module.Basis (PBWWord a c η hc θ w) ℚ (UnitalShuffle a c η hc θ) := + Module.Basis.mk (primitiveBasisFamilyWords_independent a c η hc θ b w hw hp hspan hli) + (le_of_eq (primitiveBasisFamilyWords_span a c η hc θ b w hw hp hspan).symm) + +lemma primitiveBasisPBW_apply (l : PBWWord a c η hc θ w) : + primitiveBasisPBW a c η hc θ b w hw hp hspan hli l=primitiveWord a c η hc θ b l.val := + Module.Basis.mk_apply _ _ _ + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPBWIndependent.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPBWIndependent.lean new file mode 100644 index 0000000000000000000000000000000000000000..608672a9bc942fa6ce613e17b77096bbb75ae62e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPBWIndependent.lean @@ -0,0 +1,147 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalWordDetection +import OAI.Combinatorics.Chromatic.Walls.FilteredDualIndependence + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0primitiveWord a c η hc θ b l.val) := by + apply linearIndependent_of_filtered_dual + (degree:=fun l=>l.val.length) + (f:=fun l=>(functionalWord a c η hc θ f l.val).ofConv) + (diag:=fun l=>(wordMultiplicity l.val:ℚ)) + · intro l + exact_mod_cast (Nat.ne_of_gt (wordMultiplicity_pos l.val)) + · intro u v h + by_cases huv : u=v + · subst v + rw [ite_eq_left rfl] + exact functionalWord_diagonal a c η hc θ w b hb hp f hf hfb u.val u.property + · rw [ite_eq_right huv] + by_cases hlen : v.val.length=u.val.length + · exact functionalWord_top_sorted_ne a c η hc θ w b hb hp f hf hfb u.val v.val + u.property.sorted v.property.sorted hlen (fun hh=>huv (Subtype.ext hh)) + · exact functionalWord_longer a c η hc θ w b hb hp f hf u.val v.val (lt_of_le_of_ne h hlen) + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(mem_globalPrimitives a c η hc θ _).mpr (globalPrimitiveLog_primitive a c η hc θ x)) + +lemma globalPrimitiveProjection_restrict (x : globalPrimitives a c η hc θ) : + globalPrimitiveProjection a c η hc θ x.val=x := + Subtype.ext (globalPrimitiveLog_on_primitive a c η hc θ x.property) + +lemma globalPrimitiveProjection_unit : + globalPrimitiveProjection a c η hc θ (globalUnit a c η hc θ)=0 := by + apply Subtype.ext + change (convSeries a c η hc θ (convolutionJ a c η hc θ) (PowerSeries.log ℚ)).ofConv + (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (0,0) (unitalGradeOne a c η hc θ))=0 + rw [convSeries_lof] + simp [dimensionSize] + +noncomputable def homogeneousPrimitives : Set (globalPrimitives a c η hc θ) := + {x | ∃ k,x.val ∈ globalHomogeneous a c η hc θ k} + +lemma homogeneousPrimitives_span : + ⊤ ≤ Submodule.span ℚ (homogeneousPrimitives a c η hc θ) := by + intro x hx + rw [←globalPrimitiveProjection_restrict a c η hc θ x] + have hmain : ∀ y:UnitalShuffle a c η hc θ,globalPrimitiveProjection a c η hc θ y∈ + Submodule.span ℚ (homogeneousPrimitives a c η hc θ) := by + intro y + induction y using DirectSum.induction_on with + | zero => simpa only [map_zero] using (Submodule.span ℚ (homogeneousPrimitives a c η hc θ)).zero_mem + | add y z hy hz => simpa only [map_add] using (Submodule.span ℚ (homogeneousPrimitives a c η hc θ)).add_mem hy hz + | of k y => + apply Submodule.subset_span + exact ⟨k,globalPrimitiveLog_homogeneous a c η hc θ k y⟩ + exact hmain x.val + +noncomputable def PrimitiveIndex : Type _ := + (linearIndepOn_empty ℚ (id : globalPrimitives a c η hc θ → globalPrimitives a c η hc θ)).extend + (Set.empty_subset (homogeneousPrimitives a c η hc θ)) + +noncomputable def homogeneousPrimitiveBasis : + Module.Basis (PrimitiveIndex a c η hc θ) ℚ (globalPrimitives a c η hc θ) := + Module.Basis.ofSpan (homogeneousPrimitives_span a c η hc θ) + +noncomputable def homogeneousPrimitiveFamily (i : PrimitiveIndex a c η hc θ) : UnitalShuffle a c η hc θ := + (homogeneousPrimitiveBasis a c η hc θ i).val + +lemma homogeneousPrimitiveFamily_primitive (i : PrimitiveIndex a c η hc θ) : + homogeneousPrimitiveFamily a c η hc θ i ∈ globalPrimitives a c η hc θ := + (homogeneousPrimitiveBasis a c η hc θ i).property + +lemma homogeneousPrimitiveFamily_exists_weight (i : PrimitiveIndex a c η hc θ) : + ∃ k,homogeneousPrimitiveFamily a c η hc θ i ∈ globalHomogeneous a c η hc θ k := + Module.Basis.ofSpan_subset (homogeneousPrimitives_span a c η hc θ) (Set.mem_range_self i) + +noncomputable def homogeneousPrimitiveWeight (i : PrimitiveIndex a c η hc θ) : SlopeWeight c η hc θ := + (homogeneousPrimitiveFamily_exists_weight a c η hc θ i).choose + +lemma homogeneousPrimitiveFamily_weight (i : PrimitiveIndex a c η hc θ) : + homogeneousPrimitiveFamily a c η hc θ i ∈ + globalHomogeneous a c η hc θ (homogeneousPrimitiveWeight a c η hc θ i) := + (homogeneousPrimitiveFamily_exists_weight a c η hc θ i).choose_spec + +noncomputable def homogeneousPrimitiveDual (i : PrimitiveIndex a c η hc θ) : + UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ := + (homogeneousPrimitiveBasis a c η hc θ).coord i ∘ₗ globalPrimitiveProjection a c η hc θ + +lemma homogeneousPrimitiveDual_unit (i : PrimitiveIndex a c η hc θ) : + homogeneousPrimitiveDual a c η hc θ i (globalUnit a c η hc θ)=0 := by + change (homogeneousPrimitiveBasis a c η hc θ).coord i (globalPrimitiveProjection a c η hc θ _)=0 + rw [globalPrimitiveProjection_unit,map_zero] + +lemma homogeneousPrimitiveDual_apply (i j : PrimitiveIndex a c η hc θ) : + homogeneousPrimitiveDual a c η hc θ i (homogeneousPrimitiveFamily a c η hc θ j)=if i=j then 1 else 0 := by + change (homogeneousPrimitiveBasis a c η hc θ).coord i + (globalPrimitiveProjection a c η hc θ (homogeneousPrimitiveBasis a c η hc θ j).val)=_ + rw [globalPrimitiveProjection_restrict,Module.Basis.coord_apply,Module.Basis.repr_self_apply] + congr 1 + exact propext eq_comm + +noncomputable instance primitiveIndexLinearOrder : LinearOrder (PrimitiveIndex a c η hc θ) := + linearOrderOfSTO WellOrderingRel + +lemma homogeneousPrimitiveWords_independent : + LinearIndependent ℚ (fun l : PBWWord a c η hc θ (homogeneousPrimitiveWeight a c η hc θ)=> + primitiveWord a c η hc θ (homogeneousPrimitiveFamily a c η hc θ) l.val) := + globalPBW_independent a c η hc θ _ _ (homogeneousPrimitiveFamily_weight a c η hc θ) + (homogeneousPrimitiveFamily_primitive a c η hc θ) _ (homogeneousPrimitiveDual_unit a c η hc θ) + (homogeneousPrimitiveDual_apply a c η hc θ) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveBracket.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveBracket.lean new file mode 100644 index 0000000000000000000000000000000000000000..81027d23c9d49ed586de1e73549f235e23ff0dfa --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveBracket.lean @@ -0,0 +1,237 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveGeneration +import OAI.Combinatorics.Chromatic.Shuffle.GlobalSeriesEvaluation + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 norm_num + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma globalColorSign_zero_left (k : SlopeWeight c η hc θ) : + globalColorSign a c η hc θ 0 k=1 := by simp [globalColorSign,eulerForm] +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma globalColorSign_zero_right (k : SlopeWeight c η hc θ) : + globalColorSign a c η hc θ k 0=1 := by simp [globalColorSign,eulerForm] + +omit hχ in +lemma globalHomogeneous_one : (1 : UnitalShuffle a c η hc θ) ∈ globalHomogeneous a c η hc θ 0 := + ⟨unitalGradeOne a c η hc θ,rfl⟩ + +lemma signedTensor_mul_homogeneous {k l m n : SlopeWeight c η hc θ} + {x y z w : UnitalShuffle a c η hc θ} + (hx : x ∈ globalHomogeneous a c η hc θ k) (hy : y ∈ globalHomogeneous a c η hc θ l) + (hz : z ∈ globalHomogeneous a c η hc θ m) (hw : w ∈ globalHomogeneous a c η hc θ n) : + globalSignedTensorMultiply a c η hc θ (x⊗ₜ[ℚ]y) (z⊗ₜ[ℚ]w)= + globalColorSign a c η hc θ l m • ((x*z)⊗ₜ[ℚ](y*w)) := by + obtain ⟨x,rfl⟩ := hx + obtain ⟨y,rfl⟩ := hy + obtain ⟨z,rfl⟩ := hz + obtain ⟨w,rfl⟩ := hw + exact globalSignedTensorMultiply_tmul_lof a c η hc θ k l m n x y z w + +lemma globalPrimitive_product_coproduct {k l : SlopeWeight c η hc θ} + {x y : UnitalShuffle a c η hc θ} + (hx : x ∈ globalHomogeneous a c η hc θ k) (hy : y ∈ globalHomogeneous a c η hc θ l) + (hpx : x ∈ globalPrimitives a c η hc θ) (hpy : y ∈ globalPrimitives a c η hc θ) : + globalCoproduct a c η hc θ (x*y)= + (x*y)⊗ₜ[ℚ](1:UnitalShuffle a c η hc θ)+x⊗ₜ[ℚ]y+ + globalColorSign a c η hc θ k l • (y⊗ₜ[ℚ]x)+ + (1:UnitalShuffle a c η hc θ)⊗ₜ[ℚ](x*y) := by + rw [globalCoproduct_mul,(mem_globalPrimitives a c η hc θ x).mp hpx, + (mem_globalPrimitives a c η hc θ y).mp hpy] + change globalSignedTensorMultiply a c η hc θ (x⊗ₜ[ℚ]1+1⊗ₜ[ℚ]x) (y⊗ₜ[ℚ]1+1⊗ₜ[ℚ]y)=_ + simp only [map_add,LinearMap.add_apply] + rw [signedTensor_mul_homogeneous a c η hc θ hx (globalHomogeneous_one a c η hc θ) hy (globalHomogeneous_one a c η hc θ), + signedTensor_mul_homogeneous a c η hc θ hx (globalHomogeneous_one a c η hc θ) (globalHomogeneous_one a c η hc θ) hy, + signedTensor_mul_homogeneous a c η hc θ (globalHomogeneous_one a c η hc θ) hx hy (globalHomogeneous_one a c η hc θ), + signedTensor_mul_homogeneous a c η hc θ (globalHomogeneous_one a c η hc θ) hx (globalHomogeneous_one a c η hc θ) hy] + simp only [globalColorSign_zero_left,globalColorSign_zero_right,one_smul] + change ((x*y)⊗ₜ[ℚ]((1:UnitalShuffle a c η hc θ)*1)+ + globalColorSign a c η hc θ k l • ((1*y)⊗ₜ[ℚ](x*1)))+ + ((x*1)⊗ₜ[ℚ](1*y)+(1*1)⊗ₜ[ℚ](x*y))=_ + rw [show x*1=x from mul_one x,show (1:UnitalShuffle a c η hc θ)*1=1 from one_mul 1, + show 1*y=y from one_mul y] + abel + +theorem globalPrimitive_bracket {k l : SlopeWeight c η hc θ} + {x y : UnitalShuffle a c η hc θ} + (hx : x ∈ globalHomogeneous a c η hc θ k) (hy : y ∈ globalHomogeneous a c η hc θ l) + (hpx : x ∈ globalPrimitives a c η hc θ) (hpy : y ∈ globalPrimitives a c η hc θ) : + x*y-globalColorSign a c η hc θ k l • (y*x) ∈ globalPrimitives a c η hc θ := by + rw [mem_globalPrimitives,map_sub,map_smul, + globalPrimitive_product_coproduct a c η hc θ hx hy hpx hpy, + globalPrimitive_product_coproduct a c η hc θ hy hx hpy hpx, + globalColorSign_symm a c η hc θ l k] + change _=(x*y-_ • (y*x))⊗ₜ[ℚ]1+1⊗ₜ[ℚ](x*y-_ • (y*x)) + simp only [smul_add,smul_smul,globalColorSign_sq,one_smul, + TensorProduct.sub_tmul,TensorProduct.tmul_sub,TensorProduct.smul_tmul,TensorProduct.tmul_smul] + abel + +theorem globalPrimitive_odd_square {k : SlopeWeight c η hc θ} + {x : UnitalShuffle a c η hc θ} + (hx : x ∈ globalHomogeneous a c η hc θ k) (hpx : x ∈ globalPrimitives a c η hc θ) + (hodd : globalColorSign a c η hc θ k k = -1) : x*x ∈ globalPrimitives a c η hc θ := by + rw [mem_globalPrimitives,globalPrimitive_product_coproduct a c η hc θ hx hx hpx hpx,hodd] + change (x*x)⊗ₜ[ℚ]1+x⊗ₜ[ℚ]x+(-1:ℚ) • (x⊗ₜ[ℚ]x)+1⊗ₜ[ℚ](x*x)= + (x*x)⊗ₜ[ℚ]1+1⊗ₜ[ℚ](x*x) + have hs : (-1:ℚ) • (x⊗ₜ[ℚ]x)= -(x⊗ₜ[ℚ]x) := neg_one_smul ℚ (x⊗ₜ[ℚ]x) + rw [hs] + abel + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 [⟨[],[],1⟩] + | i::l => (signedWordCuts w l).map (SignedWordCut.prependLeft i) ++ + (signedWordCuts w l).map (SignedWordCut.prependRight a c η hc θ w i) + +lemma primitiveWord_nil (b : J → UnitalShuffle a c η hc θ) : primitiveWord a c η hc θ b []=1 := rfl +lemma primitiveWord_cons (b : J → UnitalShuffle a c η hc θ) (i : J) (l : List J) : + primitiveWord a c η hc θ b (i::l)=b i*primitiveWord a c η hc θ b l := rfl + +lemma primitiveWord_homogeneous (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (l : List J) : primitiveWord a c η hc θ b l ∈ + globalHomogeneous a c η hc θ (wordWeight c η hc θ w l) := by + induction l with + | nil => exact globalHomogeneous_one a c η hc θ + | cons i l ih => exact globalHomogeneous_mul a c η hc θ (hb i) ih + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma signedWordCuts_lengths (w : J → SlopeWeight c η hc θ) (l : List J) + (s : SignedWordCut J) (hs : s ∈ signedWordCuts a c η hc θ w l) : + s.left.length+s.right.length=l.length := by + induction l generalizing s with + | nil => simp only [signedWordCuts,List.mem_singleton] at hs; subst s; rfl + | cons i l ih => + simp only [signedWordCuts,List.mem_append,List.mem_map] at hs + rcases hs with ⟨s,hs,rfl⟩ | ⟨s,hs,rfl⟩ + · have h := ih s hs + change (s.left.length+1)+s.right.length=l.length+1 + omega + · have h := ih s hs + change s.left.length+(s.right.length+1)=l.length+1 + omega + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma signedWordCuts_sublist (w : J → SlopeWeight c η hc θ) (l : List J) + (s : SignedWordCut J) (hs : s ∈ signedWordCuts a c η hc θ w l) : + s.left.Sublist l ∧ s.right.Sublist l := by + induction l generalizing s with + | nil => simp only [signedWordCuts,List.mem_singleton] at hs; subst s; exact ⟨.refl _,.refl _⟩ + | cons i l ih => + simp only [signedWordCuts,List.mem_append,List.mem_map] at hs + rcases hs with ⟨s,hs,rfl⟩ | ⟨s,hs,rfl⟩ + · exact ⟨(ih s hs).1.cons_cons i,(ih s hs).2.cons i⟩ + · exact ⟨(ih s hs).1.cons i,(ih s hs).2.cons_cons i⟩ + +noncomputable def wordCutTensor (b : J → UnitalShuffle a c η hc θ) + (s : SignedWordCut J) : UnitalShuffle a c η hc θ⊗[ℚ]UnitalShuffle a c η hc θ := + s.coeff • (primitiveWord a c η hc θ b s.left⊗ₜ[ℚ]primitiveWord a c η hc θ b s.right) + +lemma wordCutTensor_left (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (i : J) (s : SignedWordCut J) : + globalSignedTensorMultiply a c η hc θ (b i⊗ₜ[ℚ]1) (wordCutTensor a c η hc θ b s)= + wordCutTensor a c η hc θ b (s.prependLeft i) := by + unfold wordCutTensor + rw [map_smul,signedTensor_mul_homogeneous a c η hc θ (hb i) (globalHomogeneous_one a c η hc θ) + (primitiveWord_homogeneous a c η hc θ w b hb s.left) + (primitiveWord_homogeneous a c η hc θ w b hb s.right),globalColorSign_zero_left,one_smul] + rw [show (1:UnitalShuffle a c η hc θ)*primitiveWord a c η hc θ b s.right=_ from one_mul _] + rfl + +lemma wordCutTensor_right (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (i : J) (s : SignedWordCut J) : + globalSignedTensorMultiply a c η hc θ (1⊗ₜ[ℚ]b i) (wordCutTensor a c η hc θ b s)= + wordCutTensor a c η hc θ b (s.prependRight a c η hc θ w i) := by + unfold wordCutTensor + rw [map_smul,signedTensor_mul_homogeneous a c η hc θ (globalHomogeneous_one a c η hc θ) (hb i) + (primitiveWord_homogeneous a c η hc θ w b hb s.left) + (primitiveWord_homogeneous a c η hc θ w b hb s.right)] + rw [show (1:UnitalShuffle a c η hc θ)*primitiveWord a c η hc θ b s.left=_ from one_mul _,smul_smul] + rfl + +theorem globalCoproduct_primitiveWord (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (hp : ∀ i,b i ∈ globalPrimitives a c η hc θ) (l : List J) : + globalCoproduct a c η hc θ (primitiveWord a c η hc θ b l)= + ((signedWordCuts a c η hc θ w l).map (wordCutTensor a c η hc θ b)).sum := by + induction l with + | nil => + change globalCoproduct a c η hc θ (globalUnit a c η hc θ)=_ + rw [globalCoproduct_unit] + simp only [signedWordCuts,List.map_singleton,List.sum_singleton,wordCutTensor, + primitiveWord_nil,one_smul] + rfl + | cons i l ih => + rw [primitiveWord_cons,globalCoproduct_mul,(mem_globalPrimitives a c η hc θ (b i)).mp (hp i),ih] + change globalSignedTensorMultiply a c η hc θ (b i⊗ₜ[ℚ]1+1⊗ₜ[ℚ]b i) _=_ + rw [map_add,LinearMap.add_apply] + simp only [map_list_sum,List.map_map,Function.comp_def,signedWordCuts,List.map_append,List.sum_append] + congr 1 + · congr 1 + apply List.map_congr_left + intro s hs + exact wordCutTensor_left a c η hc θ w b hb i s + · congr 1 + apply List.map_congr_left + intro s hs + exact wordCutTensor_right a c η hc θ w b hb i s + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveGeneration.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveGeneration.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e000e5c19637881aa19244355178aef8061cb92 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveGeneration.lean @@ -0,0 +1,188 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveLog +import OAI.Combinatorics.Chromatic.GradedAlgebra.NilpotentSeriesInverse + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv ElementaryPositivity.FiniteLog +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 simpa only [map_add] using S.add_mem ht hu + | tmul x y => + rw [TensorProduct.map_tmul,LinearMap.mul'_apply] + exact S.mul_mem (hf x) (hg y) + +lemma convolution_mapsTo_pow (S : Subalgebra ℚ A) + {f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hf : ∀ x,f.ofConv x ∈ S) (n : ℕ) : ∀ x,(f^n).ofConv x ∈ S := by + induction n with + | zero => intro x; exact S.algebraMap_mem _ + | succ n ih => + rw [pow_succ] + exact convolution_mapsTo_mul a c η hc θ S ih hf + +theorem globalPrimitiveLog_adjoin : + Algebra.adjoin ℚ (Set.range (globalPrimitiveLog a c η hc θ))=⊤ := by + apply top_unique + intro x hx + clear hx + induction x using DirectSum.induction_on with + | zero => exact Subalgebra.zero_mem _ + | add x y hx hy => exact Subalgebra.add_mem _ hx hy + | of k x => + let S := Algebra.adjoin ℚ (Set.range (globalPrimitiveLog a c η hc θ)) + have h := congrArg (fun f=>f.ofConv (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x)) + (globalPrimitiveLog_exponential a c η hc θ) + rw [convSeries_lof] at h + simp only [LinearMap.id_apply] at h + change DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x ∈ S + rw [←h] + apply Subalgebra.sum_mem + intro r hr + exact S.smul_mem (convolution_mapsTo_pow a c η hc θ S + (fun x=>Algebra.subset_adjoin ⟨x,rfl⟩) r _) _ + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0⟨x,rfl⟩ + +omit [Fact (SlopeEulerSymmetric a c η θ)] in +lemma convPreservesWeight_sub + {f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] UnitalShuffle a c η hc θ)} + (hf : convPreservesWeight a c η hc θ f) (hg : convPreservesWeight a c η hc θ g) : + convPreservesWeight a c η hc θ (f-g) := + fun k x=>(globalHomogeneous a c η hc θ k).sub_mem (hf k x) (hg k x) + +lemma globalTensorGrade_map_homogeneous (d e : slopeDimensions c η hc θ) (W : ℤ) + (f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] UnitalShuffle a c η hc θ)) + (hf : convPreservesWeight a c η hc θ f) (hg : convPreservesWeight a c η hc θ g) + (x : UnitalSourceTensorGrade a c η hc θ d.val e.val W) : + LinearMap.mul' ℚ (UnitalShuffle a c η hc θ) + (TensorProduct.map f.ofConv g.ofConv (globalTensorGradeInclusion a c η hc θ d e W x)) ∈ + globalHomogeneous a c η hc θ (d+e,W) := by + induction x using unitalTensorGrade_induction a c η hc θ d.val e.val W with + | hz => simpa only [map_zero] using (globalHomogeneous a c η hc θ (d+e,W)).zero_mem + | ha x y hx hy => simpa only [map_add] using (globalHomogeneous a c η hc θ (d+e,W)).add_mem hx hy + | ht u x y => + rw [globalTensorGradeInclusion_part,TensorProduct.map_tmul,LinearMap.mul'_apply] + have h := globalHomogeneous_mul a c η hc θ (hf (d,u) x) (hg (e,W-u) y) + have heq : (d,u)+(e,W-u)=(d+e,W) := by ext <;> simp + rwa [heq] at h + +lemma convPreservesWeight_mul + {f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] UnitalShuffle a c η hc θ)} + (hf : convPreservesWeight a c η hc θ f) (hg : convPreservesWeight a c η hc θ g) : + convPreservesWeight a c η hc θ (f*g) := by + intro k x + rw [LinearMap.convMul_apply] + change LinearMap.mul' ℚ (UnitalShuffle a c η hc θ) (TensorProduct.map f.ofConv g.ofConv + (globalCoproduct a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x))) ∈ _ + rw [globalCoproduct_lof] + simp only [map_sum] + apply Submodule.sum_mem + intro s hs + have h := globalTensorGrade_map_homogeneous a c η hc θ + ⟨left s.val,s.property.1⟩ ⟨right s.val,s.property.2⟩ k.2 f g hf hg + (unitalGradeCoproduct a c η hc θ (left s.val) (right s.val) + (s.property.1.compatible s.property.2) k.2 + (unitalGradeCast a c η hc θ (left_add_right s.val).symm rfl x)) + have heq : (⟨left s.val,s.property.1⟩+⟨right s.val,s.property.2⟩ : slopeDimensions c η hc θ)=k.1 := + Subtype.ext (left_add_right s.val) + rw [heq] at h + exact h + +lemma convPreservesWeight_pow + {f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] UnitalShuffle a c η hc θ)} + (hf : convPreservesWeight a c η hc θ f) (n : ℕ) : + convPreservesWeight a c η hc θ (f^n) := by + induction n with + | zero => exact convPreservesWeight_one a c η hc θ + | succ n ih => rw [pow_succ]; exact convPreservesWeight_mul a c η hc θ ih hf + +lemma globalPrimitiveLog_homogeneous : + convPreservesWeight a c η hc θ (toConv (globalPrimitiveLog a c η hc θ)) := by + intro k x + change (convSeries a c η hc θ (convolutionJ a c η hc θ) (PowerSeries.log ℚ)).ofConv _ ∈ _ + rw [convSeries_lof] + apply Submodule.sum_mem + intro r hr + exact Submodule.smul_mem _ _ (convPreservesWeight_pow a c η hc θ + (convPreservesWeight_sub a c η hc θ (convPreservesWeight_id a c η hc θ) + (convPreservesWeight_one a c η hc θ)) r k x) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveLog.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveLog.lean new file mode 100644 index 0000000000000000000000000000000000000000..da40404f0ae621c7da9fdfd7ff94c8c764b13496 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveLog.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalConvolutionSeries + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv ElementaryPositivity.FiniteLog +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0x-1) (signedLeftRight_convolution a c η hc θ) + +lemma signedConvolution_J_commute : + Commute (convPost (signedLeftAlgHom a c η hc θ) (convolutionJ a c η hc θ)) + (convPost (signedRightAlgHom a c η hc θ) (convolutionJ a c η hc θ)) := by + have h : Commute (toConv (signedLeft a c η hc θ)) (toConv (signedRight a c η hc θ)) := + (signedLeftRight_convolution a c η hc θ).trans (signedRightLeft_convolution a c η hc θ).symm + simp only [convPost_J] + exact (h.sub_right (Commute.one_right _)).sub_left (Commute.one_left _) + +noncomputable def globalPrimitiveLog : UnitalShuffle a c η hc θ →ₗ[ℚ] UnitalShuffle a c η hc θ := + (convSeries a c η hc θ (convolutionJ a c η hc θ) (PowerSeries.log ℚ)).ofConv + +theorem globalPrimitiveLog_primitive (x : UnitalShuffle a c η hc θ) : + globalCoproduct a c η hc θ (globalPrimitiveLog a c η hc θ x)= + globalPrimitiveLog a c η hc θ x⊗ₜ[ℚ]globalUnit a c η hc θ+ + globalUnit a c η hc θ⊗ₜ[ℚ]globalPrimitiveLog a c η hc θ x := by + have h := convSeries_log_product a c η hc θ (signedConvolution_J_commute a c η hc θ) + (convVanishes_post a c η hc θ (signedLeftAlgHom a c η hc θ) + (convolutionJ_vanishes a c η hc θ)) + (convVanishes_post a c η hc θ (signedRightAlgHom a c η hc θ) + (convolutionJ_vanishes a c η hc θ)) + rw [signedConvolution_J_product,←convSeries_post,←convSeries_post,←convSeries_post] at h + exact congrArg (fun f=>f.ofConv x) h + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveStrings.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveStrings.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0382c537d3b39e52563b2e35f4ad8015427977b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalPrimitiveStrings.lean @@ -0,0 +1,178 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalPBWBasis +import OAI.Combinatorics.Chromatic.Shuffle.GlobalLocalPrimitives +import OAI.Combinatorics.Chromatic.Walls.DirectSumSubtype + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0k.1.val≠0) ∘ₗ + DirectSum.lmap (localPrimitiveInclusion a c η hc θ) + +lemma localPrimitiveSumToGlobal_injective : Function.Injective (localPrimitiveSumToGlobal a c η hc θ) := + (subfamilyInclusion_injective (unitalComponent a c η hc θ) (fun k=>k.1.val≠0)).comp + ((DirectSum.lmap_injective _).mpr (localPrimitiveInclusion_injective a c η hc θ)) + +lemma localPrimitiveSumToGlobal_lof (k : NonzeroSlopeWeight c η hc θ) + (x : primitiveSpace a c η hc θ Fact.out k.val.1.val k.val.2) : + localPrimitiveSumToGlobal a c η hc θ (DirectSum.lof ℚ _ + (fun k : NonzeroSlopeWeight c η hc θ=>primitiveSpace a c η hc θ Fact.out k.val.1.val k.val.2) k x)= + localPrimitiveGlobal a c η hc θ k x := by + change subfamilyInclusion (unitalComponent a c η hc θ) (fun k=>k.1.val≠0) + (DirectSum.lmap (localPrimitiveInclusion a c η hc θ) + (DirectSum.lof ℚ _ _ k x))=_ + rw [DirectSum.lmap_lof] + simp only [subfamilyInclusion,DirectSum.toModule_lof,localPrimitiveGlobal,LinearMap.comp_apply] + +abbrev GlobalStringIndex := Σ k : NonzeroSlopeWeight c η hc θ, + Σ _ : ℕ,StringBaseIndex a c η hc θ Fact.out k.val.1.val k.val.2 + +noncomputable def globalStringFamily (i : GlobalStringIndex a c η hc θ) : UnitalShuffle a c η hc θ := + localPrimitiveGlobal a c η hc θ i.1 + (homogeneousPrimitiveStringBasis a c η hc θ Fact.out i.1.val.1.val i.1.val.2 i.1.property i.2) + +lemma globalStringFamily_mem (i : GlobalStringIndex a c η hc θ) : + globalStringFamily a c η hc θ i ∈ globalPrimitives a c η hc θ := + localPrimitiveGlobal_mem a c η hc θ i.1 _ + +lemma globalStringFamily_weight (i : GlobalStringIndex a c η hc θ) : + globalStringFamily a c η hc θ i ∈ globalHomogeneous a c η hc θ i.1.val := + ⟨localPrimitiveInclusion a c η hc θ i.1 _,rfl⟩ + +lemma globalStringFamily_independent : LinearIndependent ℚ (globalStringFamily a c η hc θ) := by + have hh := directSum_map_independent + (fun k : NonzeroSlopeWeight c η hc θ=>primitiveSpace a c η hc θ Fact.out k.val.1.val k.val.2) + (fun k=>homogeneousPrimitiveStringBasis a c η hc θ Fact.out k.val.1.val k.val.2 k.property) + (fun k=>(homogeneousPrimitiveStringBasis a c η hc θ Fact.out k.val.1.val k.val.2 k.property).linearIndependent) + (localPrimitiveSumToGlobal a c η hc θ) (localPrimitiveSumToGlobal_injective a c η hc θ) + have he : globalStringFamily a c η hc θ=(fun i : GlobalStringIndex a c η hc θ=> + localPrimitiveSumToGlobal a c η hc θ (DirectSum.lof ℚ _ _ i.1 + (homogeneousPrimitiveStringBasis a c η hc θ Fact.out i.1.val.1.val i.1.val.2 i.1.property i.2))) := by + funext i + exact (localPrimitiveSumToGlobal_lof a c η hc θ i.1 _).symm + rw [he] + exact hh + +lemma localPrimitiveGlobal_mem_span (k : NonzeroSlopeWeight c η hc θ) + (x : primitiveSpace a c η hc θ Fact.out k.val.1.val k.val.2) : + localPrimitiveGlobal a c η hc θ k x∈Submodule.span ℚ (Set.range (globalStringFamily a c η hc θ)) := by + have he := congrArg (Submodule.map (localPrimitiveGlobal a c η hc θ k)) + (homogeneousPrimitiveStringBasis a c η hc θ Fact.out k.val.1.val k.val.2 k.property).span_eq + rw [Submodule.map_span,Submodule.map_top] at he + have hx : localPrimitiveGlobal a c η hc θ k x∈LinearMap.range (localPrimitiveGlobal a c η hc θ k) := ⟨x,rfl⟩ + rw [←he] at hx + apply Submodule.span_mono (s:=_) (t:=Set.range (globalStringFamily a c η hc θ)) ?_ hx + rintro y ⟨z,⟨i,rfl⟩,rfl⟩ + exact ⟨⟨k,i⟩,rfl⟩ + +lemma homogeneousPrimitive_mem_stringSpan (k : SlopeWeight c η hc θ) + (x : unitalComponent a c η hc θ k) + (hx : DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x∈globalPrimitives a c η hc θ) : + DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x∈Submodule.span ℚ (Set.range (globalStringFamily a c η hc θ)) := by + by_cases hd : k.1.val=0 + · rw [zeroDimension_lof_scalar a c η hc θ k hd x,globalPrimitive_counit a c η hc θ hx,zero_smul] + exact Submodule.zero_mem _ + · let y : primitiveSpace a c η hc θ Fact.out k.1.val k.2 := + ⟨unitalGradeNonzeroEquiv a c η hc θ k.1.val hd k.2 x, + (globalPrimitive_iff_local a c η hc θ k.1 hd k.2 x).mp hx⟩ + have h:=localPrimitiveGlobal_mem_span a c η hc θ ⟨k,hd⟩ y + change DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k + ((unitalGradeNonzeroEquiv a c η hc θ k.1.val hd k.2).symm + (unitalGradeNonzeroEquiv a c η hc θ k.1.val hd k.2 x))∈_ at h + rwa [LinearEquiv.symm_apply_apply] at h + +lemma globalStringFamily_span : + Submodule.span ℚ (Set.range (globalStringFamily a c η hc θ))=globalPrimitives a c η hc θ := by + apply le_antisymm + · exact Submodule.span_le.mpr (fun x hx=>by obtain ⟨i,rfl⟩:=hx; exact globalStringFamily_mem a c η hc θ i) + · intro x hx + rw [←globalPrimitiveLog_on_primitive a c η hc θ hx] + have hm : ∀ y : UnitalShuffle a c η hc θ,globalPrimitiveLog a c η hc θ y∈ + Submodule.span ℚ (Set.range (globalStringFamily a c η hc θ)) := by + intro y + induction y using DirectSum.induction_on with + | zero => simpa only [map_zero] using (Submodule.span ℚ (Set.range (globalStringFamily a c η hc θ))).zero_mem + | add y z hy hz => simpa only [map_add] using (Submodule.span ℚ (Set.range (globalStringFamily a c η hc θ))).add_mem hy hz + | of k y => + obtain ⟨z,hz⟩ := globalPrimitiveLog_homogeneous a c η hc θ k y + change globalPrimitiveLog a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k y)∈_ + change DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k z=globalPrimitiveLog a c η hc θ _ at hz + rw [←hz] + apply homogeneousPrimitive_mem_stringSpan a c η hc θ k z + rw [hz] + exact (mem_globalPrimitives a c η hc θ _).mpr (globalPrimitiveLog_primitive a c η hc θ _) + exact hm x + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0i.1.val)) ℚ + (UnitalShuffle a c η hc θ) := + primitiveBasisPBW a c η hc θ (globalStringFamily a c η hc θ) (fun i=>i.1.val) + (globalStringFamily_weight a c η hc θ) (globalStringFamily_mem a c η hc θ) + (globalStringFamily_span a c η hc θ) (globalStringFamily_independent a c η hc θ) + +lemma globalStringPBWBasis_apply (l : PBWWord a c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val)) : + globalStringPBWBasis a c η hc θ l=primitiveWord a c η hc θ (globalStringFamily a c η hc θ) l.val := + primitiveBasisPBW_apply a c η hc θ _ _ _ _ _ _ l + +lemma globalStringPBWBasis_weight (l : PBWWord a c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val)) : + globalStringPBWBasis a c η hc θ l∈globalHomogeneous a c η hc θ + (wordWeight c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val) l.val) := by + rw [globalStringPBWBasis_apply] + exact primitiveWord_homogeneous a c η hc θ _ _ (globalStringFamily_weight a c η hc θ) l.val + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalSeriesEvaluation.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalSeriesEvaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f26b0213a1197333d5ead92b02ccd7014b2019d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalSeriesEvaluation.lean @@ -0,0 +1,174 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveLog + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 exact ⟨0,fun n _=>by simp⟩ + | add x y hx hy => + obtain ⟨N,hN⟩ := hx + obtain ⟨M,hM⟩ := hy + refine ⟨max N M,fun n hn=>?_⟩ + rw [map_add,hN n (le_trans (le_max_left _ _) hn),hM n (le_trans (le_max_right _ _) hn)] + simp only [map_add,smul_add,Finset.sum_add_distrib] + | of k x => + refine ⟨dimensionSize k.1.val+1,fun n hn=>?_⟩ + change (convSeries a c η hc θ f p).ofConv + (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x)= + ∑ r ∈ Finset.range n,PowerSeries.coeff r p • + (f^r).ofConv (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x) + rw [convSeries_lof] + apply Finset.sum_subset (Finset.range_mono hn) + intro r hr hsmall + rw [Finset.mem_range,not_lt] at hsmall + rw [convVanishes_pow a c η hc θ hf r k (by omega) x,smul_zero] + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0globalCounit a c η hc θ + (TensorProduct.lid ℚ (UnitalShuffle a c η hc θ) t)) h + simp only [map_add,TensorProduct.lid_tmul,map_smul,globalCounit_unit,smul_eq_mul, + mul_one,one_mul] at he + exact add_eq_right.mp he + +omit [Fact (SlopeEulerSymmetric a c η θ)] in +lemma convVanishes_unit {A : Type*} [Ring A] [Algebra ℚ A] + {f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hf : convVanishes a c η hc θ 1 f) : f.ofConv (globalUnit a c η hc θ)=0 := + hf (0,0) (by simp [dimensionSize]) (unitalGradeOne a c η hc θ) + +lemma convolution_mul_primitive {A : Type*} [Ring A] [Algebra ℚ A] + (f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)) + {x : UnitalShuffle a c η hc θ} (hx : x ∈ globalPrimitives a c η hc θ) : + (f*g).ofConv x=f.ofConv x*g.ofConv (globalUnit a c η hc θ)+ + f.ofConv (globalUnit a c η hc θ)*g.ofConv x := by + rw [LinearMap.convMul_apply] + change LinearMap.mul' ℚ A (TensorProduct.map f.ofConv g.ofConv + (globalCoproduct a c η hc θ x))=_ + rw [(mem_globalPrimitives a c η hc θ x).mp hx,map_add,map_add] + simp only [TensorProduct.map_tmul,LinearMap.mul'_apply] + +lemma convolution_pow_primitive {A : Type*} [Ring A] [Algebra ℚ A] + {f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hf : convVanishes a c η hc θ 1 f) + {x : UnitalShuffle a c η hc θ} (hx : x ∈ globalPrimitives a c η hc θ) + (r : ℕ) (hr : 2 ≤ r) : (f^r).ofConv x=0 := by + obtain ⟨r,rfl⟩ := Nat.exists_eq_add_of_le hr + rw [show 2+r=(1+r)+1 by omega,pow_succ,convolution_mul_primitive a c η hc θ _ _ hx, + convVanishes_unit a c η hc θ hf] + have hp := convVanishes_mono a c η hc θ (by omega : 1 ≤ 1+r) + (convVanishes_pow a c η hc θ hf (1+r)) + rw [convVanishes_unit a c η hc θ hp,mul_zero,zero_mul,add_zero] + +lemma convolutionJ_primitive {x : UnitalShuffle a c η hc θ} + (hx : x ∈ globalPrimitives a c η hc θ) : + (convolutionJ a c η hc θ).ofConv x=x := by + change x-algebraMap ℚ (UnitalShuffle a c η hc θ) (globalCounit a c η hc θ x)=x + rw [globalPrimitive_counit a c η hc θ hx,map_zero,sub_zero] + +lemma globalPrimitiveLog_homogeneous_primitive (k : SlopeWeight c η hc θ) + (x : unitalComponent a c η hc θ k) + (hx : DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x ∈ globalPrimitives a c η hc θ) : + globalPrimitiveLog a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x)= + DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x := by + change (convSeries a c η hc θ (convolutionJ a c η hc θ) (PowerSeries.log ℚ)).ofConv _=_ + rw [convSeries_lof] + by_cases hd : dimensionSize k.1.val=0 + · have hz := zeroDimension_lof_scalar a c η hc θ k ((dimensionSize_eq_zero _).mp hd) x + rw [globalPrimitive_counit a c η hc θ hx,zero_smul] at hz + simp only [hd,zero_add,Finset.sum_range_one,PowerSeries.coeff_zero_eq_constantCoeff, + PowerSeries.constantCoeff_log,zero_smul,hz] + · rw [Finset.sum_eq_single 1] + · rw [pow_one,convolutionJ_primitive a c η hc θ hx] + simp + · intro r hr hr1 + by_cases hr0 : r=0 + · subst r + simp + · rw [convolution_pow_primitive a c η hc θ (convolutionJ_vanishes a c η hc θ) hx r + (by omega),smul_zero] + · intro h + exact False.elim (h (Finset.mem_range.mpr (by omega))) + +theorem globalPrimitiveLog_on_primitive {x : UnitalShuffle a c η hc θ} + (hx : x ∈ globalPrimitives a c η hc θ) : globalPrimitiveLog a c η hc θ x=x := by + obtain ⟨N,hN⟩ := convSeries_eventually_finite a c η hc θ + (convolutionJ_vanishes a c η hc θ) (PowerSeries.log ℚ) x + change (convSeries a c η hc θ (convolutionJ a c η hc θ) (PowerSeries.log ℚ)).ofConv x=x + rw [hN (max N 2) (le_max_left _ _),Finset.sum_eq_single 1] + · rw [pow_one,convolutionJ_primitive a c η hc θ hx] + simp + · intro r hr hr1 + by_cases hr0 : r=0 + · subst r; simp + · rw [convolution_pow_primitive a c η hc θ (convolutionJ_vanishes a c η hc θ) hx r + (by omega),smul_zero] + · intro h + exact False.elim (h (Finset.mem_range.mpr (lt_of_lt_of_le (by omega) (le_max_right _ _)))) + +theorem globalPrimitiveLog_range : LinearMap.range (globalPrimitiveLog a c η hc θ)= + globalPrimitives a c η hc θ := by + apply le_antisymm + · rintro y ⟨x,rfl⟩ + exact (mem_globalPrimitives a c η hc θ _).mpr (globalPrimitiveLog_primitive a c η hc θ x) + · intro x hx + exact ⟨x,globalPrimitiveLog_on_primitive a c η hc θ hx⟩ + +theorem globalPrimitiveLog_idempotent : + (globalPrimitiveLog a c η hc θ).comp (globalPrimitiveLog a c η hc θ)=globalPrimitiveLog a c η hc θ := by + apply LinearMap.ext + intro x + exact globalPrimitiveLog_on_primitive a c η hc θ + ((mem_globalPrimitives a c η hc θ _).mpr (globalPrimitiveLog_primitive a c η hc θ x)) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalShuffleCoalgebra.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalShuffleCoalgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..499f5e9d4825182240f6bd40fcf7f45226074e28 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalShuffleCoalgebra.lean @@ -0,0 +1,163 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SlopeGridSum +import OAI.Combinatorics.Chromatic.Shuffle.GlobalCoproductCoassociative +import OAI.Combinatorics.Chromatic.Shuffle.GlobalCoproductUnits +import OAI.Combinatorics.Chromatic.Shuffle.GlobalTensorInduction + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +noncomputable instance globalCoalgebra (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0funext h,fun h i=>congrFun h i⟩ + +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0hf k (lt_of_lt_of_le hk h) + +omit [Fact (SlopeEulerSymmetric a c η θ)] in +lemma globalTensorGrade_map_vanishes (n m : ℕ) + (f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)) + (hf : convVanishes a c η hc θ n f) (hg : convVanishes a c η hc θ m g) + (d e : slopeDimensions c η hc θ) (h : dimensionSize d.val+dimensionSize e.val < n+m) + (W : ℤ) (x : UnitalSourceTensorGrade a c η hc θ d.val e.val W) : + TensorProduct.map f.ofConv g.ofConv (globalTensorGradeInclusion a c η hc θ d e W x)=0 := by + induction x using unitalTensorGrade_induction a c η hc θ d.val e.val W with + | hz => simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy,add_zero] + | ht u x y => + rw [globalTensorGradeInclusion_part,TensorProduct.map_tmul] + by_cases hd : dimensionSize d.val < n + · rw [hf (d,u) hd x,TensorProduct.zero_tmul] + · have he : dimensionSize e.val < m := by omega + rw [hg (e,W-u) he y,TensorProduct.tmul_zero] + +lemma convVanishes_mul {n m : ℕ} + {f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hf : convVanishes a c η hc θ n f) (hg : convVanishes a c η hc θ m g) : + convVanishes a c η hc θ (n+m) (f*g) := by + intro k hk x + rw [LinearMap.convMul_apply] + change LinearMap.mul' ℚ A (TensorProduct.map f.ofConv g.ofConv + (globalCoproduct a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x)))=0 + rw [globalCoproduct_lof] + simp only [map_sum] + apply Finset.sum_eq_zero + intro s _ + change LinearMap.mul' ℚ A (TensorProduct.map f.ofConv g.ofConv + (globalTensorGradeInclusion a c η hc θ ⟨left s.val,s.property.1⟩ + ⟨right s.val,s.property.2⟩ k.2 _))=0 + rw [globalTensorGrade_map_vanishes a c η hc θ n m f g hf hg] + · exact (LinearMap.mul' ℚ A).map_zero + · rw [←dimensionSize_add,left_add_right] + exact hk + +lemma convVanishes_pow {f : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] A)} + (hf : convVanishes a c η hc θ 1 f) (n : ℕ) : + convVanishes a c η hc θ n (f^n) := by + induction n with + | zero => exact convVanishes_zero a c η hc θ _ + | succ n ih => + rw [pow_succ] + exact convVanishes_mul a c η hc θ ih hf + +noncomputable def convolutionJ : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] UnitalShuffle a c η hc θ) := + toConv LinearMap.id - 1 + +lemma zeroDimension_lof_scalar (k : SlopeWeight c η hc θ) (h : k.1.val=0) + (x : unitalComponent a c η hc θ k) : + DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x = + globalCounit a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x) • + globalUnit a c η hc θ := by + rcases k with ⟨⟨d,hd⟩,W⟩ + dsimp at h + subst d + by_cases hW : W=0 + · subst W + change DirectSum.lof ℚ _ (unitalComponent a c η hc θ) 0 x = + globalCounit a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) 0 x) • + globalUnit a c η hc θ + rw [globalCounit_lof_zero,globalUnit,←map_smul] + exact congrArg (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) 0) + (zeroGrade_eq_scalar a c η hc θ x) + · let := zeroUnitalGrade_subsingleton a c η hc θ W hW + have hx : x=0 := Subsingleton.elim _ _ + simp only [hx,map_zero,zero_smul] + +lemma convolutionJ_vanishes : convVanishes a c η hc θ 1 (convolutionJ a c η hc θ) := by + intro k hk x + have hd : k.1.val=0 := (dimensionSize_eq_zero _).mp (by omega) + change DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x - + algebraMap ℚ (UnitalShuffle a c η hc θ) + (globalCounit a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x))=0 + rw [Algebra.algebraMap_eq_smul_one,sub_eq_zero] + change DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x = + globalCounit a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x) • + globalUnit a c η hc θ + exact zeroDimension_lof_scalar a c η hc θ k hd x + +lemma convolutionJ_pow_eq_zero (k : SlopeWeight c η hc θ) + (x : unitalComponent a c η hc θ k) (r : ℕ) (hr : dimensionSize k.1.val < r) : + ((convolutionJ a c η hc θ)^r).ofConv + (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x)=0 := + convVanishes_pow a c η hc θ (convolutionJ_vanishes a c η hc θ) r k hr x + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorDetection.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorDetection.lean new file mode 100644 index 0000000000000000000000000000000000000000..98a5e03e2b2b168408ab31675b374aac96dad53c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorDetection.lean @@ -0,0 +1,161 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalSeriesEvaluation + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.LinearFiltration DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0UnitalSourceGrade a c η hc θ d v⊗[ℚ]UnitalSourceGrade a c η hc θ e (W-v)) v (x⊗ₜ[ℚ]y) := + tensorGradeEquiv_symm_inclusion _ _ _ _ W v _ + +lemma globalTensorComponent_inclusion (d e : slopeDimensions c η hc θ) (W u : ℤ) + (x : UnitalSourceTensorGrade a c η hc θ d.val e.val W) : + globalTensorComponent a c η hc θ (d,u) (e,W-u) (globalTensorGradeInclusion a c η hc θ d e W x)= + DirectSum.component ℚ ℤ _ u ((unitalSourceTensorGradeEquiv a c η hc θ d.val e.val W).symm x) := by + induction x using unitalTensorGrade_induction a c η hc θ d.val e.val W with + | hz => simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy] + | ht v x y => + rw [globalTensorGradeInclusion_part] + rw [unitalSourceTensorGradeEquiv_symm_part] + change TensorProduct.map _ _ (_⊗ₜ[ℚ]_)=_ + rw [TensorProduct.map_tmul] + by_cases hv : v=u + · subst v + simp only [DirectSum.component.lof_self] + · rw [globalComponent_lof_ne a c η hc θ (d,u) (d,v) (by simpa using hv),TensorProduct.zero_tmul, + DirectSum.component.of,dite_eq_right hv] + +lemma globalTensorGradeInclusion_injective (d e : slopeDimensions c η hc θ) (W : ℤ) : + Function.Injective (globalTensorGradeInclusion a c η hc θ d e W) := by + intro x y h + apply (unitalSourceTensorGradeEquiv a c η hc θ d.val e.val W).symm.injective + apply DirectSum.ext_component ℚ + intro u + simpa only [globalTensorComponent_inclusion] using + congrArg (globalTensorComponent a c η hc θ (d,u) (e,W-u)) h + +lemma globalTensorComponent_inclusion_ne_left (k l : SlopeWeight c η hc θ) + (d e : slopeDimensions c η hc θ) (h : d≠k.1) (W : ℤ) + (x : UnitalSourceTensorGrade a c η hc θ d.val e.val W) : + globalTensorComponent a c η hc θ k l (globalTensorGradeInclusion a c η hc θ d e W x)=0 := by + induction x using unitalTensorGrade_induction a c η hc θ d.val e.val W with + | hz => simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy,add_zero] + | ht u x y => + rw [globalTensorGradeInclusion_part] + change TensorProduct.map _ _ (_⊗ₜ[ℚ]_)=0 + rw [TensorProduct.map_tmul,globalComponent_lof_ne a c η hc θ k (d,u) + (fun he=>h (congrArg Prod.fst he)),TensorProduct.zero_tmul] + +lemma globalTensorComponent_split_ne (k : SlopeWeight c η hc θ) + (s t : SlopeSplit c η hc θ k.1.val) (h : t≠s) (u : ℤ) + (x : unitalComponent a c η hc θ k) : + globalTensorComponent a c η hc θ (⟨left s.val,s.property.1⟩,u) + (⟨right s.val,s.property.2⟩,k.2-u) (globalSplitCoproduct a c η hc θ k t x)=0 := by + apply globalTensorComponent_inclusion_ne_left + intro he + apply h + exact Subtype.ext (DimensionSplit.ext (congrArg Subtype.val he)) + +lemma globalTensorComponent_coproduct (k : SlopeWeight c η hc θ) + (s : SlopeSplit c η hc θ k.1.val) (u : ℤ) (x : unitalComponent a c η hc θ k) : + globalTensorComponent a c η hc θ (⟨left s.val,s.property.1⟩,u) + (⟨right s.val,s.property.2⟩,k.2-u) + (globalCoproduct a c η hc θ (DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x))= + globalTensorComponent a c η hc θ (⟨left s.val,s.property.1⟩,u) + (⟨right s.val,s.property.2⟩,k.2-u) (globalSplitCoproduct a c η hc θ k s x) := by + rw [globalCoproduct_lof,map_sum,Finset.sum_eq_single s] + · intro t ht hts + exact globalTensorComponent_split_ne a c η hc θ k s t hts u x + · simp + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0hk (congrArg (fun z : SlopeWeight c η hc θ=>z.1.val) h).symm) _ + +lemma globalPrimitive_split_zero (k : SlopeWeight c η hc θ) + (s : SlopeSplit c η hc θ k.1.val) (hl : left s.val≠0) (hr : right s.val≠0) + (x : unitalComponent a c η hc θ k) + (hx : DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x∈globalPrimitives a c η hc θ) : + globalSplitCoproduct a c η hc θ k s x=0 := by + change globalTensorGradeInclusion a c η hc θ _ _ _ _=0 + rw [←map_zero (globalTensorGradeInclusion a c η hc θ ⟨left s.val,s.property.1⟩ ⟨right s.val,s.property.2⟩ k.2)] + congr 1 + apply (unitalSourceTensorGradeEquiv a c η hc θ (left s.val) (right s.val) k.2).symm.injective + apply DirectSum.ext_component ℚ + intro u + rw [map_zero,map_zero] + rw [←globalTensorComponent_inclusion a c η hc θ ⟨left s.val,s.property.1⟩ ⟨right s.val,s.property.2⟩ k.2 u] + change globalTensorComponent a c η hc θ _ _ (globalSplitCoproduct a c η hc θ k s x)=0 + rw [←globalTensorComponent_coproduct,(mem_globalPrimitives a c η hc θ _).mp hx,map_add] + change TensorProduct.map _ _ (_⊗ₜ[ℚ]_) + TensorProduct.map _ _ (_⊗ₜ[ℚ]_)=0 + rw [TensorProduct.map_tmul,TensorProduct.map_tmul,globalComponent_unit a c η hc θ (⟨left s.val,s.property.1⟩,u) hl, + globalComponent_unit a c η hc θ (⟨right s.val,s.property.2⟩,k.2-u) hr,TensorProduct.tmul_zero,TensorProduct.zero_tmul,add_zero] + +lemma globalPrimitive_iff_split_zero (k : SlopeWeight c η hc θ) (hk : k.1.val≠0) + (x : unitalComponent a c η hc θ k) : + DirectSum.lof ℚ _ (unitalComponent a c η hc θ) k x∈globalPrimitives a c η hc θ ↔ + ∀ s : SlopeSplit c η hc θ k.1.val,left s.val≠0 → right s.val≠0 → + globalSplitCoproduct a c η hc θ k s x=0 := by + constructor + · exact fun hx s hl hr=>globalPrimitive_split_zero a c η hc θ k s hl hr x hx + · intro hx + rw [mem_globalPrimitives,globalCoproduct_lof] + let l := slopeSplitZeroLeft c η hc θ k.1 + let r := slopeSplitZeroRight c η hc θ k.1 + have hlr : l≠r := by + intro h + have hh := congrArg (fun s : SlopeSplit c η hc θ k.1.val=>left s.val) h + exact hk hh.symm + have hs : (∑ s : SlopeSplit c η hc θ k.1.val,globalSplitCoproduct a c η hc θ k s x)= + ∑ s∈({l,r} : Finset _),globalSplitCoproduct a c η hc θ k s x := by + symm + apply Finset.sum_subset (Finset.subset_univ _) + intro s _ hs + simp only [Finset.mem_insert,Finset.mem_singleton,not_or] at hs + exact hx s (slopeSplit_ne_left_zero c η hc θ k.1 s hs.1) + (slopeSplit_ne_right_zero c η hc θ k.1 s hs.2) + rw [hs,Finset.sum_pair hlr,globalSplitCoproduct_zero_left,globalSplitCoproduct_zero_right,add_comm] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorGradeProduct.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorGradeProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..000866e7a1feb97adafe93ac8e8a3e2f8c655de2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorGradeProduct.lean @@ -0,0 +1,219 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalCoproductComparison +import OAI.Combinatorics.Chromatic.Shuffle.TensorMiddleEnd + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +omit [DecidableEq I] in +lemma slopeDimensions_onSlope (c η : I → ℝ) (hc : ∀ i,0 simp only [map_zero,LinearMap.zero_apply] + | ha x x' hx hx' => simp only [map_add,LinearMap.add_apply,hx,hx'] + | ht u x₁ x₂ => + induction y using unitalTensorGrade_induction a c η hc θ e₁.val e₂.val V with + | hz => simp only [map_zero] + | ha y y' hy hy' => simp only [map_add,hy,hy'] + | ht v y₁ y₂ => + rw [signedCellGradeMultiply_part a c η hc θ hχ.out d₁.val e₁.val d₂.val e₂.val + (slopeDimensions_cellsOnSlope c η hc θ d₁ e₁ d₂ e₂) U V u v x₁ x₂ y₁ y₂, + map_smul,globalTensorGradeInclusion_part a c η hc θ d₁ d₂, + globalTensorGradeInclusion_part a c η hc θ e₁ e₂] + rw [globalTensorGradeInclusion_part_add,globalSignedTensorMultiply_tmul_lof] + rw [unitalLof_cast a c η hc θ (d:=d₂+e₂) (e:=d₂+e₂) + rfl (show (U-u)+(V-v)=U+V-(u+v) by omega)] + rw [unitalLof_shuffle,unitalLof_shuffle] + +lemma globalTensorGradeInclusion_signedProduct_cast (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + let : AddCommGroup (LinearDetection.additiveTensorFiltration + (unitalSourceFiltration a c η hc θ e) (unitalSourceFiltration a c η hc θ d) W) := + Submodule.addCommGroup _ + let : Module ℚ (LinearDetection.additiveTensorFiltration + (unitalSourceFiltration a c η hc θ e) (unitalSourceFiltration a c η hc θ d) W) := + Submodule.module _ + rw [unitalGradeCast_mk,unitalGradeCoproduct_mk,unitalGradeCoproduct_mk] + apply sub_eq_zero.mp + unfold unitalSourceTensorFiltration at * + change Submodule.Quotient.mk + ((⟨unitalSeparationConstant a c η hc e d (he.compatible hd) + (unitalFiltrationCast a c η hc θ (add_comm d e) rfl x).val, _⟩ : + LinearDetection.additiveTensorFiltration (unitalSourceFiltration a c η hc θ e) + (unitalSourceFiltration a c η hc θ d) W) - + (-1:ℚ)^eulerForm a d e • (tensorFiltrationComm + (unitalSourceFiltration a c η hc θ d) (unitalSourceFiltration a c η hc θ e) W + ⟨unitalSeparationConstant a c η hc d e (hd.compatible he) x.val, _⟩ : + LinearDetection.additiveTensorFiltration (unitalSourceFiltration a c η hc θ e) + (unitalSourceFiltration a c η hc θ d) W))=0 + apply (Submodule.Quotient.mk_eq_zero _).mpr + change unitalSeparationConstant a c η hc e d (he.compatible hd) + (unitalFiltrationCast a c η hc θ (add_comm d e) rfl x).val - + (-1:ℚ)^eulerForm a d e • TensorProduct.comm ℚ _ _ + (unitalSeparationConstant a c η hc d e (hd.compatible he) x.val)∈ + unitalSourceTensorFiltration a c η hc θ e d (W+1) + rw [unitalFiltrationCast_val] + exact unitalSeparationConstant_cocommutative_filtration a c η hc θ hχ d e hd he W x.val x.property + +lemma unitalTensorGradeComm_part (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + induction y using Submodule.Quotient.induction_on with + | H y => + simp only [unitalTensorGradeInclusionW,unitalGradeCast_mk, + unitalTensorGradeComm] + apply congrArg (mk _ _) + apply Subtype.ext + change y.val⊗ₜ[ℚ]x.val=y.val⊗ₜ[ℚ](unitalFiltrationCast a c η hc θ rfl _ x).val + rw [unitalFiltrationCast_val,castB_rfl] + +lemma globalTensorGradeInclusion_comm (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy] + | ht u x y => + rw [unitalTensorGradeComm_part,globalTensorGradeInclusion_part,globalTensorGradeInclusion_part, + TensorProduct.comm_tmul,unitalLof_cast a c η hc θ (d:=d) (e:=d)] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorInduction.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorInduction.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5f578840b3610a68ccbab115e529251621d8028 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTensorInduction.lean @@ -0,0 +1,188 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.TensorMiddleEnd +import OAI.Combinatorics.Chromatic.Shuffle.UnitalGradeCoproductUnits + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma globalTensor_induction (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 exact ha x y hx hy + | tmul x y => + induction x using DirectSum.induction_on with + | zero => simpa only [TensorProduct.zero_tmul] using hz + | add x x' hx hx' => rw [TensorProduct.add_tmul]; exact ha _ _ hx hx' + | of k x => + induction y using DirectSum.induction_on with + | zero => simpa only [TensorProduct.tmul_zero] using hz + | add y y' hy hy' => rw [TensorProduct.tmul_add]; exact ha _ _ hy hy' + | of l y => exact ht k l x y + +lemma globalLof_mul (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero,LinearMap.zero_apply] + | ha x x' hx hx' => simp only [map_add,LinearMap.add_apply,hx,hx'] + | ht k l x y => + induction y₀ using globalTensor_induction a c η hc θ with + | hz => simp only [map_zero,LinearMap.zero_apply] + | ha z z' hz hz' => simp only [map_add,LinearMap.add_apply,hz,hz'] + | ht m n z w => + induction z₀ using globalTensor_induction a c η hc θ with + | hz => simp only [map_zero] + | ha v v' hv hv' => simp only [map_add,hv,hv'] + | ht p q v u => exact globalSignedTensorMultiply_assoc_homogeneous a c η hc θ k l m n p q x y z w v u +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +lemma globalSignedTensorMultiply_one_left (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy] + | ht k l x y => + rw [globalUnit,globalSignedTensorMultiply_tmul_lof] + change ((-1:ℚ)^eulerForm a 0 k.1.val) • ((1 * _)⊗ₜ[ℚ](1 * _))=_ + simp only [eulerForm,Pi.zero_apply,Int.natCast_zero,zero_mul,mul_zero,Finset.sum_const_zero,sub_zero,zpow_zero,one_smul] + exact congrArg₂ (fun x y : UnitalShuffle a c η hc θ=>x⊗ₜ[ℚ]y) (one_mul _) (one_mul _) + +lemma globalSignedTensorMultiply_one_right (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero,LinearMap.zero_apply] + | ha x y hx hy => simp only [map_add,LinearMap.add_apply,hx,hy] + | ht k l x y => + rw [globalUnit,globalSignedTensorMultiply_tmul_lof] + change ((-1:ℚ)^eulerForm a l.1.val 0) • ((_ * 1)⊗ₜ[ℚ](_ * 1))=_ + simp only [eulerForm,Pi.zero_apply,Int.natCast_zero,mul_zero,Finset.sum_const_zero,sub_zero,zpow_zero,one_smul] + exact congrArg₂ (fun x y : UnitalShuffle a c η hc θ=>x⊗ₜ[ℚ]y) (mul_one _) (mul_one _) + +def SignedGlobalTensor (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0map_add (globalSignedTensorMultiply a c η hc θ x) y z + right_distrib := fun x y z=>by + exact LinearMap.congr_fun (map_add (globalSignedTensorMultiply a c η hc θ) x y) z + zero_mul := fun x=>by + exact LinearMap.congr_fun (map_zero (globalSignedTensorMultiply a c η hc θ)) x + mul_zero := fun x=>map_zero (globalSignedTensorMultiply a c η hc θ x) + natCast n := n • (globalUnit a c η hc θ⊗ₜ[ℚ]globalUnit a c η hc θ) + natCast_zero := zero_nsmul _ + natCast_succ n := by + change (n+1) • (globalUnit a c η hc θ⊗ₜ[ℚ]globalUnit a c η hc θ)=_ + exact succ_nsmul _ _ + intCast n := n • (globalUnit a c η hc θ⊗ₜ[ℚ]globalUnit a c η hc θ) + intCast_ofNat n := natCast_zsmul _ _ + intCast_negSucc n := negSucc_zsmul _ _ + +noncomputable instance (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0LinearMap.congr_fun (map_smul (globalSignedTensorMultiply a c η hc θ) r x) y) + (fun r x y=>map_smul (globalSignedTensorMultiply a c η hc θ x) r y) +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTripleGradeInclusion.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTripleGradeInclusion.lean new file mode 100644 index 0000000000000000000000000000000000000000..79d5cf5071e9cd0c49f7a6b664fa120a64ad5dcc --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalTripleGradeInclusion.lean @@ -0,0 +1,265 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SignedCoproductGridGrade +import OAI.Combinatorics.Chromatic.Shuffle.UnitalCoproductCoassociative + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration + ElementaryPositivity.LinearDetection DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +noncomputable def globalTripleGradeLeft (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (f,w)) W + +noncomputable def globalTripleGradeRight (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (d,w)) + (globalTensorGradeInclusion a c η hc θ e f) W + +lemma globalTripleGrade_assoc (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (d,u)) + (fun u=>DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (e,u)) + (fun u=>DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (f,u)) W x + +lemma globalTripleGrade_left_natural (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(globalTensorGradeInclusion a c η hc θ d e u).comp + (unitalGradeCoproduct a c η hc θ d.val e.val (d.property.compatible e.property) u)) + (fun u=>DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (f,u)) W x := by + have H := tensorGradeLift_map_natural + (unitalSourceFiltration a c η hc θ (d.val+e.val)) + (unitalSourceFiltration a c η hc θ f.val) + (unitalSourceTensorFiltration a c η hc θ d.val e.val) + (unitalSourceFiltration a c η hc θ f.val) + (unitalSourceFiltration_antitone a c η hc θ (d.val+e.val)) + (unitalSourceFiltration_antitone a c η hc θ f.val) + (unitalSourceTensorFiltration_antitone a c η hc θ d.val e.val) + (unitalSourceFiltration_antitone a c η hc θ f.val) + (unitalSeparationConstant a c η hc d.val e.val (d.property.compatible e.property)) + LinearMap.id + (unitalSeparationConstant_filtered a c η hc θ d.val e.val (d.property.compatible e.property)) + (fun _ _ h=>h) + (globalTensorGradeInclusion a c η hc θ d e) + (fun u=>DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (f,u)) W x + simp only [gradeMap_id] at H + exact H + +lemma globalTripleGrade_right_natural (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (d,u)) + (fun u=>(globalTensorGradeInclusion a c η hc θ e f u).comp + (unitalGradeCoproduct a c η hc θ e.val f.val (e.property.compatible f.property) u)) W x := by + have H := tensorGradeLift_map_natural + (unitalSourceFiltration a c η hc θ d.val) + (unitalSourceFiltration a c η hc θ (e.val+f.val)) + (unitalSourceFiltration a c η hc θ d.val) + (unitalSourceTensorFiltration a c η hc θ e.val f.val) + (unitalSourceFiltration_antitone a c η hc θ d.val) + (unitalSourceFiltration_antitone a c η hc θ (e.val+f.val)) + (unitalSourceFiltration_antitone a c η hc θ d.val) + (unitalSourceTensorFiltration_antitone a c η hc θ e.val f.val) + LinearMap.id + (unitalSeparationConstant a c η hc e.val f.val (e.property.compatible f.property)) + (fun _ _ h=>h) + (unitalSeparationConstant_filtered a c η hc θ e.val f.val (e.property.compatible f.property)) + (fun u=>DirectSum.lof ℚ _ (unitalComponent a c η hc θ) (d,u)) + (globalTensorGradeInclusion a c η hc θ e f) W x + simp only [gradeMap_id] at H + exact H + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +abbrev LeftSlopeTriple (c η : I → ℝ) (hc : ∀ i,0p.val.1) h + have h2 : right t.val=right t'.val := congrArg (fun p=>p.val.2.1) h + have hs : s=s' := by + apply Subtype.ext + apply DimensionSplit.ext + rw [←left_add_right t.val,←left_add_right t'.val,h1,h2] + subst s' + have ht : t=t' := Subtype.ext (DimensionSplit.ext h1) + subst t' + rfl + +omit [DecidableEq I] in +lemma rightTripleView_injective (c η : I → ℝ) (hc : ∀ i,0p.val.1) h + have h2 : left t.val=left t'.val := congrArg (fun p=>p.val.2.1) h + have hs : s=s' := Subtype.ext (DimensionSplit.ext h1) + subst s' + have ht : t=t' := Subtype.ext (DimensionSplit.ext h2) + subst t' + rfl + +omit [DecidableEq I] in +lemma leftTripleView_surjective (c η : I → ℝ) (hc : ∀ i,0by + apply congrArg F + exact ((rightTripleEquiv c η hc θ d).apply_symm_apply + (leftTripleEquiv c η hc θ d p)).symm) +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalWordDetection.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalWordDetection.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ad9fe1a43256dbeb4adca393d774432489188d3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalWordDetection.lean @@ -0,0 +1,204 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalWordPairing + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 simp only [signedWordCuts,List.mem_singleton] at hs; subst s; exact .refl _ + | cons i l ih => + simp only [signedWordCuts,List.mem_append,List.mem_map] at hs + rcases hs with ⟨s,hs,rfl⟩ | ⟨s,hs,rfl⟩ + · exact (ih s hs).cons i + · exact List.perm_middle.trans ((ih s hs).cons i) + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma singletonCutSum_not_mem (w : J → SlopeWeight c η hc θ) (i : J) (l : List J) + (g : List J → ℚ) (hi : i ∉ l) : singletonCutSum a c η hc θ w i l g=0 := by + unfold singletonCutSum + apply List.sum_eq_zero + intro z hz + obtain ⟨s,hs,rfl⟩ := List.mem_map.mp hz + apply ite_eq_right + intro h + apply hi + exact (signedWordCuts_sublist a c η hc θ w l s hs).1.subset (by simp [h]) + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma singletonCutSum_congr (w : J → SlopeWeight c η hc θ) (i : J) (l : List J) + (g h : List J → ℚ) + (he : ∀ s ∈ signedWordCuts a c η hc θ w l, s.left=[i] → g s.right=h s.right) : + singletonCutSum a c η hc θ w i l g=singletonCutSum a c η hc θ w i l h := by + unfold singletonCutSum + congr 1 + apply List.map_congr_left + intro s hs + by_cases hi : s.left=[i] + · rw [ite_eq_left hi,ite_eq_left hi,he s hs hi] + · rw [ite_eq_right hi,ite_eq_right hi] + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma singletonCutSum_unique (w : J → SlopeWeight c η hc θ) (i : J) (l : List J) + (g : List J → ℚ) (hi : i ∉ l) : singletonCutSum a c η hc θ w i (i::l) g=g l := by + rw [singletonCutSum_cons,ite_eq_left rfl,singletonCutSum_not_mem a c η hc θ w i l _ hi,mul_zero,add_zero] + +lemma functionalWord_top_not_perm (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (hp : ∀ i,b i ∈ globalPrimitives a c η hc θ) + (f : J → UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ) (hf : ∀ i,f i (globalUnit a c η hc θ)=0) + (hfb : ∀ i j,f i (b j)=if i=j then 1 else 0) + (u v : List J) (h : v.length=u.length) (hne : ¬u.Perm v) : + (functionalWord a c η hc θ f u).ofConv (primitiveWord a c η hc θ b v)=0 := by + induction u generalizing v with + | nil => + have hv : v=[] := List.length_eq_zero_iff.mp h + subst v + exact (hne (.refl _)).elim + | cons i u ih => + rw [functionalWord_top_singleton a c η hc θ w b hb hp f hf hfb i u v h] + unfold singletonCutSum + apply List.sum_eq_zero + intro z hz + obtain ⟨s,hs,rfl⟩ := List.mem_map.mp hz + by_cases hi : s.left=[i] + · rw [ite_eq_left hi] + have hpv := signedWordCuts_perm a c η hc θ w v s hs + rw [hi,List.singleton_append] at hpv + have hl := signedWordCuts_lengths a c η hc θ w v s hs + rw [hi,List.length_singleton] at hl + have hn : ¬u.Perm s.right := fun hh=>hne ((hh.cons i).trans hpv) + change s.coeff * (functionalWord a c η hc θ f u).ofConv (primitiveWord a c η hc θ b s.right)=0 + rw [ih s.right (by simp only [List.length_cons] at h; omega) hn,mul_zero] + · rw [ite_eq_right hi] + +section Ordered +variable [LinearOrder J] + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma singletonCutSum_even_sorted (w : J → SlopeWeight c η hc θ) (i : J) (v : List J) + (hv : v.Pairwise (· ≤ ·)) (hmin : ∀ j∈v,i≤j) + (he : globalColorSign a c η hc θ (w i) (w i)=1) (r : ℚ) : + singletonCutSum a c η hc θ w i v (fun _=>r)=(v.count i:ℚ)*r := by + induction v with + | nil => simp [singletonCutSum_nil] + | cons j v ih => + rw [singletonCutSum_cons] + have hv' := List.pairwise_cons.mp hv + by_cases hij : j=i + · subst j + rw [ite_eq_left rfl,he,one_mul,ih hv'.2 (fun j hj=>hmin j (List.mem_cons_of_mem _ hj))] + simp only [List.count_cons_self,Nat.cast_add,Nat.cast_one] + ring + · have hi : i∉j::v := by + intro hm + rcases List.mem_cons.mp hm with hh | hh + · exact hij hh.symm + · exact hij (le_antisymm (hv'.1 i hh) (hmin j (by simp))) + have hit : i∉v := fun hm=>hi (List.mem_cons_of_mem _ hm) + rw [ite_eq_right hij,singletonCutSum_not_mem a c η hc θ w i v _ hit,mul_zero,add_zero] + rw [List.count_eq_zero.mpr hi,Nat.cast_zero,zero_mul] + +lemma functionalWord_top_sorted_ne (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (hp : ∀ i,b i ∈ globalPrimitives a c η hc θ) + (f : J → UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ) (hf : ∀ i,f i (globalUnit a c η hc θ)=0) + (hfb : ∀ i j,f i (b j)=if i=j then 1 else 0) + (u v : List J) (hu : u.Pairwise (· ≤ ·)) (hv : v.Pairwise (· ≤ ·)) + (h : v.length=u.length) (hne : u≠v) : + (functionalWord a c η hc θ f u).ofConv (primitiveWord a c η hc θ b v)=0 := by + apply functionalWord_top_not_perm a c η hc θ w b hb hp f hf hfb u v h + intro hpv + exact hne (hpv.eq_of_pairwise' hu hv) + +end Ordered +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0i≤j ∧ (i=j → globalColorSign a c η hc θ (w i) (w i)=1)) + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma PBWAdmissible.sorted {w : J → SlopeWeight c η hc θ} {l : List J} + (h : PBWAdmissible a c η hc θ w l) : l.Pairwise (· ≤ ·) := h.imp (fun h=>h.1) + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma PBWAdmissible.tail {w : J → SlopeWeight c η hc θ} {i : J} {l : List J} + (h : PBWAdmissible a c η hc θ w (i::l)) : PBWAdmissible a c η hc θ w l := + (List.pairwise_cons.mp h).2 + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma singletonCutSum_sorted_self (w : J → SlopeWeight c η hc θ) (i : J) (l : List J) + (h : PBWAdmissible a c η hc θ w (i::l)) (g : List J → ℚ) : + singletonCutSum a c η hc θ w i (i::l) g=((l.count i+1:ℕ):ℚ)*g l := by + by_cases hi : i∈l + · have he := (List.pairwise_cons.mp h).1 i hi |>.2 rfl + have hcst : singletonCutSum a c η hc θ w i (i::l) g= + singletonCutSum a c η hc θ w i (i::l) (fun _=>g l) := by + apply singletonCutSum_congr + intro s hs hsi + have hp := signedWordCuts_perm a c η hc θ w (i::l) s hs + rw [hsi,List.singleton_append] at hp + have hr := (signedWordCuts_sublist a c η hc θ w (i::l) s hs).2 + have heq : s.right=l := hp.cons_inv.eq_of_pairwise' (h.sorted.sublist hr) h.tail.sorted + rw [heq] + rw [hcst,singletonCutSum_even_sorted a c η hc θ w i (i::l) h.sorted + (fun j hj=>by + rcases List.mem_cons.mp hj with rfl | hj + · exact le_rfl + · exact (List.pairwise_cons.mp h.sorted).1 j hj) he,List.count_cons_self] + · rw [singletonCutSum_unique a c η hc θ w i l g hi,List.count_eq_zero.mpr hi] + simp + +noncomputable def wordMultiplicity : List J → ℕ + | [] => 1 + | i::l => (l.count i+1)*wordMultiplicity l + +omit [LinearOrder J] in +lemma wordMultiplicity_pos (l : List J) : 0 exact Nat.zero_lt_one + | cons i l ih => exact Nat.mul_pos (Nat.succ_pos _) ih + +lemma functionalWord_diagonal (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (hp : ∀ i,b i ∈ globalPrimitives a c η hc θ) + (f : J → UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ) (hf : ∀ i,f i (globalUnit a c η hc θ)=0) + (hfb : ∀ i j,f i (b j)=if i=j then 1 else 0) + (l : List J) (hl : PBWAdmissible a c η hc θ w l) : + (functionalWord a c η hc θ f l).ofConv (primitiveWord a c η hc θ b l)=(wordMultiplicity l:ℚ) := by + induction l with + | nil => exact globalCounit_unit a c η hc θ + | cons i l ih => + rw [functionalWord_top_singleton a c η hc θ w b hb hp f hf hfb i l (i::l) rfl, + singletonCutSum_sorted_self a c η hc θ w i l hl] + rw [ih hl.tail] + exact (Nat.cast_mul _ _).symm + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalWordPairing.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalWordPairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..1bd495632ba9d521a0d9cd26fda1b34d4a71c743 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GlobalWordPairing.lean @@ -0,0 +1,208 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveBracket + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open WithConv +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0toConv (f i))).prod + +lemma functionalWord_cons (f : K → UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ) (i : K) (l : List K) : + functionalWord a c η hc θ f (i::l)=toConv (f i)*functionalWord a c η hc θ f l := rfl + +lemma convolution_mul_unit (f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ)) : + (f*g).ofConv (globalUnit a c η hc θ)= + f.ofConv (globalUnit a c η hc θ)*g.ofConv (globalUnit a c η hc θ) := by + rw [LinearMap.convMul_apply] + change LinearMap.mul' ℚ ℚ (TensorProduct.map f.ofConv g.ofConv + (globalCoproduct a c η hc θ (globalUnit a c η hc θ)))=_ + rw [globalCoproduct_unit,TensorProduct.map_tmul,LinearMap.mul'_apply] + +lemma functionalWord_unit (f : K → UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ) + (hf : ∀ i,f i (globalUnit a c η hc θ)=0) (i : K) (l : List K) : + (functionalWord a c η hc θ f (i::l)).ofConv (globalUnit a c η hc θ)=0 := by + rw [functionalWord_cons,convolution_mul_unit,ofConv_toConv,hf,zero_mul] + +lemma convolution_primitiveWord (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (hp : ∀ i,b i ∈ globalPrimitives a c η hc θ) + (f g : WithConv (UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ)) (l : List J) : + (f*g).ofConv (primitiveWord a c η hc θ b l)= + ((signedWordCuts a c η hc θ w l).map fun s=>s.coeff* + (f.ofConv (primitiveWord a c η hc θ b s.left)* + g.ofConv (primitiveWord a c η hc θ b s.right))).sum := by + rw [LinearMap.convMul_apply] + change LinearMap.mul' ℚ ℚ (TensorProduct.map f.ofConv g.ofConv + (globalCoproduct a c η hc θ (primitiveWord a c η hc θ b l)))=_ + rw [globalCoproduct_primitiveWord a c η hc θ w b hb hp l] + simp only [map_list_sum,List.map_map,Function.comp_def,wordCutTensor,map_smul, + TensorProduct.map_tmul,LinearMap.mul'_apply,smul_eq_mul] + +theorem functionalWord_longer (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (hp : ∀ i,b i ∈ globalPrimitives a c η hc θ) + (f : K → UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ) (hf : ∀ i,f i (globalUnit a c η hc θ)=0) + (u : List K) (v : List J) (h : v.length simp at h + | cons i u ih => + rw [functionalWord_cons,convolution_primitiveWord a c η hc θ w b hb hp] + apply List.sum_eq_zero + intro z hz + obtain ⟨s,hs,rfl⟩ := List.mem_map.mp hz + by_cases he : s.left=[] + · change s.coeff*(f i (primitiveWord a c η hc θ b s.left)*_)=0 + rw [he,primitiveWord_nil] + change s.coeff*(f i (globalUnit a c η hc θ)*_)=0 + rw [hf,zero_mul,mul_zero] + · have hl := signedWordCuts_lengths a c η hc θ w v s hs + have hpos : 0if s.left.length=1 then s.coeff* + (f i (primitiveWord a c η hc θ b s.left)* + (functionalWord a c η hc θ f u).ofConv (primitiveWord a c η hc θ b s.right)) else 0).sum := by + rw [functionalWord_cons,convolution_primitiveWord a c η hc θ w b hb hp] + congr 1 + apply List.map_congr_left + intro s hs + by_cases h1 : s.left.length=1 + · simp only [h1,ite_eq_left] + rw [ite_eq_right h1] + by_cases he : s.left=[] + · change s.coeff*(f i (primitiveWord a c η hc θ b s.left)*_)=0 + rw [he,primitiveWord_nil] + change s.coeff*(f i (globalUnit a c η hc θ)*_)=0 + rw [hf,zero_mul,mul_zero] + · have hl := signedWordCuts_lengths a c η hc θ w v s hs + have hpos : 0 if s.left=[] then s.coeff*g s.right else 0).sum + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma emptyCutSum_eq (w : J → SlopeWeight c η hc θ) (l : List J) (g : List J → ℚ) : + emptyCutSum a c η hc θ w l g=g l := by + induction l generalizing g with + | nil => simp [emptyCutSum,signedWordCuts] + | cons i l ih => + unfold emptyCutSum + simp only [signedWordCuts,List.map_append,List.sum_append,List.map_map,Function.comp_def] + have hl : ((signedWordCuts a c η hc θ w l).map fun s => + if (s.prependLeft i).left=[] then (s.prependLeft i).coeff*g (s.prependLeft i).right else 0).sum=0 := by + simp [SignedWordCut.prependLeft] + rw [hl,zero_add] + have hr : ((signedWordCuts a c η hc θ w l).map fun s => + if (SignedWordCut.prependRight a c η hc θ w i s).left=[] then + (SignedWordCut.prependRight a c η hc θ w i s).coeff*g (SignedWordCut.prependRight a c η hc θ w i s).right else 0).sum= + emptyCutSum a c η hc θ w l (fun r=>g (i::r)) := by + unfold emptyCutSum + congr 1 + apply List.map_congr_left + intro s hs + by_cases h : s.left=[] + · simp [SignedWordCut.prependRight,h,wordWeight,globalColorSign_zero_right] + · simp [SignedWordCut.prependRight,h] + rw [hr,ih] + +noncomputable def singletonCutSum (w : J → SlopeWeight c η hc θ) (i : J) (l : List J) + (g : List J → ℚ) : ℚ := + ((signedWordCuts a c η hc θ w l).map fun s => if s.left=[i] then s.coeff*g s.right else 0).sum + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma singletonCutSum_nil (w : J → SlopeWeight c η hc θ) (i : J) (g : List J → ℚ) : + singletonCutSum a c η hc θ w i [] g=0 := by simp [singletonCutSum,signedWordCuts] + +omit [DecidableEq I] [Fact (SlopeEulerSymmetric a c η θ)] in +lemma singletonCutSum_cons (w : J → SlopeWeight c η hc θ) (i j : J) (l : List J) (g : List J → ℚ) : + singletonCutSum a c η hc θ w i (j::l) g= + (if j=i then g l else 0)+globalColorSign a c η hc θ (w j) (w i)* + singletonCutSum a c η hc θ w i l (fun r=>g (j::r)) := by + unfold singletonCutSum + simp only [signedWordCuts,List.map_append,List.sum_append,List.map_map,Function.comp_def] + congr 1 + · by_cases h : j=i + · subst j + rw [ite_eq_left rfl] + convert emptyCutSum_eq a c η hc θ w l g using 1 + unfold emptyCutSum + congr 1 + apply List.map_congr_left + intro s hs + simp [SignedWordCut.prependLeft] + · rw [ite_eq_right h] + apply List.sum_eq_zero + intro z hz + obtain ⟨s,hs,rfl⟩ := List.mem_map.mp hz + simp [SignedWordCut.prependLeft,h] + · rw [← List.sum_map_mul_left] + congr 1 + apply List.map_congr_left + intro s hs + by_cases h : s.left=[i] + · simp [SignedWordCut.prependRight,h,wordWeight,mul_left_comm,mul_comm,mul_assoc] + · simp [SignedWordCut.prependRight,h] + +lemma functionalWord_top_singleton (w : J → SlopeWeight c η hc θ) + (b : J → UnitalShuffle a c η hc θ) (hb : ∀ i,b i ∈ globalHomogeneous a c η hc θ (w i)) + (hp : ∀ i,b i ∈ globalPrimitives a c η hc θ) + (f : J → UnitalShuffle a c η hc θ →ₗ[ℚ] ℚ) (hf : ∀ i,f i (globalUnit a c η hc θ)=0) + (hfb : ∀ i j,f i (b j)=if i=j then 1 else 0) + (i : J) (u v : List J) (h : v.length=u.length+1) : + (functionalWord a c η hc θ f (i::u)).ofConv (primitiveWord a c η hc θ b v)= + singletonCutSum a c η hc θ w i v + (fun r=>(functionalWord a c η hc θ f u).ofConv (primitiveWord a c η hc θ b r)) := by + rw [functionalWord_top_cuts a c η hc θ w b hb hp f hf i u v h] + unfold singletonCutSum + congr 1 + apply List.map_congr_left + intro s hs + by_cases h1 : s.left.length=1 + · obtain ⟨j,hj⟩ := List.length_eq_one_iff.mp h1 + rw [hj] + simp only [List.length_singleton,ite_eq_left,primitiveWord_cons,primitiveWord_nil] + rw [show b j*(1:UnitalShuffle a c η hc θ)=b j from mul_one _,hfb] + by_cases hji : i=j + · subst j; simp + · simp [hji,Ne.symm hji] + · rw [ite_eq_right h1] + have hne : s.left ≠ [i] := fun hh=>h1 (by rw [hh]; rfl) + rw [ite_eq_right hne] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GradeBInternal.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GradeBInternal.lean new file mode 100644 index 0000000000000000000000000000000000000000..0917f1607b2df1ca4a2b4a5f66d2a4927ac34c5e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GradeBInternal.lean @@ -0,0 +1,103 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.ComponentB + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.Homogeneity +variable {I : Type*} [Fintype I] [DecidableEq I] + +theorem gradeB_internal (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + DirectSum.IsInternal (gradeB a μ d) := by + classical + apply DirectSum.isInternal_submodule_of_iSupIndep_of_iSup_eq_top + · exact (iSupIndep_iff_finsetSum_eq_zero_imp_eq_zero _).mpr + (gradeB_finite_independent a μ d) + · apply top_unique + intro f hf + obtain ⟨s,hs,heq⟩ := componentB_finite_decomposition a μ d f + rw [← heq] + apply Submodule.sum_mem + intro k hk + apply (le_iSup (gradeB a μ d) k) + exact ⟨f,rfl⟩ + +lemma gradeB_homogeneous_representative (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (k : ℤ) (f : B a μ d) (hf : f∈gradeB a μ d k) : + ∃ g : S d, g.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) k ∧ + (destabilizingSpace a μ d).mkQ g=f := by + obtain ⟨x,rfl⟩ := hf + obtain ⟨g,rfl⟩ := (destabilizingSpace a μ d).mkQ_surjective x + exact ⟨componentS d k g,componentS_homogeneous d k g,rfl⟩ + +theorem shuffleB_graded (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ)) x = (Finsupp.weight (fun _=>(1:ℕ)) x : ℤ) := by + classical + simp [Finsupp.weight_apply,Finsupp.sum] + +lemma homogeneous_int_nat {σ : Type*} (p : MvPolynomial σ ℚ) (k : ℕ) : + p.IsWeightedHomogeneous (fun _=>(1:ℤ)) (k:ℤ) ↔ + p.IsWeightedHomogeneous (fun _=>(1:ℕ)) k := by + simp only [IsWeightedHomogeneous,intWeight_eq_natWeight,Nat.cast_inj] + +omit [DecidableEq I] in +lemma componentS_range_finite (d : I → ℕ) (k : ℤ) : + Module.Finite ℚ (LinearMap.range (componentS d k)) := by + classical + by_cases hk : k<0 + · have hr : LinearMap.range (componentS d k)=⊥ := by + apply bot_unique + rintro x ⟨f,rfl⟩ + exact Subtype.ext (homogeneous_negative_eq_zero _ (componentS_homogeneous d k f) hk) + rw [hr] + infer_instance + · have hk0 : 0≤k := le_of_not_gt hk + let H := weightedHomogeneousSubmodule ℚ (fun _ : Σ i,Fin (d i)=>(1:ℕ)) k.toNat + let : Module.Finite ℚ H := Module.Finite.of_fg + (weightedHomogeneousSubmodule_fg ℚ _ (fun _=>one_ne_zero) _) + let L : LinearMap.range (componentS d k) →ₗ[ℚ] H := + (((symmetricSpace d).val.toLinearMap).comp (LinearMap.range (componentS d k)).subtype).codRestrict H (by + rintro ⟨f,⟨g,rfl⟩⟩ + apply (homogeneous_int_nat _ _).mp + rw [Int.toNat_of_nonneg hk0] + exact componentS_homogeneous d k g) + have hL : Function.Injective L := by + intro x y h + have hv : x.val.val=y.val.val := congrArg (fun z : H=>z.val) h + exact Subtype.ext (Subtype.ext hv) + exact Module.Finite.of_injective L hL + +theorem gradeB_finite (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (k : ℤ) : + Module.Finite ℚ (gradeB a μ d k) := by + classical + let := componentS_range_finite d k + let Q := destabilizingSpace a μ d + let L : LinearMap.range (componentS d k) →ₗ[ℚ] gradeB a μ d k := + (Q.mkQ.comp (LinearMap.range (componentS d k)).subtype).codRestrict _ (by + rintro ⟨f,⟨g,rfl⟩⟩ + exact ⟨Q.mkQ g,rfl⟩) + apply Module.Finite.of_surjective L + rintro ⟨f,hf⟩ + obtain ⟨x,rfl⟩ := hf + obtain ⟨g,rfl⟩ := Q.mkQ_surjective x + exact ⟨⟨componentS d k g,⟨g,rfl⟩⟩,rfl⟩ + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GradedCoproduct.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GradedCoproduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..be57fedaad6069334621b30187845b0007caf555 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GradedCoproduct.lean @@ -0,0 +1,222 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.NormalizedTensorSymbol +import OAI.Combinatorics.Chromatic.Shuffle.PrimitiveSpace + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open SeparationInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +noncomputable def nextTensorFiltration (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0separationCoefficient_filtration a c η hc θ d e hs W j f.val f.property) + +noncomputable def gradeSeparationCoefficient (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 exact hT + | assoc T U V => trivial + | swap T U => trivial + | node e f he hf => trivial + | trans e f he hf => exact hf (he hT) +end SplitTree.Regroup + +lemma properSourceFiltration_allTrees (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + rcases hx with ⟨U,V,x,y,hUV,hx,hy,rfl⟩ + rw [TensorProduct.map_tmul] + by_cases h : 2*L.totalDegree k+L.doubleShift a exact map_zero _ + | add x y hx hy hix hiy => rw [map_add,hix,hiy,add_zero] + | smul r x hx hix => rw [map_smul,hix,smul_zero] + +lemma normalizedTensorSymbol_next_zero (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + rw [primitiveSpace_mk_iff] at hf + rw [separationCoproduct_mk_eq_zero_iff] + apply SplitTree.normalizedTensorSymbol_detect a c η hc θ hχ d e W + (separationCoefficientRestricted a c η hc θ d e hs W 0 f) + intro L R hL hR hd he + subst d + subst e + apply (SplitTree.coproduct_normalized_symbol a c η hc θ hχ L R hL hR W f).trans + rw [SplitTree.normalizedSymbol_eq_zero_iff] + exact SplitTree.totalLeadingPolynomial_proper_next_zero a c η hc θ (.node L R) trivial ⟨hL,hR⟩ W f.val hf + +theorem primitiveSpace_iff_coproducts_zero (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + rw [primitiveSpace_mk_iff,proper_next_iff_symbols_zero a c η hc θ hχ d W f] + rintro ⟨T,ho,hs,hd⟩ hp + subst d + cases T with + | leaf d => exact False.elim hp + | node L R => + have hf0:=hf L R hs.1 hs.2 rfl + rw [separationCoproduct_mk_eq_zero_iff] at hf0 + change SplitTree.normalizedSymbol a c η hc θ (.node L R) hs _ W f=0 + rw [←SplitTree.coproduct_normalized_symbol a c η hc θ hχ L R hs.1 hs.2 W f] + apply SplitTree.normalizedTensorSymbol_next_zero + exact hf0 + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GradedShuffle.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GradedShuffle.lean new file mode 100644 index 0000000000000000000000000000000000000000..1961918c78ef211217e8a2e8dade100671b70108 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GradedShuffle.lean @@ -0,0 +1,46 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ShuffleFiltration +import OAI.Combinatorics.Chromatic.Walls.LinearFiltrationBilinear + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def gradeShuffle (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0shuffleB_filtered a c η hc θ hχ d e hd he hdθ heθ U V f g hf hg) + (fun f hf g hg=>by + simpa only [add_assoc,add_comm (1:ℤ) V] using + shuffleB_filtered a c η hc θ hχ d e hd he hdθ heθ (U+1) V f g hf hg) + (fun f hf g hg=>by + simpa only [add_assoc] using + shuffleB_filtered a c η hc θ hχ d e hd he hdθ heθ U (V+1) f g hf hg) + +lemma gradeShuffle_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 simp only [map_add,hx,hy] + | tmul x y => rfl + +noncomputable def fourQuotient (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂) →ₐ[ℚ] + (B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂) := + Algebra.TensorProduct.map (quotientTensor a μ d₁ e₁) (quotientTensor a μ d₂ e₂) + +noncomputable def fourInterchangeB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (B a μ d₁⊗[ℚ]B a μ d₂)⊗[ℚ](B a μ e₁⊗[ℚ]B a μ e₂) ≃ₗ[ℚ] + (B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂) := + TensorProduct.tensorTensorTensorComm ℚ _ _ _ _ + +lemma fourQuotient_interchange (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S d₁⊗[ℚ]S d₂) (g : S e₁⊗[ℚ]S e₂) : + (fourQuotient a μ d₁ e₁ d₂ e₂).toLinearMap (fourInterchange d₁ e₁ d₂ e₂ (f⊗ₜ[ℚ]g))= + fourInterchangeB a μ d₁ e₁ d₂ e₂ + (quotientTensor a μ d₁ d₂ f⊗ₜ[ℚ]quotientTensor a μ e₁ e₂ g) := by + exact (LinearMap.congr_fun (TensorProduct.tensorTensorTensorComm_comp_map ℚ + (quotientAlg a μ d₁).toLinearMap (quotientAlg a μ d₂).toLinearMap + (quotientAlg a μ e₁).toLinearMap (quotientAlg a μ e₂).toLinearMap) (f⊗ₜ[ℚ]g)).symm + +lemma quotient_twoTargetTransfer_unit (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + change (quotientTensor a (slope c η) (d₁+e₁) (d₂+e₂)).toLinearMap + ((twoTargetTransfer a d₁ e₁ d₂ e₂) (x+y))=_ + rw [(twoTargetTransfer a d₁ e₁ d₂ e₂).map_add,LinearMap.map_add,LinearMap.map_add,LinearMap.map_add] + exact congrArg₂ (·+·) hx hy + | tmul x y => + change quotientAlg a (slope c η) (d₁+e₁) (shuffleTensorLinear a d₁ e₁ x)⊗ₜ[ℚ] + quotientAlg a (slope c η) (d₂+e₂) (shuffleTensorLinear a d₂ e₂ y)=_ + rw [quotient_shuffleTensorUnit a c η hc d₁ e₁ h₁, + quotient_shuffleTensorUnit a c η hc d₂ e₂ h₂] + rfl + +lemma fourQuotient_grid_factor (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 rw [map_add,add_mul,TensorProduct.add_tmul,(TensorProduct.tensorTensorTensorComm K A B C D).map_add,hx,hz] + | tmul a b => + induction y using TensorProduct.inductionOn with + | add y z hy hz => rw [map_add,mul_add,TensorProduct.tmul_add,(TensorProduct.tensorTensorTensorComm K A B C D).map_add,hy,hz] + | tmul c d => + rw [first_tmul,second_tmul,TensorProduct.tensorTensorTensorComm_tmul] + simp only [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + +end ElementaryPositivity.TensorColumns + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GridShapeFiltration.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GridShapeFiltration.lean new file mode 100644 index 0000000000000000000000000000000000000000..9415223e71afa5d080f0f7b88370c5d57ce9549c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GridShapeFiltration.lean @@ -0,0 +1,173 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.Product +import OAI.Combinatorics.Chromatic.QuantumTorus.ProductUnitFiltration +import OAI.Combinatorics.Chromatic.Shuffle.ClearedSeparationB + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.PackConvolution +open ElementaryPositivity.LinearDetection +variable {I : Type*} [Fintype I] [DecidableEq I] + +def ShuffleFiltered (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(u i).val) (shapeComplement u) (fun i=>(v i).val) (shapeComplement v)) : + quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v)∈ + unitalSourceTensorFiltration a c η hc θ α β (U+V) := by + have hα := (shape_add_complement u).trans (realization_card R) + have hβ := (shape_add_complement v).trans (realization_card T) + unfold gridShapeTensor + apply quotientTensor_cast_mem_unitalSource + apply quotient_fourGrid_filtered a c η hc θ _ _ _ _ hon + (ihα _ _ hα) (ihβ _ _ hβ) _ U V f g hf hg + rw [hα,hβ] + exact h + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma restriction_shuffleBUnit_filtered (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + induction g using Submodule.Quotient.induction_on with + | H g => + change restrictionB a c η hc (hαθ.trans hβθ.symm) (firstCut α β) (castB a (slope c η) h.symm + (quotientAlg a (slope c η) (d+e) (shufflePolynomial a f g)))∈_ + rw [castB_mk,restrictionB_mk] + apply sourceTensorFiltration_cross_cancel a c η hc θ α β (U+V) + let R : Realization (α+β) (A:=fun i=>Fin ((α+β) i)) (fun _=>Finset.univ) := + fun _=>(Equiv.subtypeUnivEquiv (fun _=>Finset.mem_univ _)).symm + rw [cleared_restriction_sameSlope_support a c η hc h.symm f g R (firstCut α β) + (hαθ.trans hβθ.symm) (hdθ.trans hαθ.symm)] + apply Submodule.smul_mem + apply Submodule.sum_mem + intro x hx + apply Submodule.sum_mem + intro y hy + split_ifs with hon + · rw [←unitalSourceTensorFiltration_nonzero a c η hc θ α β hα hβ] + apply quotient_gridShapeTensor_filtered a c η hc θ h.symm ihα ihβ U V f g hf hg + rwa [hαθ] at hon + · exact Submodule.zero_mem _ + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic +open SplitTree +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma sourceFiltration_of_binary (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + have hz : z=Finsupp.single () (z ()) := by apply Finsupp.ext; intro u; cases u; simp + rw [hz,restrictionTest_leaf_coeff] + exact ElementaryPositivity.CommonTranslation.polynomial_coeff_mem (A:=B a (slope c η) d) + (degreeCutSubmodule a (slope c η) (.leaf d) W) (taylorB a (slope c η) d f) + (fun t => by erw [taylorB_eval]; exact hleaf t) (z ()) k hw + | node T U => + cases T with + | node T V => exact False.elim hT + | leaf α => + let β:=U.dim + have hr:=hpair α β hs.1.1 (dim_ne_zero hs.2) hs.1.2 (slope_dim c η hc hs.2) rfl + have ht:=(sourceTensorFiltration_iff a c η hc θ α β W _).mp hr + let z₁ := z.comapDomain Sum.inl Sum.inl_injective.injOn + let z₂ := z.comapDomain Sum.inr Sum.inr_injective.injOn + have hz : z₁.sumElim z₂=z := Finsupp.comapDomain_sumElim_comapDomain z + rw [←hz,restrictionTest_node] + exact ht ⟨.leaf α,trivial,hs.1,rfl,k.1,z₁⟩ ⟨U,hT,hs.2,rfl,k.2,z₂⟩ (by + convert hw using 1; dsimp [RestrictionIndex.weight,totalDegree,doubleShift]; ring) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/GridShapeTensor.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/GridShapeTensor.lean new file mode 100644 index 0000000000000000000000000000000000000000..324daa307e55fc4e6c277b1f35a70c1bf698e75a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/GridShapeTensor.lean @@ -0,0 +1,98 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.TargetEmbedding + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma realization_card {d : I → ℕ} {s : Pack (A:=A)} (R : Realization d s) : + (fun i=>(s i).card) = d := by + funext i + simpa using (Fintype.card_congr (R i)).symm + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +lemma targetEmbedding_realization {d e : I → ℕ} {s : Pack (A:=A)} + (R : Realization (d+e) s) (u : Cut d e) : + targetEmbedding (cutRealizationEquiv R u).val (leftRealization R u) (rightRealization R u) = + (cutSplit u).toEmbedding.trans + (⟨realizationMap R, realizationMap_injective R⟩ : (Σi,Fin ((d+e) i)) ↪ (Σi,A i)) := by + apply Function.Embedding.ext + intro z + rcases z with x|x <;> rfl + +omit [∀ i,Fintype (A i)] in +lemma targetValueAt_restrictTensor {d e : I → ℕ} {s : Pack (A:=A)} + (R : Realization (d+e) s) (u : Cut d e) (f : S (d+e)) : + targetValueAt (cutRealizationEquiv R u).val (leftRealization R u) (rightRealization R u) + (restrictTensor u f) = labeledValue f s := by + rw [labeledValue_eq R] + change renameInjFraction + (targetEmbedding (cutRealizationEquiv R u).val (leftRealization R u) (rightRealization R u)) + (targetEmbedding (cutRealizationEquiv R u).val (leftRealization R u) (rightRealization R u)).injective + (algebraMap (MvPolynomial (CellVars d e) ℚ) (FractionRing (MvPolynomial (CellVars d e) ℚ)) + (tensorValue d e (restrictTensor u f))) = _ + rw [tensorValue_restrictTensor,targetEmbedding_algebraMap] + simp only [rename_rename,targetEmbedding_realization,Function.Embedding.coe_trans, + Equiv.coe_toEmbedding] + change algebraMap _ _ (rename ((realizationMap R ∘ cutSplit u) ∘ (cutSplit u).symm) f.val) = _ + have hfun : (realizationMap R ∘ cutSplit u) ∘ (cutSplit u).symm = realizationMap R := by + funext x + simp + rw [hfun] + rfl + +noncomputable def gridShapeTensor (a : I → I → ℕ) {d e α β : I → ℕ} + (f : S d) (g : S e) {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (R : Realization α (left p)) (T : Realization β (right p)) + (u : CutShape (left p)) (v : CutShape (right p)) : S α ⊗[ℚ] S β := + castTensor ((shape_add_complement u).trans (realization_card R)) + ((shape_add_complement v).trans (realization_card T)) + (cellTransfer a (fun i=>(u i).val) (shapeComplement u) + (fun i=>(v i).val) (shapeComplement v) + (fourGridPolynomial a f g (fun i=>(u i).val) (shapeComplement u) + (fun i=>(v i).val) (shapeComplement v))) + +lemma targetValueAt_gridShapeTensor (a : I → I → ℕ) {d e α β : I → ℕ} + (f : S d) (g : S e) {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (R : Realization α (left p)) (T : Realization β (right p)) + (u : CutShape (left p)) (v : CutShape (right p)) : + targetValueAt p R T (gridShapeTensor a f g p R T u v) = + ∑ q : SizedCut (fun i=>(u i).val) (left p), + ∑ r : SizedCut (fun i=>(v i).val) (right p), + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (gridPolynomial a f g p q.val r.val) * + kernel (pairKernel a) (left q.val) (right q.val) * + kernel (pairKernel a) (left r.val) (right r.val) := by + rw [gridShapeTensor,targetValueAt_cast _ _ p (shapeRealization u) R (shapeRealization v) T] + exact (grid_shape_transfer a f g p (shapeRealization u) (shapeRealization v)).symm + +noncomputable def gridTensor (a : I → I → ℕ) {d e α β : I → ℕ} + (f : S d) (g : S e) {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (R : Realization α (left p)) (T : Realization β (right p)) : S α ⊗[ℚ] S β := + ∑ u : CutShape (left p),∑ v : CutShape (right p),gridShapeTensor a f g p R T u v + +lemma targetValueAt_gridTensor (a : I → I → ℕ) {d e α β : I → ℕ} + (f : S d) (g : S e) {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (R : Realization α (left p)) (T : Realization β (right p)) : + targetValueAt p R T (gridTensor a f g p R T) = + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (sameDen (left p) (right p)) * + labeledValue (shufflePolynomial a f g) s := by + rw [labeledValue_shuffle] + have hf : labeledValue (A:=A) f = fun t=>algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (labeledPolynomial f t) := by + funext t; exact (labeledPolynomial_algebraMap f t).symm + have hg : labeledValue (A:=A) g = fun t=>algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (labeledPolynomial g t) := by + funext t; exact (labeledPolynomial_algebraMap g t).symm + rw [hf,hg,shuffle_grid_cleared, sum_grid_by_shape p] + simp only [gridTensor,map_sum,targetValueAt_gridShapeTensor,gridPolynomial] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDetectorBasics.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDetectorBasics.lean new file mode 100644 index 0000000000000000000000000000000000000000..b91156e22d41a116c7688f2747a843ce366f0cf6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDetectorBasics.lean @@ -0,0 +1,288 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNPolynomial +import OAI.Combinatorics.Chromatic.Walls.HNMatrixTriangular + +namespace OAI + +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] +variable (c η : I → ℝ) +lemma hnKeyLT_irrefl (d : I → ℕ) : ¬hnKeyLT c η d d := by + simp [hnKeyLT] +lemma hnKeyLT_trans {d e f : I → ℕ} (h : hnKeyLT c η d e) (k : hnKeyLT c η e f) : + hnKeyLT c η d f := by + rcases h with h|⟨h,hm⟩ <;> rcases k with k|⟨k,km⟩ + · exact Or.inl (h.trans k) + · exact Or.inl (k ▸ h) + · exact Or.inl (h ▸ k) + · exact Or.inr ⟨h.trans k,hm.trans km⟩ +instance hnKeyLT_strict : IsStrictOrder (I → ℕ) (hnKeyLT c η) where + irrefl := hnKeyLT_irrefl c η + trans := fun _ _ _=>hnKeyLT_trans c η +lemma hnKeyLT_bounds {d e : I → ℕ} (h : ¬hnKeyLT c η d e) : + slope c η e ≤ slope c η d ∧ (slope c η d=slope c η e → mass c e ≤ mass c d) := by + exact ⟨le_of_not_gt (fun hs=>h (Or.inl hs)),fun hs=>le_of_not_gt (fun hm=>h (Or.inr ⟨hs,hm⟩))⟩ +lemma ordered_tail {d : I → ℕ} {l : List (I → ℕ)} (h : HNOrdered c η (d::l)) : HNOrdered c η l := + ⟨fun e he=>h.1 e (by simp [he]),h.2.tail⟩ +lemma ordered_total_lt_head (hc : ∀ i,0MvPolynomial.constantCoeff y.val • (z⊗ₜ[ℚ](1 : S (0 : I → ℕ)))) (hσ d x) +lemma singletonDetector_ideal (d : I → ℕ) (θ : ℝ) (f : S [d].sum) + (hf : f∈destabilizingSpace a (clippedSlope c η θ) [d].sum) : singletonDetector a c η d f=0 := by + change quotientAlg a (slope c η) d (castS (add_zero d) f)⊗ₜ[ℚ](1 : S (0 : I → ℕ))=0 + exact (congrArg (fun z=>z⊗ₜ[ℚ](1 : S (0 : I → ℕ))) + (quotient_clipped_zero a c η (castS_mem_destabilizing a _ (add_zero d) hf))).trans (TensorProduct.zero_tmul _ _) + +lemma singletonDetector_off (hc : ∀ i,0 + exact (hd (by simpa using h.symm)).elim + | cons e r => + have hn : r≠[] := by + intro he; subst r + have : e=d := by simpa using h + exact hne (by simp [this]) + have H : (singletonDetector a c η d).comp ((dimensionCast h).comp (hnPolynomial a c η σ (e::r)))=0 := by + apply TensorProduct.ext' + intro x y + have hz : quotientAlg a (slope c η) d + (castS (h.trans (add_zero d)) (shufflePolynomial a (σ e x) (hnPolynomial a c η σ r y)))=0 := by + apply (Submodule.Quotient.mk_eq_zero _).mpr + apply Submodule.subset_span + refine ⟨e,r.sum,h.trans (add_zero d),σ e x,hnPolynomial a c η σ r y, + hr.1 e (by simp),list_sum_ne_zero (ordered_tail c η hr).1 hn,?_,?_⟩ + · have H:=ordered_total_lt_head c η hc hr hn + simpa only [h,List.sum_cons,List.sum_nil,add_zero] using H + · exact (dimensionCast_eq_castS (h.trans (add_zero d)) (shufflePolynomial a (σ e x) (hnPolynomial a c η σ r y))).symm + have Hcast : castS (add_zero d) (dimensionCast h + (shufflePolynomial a (σ e x) (hnPolynomial a c η σ r y)))= + castS (h.trans (add_zero d)) (shufflePolynomial a (σ e x) (hnPolynomial a c η σ r y)) := + (congrArg (castS (add_zero d)) (dimensionCast_eq_castS h _)).trans (castS_trans _ _ _) + exact (singletonDetector_apply a c η d _).trans + ((congrArg (fun f=>quotientAlg a (slope c η) d f⊗ₜ[ℚ](1 : S (0 : I → ℕ))) Hcast).trans + ((congrArg (fun z=>z⊗ₜ[ℚ](1 : S (0 : I → ℕ))) hz).trans (TensorProduct.zero_tmul _ _))) + simpa only [LinearMap.comp_apply,dimensionCast_eq_castS,LinearMap.zero_apply] using LinearMap.congr_fun H x +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) + +structure IsHNDetector (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) + (l : List (I → ℕ)) (D : S l.sum →ₗ[ℚ] HNTensor a c η l) : Prop where + ideal : ∀ θ : ℝ,(∀ d∈l,slope c η d ≤ θ) → ∀ f : S l.sum, + f∈destabilizingSpace a (clippedSlope c η θ) l.sum → D f=0 + diagonal : D.comp (hnPolynomial a c η σ l)=LinearMap.id + off : ∀ (r : List (I → ℕ)),HNOrdered c η r → ∀ h : r.sum=l.sum, + ¬List.Lex (hnKeyLT c η) r l → r≠l → ∀ x : HNTensor a c η r, + D (castS h (hnPolynomial a c η σ r x))=0 + +noncomputable def quotientDetector (l : List (I → ℕ)) (D : S l.sum →ₗ[ℚ] HNTensor a c η l) + (κ : ℝ) (hk : ∀ f : S l.sum,f∈destabilizingSpace a (clippedSlope c η κ) l.sum → D f=0) : + B a (clippedSlope c η κ) l.sum →ₗ[ℚ] HNTensor a c η l := + (destabilizingSpace a (clippedSlope c η κ) l.sum).liftQ D (fun f hf=>hk f hf) +lemma quotientDetector_mk (l : List (I → ℕ)) (D : S l.sum →ₗ[ℚ] HNTensor a c η l) + (κ : ℝ) (hk : ∀ f : S l.sum,f∈destabilizingSpace a (clippedSlope c η κ) l.sum → D f=0) + (f : S l.sum) : quotientDetector a c η l D κ hk (quotientAlg a (clippedSlope c η κ) l.sum f)=D f := rfl + +noncomputable def consDetector (d : I → ℕ) (l : List (I → ℕ)) (D : S l.sum →ₗ[ℚ] HNTensor a c η l) + (κ : ℝ) (hk : ∀ f : S l.sum,f∈destabilizingSpace a (clippedSlope c η κ) l.sum → D f=0) : + S (d::l).sum →ₗ[ℚ] HNTensor a c η (d::l) := + (TensorProduct.map (clippedToOriginal a c η κ d) (quotientDetector a c η l D κ hk)).comp + (headRestriction a (clippedSlope c η κ) d l.sum) + +lemma consDetector_shuffle (hc : ∀ i,0quotientAlg a (slope c η) d (σ d v)⊗ₜ[ℚ]z) (hD w)).trans + (TensorProduct.tmul_zero _ _)))) + exact (congrArg (consDetector a c η d l D κ hk) (dimensionCast_eq_castS _ _)).symm.trans + (LinearMap.congr_fun Hzero x) + +lemma consDetector_wrong_head (hc : ∀ i,0 + refine ⟨LinearMap.id,?_,rfl,?_⟩ + · intro θ h f hf + change f∈destabilizingSpace a (clippedSlope c η θ) 0 at hf + rw [destabilizingSpace_zero] at hf + exact hf + · intro r hr h hn he x + exact (list_sum_ne_zero hr.1 he h).elim + | cons d l ih => + have hd : d≠0:=hl.1 d (by simp) + cases l with + | nil => + refine ⟨singletonDetector a c η d,?_,singletonDetector_diagonal a c η σ hσ d,?_⟩ + · intro θ h f hf; exact singletonDetector_ideal a c η d θ f hf + · intro r hr h hn he x; exact singletonDetector_off a c η hc σ d hd r hr h he x + | cons e l => + let t:=e::l + have ho : HNOrdered c η t := ordered_tail c η hl + obtain ⟨D,hD⟩:=ih ho + obtain ⟨κ,hκ,hkb⟩:=exists_uniform_cutoff c η (d+t.sum) (slope c η d) + have hb : ∀ x∈t,slope c η x ≤ κ := by + intro x hx + apply hkb x _ (ho.1 x hx) ((List.pairwise_cons.mp hl.2).1 x hx) + exact (List.le_sum_of_mem hx).trans (le_add_of_nonneg_left zero_le) + have ht : slope c η t.sum ≤ κ := list_slope_le c η hc κ t + (list_sum_ne_zero ho.1 (by simp [t])) hb + let hk := hD.ideal κ hb + refine ⟨consDetector a c η d t D κ hk,?_,?_,?_⟩ + · intro θ h f hf + apply consDetector_ideal a c η hc d t D κ hk θ ?_ ?_ ?_ f hf + · exact (ordered_sum_le_head c η hc hl).trans (h d (by simp)) + · exact max_le (h d (by simp)) (hκ.le.trans (h d (by simp))) + · exact max_le (ht.trans (hκ.le.trans (h d (by simp)))) (hκ.le.trans (h d (by simp))) + · exact consDetector_diagonal a c η hc σ hσ d t D κ hk hd hκ ht hD.diagonal + · intro r hr h hn he x + cases r with + | nil => exact (list_sum_ne_zero hl.1 (by simp) h.symm).elim + | cons b r => + have hb0:=hr.1 b (by simp) + have hbd : ¬hnKeyLT c η b d := fun H=>hn (List.Lex.rel H) + obtain ⟨hs,hm⟩:=hnKeyLT_bounds c η hbd + by_cases hbd' : b=d + · subst b + have hr' : r.sum=t.sum := add_left_cancel h + have hne : r≠t := fun H=>he (congrArg (d::·) H) + have hn' : ¬List.Lex (hnKeyLT c η) r t := fun H=>hn (List.Lex.cons H) + exact consDetector_same_head a c η hc σ d t D κ hk hd hκ ht r hr' + (hD.off r (ordered_tail c η hr) hr' hn' hne) x + · exact consDetector_wrong_head a c η hc σ d t D κ hk hκ ht b r h hb0 hs hm hbd' x +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDiagonal.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDiagonal.lean new file mode 100644 index 0000000000000000000000000000000000000000..005dd8448c7116b108fe663b131412ee212e6fe7 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDiagonal.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalFiltration + +namespace OAI + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial HahnSeries +open ElementaryPositivity.LaurentAtInfinity SeparationInfinity +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] cancelTensorRing cancelTensorAlg cancelFourRing cancelFourAlg +attribute [local instance] cancelTensorDistrib cancelTensorSelf cancelTensorNonUnital cancelFourNonUnital cancelSeriesRing +attribute [local instance] cellSepTensorSemiring cellSepTensorNonAssoc cellSepFourSemiring cellSepFourNonAssoc cellSepFourModule + +lemma mappedInverseKernel_zero_head {R : Type*} [CommRing R] [Algebra ℚ R] + (a : I → I → ℕ) (e : I → ℕ) (F : S 0⊗[ℚ]S e →ₐ[ℚ]R) : + mappedInverseKernel a 0 e F=1 := by + unfold mappedInverseKernel + rw [inverseKernelUnit_zero_left,map_one] + +lemma mappedInverseRatio_zero_head {R : Type*} [CommRing R] [Algebra ℚ R] + (a b : I → I → ℕ) (e : I → ℕ) (F : S 0⊗[ℚ]S e →ₐ[ℚ]R) : + (mappedInverseKernel a 0 e F*(mappedInverseKernel b 0 e F)⁻¹).val=1 := by + rw [mappedInverseKernel_zero_head,mappedInverseKernel_zero_head,inv_one,mul_one,Units.val_one] + +lemma separation_zero_right (a : I → I → ℕ) (d : I → ℕ) (f : S d) : + tensorSeparationSeries a d 0 (castS (add_zero d).symm f)= + polynomial (relativeTaylor d 0 (f⊗ₜ[ℚ](1 : S 0))) := by + rw [tensorSeparationSeries,inverseKernelUnit_zero_right,Units.val_one,one_mul,restrictTensor_zero_right] +lemma separation_zero_left (a : I → I → ℕ) (e : I → ℕ) (g : S e) : + tensorSeparationSeries a 0 e (castS (zero_add e).symm g)= + polynomial (relativeTaylor 0 e ((1 : S 0)⊗ₜ[ℚ]g)) := by + rw [tensorSeparationSeries,inverseKernelUnit_zero_left,Units.val_one,one_mul,restrictTensor_zero_left] + +lemma polynomial_mapped_product_two {R S T : Type*} [CommRing R] [CommRing S] [CommRing T] + (f : R →+* T) (g : S →+* T) (p : Polynomial R) (q : Polynomial S) : + polynomial (Polynomial.map f p * Polynomial.map g q)= + mapRing f (polynomial p)*mapRing g (polynomial q) := by + rw [polynomial.map_mul,←polynomial_map,←polynomial_map] + +omit [Fintype I] [DecidableEq I] in +lemma fourPolynomial_mapped_product_two (d₁ e₁ d₂ e₂ : I → ℕ) + (p : Polynomial (S d₁⊗[ℚ]S d₂)) (q : Polynomial (S e₁⊗[ℚ]S e₂)) : + polynomial (Polynomial.map (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom p * + Polynomial.map (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom q)= + mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom (polynomial p)* + mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom (polynomial q) := + @polynomial_mapped_product_two (S d₁⊗[ℚ]S d₂) (S e₁⊗[ℚ]S e₂) + ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) + (cancelTensorRing d₁ d₂) (cancelTensorRing e₁ e₂) (cancelFourRing d₁ e₁ d₂ e₂) + (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom p q + +lemma fourTaylor_column_product (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S d₁⊗[ℚ]S d₂) (g : S e₁⊗[ℚ]S e₂) : + mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom (polynomial (relativeTaylor d₁ d₂ f)) * + mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom (polynomial (relativeTaylor e₁ e₂ g))= + polynomial (fourRelativeTaylor d₁ e₁ d₂ e₂ (fourInterchange d₁ e₁ d₂ e₂ (f⊗ₜ[ℚ]g))) := by + rw [←fourPolynomial_mapped_product_two] + apply congrArg polynomial + rw [firstColumn_relativeTaylor, secondColumn_relativeTaylor] + exact ((fourRelativeTaylor d₁ e₁ d₂ e₂).map_mul + (firstColumnAlg d₁ e₁ d₂ e₂ f) (secondColumnAlg d₁ e₁ d₂ e₂ g)).symm.trans + (congrArg (fourRelativeTaylor d₁ e₁ d₂ e₂) + (fourColumns_product d₁ e₁ d₂ e₂ f g)) + +lemma fourInputSeries_head (a : I → I → ℕ) (d e : I → ℕ) (f : S d) (g : S e) : + fourInputSeries a d 0 0 e (castS (add_zero d).symm f) (castS (zero_add e).symm g)= + polynomial (fourRelativeTaylor d 0 0 e ((f⊗ₜ[ℚ](1 : S 0))⊗ₜ[ℚ]((1 : S 0)⊗ₜ[ℚ]g))) := by + unfold fourInputSeries + have hf := congrArg (mapRing (firstColumnAlg d 0 0 e).toRingHom) + (separation_zero_right a d f) + have hg := congrArg (mapRing (secondColumnAlg d 0 0 e).toRingHom) + (separation_zero_left a e g) + have hkernel := mappedInverseRatio_zero_head a (fun i j => a j i) + (0 : I → ℕ) (crossingColumnAlg d 0 0 e) + exact (congrArg₂ (· * ·) (congrArg₂ (· * ·) hf hg) hkernel).trans + ((mul_one _).trans (fourTaylor_column_product d 0 0 e _ _)) + +noncomputable def rawClearedSeparation (a : I → I → ℕ) (d e : I → ℕ) : + S d⊗[ℚ]S e →ₗ[ℚ] LaurentSeries (S d⊗[ℚ]S e) := + (mulPolynomial (inverseKernelUnit a d e*(inverseKernelUnit (fun _ _ : I=>0) d e)⁻¹).val).comp + (relativeTaylor d e).toLinearMap + +noncomputable def rawRelativeSeries (d e : I → ℕ) (x : S d⊗[ℚ]S e) : + LaurentSeries (S d⊗[ℚ]S e) := polynomial (relativeTaylor d e x) + +lemma cellTransfer_head_normalized (a : I → I → ℕ) (d e : I → ℕ) (f : S d) (g : S e) : + rawClearedSeparation a (d+0) (0+e) + (cellTransfer a d 0 0 e + (fourGridPolynomial a (castS (add_zero d).symm f) (castS (zero_add e).symm g) d 0 0 e))= + rawRelativeSeries (d+0) (0+e) + (castS (add_zero d).symm f⊗ₜ[ℚ]castS (zero_add e).symm g) := by + unfold rawClearedSeparation + simp only [LinearMap.comp_apply,mulPolynomial_apply,AlgHom.toLinearMap_apply] + rw [cellTransfer_normalized,fourInputSeries_head,twoTarget_polynomial_relativeTaylor, + twoTargetTransfer_tmul,shufflePolynomial_unit_right,shufflePolynomial_unit_left] + simp [eulerForm,rawRelativeSeries] +end ElementaryPositivity.RawShuffle + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDiagonalConstant.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDiagonalConstant.lean new file mode 100644 index 0000000000000000000000000000000000000000..48a1a213ae3caa5ca59f6b6d3c52f27336533fbf --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNDiagonalConstant.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNDiagonal +import OAI.Combinatorics.Chromatic.Shuffle.CellLeadingSum + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial HahnSeries +open ElementaryPositivity.LaurentAtInfinity SeparationInfinity +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] clearedSepTensorRing clearedSepTensorAlg clearBTensorB clearBTensorBA + +omit [Fintype I] [DecidableEq I] in +lemma rawRelativeSeries_constant (d e : I → ℕ) (x : S d⊗[ℚ]S e) : + (rawRelativeSeries d e x).coeff 0=x := by + have ht : translationS d 0=LinearMap.id := by apply LinearMap.ext; intro f; exact translationS_zero d f + have he := relativeTaylor_eval d e x 0 + rw [map_zero,←Polynomial.coeff_zero_eq_eval_zero,ht,TensorProduct.map_id] at he + simpa only [rawRelativeSeries,show (0 : ℤ)=-(0 : ℕ) by rfl,polynomial_coeff,LinearMap.id_apply] using he + +lemma fourGridPolynomial_castSources (a : I → I → ℕ) + {d e d' e' : I → ℕ} (h : d=d') (k : e=e') (f : S d) (g : S e) + (d₁ e₁ d₂ e₂ : I → ℕ) : + fourGridPolynomial a (castS h f) (castS k g) d₁ e₁ d₂ e₂= + fourGridPolynomial a f g d₁ e₁ d₂ e₂ := by + subst d'; subst e'; rfl + +lemma clearedConstantB_cell_head (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d e : I → ℕ) (f : S d) (g : S e) : + clearedConstantB a μ (d+0) (0+e) + (quotientTensor a μ (d+0) (0+e) + (cellTransfer a d 0 0 e (fourGridPolynomial a f g d 0 0 e)))= + quotientTensor a μ (d+0) (0+e) + (castS (add_zero d).symm f⊗ₜ[ℚ]castS (zero_add e).symm g) := by + have h := cellTransfer_head_normalized a d e f g + rw [fourGridPolynomial_castSources] at h + rw [clearedConstantB_apply,clearedSeparationB_mk] + change (mapRing (quotientTensor a μ (d+0) (0+e)).toRingHom + (rawClearedSeparation a (d+0) (0+e) _)).coeff 0=_ + rw [h,mapRing_coeff,rawRelativeSeries_constant] + rfl + +lemma castBTensor_quotient_tmul (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e d' e' : I → ℕ} (h : d=d') (k : e=e') (f : S d) (g : S e) : + castBTensor a μ h k (quotientTensor a μ d e (f⊗ₜ[ℚ]g))= + quotientTensor a μ d' e' (castS h f⊗ₜ[ℚ]castS k g) := by + subst d'; subst e'; rfl + +lemma clearedConstantB_cell_head_cast (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d e d₁ e₁ d₂ e₂ : I → ℕ) (h₁ : d₁+e₁=d) (h₂ : d₂+e₂=e) + (he : e₁=0) (hd : d₂=0) (f : S d) (g : S e) : + clearedConstantB a μ d e (quotientTensor a μ d e + (castTensor h₁ h₂ (cellTransfer a d₁ e₁ d₂ e₂ + (fourGridPolynomial a f g d₁ e₁ d₂ e₂))))= + quotientTensor a μ d e (f⊗ₜ[ℚ]g) := by + subst e₁; subst d₂ + have h₁' : d₁=d := by simpa only [add_zero] using h₁ + have h₂' : e₂=e := by simpa only [zero_add] using h₂ + subst d₁; subst e₂ + rw [clearedConstantB_castTensor,clearedConstantB_cell_head,castBTensor_quotient_tmul] + simp only [castS_trans,castS_rfl] +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNExpansion.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..a76ee2463a1a87b04910539c6ce35a289dce1a89 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNExpansion.lean @@ -0,0 +1,205 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FourCellFactorization +import OAI.Combinatorics.Chromatic.Shuffle.RawGradedAlgebra + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) +noncomputable def HNTensor : List (I → ℕ) → CommAlgCat.{u} ℚ + | [] => CommAlgCat.of ℚ (S (0 : I → ℕ)) + | d::l => CommAlgCat.of ℚ (B a (slope c η) d⊗[ℚ]HNTensor l) + +noncomputable def hnWordMap (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) : + (l : List (I → ℕ)) → HNTensor a c η l →ₗ[ℚ] RawAlgebra a + | [] => rawLof a 0 + | d::l => (LinearMap.mul' ℚ (RawAlgebra a)).comp + (TensorProduct.map ((rawLof a d).comp (σ d)) (hnWordMap σ l)) + +lemma range_tensor_mul {A M N : Type*} [Ring A] [Algebra ℚ A] + [AddCommGroup M] [Module ℚ M] [AddCommGroup N] [Module ℚ N] + (f : M →ₗ[ℚ] A) (g : N →ₗ[ℚ] A) : + LinearMap.range ((LinearMap.mul' ℚ A).comp (TensorProduct.map f g))= + LinearMap.range f*LinearMap.range g := by + apply le_antisymm + · rintro _ ⟨x,rfl⟩ + induction x using TensorProduct.inductionOn with + | tmul x y => + exact Submodule.mul_mem_mul (show f x∈LinearMap.range f from ⟨x,rfl⟩) + (show g y∈LinearMap.range g from ⟨y,rfl⟩) + | add x y hx hy => simpa only [map_add] using Submodule.add_mem _ hx hy + · apply Submodule.mul_le.mpr + rintro _ ⟨x,rfl⟩ _ ⟨y,rfl⟩ + exact ⟨x⊗ₜ[ℚ]y,rfl⟩ + +lemma rawDimensionSpace_zero_eq : rawDimensionSpace a 0=1 := by + apply le_antisymm (rawDimensionSpace_zero a) + apply Submodule.one_le.mpr + exact ⟨(1 : S (0 : I → ℕ)),rfl⟩ +lemma hnWordMap_range (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (l : List (I → ℕ)) : + LinearMap.range (hnWordMap a c η σ l)=hnWordSpace (rawSectionSpace a c η σ) l := by + induction l with + | nil => exact rawDimensionSpace_zero_eq a + | cons d l ih => + change LinearMap.range ((LinearMap.mul' ℚ (RawAlgebra a)).comp + (TensorProduct.map ((rawLof a d).comp (σ d)) (hnWordMap a c η σ l)))= + rawSectionSpace a c η σ d*hnWordSpace (rawSectionSpace a c η σ) l + rw [range_tensor_mul,ih] + rfl +lemma hnWordSpace_raw_le (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (l : List (I → ℕ)) : + hnWordSpace (rawSectionSpace a c η σ) l ≤ rawDimensionSpace a l.sum := by + induction l with + | nil => simp only [hnWordSpace_nil,List.sum_nil,rawDimensionSpace_zero_eq,le_refl] + | cons d l ih => exact (mul_le_mul' (rawSectionSpace_le a c η σ d) ih).trans (rawDimensionSpace_mul a d l.sum) + +abbrev HNIndex (d : I → ℕ) := {l : List (I → ℕ) // l.sum=d ∧ HNOrdered c η l} +noncomputable def hnExpansionRaw (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (d : I → ℕ) : + (⨁ l : HNIndex c η d,HNTensor a c η l.val) →ₗ[ℚ] RawAlgebra a := + DirectSum.toModule ℚ _ _ (fun l=>hnWordMap a c η σ l.val) + +lemma hnExpansionRaw_range (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (d : I → ℕ) : + LinearMap.range (hnExpansionRaw a c η σ d)=hnOrderedSpan c η (rawSectionSpace a c η σ) d := by + apply le_antisymm + · rintro _ ⟨x,rfl⟩ + induction x using DirectSum.induction_on with + | zero => simpa only [map_zero] using Submodule.zero_mem (hnOrderedSpan c η (rawSectionSpace a c η σ) d) + | of l x => + have hx : hnWordMap a c η σ l.val x∈hnWordSpace (rawSectionSpace a c η σ) l.val := + hnWordMap_range a c η σ l.val ▸ LinearMap.mem_range_self _ x + change hnExpansionRaw a c η σ d (DirectSum.lof ℚ _ _ l x)∈_ + rw [hnExpansionRaw,DirectSum.toModule_lof] + exact hnWordSpace_le c η (rawSectionSpace a c η σ) l.val l.property.1 l.property.2 hx + | add x y hx hy => simpa only [map_add] using Submodule.add_mem _ hx hy + · refine iSup_le fun l=>iSup_le fun hl=>iSup_le fun ho=>?_ + rw [←hnWordMap_range] + rintro _ ⟨x,rfl⟩ + exact ⟨DirectSum.lof ℚ _ _ ⟨l,hl,ho⟩ x,DirectSum.toModule_lof ℚ _ _⟩ + +lemma hnExpansionRaw_mem (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (d : I → ℕ) + (x : ⨁ l : HNIndex c η d,HNTensor a c η l.val) : + hnExpansionRaw a c η σ d x∈rawDimensionSpace a d := by + have h : hnOrderedSpan c η (rawSectionSpace a c η σ) d ≤ rawDimensionSpace a d := by + refine iSup_le fun l=>iSup_le fun hl=>iSup_le fun _=>?_ + simpa only [hl] using hnWordSpace_raw_le a c η σ l + exact h ((hnExpansionRaw_range a c η σ d) ▸ LinearMap.mem_range_self _ x) + +noncomputable def hnExpansion (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (d : I → ℕ) : + (⨁ l : HNIndex c η d,HNTensor a c η l.val) →ₗ[ℚ] rawDimensionSpace a d := + (hnExpansionRaw a c η σ d).codRestrict _ (hnExpansionRaw_mem a c η σ d) + +theorem hnExpansion_surjective (hc : ∀ i,0 < c i) + (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) + (hσ : ∀ d,Function.RightInverse (σ d) (destabilizingSpace a (slope c η) d).mkQ) (d : I → ℕ) : + Function.Surjective (hnExpansion a c η σ d) := by + intro x + obtain ⟨y,hy⟩ : x.val∈LinearMap.range (hnExpansionRaw a c η σ d) := by + rw [hnExpansionRaw_range] + exact raw_hn_spanning a c η σ hσ hc d x.property + exact ⟨y,Subtype.ext hy⟩ +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open ElementaryPositivity.SeparatedSymmetry +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable local instance tensorSCommRing (d e : I → ℕ) : CommRing (S d ⊗[ℚ] S e) := inferInstance +noncomputable local instance tensorSAlgebra (d e : I → ℕ) : Algebra ℚ (S d ⊗[ℚ] S e) := inferInstance +noncomputable local instance fourSCommRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂)) := inferInstance +noncomputable local instance fourSAlgebra (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂)) := inferInstance + +noncomputable def fourValueAlg (d₁ e₁ d₂ e₂ : I → ℕ) : + (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂) →ₐ[ℚ] + MvPolynomial (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) ℚ := + (tensorEquivSum ℚ _ _ ℚ).toAlgHom.comp + (Algebra.TensorProduct.map (tensorValueAlg d₁ e₁) (tensorValueAlg d₂ e₂)) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma fourValueAlg_apply (d₁ e₁ d₂ e₂ : I → ℕ) + (x : (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂)) : + fourValueAlg d₁ e₁ d₂ e₂ x=fourValue d₁ e₁ d₂ e₂ x := rfl + +noncomputable def fourInterchange (d₁ e₁ d₂ e₂ : I → ℕ) : + (S d₁ ⊗[ℚ] S d₂) ⊗[ℚ] (S e₁ ⊗[ℚ] S e₂) ≃ₗ[ℚ] + (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂) := + TensorProduct.tensorTensorTensorComm ℚ _ _ _ _ + +omit [Fintype I] [DecidableEq I] in +lemma fourValue_interchange (d₁ e₁ d₂ e₂ : I → ℕ) + (f : S d₁ ⊗[ℚ] S d₂) (g : S e₁ ⊗[ℚ] S e₂) : + fourValue d₁ e₁ d₂ e₂ (fourInterchange d₁ e₁ d₂ e₂ (f⊗ₜ[ℚ]g))= + rename (firstColumnVars d₁ e₁ d₂ e₂) (tensorValue d₁ d₂ f) * + rename (secondColumnVars d₁ e₁ d₂ e₂) (tensorValue e₁ e₂ g) := by + induction f using TensorProduct.inductionOn with + | add f h hf hh => + rw [TensorProduct.add_tmul, (fourInterchange d₁ e₁ d₂ e₂).map_add, + (fourValue d₁ e₁ d₂ e₂).map_add, (tensorValue d₁ d₂).map_add, map_add, hf, hh, add_mul] + | tmul x y => + induction g using TensorProduct.inductionOn with + | add g h hg hh => + rw [TensorProduct.tmul_add, (fourInterchange d₁ e₁ d₂ e₂).map_add, + (fourValue d₁ e₁ d₂ e₂).map_add, (tensorValue e₁ e₂).map_add, map_add, hg, hh, mul_add] + | tmul z w => + simp only [fourInterchange,TensorProduct.tensorTensorTensorComm_tmul, + fourValue_tmul,tensorValue_tmul,map_mul,rename_rename] + have h₁ : Sum.inl ∘ Sum.inl = firstColumnVars d₁ e₁ d₂ e₂ ∘ Sum.inl := rfl + have h₂ : Sum.inl ∘ Sum.inr = secondColumnVars d₁ e₁ d₂ e₂ ∘ Sum.inl := rfl + have h₃ : Sum.inr ∘ Sum.inl = firstColumnVars d₁ e₁ d₂ e₂ ∘ Sum.inr := rfl + have h₄ : Sum.inr ∘ Sum.inr = secondColumnVars d₁ e₁ d₂ e₂ ∘ Sum.inr := rfl + rw [h₁,h₂,h₃,h₄] + ring + +noncomputable def fourCrossPolynomial (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) := + rename (fourPackEquiv d₁ e₁ d₂ e₂) + (crossKernelPolynomial a (canonicalGridCut d₁ e₁ d₂ e₂) + (canonicalLeftCut d₁ e₁ d₂ e₂) (canonicalRightCut d₁ e₁ d₂ e₂)) + +lemma fourGridPolynomial_one (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + fourGridPolynomial a (1 : S (d₁+d₂)) (1 : S (e₁+e₂)) d₁ e₁ d₂ e₂= + fourCrossPolynomial a d₁ e₁ d₂ e₂ := by + rw [fourGridPolynomial_factor a d₁ e₁ d₂ e₂ (firstCut d₁ d₂) (firstCut e₁ e₂)] + simp only [tensorValue_restrictTensor,OneMemClass.coe_one,map_one,one_mul,fourCrossPolynomial] + +lemma fourCrossPolynomial_invariant (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (σ : CellGroup d₁ e₁ × CellGroup d₂ e₂) : + rename (sumAction (cellAction d₁ e₁) (cellAction d₂ e₂) σ) + (fourCrossPolynomial a d₁ e₁ d₂ e₂)=fourCrossPolynomial a d₁ e₁ d₂ e₂ := by + rw [←fourGridPolynomial_one] + exact fourGridPolynomial_invariant _ _ _ _ _ _ _ _ + +noncomputable def fourCrossTensor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂) := + separateFour d₁ e₁ d₂ e₂ (fourCrossPolynomial a d₁ e₁ d₂ e₂) + +lemma fourValue_fourCrossTensor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + fourValue d₁ e₁ d₂ e₂ (fourCrossTensor a d₁ e₁ d₂ e₂)= + fourCrossPolynomial a d₁ e₁ d₂ e₂ := + fourValue_separateFour _ _ _ _ _ (fourCrossPolynomial_invariant _ _ _ _ _) + +lemma separateFour_grid_factor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ d₂) (B : Cut e₁ e₂) (f : S (d₁+d₂)) (g : S (e₁+e₂)) : + separateFour d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂)= + fourInterchange d₁ e₁ d₂ e₂ (restrictTensor A f⊗ₜ[ℚ]restrictTensor B g)* + fourCrossTensor a d₁ e₁ d₂ e₂ := by + apply fourValue_injective + rw [fourValue_separateFour _ _ _ _ _ (fourGridPolynomial_invariant _ _ _ _ _ _ _)] + change _=fourValueAlg d₁ e₁ d₂ e₂ (_*_) + rw [map_mul,fourValueAlg_apply,fourValueAlg_apply,fourValue_interchange,fourValue_fourCrossTensor] + exact fourGridPolynomial_factor _ _ _ _ _ A B f g + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNHilbert.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNHilbert.lean new file mode 100644 index 0000000000000000000000000000000000000000..8354a838a8345e979c254eb1f83192e1e61916a4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNHilbert.lean @@ -0,0 +1,45 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNHomogeneousBasis +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousBasisFibre + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0hnBasisDegree a c η i.1.val i.2) (componentS d) + (hnHomogeneousBasis_component a c η hc d) k + +include hc + +theorem hnGradedIndex_finite (d : I → ℕ) (k : ℤ) : Finite (HNGradedIndex a c η d k) := by + let := componentS_range_finite d k + exact Module.Finite.finite_basis (hnGradedBasis a c η hc d k) + +theorem hnHilbert_coefficient (d : I → ℕ) (k : ℤ) : + Module.finrank ℚ (LinearMap.range (componentS d k))=Nat.card (HNGradedIndex a c η d k) := by + let := hnGradedIndex_finite a c η hc d k + let := Fintype.ofFinite (HNGradedIndex a c η d k) + rw [Module.finrank_eq_card_basis (hnGradedBasis a c η hc d k),Nat.card_eq_fintype_card] +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNHomogeneousBasis.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNHomogeneousBasis.lean new file mode 100644 index 0000000000000000000000000000000000000000..78cdc1aee43868ea8634082fb935bd19726c221c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNHomogeneousBasis.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNIndependent +import OAI.Combinatorics.Chromatic.Walls.Grade + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic +attribute [local instance] Classical.propDecidable +lemma dfinsupp_basis_apply {J : Type*} [DecidableEq J] {M : J → Type*} [∀ j,AddCommGroup (M j)] + [∀ j,Module ℚ (M j)] {K : J → Type*} (b : ∀ j,Module.Basis (K j) ℚ (M j)) + (j : J) (k : K j) : DFinsupp.basis b ⟨j,k⟩=DFinsupp.single j (b j k) := by + classical + apply Module.Basis.apply_eq_iff.mpr + ext ⟨i,l⟩ + by_cases h : i=j + · subst i + simp [DFinsupp.basis,Finsupp.single_apply] + · simp [DFinsupp.basis,h,Ne.symm h] + +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) + +local instance gradeBFinite (d : I → ℕ) (k : ℤ) : Module.Finite ℚ (gradeB a (slope c η) d k) := + gradeB_finite a (slope c η) d k + +local instance gradeBFree (d : I → ℕ) (k : ℤ) : Module.Free ℚ (gradeB a (slope c η) d k) := + Module.Free.of_divisionRing ℚ _ + +abbrev HomogeneousBIndex (d : I → ℕ) := Σ k : ℤ,Fin (Module.finrank ℚ (gradeB a (slope c η) d k)) +noncomputable def homogeneousBBasis (d : I → ℕ) : Module.Basis (HomogeneousBIndex a c η d) ℚ (B a (slope c η) d) := + (gradeB_internal a (slope c η) d).collectedBasis (fun k=>Module.finBasis ℚ (gradeB a (slope c η) d k)) +lemma homogeneousBBasis_mem (d : I → ℕ) (i : HomogeneousBIndex a c η d) : + homogeneousBBasis a c η d i∈gradeB a (slope c η) d i.1 := + (gradeB_internal a (slope c η) d).collectedBasis_mem _ i + +def HNBasisIndex : List (I → ℕ) → Type + | [] => Unit + | d::l => HomogeneousBIndex a c η d × HNBasisIndex l +noncomputable def hnTensorBasis : (l : List (I → ℕ)) → Module.Basis (HNBasisIndex a c η l) ℚ (HNTensor a c η l) + | [] => (Module.Basis.singleton Unit ℚ).map (zeroPolynomialEquiv (I:=I)).symm + | d::l => (homogeneousBBasis a c η d).tensorProduct (hnTensorBasis l) + +def hnBasisDegree : (l : List (I → ℕ)) → HNBasisIndex a c η l → ℤ + | [],_ => 0 + | d::l,i => i.1.1+hnBasisDegree l i.2-eulerForm a d l.sum + +lemma hnTensorBasis_nil (i : Unit) : hnTensorBasis a c η [] i=(1 : S (0 : I → ℕ)) := by + change ((Module.Basis.singleton Unit ℚ).map (zeroPolynomialEquiv (I:=I)).symm) i=_ + rw [Module.Basis.map_apply,Module.Basis.singleton_apply] + exact one_smul ℚ (1 : S (0 : I → ℕ)) +lemma hnTensorBasis_cons (d : I → ℕ) (l : List (I → ℕ)) + (i : HomogeneousBIndex a c η d) (j : HNBasisIndex a c η l) : + hnTensorBasis a c η (d::l) (i,j)=homogeneousBBasis a c η d i⊗ₜ[ℚ]hnTensorBasis a c η l j := + Module.Basis.tensorProduct_apply _ _ i j + +lemma hnTensorBasis_polynomial (l : List (I → ℕ)) (i : HNBasisIndex a c η l) : + (hnPolynomial a c η (homogeneousSection a (slope c η)) l (hnTensorBasis a c η l i)).val.IsWeightedHomogeneous + (fun _=>(1:ℤ)) (hnBasisDegree a c η l i) := by + induction l with + | nil => + have H := hnTensorBasis_nil a c η i + exact (congrArg (fun f : S (0 : I → ℕ)=>f.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) 0) H).mpr + (MvPolynomial.isWeightedHomogeneous_one ℚ (fun _=>(1:ℤ))) + | cons d l ih => + rcases i with ⟨i,j⟩ + have H := congrArg (hnPolynomial a c η (homogeneousSection a (slope c η)) (d::l)) + (hnTensorBasis_cons a c η d l i j) + have H' := H.trans (hnPolynomial_cons a c η (homogeneousSection a (slope c η)) d l _ _) + exact (congrArg (fun f : S (d+l.sum)=>f.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) + (i.1+hnBasisDegree a c η l j-eulerForm a d l.sum)) H').mpr + (shufflePolynomial_homogeneous a _ _ + (homogeneousSection_graded a (slope c η) d i.1 _ (homogeneousBBasis_mem a c η d i)) (ih j)) + +noncomputable def hnHomogeneousBasis (hc : ∀ i,0hnTensorBasis a c η l.val)).map + (hnOrderedEquiv a c η hc (homogeneousSection a (slope c η)) + (homogeneousSection_rightInverse a (slope c η)) d) + +lemma hnHomogeneousBasis_apply (hc : ∀ i,0(1:ℤ)) + (hnBasisDegree a c η i.1.val i.2) := by + rw [hnHomogeneousBasis_apply] + have H := hnTensorBasis_polynomial a c η i.1.val i.2 + generalize hp : hnPolynomial a c η (homogeneousSection a (slope c η)) i.1.val + (hnTensorBasis a c η i.1.val i.2)=x at H ⊢ + rcases i with ⟨⟨l,hl,ho⟩,i⟩ + dsimp only at * + subst d + exact H +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNIndependent.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNIndependent.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ba8a50342e9b45ff80df9b7b22ef74c219e0a0e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNIndependent.lean @@ -0,0 +1,145 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNDetectorBasics +import OAI.Combinatorics.Chromatic.Walls.TriangularDirectSum + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) + +noncomputable def hnPolynomialExpansion (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (d : I → ℕ) : + (⨁ l : HNIndex c η d,HNTensor a c η l.val) →ₗ[ℚ] S d := + DirectSum.toModule ℚ _ _ (fun l=>(dimensionCast l.property.1).comp (hnPolynomial a c η σ l.val)) + +lemma hnExpansionRaw_polynomial (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (d : I → ℕ) : + hnExpansionRaw a c η σ d=(rawLof a d).comp (hnPolynomialExpansion a c η σ d) := by + apply DirectSum.linearMap_ext + intro l + apply LinearMap.ext + intro x + simp only [hnExpansionRaw,hnPolynomialExpansion,LinearMap.comp_apply,DirectSum.toModule_lof] + rw [hnWordMap_polynomial,LinearMap.comp_apply,dimensionCast_eq_castS,rawLof_cast] + +instance hnIndex_strict (d : I → ℕ) : + IsStrictOrder (HNIndex c η d) (fun l r=>List.Lex (hnKeyLT c η) l.val r.val) where + irrefl := fun l=>List.lex_irrefl (hnKeyLT_irrefl c η) l.val + trans := fun _ _ _=>List.lex_trans (hnKeyLT_trans c η) + +theorem hnPolynomialExpansion_injective (hc : ∀ i,0hn_detector_exists a c η hc σ hσ l.val l.property.2 + let F := fun l : HNIndex c η d=>(dimensionCast l.property.1).comp (hnPolynomial a c η σ l.val) + let T := fun l : HNIndex c η d=>(D l).comp (dimensionCast l.property.1.symm) + apply triangular_directSum_injective (fun l r : HNIndex c η d=>List.Lex (hnKeyLT c η) l.val r.val) F T + · intro l x + change D l (dimensionCast l.property.1.symm (dimensionCast l.property.1 (hnPolynomial a c η σ l.val x)))=x + rw [dimensionCast_trans] + exact LinearMap.congr_fun (hD l).diagonal x + · intro l r hne hn x + change D l (dimensionCast l.property.1.symm (dimensionCast r.property.1 (hnPolynomial a c η σ r.val x)))=0 + rw [dimensionCast_trans,dimensionCast_eq_castS] + exact (hD l).off r.val r.property.2 (r.property.1.trans l.property.1.symm) hn + (fun h=>hne (Subtype.ext h)) x + +lemma hnPolynomialExpansion_surjective (hc : ∀ i,0 ↥(gradeB a μ d k)) k x)=x.val := + DirectSum.coeLinearMap_of _ _ _ +lemma gradeBEquiv_symm_homogeneous (k : ℤ) (x : gradeB a μ d k) : + (gradeBEquiv a μ d).symm x.val=DirectSum.lof ℚ ℤ (fun k => ↥(gradeB a μ d k)) k x := by + apply (gradeBEquiv a μ d).injective + rw [LinearEquiv.apply_symm_apply,gradeBEquiv_of] + +noncomputable def homogeneousSection : B a μ d →ₗ[ℚ] S d := + (DirectSum.toModule ℚ _ _ (fun k=>(LinearMap.range (componentS d k)).subtype.comp + (degreeSection a μ d k))).comp (gradeBEquiv a μ d).symm.toLinearMap +lemma homogeneousSection_on_grade (k : ℤ) (x : gradeB a μ d k) : + homogeneousSection a μ d x.val=(degreeSection a μ d k x).val := by + unfold homogeneousSection + rw [LinearMap.comp_apply,LinearEquiv.coe_coe,gradeBEquiv_symm_homogeneous,DirectSum.toModule_lof] + rfl +lemma homogeneousSection_rightInverse : + Function.RightInverse (homogeneousSection a μ d) (destabilizingSpace a μ d).mkQ := by + have H : (destabilizingSpace a μ d).mkQ.comp + (DirectSum.toModule ℚ ℤ (S d) (fun k=>(LinearMap.range (componentS d k)).subtype.comp + (degreeSection a μ d k)))=(gradeBEquiv a μ d).toLinearMap := by + apply DirectSum.linearMap_ext + intro k + apply LinearMap.ext + intro x + change (destabilizingSpace a μ d).mkQ + ((DirectSum.toModule ℚ ℤ (S d) (fun k=>(LinearMap.range (componentS d k)).subtype.comp + (degreeSection a μ d k))) (DirectSum.lof ℚ ℤ (fun k => ↥(gradeB a μ d k)) k x))=_ + rw [DirectSum.toModule_lof] + exact (congrArg Subtype.val (degreeSection_rightInverse a μ d k x)).trans (gradeBEquiv_of a μ d k x).symm + intro x + exact (LinearMap.congr_fun H ((gradeBEquiv a μ d).symm x)).trans (LinearEquiv.apply_symm_apply _ x) +lemma homogeneousSection_graded (k : ℤ) (x : B a μ d) (hx : x∈gradeB a μ d k) : + (homogeneousSection a μ d x).val.IsWeightedHomogeneous (fun _=>(1:ℤ)) k := by + rw [homogeneousSection_on_grade a μ d k ⟨x,hx⟩] + obtain ⟨g,hg⟩:=(degreeSection a μ d k ⟨x,hx⟩).property + rw [←hg] + exact componentS_homogeneous d k g +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNPolynomial.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNPolynomial.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee164e956d4a8ef6337e9706251619574dc72468 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNPolynomial.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.CutoffGrid + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) + +noncomputable def hnPolynomial (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) : + (l : List (I → ℕ)) → HNTensor a c η l →ₗ[ℚ] S l.sum + | [] => LinearMap.id + | d::l => (shuffleTensorLinear a d l.sum).comp (TensorProduct.map (σ d) (hnPolynomial σ l)) +lemma hnPolynomial_cons (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) + (d : I → ℕ) (l : List (I → ℕ)) (x : B a (slope c η) d) (y : HNTensor a c η l) : + hnPolynomial a c η σ (d::l) (x⊗ₜ[ℚ]y)=shufflePolynomial a (σ d x) (hnPolynomial a c η σ l y) := rfl +lemma hnWordMap_polynomial (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (l : List (I → ℕ)) : + hnWordMap a c η σ l=(rawLof a l.sum).comp (hnPolynomial a c η σ l) := by + induction l with + | nil => rfl + | cons d l ih => + apply TensorProduct.ext' + intro x y + change rawLof a d (σ d x)*hnWordMap a c η σ l y=rawLof a (d+l.sum) _ + rw [ih,LinearMap.comp_apply,rawLof_mul] + rfl + +lemma clipped_destabilizingSpace_le (κ : ℝ) (d : I → ℕ) : + destabilizingSpace a (clippedSlope c η κ) d ≤ destabilizingSpace a (slope c η) d := by + apply Submodule.span_le.mpr + rintro f ⟨u,v,h,x,y,hu,hv,hs,rfl⟩ + apply Submodule.subset_span + refine ⟨u,v,h,x,y,hu,hv,?_,rfl⟩ + have H := (lt_max_iff.mp hs).resolve_right (not_lt_of_ge (le_max_right _ _)) + exact (le_max_left _ _).trans_lt H + +noncomputable def clippedToOriginal (κ : ℝ) (d : I → ℕ) : + B a (clippedSlope c η κ) d →ₗ[ℚ] B a (slope c η) d := + Submodule.mapQ _ _ LinearMap.id (clipped_destabilizingSpace_le a c η κ d) +lemma clippedToOriginal_mk (κ : ℝ) (d : I → ℕ) (f : S d) : + clippedToOriginal a c η κ d (quotientAlg a (clippedSlope c η κ) d f)=quotientAlg a (slope c η) d f := rfl + +lemma headRestriction_wrong_head (hc : ∀ i,0simp [decoratedDimension] + | cons b l ih=> + change slopeValue c η θ (b.1+decoratedDimension a c η hc l)≤0 + rw [slopeValue_add] + exact add_nonpos (h b (by simp)) (ih (fun e he=>h e (by simp [he]))) + +lemma decorated_value_pos (θ : ℝ) (l : List (RowBlock a c η hc)) (hl : l≠[]) + (h : ∀b∈l,0exact (hl rfl).elim + | cons b l ih=> + change 0h e (by simp [he]))) + +lemma highIndex_sign (θ : ℝ) (d : I → ℕ) (w : HighHNIndex a c η hc θ d) : + d=0 ∨ 0 + (slopeValue_pos_iff c η hc θ b.1 (w.val.val.property.1 b hb)).mpr (w.val.property b hb)) + +lemma lowIndex_sign (θ : ℝ) (d : I → ℕ) (w : LowHNIndex a c η hc θ d) : + slopeValue c η θ d≤0 := by + rw [←w.property] + exact decorated_value_nonpos a c η hc θ _ (fun b hb=> + (slopeValue_nonpos_iff c η hc θ b.1 (w.val.val.property.1 b hb)).mpr (w.val.property b hb)) + +end +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open UnitSelections EnergyLaurent WallUnits +noncomputable section +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] +variable (a : I → I → ℕ) (κ : I → ℤ) (ε : I → Bool) + +def inputUnitEquiv (d : I → ℕ) : InputIndexLists ε d ≃ + (∀i,UnitIndex (elementaryDiagonal ε i) (d i)) := + Equiv.piCongrRight (fun i=>Equiv.subtypeEquivRight (fun f=>by + cases hi : ε i <;> simp [elementaryDiagonal,hi])) + +lemma inputUnit_energy (d : I → ℕ) (x : InputIndexLists ε d) : + (∑i,unitEnergy (elementaryDiagonal ε i) (d i) (κ i) (inputUnitEquiv ε d x i))+ + crossInteraction a d=inputTorusEnergy a κ ε d x := by + simp only [unitEnergy,unitWeight,weight,inputUnitEquiv,Equiv.piCongrRight_apply,Pi.map, + Equiv.subtypeEquivRight_apply,inputTorusEnergy,inputLinearEnergy, + listIndexSum,Nat.cast_sum,Finset.sum_sub_distrib,←Finset.mul_sum] + congr 1 + apply congrArg₂ (·-·) + · apply Finset.sum_congr rfl; intro i hi; ring + · rfl + +def literalInputCoefficient (d : I → ℕ) : LaurentSeries ℚ := + (∏i,LaurentRay.atInfinity (PowerSeries.coeff (d i) (indexedUnit (elementaryDiagonal ε i) (κ i)))) * + HahnSeries.single (-crossInteraction a d) 1 + +theorem literalInputCoefficient_eq (ha : ∀i,a i i=elementaryDiagonal ε i) (d : I → ℕ) : + literalInputCoefficient a κ ε d=inputReorderingSeries a κ ε ha d := by + unfold literalInputCoefficient + simp only [indexedUnit_literal_expansion,indexedUnitSeries] + rw [series_pi] + rw [←series_shift] + apply series_equiv _ _ (inputUnitEquiv ε d).symm + intro x + have H:=inputUnit_energy a κ ε d ((inputUnitEquiv ε d).symm x) + simpa only [Equiv.apply_symm_apply] using H.symm +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNThreshold.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNThreshold.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9a412b7aa0e5afcd6945283f7e0e7d39489bb38 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNThreshold.lean @@ -0,0 +1,162 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.PrimitiveBlockRows +import OAI.Combinatorics.Chromatic.Walls.ThresholdWords +import OAI.Combinatorics.Chromatic.GradedAlgebra.EnergyLaurentFinite + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic +noncomputable section +attribute [local instance] Classical.propDecidable +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0b.1≠0) (fun b=>slope c η b.1) +abbrev HighHNWord (θ : ℝ) := ThresholdWords.High + (fun b : RowBlock a c η hc=>b.1≠0) (fun b=>slope c η b.1) θ +abbrev LowHNWord (θ : ℝ) := ThresholdWords.Low + (fun b : RowBlock a c η hc=>b.1≠0) (fun b=>slope c η b.1) θ + +lemma hnOrdered_map_iff (l : List (RowBlock a c η hc)) : + HNOrdered c η (l.map Sigma.fst) ↔ + (∀ b∈l,b.1≠0) ∧ l.Pairwise (fun b e=>slope c η e.1by rw [splitHNWord_dimension])).trans + (dimensionProduct (fun w : HighHNWord a c η hc θ=>decoratedDimension a c η hc w.val.val) + (fun w : LowHNWord a c η hc θ=>decoratedDimension a c η hc w.val.val) d).symm) + +lemma thresholdIndexEquiv_symm_energy (θ : ℝ) (d : I → ℕ) + (z : Σ s : DimensionSplit d,HighHNIndex a c η hc θ s.left × LowHNIndex a c η hc θ s.right) : + decoratedEnergy a κ c η hc ((thresholdIndexEquiv a c η hc θ d).symm z).val= + decoratedEnergy a κ c η hc z.2.1.val.val.val+ + decoratedEnergy a κ c η hc z.2.2.val.val.val+ + (eulerForm a z.1.left z.1.right-eulerForm a z.1.right z.1.left) := by + change decoratedEnergy a κ c η hc (z.2.1.val.val.val++z.2.2.val.val.val)=_ + rw [decoratedEnergy_append,z.2.1.property,z.2.2.property] + +lemma thresholdIndexEquiv_energy (θ : ℝ) (d : I → ℕ) (w : DecoratedHN a c η hc d) : + let z:=thresholdIndexEquiv a c η hc θ d w + decoratedEnergy a κ c η hc z.2.1.val.val.val+ + decoratedEnergy a κ c η hc z.2.2.val.val.val+ + (eulerForm a z.1.left z.1.right-eulerForm a z.1.right z.1.left)= + decoratedEnergy a κ c η hc w.val := by + simpa only [Equiv.symm_apply_apply] using + (thresholdIndexEquiv_symm_energy a κ c η hc θ d (thresholdIndexEquiv a c η hc θ d w)).symm + +end +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.EnergyLaurent +noncomputable section +lemma admissible_injective {A B : Type*} {e : A → ℤ} {f : B → ℤ} + (he : Admissible e) (g : B → A) (hg : Function.Injective g) + (hf : ∀b,e (g b)=f b) : Admissible f := by + constructor + · obtain ⟨K,hK⟩:=he.1 + exact ⟨K,fun b=>by rw [←hf]; exact hK (g b)⟩ + · intro E + let := he.2 E + exact Finite.of_injective (fun b : {b // f b=E}=> + (⟨g b.val,by rw [hf,b.property]⟩ : {a // e a=E})) + (fun x y H=>Subtype.ext (hg (congrArg Subtype.val H))) +end +end ElementaryPositivity.EnergyLaurent + +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic EnergyLaurent +noncomputable section +attribute [local instance] Classical.propDecidable +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0Subtype.ext (Subtype.ext (Subtype.ext (congrArg (fun z : DecoratedHN a c η hc d=>z.val) H)))) (fun _=>rfl) +lemma lowEnergy_admissible (θ : ℝ) (d : I → ℕ) : Admissible (lowEnergy a κ c η hc θ d) := + admissible_injective (decoratedEnergy_admissible a κ c η hc d) (lowDecorated a c η hc θ d) + (fun _ _ H=>Subtype.ext (Subtype.ext (Subtype.ext (congrArg (fun z : DecoratedHN a c η hc d=>z.val) H)))) (fun _=>rfl) + +def highSeries (θ : ℝ) (d : I → ℕ) : LaurentSeries ℚ := + series (highEnergy a κ c η hc θ d) (highEnergy_admissible a κ c η hc θ d) +def lowSeries (θ : ℝ) (d : I → ℕ) : LaurentSeries ℚ := + series (lowEnergy a κ c η hc θ d) (lowEnergy_admissible a κ c η hc θ d) +def hnSeries (d : I → ℕ) : LaurentSeries ℚ := + series (fun w : DecoratedHN a c η hc d=>decoratedEnergy a κ c η hc w.val) + (decoratedEnergy_admissible a κ c η hc d) + +lemma hnSeries_threshold (θ : ℝ) (d : I → ℕ) : + hnSeries a κ c η hc d = ∑s : DimensionSplit d, + highSeries a κ c η hc θ s.left * lowSeries a κ c η hc θ s.right * + HahnSeries.single (-(eulerForm a s.left s.right-eulerForm a s.right s.left)) 1 := by + let f := fun s : DimensionSplit d=>fun p : HighHNIndex a c η hc θ s.left × LowHNIndex a c η hc θ s.right=> + highEnergy a κ c η hc θ s.left p.1+lowEnergy a κ c η hc θ s.right p.2+ + (eulerForm a s.left s.right-eulerForm a s.right s.left) + have hf : ∀s,Admissible (f s) := fun s=> + admissible_shift (admissible_prod (highEnergy_admissible a κ c η hc θ s.left) + (lowEnergy_admissible a κ c η hc θ s.right)) _ + have H := series_equiv (decoratedEnergy_admissible a κ c η hc d) + (admissible_sigma f hf) (thresholdIndexEquiv a c η hc θ d) + (thresholdIndexEquiv_energy a κ c η hc θ d) + rw [series_sigma f hf] at H + change hnSeries a κ c η hc d=_ at H + rw [H] + apply Finset.sum_congr rfl + intro s hs + dsimp only [f] + rw [series_shift (admissible_prod (highEnergy_admissible a κ c η hc θ s.left) + (lowEnergy_admissible a κ c η hc θ s.right)), + ←series_mul (highEnergy_admissible a κ c η hc θ s.left) (lowEnergy_admissible a κ c η hc θ s.right)] + rfl + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/HNZeroFactor.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNZeroFactor.lean new file mode 100644 index 0000000000000000000000000000000000000000..13adafeeda9f32f998272f6e06cd6f8c7a1e9607 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/HNZeroFactor.lean @@ -0,0 +1,145 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.HNTorusFactor +import OAI.Combinatorics.Chromatic.Shuffle.HNZeroRows +import OAI.Combinatorics.Chromatic.QuantumTorus.TorusProjection + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic EnergyLaurent QuantumTorus WeightedTorusSeries WallUnits +open PowerSeries +noncomputable section +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0 simp only [Torus.monomial_zero] + +include hΩ hh in + +theorem hnTorus_zeroFactor : + push w LaurentRay.vUnit Ω P (zeroBlockCoefficient a κ c η hc θ)= + PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) (push w LaurentRay.vUnit Ω P (hnSeries a κ c η hc)) := by + apply PowerSeries.ext + intro n + rw [zeroFactor_coeff_projection,←(hnTorus_canonical_factors a κ c η hc w Ω P hΩ h θ hh).2] + exact zeroBlockCoeff_project a κ c η hc w Ω P h θ hh n + +include hΩ hh in +theorem literalInput_zeroFactor (ε : I → Bool) (ha : ∀i,a i i=elementaryDiagonal ε i) : + push w LaurentRay.vUnit Ω P (zeroBlockCoefficient a κ c η hc θ)= + PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) (push w LaurentRay.vUnit Ω P (literalInputCoefficient a κ ε)) := by + have he : literalInputCoefficient a κ ε=hnSeries a κ c η hc := + funext (literalInput_hnSeries a κ c η hc ε ha) + rw [he] + exact hnTorus_zeroFactor a κ c η hc w Ω P hΩ h θ hh + +end +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic SignedMultiplicity UnitSelections EnergyLaurent +noncomputable section +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0hd (primitiveCounts_onSlope a c η hc θ d x)⟩ + ext j + rw [primitiveCountsSeries,series_coeff] + simp + +lemma primitiveCountsSeries_support (θ : ℝ) (d : I → ℕ) + (hd : primitiveCountsSeries a κ c η hc θ d≠0) : OnSlopeOrZero c η θ d := by + by_contra H + exact hd (primitiveCountsSeries_vanish a κ c η hc θ d H) + +lemma primitiveCountsSeries_eq_zeroBlock (θ : ℝ) (d : I → ℕ) : + primitiveCountsSeries a κ c η hc θ d=zeroBlockCoefficient a κ c η hc θ d := by + by_cases hd : d=0 + · subst d + rw [primitiveCountsSeries_zero] + simp only [zeroBlockCoefficient,dite_eq_left trivial] + · rw [zeroBlockCoefficient,dite_eq_right hd] + by_cases hz : slopeValue c η θ d=0 + · rw [ite_eq_left hz] + have hs := (slopeValue_eq_zero_iff c η hc θ d hd).mp hz + subst θ + exact series_equiv _ _ (primitiveCountsRows a c η hc d) + (primitiveCountsRows_energy a κ c η hc d) + · rw [ite_eq_right hz] + apply primitiveCountsSeries_vanish + intro H + apply hz + exact (slopeValue_eq_zero_iff c η hc θ d hd).mpr (H.resolve_left hd) + +open QuantumTorus WeightedTorusSeries WallUnits +variable (w : I → ℕ) [Fact (∀i,0simp + | cons b l ih=> + have hb:=h b (by simp) + have ht : ∀e∈l,slopeValue c η θ e.1≤0 := fun e he=>h e (by simp [he]) + have hl:=decorated_value_nonpos a c η hc θ l ht + change slopeValue c η θ (b.1+decoratedDimension a c η hc l)=0 at hz + rw [slopeValue_add] at hz + have hb0 : slopeValue c η θ b.1=0 := by linarith + have hl0 : slopeValue c η θ (decoratedDimension a c η hc l)=0 := by linarith + intro e he + rcases List.mem_cons.mp he with rfl|he + · exact hb0 + · exact ih ht hl0 e he + +lemma lowIndex_singleton (θ : ℝ) (d : I → ℕ) (hd : d≠0) + (hz : slopeValue c η θ d=0) (x : LowHNIndex a c η hc θ d) : + ∃r : BlockRows a c η hc d,x.val.val.val=[⟨d,r⟩] := by + have hval : ∀b∈x.val.val.val,slopeValue c η θ b.1≤0 := fun b hb=> + (slopeValue_nonpos_iff c η hc θ b.1 (x.val.val.property.1 b hb)).mpr (x.val.property b hb) + have heach:=decorated_zero_each a c η hc θ x.val.val.val hval (by rw [x.property,hz]) + have hs : ∀b∈x.val.val.val,slope c η b.1=θ := fun b hb=> + (slopeValue_eq_zero_iff c η hc θ b.1 (x.val.val.property.1 b hb)).mp (heach b hb) + have hn : x.val.val.val≠[] := by + intro H + have hh:=x.property + rw [H] at hh + exact hd hh.symm + obtain ⟨b,l,hl⟩:=List.exists_cons_of_ne_nil hn + have hnil : l=[] := by + cases l with + | nil=>rfl + | cons e l=> + have H:=x.val.val.property.2 + rw [hl] at H + have Hbe := (List.pairwise_cons.mp H).1 e (by simp) + change slope c η e.1 < slope c η b.1 at Hbe + rw [hs b (by rw [hl]; simp),hs e (by rw [hl]; simp)] at Hbe + exact (lt_irrefl θ Hbe).elim + subst l + have hb : b.1=d := by + have H:=x.property + simpa only [hl,decoratedDimension,List.map_cons,List.map_nil,List.sum_cons,List.sum_nil,add_zero] using H + rcases b with ⟨b,r⟩ + dsimp only at hb + subst b + exact ⟨r,hl⟩ + +def lowFromRow (θ : ℝ) (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) + (r : BlockRows a c η hc d) : LowHNIndex a c η hc θ d := + ⟨⟨⟨[⟨d,r⟩],by simp [hd]⟩,by simp [hs]⟩,by simp [decoratedDimension]⟩ + +lemma lowFromRow_injective (θ : ℝ) (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) : + Function.Injective (lowFromRow a c η hc θ d hd hs) := by + intro r s H + have H':=congrArg (fun x : LowHNIndex a c η hc θ d=>x.val.val.val) H + simpa only [lowFromRow,List.cons.injEq,and_true,Sigma.mk.inj_iff,heq_eq_eq,true_and] using H' + +def lowRowsEquiv (θ : ℝ) (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) : + BlockRows a c η hc d ≃ LowHNIndex a c η hc θ d := + Equiv.ofBijective (lowFromRow a c η hc θ d hd hs) + ⟨lowFromRow_injective a c η hc θ d hd hs,fun x=>by + obtain ⟨r,hr⟩:=lowIndex_singleton a c η hc θ d hd + ((slopeValue_eq_zero_iff c η hc θ d hd).mpr hs) x + exact ⟨r,Subtype.ext (Subtype.ext (Subtype.ext hr.symm))⟩⟩ + +lemma lowFromRow_energy (θ : ℝ) (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) + (r : BlockRows a c η hc d) : + lowEnergy a κ c η hc θ d (lowFromRow a c η hc θ d hd hs r)=blockRowsEnergy a κ c η hc d r := by + simp [lowEnergy,lowFromRow,decoratedEnergy,decoratedDimension,eulerForm] + +lemma blockRowsEnergy_admissible (d : I → ℕ) (hd : d≠0) : + Admissible (blockRowsEnergy a κ c η hc d) := + admissible_injective (lowEnergy_admissible a κ c η hc (slope c η d) d) + (lowFromRow a c η hc (slope c η d) d hd rfl) + (lowFromRow_injective a c η hc (slope c η d) d hd rfl) + (lowFromRow_energy a κ c η hc (slope c η d) d hd rfl) + +lemma lowSeries_on_slope (θ : ℝ) (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) : + lowSeries a κ c η hc θ d=series (blockRowsEnergy a κ c η hc d) + (blockRowsEnergy_admissible a κ c η hc d hd) := by + symm + exact series_equiv _ _ (lowRowsEquiv a c η hc θ d hd hs) + (lowFromRow_energy a κ c η hc θ d hd hs) + +end +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic SignedMultiplicity UnitSelections EnergyLaurent +noncomputable section +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0slopeStartRowType a c η hc θ x.1≠0) + (fun x=>x.1.1.val.1.val) d + +def primitiveCountsEnergy (θ : ℝ) (d : I → ℕ) (x : PrimitiveCounts a c η hc θ d) : ℤ := + countEnergy _ (fun x=>slopeStartParameter a κ c η hc θ x.1-2*(x.2:ℤ)) x.val + +lemma primitiveCounts_onSlope (θ : ℝ) (d : I → ℕ) (x : PrimitiveCounts a c η hc θ d) : + OnSlopeOrZero c η θ d := by + rw [←x.property] + exact countDimension_mem _ _ (slopeDimensions c η hc θ) (fun x=>x.1.1.val.1.property) x.val + +def primitiveCountsRows (d : I → ℕ) : + PrimitiveCounts a c η hc (slope c η d) d ≃ BlockRows a c η hc d := + (allUnitRowsEquiv (slopeStartRowType a c η hc (slope c η d))).subtypeEquiv + (fun x=>by rw [rowsDimension_equiv]; rfl) + +lemma primitiveCountsRows_energy (d : I → ℕ) (x : PrimitiveCounts a c η hc (slope c η d) d) : + blockRowsEnergy a κ c η hc d (primitiveCountsRows a c η hc d x)= + primitiveCountsEnergy a κ c η hc (slope c η d) d x := by + change rowsEnergy _ _ (allUnitRowsEquiv _ x.val)=_ + rw [rowsEnergy_equiv] + rfl + +lemma primitiveCountsEnergy_admissible (θ : ℝ) (d : I → ℕ) : + Admissible (primitiveCountsEnergy a κ c η hc θ d) := by + classical + by_cases hd : d=0 + · subst d + let := dimensionCounts_zero_subsingleton + (fun x : SlopeStringStart a c η hc θ × ℕ=>slopeStartRowType a c η hc θ x.1≠0) + (fun x=>x.1.1.val.1.val) (fun x=>x.1.1.property) + refine ⟨⟨0,fun x=>?_⟩,fun E=>inferInstance⟩ + change countEnergy _ _ x.val≤0 + rw [dimensionCounts_zero_energy _ _ (fun x=>x.1.1.property)] + · by_cases h : Nonempty (PrimitiveCounts a c η hc θ d) + · have hs : slope c η d=θ := (primitiveCounts_onSlope a c η hc θ d h.some).resolve_left hd + subst θ + exact admissible_injective (blockRowsEnergy_admissible a κ c η hc d hd) + (primitiveCountsRows a c η hc d) (primitiveCountsRows a c η hc d).injective + (primitiveCountsRows_energy a κ c η hc d) + · let : IsEmpty (PrimitiveCounts a c η hc θ d) := not_nonempty_iff.mp h + exact ⟨⟨0,fun x=>isEmptyElim x⟩,fun _=>inferInstance⟩ + +def primitiveCountsSeries (θ : ℝ) (d : I → ℕ) : LaurentSeries ℚ := + series _ (primitiveCountsEnergy_admissible a κ c η hc θ d) + +lemma primitiveCountsSeries_zero (θ : ℝ) : primitiveCountsSeries a κ c η hc θ 0=1 := by + have he : ∀x : PrimitiveCounts a c η hc θ 0,primitiveCountsEnergy a κ c η hc θ 0 x=0 := + fun x=>dimensionCounts_zero_energy _ _ (fun x=>x.1.1.property) _ x + let := dimensionCounts_zero_subsingleton + (fun x : SlopeStringStart a c η hc θ × ℕ=>slopeStartRowType a c η hc θ x.1≠0) + (fun x=>x.1.1.val.1.val) (fun x=>x.1.1.property) + let : Nonempty (PrimitiveCounts a c η hc θ 0) := ⟨⟨zeroCount _,countDimension_zero _ _⟩⟩ + ext j + rw [primitiveCountsSeries,series_coeff,HahnSeries.coeff_one] + by_cases hj : j=0 + · subst j + have H : ∀x : PrimitiveCounts a c η hc θ 0,primitiveCountsEnergy a κ c η hc θ 0 x= -0 := by simpa using he + simp only [H,neg_zero] + simp + · have H : IsEmpty {x : PrimitiveCounts a c η hc θ 0 // primitiveCountsEnergy a κ c η hc θ 0 x= -j} := + ⟨fun x=>hj (by have HH:=x.property; rw [he] at HH; omega)⟩ + let := H + simp [hj] + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/InfinityLaurentFinite.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/InfinityLaurentFinite.lean new file mode 100644 index 0000000000000000000000000000000000000000..843333dfabeb451a00aaf0c8b331701e4da2a4b3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/InfinityLaurentFinite.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.InfinityExpansionFaithful +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentRegradeFinite + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +local instance infinityLaurentFiniteRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance infinityLaurentFiniteAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance infinityLaurentFiniteAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance infinityLaurentFiniteNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance infinityLaurentFiniteNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +include hp in +lemma expandFiberInfinity_off_diagonal + (f : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) + (z : ℤ) (m : M) (h : z≠-k m) : + ((expandFiberInfinity v Ω hΩ k p f).coeff z) m=0 := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp only [map_add,HahnSeries.coeff_add,Finsupp.add_apply,hf,hg,add_zero] + | single l a=> + change ((expandFiberInfinity v Ω hΩ k p (FiberTorus.monomial v _ _ l a)).coeff z) m=0 + rw [expandFiberInfinity_monomial_coeff v Ω hΩ k p l a z] + apply Finsupp.single_eq_of_ne + intro hm + apply h + have H:=congrArg k hm + have hl : k (l:M)=0 := l.property + simp only [map_add,map_zsmul,map_neg,hp,hl,smul_eq_mul,add_zero,mul_neg,mul_one] at H + omega + +lemma expandFiberInfinity_embed_coeff (f : Torus v Ω) (z : ℤ) (m : M) : + ((expandFiberInfinity v Ω hΩ k p (embed v Ω hΩ k p hp f)).coeff z) m= + if z=-k m then f m else 0 := by + by_cases hz : z=-k m + · rw [ite_eq_left hz,hz,expandFiberInfinity_read v Ω hΩ k p hp] + exact readFiberInfinity_embedAdd v Ω k p hp f m + · rw [ite_eq_right hz] + exact expandFiberInfinity_off_diagonal v Ω hΩ k p hp _ z m hz + +lemma expandInfinity_rationalRegrade (δ : M →+ ℤ) (B D : ℕ) + (f : PowerSeries (Torus v Ω)) (hf : LaurentBounded v Ω δ (-k) B f) + (hg : RegradeBound v Ω δ D f) : + PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + (rationalRegrade v Ω hΩ k p hp δ D f)=laurentRegrade v Ω δ (-k) B f hf := by + apply PowerSeries.ext + intro d + apply HahnSeries.ext + funext z + ext m + rw [coeff_map,rationalRegrade,coeff_map,expandFiberInfinity_embed_coeff, + laurentRegrade_finite_read v Ω δ (-k) B D hf hg] + rfl +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/InputOrderedEnergy.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/InputOrderedEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..5db2427a3685c36da42468b59a8880b7eae18c42 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/InputOrderedEnergy.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.InputTorusEnergy +import OAI.Combinatorics.Chromatic.GradedAlgebra.SupportedConvolution + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open WeightedTorusSeries +noncomputable section +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) + +def crossDiagonal (d : I → ℕ) : ℤ := ∑i,(1-(a i i:ℤ))*(d i:ℤ)^2 + +omit [DecidableEq I] in +lemma crossInteraction_euler (d : I → ℕ) : + crossInteraction a d=crossDiagonal a d-eulerForm a d d := by + have H : crossDiagonal a d=(∑ i,(d i:ℤ)*(d i:ℤ))-∑i,(a i i:ℤ)*(d i:ℤ)^2 := by + rw [crossDiagonal,←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro i hi + ring + rw [H,crossInteraction,eulerForm] + ring + +omit [DecidableEq I] in +lemma crossDiagonal_add_disjoint (d e : I → ℕ) (hde : ∀i,d i=0 ∨ e i=0) : + crossDiagonal a (d+e)=crossDiagonal a d+crossDiagonal a e := by + rw [crossDiagonal,crossDiagonal,crossDiagonal,←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i hi + rcases hde i with H|H <;> simp [H] + +omit [DecidableEq I] in +lemma eulerForm_zero_separated (d e : I → ℕ) (hde : ∀i,d i=0 ∨ e i=0) + (ha : ∀i j,d i≠0 → e j≠0 → a i j=0) : eulerForm a d e=0 := by + unfold eulerForm + have H₁ : (∑i,(d i:ℤ)*(e i:ℤ))=0 := by + apply Finset.sum_eq_zero + intro i hi + rcases hde i with H|H <;> simp [H] + have H₂ : (∑ i,∑j,(a i j:ℤ)*(d i:ℤ)*(e j:ℤ))=0 := by + apply Finset.sum_eq_zero + intro i hi + apply Finset.sum_eq_zero + intro j hj + by_cases hd : d i=0 + · simp [hd] + · by_cases he : e j=0 + · simp [he] + · simp [ha i j hd he] + rw [H₁,H₂,sub_self] + +omit [DecidableEq I] in +lemma crossInteraction_add_separated (d e : I → ℕ) (hde : ∀i,d i=0 ∨ e i=0) + (ha : ∀i j,d i≠0 → e j≠0 → a i j=0) : + crossInteraction a (d+e)=crossInteraction a d+crossInteraction a e+ + (eulerForm a d e-eulerForm a e d) := by + rw [crossInteraction_euler,crossInteraction_euler,crossInteraction_euler, + crossDiagonal_add_disjoint a d e hde,eulerForm_add_left,eulerForm_add_right,eulerForm_add_right, + eulerForm_zero_separated a d e hde ha] + ring + +lemma crossInteraction_restrict_union (S T : Finset I) (hST : Disjoint S T) + (ha : ∀i∈S,∀j∈T,a i j=0) (d : I → ℕ) (hd : Supported (S∪T) d) : + crossInteraction a d=crossInteraction a (restrictDim S d)+crossInteraction a (restrictDim T d)+ + (eulerForm a (restrictDim S d) (restrictDim T d)-eulerForm a (restrictDim T d) (restrictDim S d)) := by + conv_lhs => rw [←restrictDim_split S T hST d hd] + apply crossInteraction_add_separated + · intro i + by_cases hS : i∈S + · exact Or.inr (restrictDim_supported T d i (fun hT=>Finset.disjoint_left.mp hST hS hT)) + · exact Or.inl (restrictDim_supported S d i hS) + · intro i j hi hj + apply ha + · by_contra H + exact hi (restrictDim_supported S d i H) + · by_contra H + exact hj (restrictDim_supported T d j H) + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/InputProduct.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/InputProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..387ebeb8420c6847870c68b960013a0ad461ccc0 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/InputProduct.lean @@ -0,0 +1,179 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.HNTorusFactor +import OAI.Combinatorics.Chromatic.GradedAlgebra.InputOrderedProduct + +namespace OAI + +section +namespace ElementaryPositivity.WeightedTorusSeries +open RawShuffle QuantumTorus PowerSeries WallUnits +noncomputable section +attribute [local instance] Classical.propDecidable +variable {I R M : Type*} [Fintype I] [DecidableEq I] [CommRing R] [AddCommGroup M] +variable (a : I → I → ℕ) (u : I → ℕ → R) +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (P : (I → ℕ) →+ M) + +lemma crossInteraction_axis (i : I) (d : I → ℕ) (hd : Supported {i} d) : crossInteraction a d=0 := by + rw [crossInteraction_offdiagonal] + apply Finset.sum_eq_zero + intro j hj + apply Finset.sum_eq_zero + intro k hk + by_cases hjk : j=k + · simp [hjk] + · rw [ite_eq_right hjk] + by_cases hji : j=i + · subst j + rw [hd k (by simp [Ne.symm hjk]),Nat.cast_zero,mul_zero] + · rw [hd j (by simp [hji]),Nat.cast_zero,mul_zero,zero_mul] + +lemma partialCoefficient_singleton (i : I) : + partialCoefficient a u v {i}=supportedCoefficient {i} (fun d=>u i (d i)) := by + funext d + rw [partialCoefficient,supportedCoefficient,supportedCoefficient] + by_cases hd : Supported {i} d + · rw [ite_eq_left hd,ite_eq_left hd] + simp only [Finset.prod_singleton,crossInteraction_axis a i d hd,zpow_zero,Units.val_one,mul_one] + · rw [ite_eq_right hd,ite_eq_right hd] + +variable (w : I → ℕ) [Fact (∀i,0coeff n f) v {i})= + weightedRay v Ω (w i) (P (Pi.single i 1)) f := by + rw [partialCoefficient_singleton,push_axis] + +lemma push_partial_axis_family (i : I) (f : I → PowerSeries R) : + push w v Ω P (partialCoefficient a (fun j n=>coeff n (f j)) v {i})= + weightedRay v Ω (w i) (P (Pi.single i 1)) (f i) := by + rw [partialCoefficient_singleton,push_axis] + +end +end ElementaryPositivity.WeightedTorusSeries + +namespace ElementaryPositivity.RawShuffle +open QuantumTorus WeightedTorusSeries PowerSeries WallUnits +noncomputable section +attribute [local instance] Classical.propDecidable +variable {I M : Type*} [Fintype I] [DecidableEq I] [AddCommGroup M] +variable (a : I → I → ℕ) (κ : I → ℤ) (ε : I → Bool) +variable (Ω : M →+ M →+ ℤ) (P : (I → ℕ) →+ M) +variable (w : I → ℕ) [Fact (∀i,0coeff n (literalAxisScalar κ ε i)) LaurentRay.vUnit Finset.univ= + literalInputCoefficient a κ ε := by + funext d + have HS : Supported Finset.univ d := by intro i hi; exact (hi (Finset.mem_univ i)).elim + rw [partialCoefficient,supportedCoefficient,ite_eq_left HS] + dsimp only [literalAxisScalar] + simp only [coeff_map,LaurentRay.vUnit_zpow] + rfl + +theorem literalInput_ordered (hΩ : ∀d e,Ω (P d) (P e)=eulerForm a d e-eulerForm a e d) + (l : List I) (hl : l.Nodup) (hall : l.toFinset=Finset.univ) + (ho : l.Pairwise fun i j=>a i j=0) : + push w LaurentRay.vUnit Ω P (literalInputCoefficient a κ ε)= + (l.map (literalAxis κ ε Ω P w)).prod := by + have H:=push_partial_list a (fun i n=>coeff n (literalAxisScalar κ ε i)) + LaurentRay.vUnit Ω P hΩ w l hl ho + rw [hall,partial_univ_literal a κ ε] at H + rw [H] + apply congrArg List.prod + apply List.map_congr_left + intro i hi + exact push_partial_axis_family a LaurentRay.vUnit Ω P w i (literalAxisScalar κ ε) + +end +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic QuantumTorus +noncomputable section +variable {I M : Type*} [Fintype I] [DecidableEq I] [AddCommGroup M] +variable (Ω : M →+ M →+ ℤ) (p : I → M) (ε : I → Bool) + +def geometricQuiver (i j : I) : ℕ := + if i=j then elementaryDiagonal ε i else (Ω (p j) (p i)).toNat + +def rootSum : (I→ℕ) →+ M where + toFun d:=∑i,d i • p i + map_zero':=by simp + map_add':=by intro d e; simp only [Pi.add_apply,add_nsmul,Finset.sum_add_distrib] + +lemma rootSum_single (i : I) (n : ℕ) : rootSum p (Pi.single i n)=n • p i := by + classical + simp [rootSum,Pi.single_apply,ite_smul,Finset.sum_ite_eq'] + +omit [Fintype I] in +lemma geometricQuiver_diag (i : I) : geometricQuiver Ω p ε i i=elementaryDiagonal ε i := by + simp [geometricQuiver] + +variable (hΩ : ∀m,Ω m m=0) +omit [Fintype I] in +include hΩ in +lemma geometricQuiver_skew (i j : I) : + (geometricQuiver Ω p ε j i:ℤ)-geometricQuiver Ω p ε i j=Ω (p i) (p j) := by + by_cases h : i=j + · subst j; rw [sub_self,hΩ] + · rw [geometricQuiver,ite_eq_right (Ne.symm h),geometricQuiver,ite_eq_right h, + alternating_skew Ω hΩ (p j) (p i)] + omega + +include hΩ in +lemma geometricQuiver_euler (d e : I→ℕ) : + Ω (rootSum p d) (rootSum p e)= + eulerForm (geometricQuiver Ω p ε) d e-eulerForm (geometricQuiver Ω p ε) e d := by + rw [euler_skew_sum] + simp only [rootSum,AddMonoidHom.coe_mk,ZeroHom.coe_mk,map_sum,map_nsmul, + AddMonoidHom.finsetSum_apply,AddMonoidHom.nsmul_apply,nsmul_eq_mul, + geometricQuiver_skew Ω p ε hΩ] + simp only [Finset.mul_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + ring + +omit [Fintype I] in +include hΩ in +lemma geometricQuiver_forward (i j : I) (hij : i≠j) (hp : 0≤Ω (p i) (p j)) : + geometricQuiver Ω p ε i j=0 := by + rw [geometricQuiver,ite_eq_right hij,alternating_skew Ω hΩ (p j) (p i)] + exact Int.toNat_eq_zero.mpr (by omega) + +omit [Fintype I] in +include hΩ in +lemma geometricQuiver_pairwise (l : List I) (hn : l.Nodup) + (hl : l.Pairwise (fun i j=>0≤Ω (p i) (p j))) : + l.Pairwise (fun i j=>geometricQuiver Ω p ε i j=0) := by + apply (hn.and hl).imp + intro i j h + exact geometricQuiver_forward Ω p ε hΩ i j h.1 h.2 + +include hΩ in +lemma geometricQuiver_symmetric (c η : I→ℝ) (hc : ∀i,0(z:ℝ)) (geometricQuiver_skew Ω p ε hΩ i j) + push_cast at H + exact H.trans (hp i j) + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/InputTorusEnergy.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/InputTorusEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..69d93e2e40d13021d484ab8c055047ed2c76af47 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/InputTorusEnergy.lean @@ -0,0 +1,175 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.PrimitiveUnitRows + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) + +def crossInteraction (d : I → ℕ) : ℤ := + (∑ i,∑ j,(a i j:ℤ)*d i*d j)-∑ i,(a i i:ℤ)*(d i:ℤ)^2 + +def staircaseShift (d : I → ℕ) : ℤ := + ∑ i,((1:ℤ)-a i i)*(d i:ℤ)*((d i:ℤ)-1) + +def inputLinearEnergy (d : I → ℕ) : ℤ := ∑ i,κ i*(d i:ℤ) + +omit [DecidableEq I] in +lemma normalization_diagonal (d : I → ℕ) : + inputShift a κ d-eulerForm a d d= + inputLinearEnergy κ d-staircaseShift a d+crossInteraction a d := by + have H : (∑ i,(d i:ℤ)*(κ i+1-a i i))-(∑ i,(d i:ℤ)*(d i:ℤ))= + (∑ i,κ i*(d i:ℤ))-(∑ i,((1:ℤ)-a i i)*(d i:ℤ)*((d i:ℤ)-1))- + ∑ i,(a i i:ℤ)*(d i:ℤ)^2 := by + simp only [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl; intro i hi + ring + unfold inputShift eulerForm inputLinearEnergy staircaseShift crossInteraction + linear_combination H + +lemma crossInteraction_offdiagonal (d : I → ℕ) : + crossInteraction a d=∑ i,∑ j,if i=j then 0 else (a i j:ℤ)*d i*d j := by + unfold crossInteraction + rw [←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl; intro i hi + have H : (∑ j,(a i j:ℤ)*d i*d j)= + (a i i:ℤ)*(d i:ℤ)^2+∑ j,if i=j then 0 else (a i j:ℤ)*d i*d j := by + calc + _ = ∑ j,((if i=j then (a i i:ℤ)*(d i:ℤ)^2 else 0)+ + if i=j then 0 else (a i j:ℤ)*d i*d j) := by + apply Finset.sum_congr rfl; intro j hj + by_cases h : i=j + · subst j; simp [pow_two,mul_assoc] + · simp [h] + _ = _ := by rw [Finset.sum_add_distrib]; simp + linear_combination H + +variable (ε : I → Bool) (d : I → ℕ) +def inputTorusEnergy (x : InputIndexLists ε d) : ℤ := + inputLinearEnergy κ d-2*(listIndexSum ε d x:ℤ)+crossInteraction a d + +omit [DecidableEq I] in +theorem inputListEnergy_normalized (ha : ∀ i,a i i=elementaryDiagonal ε i) + (x : SortedPackExponent d) : + inputTorusEnergy a κ ε d (inputListEquiv ε d x)= + normalizedEnergy a κ d (sortedPackDegree d x) := by + have H:=inputListIndexSum ε d x + have Hs : (∑ i,((1:ℤ)-elementaryDiagonal ε i)*(d i:ℤ)*((d i:ℤ)-1))= + staircaseShift a d := by simp only [staircaseShift,ha] + rw [Hs] at H + unfold inputTorusEnergy normalizedEnergy + rw [normalization_diagonal] + linear_combination -H +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +attribute [local instance] Classical.propDecidable +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + (⟨d.val,d.property.1⟩ : {d : I → ℕ // d≤D})) (by intro x y h; exact Subtype.ext (congrArg (fun z : {d : I → ℕ // d≤D}=>z.val) h)) + +theorem outputStarts_bounded_finite (κ : I → ℤ) (D : I → ℕ) (L : ℤ) : + Finite {i : OutputStart a c η hc // i.1.val≤D ∧ L≤outputParameter a c η hc κ i} := by + let m (d : I → ℕ) := inputShift a κ d-eulerForm a d d-L + let T := Σ d : {d : I → ℕ // d≤D ∧ d≠0}, + {j : (Σ W : ℤ,StringBaseIndex a c η hc (slope c η d.val) (hχ.out _) d.val W) // + stringBaseDegree a c η hc (slope c η d.val) (hχ.out _) d.val j.1 j.2 ≤ m d.val} + let := finite_nonzero_dimensions_le D + let (d : {d : I → ℕ // d≤D ∧ d≠0}) := stringStarts_bounded_finite a c η hc + (slope c η d.val) (hχ.out _) d.val d.property.2 rfl (m d.val) + let f : {i : OutputStart a c η hc // i.1.val≤D ∧ L≤outputParameter a c η hc κ i} → T := fun i=> + ⟨⟨i.val.1.val,i.property.1,i.val.1.property⟩,⟨i.val.2,by + have H:=i.property.2 + have Hn:=stringBaseDegree_nonneg a c η hc (slope c η i.val.1.val) + (hχ.out _) i.val.1.val i.val.2.1 i.val.2.2 + dsimp only [outputParameter,normalizedEnergy] at H + dsimp only [m] + omega⟩⟩ + apply Finite.of_injective f + intro x y h + have H:=congrArg (fun z : T=> + (⟨⟨z.1.val,z.1.property.2⟩,z.2.val⟩ : OutputStart a c η hc)) h + exact Subtype.ext H +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +lemma euler_skew_sum (a : I → I → ℕ) (d e : I → ℕ) : + eulerForm a d e-eulerForm a e d= + ∑ i,∑ j,((a j i:ℤ)-a i j)*d i*e j := by + have H₁ : (∑ i,(d i:ℤ)*e i)=(∑ i,(e i:ℤ)*d i) := by + apply Finset.sum_congr rfl; intro i hi; ring + have H₂ : (∑ i,∑ j,(a i j:ℤ)*e i*d j)=(∑ i,∑ j,(a j i:ℤ)*d i*e j) := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl; intro i hi + apply Finset.sum_congr rfl; intro j hj + ring + simp only [eulerForm,H₁,H₂,sub_mul,Finset.sum_sub_distrib] + ring + +omit [DecidableEq I] in +lemma euler_skew_plane (a : I → I → ℕ) (c η : I → ℝ) (t : ℝ) + (ha : ∀ i j,(a j i:ℝ)-a i j=t*(η i*c j-c i*η j)) (d e : I → ℕ) : + (eulerForm a d e:ℝ)-eulerForm a e d= + t*(mass η d*mass c e-mass c d*mass η e) := by + have H:=congrArg (fun k : ℤ=>(k:ℝ)) (euler_skew_sum a d e) + push_cast at H + rw [H] + simp only [ha] + have HS (f g : I → ℝ) : (∑ i,∑ j,f i*g j)=(∑ i,f i)*(∑ j,g j) := by + rw [Finset.sum_mul] + simp only [Finset.mul_sum] + calc + _ = t*((∑ i,∑ j,(d i:ℝ)*η i*((e j:ℝ)*c j))- + ∑ i,∑ j,(d i:ℝ)*c i*((e j:ℝ)*η j)) := by + simp only [mul_sub,Finset.mul_sum,←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl; intro i hi + apply Finset.sum_congr rfl; intro j hj + ring + _ = _ := by rw [HS,HS]; rfl + +omit [DecidableEq I] in +theorem slopeEulerSymmetric_of_plane (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0Finset.sum_nonneg (fun j _=> + mul_nonneg (mul_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) (Nat.cast_nonneg _))) + +omit [DecidableEq I] in +lemma interaction_add (a : I → I → ℕ) (d e : I → ℕ) : + interaction a (d+e) (d+e) = interaction a d d + interaction a d e + + interaction a e d + interaction a e e := by + simp only [interaction,Pi.add_apply,Nat.cast_add,mul_add,add_mul,Finset.sum_add_distrib] + ring + +omit [DecidableEq I] in +lemma eulerForm_lower (a : I → I → ℕ) (d : I → ℕ) : -interaction a d d≤eulerForm a d d := by + have h : 0≤∑ i,(d i:ℤ)*d i := Finset.sum_nonneg (fun i _=>mul_self_nonneg _) + change -interaction a d d≤(∑ i,(d i:ℤ)*d i)-interaction a d d + omega + +omit [DecidableEq I] in +lemma SplitTree.doubleShift_lower (a : I → I → ℕ) (T : SplitTree I) : + -interaction a T.dim T.dim ≤ T.doubleShift a := by + induction T with + | leaf d => exact eulerForm_lower a d + | node l r ihl ihr => + change -interaction a (l.dim+r.dim) (l.dim+r.dim)≤l.doubleShift a+r.doubleShift a + rw [interaction_add] + have h1 := interaction_nonnegative a l.dim r.dim + have h2 := interaction_nonnegative a r.dim l.dim + omega + +noncomputable def dimensionEquivB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (h : d=e) : B a μ d ≃ₐ[ℚ] B a μ e := by + subst e + exact AlgEquiv.refl + +noncomputable def restrictionTest (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 (0:R)) i) p + simpa [Polynomial.coeff_zero_eq_eval_zero] using h + +lemma restrictionTest_leaf_zero (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ)) k) : + (reynoldsS d p).val.IsWeightedHomogeneous (fun _=>(1:ℤ)) k := by + change (average (packAction (fun i=>Fin (d i))) p).IsWeightedHomogeneous _ _ + rw [average_apply] + apply (weightedHomogeneousSubmodule ℚ (fun _=>(1:ℤ)) k).smul_mem + exact IsWeightedHomogeneous.sum _ _ _ (fun σ _=>constantWeight_rename _ _ hp) + +lemma separateTensor_product_any (d e : I → ℕ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + separateTensor d e (rename Sum.inl f * rename Sum.inr g) = reynoldsS d f ⊗ₜ[ℚ] reynoldsS e g := by + rw [← tensorEquivSum_tmul] + simp [separateTensor] + +lemma monomial_sumElim {α β : Type*} (x : α →₀ ℕ) (y : β →₀ ℕ) (c : ℚ) : + monomial (x.sumElim y) c = rename Sum.inl (monomial x c) * rename Sum.inr (monomial y (1:ℚ)) := by + rw [rename_monomial,rename_monomial,monomial_mul_monomial,mul_one,Finsupp.sumElim_eq_add] + +lemma totalWeight_sumElim {α β : Type*} (x : α →₀ ℕ) (y : β →₀ ℕ) : + Finsupp.weight (fun _=>(1:ℤ)) (x.sumElim y) = + Finsupp.weight (fun _=>(1:ℤ)) x + Finsupp.weight (fun _=>(1:ℤ)) y := by + simp only [Finsupp.weight_apply,Finsupp.sum_sumElim,Function.comp_def] + +lemma component_separateTensor_homogeneous (d e : I → ℕ) + (f : MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ) (k : ℤ) + (hf : f.IsWeightedHomogeneous (fun _=>(1:ℤ)) k) (m n : ℤ) (h : m+n≠k) : + TensorProduct.map (componentS d m) (componentS e n) (separateTensor d e f)=0 := by + classical + rw [← f.support_sum_monomial_coeff,map_sum,map_sum] + apply Finset.sum_eq_zero + intro u hu + let x := Finsupp.comapDomain Sum.inl u (Set.injOn_of_injective Sum.inl_injective) + let y := Finsupp.comapDomain Sum.inr u (Set.injOn_of_injective Sum.inr_injective) + have hxy : x.sumElim y=u := Finsupp.comapDomain_sumElim_comapDomain u + have hw : Finsupp.weight (fun _=>(1:ℤ)) x + Finsupp.weight (fun _=>(1:ℤ)) y=k := by + rw [← totalWeight_sumElim,hxy] + exact hf (mem_support_iff.mp hu) + rw [← hxy,monomial_sumElim,separateTensor_product_any,TensorProduct.map_tmul, + componentS_of_homogeneous _ _ (reynoldsS_homogeneous _ _ _ (isWeightedHomogeneous_monomial _ _ _ rfl)), + componentS_of_homogeneous _ _ (reynoldsS_homogeneous _ _ _ (isWeightedHomogeneous_monomial _ _ _ rfl))] + split_ifs with hm hn <;> simp_all + +lemma component_restrictTensor_homogeneous {d e : I → ℕ} (A : Cut d e) + (f : S (d+e)) (k : ℤ) (hf : f.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) k) + (m n : ℤ) (h : m+n≠k) : + TensorProduct.map (componentS d m) (componentS e n) (restrictTensor A f)=0 := by + exact component_separateTensor_homogeneous d e _ k (constantWeight_rename _ _ hf) m n h + +lemma component_quotientTensor (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d e : I → ℕ) (m n : ℤ) (f : S d ⊗[ℚ] S e) : + TensorProduct.map (componentB a μ d m) (componentB a μ e n) (quotientTensor a μ d e f)= + quotientTensor a μ d e (TensorProduct.map (componentS d m) (componentS e n) f) := by + induction f using TensorProduct.inductionOn with + | tmul f g => rfl + | add f g hf hg => simp [hf,hg] + +theorem restrictionB_graded (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 simp [valueAt] + +def mapPack (σ : ∀ i,Equiv.Perm (A i)) (s : Pack (A:=A)) : Pack (A:=A) := + fun i=>(s i).map (σ i).toEmbedding + +noncomputable def mapRealization (σ : ∀ i,Equiv.Perm (A i)) {d : I → ℕ} + {s : Pack (A:=A)} (r : Realization d s) : Realization d (mapPack σ s) := + fun i=>(r i).trans (PackEnumeration.mapEquiv (σ i).toEmbedding (s i)) + +omit [Fintype I] [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma mapRealization_map (σ : ∀ i,Equiv.Perm (A i)) {d : I → ℕ} + {s : Pack (A:=A)} (r : Realization d s) : + realizationMap (mapRealization σ r) = packAction A σ ∘ realizationMap r := rfl + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma rename_labeledPolynomial (σ : ∀ i,Equiv.Perm (A i)) {d : I → ℕ} + (f : S d) (s : Pack (A:=A)) : + rename (packAction A σ) (labeledPolynomial f s) = labeledPolynomial f (mapPack σ s) := by + by_cases h : ∀ i,(s i).card = d i + · rw [labeledPolynomial_eq (defaultRealization h), + labeledPolynomial_eq (mapRealization σ (defaultRealization h)),mapRealization_map,rename_rename] + · have hm : ¬ ∀ i,(mapPack σ s i).card = d i := by simpa [mapPack] using h + simp only [labeledPolynomial,dite_eq_right h,dite_eq_right hm,map_zero] + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma rename_sameDen (σ : ∀ i,Equiv.Perm (A i)) (s t : Pack (A:=A)) : + rename (packAction A σ) (sameDen s t) = sameDen (mapPack σ s) (mapPack σ t) := by + simp only [sameDen,mapPack,map_prod,Finset.prod_map,diagonal,map_sub,rename_X] + rfl + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma rename_arrowNum (σ : ∀ i,Equiv.Perm (A i)) (a : I → I → ℕ) (s t : Pack (A:=A)) : + rename (packAction A σ) (arrowNum a s t) = arrowNum a (mapPack σ s) (mapPack σ t) := by + simp only [arrowNum,mapPack,map_prod,map_pow,Finset.prod_map,diagonal,map_sub,rename_X] + rfl + +omit [∀ i,DecidableEq (A i)] in +lemma rename_pack_kernel (σ : ∀ i,Equiv.Perm (A i)) (a : I → I → ℕ) (s t : Pack (A:=A)) : + renameFraction (packAction A σ) (kernel (pairKernel a) s t) = + kernel (pairKernel a) (mapPack σ s) (mapPack σ t) := by + rw [kernel_polynomial_ratio,kernel_polynomial_ratio,map_div₀, + renameFraction_algebraMap,renameFraction_algebraMap,rename_sameDen,rename_arrowNum] + +noncomputable def mapPackCut (σ : ∀ i,Equiv.Perm (A i)) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) : PackConvolution.Cut (mapPack σ s) := fun i=> + ⟨((left p i).map (σ i).toEmbedding,(right p i).map (σ i).toEmbedding), + (Finset.disjoint_map _).mpr (p i).property.1,by + rw [← Finset.map_union] + change Finset.map (σ i).toEmbedding ((p i).val.1 ∪ (p i).val.2) = _ + rw [(p i).property.2] + rfl⟩ + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma mapPackCut_left (σ : ∀ i,Equiv.Perm (A i)) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) : left (mapPackCut σ p) = mapPack σ (left p) := rfl +omit [Fintype I] [DecidableEq I] in +@[simp] lemma mapPackCut_right (σ : ∀ i,Equiv.Perm (A i)) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) : right (mapPackCut σ p) = mapPack σ (right p) := rfl + +lemma rename_crossKernelPolynomial (σ : ∀ i,Equiv.Perm (A i)) (a : I → I → ℕ) + {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) : + rename (packAction A σ) (crossKernelPolynomial a p q r) = + crossKernelPolynomial a (mapPackCut σ p) (mapPackCut σ q) (mapPackCut σ r) := by + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) + rw [← renameFraction_algebraMap (packAction A σ),← crossKernelPolynomial_spec, + map_mul,map_mul,renameFraction_algebraMap,rename_sameDen, + rename_pack_kernel,rename_pack_kernel] + exact crossKernelPolynomial_spec a (mapPackCut σ p) (mapPackCut σ q) (mapPackCut σ r) + +noncomputable def gridPolynomial (a : I → I → ℕ) {d e : I → ℕ} (f : S d) (g : S e) + {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) : + MvPolynomial (Σi,A i) ℚ := + labeledPolynomial f (fun i=>left q i ∪ left r i) * + labeledPolynomial g (fun i=>right q i ∪ right r i) * crossKernelPolynomial a p q r + +omit [Fintype I] [DecidableEq I] in +lemma mapPack_union (σ : ∀ i,Equiv.Perm (A i)) (s t : Pack (A:=A)) : + mapPack σ (fun i=>s i ∪ t i) = fun i=>mapPack σ s i ∪ mapPack σ t i := by + funext i + exact Finset.map_union _ _ + +lemma rename_gridPolynomial (σ : ∀ i,Equiv.Perm (A i)) (a : I → I → ℕ) + {d e : I → ℕ} (f : S d) (g : S e) {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) : + rename (packAction A σ) (gridPolynomial a f g p q r) = + gridPolynomial a f g (mapPackCut σ p) (mapPackCut σ q) (mapPackCut σ r) := by + simp only [gridPolynomial,map_mul,rename_labeledPolynomial,rename_crossKernelPolynomial, + mapPack_union,mapPackCut_left,mapPackCut_right] + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A B : I → Type*} [∀ i,DecidableEq (A i)] [∀ i,DecidableEq (B i)] + +def packEmbedding (φ : ∀ i,A i ↪ B i) : (Σi,A i) ↪ (Σi,B i) := + Function.Embedding.sigmaMap (Function.Embedding.refl I) φ + +def embedPack (φ : ∀ i,A i ↪ B i) (s : Pack (A:=A)) : Pack (A:=B) := + fun i=>(s i).map (φ i) + +noncomputable def embedRealization (φ : ∀ i,A i ↪ B i) {d : I → ℕ} + {s : Pack (A:=A)} (r : Realization d s) : Realization d (embedPack φ s) := + fun i=>(r i).trans (PackEnumeration.mapEquiv (φ i) (s i)) + +omit [Fintype I] [DecidableEq I] [∀ i,DecidableEq (A i)] [∀ i,DecidableEq (B i)] in +lemma embedRealization_map (φ : ∀ i,A i ↪ B i) {d : I → ℕ} + {s : Pack (A:=A)} (r : Realization d s) : + realizationMap (embedRealization φ r) = packEmbedding φ ∘ realizationMap r := rfl + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] [∀ i,DecidableEq (B i)] in +lemma embed_labeledPolynomial (φ : ∀ i,A i ↪ B i) {d : I → ℕ} + (f : S d) (s : Pack (A:=A)) : + rename (packEmbedding φ) (labeledPolynomial f s) = labeledPolynomial f (embedPack φ s) := by + by_cases h : ∀ i,(s i).card = d i + · rw [labeledPolynomial_eq (defaultRealization h), + labeledPolynomial_eq (embedRealization φ (defaultRealization h)),embedRealization_map,rename_rename] + · have hm : ¬ ∀ i,(embedPack φ s i).card = d i := by simpa [embedPack] using h + simp only [labeledPolynomial,dite_eq_right h,dite_eq_right hm,map_zero] + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] [∀ i,DecidableEq (B i)] in +lemma embed_sameDen (φ : ∀ i,A i ↪ B i) (s t : Pack (A:=A)) : + rename (packEmbedding φ) (sameDen s t) = sameDen (embedPack φ s) (embedPack φ t) := by + simp only [sameDen,embedPack,map_prod,Finset.prod_map,diagonal,map_sub,rename_X] + rfl + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] [∀ i,DecidableEq (B i)] in +lemma embed_arrowNum (φ : ∀ i,A i ↪ B i) (a : I → I → ℕ) (s t : Pack (A:=A)) : + rename (packEmbedding φ) (arrowNum a s t) = arrowNum a (embedPack φ s) (embedPack φ t) := by + simp only [arrowNum,embedPack,map_prod,map_pow,Finset.prod_map,diagonal,map_sub,rename_X] + rfl + +omit [∀ i,DecidableEq (A i)] [∀ i,DecidableEq (B i)] in +lemma embed_pack_kernel (φ : ∀ i,A i ↪ B i) (a : I → I → ℕ) (s t : Pack (A:=A)) : + renameInjFraction (packEmbedding φ) (packEmbedding φ).injective (kernel (pairKernel a) s t) = + kernel (pairKernel a) (embedPack φ s) (embedPack φ t) := by + rw [kernel_polynomial_ratio,kernel_polynomial_ratio,map_div₀, + renameInjFraction_algebraMap,renameInjFraction_algebraMap,embed_sameDen,embed_arrowNum] + +noncomputable def embedPackCut (φ : ∀ i,A i ↪ B i) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) : PackConvolution.Cut (embedPack φ s) := fun i=> + ⟨((left p i).map (φ i),(right p i).map (φ i)), + (Finset.disjoint_map _).mpr (p i).property.1,by + rw [← Finset.map_union] + change Finset.map (φ i) ((p i).val.1 ∪ (p i).val.2) = _ + rw [(p i).property.2] + rfl⟩ + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma embedPackCut_left (φ : ∀ i,A i ↪ B i) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) : left (embedPackCut φ p) = embedPack φ (left p) := rfl +omit [Fintype I] [DecidableEq I] in +@[simp] lemma embedPackCut_right (φ : ∀ i,A i ↪ B i) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) : right (embedPackCut φ p) = embedPack φ (right p) := rfl + +lemma embed_crossKernelPolynomial (φ : ∀ i,A i ↪ B i) (a : I → I → ℕ) + {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) : + rename (packEmbedding φ) (crossKernelPolynomial a p q r) = + crossKernelPolynomial a (embedPackCut φ p) (embedPackCut φ q) (embedPackCut φ r) := by + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,B i) ℚ)) + rw [← renameInjFraction_algebraMap (packEmbedding φ) (packEmbedding φ).injective,← crossKernelPolynomial_spec, + map_mul,map_mul,renameInjFraction_algebraMap,embed_sameDen, + embed_pack_kernel,embed_pack_kernel] + exact crossKernelPolynomial_spec a (embedPackCut φ p) (embedPackCut φ q) (embedPackCut φ r) + +omit [Fintype I] [DecidableEq I] in +lemma embedPack_union (φ : ∀ i,A i ↪ B i) (s t : Pack (A:=A)) : + embedPack φ (fun i=>s i ∪ t i) = fun i=>embedPack φ s i ∪ embedPack φ t i := by + funext i + exact Finset.map_union _ _ + +lemma embed_gridPolynomial (φ : ∀ i,A i ↪ B i) (a : I → I → ℕ) + {d e : I → ℕ} (f : S d) (g : S e) {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) : + rename (packEmbedding φ) (gridPolynomial a f g p q r) = + gridPolynomial a f g (embedPackCut φ p) (embedPackCut φ q) (embedPackCut φ r) := by + simp only [gridPolynomial,map_mul,embed_labeledPolynomial,embed_crossKernelPolynomial, + embedPack_union,embedPackCut_left,embedPackCut_right] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentIdealCoefficients.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentIdealCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd7d5111fb0aad73183e53bda4c8a734692cf8e1 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentIdealCoefficients.lean @@ -0,0 +1,39 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +variable {R : Type*} [CommRing R] + +lemma map_quotient_eq_zero_iff (J : Ideal R) (x : LaurentSeries R) : + mapRing (Ideal.Quotient.mk J) x=0 ↔ ∀ k,x.coeff k∈J := by + constructor + · intro h k + have he:=congrArg (fun f : LaurentSeries (R⧸J)=>f.coeff k) h + simpa only [mapRing_coeff,HahnSeries.coeff_zero,Pi.zero_apply,Ideal.Quotient.eq_zero_iff_mem] using he + · intro h + apply HahnSeries.ext + funext k + simpa only [mapRing_coeff,HahnSeries.coeff_zero,Pi.zero_apply,Ideal.Quotient.eq_zero_iff_mem] using h k + +lemma coeff_mul_mem (J : Ideal R) (x y : LaurentSeries R) + (hx : ∀ k,x.coeff k∈J) (k : ℤ) : (x*y).coeff k∈J := by + apply (map_quotient_eq_zero_iff J (x*y)).mp _ k + rw [map_mul,(map_quotient_eq_zero_iff J x).mpr hx,zero_mul] + +lemma polynomial_coeff_mem (J : Ideal R) (p : Polynomial R) + (hp : ∀ n,p.coeff n∈J) (k : ℤ) : (polynomial p).coeff k∈J := by + by_cases hk : k≤0 + · obtain ⟨n,hn⟩:=Int.eq_ofNat_of_zero_le (neg_nonneg.mpr hk) + have he : k=-(n:ℤ) := by omega + rw [he,polynomial_coeff] + exact hp n + · rw [polynomial_coeff_positive p k (lt_of_not_ge hk)] + exact J.zero_mem +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentKernel.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..43965bfcd8da7e51c835496309a77b2dc7d8a233 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentKernel.lean @@ -0,0 +1,121 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.CellVars +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial HahnSeries +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.SeparatedSymmetry +open scoped TensorProduct +namespace SeparationInfinity +open ElementaryPositivity.LaurentAtInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] + +def inverseExponent (a : I → I → ℕ) (i j : I) : ℤ := + (if i=j then 1 else 0)-(a i j:ℤ) + +noncomputable def rawFactor (a : I → I → ℕ) (d e : I → ℕ) + (i j : I) (x : Fin (d i)) (y : Fin (e j)) : + (LaurentSeries (MvPolynomial (CellVars d e) ℚ))ˣ := + affineUnit (X (Sum.inr ⟨j,y⟩)-X (Sum.inl ⟨i,x⟩)) ^ inverseExponent a i j + +noncomputable def renameSeries (d e : I → ℕ) (σ : CellGroup d e) : + LaurentSeries (MvPolynomial (CellVars d e) ℚ) →+* + LaurentSeries (MvPolynomial (CellVars d e) ℚ) := + mapRing (rename (cellAction d e σ)).toRingHom + +omit [Fintype I] in +lemma rename_rawFactor (a : I → I → ℕ) (d e : I → ℕ) + (σ : CellGroup d e) (i j : I) (x : Fin (d i)) (y : Fin (e j)) : + Units.map (renameSeries d e σ).toMonoidHom (rawFactor a d e i j x y)= + rawFactor a d e i j (σ.1 i x) (σ.2 j y) := by + unfold rawFactor renameSeries + rw [map_zpow,affineUnit_map] + congr 2 + simp only [AlgHom.toRingHom_eq_coe,RingHom.coe_coe,map_sub,rename_X] + rfl + +noncomputable def rawInverseKernelUnit (a : I → I → ℕ) (d e : I → ℕ) : + (LaurentSeries (MvPolynomial (CellVars d e) ℚ))ˣ := + ∏ i, ∏ j, ∏ x : Fin (d i), ∏ y : Fin (e j), rawFactor a d e i j x y + +lemma rawInverseKernelUnit_symmetric (a : I → I → ℕ) (d e : I → ℕ) + (σ : CellGroup d e) : + Units.map (renameSeries d e σ).toMonoidHom + (rawInverseKernelUnit a d e)=rawInverseKernelUnit a d e := by + simp only [rawInverseKernelUnit,map_prod,rename_rawFactor] + apply Finset.prod_congr rfl + intro i hi + apply Finset.prod_congr rfl + intro j hj + calc + _ = ∏ x : Fin (d i), ∏ y : Fin (e j), rawFactor a d e i j (σ.1 i x) y := by + exact Finset.prod_congr rfl (fun x hx=>Equiv.prod_comp (σ.2 j) _) + _ = _ := Equiv.prod_comp (σ.1 i) (fun x : Fin (d i)=>∏ y : Fin (e j), rawFactor a d e i j x y) + +def IsSeparate (d e : I → ℕ) (f : LaurentSeries (MvPolynomial (CellVars d e) ℚ)) : Prop := + ∀ σ : CellGroup d e, renameSeries d e σ f=f + +noncomputable def separateSeries (d e : I → ℕ) : + LaurentSeries (MvPolynomial (CellVars d e) ℚ) →ₗ[ℚ] LaurentSeries (S d ⊗[ℚ] S e) := + mapLinear (separateTensor d e) + +lemma realize_separateSeries (d e : I → ℕ) + (f : LaurentSeries (MvPolynomial (CellVars d e) ℚ)) (hf : IsSeparate d e f) : + mapRing (R:=S d ⊗[ℚ] S e) (S:=MvPolynomial (CellVars d e) ℚ) (tensorValueAlg d e).toRingHom (separateSeries d e f)=f := by + apply HahnSeries.ext + funext k + apply tensorValue_separateTensor + intro σ + exact congrArg (fun p : LaurentSeries (MvPolynomial (CellVars d e) ℚ)=>p.coeff k) (hf σ) + +lemma realize_injective (d e : I → ℕ) : + Function.Injective (mapRing (R:=S d ⊗[ℚ] S e) (S:=MvPolynomial (CellVars d e) ℚ) (tensorValueAlg d e).toRingHom) := + mapRing_injective _ (tensorValue_injective d e) + +noncomputable def liftSeparateUnit (d e : I → ℕ) + (f : (LaurentSeries (MvPolynomial (CellVars d e) ℚ))ˣ) + (hf : ∀ σ : CellGroup d e, Units.map + (renameSeries d e σ).toMonoidHom f=f) : + (LaurentSeries (S d ⊗[ℚ] S e))ˣ where + val := separateSeries d e f + inv := separateSeries d e (↑f⁻¹) + val_inv := by + apply realize_injective d e + rw [map_mul,map_one,realize_separateSeries,realize_separateSeries] + · exact f.val_inv + · intro σ + exact congrArg Units.val (by simpa only [map_inv] using congrArg Inv.inv (hf σ)) + · intro σ + exact congrArg Units.val (hf σ) + inv_val := by + apply realize_injective d e + rw [map_mul,map_one,realize_separateSeries,realize_separateSeries] + · exact f.inv_val + · intro σ + exact congrArg Units.val (hf σ) + · intro σ + exact congrArg Units.val (by simpa only [map_inv] using congrArg Inv.inv (hf σ)) + +noncomputable def inverseKernelUnit (a : I → I → ℕ) (d e : I → ℕ) : + (LaurentSeries (S d ⊗[ℚ] S e))ˣ := + liftSeparateUnit d e (rawInverseKernelUnit a d e) (rawInverseKernelUnit_symmetric a d e) + +lemma realize_inverseKernelUnit (a : I → I → ℕ) (d e : I → ℕ) : + mapRing (R:=S d ⊗[ℚ] S e) (S:=MvPolynomial (CellVars d e) ℚ) (tensorValueAlg d e).toRingHom (inverseKernelUnit a d e).val=(rawInverseKernelUnit a d e).val := by + exact realize_separateSeries d e (rawInverseKernelUnit a d e).val (fun σ=> + congrArg Units.val (rawInverseKernelUnit_symmetric a d e σ)) + +noncomputable def quotientInverseKernelUnit (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + (LaurentSeries (B a μ d ⊗[ℚ] B a μ e))ˣ := + Units.map (mapRing (R:=S d ⊗[ℚ] S e) (S:=B a μ d ⊗[ℚ] B a μ e) (Algebra.TensorProduct.map (quotientAlg a μ d) + (quotientAlg a μ e)).toRingHom).toMonoidHom (inverseKernelUnit a d e) + +end SeparationInfinity +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentLeading.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentLeading.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f4caae838048931ae5649858a8df331d5d4fed8 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/LaurentLeading.lean @@ -0,0 +1,50 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Degree +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentFilteredMultiplication +import OAI.Combinatorics.Chromatic.Walls.LaurentScalarAction + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open HahnSeries +open ElementaryPositivity.LaurentAtInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma weightComponent_laurent_mul (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (W : ℤ) + (K F : LaurentSeries (tensor (quotientFamily a μ) T)) (q : LaurentSeries ℚ) + (hF : ∀ k,F.coeff k∈degreeCutSubmodule a μ T W) + (hK : mapRing (degreeZeroTensor a μ T).toRingHom K= + mapRing (algebraMap ℚ (tensor (quotientFamily a μ) T)) q) : + mapLinear (weightComponent a μ T W) (K*F)= + mapRing (algebraMap ℚ (tensor (quotientFamily a μ) T)) q* + mapLinear (weightComponent a μ T W) F := by + let Q:=mapRing (algebraMap ℚ (tensor (quotientFamily a μ) T)) q + have hpos : ∀ k,(K-Q).coeff k∈degreeCutSubmodule a μ T (T.doubleShift a+1) := by + intro k + have hh:=congrArg (fun x : LaurentSeries (tensor (quotientFamily a μ) T)=>x.coeff k) hK + change degreeZeroTensor a μ T (K.coeff k)=Q.coeff k at hh + rw [coeff_sub,←hh] + exact sub_degreeZero_mem a μ T _ + have hz : mapLinear (weightComponent a μ T W) ((K-Q)*F)=0 := by + apply HahnSeries.ext + funext k + change weightComponent a μ T W (((K-Q)*F).coeff k)=0 + apply degreeCut_weightComponent_zero + have h:=coeff_mul_mem_of_pair + (degreeCutSubmodule a μ T (T.doubleShift a+1)) (degreeCutSubmodule a μ T W) + (degreeCutSubmodule a μ T (W+1)) + (fun x hx y hy=>by + have hh:=degreeCut_mul a μ T (T.doubleShift a+1) W x y hx hy + simpa only [show T.doubleShift a+1+W-T.doubleShift a=W+1 by omega] using hh) + (K-Q) F hpos hF k + exact h + rw [sub_mul,map_sub] at hz + rw [sub_eq_zero.mp hz,mapLinear_scalar_mul] +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/LeadingIndex.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/LeadingIndex.lean new file mode 100644 index 0000000000000000000000000000000000000000..67a6c4c161d4adc413051735496e7768ac53623d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/LeadingIndex.lean @@ -0,0 +1,79 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Interaction + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +structure LeadingIndex (c η : I → ℝ) (θ : ℝ) (a : I → I → ℕ) + (d : I → ℕ) (W : ℤ) where + tree : SplitTree I + ordered : tree.IsOrderedList + onSlope : tree.OnSlope c η θ + dimension : tree.dim=d + degree : tree.Degrees + center : tree.Centers →₀ ℕ + weight : 2*tree.totalDegree degree+tree.doubleShift a=W + +noncomputable def leadingRawMap (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 (restrictionTest a c η hc θ j.tree j.onSlope j.dimension j.degree j.center).comp + (sourceFiltration a c η hc θ d W).subtype + +noncomputable def nextFiltration (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + apply (Submodule.Quotient.mk_eq_zero _).mpr + rw [← leadingRawMap_ker] + exact hf + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/ManyBlockDiagonal.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/ManyBlockDiagonal.lean new file mode 100644 index 0000000000000000000000000000000000000000..462402b48192144f659411185ffbfa300ed0d518 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/ManyBlockDiagonal.lean @@ -0,0 +1,431 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.BothTaylorB +import OAI.Combinatorics.Chromatic.Shuffle.DimensionEquivBTrans +import OAI.Combinatorics.Chromatic.Walls.HNSpanning + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +noncomputable def pairRelativeCoefficient (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 < c i) {d e : I → ℕ} + (hs : SlopeArithmetic.slope c η d = SlopeArithmetic.slope c η e) + (s : ℕ) (p q : ℤ) : + B a (SlopeArithmetic.slope c η) (d+e) →ₗ[ℚ] + B a (SlopeArithmetic.slope c η) d ⊗[ℚ] B a (SlopeArithmetic.slope c η) e := + (polynomialCoeffLinear _ s).comp (relativeLeading a c η hc hs p q) + +lemma pairRelativeCoefficient_wrong_degree (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 < c i) {d e : I → ℕ} + (hs : SlopeArithmetic.slope c η d = SlopeArithmetic.slope c η e) + (s : ℕ) (p q m : ℤ) (h : p+q ≠ m-s) + (f : B a (SlopeArithmetic.slope c η) (d+e)) : + pairRelativeCoefficient a c η hc hs s p q + (componentB a (SlopeArithmetic.slope c η) (d+e) m f) = 0 := by + exact relative_restriction_graded a c η hc hs (firstCut d e) + (componentB a (SlopeArithmetic.slope c η) (d+e) m f) m ⟨f,rfl⟩ s p q h + +namespace SplitTree + +noncomputable def pairRefinementCoefficient (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 < c i) {d e : I → ℕ} + (hs : SlopeArithmetic.slope c η d = SlopeArithmetic.slope c η e) + (T : SplitTree I) (s : ℕ) (p q : ℤ) (k : T.Degrees) : + tensor (quotientFamily a (SlopeArithmetic.slope c η)) (.node (.leaf (d+e)) T) →ₗ[ℚ] + tensor (quotientFamily a (SlopeArithmetic.slope c η)) + (.node (.node (.leaf d) (.leaf e)) T) := + TensorProduct.map (pairRelativeCoefficient a c η hc hs s p q) + (componentTensor a (SlopeArithmetic.slope c η) T k) + +theorem pairRefinementCoefficient_zero (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 < c i) (θ : ℝ) {d e : I → ℕ} + (hd : d ≠ 0) (hdθ : SlopeArithmetic.slope c η d = θ) + (heθ : SlopeArithmetic.slope c η e = θ) + (hsym : eulerForm a d e = eulerForm a e d) + (T : SplitTree I) (hT : T.OnSlope c η θ) + (p q W : ℤ) (k : T.Degrees) + (hw : 2*(p+q+T.totalDegree k)+eulerForm a d d+eulerForm a e e+T.doubleShift a = W) + (f : B a (SlopeArithmetic.slope c η) ((d+e)+T.dim)) + (hf : f ∈ sourceFiltration a c η hc θ ((d+e)+T.dim) W) + (z : (SplitTree.node (.leaf (d+e)) T).Centers →₀ ℕ) + (s : ℕ) (hs : s < (-eulerForm a d e).toNat) : + pairRefinementCoefficient a c η hc (hdθ.trans heθ.symm) T s p q k + ((centeredRestrictionB a c η hc θ (.node (.leaf (d+e)) T) + ⟨⟨SlopeArithmetic.add_ne_zero_left d e hd, + (SlopeArithmetic.slope_add_same c η hc (hdθ.trans heθ.symm)).trans hdθ⟩,hT⟩ f).coeff z) = 0 := by + classical + let μ := SlopeArithmetic.slope c η + let U : SplitTree I := .node (.leaf (d+e)) T + have hU : U.OnSlope c η θ := + ⟨⟨SlopeArithmetic.add_ne_zero_left d e hd, + (SlopeArithmetic.slope_add_same c η hc (hdθ.trans heθ.symm)).trans hdθ⟩,hT⟩ + let x : tensor (quotientFamily a μ) U := (centeredRestrictionB a c η hc θ U hU f).coeff z + let F := pairRefinementCoefficient a c η hc (hdθ.trans heθ.symm) T s p q k + change F x = 0 + obtain ⟨t,ht,heq⟩ := componentTensor_finite_decomposition a μ U x + have hterm : ∀ j ∈ t, F (componentTensor a μ U j x) = 0 := by + intro j hj + by_cases hk : k = j.2 + · subst k + by_cases hm : p+q = j.1-s + · have hsmall : 2*U.totalDegree j+U.doubleShift a < W := by + change 2*(j.1+T.totalDegree j.2)+(eulerForm a (d+e) (d+e)+T.doubleShift a) < W + rw [eulerForm_add_left,eulerForm_add_right,eulerForm_add_right,← hsym] + have hs' : (s : ℤ) < -eulerForm a d e := Int.lt_toNat.mp hs + linarith only [hs', hm, hw] + have hz := sourceFiltration_allTrees a c η hc θ W f hf U hU rfl j z hsmall + change componentTensor a μ U j x = 0 at hz + rw [hz,map_zero] + · generalize x = y + induction y using TensorProduct.inductionOn with + | tmul g h => + change pairRelativeCoefficient a c η hc (hdθ.trans heθ.symm) s p q + (componentB a μ (d+e) j.1 g) ⊗ₜ[ℚ] + componentTensor a μ T j.2 (componentTensor a μ T j.2 h) = 0 + change B a μ (d+e) at g + rw [pairRelativeCoefficient_wrong_degree a c η hc (d := d) (e := e) (hdθ.trans heθ.symm) s p q j.1 hm, TensorProduct.zero_tmul] + | add y y' hy hy' => simp only [map_add,hy,hy',add_zero] + · generalize x = y + induction y using TensorProduct.inductionOn with + | tmul g h => + change pairRelativeCoefficient a c η hc (hdθ.trans heθ.symm) s p q + (componentB a μ (d+e) j.1 g) ⊗ₜ[ℚ] + componentTensor a μ T k (componentTensor a μ T j.2 h) = 0 + rw [componentTensor_componentTensor,ite_eq_right hk,TensorProduct.tmul_zero] + | add y y' hy hy' => simp only [map_add,hy,hy',add_zero] + calc + F x = F (∑ j ∈ t, componentTensor a μ U j x) := congrArg F heq.symm + _ = 0 := by rw [map_sum]; exact Finset.sum_eq_zero hterm + +end SplitTree +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.CenterCalculus +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma evalRat_extendPolynomial {A D α β : Type*} [CommRing A] [CommRing D] + [Algebra ℚ A] [Algebra ℚ D] (f : A →ₐ[ℚ] D) (j : α → β) + (p : MvPolynomial α A) (v : β → ℚ) : + evalRat v (extendPolynomial f j p) = f (evalRat (v ∘ j) p) := by + induction p using MvPolynomial.induction_on with + | C a => simp [extendPolynomial] + | add p q hp hq => simp only [map_add,hp,hq] + | mul_X p i hp => + simp only [map_mul,hp] + congr 1 + simp [extendPolynomial,evalRat] + +lemma evalRat_toMvPolynomial {A α : Type*} [CommRing A] [Algebra ℚ A] + (i : α) (p : Polynomial A) (v : α → ℚ) : + evalRat v (Polynomial.toMvPolynomial i p) = p.eval (algebraMap ℚ A (v i)) := by + induction p using Polynomial.induction_on' with + | add p q hp hq => simp only [map_add,Polynomial.eval_add,hp,hq] + | monomial n a => simp [← Polynomial.C_mul_X_pow_eq_monomial] + +lemma evalRat_mapAlgHom {A D α : Type*} [CommRing A] [CommRing D] + [Algebra ℚ A] [Algebra ℚ D] (f : A →ₐ[ℚ] D) + (p : MvPolynomial α A) (v : α → ℚ) : + evalRat v (map f.toRingHom p) = f (evalRat v p) := by + have he : map f.toRingHom p = mapLinear f.toLinearMap p := by ext s; simp only [coeff_map,coeff_mapLinear,AlgHom.toLinearMap_apply]; rfl + rw [he,evalRat_mapLinear] + rfl + +noncomputable def translationAtB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) : + (T : SplitTree I) → (T.Centers → ℚ) → + tensor (quotientFamily a μ) T →ₗ[ℚ] tensor (quotientFamily a μ) T + | .leaf d, v => translationB a μ d (v ()) + | .node l r, v => TensorProduct.map + (translationAtB a μ l (v ∘ Sum.inl)) (translationAtB a μ r (v ∘ Sum.inr)) + +lemma centerTranslation_evalRat (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (x : tensor (quotientFamily a μ) T) (v : T.Centers → ℚ) : + evalRat v (centerTranslation (quotientFamily a μ) (taylorB a μ) T x) = + translationAtB a μ T v x := by + induction T with + | leaf d => + change B a μ d at x + change evalRat v (Polynomial.toMvPolynomial () (taylorB a μ d x)) = _ + rw [evalRat_toMvPolynomial,taylorB_eval] + rfl + | node l r ihl ihr => + induction x using TensorProduct.inductionOn with + | tmul x y => + erw [centerTranslation_tmul,map_mul,evalRat_extendPolynomial,evalRat_extendPolynomial,ihl,ihr] + change (translationAtB a μ l (v ∘ Sum.inl) x ⊗ₜ[ℚ] 1) * + (1 ⊗ₜ[ℚ] translationAtB a μ r (v ∘ Sum.inr) y) = _ + rw [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + rfl + | add x y hx hy => simp only [map_add,hx,hy] + +noncomputable def polynomialOnLeft {A D Q : Type*} [CommRing A] [CommRing D] + [CommRing Q] [Algebra ℚ A] [Algebra ℚ D] [Algebra ℚ Q] + (f : A →ₐ[ℚ] Polynomial D) : A ⊗[ℚ] Q →ₐ[ℚ] Polynomial (D ⊗[ℚ] Q) := + let L : A →ₐ[ℚ] Polynomial (D ⊗[ℚ] Q) := + (Polynomial.mapAlgHom (Algebra.TensorProduct.includeLeft : D →ₐ[ℚ] D ⊗[ℚ] Q)).comp f + let R : Q →ₐ[ℚ] Polynomial (D ⊗[ℚ] Q) := + (Polynomial.CAlgHom : D ⊗[ℚ] Q →ₐ[ℚ] Polynomial (D ⊗[ℚ] Q)).comp + Algebra.TensorProduct.includeRight + Algebra.TensorProduct.lift (S:=ℚ) L R (fun x y => mul_comm (L x) (R y)) + +lemma polynomialOnLeft_eval_tmul {A D Q : Type*} [CommRing A] [CommRing D] + [CommRing Q] [Algebra ℚ A] [Algebra ℚ D] [Algebra ℚ Q] + (f : A →ₐ[ℚ] Polynomial D) (g : A) (h : Q) (t : ℚ) : + (polynomialOnLeft f (g ⊗ₜ[ℚ] h)).eval (algebraMap ℚ _ t) = + (f g).eval (algebraMap ℚ D t) ⊗ₜ[ℚ] h := by + change (Polynomial.map (Algebra.TensorProduct.includeLeft : D →ₐ[ℚ] D ⊗[ℚ] Q).toRingHom + (f g) * Polynomial.C + ((Algebra.TensorProduct.includeRight : Q →ₐ[ℚ] D ⊗[ℚ] Q) h)).eval _ = _ + rw [Polynomial.eval_mul,eval_map_rat,Polynomial.eval_C] + change (_ ⊗ₜ[ℚ] 1) * (1 ⊗ₜ[ℚ] h) = _ + rw [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + +lemma polynomialOnLeft_coeff_tmul {A D Q : Type*} [CommRing A] [CommRing D] + [CommRing Q] [Algebra ℚ A] [Algebra ℚ D] [Algebra ℚ Q] + (f : A →ₐ[ℚ] Polynomial D) (g : A) (h : Q) (s : ℕ) : + (polynomialOnLeft f (g ⊗ₜ[ℚ] h)).coeff s = (f g).coeff s ⊗ₜ[ℚ] h := by + change (Polynomial.map (Algebra.TensorProduct.includeLeft : D →ₐ[ℚ] D ⊗[ℚ] Q).toRingHom + (f g) * Polynomial.C + ((Algebra.TensorProduct.includeRight : Q →ₐ[ℚ] D ⊗[ℚ] Q) h)).coeff s = _ + rw [Polynomial.coeff_mul_C,Polynomial.coeff_map] + change (_ ⊗ₜ[ℚ] 1) * (1 ⊗ₜ[ℚ] h) = _ + rw [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + +noncomputable def pairRelativeRefinement (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 + let μ := SlopeArithmetic.slope c η + change translationAtB a μ (.node (.node (.leaf d) (.leaf e)) T) (relativePoint t v) + ((RawShuffle.restrictionB a c η hc hs (firstCut d e) g) ⊗ₜ[ℚ] h) = + (pairRelativeRefinement a c η hc hs T + (translationB a μ (d+e) (v (Sum.inl ())) g ⊗ₜ[ℚ] + translationAtB a μ T (v ∘ Sum.inr) h)).eval _ + erw [pairRelativeRefinement_eval_tmul a c η hc hs T, + restrictionB_translation a c η hc hs (firstCut d e)] + change TensorProduct.map (translationB a μ d (t+v (Sum.inl ()))) + (translationB a μ e (v (Sum.inl ()))) + (RawShuffle.restrictionB a c η hc hs (firstCut d e) g) ⊗ₜ[ℚ] + translationAtB a μ T (v ∘ Sum.inr) h = _ + congr 1 + generalize RawShuffle.restrictionB a c η hc hs (firstCut d e) g = y + induction y using TensorProduct.inductionOn with + | tmul f h => + simp only [TensorProduct.map_tmul,LinearMap.id_apply,translationB_add] + rfl + | add y y' hy hy' => simp only [map_add,hy,hy'] + | add x y hx hy => + erw [map_add,map_add,map_add,map_add,Polynomial.eval_add] + exact congrArg₂ (· + ·) hx hy + +lemma pairRefinement_centerTranslation (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 p.eval (algebraMap ℚ _ t)) + (evalRat_mapAlgHom F (centerTranslation (quotientFamily a μ) (taylorB a μ) U x) v).symm + +lemma toRelative_mapLinear {A D α : Type*} [CommRing A] [CommRing D] + [Algebra ℚ A] [Algebra ℚ D] (l : A →ₗ[ℚ] D) + (p : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A) : + toRelative (mapLinear l p) = mapLinear (polynomialMapLinear l) (toRelative p) := by + apply eq_of_evalRat + intro v + apply polynomial_eq_of_rat_evals + intro t + rw [evalRat_toRelative,evalRat_mapLinear,evalRat_mapLinear, + polynomialMapLinear_eval_rat,evalRat_toRelative] + +lemma pairRelativeRefinement_component_coeff (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 + erw [pairRelativeRefinement,polynomialOnLeft_coeff_tmul] + rfl + | add x y hx hy => simp only [map_add,Polynomial.coeff_add,hx,hy] + +lemma restrictionB_two (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 + change restrictionB a c η hc θ (.node (.leaf d) (.leaf e)) ⟨hd,he⟩ g ⊗ₜ[ℚ] + restrictionB a c η hc θ T hT h = _ + rw [restrictionB_two a c η hc θ hd he] + rfl + | add x y hx hy => simp only [map_add,hx,hy]; rfl + +end ElementaryPositivity.RawShuffle.SplitTree + +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.CenterCalculus +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma centeredRestrictionB_pairRefinement (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0componentTensor a μ T k x) (by + obtain ⟨s,hs,_⟩ := componentTensor_finite_decomposition a μ T x + apply s.finite_toSet.subset + intro k hk + by_contra hn + exact hk (hs k hn)) + map_add' x y := by + ext k + change componentTensor a μ T k (x+y)=componentTensor a μ T k x+componentTensor a μ T k y + exact map_add _ x y + map_smul' r x := by + ext k + change componentTensor a μ T k (r • x)=r • componentTensor a μ T k x + exact map_smul _ r x + +@[simp] lemma componentFinsupp_apply (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (x : tensor (quotientFamily a μ) T) (k : T.Degrees) : + componentFinsupp a μ T x k = componentTensor a μ T k x := rfl + +lemma componentTensor_sum (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (x : tensor (quotientFamily a μ) T) (s : Finset T.Degrees) + (hs : ∀ k∉s, componentTensor a μ T k x=0) : + (∑ k∈s,componentTensor a μ T k x)=x := by + classical + apply sub_eq_zero.mp + apply componentTensor_detect a μ T + intro k + rw [map_sub,map_sum] + simp only [componentTensor_componentTensor] + by_cases hk : k∈s + · rw [Finset.sum_eq_single k] + · simp + · intro j hj hne + simp [Ne.symm hne] + · exact fun h=>False.elim (h hk) + · simp only [hs k hk] + rw [sub_zero] + apply Finset.sum_eq_zero + intro j hj + have hne : k≠j := fun h=>hk (h ▸ hj) + simp [hne] + +noncomputable def weightComponent (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (W : ℤ) : + tensor (quotientFamily a μ) T →ₗ[ℚ] tensor (quotientFamily a μ) T := by + classical + exact (Finsupp.lsum ℚ (fun k : T.Degrees=> + if 2*T.totalDegree k+T.doubleShift a=W then LinearMap.id else 0)).comp + (componentFinsupp a μ T) + +lemma weightComponent_eq_sum (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (W : ℤ) (x : tensor (quotientFamily a μ) T) (s : Finset T.Degrees) + (hs : ∀ k∉s, componentTensor a μ T k x=0) : + weightComponent a μ T W x = ∑ k∈s, + if 2*T.totalDegree k+T.doubleShift a=W then componentTensor a μ T k x else 0 := by + classical + unfold weightComponent + rw [LinearMap.comp_apply,Finsupp.lsum_apply] + have hsub : (componentFinsupp a μ T x).support ⊆ s := by + intro k hk + by_contra hn + exact (Finsupp.mem_support_iff.mp hk) (hs k hn) + rw [Finsupp.sum_of_support_subset _ hsub _ (by intro k hk; split_ifs <;> simp)] + apply Finset.sum_congr rfl + intro k hk + split_ifs <;> rfl + +lemma componentTensor_weightComponent (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (W : ℤ) (x : tensor (quotientFamily a μ) T) (k : T.Degrees) : + componentTensor a μ T k (weightComponent a μ T W x) = + if 2*T.totalDegree k+T.doubleShift a=W then componentTensor a μ T k x else 0 := by + classical + obtain ⟨s,hs,he⟩ := componentTensor_finite_decomposition a μ T x + rw [weightComponent_eq_sum a μ T W x s hs,map_sum] + simp only [apply_ite,componentTensor_componentTensor,map_zero] + by_cases hk : k∈s + · rw [Finset.sum_eq_single k] + · by_cases hw : 2*T.totalDegree k+T.doubleShift a=W <;> simp [hw] + · intro j hj hne + simp [Ne.symm hne] + · exact fun h=>False.elim (h hk) + · rw [hs k hk] + simp only [ite_self] + apply Finset.sum_eq_zero + intro j hj + have hne : k≠j := fun h=>hk (h ▸ hj) + simp [hne] + +lemma polynomial_component_finite (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (p : MvPolynomial T.Centers (tensor (quotientFamily a μ) T)) : + ∃ s : Finset T.Degrees, ∀ k∉s, mapLinear (componentTensor a μ T k) p=0 := by + classical + let s := p.support.biUnion (fun z=>(componentFinsupp a μ T (p.coeff z)).support) + refine ⟨s,?_⟩ + intro k hk + ext z + simp only [coeff_mapLinear,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply] + by_cases hz : z∈p.support + · have hnot : k∉(componentFinsupp a μ T (p.coeff z)).support := fun h=> + hk (Finset.mem_biUnion.mpr ⟨z,hz,h⟩) + exact Finsupp.notMem_support_iff.mp hnot + · rw [notMem_support_iff.mp hz,map_zero] + +lemma mapLinear_weightComponent_eq_sum (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (W : ℤ) (p : MvPolynomial T.Centers (tensor (quotientFamily a μ) T)) + (s : Finset T.Degrees) (hs : ∀ k∉s, mapLinear (componentTensor a μ T k) p=0) : + mapLinear (weightComponent a μ T W) p = ∑ k∈s, + if 2*T.totalDegree k+T.doubleShift a=W then mapLinear (componentTensor a μ T k) p else 0 := by + classical + ext z + simp only [coeff_mapLinear,coeff_sum,apply_ite,AddMonoidAlgebra.coeff_zero, + DFunLike.ite_apply,Finsupp.zero_apply] + apply weightComponent_eq_sum + intro k hk + have h := congrArg (fun polynomial => AddMonoidAlgebra.coeff polynomial z) (hs k hk) + simpa only [coeff_mapLinear,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply] using h + +noncomputable def totalLeadingPolynomial (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0centerDenominator_ne_zero a L ((rename_eq_zero_iff_of_injective _ Sum.inl_injective).mp h) + · exact fun h=>centerDenominator_ne_zero a R ((rename_eq_zero_iff_of_injective _ Sum.inr_injective).mp h) + +noncomputable def tensorClearedLeading (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0centerNumerator_ne_zero a L ((rename_eq_zero_iff_of_injective _ Sum.inl_injective).mp h) + · exact fun h=>centerNumerator_ne_zero a R ((rename_eq_zero_iff_of_injective _ Sum.inr_injective).mp h) + +lemma normalizedTensorSymbol_tmul (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0componentTensor a (SlopeArithmetic.slope c η) (.node L R) (k,l) + (AddMonoidAlgebra.coeff p (z.sumElim w))) hp + have heq : 2*(L.totalDegree k+R.totalDegree l)+(L.doubleShift a+R.doubleShift a)=W := by + change (2*L.totalDegree k+L.doubleShift a)+(2*R.totalDegree l+R.doubleShift a)=W at hw + omega + rw [coeff_mapLinear,componentTensor_weightComponent,ite_eq_left heq, + AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply,map_zero, + refinedCenterPolynomial_coeff_test] at ht + exact ht + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/NormalizedTripleSymbol.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/NormalizedTripleSymbol.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ca4c0d2ea1a4af2e5270105847bbb0f7de80faa --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/NormalizedTripleSymbol.lean @@ -0,0 +1,197 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TripleSymbols + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial ElementaryPositivity.CenterCalculus ElementaryPositivity.ShufflePolynomiality +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def tripleClearedLeading (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + obtain ⟨U,V,x,y,hUV,hx,hy,rfl⟩:=hx + have hy' := sourceFiltration_antitone a c η hc θ N.dim (show W-U≤V by omega) hy + rw [refinedTripleCenterPolynomial_tmul,←Finsupp.comapDomain_sumElim_comapDomain z,coeff_box] + have he : W=U+(W-U) := by omega + rw [he] + exact degreeCut_node_tmul a _ (.node L M) N U (W-U) _ _ + (refinedCenterPolynomial_coeff_degreeCut a c η hc θ L M hL hM U x hx _) + (centeredRestrictionB_coeff_degreeCut a c η hc θ N hN (W-U) y hy' _) + | zero => + rw [LinearMap.map_zero,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply] + exact (degreeCutSubmodule a (SlopeArithmetic.slope c η) ((L.node M).node N) W).zero_mem + | add x y hx hy ihx ihy => + rw [LinearMap.map_add,AddMonoidAlgebra.coeff_add,Finsupp.add_apply] + exact (degreeCutSubmodule a (SlopeArithmetic.slope c η) ((L.node M).node N) W).add_mem ihx ihy + | smul r x hx ih => + rw [LinearMap.map_smul,coeff_smul] + exact (degreeCutSubmodule a (SlopeArithmetic.slope c η) ((L.node M).node N) W).smul_mem r ih + +lemma normalizedTripleSymbol_next_zero (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0componentTensor a (SlopeArithmetic.slope c η) ((L.node M).node N) ((k,l),m) + (AddMonoidAlgebra.coeff p ((z.sumElim w).sumElim t))) hp + have heq : 2*((L.totalDegree k+M.totalDegree l)+N.totalDegree m)+ + ((L.doubleShift a+M.doubleShift a)+N.doubleShift a)=W := by + change (2*L.totalDegree k+L.doubleShift a)+(2*M.totalDegree l+M.doubleShift a)+ + (2*N.totalDegree m+N.doubleShift a)=W at hw + omega + rw [coeff_mapLinear,componentTensor_weightComponent,ite_eq_left heq, + AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply,LinearMap.map_zero, + refinedTripleCenterPolynomial_coeff_test] at ht + exact ht + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/OriginalDegree.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/OriginalDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..4dbec7a17494b7d2a6053ac38fa776818752321d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/OriginalDegree.lean @@ -0,0 +1,183 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiltrationHomogeneousRank +import OAI.Combinatorics.Chromatic.Shuffle.PrimitiveSpace +import OAI.Combinatorics.Chromatic.Walls.LinearFiltrationFinite + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma properSourceFiltration_component_mem (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0sourceFiltration_component_mem a c η hc θ d W ℓ f hf) + (fun f hf=>sourceFiltration_component_mem a c η hc θ d (W+1) ℓ f hf) + +lemma associatedComponent_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + simp only [associatedComponent_mk] + split_ifs with h + · apply congrArg Submodule.Quotient.mk + apply Subtype.ext + exact (componentB_componentB a _ d ℓ m f.val).trans (ite_eq_left h) + · rw [show (0 : SourceAssociatedGrade a c η hc θ d W)=Submodule.Quotient.mk 0 from rfl] + apply congrArg Submodule.Quotient.mk + apply Subtype.ext + exact (componentB_componentB a _ d ℓ m f.val).trans (ite_eq_right h) + +lemma associatedComponent_finite (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + obtain ⟨s,hs,he⟩:=componentB_finite_decomposition a (SlopeArithmetic.slope c η) d f.val + refine ⟨s,?_,?_⟩ + · intro ℓ hℓ + rw [associatedComponent_mk] + apply (Submodule.Quotient.mk_eq_zero _).mpr + change componentB a _ d ℓ f.val∈sourceFiltration a c η hc θ d (W+1) + rw [hs ℓ hℓ] + exact Submodule.zero_mem _ + · let g : ℤ → sourceFiltration a c η hc θ d W := fun ℓ=> + ⟨componentB a (SlopeArithmetic.slope c η) d ℓ f.val, + sourceFiltration_component_mem a c η hc θ d W ℓ f.val f.property⟩ + change (∑ ℓ∈s,(nextFiltration a c η hc θ d W).mkQ (g ℓ))=_ + rw [←map_sum] + apply congrArg (nextFiltration a c η hc θ d W).mkQ + apply Subtype.ext + simpa only [Submodule.coe_sum] using he + +lemma associatedComponent_primitive (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + rw [associatedComponent_mk] + apply (primitiveSpace_mk_iff a c η hc θ hχ d W _).mpr + exact properSourceFiltration_component_mem a c η hc θ d (W+1) ℓ f.val + ((primitiveSpace_mk_iff a c η hc θ hχ d W f).mp hf) + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + arg 2 + ext j + rw [associatedComponent_rank_eq] + exact finiteFiltration_rank_total (originalFilteredPiece a c η hc θ d k) + (originalFilteredPiece_antitone a c η hc θ d k) (-interaction a d d) n + (originalFilteredPiece_lower a c η hc θ d k) + (originalFilteredPiece_upper a c η hc θ d hd hs k _ hn) +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/PackExponentSorting.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/PackExponentSorting.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b2fe9d3ae0d0add80e1bfaf8ccdab6cb540b562 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/PackExponentSorting.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Diagonal + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.ShufflePolynomiality +variable {I : Type*} [Fintype I] +attribute [local instance] Classical.propDecidable + +abbrev PackExponent (d : I → ℕ) := (Σ i,Fin (d i)) →₀ ℕ +abbrev SortedPackExponent (d : I → ℕ) := ∀ i,{f : Fin (d i) → ℕ // Monotone f} + +def sortPackExponent (d : I → ℕ) (m : PackExponent d) : SortedPackExponent d := + fun i=>⟨(fun j=>m ⟨i,j⟩) ∘ Tuple.sort (fun j=>m ⟨i,j⟩),Tuple.monotone_sort _⟩ + +noncomputable def sortedPackRepresentative (d : I → ℕ) (k : SortedPackExponent d) : PackExponent d := + Finsupp.equivFunOnFinite.symm (fun ij=> (k ij.1).val ij.2) + +lemma sortPack_representative (d : I → ℕ) (k : SortedPackExponent d) : + sortPackExponent d (sortedPackRepresentative d k)=k := by + funext i + apply Subtype.ext + exact Tuple.unique_monotone (Tuple.monotone_sort (k i).val) (show Monotone ((k i).val ∘ Equiv.refl _) from (k i).property) + +lemma tuple_sorted_comp_perm {n : ℕ} (f : Fin n → ℕ) (σ : Equiv.Perm (Fin n)) : + (f ∘ σ) ∘ Tuple.sort (f ∘ σ)=f ∘ Tuple.sort f := by + exact Tuple.unique_monotone (σ:= (Tuple.sort (f ∘ σ)).trans σ) + (Tuple.monotone_sort (f ∘ σ)) (Tuple.monotone_sort f) + +omit [Fintype I] in +lemma packExponent_permute_apply (d : I → ℕ) (g : ∀ i,Equiv.Perm (Fin (d i))) + (m : PackExponent d) (i : I) (j : Fin (d i)) : + m.mapDomain (packAction (fun i=>Fin (d i)) g) ⟨i,j⟩=m ⟨i,(g i).symm j⟩ := by + rw [Finsupp.mapDomain_equiv_apply] + rfl + +omit [Fintype I] in +lemma sortPack_permute (d : I → ℕ) (g : ∀ i,Equiv.Perm (Fin (d i))) (m : PackExponent d) : + sortPackExponent d (m.mapDomain (packAction (fun i=>Fin (d i)) g))=sortPackExponent d m := by + funext i + apply Subtype.ext + change ((fun j=>m.mapDomain (packAction (fun i=>Fin (d i)) g) ⟨i,j⟩) ∘ Tuple.sort _) = _ + simp only [packExponent_permute_apply] + exact tuple_sorted_comp_perm (fun j=>m ⟨i,j⟩) (g i).symm + +lemma packExponent_of_sorted (d : I → ℕ) (m : PackExponent d) : + (sortedPackRepresentative d (sortPackExponent d m)).mapDomain + (packAction (fun i=>Fin (d i)) (fun i=>Tuple.sort (fun j=>m ⟨i,j⟩)))=m := by + ext ⟨i,j⟩ + rw [packExponent_permute_apply] + change m ⟨i,Tuple.sort (fun j=>m ⟨i,j⟩) ((Tuple.sort (fun j=>m ⟨i,j⟩)).symm j)⟩=_ + rw [Equiv.apply_symm_apply] + +lemma sortPack_fibre_finite (d : I → ℕ) (k : SortedPackExponent d) : + Set.Finite {m : PackExponent d | sortPackExponent d m=k} := by + apply (Set.finite_range (fun g : ∀ i,Equiv.Perm (Fin (d i))=> + (sortedPackRepresentative d k).mapDomain (packAction (fun i=>Fin (d i)) g))).subset + intro m hm + refine ⟨fun i=>Tuple.sort (fun j=>m ⟨i,j⟩),?_⟩ + rw [←hm] + exact packExponent_of_sorted d m + +omit [Fintype I] in +lemma packExponent_permute_inverse (d : I → ℕ) (g : ∀ i,Equiv.Perm (Fin (d i))) (m : PackExponent d) : + (m.mapDomain (packAction (fun i=>Fin (d i)) (fun i=>(g i).symm))).mapDomain + (packAction (fun i=>Fin (d i)) g)=m := by + ext ⟨i,j⟩ + simp only [packExponent_permute_apply,Equiv.symm_symm,Equiv.apply_symm_apply] +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/PackOrbitBasis.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/PackOrbitBasis.lean new file mode 100644 index 0000000000000000000000000000000000000000..d786fd9840c2bc9f2ea13824ab959ca39ae4cbcf --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/PackOrbitBasis.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GradeBInternal +import OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousBasisFibre +import OAI.Combinatorics.Chromatic.Shuffle.PackExponentSorting +import OAI.Combinatorics.Chromatic.Walls.FiniteFibreFinsupp + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.ShufflePolynomiality +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [Fintype I] [DecidableEq I] in +lemma packSymmetric_coeff_permute (d : I → ℕ) (f : S d) + (g : ∀ i,Equiv.Perm (Fin (d i))) (m : PackExponent d) : + f.val.coeff (m.mapDomain (packAction (fun i=>Fin (d i)) g))=f.val.coeff m := by + have H:=coeff_rename_mapDomain _ (packAction (fun i=>Fin (d i)) g).injective f.val m + rw [f.property g] at H + exact H + +omit [DecidableEq I] in +lemma packSymmetric_coeff_sorted (d : I → ℕ) (f : S d) (m : PackExponent d) : + f.val.coeff m=f.val.coeff (sortedPackRepresentative d (sortPackExponent d m)) := by + have h:=packSymmetric_coeff_permute d f (fun i=>Tuple.sort (fun j=>m ⟨i,j⟩)) + (sortedPackRepresentative d (sortPackExponent d m)) + rwa [packExponent_of_sorted] at h + +omit [DecidableEq I] in +lemma packSymmetric_iff_fibre (d : I → ℕ) (f : MvPolynomial (Σ i,Fin (d i)) ℚ) : + PackSymmetric d f ↔ AddMonoidAlgebra.coeff f∈fibreConstant (sortPackExponent d) := by + constructor + · intro hf m n h + change f.coeff m=f.coeff n + rw [packSymmetric_coeff_sorted d ⟨f,hf⟩ m,packSymmetric_coeff_sorted d ⟨f,hf⟩ n,h] + · intro hf g + ext m + have H:=coeff_rename_mapDomain (packAction (fun i=>Fin (d i)) g) + (packAction (fun i=>Fin (d i)) g).injective f + (m.mapDomain (packAction (fun i=>Fin (d i)) (fun i=>(g i).symm))) + rw [packExponent_permute_inverse] at H + exact H.trans (hf _ _ (sortPack_permute d _ m)) + +noncomputable def packFibreEquiv (d : I → ℕ) : + fibreConstant (sortPackExponent d) ≃ₗ[ℚ] S d where + toFun f := ⟨AddMonoidAlgebra.ofCoeff f.val,(packSymmetric_iff_fibre d (AddMonoidAlgebra.ofCoeff f.val)).mpr f.property⟩ + invFun f := ⟨AddMonoidAlgebra.coeff f.val,(packSymmetric_iff_fibre d f.val).mp f.property⟩ + left_inv _ := rfl + right_inv _ := rfl + map_add' _ _ := rfl + map_smul' _ _ := rfl + +noncomputable def packOrbitBasis (d : I → ℕ) : Module.Basis (SortedPackExponent d) ℚ (S d) := + (fibreConstantBasis (sortPackExponent d) (sortPack_fibre_finite d) + (sortedPackRepresentative d) (sortPack_representative d)).map (packFibreEquiv d) + +omit [DecidableEq I] in +lemma packOrbitBasis_coeff (d : I → ℕ) (k : SortedPackExponent d) (m : PackExponent d) : + (packOrbitBasis d k).val.coeff m=if sortPackExponent d m=k then 1 else 0 := by + have H:=fibreConstantBasis_apply (sortPackExponent d) (sortPack_fibre_finite d) + (sortedPackRepresentative d) (sortPack_representative d) k m + by_cases h : sortPackExponent d m=k + · simp only [ite_eq_left h] at H ⊢; exact H + · simp only [ite_eq_right h] at H ⊢; exact H + +noncomputable def sortedPackDegree (d : I → ℕ) (k : SortedPackExponent d) : ℕ := + ∑ i,∑ j,(k i).val j + +omit [DecidableEq I] in +lemma packExponent_degree_sort (d : I → ℕ) (m : PackExponent d) : + sortedPackDegree d (sortPackExponent d m)=m.sum (fun _ n=>n) := by + unfold sortedPackDegree sortPackExponent + simp only [Function.comp_apply] + calc + _ = ∑ i,∑ j,m ⟨i,j⟩ := Finset.sum_congr rfl (fun i _=> Equiv.sum_comp (Tuple.sort (fun j=>m ⟨i,j⟩)) (fun j=>m ⟨i,j⟩)) + _ = ∑ ij,m ij := (Fintype.sum_sigma _).symm + _ = _ := (m.sum_fintype (fun _ n=>n) (fun _=>rfl)).symm + +omit [DecidableEq I] in +lemma packOrbitBasis_homogeneous (d : I → ℕ) (k : SortedPackExponent d) : + (packOrbitBasis d k).val.IsWeightedHomogeneous (fun _=>(1:ℤ)) (sortedPackDegree d k) := by + intro m hm + have h : sortPackExponent d m=k := by + by_contra h + rw [packOrbitBasis_coeff,ite_eq_right h] at hm + exact hm rfl + rw [←h,packExponent_degree_sort] + simp [Finsupp.weight_apply,Finsupp.sum] + +omit [DecidableEq I] in +lemma packOrbitBasis_component (d : I → ℕ) (ℓ : ℤ) (k : SortedPackExponent d) : + componentS d ℓ (packOrbitBasis d k)= + if (sortedPackDegree d k : ℤ)=ℓ then packOrbitBasis d k else 0 := by + rw [componentS_of_homogeneous d _ (packOrbitBasis_homogeneous d k)] + simp only [eq_comm] + +omit [DecidableEq I] in +theorem packHilbert_coefficient (d : I → ℕ) (ℓ : ℤ) : + Module.finrank ℚ (LinearMap.range (componentS d ℓ))= + Nat.card {k : SortedPackExponent d // (sortedPackDegree d k : ℤ)=ℓ} := by + let := componentS_range_finite d ℓ + exact ElementaryPositivity.homogeneousBasis_finrank (packOrbitBasis d) _ _ + (packOrbitBasis_component d) ℓ +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/PackSplit.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/PackSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..119690f500dcf3dbfc05d46f08052b9d9e388ce6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/PackSplit.lean @@ -0,0 +1,270 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SymmetricSpace +import OAI.Combinatorics.Chromatic.Walls.Average + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +open ElementaryPositivity.SeparatedSymmetry +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {d e : I → ℕ} + +noncomputable def packSplit (A : Cut d e) (i : I) : + Fin (d i) ⊕ Fin (e i) ≃ Fin (d i+e i) := + (Equiv.sumCongr (leftEnum A i) ((rightEnum A i).trans + ((Equiv.refl _).subtypeEquiv (by intro x; simp only [Finset.mem_compl, Equiv.refl_apply])))).trans + (Equiv.sumCompl fun x => x ∈ (A i).val) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma packSplit_inl (A : Cut d e) (i : I) (x : Fin (d i)) : + packSplit A i (Sum.inl x) = leftEnum A i x := rfl +omit [Fintype I] [DecidableEq I] in +@[simp] lemma packSplit_inr (A : Cut d e) (i : I) (x : Fin (e i)) : + packSplit A i (Sum.inr x) = rightEnum A i x := rfl + +noncomputable def cutSplit (A : Cut d e) : + ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ≃ (Σi,Fin (d i+e i)) := + (Equiv.sigmaSumDistrib _ _).symm.trans (Equiv.sigmaCongrRight (packSplit A)) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma cutSplit_inl (A : Cut d e) (x : Σi,Fin (d i)) : + cutSplit A (Sum.inl x) = leftInput A x := rfl +omit [Fintype I] [DecidableEq I] in +@[simp] lemma cutSplit_inr (A : Cut d e) (x : Σi,Fin (e i)) : + cutSplit A (Sum.inr x) = rightInput A x := rfl + +omit [Fintype I] [DecidableEq I] in +lemma cutSplit_change (A B : Cut d e) : + (cutSplit A).symm.trans (cutSplit B) = + packAction (fun i => Fin (d i+e i)) (fun i => (packSplit A i).symm.trans (packSplit B i)) := by + apply Equiv.ext + intro x + obtain ⟨y,rfl⟩ := (cutSplit A).surjective x + simp only [Equiv.trans_apply, Equiv.symm_apply_apply] + cases y with + | inl x => + rcases x with ⟨i,x⟩ + change (⟨i,packSplit B i (Sum.inl x)⟩ : Σi,Fin (d i+e i)) = + ⟨i,packSplit B i ((packSplit A i).symm (packSplit A i (Sum.inl x)))⟩ + rw [Equiv.symm_apply_apply] + | inr x => + rcases x with ⟨i,x⟩ + change (⟨i,packSplit B i (Sum.inr x)⟩ : Σi,Fin (d i+e i)) = + ⟨i,packSplit B i ((packSplit A i).symm (packSplit A i (Sum.inr x)))⟩ + rw [Equiv.symm_apply_apply] + +omit [Fintype I] [DecidableEq I] in +lemma split_symmetric_independent (A B : Cut d e) (F : S (d+e)) : + rename (cutSplit B) (rename (cutSplit A).symm F.val) = F.val := by + rw [rename_rename] + change rename ((cutSplit A).symm.trans (cutSplit B)) F.val = _ + rw [cutSplit_change] + exact F.property _ + +omit [Fintype I] [DecidableEq I] in +lemma cutSplit_action (A : Cut d e) + (σ : (∀i,Equiv.Perm (Fin (d i))) × (∀i,Equiv.Perm (Fin (e i)))) : + (cutSplit A).symm.trans ((sumAction (packAction (fun i=>Fin (d i))) + (packAction (fun i=>Fin (e i))) σ).trans (cutSplit A)) = + packAction (fun i=>Fin (d i+e i)) (fun i => + (packSplit A i).symm.trans ((Equiv.sumCongr (σ.1 i) (σ.2 i)).trans (packSplit A i))) := by + apply Equiv.ext + intro x + obtain ⟨y,rfl⟩ := (cutSplit A).surjective x + simp only [Equiv.trans_apply, Equiv.symm_apply_apply] + cases y with + | inl x => + rcases x with ⟨i,x⟩ + change (⟨i,packSplit A i (Sum.inl (σ.1 i x))⟩ : Σi,Fin (d i+e i)) = + ⟨i,packSplit A i ((Equiv.sumCongr (σ.1 i) (σ.2 i)) + ((packSplit A i).symm (packSplit A i (Sum.inl x))))⟩ + rw [Equiv.symm_apply_apply]; rfl + | inr x => + rcases x with ⟨i,x⟩ + change (⟨i,packSplit A i (Sum.inr (σ.2 i x))⟩ : Σi,Fin (d i+e i)) = + ⟨i,packSplit A i ((Equiv.sumCongr (σ.1 i) (σ.2 i)) + ((packSplit A i).symm (packSplit A i (Sum.inr x))))⟩ + rw [Equiv.symm_apply_apply]; rfl + +omit [Fintype I] [DecidableEq I] in +lemma split_symmetric (A : Cut d e) (F : S (d+e)) : + ∀ σ, rename (sumAction (packAction (fun i=>Fin (d i))) (packAction (fun i=>Fin (e i))) σ) + (rename (cutSplit A).symm F.val) = rename (cutSplit A).symm F.val := by + intro σ + apply rename_injective (cutSplit A) (cutSplit A).injective + simp only [rename_rename] + have h := F.property (fun i => (packSplit A i).symm.trans + ((Equiv.sumCongr (σ.1 i) (σ.2 i)).trans (packSplit A i))) + change rename (packAction (fun i=>Fin (d i+e i)) (fun i => (packSplit A i).symm.trans + ((Equiv.sumCongr (σ.1 i) (σ.2 i)).trans (packSplit A i)))) F.val = F.val at h + rw [← cutSplit_action A σ] at h + convert h using 1 + · rfl + · simp + +lemma split_symmetric_span (A : Cut d e) (F : S (d+e)) : + rename (cutSplit A).symm F.val ∈ Submodule.span ℚ + {q | ∃ (f : S d) (g : S e), q = rename Sum.inl f.val * rename Sum.inr g.val} := by + have h := invariant_separated_span (packAction (fun i=>Fin (d i))) + (packAction (fun i=>Fin (e i))) (rename (cutSplit A).symm F.val) (split_symmetric A F) + apply Submodule.span_mono _ h + rintro q ⟨f,g,hf,hg,rfl⟩ + exact ⟨⟨f,hf⟩,⟨g,hg⟩,rfl⟩ + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {d e : I → ℕ} + +noncomputable def firstCut (d e : I → ℕ) : Cut d e := fun i => + ⟨Finset.univ.map (Fin.castAddEmb (e i)), by simp⟩ + +noncomputable def localizeS (d : I → ℕ) : + S d →ₗ[ℚ] FractionRing (MvPolynomial (Σi,Fin (d i)) ℚ) where + toFun f := algebraMap _ _ f.val + map_add' := by intro f g; exact map_add _ f.val g.val + map_smul' := by + intro r f + change algebraMap _ _ (r • f.val) = r • algebraMap _ _ f.val + exact map_rat_smul (algebraMap (MvPolynomial (Σi,Fin (d i)) ℚ) + (FractionRing (MvPolynomial (Σi,Fin (d i)) ℚ))) r f.val + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma localizeS_apply (d : I → ℕ) (f : S d) : + localizeS d f = algebraMap _ (FractionRing (MvPolynomial (Σi,Fin (d i)) ℚ)) f.val := rfl + +omit [Fintype I] [DecidableEq I] in +lemma localizeS_injective (d : I → ℕ) : Function.Injective (localizeS d) := by + intro f g h + apply Subtype.ext + exact IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,Fin (d i)) ℚ)) h + +noncomputable def shuffleImage (a : I → I → ℕ) (d e : I → ℕ) : Submodule ℚ (S (d+e)) := + Submodule.span ℚ {q | ∃ (f : S d) (g : S e), q = shufflePolynomial a f g} + +lemma rawShuffle_mem_localized_image (a : I → I → ℕ) (f : S d) (g : S e) : + rawShuffle a f.val g.val ∈ (shuffleImage a d e).map (localizeS (d+e)) := by + apply Submodule.mem_map.mpr + exact ⟨shufflePolynomial a f g, Submodule.subset_span ⟨f,g,rfl⟩, + shufflePolynomial_eq a f g⟩ + +noncomputable def tensorShuffle (a : I → I → ℕ) : + MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ →ₗ[ℚ] + FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ) where + toFun p := ∑ A : Cut d e, + algebraMap _ _ (rename (cutSplit A) p * ∏ i, ∏ j, cutFactor A i j (a i j)) / + algebraMap _ _ (cutDenominator A) + map_add' := by + intro p q + simp only [map_add, add_mul, add_div, Finset.sum_add_distrib] + map_smul' := by + let : DistribSMul ℚ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) := + (inferInstance : Module ℚ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ))).toDistribMulAction.toDistribSMul + intro r p + simp only [map_smul, map_rat_smul, smul_mul_assoc, div_eq_mul_inv, + Finset.smul_sum, RingHom.id_apply] + +lemma tensorShuffle_decomposable (a : I → I → ℕ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + tensorShuffle a (rename Sum.inl f * rename Sum.inr g) = rawShuffle a f g := by + simp only [tensorShuffle, LinearMap.coe_mk, AddHom.coe_mk, map_mul, rename_rename, + rawShuffle, cutNumerator] + rfl + +lemma tensorShuffle_restricted_mul (a : I → I → ℕ) (A₀ : Cut d e) (F : S (d+e)) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + tensorShuffle a (rename (cutSplit A₀).symm F.val * + (rename Sum.inl f * rename Sum.inr g)) = + localizeS (d+e) F * rawShuffle a f g := by + dsimp only [Pi.add_apply] at * + simp only [tensorShuffle, LinearMap.coe_mk, AddHom.coe_mk, map_mul, + split_symmetric_independent, localizeS_apply, rawShuffle, cutNumerator, + Finset.mul_sum] + apply Finset.sum_congr rfl + intro A _ + simp only [rename_rename] + change (algebraMap _ _ F.val * + (algebraMap _ _ (rename (leftInput A) f) * algebraMap _ _ (rename (rightInput A) g)) * + algebraMap _ _ (∏ i, ∏ j, cutFactor A i j (a i j))) / algebraMap _ _ (cutDenominator A) = _ + simp only [mul_assoc, mul_div_assoc] + rfl + +theorem mul_shuffle_mem (a : I → I → ℕ) (F : S (d+e)) (f : S d) (g : S e) : + F * shufflePolynomial a f g ∈ shuffleImage a d e := by + let V := (shuffleImage a d e).map (localizeS (d+e)) + let T : MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ →ₗ[ℚ] + FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ) := + (tensorShuffle a).comp (LinearMap.mulRight ℚ (rename Sum.inl f.val * rename Sum.inr g.val)) + have hT : Submodule.span ℚ + {q | ∃ (f' : S d) (g' : S e), q = rename Sum.inl f'.val * rename Sum.inr g'.val} + ≤ V.comap T := by + apply Submodule.span_le.mpr + rintro q ⟨f',g',rfl⟩ + change T (rename Sum.inl f'.val * rename Sum.inr g'.val) ∈ V + dsimp only [T, LinearMap.comp_apply, LinearMap.mulRight_apply] + have he : (rename Sum.inl f'.val * rename Sum.inr g'.val) * + (rename Sum.inl f.val * rename Sum.inr g.val) = + rename Sum.inl (f'*f).val * rename Sum.inr (g'*g).val := by + simp only [Subalgebra.coe_mul, map_mul] + ring + rw [he, tensorShuffle_decomposable] + exact rawShuffle_mem_localized_image a (f'*f) (g'*g) + have h := hT (split_symmetric_span (firstCut d e) F) + simp only [Submodule.mem_comap, T, LinearMap.comp_apply, LinearMap.mulRight_apply] at h + rw [tensorShuffle_restricted_mul] at h + obtain ⟨q,hq,he⟩ := Submodule.mem_map.mp h + have eq : q = F * shufflePolynomial a f g := by + apply localizeS_injective (d+e) + rw [he] + change _ = algebraMap _ _ (F.val * (shufflePolynomial a f g).val) + rw [map_mul] + exact congrArg (fun x => localizeS (d+e) F * x) (shufflePolynomial_eq a f g).symm + exact eq ▸ hq + +lemma shuffleImage_mul_mem (a : I → I → ℕ) (F : S (d+e)) + {q : S (d+e)} (hq : q ∈ shuffleImage a d e) : F*q ∈ shuffleImage a d e := by + induction hq using Submodule.span_induction with + | mem q hq => obtain ⟨f,g,rfl⟩ := hq; exact mul_shuffle_mem a F f g + | zero => simp + | add q r hq hr ihq ihr => simpa [mul_add] using (shuffleImage a d e).add_mem ihq ihr + | smul c q hq ih => simpa [mul_smul_comm] using (shuffleImage a d e).smul_mem c ih + +theorem destabilizing_mul_mem (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (F : S d) {q : S d} (hq : q ∈ destabilizingSpace a μ d) : + F*q ∈ destabilizingSpace a μ d := by + induction hq using Submodule.span_induction with + | mem q hq => + obtain ⟨u,v,h,f,g,hu,hv,hμ,rfl⟩ := hq + subst d + have hs : shuffleImage a u v ≤ destabilizingSpace a μ (u+v) := by + apply Submodule.span_le.mpr + rintro q ⟨f',g',rfl⟩ + exact Submodule.subset_span ⟨u,v,rfl,f',g',hu,hv,hμ,rfl⟩ + exact hs (mul_shuffle_mem a F f g) + | zero => simp + | add q r hq hr ihq ihr => + simpa [mul_add] using (destabilizingSpace a μ d).add_mem ihq ihr + | smul c q hq ih => + simpa [mul_smul_comm] using (destabilizingSpace a μ d).smul_mem c ih + +noncomputable def destabilizingIdeal (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + Ideal (S d) where + carrier := destabilizingSpace a μ d + zero_mem' := (destabilizingSpace a μ d).zero_mem + add_mem' := (destabilizingSpace a μ d).add_mem + smul_mem' := destabilizing_mul_mem a μ d + +@[simp] lemma mem_destabilizingIdeal (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (f : S d) : f ∈ destabilizingIdeal a μ d ↔ f ∈ destabilizingSpace a μ d := Iff.rfl + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/PointEvaluation.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/PointEvaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..9415396c00af87497dba08fb7bd774c38abad572 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/PointEvaluation.lean @@ -0,0 +1,214 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Degree + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma constantCoeff_translation {α : Type*} (t : ℚ) (f : MvPolynomial α ℚ) : + constantCoeff (translation t f)=eval (fun _=>t) f := by + induction f using MvPolynomial.induction_on with + | C q => simp only [translation_C,constantCoeff_C,eval_C] + | add f g hf hg => simp only [map_add,hf,hg] + | mul_X f i hf => simp only [map_mul,translation_X,map_add,constantCoeff_X, + constantCoeff_C,zero_add,hf,eval_X] + +noncomputable def translationAlgB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (t : ℚ) : B a μ d →ₐ[ℚ] B a μ d := + (Polynomial.eval₂AlgHom (AlgHom.id ℚ (B a μ d)) (algebraMap ℚ (B a μ d) t) + (fun _=>Commute.all _ _)).comp + (taylorB a μ d) + +lemma translationAlgB_apply (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (t : ℚ) (f : B a μ d) : + translationAlgB a μ d t f=translationB a μ d t f := by + change Polynomial.eval₂ (RingHom.id _) (algebraMap ℚ (B a μ d) t) (taylorB a μ d f)=_ + rw [Polynomial.eval₂_id,taylorB_eval] + +namespace SplitTree +@[reducible] def centerOfVar : (T : SplitTree I) → T.Vars → T.Centers + | .leaf _, _ => () + | .node l _, .inl x => .inl (l.centerOfVar x) + | .node _ r, .inr x => .inr (r.centerOfVar x) + +noncomputable def translationAtAlgB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) : + (T : SplitTree I) → (T.Centers → ℚ) → + tensor (quotientFamily a μ) T →ₐ[ℚ] tensor (quotientFamily a μ) T + | .leaf d, v => translationAlgB a μ d (v ()) + | .node l r, v => Algebra.TensorProduct.map + (translationAtAlgB a μ l (v ∘ Sum.inl)) (translationAtAlgB a μ r (v ∘ Sum.inr)) + +lemma translationAtAlgB_apply (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (v : T.Centers → ℚ) (x : tensor (quotientFamily a μ) T) : + translationAtAlgB a μ T v x=translationAtB a μ T v x := by + induction T with + | leaf d => exact translationAlgB_apply a μ d (v ()) x + | node l r hl hr => + induction x using TensorProduct.inductionOn with + | tmul x y => + change translationAtAlgB a μ l (v ∘ Sum.inl) x⊗ₜ[ℚ] + translationAtAlgB a μ r (v ∘ Sum.inr) y=_ + rw [hl,hr] + rfl + | add x y hx hy => simp only [map_add,hx,hy] + +lemma degreeZero_translate_quotient (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (v : T.Centers → ℚ) (x : tensor rawFamily T) : + degreeZeroTensor a μ T (translationAtAlgB a μ T v (quotientMap a μ T x))= + algebraMap ℚ (tensor (quotientFamily a μ) T) + (eval (v ∘ T.centerOfVar) (tensorValue T x)) := by + induction T with + | leaf d => + change degreeZeroB a μ d (translationAlgB a μ d (v ()) (quotientAlg a μ d x))=_ + rw [translationAlgB_apply] + change degreeZeroB a μ d (quotientAlg a μ d (translationS d (v ()) x))=_ + rw [degreeZeroB_mk] + congr 1 + exact constantCoeff_translation (v ()) x.val + | node l r hl hr => + induction x using TensorProduct.inductionOn with + | tmul x y => + change degreeZeroTensor a μ l (translationAtAlgB a μ l (v ∘ Sum.inl) (quotientMap a μ l x))⊗ₜ[ℚ] + degreeZeroTensor a μ r (translationAtAlgB a μ r (v ∘ Sum.inr) (quotientMap a μ r y))=_ + rw [hl,hr,tensorValue_tmul,map_mul,eval_rename,eval_rename] + simp only [Function.comp_def,centerOfVar] + simp only [Algebra.algebraMap_eq_smul_one,TensorProduct.smul_tmul, + TensorProduct.tmul_smul,smul_smul,Algebra.TensorProduct.one_def,mul_comm] + | add x y hx hy => simp only [map_add,hx,hy] + +noncomputable def pointedRestrictionB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 inferInstanceAs (Fintype Unit) + | .node l r => by + letI := centersFintype l + letI := centersFintype r + exact inferInstanceAs (Fintype (l.Centers ⊕ r.Centers)) + +instance centersLinearOrder : (T : SplitTree I) → LinearOrder T.Centers + | .leaf _ => inferInstanceAs (LinearOrder Unit) + | .node l r => by + letI := centersLinearOrder l + letI := centersLinearOrder r + exact Sum.Lex.linearOrder + +def centerPairs (T : SplitTree I) : Finset (T.Centers × T.Centers) := + Finset.univ.filter (fun ij=>ij.1 < ij.2) + +omit [Fintype I] [DecidableEq I] in +lemma centerPairs_ne (T : SplitTree I) (ij : T.Centers×T.Centers) (h : ij∈T.centerPairs) : + ij.1≠ij.2 := (Finset.mem_filter.mp h).2.ne + +omit [Fintype I] [DecidableEq I] in +lemma centerPairs_norev (T : SplitTree I) (ij : T.Centers×T.Centers) (h : ij∈T.centerPairs) : + (ij.2,ij.1)∉T.centerPairs := by + intro hr + exact lt_asymm (Finset.mem_filter.mp h).2 (Finset.mem_filter.mp hr).2 + +noncomputable def centerNumerator (a : I → I → ℕ) (T : SplitTree I) + (s : Finset (T.Centers×T.Centers)) : MvPolynomial T.Centers ℚ := + ∏ ij∈s,diagonal ij.1 ij.2 ^ (eulerForm a (T.leafDimension ij.1) (T.leafDimension ij.2)).toNat + +omit [DecidableEq I] in +lemma centerDenominator_ne_zero (a : I → I → ℕ) (T : SplitTree I) : + centerDenominator a T T.centerPairs≠0 := by + exact Finset.prod_ne_zero_iff.mpr fun ij hij=> + pow_ne_zero _ (diagonal_ne_zero (T.centerPairs_ne ij hij)) + +omit [DecidableEq I] in +lemma centerNumerator_ne_zero (a : I → I → ℕ) (T : SplitTree I) : + centerNumerator a T T.centerPairs≠0 := by + exact Finset.prod_ne_zero_iff.mpr fun ij hij=> + pow_ne_zero _ (diagonal_ne_zero (T.centerPairs_ne ij hij)) + +def PairSymmetric (a : I → I → ℕ) (T : SplitTree I) : Prop := + ∀ ij∈T.centerPairs,eulerForm a (T.leafDimension ij.1) (T.leafDimension ij.2) = + eulerForm a (T.leafDimension ij.2) (T.leafDimension ij.1) + +noncomputable def clearedLeading (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0g.1.1.val) i.2.2.property⟩ + invFun w:=⟨(stringPBWGrade a c η hc (slope c η d) w.val).2, + (stringPBWGrade a c η hc (slope c η d) w.val).1.2,⟨w.val,by + apply Prod.ext + · apply Prod.ext + · exact Subtype.ext w.property + · rfl + · rfl⟩⟩ + left_inv i:=by + rcases i with ⟨k,W,w,hw⟩ + dsimp only + have hk := congrArg Prod.snd hw + have hW := congrArg (fun g : SlopeWeight c η hc (slope c η d) × ℤ => g.1.2) hw + dsimp only at hk hW + subst k + subst W + rfl + right_inv _:=rfl + +abbrev BlockRows (d : I → ℕ) := + {r : SupportedUnitRows (slopeStartRowType a c η hc (slope c η d)) // + rowsDimension (slopeStartRowType a c η hc (slope c η d)) + (fun i=>i.1.val.1.val) r=d} + +def blockRowsEquiv (d : I → ℕ) : StringBlockIndex a c η hc d ≃ BlockRows a c η hc d := + (blockWordEquiv a c η hc d).trans + ((primitiveRowsEquiv a c η hc (slope c η d)).subtypeEquiv (fun w=>by + rw [primitiveRows_dimension])) + +def blockRowsEnergy (d : I → ℕ) (r : BlockRows a c η hc d) : ℤ := + rowsEnergy (slopeStartRowType a c η hc (slope c η d)) + (slopeStartParameter a κ c η hc (slope c η d)) r.val + +lemma blockRowsEquiv_energy (d : I → ℕ) (w : StringBlockIndex a c η hc d) : + blockRowsEnergy a κ c η hc d (blockRowsEquiv a c η hc d w)= + stringBlockEnergy a κ c η hc d w := by + change rowsEnergy _ _ (primitiveRowsEquiv a c η hc (slope c η d) w.2.2.val)=_ + rw [primitiveRows_energy,w.2.2.property,stringBlockEnergy_normalized] + +def HNRowsIndex : List (I → ℕ) → Type u + | []=>ULift.{u} Unit + | d::l=>BlockRows a c η hc d × HNRowsIndex l + +def hnRowsEquiv : (l : List (I → ℕ)) → HNStringIndex a c η hc l ≃ HNRowsIndex a c η hc l + | []=>Equiv.refl _ + | d::l=>Equiv.prodCongr (blockRowsEquiv a c η hc d) (hnRowsEquiv l) + +def hnRowsEnergy : (l : List (I → ℕ)) → HNRowsIndex a c η hc l → ℤ + | [],_=>0 + | d::l,r=>blockRowsEnergy a κ c η hc d r.1+hnRowsEnergy l r.2+ + (eulerForm a d l.sum-eulerForm a l.sum d) + +lemma hnRowsEquiv_energy (l : List (I → ℕ)) (w : HNStringIndex a c η hc l) : + hnRowsEnergy a κ c η hc l (hnRowsEquiv a c η hc l w)=hnStringEnergy a κ c η hc l w := by + induction l with + | nil=>rfl + | cons d l ih=> + change blockRowsEnergy a κ c η hc d (blockRowsEquiv a c η hc d w.1)+ + hnRowsEnergy a κ c η hc l (hnRowsEquiv a c η hc l w.2)+_=_ + rw [blockRowsEquiv_energy,ih] + rfl + +def outputRowsEquiv (d : I → ℕ) : + (Σ l : HNIndex c η d,HNStringIndex a c η hc l.val) ≃ + Σ l : HNIndex c η d,HNRowsIndex a c η hc l.val := + Equiv.sigmaCongrRight (fun l=>hnRowsEquiv a c η hc l.val) + +lemma outputRows_admissible (d : I → ℕ) : EnergyLaurent.Admissible + (fun r : Σ l : HNIndex c η d,HNRowsIndex a c η hc l.val=>hnRowsEnergy a κ c η hc r.1.val r.2) := + EnergyLaurent.admissible_equiv (outputEnergy_admissible a κ c η hc d) + (outputRowsEquiv a c η hc d) (fun w=>hnRowsEquiv_energy a κ c η hc w.1.val w.2) + +def outputRowsSeries (d : I → ℕ) : LaurentSeries ℚ := EnergyLaurent.series _ + (outputRows_admissible a κ c η hc d) + +theorem finiteReordering_rows (ε : I → Bool) (ha : ∀i,a i i=elementaryDiagonal ε i) (d : I → ℕ) : + inputReorderingSeries a κ ε ha d=outputRowsSeries a κ c η hc d := by + rw [finiteReordering_laurent a κ c η hc ε ha] + exact EnergyLaurent.series_equiv _ _ (outputRowsEquiv a c η hc d) + (fun w=>hnRowsEquiv_energy a κ c η hc w.1.val w.2) +end +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic +noncomputable section +attribute [local instance] Classical.propDecidable +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0[] + | d::l,r=>⟨d,r.1⟩::rowsDecorate l r.2 + +@[simp] lemma rowsDecorate_dim (l : List (I → ℕ)) (r : HNRowsIndex a c η hc l) : + (rowsDecorate a c η hc l r).map Sigma.fst=l := by + induction l with + | nil=>rfl + | cons d l ih=>simpa only [rowsDecorate,List.map_cons] using congrArg (List.cons d) (ih r.2) + +def rowsUndecorate : (l : List (RowBlock a c η hc)) → HNRowsIndex a c η hc (l.map Sigma.fst) + | []=>⟨()⟩ + | b::l=>(b.2,rowsUndecorate l) + +@[simp] lemma rowsDecorate_undecorate (l : List (RowBlock a c η hc)) : + rowsDecorate a c η hc (l.map Sigma.fst) (rowsUndecorate a c η hc l)=l := by + induction l with + | nil=>rfl + | cons b l ih=> + change b::rowsDecorate a c η hc (l.map Sigma.fst) (rowsUndecorate a c η hc l)=b::l + rw [ih] + +lemma rowsDecorate_injective (l : List (I → ℕ)) : + Function.Injective (rowsDecorate a c η hc l) := by + induction l with + | nil=>intro x y _; exact @Subsingleton.elim (ULift Unit) inferInstance x y + | cons d l ih=> + intro x y H + simp only [rowsDecorate,List.cons.injEq] at H + apply Prod.ext + · exact eq_of_heq (Sigma.mk.inj H.1).2 + · exact ih H.2 + +def rowsCons (d : I → ℕ) (r : BlockRows a c η hc d) + (x : Σ l : List (I → ℕ),HNRowsIndex a c η hc l) : + Σ l : List (I → ℕ),HNRowsIndex a c η hc l := ⟨d::x.1,(r,x.2)⟩ + +lemma rowsUndecorate_decorate (l : List (I → ℕ)) (r : HNRowsIndex a c η hc l) : + (⟨(rowsDecorate a c η hc l r).map Sigma.fst, + rowsUndecorate a c η hc (rowsDecorate a c η hc l r)⟩ : + Σ l : List (I → ℕ),HNRowsIndex a c η hc l)=⟨l,r⟩ := by + induction l with + | nil=> + have H : r=(⟨()⟩ : ULift Unit) := @Subsingleton.elim (ULift Unit) inferInstance r ⟨()⟩ + cases H + rfl + | cons d l ih=>exact congrArg (rowsCons a c η hc d r.1) (ih r.2) + +abbrev DecoratedHN (d : I → ℕ) := + {l : List (RowBlock a c η hc) // (l.map Sigma.fst).sum=d ∧ HNOrdered c η (l.map Sigma.fst)} + +def decorateOutput (d : I → ℕ) : + (Σ l : HNIndex c η d,HNRowsIndex a c η hc l.val) ≃ DecoratedHN a c η hc d where + toFun x:=⟨rowsDecorate a c η hc x.1.val x.2,by simpa only [rowsDecorate_dim] using x.1.property⟩ + invFun l:=⟨⟨l.val.map Sigma.fst,l.property⟩,rowsUndecorate a c η hc l.val⟩ + left_inv x:=by + have H:=rowsUndecorate_decorate a c η hc x.1.val x.2 + exact Sigma.ext (Subtype.ext (Sigma.mk.inj H).1) (Sigma.mk.inj H).2 + right_inv l:=Subtype.ext (rowsDecorate_undecorate a c η hc l.val) + +def decoratedDimension (l : List (RowBlock a c η hc)) : I → ℕ := (l.map Sigma.fst).sum + +def decoratedEnergy : List (RowBlock a c η hc) → ℤ + | []=>0 + | b::l=>blockRowsEnergy a κ c η hc b.1 b.2+decoratedEnergy l+ + (eulerForm a b.1 (decoratedDimension a c η hc l)-eulerForm a (decoratedDimension a c η hc l) b.1) + +lemma decoratedEnergy_rows (l : List (I → ℕ)) (r : HNRowsIndex a c η hc l) : + decoratedEnergy a κ c η hc (rowsDecorate a c η hc l r)=hnRowsEnergy a κ c η hc l r := by + induction l with + | nil=>rfl + | cons d l ih=> + simp only [rowsDecorate,decoratedEnergy,decoratedDimension,rowsDecorate_dim,ih,hnRowsEnergy] + +lemma decoratedDimension_append (l r : List (RowBlock a c η hc)) : + decoratedDimension a c η hc (l++r)=decoratedDimension a c η hc l+decoratedDimension a c η hc r := by + simp [decoratedDimension] + +lemma decoratedEnergy_append (l r : List (RowBlock a c η hc)) : + decoratedEnergy a κ c η hc (l++r)= + decoratedEnergy a κ c η hc l+decoratedEnergy a κ c η hc r+ + (eulerForm a (decoratedDimension a c η hc l) (decoratedDimension a c η hc r)- + eulerForm a (decoratedDimension a c η hc r) (decoratedDimension a c η hc l)) := by + induction l with + | nil=>simp [decoratedEnergy,decoratedDimension,eulerForm] + | cons b l ih=> + simp only [List.cons_append,decoratedEnergy,ih, + decoratedDimension,List.map_cons,List.sum_cons,List.map_append,List.sum_append,eulerForm_add_left,eulerForm_add_right] + ring + +lemma decoratedEnergy_admissible (d : I → ℕ) : + EnergyLaurent.Admissible (fun l : DecoratedHN a c η hc d=>decoratedEnergy a κ c η hc l.val) := + EnergyLaurent.admissible_equiv (outputRows_admissible a κ c η hc d) + (decorateOutput a c η hc d) (fun l=>decoratedEnergy_rows a κ c η hc l.1.val l.2) + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveOperators.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveOperators.lean new file mode 100644 index 0000000000000000000000000000000000000000..c24ae5248578092aba68da88bc45a0436c227c0c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveOperators.lean @@ -0,0 +1,106 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.PrimitiveSpace +import OAI.Combinatorics.Chromatic.Walls.PrimitiveStrings + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open CommonTranslation +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma derivativeB_properFiltered (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + rw [primitiveSpace_mk_iff] at hf + let y : sourceFiltration a c η hc θ d W := + ⟨derivativeB a (SlopeArithmetic.slope c η) d f.val, + derivativeB_filtered a c η hc θ d W f.val f.property⟩ + change (Submodule.Quotient.mk y : SourceAssociatedGrade a c η hc θ d W)∈_ + exact (primitiveSpace_mk_iff a c η hc θ hχ d W y).mpr + (derivativeB_properFiltered a c η hc θ d (W+1) f.val hf) + +lemma gradeMeanMultiply_primitive (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + rw [primitiveSpace_mk_iff] at hf + let y : sourceFiltration a c η hc θ d W := + ⟨meanMultiplyB a (SlopeArithmetic.slope c η) d f.val, + meanMultiplyB_filtered a c η hc θ d W f.val f.property⟩ + change (Submodule.Quotient.mk y : SourceAssociatedGrade a c η hc θ d W)∈_ + exact (primitiveSpace_mk_iff a c η hc θ hχ d W y).mpr + (meanMultiplyB_properFiltered a c η hc θ d (W+1) f.val hf) + +lemma gradeDerivative_locally_nilpotent (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0s.1.val.1.val + have hdim : ∀s,dim s∈slopeDimensions c η hc θ := fun s=>s.1.val.1.property + have hi : ∀d∈slopeDimensions c η hc θ,∀e∈slopeDimensions c η hc θ,Ω (P d) (P e)=0 := by + intro d hd e he + rw [hgeom,eulerForm_slopeDimensions_symm a c η hc θ ⟨d,hd⟩ ⟨e,he⟩,sub_self] + exact stringRoot_closure (slopeStartRowType a c η hc θ) dim + (slopeStartParameter a κ c η hc θ) (primitiveCountsEnergy_admissible a κ c η hc θ) + (slopeDimensions c η hc θ) hdim (fun s=>s.1.property) w Ω P C hi V + (fun s=>hroot (dim s)) (fun s=>hv _ (hdim s)) + +variable (h : M→+ℝ) (hh : ∀d,h (P d)=slopeValue c η θ d) +include hgeom hroot hv hh in +theorem finiteInput_zero_rootClosure (ε : I→Bool) (ha : ∀i,a i i=elementaryDiagonal ε i) : + InPrecisionClosure LaurentRay.vUnit Ω (literalRootProducts Ω C V) + (PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) + (push w LaurentRay.vUnit Ω P (literalInputCoefficient a κ ε))) := by + rw [←literalInput_primitiveFactor a κ c η hc w Ω P hgeom h θ hh ε ha] + exact primitiveFactor_rootClosure a κ c η hc w Ω P C hgeom hroot θ V hv +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveSpace.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4b7a9a5680eade8a6a1354c7a5a6e32f4de0d7b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveSpace.lean @@ -0,0 +1,68 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SymbolDetection +import OAI.Combinatorics.Chromatic.Shuffle.VariableMean + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.CenterCalculus +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma proper_next_iff_symbols_zero (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + (LinearMap.proj j.val).comp (gradeSymbolFamily a c η hc θ hχ d W)) + +lemma primitiveSpace_mk_iff (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + symbolFamily a c η hc θ hχ d W f j.val)=0 ↔ _ + constructor + · intro h j hp + exact congrFun h ⟨j,hp⟩ + · intro h + funext j + exact h j.val j.property + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveStringBounds.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveStringBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..0788613c5cb4ba536cc169c75205fe0e94ff1e99 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveStringBounds.lean @@ -0,0 +1,213 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalHilbertGrading + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + apply (Submodule.Quotient.mk_eq_zero _).mpr + change x.val∈sourceFiltration a c η hc θ d (W+1) + exact sourceFiltration_antitone a c η hc θ d (show W+1≤-interaction a d d by omega) + (by rw [sourceFiltration_lower]; trivial) + +lemma stringBase_auxiliary_lower (i : StringBaseIndex a c η hc θ hχ d W) : + -interaction a d d≤W := by + by_contra h + have H:=associatedGrade_eq_zero_below a c η hc θ d W (lt_of_not_ge h) + (homogeneousStringBaseBasis a c η hc θ hχ d W i).val.val + exact (homogeneousStringBaseBasis a c η hc θ hχ d W).ne_zero i (Subtype.ext (Subtype.ext H)) + +theorem stringStarts_bounded_finite (hd : d≠0) (hs : slope c η d=θ) (m : ℤ) : + Finite {i : (Σ W : ℤ,StringBaseIndex a c η hc θ hχ d W) // + stringBaseDegree a c η hc θ hχ d i.1 i.2 ≤ m} := by + let f : {i : (Σ W : ℤ,StringBaseIndex a c η hc θ hχ d W) // + stringBaseDegree a c η hc θ hχ d i.1 i.2 ≤ m} → + (Σ w : {w : ℤ // w∈Set.Icc (-interaction a d d) (2*m+eulerForm a d d)}, + Σ ℓ : {ℓ : ℤ // ℓ∈Set.Icc 0 m}, + {j : StringBaseIndex a c η hc θ hχ d w.val // stringBaseDegree a c η hc θ hχ d w.val j=ℓ.val}) := fun i=> + ⟨⟨i.val.1,stringBase_auxiliary_lower a c η hc θ hχ d _ i.val.2, + (stringBase_auxiliary_upper a c η hc θ hχ d _ hd hs i.val.2).trans (by omega)⟩, + ⟨stringBaseDegree a c η hc θ hχ d i.val.1 i.val.2, + stringBaseDegree_nonneg a c η hc θ hχ d _ i.val.2,i.property⟩,⟨i.val.2,rfl⟩⟩ + let (w : {w : ℤ // w∈Set.Icc (-interaction a d d) (2*m+eulerForm a d d)}) + (ℓ : {ℓ : ℤ // ℓ∈Set.Icc 0 m}) := stringBaseDegree_finite a c η hc θ hχ d w.val ℓ.val + apply Finite.of_injective f + intro x y h + have H:=congrArg (fun i=> (⟨i.1.val,i.2.2.val⟩ : Σ W : ℤ,StringBaseIndex a c η hc θ hχ d W)) h + exact Subtype.ext H +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped DirectSum +open ElementaryPositivity.SlopeArithmetic +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0hne (by rw [h,map_zero]) + let e := unitalGradeNonzeroEquiv a c η hc θ d.val hd W + have he : e y≠0 := fun h=>hyne (e.injective (h.trans e.map_zero.symm)) + have H:=congrArg e (mem_unitalOriginalHomogeneous a c η hc θ d.val W k y |>.mp hy) + rw [unitalAssociatedComponent_nonzero] at H + constructor + · by_contra h + exact he (associatedGrade_eq_zero_below a c η hc θ d.val W (lt_of_not_ge h) (e y)) + · by_contra h + rw [associatedComponent_upper a c η hc θ d.val hd (d.property.resolve_left hd) W k + (lt_of_not_ge h),LinearMap.zero_apply] at H + exact he H.symm + +abbrev SlopeStringCoefficient (d : I → ℕ) (hs : slope c η d=θ) (k : ℤ) := + Σ W : ℤ,StringPBWGradedIndex a c η hc θ (⟨d,Or.inr hs⟩,W) k + +lemma slopeStringCoefficient_bounds (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) + (k : ℤ) (i : SlopeStringCoefficient a c η hc θ d hs k) : + -interaction a d d ≤ i.1 ∧ i.1 ≤ 2*k+eulerForm a d d := by + exact globalOriginal_nonzero_bounds a c η hc θ ⟨d,Or.inr hs⟩ hd i.1 k + (globalStringPBWBasis a c η hc θ i.2.val) + ((congrArg (fun z : SlopeWeight c η hc θ × ℤ=> + globalStringPBWBasis a c η hc θ i.2.val ∈ globalOriginalHomogeneous a c η hc θ z.1 z.2) + i.2.property).mp (globalStringPBWBasis_original a c η hc θ i.2.val)) + ((globalStringPBWBasis a c η hc θ).ne_zero i.2.val) + +def slopeStringCutoff (d : I → ℕ) (k : ℤ) : ℕ := + (2*k+eulerForm a d d+interaction a d d+1).toNat + +omit [DecidableEq I] in +lemma slopeStringCutoff_bound (d : I → ℕ) (k : ℤ) : + 2*k+eulerForm a d d < -interaction a d d+slopeStringCutoff a d k := by + unfold slopeStringCutoff + omega + +lemma sigmaSubtype_ext {A B : Type*} {p : A → B → Prop} {x y : Σ a,{b // p a b}} + (h : x.1=y.1) (hval : x.2.val=y.2.val) : x=y := by + rcases x with ⟨a,b⟩ + rcases y with ⟨a',b'⟩ + dsimp at h hval + subst a' + exact congrArg (Sigma.mk a) (Subtype.ext hval) + +noncomputable def slopeStringCutoffEquiv (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) (k : ℤ) : + SlopeStringCoefficient a c η hc θ d hs k ≃ + Σ j : Fin (slopeStringCutoff a d k),StringPBWGradedIndex a c η hc θ + (⟨d,Or.inr hs⟩,-interaction a d d+j.val) k where + toFun i := by + have H:=slopeStringCoefficient_bounds a c η hc θ d hd hs k i + have Hn:=slopeStringCutoff_bound a d k + let j : Fin (slopeStringCutoff a d k):=⟨(i.1+interaction a d d).toNat,by omega⟩ + refine ⟨j,⟨i.2.val,?_⟩⟩ + have E : -interaction a d d+(j.val:ℤ)=i.1 := by dsimp [j]; omega + rw [E] + exact i.2.property + invFun i := ⟨-interaction a d d+i.1.val,i.2⟩ + left_inv i := by + apply sigmaSubtype_ext + · dsimp; have H:=slopeStringCoefficient_bounds a c η hc θ d hd hs k i; omega + · rfl + right_inv i := by + apply sigmaSubtype_ext + · apply Fin.ext + dsimp + omega + · rfl + +lemma slopeStringCoefficient_finite (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) (k : ℤ) : + Finite (SlopeStringCoefficient a c η hc θ d hs k) := by + let (j : Fin (slopeStringCutoff a d k)) := stringPBWGradedIndex_finite a c η hc θ + (⟨d,Or.inr hs⟩,-interaction a d d+j.val) k + exact Finite.of_equiv _ (slopeStringCutoffEquiv a c η hc θ d hd hs k).symm + +theorem slopeStringHilbert_coefficient (d : I → ℕ) (hd : d≠0) (hs : slope c η d=θ) (k : ℤ) : + Module.finrank ℚ (gradeB a (slope c η) d k)= + Nat.card (SlopeStringCoefficient a c η hc θ d hs k) := by + rw [Nat.card_congr (slopeStringCutoffEquiv a c η hc θ d hd hs k)] + let (j : Fin (slopeStringCutoff a d k)) := stringPBWGradedIndex_finite a c η hc θ + (⟨d,Or.inr hs⟩,-interaction a d d+j.val) k + rw [Nat.card_sigma] + exact (sourcePBWHilbert_coefficient a c η hc θ d hd hs k _ (slopeStringCutoff_bound a d k)).trans + (Fin.sum_univ_eq_sum_range (fun j=>Nat.card (StringPBWGradedIndex a c η hc θ + (⟨d,Or.inr hs⟩,-interaction a d d+j) k)) (slopeStringCutoff a d k)).symm +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveUnitRows.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveUnitRows.lean new file mode 100644 index 0000000000000000000000000000000000000000..2193f41f582b5d8108569234a3c66e9049f9af7f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/PrimitiveUnitRows.lean @@ -0,0 +1,186 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.FinitelySupportedUnitRows +import OAI.Combinatorics.Chromatic.Walls.StringReorderingEnergy + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic SignedMultiplicity UnitSelections +noncomputable section +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0 simp_all + +def primitiveCountEquiv : StringPBWIndex a c η hc θ ≃ + CountSelection (fun i : SlopeStringStart a c η hc θ × ℕ=> + slopeStartRowType a c η hc θ i.1≠0) := + ((stringSelectionEquiv a c η hc θ).trans + (selectionCountEquiv _)).trans + (countReindex (stringLetterStartEquiv a c η hc θ) _ _ (slopeStartEven_iff a c η hc θ)) + +def primitiveRowsEquiv : StringPBWIndex a c η hc θ ≃ + SupportedUnitRows (slopeStartRowType a c η hc θ) := + (primitiveCountEquiv a c η hc θ).trans (allUnitRowsEquiv _) + +lemma primitiveCount_energy (w : StringPBWIndex a c η hc θ) : + (primitiveCountEquiv a c η hc θ w).val.sum (fun i n=> + n • (slopeStartParameter a κ c η hc θ i.1-2*(i.2:ℤ)))= + normalizedEnergy a κ (stringPBWGrade a c η hc θ w).1.1.val + (stringPBWGrade a c η hc θ w).2 := by + change (countReindex _ _ _ (slopeStartEven_iff a c η hc θ) _).val.sum _=_ + rw [countReindex_sum] + change ((stringSelectionEquiv a c η hc θ w).val).toFinsupp.sum _=_ + rw [multiset_count_sum] + rw [stringWordEnergy] + rfl + +lemma stringWord_dimension (w : List (GlobalStringIndex a c η hc θ)) : + (w.map (fun i=>i.1.val.1.val)).sum= + (wordWeight c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val) w).1.val := by + induction w with + | nil => rfl + | cons i w ih => simpa only [List.map_cons,List.sum_cons,wordWeight,Prod.fst_add,AddSubmonoid.coe_add] using congrArg (i.1.val.1.val+·) ih + +lemma primitiveCount_dimension (w : StringPBWIndex a c η hc θ) : + (primitiveCountEquiv a c η hc θ w).val.sum (fun i n=>n • i.1.1.val.1.val)= + (stringPBWGrade a c η hc θ w).1.1.val := by + change (countReindex _ _ _ (slopeStartEven_iff a c η hc θ) _).val.sum _=_ + rw [countReindex_sum] + change ((stringSelectionEquiv a c η hc θ w).val).toFinsupp.sum _=_ + rw [multiset_count_sum] + exact stringWord_dimension a c η hc θ w.val + +theorem primitiveRows_energy (w : StringPBWIndex a c η hc θ) : + rowsEnergy (slopeStartRowType a c η hc θ) (slopeStartParameter a κ c η hc θ) + (primitiveRowsEquiv a c η hc θ w)= + normalizedEnergy a κ (stringPBWGrade a c η hc θ w).1.1.val + (stringPBWGrade a c η hc θ w).2 := by + rw [primitiveRowsEquiv,Equiv.trans_apply,rowsEnergy_equiv] + exact primitiveCount_energy a κ c η hc θ w + +theorem primitiveRows_dimension (w : StringPBWIndex a c η hc θ) : + rowsDimension (slopeStartRowType a c η hc θ) (fun i=>i.1.val.1.val) + (primitiveRowsEquiv a c η hc θ w)=(stringPBWGrade a c η hc θ w).1.1.val := by + rw [primitiveRowsEquiv,Equiv.trans_apply,rowsDimension_equiv] + exact primitiveCount_dimension a c η hc θ w +end +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +attribute [local instance] Classical.propDecidable + +lemma strict_fin_nat_bound {n : ℕ} {f : Fin n → ℕ} (hf : StrictMono f) (i : Fin n) : i.val≤f i := by + cases n with + | zero => exact Fin.elim0 i + | succ n => + induction i using Fin.induction with + | zero => simp + | succ i ih => + have H:=hf (Fin.castSucc_lt_succ (i := i)) + change i.val≤f i.castSucc at ih + change i.val+1≤f i.succ + omega + +noncomputable def weakStrictListEquiv (n : ℕ) : + {f : Fin n → ℕ // Monotone f} ≃ {f : Fin n → ℕ // StrictMono f} where + toFun f := ⟨fun i=>f.val i+i.val,by + intro i j hij + have H:=f.property hij.le + have Hij : i.valf.val i-i.val,by + cases n with + | zero => intros i; exact Fin.elim0 i + | succ n => + apply Fin.monotone_iff_le_succ.mpr + intro i + have H:=f.property (Fin.castSucc_lt_succ (i := i)) + change f.val i.castSucc-i.val≤f.val i.succ-(i.val+1) + omega⟩ + left_inv f := by apply Subtype.ext; funext i; dsimp; omega + right_inv f := by + apply Subtype.ext; funext i + have H:=strict_fin_nat_bound f.property i + dsimp + omega + +abbrev UnitIndexList (elementary : Bool) (n : ℕ) := + {f : Fin n → ℕ // if elementary then StrictMono f else Monotone f} +noncomputable def weakUnitListEquiv (elementary : Bool) (n : ℕ) : + {f : Fin n → ℕ // Monotone f} ≃ UnitIndexList elementary n := by + cases elementary + · exact Equiv.refl _ + · exact weakStrictListEquiv n + +lemma weakUnitListEquiv_val (elementary : Bool) (n : ℕ) + (f : {f : Fin n → ℕ // Monotone f}) (i : Fin n) : + (weakUnitListEquiv elementary n f).val i=f.val i+(if elementary then i.val else 0) := by + cases elementary <;> rfl + +lemma fin_staircase_sum (n : ℕ) : + 2*(∑ j : Fin n,(j.val:ℤ))=(n:ℤ)*((n:ℤ)-1) := by + induction n with + | zero => simp + | succ n ih => + rw [Fin.sum_univ_castSucc] + simp only [Fin.val_castSucc,Fin.val_last,Nat.cast_add,Nat.cast_one] + nlinarith + +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (ε : I → Bool) (d : I → ℕ) +abbrev InputIndexLists := ∀ i,UnitIndexList (ε i) (d i) +noncomputable def inputListEquiv : SortedPackExponent d ≃ InputIndexLists ε d := + Equiv.piCongrRight (fun i=>weakUnitListEquiv (ε i) (d i)) + +def elementaryDiagonal (i : I) : ℕ := if ε i then 0 else 1 + +def listIndexSum (x : InputIndexLists ε d) : ℕ := ∑ i,∑ j,(x i).val j + +omit [DecidableEq I] in +lemma inputListIndexSum (x : SortedPackExponent d) : + 2*(listIndexSum ε d (inputListEquiv ε d x):ℤ)= + 2*(sortedPackDegree d x:ℤ)+ + ∑ i,((1:ℤ)-elementaryDiagonal ε i)*(d i:ℤ)*((d i:ℤ)-1) := by + simp only [listIndexSum,inputListEquiv,Equiv.piCongrRight_apply,Pi.map,weakUnitListEquiv_val, + sortedPackDegree,Nat.cast_sum,Nat.cast_add,Finset.sum_add_distrib,mul_add] + congr 1 + rw [Finset.mul_sum] + apply Finset.sum_congr rfl; intro i hi + cases h : ε i with + | false => simp [h,elementaryDiagonal] + | true => simpa [h,elementaryDiagonal] using fin_staircase_sum (d i) +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/QuantumTorusTrace.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/QuantumTorusTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..46786b4033b5f323c736f4d4728a75d0eb08f264 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/QuantumTorusTrace.lean @@ -0,0 +1,45 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus + +namespace OAI + +section +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) +lemma alternating_skew (hΩ : ∀m,Ω m m=0) (a b : M) : Ω a b= -(Ω b a) := by + have hh:=hΩ (a+b) + simp only [map_add,AddMonoidHom.add_apply,hΩ] at hh + omega + +lemma coefficient_trace (hΩ : ∀m,Ω m m=0) (r : M) (f g : Torus v Ω) + (hf : ∀m,Ω m r≠0 → f m=0) : (f*g) r=(g*f) r := by + classical + change (Torus.multiply v Ω f g) r=(Torus.multiply v Ω g f) r + simp only [Torus.multiply,Finsupp.sum,Finsupp.finsetSum_apply] + conv_rhs => rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a ha + apply Finset.sum_congr rfl + intro b hb + by_cases he : a+b=r + · have har : Ω a r=0 := by + by_contra hn + exact (Finsupp.mem_support_iff.mp ha) (hf a hn) + have hab : Ω a b=0 := by + rw [←he,map_add,hΩ a,zero_add] at har + exact har + have hba : Ω b a=0 := by rw [alternating_skew Ω hΩ b a,hab,neg_zero] + simp only [he,show b+a=r by rwa [add_comm],Finsupp.single_eq_same,hab,hba, + zpow_zero,Units.val_one,mul_one] + exact mul_comm _ _ + · have he' : b+a≠r := by rwa [add_comm] + rw [Finsupp.single_eq_of_ne (Ne.symm he),Finsupp.single_eq_of_ne (Ne.symm he')] +end +end ElementaryPositivity.QuantumTorus +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/QuotientAlg.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/QuotientAlg.lean new file mode 100644 index 0000000000000000000000000000000000000000..bca392f58ee20d82d72af644773ec9d18b50bf78 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/QuotientAlg.lean @@ -0,0 +1,241 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.ReynoldsS +import OAI.Combinatorics.Chromatic.Walls.Taylor + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.CommonTranslation +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable instance quotientCommRing (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + CommRing (B a μ d) := inferInstanceAs (CommRing (S d ⧸ destabilizingIdeal a μ d)) +noncomputable instance quotientAlgebra (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + Algebra ℚ (B a μ d) := inferInstanceAs (Algebra ℚ (S d ⧸ destabilizingIdeal a μ d)) + +noncomputable def quotientAlg (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + S d →ₐ[ℚ] B a μ d := Ideal.Quotient.mkₐ ℚ (destabilizingIdeal a μ d) + +@[simp] lemma quotientAlg_apply (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (f : S d) : + quotientAlg a μ d f = (destabilizingSpace a μ d).mkQ f := rfl + +noncomputable def tensorValueAlg (d e : I → ℕ) : + S d ⊗[ℚ] S e →ₐ[ℚ] MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ := + (tensorEquivSum ℚ _ _ ℚ).toAlgHom.comp + (Algebra.TensorProduct.map (symmetricSpace d).val (symmetricSpace e).val) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma tensorValueAlg_apply (d e : I → ℕ) (f : S d ⊗[ℚ] S e) : + tensorValueAlg d e f = tensorValue d e f := rfl + +omit [Fintype I] [DecidableEq I] in +lemma tensorValue_mul (d e : I → ℕ) (f g : S d ⊗[ℚ] S e) : + tensorValue d e (f*g) = tensorValue d e f * tensorValue d e g := + (tensorValueAlg d e).map_mul f g + +noncomputable def restrictTensorAlg {d e : I → ℕ} (A : Cut d e) : S (d+e) →ₐ[ℚ] S d ⊗[ℚ] S e where + toFun := restrictTensor A + map_zero' := map_zero _ + map_add' := map_add _ + map_one' := by + apply tensorValue_injective + rw [tensorValue_restrictTensor] + change rename (cutSplit A).symm 1 = tensorValueAlg d e 1 + exact (map_one (rename (R:=ℚ) (cutSplit A).symm)).trans + (map_one (tensorValueAlg d e)).symm + map_mul' f g := by + apply tensorValue_injective + rw [tensorValue_restrictTensor,tensorValue_mul,tensorValue_restrictTensor,tensorValue_restrictTensor] + exact map_mul _ _ _ + commutes' q := by + apply tensorValue_injective + rw [tensorValue_restrictTensor] + change rename (cutSplit A).symm (algebraMap ℚ _ q) = + tensorValueAlg d e (algebraMap ℚ _ q) + rw [(tensorValueAlg d e).commutes,(rename (cutSplit A).symm).commutes] + +omit [Fintype I] [DecidableEq I] in +lemma taylorS_exists (d : I → ℕ) (f : S d) : + ∃ q : Polynomial (S d), Polynomial.map (symmetricSpace d).val.toRingHom q = taylor f.val := by + apply (Polynomial.mem_lifts _).mp + apply (Polynomial.lifts_iff_coeff_lifts _).mpr + intro n + have h : (taylor f.val).coeff n ∈ (symmetricSpace d).toSubmodule := by + apply polynomial_coeff_mem (symmetricSpace d).toSubmodule (taylor f.val) + intro t + change (taylor f.val).eval (C t) ∈ (symmetricSpace d).toSubmodule + rw [taylor_eval] + exact translation_symmetric t f.val f.property + exact ⟨⟨_,h⟩,rfl⟩ + +noncomputable def taylorSValue (d : I → ℕ) (f : S d) : Polynomial (S d) := + (taylorS_exists d f).choose + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma map_taylorSValue (d : I → ℕ) (f : S d) : + Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d f) = taylor f.val := + (taylorS_exists d f).choose_spec + +omit [Fintype I] [DecidableEq I] in +lemma polynomial_symmetric_injective (d : I → ℕ) : + Function.Injective (Polynomial.map (symmetricSpace d).val.toRingHom) := + Polynomial.map_injective _ Subtype.val_injective + +noncomputable def taylorS (d : I → ℕ) : S d →ₐ[ℚ] Polynomial (S d) where + toFun := taylorSValue d + map_zero' := by + apply polynomial_symmetric_injective d + change Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d 0) = + Polynomial.map (symmetricSpace d).val.toRingHom 0 + exact (map_taylorSValue d 0).trans (by simp) + map_one' := by + apply polynomial_symmetric_injective d + change Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d 1) = + Polynomial.map (symmetricSpace d).val.toRingHom 1 + exact (map_taylorSValue d 1).trans (by simp) + map_add' f g := by + apply polynomial_symmetric_injective d + rw [Polynomial.map_add] + change Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d (f+g)) = + Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d f) + + Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d g) + rw [map_taylorSValue,map_taylorSValue,map_taylorSValue] + exact map_add _ _ _ + map_mul' f g := by + apply polynomial_symmetric_injective d + rw [Polynomial.map_mul] + change Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d (f*g)) = + Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d f) * + Polynomial.map (symmetricSpace d).val.toRingHom (taylorSValue d g) + rw [map_taylorSValue,map_taylorSValue,map_taylorSValue] + exact map_mul _ _ _ + commutes' q := by + apply polynomial_symmetric_injective d + change Polynomial.map (symmetricSpace d).val.toRingHom + (taylorSValue d (algebraMap ℚ (S d) q)) = + Polynomial.map (symmetricSpace d).val.toRingHom (Polynomial.C (algebraMap ℚ (S d) q)) + rw [map_taylorSValue,Polynomial.map_C] + change taylor (C q : MvPolynomial (Σi,Fin (d i)) ℚ) = Polynomial.C (C q) + exact taylor_C q + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma map_taylorS (d : I → ℕ) (f : S d) : + Polynomial.map (symmetricSpace d).val.toRingHom (taylorS d f) = taylor f.val := + map_taylorSValue d f + +omit [Fintype I] [DecidableEq I] in +lemma taylorS_eval (d : I → ℕ) (f : S d) (t : ℚ) : + (taylorS d f).eval (algebraMap ℚ (S d) t) = translationS d t f := by + apply Subtype.ext + have h := congrArg (fun p : Polynomial (MvPolynomial (Σi,Fin (d i)) ℚ) => + p.eval (C t)) (map_taylorS d f) + rw [taylor_eval] at h + change (symmetricSpace d).val ((taylorS d f).eval (algebraMap ℚ (S d) t)) = + translation t f.val + calc + _ = (Polynomial.map (symmetricSpace d).val.toRingHom (taylorS d f)).eval (C t) := by + rw [Polynomial.eval_map] + exact (Polynomial.eval₂_at_apply (symmetricSpace d).val.toRingHom (algebraMap ℚ (S d) t)).symm + _ = translation t f.val := h + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.CommonTranslation +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma taylorS_coeff_destabilizing (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) {f : S d} (hf : f ∈ destabilizingSpace a μ d) (n : ℕ) : + (taylorS d f).coeff n ∈ destabilizingSpace a μ d := by + apply polynomial_coeff_mem (destabilizingSpace a μ d) (taylorS d f) + intro t + rw [taylorS_eval] + exact translation_destabilizing a μ d t hf + +noncomputable def taylorB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + B a μ d →ₐ[ℚ] Polynomial (B a μ d) := + Ideal.Quotient.liftₐ (destabilizingIdeal a μ d) + ((Polynomial.mapAlgHom (quotientAlg a μ d)).comp (taylorS d)) (by + intro f hf + apply Polynomial.ext + intro n + change (Polynomial.map (quotientAlg a μ d).toRingHom (taylorS d f)).coeff n = (0 : Polynomial (B a μ d)).coeff n + rw [Polynomial.coeff_map,Polynomial.coeff_zero] + exact Ideal.Quotient.eq_zero_iff_mem.mpr (taylorS_coeff_destabilizing a μ d hf n)) + +@[simp] lemma taylorB_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (f : S d) : + taylorB a μ d (quotientAlg a μ d f) = Polynomial.map (quotientAlg a μ d).toRingHom (taylorS d f) := rfl + +lemma eval_map_rat {R T : Type*} [Semiring R] [Semiring T] [Algebra ℚ R] [Algebra ℚ T] + (φ : R →ₐ[ℚ] T) (p : Polynomial R) (t : ℚ) : + (Polynomial.map φ.toRingHom p).eval (algebraMap ℚ T t) = + φ (p.eval (algebraMap ℚ R t)) := by + rw [Polynomial.eval_map] + calc + _ = Polynomial.eval₂ φ.toRingHom (φ (algebraMap ℚ R t)) p := + congrArg (fun x => Polynomial.eval₂ φ.toRingHom x p) (φ.commutes t).symm + _ = _ := Polynomial.eval₂_at_apply φ.toRingHom (algebraMap ℚ R t) + +noncomputable def relativeTaylor (d e : I → ℕ) : + S d ⊗[ℚ] S e →ₐ[ℚ] Polynomial (S d ⊗[ℚ] S e) := + let L : S d →ₐ[ℚ] Polynomial (S d ⊗[ℚ] S e) := + (Polynomial.mapAlgHom (Algebra.TensorProduct.includeLeft : S d →ₐ[ℚ] S d ⊗[ℚ] S e)).comp (taylorS d) + let R : S e →ₐ[ℚ] Polynomial (S d ⊗[ℚ] S e) := + Polynomial.CAlgHom.comp (Algebra.TensorProduct.includeRight : S e →ₐ[ℚ] S d ⊗[ℚ] S e) + Algebra.TensorProduct.lift (S:=ℚ) L R (fun x y => (mul_comm (L x) (R y))) + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma relativeTaylor_tmul (d e : I → ℕ) (f : S d) (g : S e) : + relativeTaylor d e (f ⊗ₜ[ℚ] g) = + Polynomial.map (Algebra.TensorProduct.includeLeft : S d →ₐ[ℚ] S d ⊗[ℚ] S e).toRingHom (taylorS d f) * + Polynomial.C ((1 : S d) ⊗ₜ[ℚ] g) := by + simp only [relativeTaylor] + rfl + +noncomputable def quotientTensor (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + S d ⊗[ℚ] S e →ₐ[ℚ] B a μ d ⊗[ℚ] B a μ e := + Algebra.TensorProduct.map (quotientAlg a μ d) (quotientAlg a μ e) + +noncomputable def restrictRelative (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (A : Cut d e) : + S (d+e) →ₐ[ℚ] Polynomial (B a μ d ⊗[ℚ] B a μ e) := + (Polynomial.mapAlgHom (quotientTensor a μ d e)).comp + ((relativeTaylor d e).comp (restrictTensorAlg A)) + +omit [Fintype I] [DecidableEq I] in +lemma relativeTaylor_eval (d e : I → ℕ) (f : S d ⊗[ℚ] S e) (t : ℚ) : + (relativeTaylor d e f).eval (algebraMap ℚ (S d ⊗[ℚ] S e) t) = + TensorProduct.map (translationS d t) (LinearMap.id : S e →ₗ[ℚ] S e) f := by + induction f using TensorProduct.inductionOn with + | tmul f g => + rw [relativeTaylor_tmul,Polynomial.eval_mul,Polynomial.eval_C, + eval_map_rat (R := S d) (T := S d ⊗[ℚ] S e) (Algebra.TensorProduct.includeLeft : S d →ₐ[ℚ] S d ⊗[ℚ] S e),taylorS_eval] + simp + | add f g hf hg => rw [map_add,Polynomial.eval_add,map_add,hf,hg] + +lemma restrictRelative_eval (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (A : Cut d e) (f : S (d+e)) (t : ℚ) : + (restrictRelative a μ A f).eval (algebraMap ℚ (B a μ d ⊗[ℚ] B a μ e) t) = + restrictQuotientAt a μ A t 0 f := by + change (Polynomial.map (quotientTensor a μ d e).toRingHom + (relativeTaylor d e (restrictTensor A f))).eval _ = _ + rw [eval_map_rat (R := S d ⊗[ℚ] S e) (T := B a μ d ⊗[ℚ] B a μ e) (quotientTensor a μ d e),relativeTaylor_eval] + change quotientTensor a μ d e (TensorProduct.map (translationS d t) LinearMap.id (restrictTensor A f)) = + TensorProduct.map + ((destabilizingSpace a μ d).mkQ ∘ₗ translationS d t) + ((destabilizingSpace a μ e).mkQ ∘ₗ translationS e 0) (restrictTensor A f) + generalize restrictTensor A f = x + induction x using TensorProduct.inductionOn with + | tmul x y => simp [quotientTensor] + | add x y hx hy => simp_all + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/RawGradedAlgebra.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/RawGradedAlgebra.lean new file mode 100644 index 0000000000000000000000000000000000000000..67a01c9cd584b88bdf30350c3604725f85b39d42 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/RawGradedAlgebra.lean @@ -0,0 +1,153 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.HNSpanning +import OAI.Combinatorics.Chromatic.Shuffle.ShuffleUnits +import OAI.Combinatorics.Chromatic.GradedAlgebra.GradedBuilders + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped DirectSum +variable {I : Type*} [Fintype I] [DecidableEq I] + +def rawComponent (_a : I → I → ℕ) (d : I → ℕ) := S d +noncomputable instance (a : I → I → ℕ) (d : I → ℕ) : AddCommGroup (rawComponent a d) := + inferInstanceAs (AddCommGroup (S d)) +noncomputable instance (a : I → I → ℕ) (d : I → ℕ) : Module ℚ (rawComponent a d) := + inferInstanceAs (Module ℚ (S d)) + +noncomputable instance rawGradedMul (a : I → I → ℕ) : GradedMonoid.GMul (rawComponent a) where + mul f g := shufflePolynomial a f g +noncomputable instance rawGradedOne (a : I → I → ℕ) : GradedMonoid.GOne (rawComponent a) where + one := (1 : S (0 : I → ℕ)) + +omit [Fintype I] [DecidableEq I] in +lemma castS_heq {d e : I → ℕ} (h : d=e) (f : S d) : HEq (castS h f) f := by + subst e + rfl + +lemma raw_one_mul (a : I → I → ℕ) (x : GradedMonoid (rawComponent a)) : 1*x=x := by + apply Sigma.ext (zero_add _) + exact (heq_of_eq (shufflePolynomial_unit_left a x.1 x.2)).trans (castS_heq _ _) +lemma raw_mul_one (a : I → I → ℕ) (x : GradedMonoid (rawComponent a)) : x*1=x := by + apply Sigma.ext (add_zero _) + exact (heq_of_eq (shufflePolynomial_unit_right a x.1 x.2)).trans (castS_heq _ _) +lemma raw_mul_assoc (a : I → I → ℕ) (x y z : GradedMonoid (rawComponent a)) : x*y*z=x*(y*z) := by + apply Sigma.ext (add_assoc _ _ _) + exact (castS_heq (add_assoc x.1 y.1 z.1) _).symm.trans (heq_of_eq (shufflePolynomial_assoc a x.2 y.2 z.2)) +noncomputable instance rawGradedMonoid (a : I → I → ℕ) : GradedMonoid.GMonoid (rawComponent a) := + gradedMonoidOfLaws (raw_one_mul a) (raw_mul_one a) (raw_mul_assoc a) +noncomputable instance rawGradedRing (a : I → I → ℕ) : DirectSum.GRing (rawComponent a) := + gradedRingOfAddLaws (fun _=>shufflePolynomial_zero_right a _ _ _) + (fun _=>shufflePolynomial_zero_left a _ _ _) + (fun _ _ _=>shufflePolynomial_add_right a _ _ _) + (fun _ _ _=>shufflePolynomial_add_left a _ _ _) +lemma raw_smul_mul (a : I → I → ℕ) (r : ℚ) (x y : GradedMonoid (rawComponent a)) : + (r•x)*y=r•(x*y) := by + apply Sigma.ext (show x.1+y.1=x.1+y.1 from rfl) + exact heq_of_eq (shufflePolynomial_smul_left a r x.2 y.2) +lemma raw_mul_smul (a : I → I → ℕ) (r : ℚ) (x y : GradedMonoid (rawComponent a)) : + x*(r•y)=r•(x*y) := by + apply Sigma.ext (show x.1+y.1=x.1+y.1 from rfl) + exact heq_of_eq (shufflePolynomial_smul_right a r x.2 y.2) +noncomputable instance rawGradedAlgebra (a : I → I → ℕ) : DirectSum.GAlgebra ℚ (rawComponent a) := + gradedAlgebraOfBilinear (raw_smul_mul a) (raw_mul_smul a) + +abbrev RawAlgebra (a : I → I → ℕ) := ⨁ d : I → ℕ,rawComponent a d +noncomputable def rawLof (a : I → I → ℕ) (d : I → ℕ) : S d →ₗ[ℚ] RawAlgebra a := + DirectSum.lof ℚ _ (rawComponent a) d +lemma rawLof_mul (a : I → I → ℕ) (d e : I → ℕ) (x : S d) (y : S e) : + rawLof a d x*rawLof a e y=rawLof a (d+e) (shufflePolynomial a x y) := by + exact DirectSum.of_mul_of (A:=rawComponent a) x y +omit [DecidableEq I] in +lemma rawLof_cast (a : I → I → ℕ) {d e : I → ℕ} (h : d=e) (x : S d) : + rawLof a e (castS h x)=rawLof a d x := by subst e; rfl + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) +noncomputable def rawDimensionSpace (d : I → ℕ) : Submodule ℚ (RawAlgebra a) := + LinearMap.range (rawLof a d) +noncomputable def rawSectionSpace + (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (d : I → ℕ) : Submodule ℚ (RawAlgebra a) := + LinearMap.range ((rawLof a d).comp (σ d)) +lemma rawSectionSpace_le (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) (d : I → ℕ) : + rawSectionSpace a c η σ d ≤ rawDimensionSpace a d := by + rintro _ ⟨x,rfl⟩ + exact ⟨σ d x,rfl⟩ +lemma rawDimensionSpace_mul (d e : I → ℕ) : + rawDimensionSpace a d*rawDimensionSpace a e ≤ rawDimensionSpace a (d+e) := by + apply Submodule.mul_le.mpr + rintro _ ⟨x,rfl⟩ _ ⟨y,rfl⟩ + exact ⟨shufflePolynomial a x y,(rawLof_mul a d e x y).symm⟩ +lemma rawDimensionSpace_zero : rawDimensionSpace a 0 ≤ 1 := by + rintro _ ⟨x,rfl⟩ + rw [S_zero_eq_scalar x,map_smul] + change MvPolynomial.constantCoeff x.val • (1 : RawAlgebra a) ∈ (1 : Submodule ℚ _) + exact Submodule.smul_mem _ _ (Submodule.one_le.mp le_rfl) + +variable (σ : ∀ d,B a (slope c η) d →ₗ[ℚ] S d) +variable (hσ : ∀ d,Function.RightInverse (σ d) (destabilizingSpace a (slope c η) d).mkQ) +include hσ in +lemma rawDimensionSpace_decompose (d : I → ℕ) (_hd : d≠0) : + rawDimensionSpace a d ≤ rawSectionSpace a c η σ d ⊔ + ⨆ (u : I → ℕ) (v : I → ℕ) (_ : u+v=d) (_ : u≠0) (_ : v≠0) + (_ : slope c η d < slope c η u),rawDimensionSpace a u*rawDimensionSpace a v := by + let Q := destabilizingSpace a (slope c η) d + let U : Submodule ℚ (RawAlgebra a) := + ⨆ (u : I → ℕ) (v : I → ℕ) (_ : u+v=d) (_ : u≠0) (_ : v≠0) + (_ : slope c η d < slope c η u),rawDimensionSpace a u*rawDimensionSpace a v + have hQ : Q ≤ U.comap (rawLof a d) := by + apply Submodule.span_le.mpr + rintro f ⟨u,v,h,x,y,hu,hv,hμ,rfl⟩ + change rawLof a d (dimensionCast h (shufflePolynomial a x y)) ∈ U + have hc : dimensionCast h (shufflePolynomial a x y)=castS h (shufflePolynomial a x y) := by + subst d; rfl + rw [hc,rawLof_cast,←rawLof_mul] + have hi : rawDimensionSpace a u*rawDimensionSpace a v ≤ U := + le_iSup_of_le u (le_iSup_of_le v (le_iSup_of_le h + (le_iSup_of_le hu (le_iSup_of_le hv (le_iSup_of_le hμ le_rfl))))) + apply hi + exact Submodule.mul_mem_mul (show rawLof a u x∈rawDimensionSpace a u from ⟨x,rfl⟩) + (show rawLof a v y∈rawDimensionSpace a v from ⟨y,rfl⟩) + rintro _ ⟨f,rfl⟩ + have hm : f-σ d (Q.mkQ f)∈Q := by + apply (Submodule.Quotient.mk_eq_zero Q).mp + change Q.mkQ (f-σ d (Q.mkQ f))=0 + rw [map_sub,hσ d,sub_self] + have hleft : rawLof a d (σ d (Q.mkQ f))∈rawSectionSpace a c η σ d := ⟨Q.mkQ f,rfl⟩ + have hright : rawLof a d (f-σ d (Q.mkQ f))∈U := hQ hm + have hh := Submodule.add_mem_sup hleft hright + simpa only [map_sub,add_sub_cancel] using hh + +include hσ in + +theorem raw_hn_spanning (hc : ∀ i,0 < c i) (d : I → ℕ) : + rawDimensionSpace a d ≤ hnOrderedSpan c η (rawSectionSpace a c η σ) d := + hn_spanning c η (rawSectionSpace a c η σ) hc (rawDimensionSpace a) + (rawSectionSpace_le a c η σ) (rawDimensionSpace_mul a) (rawDimensionSpace_zero a) + (rawDimensionSpace_decompose a c η σ hσ) d + +noncomputable def quotientSection (d : I → ℕ) : B a (slope c η) d →ₗ[ℚ] S d := + Classical.choose ((destabilizingSpace a (slope c η) d).mkQ.exists_rightInverse_of_surjective + (Submodule.range_mkQ _)) +lemma quotientSection_rightInverse (d : I → ℕ) : + Function.RightInverse (quotientSection a c η d) (destabilizingSpace a (slope c η) d).mkQ := by + have h := Classical.choose_spec ((destabilizingSpace a (slope c η) d).mkQ.exists_rightInverse_of_surjective + (Submodule.range_mkQ _)) + intro x + exact LinearMap.congr_fun h x + +theorem actual_raw_hn_spanning (hc : ∀ i,0 < c i) (d : I → ℕ) : + rawDimensionSpace a d ≤ hnOrderedSpan c η (rawSectionSpace a c η (quotientSection a c η)) d := + raw_hn_spanning a c η (quotientSection a c η) (quotientSection_rightInverse a c η) hc d +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/Realization.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/Realization.lean new file mode 100644 index 0000000000000000000000000000000000000000..869b4fdfc4134217ff5386e3dade33b803063010 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/Realization.lean @@ -0,0 +1,300 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.CellVars +import OAI.Combinatorics.Chromatic.Walls.Pack + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,DecidableEq (A i)] + +abbrev Realization (d : I → ℕ) (s : ∀ i,Finset (A i)) := ∀ i,Fin (d i) ≃ s i + +def realizationMap {d : I → ℕ} {s : ∀ i,Finset (A i)} (r : Realization d s) : + (Σi,Fin (d i)) → (Σi,A i) := fun x => ⟨x.1,r x.1 x.2⟩ + +omit [Fintype I] [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma realizationMap_injective {d : I → ℕ} {s : ∀ i,Finset (A i)} (r : Realization d s) : + Function.Injective (realizationMap r) := by + exact (Function.Embedding.sigmaMap (Function.Embedding.refl I) + (fun i => (r i).toEmbedding.trans (Function.Embedding.subtype _))).injective + +omit [Fintype I] [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma rename_realization_independent {d : I → ℕ} {s : ∀ i,Finset (A i)} + (r t : Realization d s) (f : S d) : + rename (realizationMap r) f.val = rename (realizationMap t) f.val := by + let σ : ∀ i,Equiv.Perm (Fin (d i)) := fun i => (r i).trans (t i).symm + have he : realizationMap t ∘ packAction (fun i => Fin (d i)) σ = realizationMap r := by + funext ⟨i,x⟩ + change (⟨i,↑(t i (σ i x))⟩ : Σi,A i) = ⟨i,↑(r i x)⟩ + simp [σ] + rw [← he, ← rename_rename, f.property σ] + +noncomputable def valueAt {d : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization d s) (f : S d) : FractionRing (MvPolynomial (Σi,A i) ℚ) := + algebraMap _ _ (rename (realizationMap r) f.val) + +omit [Fintype I] [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma valueAt_independent {d : I → ℕ} {s : ∀ i,Finset (A i)} + (r t : Realization d s) (f : S d) : valueAt r f = valueAt t f := by + rw [valueAt,valueAt,rename_realization_independent] + +noncomputable def defaultRealization {d : I → ℕ} {s : ∀ i,Finset (A i)} + (h : ∀ i,(s i).card = d i) : Realization d s := fun i => + Fintype.equivOfCardEq (by simp [h i]) + +noncomputable def labeledValue {d : I → ℕ} (f : S d) (s : ∀ i,Finset (A i)) : + FractionRing (MvPolynomial (Σi,A i) ℚ) := + if h : ∀ i,(s i).card = d i then valueAt (defaultRealization h) f else 0 + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma labeledValue_eq {d : I → ℕ} {s : ∀ i,Finset (A i)} (r : Realization d s) (f : S d) : + labeledValue f s = valueAt r f := by + have h : ∀ i,(s i).card = d i := by + intro i + simpa using (Fintype.card_congr (r i)).symm + rw [labeledValue, dite_eq_left h, valueAt_independent _ r] + +omit [∀ i,DecidableEq (A i)] in +lemma valueAt_shuffle (a : I → I → ℕ) {d e : I → ℕ} + (s : ∀ i,Finset (A i)) (r : Realization (d+e) s) (f : S d) (g : S e) : + valueAt r (shufflePolynomial a f g) = + renameInjFraction (realizationMap r) (realizationMap_injective r) (rawShuffle a f.val g.val) := by + rw [← shufflePolynomial_eq] + exact (renameInjFraction_algebraMap (realizationMap r) (realizationMap_injective r) + (shufflePolynomial a f g).val).symm + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,DecidableEq (A i)] + +abbrev SizedCut (d : I → ℕ) (s : ∀ i,Finset (A i)) := + {p : PackConvolution.Cut s // ∀ i,(PackConvolution.left p i).card = d i} + +noncomputable def cutRealizationEquiv {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) : Cut d e ≃ SizedCut d s := + (Equiv.piCongrRight fun i => PackEnumeration.sizedSplitEquiv (r i) (d i)).trans + Equiv.subtypePiEquivPi.symm + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma cutRealizationEquiv_left {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) (t : Cut d e) (i : I) : + PackConvolution.left (cutRealizationEquiv r t).val i = + (t i).val.map (PackEnumeration.embedding (r i)) := rfl +omit [Fintype I] [DecidableEq I] in +@[simp] lemma cutRealizationEquiv_right {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) (t : Cut d e) (i : I) : + PackConvolution.right (cutRealizationEquiv r t).val i = + (t i).valᶜ.map (PackEnumeration.embedding (r i)) := rfl + +noncomputable def leftRealization {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) (t : Cut d e) : + Realization d (PackConvolution.left (cutRealizationEquiv r t).val) := + fun i => (leftEnum t i).trans (PackEnumeration.mapEquiv + (PackEnumeration.embedding (r i)) (t i).val) + +noncomputable def rightRealization {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) (t : Cut d e) : + Realization e (PackConvolution.right (cutRealizationEquiv r t).val) := + fun i => (rightEnum t i).trans (PackEnumeration.mapEquiv + (PackEnumeration.embedding (r i)) (t i).valᶜ) + +omit [Fintype I] [DecidableEq I] in +lemma leftRealization_map {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) (t : Cut d e) : + realizationMap (leftRealization r t) = realizationMap r ∘ leftInput t := rfl +omit [Fintype I] [DecidableEq I] in +lemma rightRealization_map {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) (t : Cut d e) : + realizationMap (rightRealization r t) = realizationMap r ∘ rightInput t := rfl + +omit [DecidableEq I] in +lemma labeledValue_left {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) (t : Cut d e) (f : S d) : + labeledValue f (PackConvolution.left (cutRealizationEquiv r t).val) = + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) + (rename (realizationMap r) (rename (leftInput t) f.val)) := by + rw [labeledValue_eq (leftRealization r t),valueAt,leftRealization_map,rename_rename] +omit [DecidableEq I] in +lemma labeledValue_right {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (r : Realization (d+e) s) (t : Cut d e) (g : S e) : + labeledValue g (PackConvolution.right (cutRealizationEquiv r t).val) = + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) + (rename (realizationMap r) (rename (rightInput t) g.val)) := by + rw [labeledValue_eq (rightRealization r t),valueAt,rightRealization_map,rename_rename] + +noncomputable def pairKernel (a : I → I → ℕ) (x y : Σi,A i) : + FractionRing (MvPolynomial (Σi,A i) ℚ) := + let v := algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (diagonal x y) + v^(a x.1 y.1) / if x.1 = y.1 then v else 1 + +omit [∀ i,DecidableEq (A i)] in +lemma kernel_formula (a : I → I → ℕ) (s t : ∀ i,Finset (A i)) : + PackConvolution.kernel (pairKernel a) s t = + (∏ i,∏ j,∏ x ∈ s i,∏ y ∈ t j, + (algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (diagonal (⟨i,x⟩ : Σi,A i) ⟨j,y⟩))^(a i j)) / + (∏ i,∏ x ∈ s i,∏ y ∈ t i, + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (diagonal (⟨i,x⟩ : Σi,A i) ⟨i,y⟩)) := by + simp only [PackConvolution.kernel,pairKernel,Finset.prod_div_distrib] + congr 1 + · apply Finset.prod_congr rfl + intro i hi + exact Finset.prod_comm + · apply Finset.prod_congr rfl + intro i hi + apply Finset.prod_congr rfl + intro x hx + rw [Finset.prod_eq_single i] + · simp + · intro j hj hji + simp only [ite_eq_right (Ne.symm hji),Finset.prod_const_one] + · simp + +lemma mapped_cut_kernel (a : I → I → ℕ) {d e : I → ℕ} + {s : ∀ i,Finset (A i)} (r : Realization (d+e) s) (t : Cut d e) : + PackConvolution.kernel (pairKernel a) + (PackConvolution.left (cutRealizationEquiv r t).val) + (PackConvolution.right (cutRealizationEquiv r t).val) = + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) + (rename (realizationMap r) (∏ i,∏ j,cutFactor t i j (a i j))) / + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) + (rename (realizationMap r) (cutDenominator t)) := by + rw [kernel_formula] + simp only [cutRealizationEquiv_left,cutRealizationEquiv_right, + Finset.prod_map,cutFactor,cutDenominator,map_prod,map_pow,diagonal,map_sub,rename_X,pow_one] + rfl + +variable [∀ i,Fintype (A i)] + +lemma valueAt_shuffle_sum (a : I → I → ℕ) {d e : I → ℕ} + {s : ∀ i,Finset (A i)} (r : Realization (d+e) s) (f : S d) (g : S e) : + valueAt r (shufflePolynomial a f g) = + ∑ p : SizedCut d s, labeledValue f (PackConvolution.left p.val) * + labeledValue g (PackConvolution.right p.val) * + PackConvolution.kernel (pairKernel a) + (PackConvolution.left p.val) (PackConvolution.right p.val) := by + classical + rw [valueAt_shuffle a s r, ← (cutRealizationEquiv r).sum_comp] + simp only [rawShuffle,map_sum,map_div₀] + apply Finset.sum_congr rfl + intro t ht + rw [labeledValue_left,labeledValue_right,mapped_cut_kernel] + have hn := renameInjFraction_algebraMap (α := Σi,Fin (d i+e i)) (realizationMap r) (realizationMap_injective r) + (cutNumerator a t f.val g.val) + have hd := renameInjFraction_algebraMap (α := Σi,Fin (d i+e i)) (realizationMap r) (realizationMap_injective r) + (cutDenominator t) + rw [hn,hd] + simp only [cutNumerator,map_mul] + rw [mul_div_assoc] + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +lemma cut_right_card {d e : I → ℕ} {s : ∀ i,Finset (A i)} + (hs : ∀ i,(s i).card = (d+e) i) (p : SizedCut d s) : + ∀ i,(PackConvolution.right p.val i).card = e i := by + intro i + have h := Finset.card_union_of_disjoint (p.val i).property.1 + rw [(p.val i).property.2, hs i] at h + have hl := p.property i + change (p.val i).val.1.card = d i at hl + change (p.val i).val.2.card = e i + simp only [Pi.add_apply] at h + omega + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +lemma cut_card_add {d e : I → ℕ} {s : ∀ i,Finset (A i)} (p : PackConvolution.Cut s) + (hl : ∀ i,(PackConvolution.left p i).card = d i) + (hr : ∀ i,(PackConvolution.right p i).card = e i) : + ∀ i,(s i).card = (d+e) i := by + intro i + have h := Finset.card_union_of_disjoint (p i).property.1 + rw [(p i).property.2] at h + exact h.trans (congrArg₂ (·+·) (hl i) (hr i)) + +lemma pack_shuffle_sum (a : I → I → ℕ) {d e : I → ℕ} + (s : ∀ i,Finset (A i)) (f : S d) (g : S e) : + PackConvolution.shuffle (pairKernel a) (labeledValue f) (labeledValue g) s = + ∑ p : SizedCut d s, labeledValue f (PackConvolution.left p.val) * + labeledValue g (PackConvolution.right p.val) * + PackConvolution.kernel (pairKernel a) + (PackConvolution.left p.val) (PackConvolution.right p.val) := by + classical + unfold PackConvolution.shuffle + rw [← Fintype.sum_subtype_add_sum_subtype + (fun p : PackConvolution.Cut s => ∀ i,(PackConvolution.left p i).card = d i)] + suffices hz : (∑ p : {p : PackConvolution.Cut s // + ¬ ∀ i,(PackConvolution.left p i).card = d i}, + labeledValue f (PackConvolution.left p.val) * labeledValue g (PackConvolution.right p.val) * + PackConvolution.kernel (pairKernel a) + (PackConvolution.left p.val) (PackConvolution.right p.val)) = 0 by + rw [hz,add_zero] + apply Finset.sum_eq_zero + intro p hp + rw [labeledValue,dite_eq_right p.property,zero_mul,zero_mul] + +lemma labeledValue_shuffle (a : I → I → ℕ) {d e : I → ℕ} (f : S d) (g : S e) : + labeledValue (A := A) (shufflePolynomial a f g) = + PackConvolution.shuffle (pairKernel a) (labeledValue f) (labeledValue g) := by + classical + funext s + by_cases hs : ∀ i,(s i).card = (d+e) i + · rw [labeledValue_eq (defaultRealization hs),valueAt_shuffle_sum,pack_shuffle_sum] + · rw [labeledValue,dite_eq_right hs,PackConvolution.shuffle] + symm + apply Finset.sum_eq_zero + intro p hp + by_cases hl : ∀ i,(PackConvolution.left p i).card = d i + · have hr : ¬ ∀ i,(PackConvolution.right p i).card = e i := by + intro hh + exact hs (cut_card_add p hl hh) + simp only [labeledValue,dite_eq_right hr,mul_zero,zero_mul] + · simp only [labeledValue,dite_eq_right hl,zero_mul,zero_mul] + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma valueAt_injective {d : I → ℕ} {s : ∀ i,Finset (A i)} (r : Realization d s) : + Function.Injective (valueAt r) := by + intro f g h + apply Subtype.ext + apply MvPolynomial.rename_injective (realizationMap r) (realizationMap_injective r) + exact IsFractionRing.injective (MvPolynomial (Σi,A i) ℚ) _ h + +omit [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma labeledValue_injective {d : I → ℕ} {s : ∀ i,Finset (A i)} (r : Realization d s) : + Function.Injective (fun f : S d => labeledValue f s) := by + intro f g hh + apply valueAt_injective r + simpa only [labeledValue_eq r] using hh + +def castS {d e : I → ℕ} (h : d=e) (f : S d) : S e := h ▸ f + +omit [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma labeledValue_cast {d e : I → ℕ} (h : d=e) (f : S d) : + labeledValue (A := A) (castS h f) = labeledValue f := by + subst e + rfl + +theorem shufflePolynomial_assoc (a : I → I → ℕ) {d e b : I → ℕ} + (f : S d) (g : S e) (h : S b) : + castS (add_assoc d e b) (shufflePolynomial a (shufflePolynomial a f g) h) = + shufflePolynomial a f (shufflePolynomial a g h) := by + classical + let s : ∀ i,Finset (Fin ((d+(e+b)) i)) := fun _ => Finset.univ + let r : Realization (d+(e+b)) s := defaultRealization (by intro i; simp [s]) + apply labeledValue_injective r + dsimp only + rw [labeledValue_cast,labeledValue_shuffle,labeledValue_shuffle, + labeledValue_shuffle,labeledValue_shuffle] + exact congrFun (PackConvolution.shuffle_assoc (pairKernel a) + (labeledValue f) (labeledValue g) (labeledValue h)) s + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/Regroup.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/Regroup.lean new file mode 100644 index 0000000000000000000000000000000000000000..d520d1d1da2ac46f5af3f552f6bf1717a20ce959 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/Regroup.lean @@ -0,0 +1,169 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Interaction +import OAI.Combinatorics.Chromatic.Shuffle.DimensionEquivS + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +inductive Regroup : SplitTree I → SplitTree I → Type u + | refl (T) : Regroup T T + | assoc (T U V) : Regroup (.node (.node T U) V) (.node T (.node U V)) + | swap (T U) : Regroup (.node T U) (.node U T) + | node {T U V W} : Regroup T U → Regroup V W → Regroup (.node T V) (.node U W) + | trans {T U V} : Regroup T U → Regroup U V → Regroup T V + +namespace Regroup +noncomputable def vars {T U : SplitTree I} : Regroup T U → T.Vars ≃ U.Vars + | .refl _ => Equiv.refl _ + | .assoc _ _ _ => Equiv.sumAssoc _ _ _ + | .swap _ _ => Equiv.sumComm _ _ + | .node f g => Equiv.sumCongr f.vars g.vars + | .trans f g => f.vars.trans g.vars + +omit [Fintype I] [DecidableEq I] in +lemma pack {T U : SplitTree I} (e : Regroup T U) (x : T.Vars) : + U.packIndex (e.vars x)=T.packIndex x := by + induction e with + | refl T => rfl + | assoc T U V => rcases x with (x|x)|x <;> rfl + | swap T U => cases x <;> rfl + | node f g ihf ihg => cases x with + | inl x => exact ihf x + | inr x => exact ihg x + | trans f g ihf ihg => exact (ihg (f.vars x)).trans (ihf x) + +omit [Fintype I] [DecidableEq I] in +lemma dimension {T U : SplitTree I} (e : Regroup T U) : T.dim=U.dim := by + induction e with + | refl T => rfl + | assoc T U V => exact add_assoc _ _ _ + | swap T U => exact add_comm _ _ + | node f g ihf ihg => exact congrArg₂ (·+·) ihf ihg + | trans f g ihf ihg => exact ihf.trans ihg + +noncomputable def equivalence (A : (I → ℕ) → CommAlgCat.{u} ℚ) + {T U : SplitTree I} : Regroup T U → tensor A T ≃ₐ[ℚ] tensor A U + | .refl _ => AlgEquiv.refl + | .assoc T U V => Algebra.TensorProduct.assoc ℚ ℚ ℚ (tensor A T) (tensor A U) (tensor A V) + | .swap T U => Algebra.TensorProduct.comm ℚ (tensor A T) (tensor A U) + | .node f g => Algebra.TensorProduct.congr (f.equivalence A) (g.equivalence A) + | .trans f g => (f.equivalence A).trans (g.equivalence A) + +omit [Fintype I] [DecidableEq I] in +lemma tensorMap_natural (A C : (I → ℕ) → CommAlgCat.{u} ℚ) (f : ∀ d,A d →ₐ[ℚ] C d) + {T U : SplitTree I} (e : Regroup T U) (x : tensor A T) : + e.equivalence C (tensorMap A C f T x)=tensorMap A C f U (e.equivalence A x) := by + induction e with + | refl T => rfl + | assoc T U V => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x z => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [TensorProduct.add_tmul,map_add,hx,hy] + | tmul x y => rfl + | swap T U => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => rfl + | node e g ihe ihg => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => + change e.equivalence C (tensorMap A C f _ x) ⊗ₜ[ℚ] + g.equivalence C (tensorMap A C f _ y)= + tensorMap A C f _ (e.equivalence A x) ⊗ₜ[ℚ] + tensorMap A C f _ (g.equivalence A y) + rw [ihe,ihg] + | trans e g ihe ihg => + change g.equivalence C (e.equivalence C (tensorMap A C f _ x))=_ + rw [ihe,ihg] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma tensorValue_natural {T U : SplitTree I} (e : Regroup T U) (x : tensor rawFamily T) : + tensorValue U (e.equivalence rawFamily x)=rename e.vars (tensorValue T x) := by + induction e with + | refl T => + change tensorValue T x=rename id (tensorValue T x) + simp only [rename_id,AlgHom.id_apply] + | assoc T U V => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x z => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [TensorProduct.add_tmul,map_add,hx,hy] + | tmul x y => + change tensorValue (.node T (.node U V)) (x ⊗ₜ[ℚ] (y ⊗ₜ[ℚ] z)) = _ + rw [tensorValue_tmul T (.node U V),tensorValue_tmul U V, + tensorValue_tmul (.node T U) V,tensorValue_tmul T U] + simp only [map_mul,rename_rename] + exact (mul_assoc _ _ _).symm + | swap T U => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => + change tensorValue (.node U T) (y ⊗ₜ[ℚ] x)=_ + rw [tensorValue_tmul U T,tensorValue_tmul T U] + simp only [map_mul,rename_rename] + exact mul_comm _ _ + | node e g ihe ihg => + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => + change tensorValue (.node _ _) (e.equivalence rawFamily x ⊗ₜ[ℚ] g.equivalence rawFamily y)=_ + rw [tensorValue_tmul,ihe,ihg,tensorValue_tmul,map_mul,rename_rename,rename_rename,rename_rename,rename_rename] + rfl + | trans e g ihe ihg => + change tensorValue _ (g.equivalence rawFamily (e.equivalence rawFamily x))=_ + rw [ihg,ihe,rename_rename] + rfl + +lemma rawRestriction_natural {T U : SplitTree I} (e : Regroup T U) (f : S T.dim) : + e.equivalence rawFamily (rawRestriction T f)= + rawRestriction U (dimensionEquivS e.dimension f) := by + apply tensorValue_injective U + rw [tensorValue_natural] + exact rawRestriction_regroup_of_pack_preserving e.dimension e.vars e.pack f + +lemma dimensionEquivB_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (h : d=e) (f : S d) : + dimensionEquivB a μ h (quotientAlg a μ d f)= + quotientAlg a μ e (dimensionEquivS h f) := by + subst e + rfl + +lemma restrictionB_natural (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + change e.equivalence (quotientFamily a (SlopeArithmetic.slope c η)) + (restrictionB a c η hc θ T hT (quotientAlg a _ T.dim f))= + restrictionB a c η hc θ U hU + (dimensionEquivB a (SlopeArithmetic.slope c η) e.dimension (quotientAlg a _ T.dim f)) + rw [dimensionEquivB_mk,restrictionB_mk,restrictionB_mk] + change e.equivalence (quotientFamily a (SlopeArithmetic.slope c η)) + (tensorMap rawFamily (quotientFamily a (SlopeArithmetic.slope c η)) + (quotientAlg a (SlopeArithmetic.slope c η)) T (rawRestriction T f))=_ + erw [tensorMap_natural] + rw [rawRestriction_natural] + rfl + +end Regroup +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/RenameFraction.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/RenameFraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ab4f23270b5e9723caf267d346b39248d9e9a6d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/RenameFraction.lean @@ -0,0 +1,220 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Diagonal + +namespace OAI + +section +namespace ElementaryPositivity.ShufflePolynomiality +open MvPolynomial +variable {α : Type*} [DecidableEq α] +section FractionRename +variable {α : Type*} [DecidableEq α] + +noncomputable def renameFraction (σ : Equiv.Perm α) : + FractionRing (MvPolynomial α ℚ) →+* FractionRing (MvPolynomial α ℚ) := + IsFractionRing.lift (g := (algebraMap (MvPolynomial α ℚ) + (FractionRing (MvPolynomial α ℚ))).comp (rename σ).toRingHom) + ((IsFractionRing.injective (MvPolynomial α ℚ) + (FractionRing (MvPolynomial α ℚ))).comp (rename_injective σ σ.injective)) + +omit [DecidableEq α] in +@[simp] lemma renameFraction_algebraMap (σ : Equiv.Perm α) (f : MvPolynomial α ℚ) : + renameFraction σ (algebraMap (MvPolynomial α ℚ) (FractionRing (MvPolynomial α ℚ)) f) = + algebraMap (MvPolynomial α ℚ) (FractionRing (MvPolynomial α ℚ)) (rename σ f) := + IsFractionRing.lift_algebraMap _ _ + +end FractionRename + +section RationalAverage +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (n : I → ℕ) (E : I → Prop) [DecidablePred E] +local notation "P" => MvPolynomial (Σ i, Fin (n i)) ℚ +local notation "K" => FractionRing P + +omit [DecidableEq I] in +lemma naturalVandermonde_ne_zero : naturalVandermonde n E ≠ 0 := by + rw [naturalVandermonde_product, Finset.prod_ne_zero_iff] + rintro ⟨i,a,b⟩ ha + simp only [naturalPairs, Finset.mem_sigma, Finset.mem_univ, Finset.mem_filter, + Finset.mem_product, true_and] at ha + apply diagonal_ne_zero + simpa [finPackPair] using ha.2.ne + +theorem rational_pack_sum_polynomial (N C : P) + (hC : C ∣ naturalVandermonde n E) : + ∃ q : P, (∑ g : ∀i, Equiv.Perm (Fin (n i)), + renameFraction (packAction (fun i => Fin (n i)) g) + (algebraMap P K N / algebraMap P K C)) = algebraMap P K q := by + let D := naturalVandermonde n E + let ρ := packAction (fun i => Fin (n i)) + let χ := packSign (fun i => Fin (n i)) E + have hD : D ≠ 0 := naturalVandermonde_ne_zero n E + obtain ⟨r,hr⟩ := hC + have hC0 : C ≠ 0 := by intro h; rw [h,zero_mul] at hr; exact hD hr + have hr0 : r ≠ 0 := by intro h; rw [h,mul_zero] at hr; exact hD hr + have hrK : algebraMap P K r ≠ 0 := by + exact fun h => hr0 ((IsFractionRing.injective P K) (by simpa using h)) + have hDK : algebraMap P K D ≠ 0 := by + exact fun h => hD ((IsFractionRing.injective P K) (by simpa using h)) + obtain ⟨q,hq⟩ := naturalVandermonde_dvd_alternate n E (N*r) + refine ⟨q, ?_⟩ + have hseed : algebraMap P K N / algebraMap P K C = + algebraMap P K (N*r) / algebraMap P K D := by + dsimp [D] + rw [hr, map_mul, map_mul, mul_div_mul_right _ _ hrK] + rw [hseed] + calc + (∑ g, renameFraction (ρ g) (algebraMap P K (N*r) / algebraMap P K D)) = + (∑ g, algebraMap P K ((χ g : ℤ) • rename (ρ g) (N*r))) / + algebraMap P K D := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro g _ + rw [map_div₀, renameFraction_algebraMap, renameFraction_algebraMap] + change algebraMap P K (rename (ρ g) (N*r)) / + algebraMap P K (rename (ρ g) (naturalVandermonde n E)) = _ + rw [rename_naturalVandermonde] + change algebraMap P K (rename (ρ g) (N*r)) / + algebraMap P K ((χ g : ℤ) • D) = _ + rcases Int.units_eq_one_or (χ g) with h|h <;> simp [h, div_neg_eq_neg_div, neg_div] + _ = algebraMap P K q := by + rw [← map_sum] + change algebraMap P K (alternate ρ χ (N*r)) / algebraMap P K D = _ + rw [hq, map_mul] + exact mul_div_cancel_left₀ _ hDK + +noncomputable def crossDenominator (d e : I → ℕ) : + MvPolynomial (Σ i, Fin (d i + e i)) ℚ := + ∏ a ∈ (naturalPairs (fun i => d i + e i) (fun _ => True)).filter + (fun a => a.2.1.val < d a.1 ∧ d a.1 ≤ a.2.2.val), + diagonal (finPackPair (fun i => d i + e i) a).1 + (finPackPair (fun i => d i + e i) a).2 + +omit [DecidableEq I] in +lemma crossDenominator_dvd (d e : I → ℕ) : + crossDenominator d e ∣ naturalVandermonde (fun i => d i + e i) (fun _ => True) := by + rw [naturalVandermonde_product] + exact Finset.prod_dvd_prod_of_subset _ _ _ (Finset.filter_subset _ _) + +theorem shuffle_denominator_sum_polynomial (d e : I → ℕ) + (N : MvPolynomial (Σ i, Fin (d i + e i)) ℚ) : + ∃ q : MvPolynomial (Σ i, Fin (d i + e i)) ℚ, + (∑ g : ∀i, Equiv.Perm (Fin (d i + e i)), + renameFraction (packAction (fun i => Fin (d i + e i)) g) + (algebraMap _ (FractionRing (MvPolynomial (Σ i, Fin (d i + e i)) ℚ)) N / + algebraMap _ _ (crossDenominator d e))) = algebraMap _ _ q := + rational_pack_sum_polynomial (fun i => d i + e i) (fun _ => True) N + (crossDenominator d e) (crossDenominator_dvd d e) + +end RationalAverage + +section InvariantPoles +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (n : I → ℕ) +local notation "P" => MvPolynomial (Σ i, Fin (n i)) ℚ +local notation "K" => FractionRing P + +lemma packed_pairs_product_dvd + (s : ∀ i, Finset (Fin (n i) × Fin (n i))) (f : P) + (hne : ∀ i ab, ab ∈ s i → ab.1 ≠ ab.2) + (hrev : ∀ i ab, ab ∈ s i → (ab.2, ab.1) ∉ s i) + (hf : ∀ i ab, ab ∈ s i → diagonal ⟨i,ab.1⟩ ⟨i,ab.2⟩ ∣ f) : + (∏ i, ∏ ab ∈ s i, diagonal ⟨i,ab.1⟩ ⟨i,ab.2⟩) ∣ f := by + suffices h : (∏ a ∈ Finset.univ.sigma s, + diagonal (finPackPair n a).1 (finPackPair n a).2) ∣ f by + simpa only [Finset.prod_sigma, finPackPair] using h + apply Finset.prod_dvd_of_isRelPrime + · rintro ⟨i,a,b⟩ hi ⟨j,c,d⟩ hj hdiff + change (⟨i,(a,b)⟩ : Σ i, Fin (n i) × Fin (n i)) ∈ Finset.univ.sigma s at hi + change (⟨j,(c,d)⟩ : Σ i, Fin (n i) × Fin (n i)) ∈ Finset.univ.sigma s at hj + simp only [Finset.mem_sigma, Finset.mem_univ, true_and] at hi hj + apply independent_diagonals + (by simpa [finPackPair] using hne i (a,b) hi) (by simpa [finPackPair] using hne j (c,d) hj) + · exact fun h => hdiff (finPackPair_injective n h) + · intro hr + have hij : i = j := congrArg (fun p => p.1.1) hr + subst j + simp only [finPackPair, Prod.mk.injEq, Sigma.mk.inj_iff, heq_eq_eq, true_and] at hr + obtain ⟨rfl,rfl⟩ := hr + exact hrev i (a,b) hi hj + · rintro ⟨i,a,b⟩ hi + exact hf i (a,b) (Finset.mem_sigma.mp hi).2 + +omit [DecidableEq I] in +lemma diagonal_dvd_naturalVandermonde (i : I) (a b : Fin (n i)) (hab : a ≠ b) : + diagonal ⟨i,a⟩ ⟨i,b⟩ ∣ naturalVandermonde n (fun _ => True) := by + have hlt (x y : Fin (n i)) (hxy : x < y) : + diagonal ⟨i,x⟩ ⟨i,y⟩ ∣ naturalVandermonde n (fun _ => True) := by + rw [naturalVandermonde_product] + exact Finset.dvd_prod_of_mem + (fun a : Σ i,Fin (n i) × Fin (n i) => diagonal (finPackPair n a).1 (finPackPair n a).2) + (a := ⟨i,(x,y)⟩) (by simp only [naturalPairs, Finset.mem_sigma, Finset.mem_univ, + Finset.mem_filter, Finset.mem_product, true_and]; exact hxy) + rcases lt_or_gt_of_ne hab with h|h + · exact hlt a b h + · have hd := hlt b a h + have he : diagonal (⟨i,a⟩ : Σi,Fin (n i)) ⟨i,b⟩ = -diagonal ⟨i,b⟩ ⟨i,a⟩ := by + simp only [diagonal]; ring + rw [he] + exact neg_dvd.mpr hd + +theorem invariant_fraction_regular (F : K) + (hsym : ∀ g : ∀i, Equiv.Perm (Fin (n i)), + renameFraction (packAction (fun i => Fin (n i)) g) F = F) + (hreg : ∃ N : P, algebraMap P K (naturalVandermonde n (fun _ => True)) * F = + algebraMap P K N) : + ∃ q : P, F = algebraMap P K q := by + obtain ⟨N,hN⟩ := hreg + let V := fun i => Fin (n i) + let D := naturalVandermonde n (fun _ => True) + have hDK : algebraMap P K D ≠ 0 := by + intro h + apply naturalVandermonde_ne_zero n (fun _ => True) + exact (IsFractionRing.injective P K) (by simpa using h) + have hanti (i : I) (a b : Fin (n i)) (hab : a ≠ b) : + rename (Equiv.swap (⟨i,a⟩ : Σi,Fin (n i)) ⟨i,b⟩) N = -N := by + let t : ∀i, Equiv.Perm (V i) := Function.update 1 i (Equiv.swap a b) + have ht := congrArg (renameFraction (packAction V t)) hN + rw [map_mul, renameFraction_algebraMap, renameFraction_algebraMap, hsym] at ht + have hsign : packSign V (fun _ => True) t = -1 := + packSign_transposition V (fun _ => True) i a b trivial hab + rw [rename_naturalVandermonde, hsign] at ht + simp only [Units.val_neg, Units.val_one, neg_smul, one_smul, map_neg, neg_mul] at ht + rw [hN] at ht + have hpoly : rename (packAction V t) N = -N := + (IsFractionRing.injective P K) (by simpa using ht.symm) + simpa only [t, V, packAction_transposition] using hpoly + have hd : D ∣ N := by + change naturalVandermonde n (fun _ => True) ∣ N + rw [naturalVandermonde_product] + apply Finset.prod_dvd_of_isRelPrime + · rintro ⟨i,a,b⟩ hi ⟨j,c,d⟩ hj hdiff + change (⟨i,(a,b)⟩ : Σ i,Fin (n i) × Fin (n i)) ∈ naturalPairs n (fun _ => True) at hi + change (⟨j,(c,d)⟩ : Σ i,Fin (n i) × Fin (n i)) ∈ naturalPairs n (fun _ => True) at hj + simp only [naturalPairs, Finset.mem_sigma, Finset.mem_univ, Finset.mem_filter, + Finset.mem_product, true_and] at hi hj + apply independent_diagonals (by simpa [finPackPair] using hi.ne) (by simpa [finPackPair] using hj.ne) + · exact fun h => hdiff (finPackPair_injective n h) + · intro hr + have hij : i = j := congrArg (fun p => p.1.1) hr + subst j + simp only [finPackPair, Prod.mk.injEq, Sigma.mk.inj_iff, heq_eq_eq, true_and] at hr + obtain ⟨rfl,rfl⟩ := hr + exact lt_asymm hi hj + · rintro ⟨i,a,b⟩ hi + simp only [naturalPairs, Finset.mem_sigma, Finset.mem_univ, Finset.mem_filter, + Finset.mem_product, true_and] at hi + exact diagonal_dvd_of_antisymmetric _ _ N (hanti i a b hi.ne) + obtain ⟨q,hq⟩ := hd + refine ⟨q, ?_⟩ + apply mul_left_cancel₀ hDK + change algebraMap P K D * F = _ + rw [hN, hq, map_mul] + +end InvariantPoles + +end ElementaryPositivity.ShufflePolynomiality + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictSplit.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictSplit.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec89f623c32f6fb9ef5f975f2dd0654919ba2420 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictSplit.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Split + +namespace OAI + +section +namespace ElementaryPositivity.ShuffleConvolution +variable {A : Type*} [Fintype A] [DecidableEq A] + +def restrictSplit {s t : Finset A} (ht : t ⊆ s) (q : Split s) : Split t := + ⟨(q.val.1 ∩ t,q.val.2 ∩ t),q.property.1.mono Finset.inter_subset_left Finset.inter_subset_left,by + change (q.val.1 ∩ t) ∪ (q.val.2 ∩ t) = t + rw [← Finset.union_inter_distrib_right,q.property.2] + exact Finset.inter_eq_right.mpr ht⟩ + +def grid {s : Finset A} (p : Split s) : Split s ≃ Split p.val.1 × Split p.val.2 where + toFun q := (restrictSplit p.left_subset q,restrictSplit p.right_subset q) + invFun q := ⟨(q.1.val.1 ∪ q.2.val.1,q.1.val.2 ∪ q.2.val.2),by + constructor + · apply Finset.disjoint_union_left.mpr + constructor + · apply Finset.disjoint_union_right.mpr + exact ⟨q.1.property.1,p.property.1.mono q.1.left_subset q.2.right_subset⟩ + · apply Finset.disjoint_union_right.mpr + exact ⟨p.property.1.symm.mono q.2.left_subset q.1.right_subset,q.2.property.1⟩ + · calc + (q.1.val.1 ∪ q.2.val.1) ∪ (q.1.val.2 ∪ q.2.val.2) = + (q.1.val.1 ∪ q.1.val.2) ∪ (q.2.val.1 ∪ q.2.val.2) := by ac_rfl + _ = s := by rw [q.1.property.2,q.2.property.2,p.property.2]⟩ + left_inv q := by + apply Subtype.ext + dsimp [restrictSplit] + congr 1 + · rw [← Finset.inter_union_distrib_left,p.property.2] + exact Finset.inter_eq_left.mpr q.left_subset + · rw [← Finset.inter_union_distrib_left,p.property.2] + exact Finset.inter_eq_left.mpr q.right_subset + right_inv q := by + apply Prod.ext <;> apply Subtype.ext + · dsimp [restrictSplit] + have h1 := p.property.1.symm.mono_left q.2.left_subset + have h2 := p.property.1.symm.mono_left q.2.right_subset + rw [Finset.union_inter_distrib_right,Finset.union_inter_distrib_right, + Finset.inter_eq_left.mpr q.1.left_subset,Finset.inter_eq_left.mpr q.1.right_subset, + Finset.disjoint_iff_inter_eq_empty.mp h1,Finset.disjoint_iff_inter_eq_empty.mp h2] + simp + · dsimp [restrictSplit] + have h1 := p.property.1.mono_left q.1.left_subset + have h2 := p.property.1.mono_left q.1.right_subset + rw [Finset.union_inter_distrib_right,Finset.union_inter_distrib_right, + Finset.inter_eq_left.mpr q.2.left_subset,Finset.inter_eq_left.mpr q.2.right_subset, + Finset.disjoint_iff_inter_eq_empty.mp h1,Finset.disjoint_iff_inter_eq_empty.mp h2] + simp + +end ElementaryPositivity.ShuffleConvolution + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/Restriction.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/Restriction.lean new file mode 100644 index 0000000000000000000000000000000000000000..f802a46c2408d9ac55ad6effec5a7f87a07102ac --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/Restriction.lean @@ -0,0 +1,219 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SeparationCoefficients +import OAI.Combinatorics.Chromatic.Shuffle.ShuffleUnits + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +lemma labeledPolynomial_cast {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + {d e : I → ℕ} (h : d=e) (f : S d) : + labeledPolynomial (A:=A) (castS h f)=labeledPolynomial f := by + subst e + rfl + +omit [DecidableEq I] in +lemma labeledPolynomial_full (d : I → ℕ) (f : S d) : + labeledPolynomial (A:=fun i=>Fin (d i)) f (fun _=>Finset.univ)=f.val := by + let r : Realization d (A:=fun i=>Fin (d i)) (fun _=>Finset.univ) := + fun _=>(Equiv.subtypeUnivEquiv (fun _=>Finset.mem_univ _)).symm + rw [labeledPolynomial_eq r] + have hr : realizationMap r=id := rfl + rw [hr,rename_id] + rfl + +omit [DecidableEq I] in +lemma rightInput_zero_rename {e : I → ℕ} (A : Cut 0 e) (f : S e) : + rename (rightInput A) f.val=(castS (zero_add e).symm f).val := by + classical + have hempty : ∀ i,(A i).val=∅ := fun i=>Finset.card_eq_zero.mp (A i).property + have huniv : ∀ i,(A i).valᶜ=Finset.univ := by intro i; rw [hempty]; exact Finset.compl_empty + let r : Realization e (A:=fun i=>Fin ((0+e) i)) (fun _=>Finset.univ) := + fun i=>(rightEnum A i).trans (Equiv.subtypeEquivRight (fun x=>by rw [huniv])) + have hr : realizationMap r=rightInput A := rfl + rw [←hr,←labeledPolynomial_eq r,←labeledPolynomial_cast (zero_add e).symm f, + labeledPolynomial_full] + +omit [DecidableEq I] in +lemma leftInput_zero_rename {d : I → ℕ} (A : Cut d 0) (f : S d) : + rename (leftInput A) f.val=(castS (add_zero d).symm f).val := by + classical + have huniv : ∀ i,(A i).val=Finset.univ := by + intro i + apply Finset.eq_univ_of_card + simpa only [Fintype.card_fin,Pi.zero_apply,Nat.add_zero] using (A i).property + let r : Realization d (A:=fun i=>Fin ((d+0) i)) (fun _=>Finset.univ) := + fun i=>(leftEnum A i).trans (Equiv.subtypeEquivRight (fun x=>by rw [huniv])) + have hr : realizationMap r=leftInput A := rfl + rw [←hr,←labeledPolynomial_eq r,←labeledPolynomial_cast (add_zero d).symm f, + labeledPolynomial_full] + +lemma restrictTensor_zero_left {e : I → ℕ} (A : Cut 0 e) (f : S e) : + restrictTensor A (castS (zero_add e).symm f)=(1 : S 0)⊗ₜ[ℚ]f := by + apply tensorValue_injective + rw [tensorValue_restrictTensor,tensorValue_tmul,OneMemClass.coe_one,map_one,one_mul] + apply rename_injective (cutSplit A) (cutSplit A).injective + rw [rename_rename,rename_rename] + have h₁ : cutSplit A ∘ (cutSplit A).symm=id := funext ((cutSplit A).apply_symm_apply) + have h₂ : cutSplit A ∘ Sum.inr=rightInput A := rfl + rw [h₁,h₂,rename_id,rightInput_zero_rename] + rfl + +lemma restrictTensor_zero_right {d : I → ℕ} (A : Cut d 0) (f : S d) : + restrictTensor A (castS (add_zero d).symm f)=f⊗ₜ[ℚ](1 : S 0) := by + apply tensorValue_injective + rw [tensorValue_restrictTensor,tensorValue_tmul,OneMemClass.coe_one,map_one,mul_one] + apply rename_injective (cutSplit A) (cutSplit A).injective + rw [rename_rename,rename_rename] + have h₁ : cutSplit A ∘ (cutSplit A).symm=id := funext ((cutSplit A).apply_symm_apply) + have h₂ : cutSplit A ∘ Sum.inl=leftInput A := rfl + rw [h₁,h₂,rename_id,leftInput_zero_rename] + rfl + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.CoefficientIdeals +variable {R : Type*} [CommRing R] +lemma polynomial_map_quotient_eq_zero_iff (J : Ideal R) (p : Polynomial R) : + Polynomial.map (Ideal.Quotient.mk J) p=0 ↔ ∀ n,p.coeff n∈J := by + constructor + · intro hp n + have h:=congrArg (fun p : Polynomial (R⧸J)=>p.coeff n) hp + simpa only [Polynomial.coeff_map,Polynomial.coeff_zero,Ideal.Quotient.eq_zero_iff_mem] using h + · intro hp + ext n + simpa only [Polynomial.coeff_map,Polynomial.coeff_zero,Ideal.Quotient.eq_zero_iff_mem] using hp n +end ElementaryPositivity.CoefficientIdeals + +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.CoefficientIdeals +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma relativeTaylorB_coeff_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (x : B a μ d ⊗[ℚ] B a μ e) : (relativeTaylorB a μ d e x).coeff 0=x := by + rw [Polynomial.coeff_zero_eq_eval_zero,←map_zero (algebraMap ℚ (B a μ d ⊗[ℚ] B a μ e)),relativeTaylorB_eval] + have he : translationB a μ d 0=LinearMap.id := LinearMap.ext (translationB_zero a μ d) + rw [he,TensorProduct.map_id,LinearMap.id_apply] + +lemma sourceTensorFiltration_cross_cancel (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + change restrictionBUnit a c η hc (Or.inl rfl) A + (castB a _ (zero_add e).symm (quotientAlg a (slope c η) e f))= + (1 : B a (slope c η) 0)⊗ₜ[ℚ]quotientAlg a (slope c η) e f + rw [castB_mk,restrictionBUnit_mk,restrictTensor_zero_left,quotientTensor_tmul,map_one] + +lemma restrictionBUnit_zero_right (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + change restrictionBUnit a c η hc (Or.inr (Or.inl rfl)) A + (castB a _ (add_zero d).symm (quotientAlg a (slope c η) d f))= + quotientAlg a (slope c η) d f⊗ₜ[ℚ](1 : B a (slope c η) 0) + rw [castB_mk,restrictionBUnit_mk,restrictTensor_zero_right,quotientTensor_tmul,map_one] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictionB.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictionB.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2681bf6942f4db4c06b48d4a8f8d1f116cbad76 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictionB.lean @@ -0,0 +1,188 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.CanonicalCard + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open ElementaryPositivity.SlopeArithmetic +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [Fintype I] [DecidableEq I] in +lemma dimensionCast_eq_castS {d e : I → ℕ} (h : d=e) (f : S d) : + dimensionCast h f = castS h f := by subst e; rfl + +theorem restrict_destabilizing_shuffle (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 slope c η (α+β)) : + quotientTensor a (slope c η) α β + (restrictTensor u (dimensionCast h (shufflePolynomial a f g))) = 0 := by + rw [dimensionCast_eq_castS] + apply quotient_crossTensor_cancel + let s : Pack (A:=fun i=>Fin ((α+β) i)) := fun _=>Finset.univ + let R : Realization (α+β) s := defaultRealization (by intro i; simp [s]) + rw [cleared_restrictTensor a h f g R u, map_smul] + rw [quotient_gridTensor_zero a c η hc f g _ _ _ hd hα] + · simp + · rwa [slope_add_same c η hc hα] at hμ + +theorem restriction_kills_destabilizingSpace (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + obtain ⟨α,β,h,F,G,hα,hβ,hμ,rfl⟩ := hf + exact restrict_destabilizing_shuffle a c η hc h F G u hα hs hμ + | zero => simp + | add f g hf hg ihf ihg => simp only [map_add,ihf,ihg,add_zero] + | smul r f hf ih => simp only [map_smul,ih,smul_zero] + +noncomputable def restrictionB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 d + | .node l r => l.dim + r.dim + +@[reducible] def OnSlope (c η : I → ℝ) (θ : ℝ) : SplitTree I → Prop + | .leaf d => d ≠ 0 ∧ slope c η d = θ + | .node l r => l.OnSlope c η θ ∧ r.OnSlope c η θ + +omit [DecidableEq I] in +lemma dim_ne_zero {T : SplitTree I} {c η : I → ℝ} {θ : ℝ} (h : T.OnSlope c η θ) : + T.dim ≠ 0 := by + induction T with + | leaf d => exact h.1 + | node l r ihl ihr => exact add_ne_zero_left _ _ (ihl h.1) + +omit [DecidableEq I] in +lemma slope_dim (c η : I → ℝ) (hc : ∀ i,0 exact h.2 + | node l r ihl ihr => + have hl := ihl h.1 + have hr := ihr h.2 + exact (slope_add_same c η hc (hl.trans hr.symm)).trans hl + +@[reducible] noncomputable def tensor (A : (I → ℕ) → CommAlgCat.{u} ℚ) : SplitTree I → CommAlgCat.{u} ℚ + | .leaf d => A d + | .node l r => CommAlgCat.of ℚ (tensor A l ⊗[ℚ] tensor A r) + +noncomputable def tensorMap (A C : (I → ℕ) → CommAlgCat.{u} ℚ) + (f : ∀ d, A d →ₐ[ℚ] C d) : (T : SplitTree I) → tensor A T →ₐ[ℚ] tensor C T + | .leaf d => f d + | .node l r => Algebra.TensorProduct.map (tensorMap A C f l) (tensorMap A C f r) + +noncomputable def rawFamily (d : I → ℕ) : CommAlgCat.{u} ℚ := CommAlgCat.of ℚ (S d) +noncomputable def quotientFamily (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : CommAlgCat.{u} ℚ := + CommAlgCat.of ℚ (B a μ d) + +noncomputable def rawRestriction : (T : SplitTree I) → S T.dim →ₐ[ℚ] tensor rawFamily T + | .leaf d => AlgHom.id ℚ (S d) + | .node l r => (Algebra.TensorProduct.map (rawRestriction l) (rawRestriction r)).comp + (restrictTensorAlg (firstCut l.dim r.dim)) + +noncomputable def quotientMap (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (T : SplitTree I) : + tensor rawFamily T →ₐ[ℚ] tensor (quotientFamily a μ) T := + tensorMap rawFamily (quotientFamily a μ) (quotientAlg a μ) T + +noncomputable def restrictionB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 AlgHom.id ℚ (B a (slope c η) d) + | .node l r, h => + (Algebra.TensorProduct.map (restrictionB a c η hc θ l h.1) + (restrictionB a c η hc θ r h.2)).comp + (RawShuffle.restrictionB a c η hc + ((slope_dim c η hc h.1).trans (slope_dim c η hc h.2).symm) + (firstCut l.dim r.dim)) + +lemma restrictionB_square (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 rfl + | node l r ihl ihr => + apply AlgHom.ext + intro f + change (Algebra.TensorProduct.map (restrictionB a c η hc θ l h.1) + (restrictionB a c η hc θ r h.2)) + (quotientTensor a (slope c η) l.dim r.dim (restrictTensor (firstCut l.dim r.dim) f)) = + (Algebra.TensorProduct.map (quotientMap a (slope c η) l) (quotientMap a (slope c η) r)) + ((Algebra.TensorProduct.map (rawRestriction l) (rawRestriction r)) + (restrictTensor (firstCut l.dim r.dim) f)) + generalize restrictTensor (firstCut l.dim r.dim) f = t + induction t using TensorProduct.inductionOn with + | tmul x y => + change restrictionB a c η hc θ l h.1 (quotientAlg a (slope c η) l.dim x) ⊗ₜ[ℚ] + restrictionB a c η hc θ r h.2 (quotientAlg a (slope c η) r.dim y) = + quotientMap a (slope c η) l (rawRestriction l x) ⊗ₜ[ℚ] + quotientMap a (slope c η) r (rawRestriction r y) + exact congrArg₂ (fun x y => x ⊗ₜ[ℚ] y) + (AlgHom.congr_fun (ihl h.1) x) (AlgHom.congr_fun (ihr h.2) y) + | add x y hx hy => simp only [map_add,hx,hy] + +lemma restrictionB_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + change componentB a (SlopeArithmetic.slope c η) d j f=0 + rw [← (mem_gradeB_iff a _ d k f).mp hf,componentB_componentB,ite_eq_right hj] + | node l r ihl ihr => + let μ:=SlopeArithmetic.slope c η + let Rl := (restrictionB a c η hc θ l hs.1).toLinearMap + let Rr := (restrictionB a c η hc θ r hs.2).toLinearMap + let Cl := componentTensor a μ l j.1 + let Cr := componentTensor a μ r j.2 + let x:=RawShuffle.restrictionB a c η hc + ((slope_dim c η hc hs.1).trans (slope_dim c η hc hs.2).symm) (firstCut l.dim r.dim) f + let F:=TensorProduct.map Cl Cr ∘ₗ TensorProduct.map Rl Rr + change F x=0 + obtain ⟨s,hout,he⟩ := componentTensor_finite_decomposition a μ (.node (.leaf l.dim) (.leaf r.dim)) x + change (∑ mn∈s,TensorProduct.map (componentB a μ l.dim mn.1) + (componentB a μ r.dim mn.2) x)=x at he + have hterm : ∀ mn∈s,F (TensorProduct.map (componentB a μ l.dim mn.1) + (componentB a μ r.dim mn.2) x)=0 := by + intro mn hmn + by_cases hm : mn.1+mn.2=k + · have hsep : l.totalDegree j.1≠mn.1 ∨ r.totalDegree j.2≠mn.2 := by + by_contra hh + push Not at hh + apply hj + change l.totalDegree j.1+r.totalDegree j.2=k + rw [hh.1,hh.2,hm] + generalize x=y + induction y using TensorProduct.inductionOn with + | tmul g h => + change Cl (Rl (componentB a μ l.dim mn.1 g)) ⊗ₜ[ℚ] + Cr (Rr (componentB a μ r.dim mn.2 h))=0 + rcases hsep with hl|hr + · have hzero := ihl hs.1 (componentB a μ l.dim mn.1 g) mn.1 + (⟨g,rfl⟩) j.1 hl + rw [show Cl (Rl (componentB a μ l.dim mn.1 g))=0 from hzero,TensorProduct.zero_tmul] + · have hzero := ihr hs.2 (componentB a μ r.dim mn.2 h) mn.2 + (⟨h,rfl⟩) j.2 hr + rw [show Cr (Rr (componentB a μ r.dim mn.2 h))=0 from hzero,TensorProduct.tmul_zero] + | add y z hy hz => simp only [map_add,hy,hz,add_zero] + · have hzero := RawShuffle.restrictionB_graded a c η hc + ((slope_dim c η hc hs.1).trans (slope_dim c η hc hs.2).symm) + (firstCut l.dim r.dim) f k hf mn.1 mn.2 hm + change TensorProduct.map (componentB a μ l.dim mn.1) + (componentB a μ r.dim mn.2) x=0 at hzero + rw [hzero,map_zero] + calc + F x = F (∑ mn∈s,TensorProduct.map (componentB a μ l.dim mn.1) (componentB a μ r.dim mn.2) x) := + congrArg F he.symm + _ = 0 := by rw [map_sum]; exact Finset.sum_eq_zero hterm + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictionTestHomogeneity.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictionTestHomogeneity.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a51e55549875ee48f2515af0383b80b1511cdf6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/RestrictionTestHomogeneity.lean @@ -0,0 +1,203 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.LeadingIndex +import OAI.Combinatorics.Chromatic.Shuffle.TensorFiltration +import OAI.Combinatorics.Chromatic.Shuffle.Degree +import OAI.Combinatorics.Chromatic.Walls.TensorFiltrationInterchange + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.Homogeneity +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +namespace SplitTree +lemma restrictionTest_homogeneous (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ)) z≠ℓ) : + restrictionTest a c η hc θ T hs rfl k z f=0 := by + classical + induction T generalizing ℓ with + | leaf d => + have hzs : z=Finsupp.single () (z ()) := by apply Finsupp.ext; intro x; cases x; simp + rw [hzs] + rw [restrictionTest_leaf_coeff] + have hh:=taylorB_coeff_graded a (SlopeArithmetic.slope c η) d f ℓ hf (z ()) + have hne : k≠ℓ-(z () : ℤ) := by + rw [hzs,Finsupp.weight_single] at hz + change (k : ℤ)+(z () : ℤ) • (1 : ℤ)≠ℓ at hz + simp only [zsmul_eq_mul, mul_one] at hz + change (k : ℤ)+(z () : ℤ)≠ℓ at hz + intro h + apply hz + rw [h,sub_add_cancel] + rw [←(mem_gradeB_iff a _ d (ℓ-(z ():ℤ)) _).mp hh,componentB_componentB,ite_eq_right hne] + rfl + | node l r ihl ihr => + let z₁:=z.comapDomain Sum.inl Sum.inl_injective.injOn + let z₂:=z.comapDomain Sum.inr Sum.inr_injective.injOn + have hzs : z₁.sumElim z₂=z := Finsupp.comapDomain_sumElim_comapDomain z + rw [←hzs] at hz ⊢ + rw [totalWeight_sumElim] at hz + rw [restrictionTest_node] + let μ:=SlopeArithmetic.slope c η + let Rl:=restrictionTest a c η hc θ l hs.1 rfl k.1 z₁ + let Rr:=restrictionTest a c η hc θ r hs.2 rfl k.2 z₂ + let x:=RawShuffle.restrictionB a c η hc + ((slope_dim c η hc hs.1).trans (slope_dim c η hc hs.2).symm) (firstCut l.dim r.dim) f + let F:=TensorProduct.map Rl Rr + change F x=0 + obtain ⟨s,_,he⟩:=componentTensor_finite_decomposition a μ (.node (.leaf l.dim) (.leaf r.dim)) x + change (∑ mn∈s,TensorProduct.map (componentB a μ l.dim mn.1) (componentB a μ r.dim mn.2) x)=x at he + have hterm : ∀ mn∈s,F (TensorProduct.map (componentB a μ l.dim mn.1) (componentB a μ r.dim mn.2) x)=0 := by + intro mn _ + by_cases hm : mn.1+mn.2=ℓ + · have hsep : l.totalDegree k.1+Finsupp.weight (fun _=>(1:ℤ)) z₁≠mn.1 ∨ + r.totalDegree k.2+Finsupp.weight (fun _=>(1:ℤ)) z₂≠mn.2 := by + change l.totalDegree k.1+r.totalDegree k.2+_≠ℓ at hz + by_contra hh + push Not at hh + apply hz + rw [←hm,←hh.1,←hh.2] + ring + generalize x=y + induction y using TensorProduct.inductionOn with + | tmul g h => + change Rl (componentB a μ l.dim mn.1 g) ⊗ₜ[ℚ] Rr (componentB a μ r.dim mn.2 h)=0 + rcases hsep with hl|hr + · have hzero:=ihl hs.1 (componentB a μ l.dim mn.1 g) mn.1 ⟨g,rfl⟩ k.1 z₁ hl + rw [show Rl (componentB a μ l.dim mn.1 g)=0 from hzero,TensorProduct.zero_tmul] + · have hzero:=ihr hs.2 (componentB a μ r.dim mn.2 h) mn.2 ⟨h,rfl⟩ k.2 z₂ hr + rw [show Rr (componentB a μ r.dim mn.2 h)=0 from hzero,TensorProduct.tmul_zero] + | add g h hg hh => simp only [map_add,hg,hh,add_zero] + · have hzero:=RawShuffle.restrictionB_graded a c η hc + ((slope_dim c η hc hs.1).trans (slope_dim c η hc hs.2).symm) + (firstCut l.dim r.dim) f ℓ hf mn.1 mn.2 hm + change TensorProduct.map (componentB a μ l.dim mn.1) (componentB a μ r.dim mn.2) x=0 at hzero + rw [hzero,map_zero] + rw [←he,map_sum] + exact Finset.sum_eq_zero hterm + +lemma restrictionTest_component (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ)) z + then restrictionTest a c η hc θ T hs rfl k z f else 0 := by + classical + split_ifs with h + · obtain ⟨s,hs',he⟩:=componentB_finite_decomposition a (SlopeArithmetic.slope c η) T.dim f + let R:=restrictionTest a c η hc θ T hs rfl k z + change R (componentB a (SlopeArithmetic.slope c η) T.dim ℓ f)=R f + have hsum : (∑ i∈s,R (componentB a (SlopeArithmetic.slope c η) T.dim i f))= + R (componentB a (SlopeArithmetic.slope c η) T.dim ℓ f) := by + apply Finset.sum_eq_single ℓ + · intro i _ hi + exact restrictionTest_homogeneous a c η hc θ T hs _ i ⟨f,rfl⟩ k z (by omega) + · intro hl + rw [hs' ℓ hl,map_zero] + rw [←hsum,←map_sum,he] + · exact restrictionTest_homogeneous a c η hc θ T hs _ ℓ ⟨f,rfl⟩ k z (Ne.symm h) +end SplitTree + +lemma sourceFiltration_component_mem (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0p.coeff 1) + (map_taylorS d f) + simpa [derivativeS] using h + +noncomputable def derivativeB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + Module.End ℚ (B a μ d) := + ((Polynomial.lcoeff (B a μ d) 1).restrictScalars ℚ).comp (taylorB a μ d).toLinearMap + +lemma derivativeB_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (f : S d) : + derivativeB a μ d (quotientAlg a μ d f)=quotientAlg a μ d (derivativeS d f) := by + change (taylorB a μ d (quotientAlg a μ d f)).coeff 1=_ + rw [taylorB_mk,Polynomial.coeff_map] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma derivativeS_pow_val (d : I → ℕ) (n : ℕ) (f : S d) : + ((derivativeS d^n) f).val=(D.toLinearMap^n) f.val := by + induction n with + | zero => rfl + | succ n ih => + simp only [pow_succ',Module.End.mul_apply,derivativeS_val,ih] + rfl + +lemma derivativeB_pow_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (n : ℕ) (f : S d) : + (derivativeB a μ d^n) (quotientAlg a μ d f)=quotientAlg a μ d ((derivativeS d^n) f) := by + induction n with + | zero => rfl + | succ n ih => simp only [pow_succ',Module.End.mul_apply,ih,derivativeB_mk] + +theorem derivativeB_locally_nilpotent (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (f : B a μ d) : ∃ N : ℕ,(derivativeB a μ d^N) f=0 := by + induction f using Submodule.Quotient.induction_on with + | H f => + refine ⟨(taylor f.val).natDegree+1,?_⟩ + change (derivativeB a μ d^_) (quotientAlg a μ d f)=0 + rw [derivativeB_pow_mk] + have h : (derivativeS d^((taylor f.val).natDegree+1)) f=0 := by + apply Subtype.ext + rw [derivativeS_pow_val,locally_nilpotent_D] + rfl + rw [h,map_zero] + +lemma derivativeB_mul (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (f g : B a μ d) : + derivativeB a μ d (f*g)=derivativeB a μ d f*g+f*derivativeB a μ d g := by + change (taylorB a μ d (f*g)).coeff 1=_ + rw [map_mul,Polynomial.mul_coeff_one,taylorB_coeff_zero,taylorB_coeff_zero] + exact add_comm _ _ + +lemma derivativeB_filtered (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0derivativeB_filtered a c η hc θ d W f hf) + (fun f hf=>derivativeB_filtered a c η hc θ d (W+1) f hf) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/ReynoldsS.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/ReynoldsS.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e324d2b96ddac72dca1359dbf9ac0c9289d7720 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/ReynoldsS.lean @@ -0,0 +1,122 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.PackSplit + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.SeparatedSymmetry +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def reynoldsS (d : I → ℕ) : + MvPolynomial (Σi,Fin (d i)) ℚ →ₗ[ℚ] S d where + toFun f := ⟨average (packAction (fun i=>Fin (d i))) f, + fun σ => rename_average _ σ f⟩ + map_add' := by intros; apply Subtype.ext; exact map_add _ _ _ + map_smul' := by intros; apply Subtype.ext; exact map_smul _ _ _ + +@[simp] lemma reynoldsS_val (d : I → ℕ) (f : S d) : reynoldsS d f.val = f := by + apply Subtype.ext + exact average_fixed _ f.val f.property + +lemma tensorEquivSum_tmul {α β : Type*} (f : MvPolynomial α ℚ) (g : MvPolynomial β ℚ) : + tensorEquivSum ℚ α β ℚ (f ⊗ₜ[ℚ] g) = rename Sum.inl f * rename Sum.inr g := by + let H := tensorEquivSum ℚ α β ℚ + have hL : H.toAlgHom.comp Algebra.TensorProduct.includeLeft = rename (R:=ℚ) Sum.inl := by + ext i + simp [H] + have hR : H.toAlgHom.comp Algebra.TensorProduct.includeRight = rename (R:=ℚ) Sum.inr := by + ext i + simp [H] + change H (f ⊗ₜ[ℚ] g) = _ + have ht : f ⊗ₜ[ℚ] g = (f ⊗ₜ[ℚ] (1 : MvPolynomial β ℚ)) * ((1 : MvPolynomial α ℚ) ⊗ₜ[ℚ] g) := by + simp + rw [ht, map_mul] + exact congrArg₂ (· * ·) (DFunLike.congr_fun hL f) (DFunLike.congr_fun hR g) + +noncomputable def tensorValue (d e : I → ℕ) : + S d ⊗[ℚ] S e →ₗ[ℚ] MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ := + (tensorEquivSum ℚ _ _ ℚ).toLinearMap ∘ₗ + TensorProduct.map (symmetricSpace d).val.toLinearMap (symmetricSpace e).val.toLinearMap + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma tensorValue_tmul (d e : I → ℕ) (f : S d) (g : S e) : + tensorValue d e (f ⊗ₜ[ℚ] g) = rename Sum.inl f.val * rename Sum.inr g.val := by + exact tensorEquivSum_tmul f.val g.val + +noncomputable def separateTensor (d e : I → ℕ) : + MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ →ₗ[ℚ] S d ⊗[ℚ] S e := + TensorProduct.map (reynoldsS d) (reynoldsS e) ∘ₗ + (tensorEquivSum ℚ _ _ ℚ).symm.toLinearMap + +@[simp] lemma separateTensor_product (d e : I → ℕ) (f : S d) (g : S e) : + separateTensor d e (rename Sum.inl f.val * rename Sum.inr g.val) = f ⊗ₜ[ℚ] g := by + rw [← tensorEquivSum_tmul] + simp [separateTensor] + +@[simp] lemma separateTensor_tensorValue (d e : I → ℕ) (f : S d ⊗[ℚ] S e) : + separateTensor d e (tensorValue d e f) = f := by + induction f using TensorProduct.inductionOn with + | tmul f g => simp + | add x y hx hy => simp [hx,hy] + +lemma tensorValue_injective (d e : I → ℕ) : Function.Injective (tensorValue d e) := by + intro f g h + simpa using congrArg (separateTensor d e) h + +lemma tensorValue_separateTensor (d e : I → ℕ) + (f : MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ) + (hf : ∀ σ, rename (sumAction (packAction (fun i=>Fin (d i))) + (packAction (fun i=>Fin (e i))) σ) f = f) : + tensorValue d e (separateTensor d e f) = f := by + have h := invariant_separated_span (packAction (fun i=>Fin (d i))) + (packAction (fun i=>Fin (e i))) f hf + clear hf + induction h using Submodule.span_induction with + | mem p hp => + obtain ⟨f,g,hf,hg,rfl⟩ := hp + change tensorValue d e (separateTensor d e + (rename Sum.inl (⟨f,hf⟩ : S d).val * rename Sum.inr (⟨g,hg⟩ : S e).val)) = _ + rw [separateTensor_product,tensorValue_tmul] + | zero => simp + | add x y hx hy ihx ihy => simp [ihx,ihy] + | smul c x hx ih => simp [ih] + +noncomputable def restrictTensor {d e : I → ℕ} (A : Cut d e) : S (d+e) →ₗ[ℚ] S d ⊗[ℚ] S e := + separateTensor d e ∘ₗ (rename (cutSplit A).symm).toLinearMap ∘ₗ + (symmetricSpace (d+e)).val.toLinearMap + +@[simp] lemma tensorValue_restrictTensor {d e : I → ℕ} (A : Cut d e) (f : S (d+e)) : + tensorValue d e (restrictTensor A f) = rename (cutSplit A).symm f.val := by + exact tensorValue_separateTensor d e _ (split_symmetric A f) + +lemma restrictTensor_independent {d e : I → ℕ} (A B : Cut d e) (f : S (d+e)) : + restrictTensor A f = restrictTensor B f := by + apply tensorValue_injective + rw [tensorValue_restrictTensor,tensorValue_restrictTensor] + apply rename_injective (cutSplit B) (cutSplit B).injective + rw [split_symmetric_independent] + simp only [rename_rename] + simp + +noncomputable def restrictQuotientAt (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (A : Cut d e) (z w : ℚ) : + S (d+e) →ₗ[ℚ] B a μ d ⊗[ℚ] B a μ e := + TensorProduct.map + ((destabilizingSpace a μ d).mkQ ∘ₗ translationS d z) + ((destabilizingSpace a μ e).mkQ ∘ₗ translationS e w) ∘ₗ restrictTensor A + +lemma restrictQuotientAt_independent (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (A B : Cut d e) (z w : ℚ) : + restrictQuotientAt a μ A z w = restrictQuotientAt a μ B z w := by + apply LinearMap.ext + intro f + simp only [restrictQuotientAt,LinearMap.comp_apply,restrictTensor_independent A B] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SameDen.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SameDen.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b8dbcbe343a22281b6698ffeaf695a9947c304c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SameDen.lean @@ -0,0 +1,226 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Realization +import OAI.Combinatorics.Chromatic.Walls.Grid + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +open ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,DecidableEq (A i)] + +noncomputable def sameDen (s t : Pack (A:=A)) : MvPolynomial (Σi,A i) ℚ := + ∏ i,∏ x ∈ s i,∏ y ∈ t i,diagonal (⟨i,x⟩ : Σi,A i) ⟨i,y⟩ + +noncomputable def arrowNum (a : I → I → ℕ) (s t : Pack (A:=A)) : MvPolynomial (Σi,A i) ℚ := + ∏ i,∏ j,∏ x ∈ s i,∏ y ∈ t j,diagonal (⟨i,x⟩ : Σi,A i) ⟨j,y⟩ ^ a i j + +omit [∀ i,DecidableEq (A i)] in +lemma kernel_polynomial_ratio (a : I → I → ℕ) (s t : Pack (A:=A)) : + kernel (pairKernel a) s t = + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (arrowNum a s t) / + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (sameDen s t) := by + rw [kernel_formula] + simp only [arrowNum,sameDen,map_prod,map_pow] + +omit [DecidableEq I] in +lemma sameDen_union_left (s t r : Pack (A:=A)) (h : ∀ i,Disjoint (s i) (t i)) : + sameDen (fun i=>s i ∪ t i) r = sameDen s r * sameDen t r := by + simp only [sameDen,Finset.prod_union (h _),Finset.prod_mul_distrib] + +omit [DecidableEq I] in +lemma sameDen_union_right (s t r : Pack (A:=A)) (h : ∀ i,Disjoint (t i) (r i)) : + sameDen s (fun i=>t i ∪ r i) = sameDen s t * sameDen s r := by + simp only [sameDen,Finset.prod_union (h _),Finset.prod_mul_distrib] + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma sameDen_ne_zero (s t : Pack (A:=A)) (h : ∀ i,Disjoint (s i) (t i)) : + sameDen s t ≠ 0 := by + apply Finset.prod_ne_zero_iff.mpr + intro i hi + apply Finset.prod_ne_zero_iff.mpr + intro x hx + apply Finset.prod_ne_zero_iff.mpr + intro y hy + apply diagonal_ne_zero + intro heq + have hxy : x=y := eq_of_heq (Sigma.mk.inj_iff.mp heq).2 + exact Finset.disjoint_left.mp (h i) hx (hxy.symm ▸ hy) + +omit [DecidableEq I] [∀ i,DecidableEq (A i)] in +lemma sameDen_reverse_dvd (s t : Pack (A:=A)) : sameDen s t ∣ sameDen t s := by + unfold sameDen + apply Finset.prod_dvd_prod_of_dvd + intro i hi + rw [Finset.prod_comm] + apply Finset.prod_dvd_prod_of_dvd + intro x hx + apply Finset.prod_dvd_prod_of_dvd + intro y hy + refine ⟨-1,?_⟩ + simp only [diagonal] + ring + +noncomputable def crossDen (q₁ q₂ r₁ r₂ : Pack (A:=A)) : MvPolynomial (Σi,A i) ℚ := + sameDen q₁ r₂ * sameDen r₁ q₂ + +omit [DecidableEq I] in +lemma crossDen_dvd {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) : + crossDen (left q) (right q) (left r) (right r) ∣ sameDen (left p) (right p) := by + have hq : (fun i=>left q i ∪ right q i) = left p := funext fun i=>(q i).property.2 + have hr : (fun i=>left r i ∪ right r i) = right p := funext fun i=>(r i).property.2 + conv_rhs => rw [← hq,← hr] + rw [sameDen_union_left (left q) (right q) (fun i=>left r i ∪ right r i) (fun i=>(q i).property.1), + sameDen_union_right (left q) (left r) (right r) (fun i=>(r i).property.1), + sameDen_union_right (right q) (left r) (right r) (fun i=>(r i).property.1)] + apply dvd_trans (mul_dvd_mul_left (sameDen (left q) (right r)) + (sameDen_reverse_dvd (left r) (right q))) + refine ⟨sameDen (left q) (left r) * sameDen (right q) (right r),?_⟩ + ac_rfl + +omit [DecidableEq I] in +lemma crossDen_ne_zero {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) : + crossDen (left q) (right q) (left r) (right r) ≠ 0 := by + apply mul_ne_zero + · exact sameDen_ne_zero _ _ (fun i=>(p i).property.1.mono (q i).left_subset (r i).right_subset) + · exact sameDen_ne_zero _ _ (fun i=>(p i).property.1.symm.mono (r i).left_subset (q i).right_subset) + +lemma crossKernel_polynomial (a : I → I → ℕ) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (q : PackConvolution.Cut (left p)) + (r : PackConvolution.Cut (right p)) : + ∃ N : MvPolynomial (Σi,A i) ℚ, + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (sameDen (left p) (right p)) * + kernel (pairKernel a) (left q) (right r) * + kernel (pairKernel a) (left r) (right q) = algebraMap _ _ N := by + obtain ⟨b,hb⟩ := crossDen_dvd p q r + refine ⟨b * arrowNum a (left q) (right r) * arrowNum a (left r) (right q),?_⟩ + have hn := crossDen_ne_zero p q r + have hn₁ : algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) + (sameDen (left q) (right r)) ≠ 0 := by + simpa only [map_zero] using + (IsFractionRing.injective (MvPolynomial (Σi,A i) ℚ) (FractionRing (MvPolynomial (Σi,A i) ℚ))).ne ((mul_ne_zero_iff.mp hn).1) + have hn₂ : algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) + (sameDen (left r) (right q)) ≠ 0 := by + simpa only [map_zero] using + (IsFractionRing.injective (MvPolynomial (Σi,A i) ℚ) (FractionRing (MvPolynomial (Σi,A i) ℚ))).ne ((mul_ne_zero_iff.mp hn).2) + rw [kernel_polynomial_ratio,kernel_polynomial_ratio,hb] + simp only [crossDen,map_mul] + field_simp + +noncomputable def crossKernelPolynomial (a : I → I → ℕ) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (q : PackConvolution.Cut (left p)) + (r : PackConvolution.Cut (right p)) : MvPolynomial (Σi,A i) ℚ := + (crossKernel_polynomial a p q r).choose + +lemma crossKernelPolynomial_spec (a : I → I → ℕ) {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (q : PackConvolution.Cut (left p)) + (r : PackConvolution.Cut (right p)) : + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (sameDen (left p) (right p)) * + kernel (pairKernel a) (left q) (right r) * + kernel (pairKernel a) (left r) (right q) = + algebraMap _ _ (crossKernelPolynomial a p q r) := + (crossKernel_polynomial a p q r).choose_spec + +variable [∀ i,Fintype (A i)] + +theorem shuffle_grid_cleared (a : I → I → ℕ) + (f g : Pack (A:=A) → MvPolynomial (Σi,A i) ℚ) + {s : Pack (A:=A)} (p : PackConvolution.Cut s) : + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (sameDen (left p) (right p)) * + PackConvolution.shuffle (pairKernel a) + (fun t=>algebraMap _ _ (f t)) (fun t=>algebraMap _ _ (g t)) s = + ∑ q : PackConvolution.Cut (left p), ∑ r : PackConvolution.Cut (right p), + algebraMap _ _ (f (fun i=>left q i ∪ left r i) * + g (fun i=>right q i ∪ right r i) * crossKernelPolynomial a p q r) * + kernel (pairKernel a) (left q) (right q) * + kernel (pairKernel a) (left r) (right r) := by + rw [PackConvolution.shuffle_grid _ _ _ p] + simp only [Finset.mul_sum,map_mul] + apply Finset.sum_congr rfl + intro q hq + apply Finset.sum_congr rfl + intro r hr + rw [← crossKernelPolynomial_spec] + ring + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + +abbrev CutShape (s : Pack (A:=A)) := ∀ i, Fin ((s i).card + 1) + +def cutShape {s : Pack (A:=A)} (q : PackConvolution.Cut s) : CutShape s := fun i => + ⟨(left q i).card, Nat.lt_succ_of_le (Finset.card_le_card (q i).left_subset)⟩ + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +lemma cutShape_eq_iff {s : Pack (A:=A)} (q : PackConvolution.Cut s) (d : CutShape s) : + cutShape q = d ↔ ∀ i,(left q i).card = (d i).val := by + constructor + · intro h i + exact congrArg Fin.val (congrFun h i) + · intro h + exact funext fun i=>Fin.ext (h i) + +noncomputable def cutByShape (s : Pack (A:=A)) : + PackConvolution.Cut s ≃ Σ d : CutShape s,SizedCut (fun i=>(d i).val) s := + (Equiv.sigmaFiberEquiv (cutShape (s:=s))).symm.trans + (Equiv.sigmaCongrRight fun d=>Equiv.subtypeEquivRight fun q=>cutShape_eq_iff q d) + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +@[simp] lemma cutByShape_snd (s : Pack (A:=A)) (q : PackConvolution.Cut s) : + (cutByShape s q).2.val = q := rfl + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +@[simp] lemma cutByShape_symm {s : Pack (A:=A)} + (d : CutShape s) (q : SizedCut (fun i=>(d i).val) s) : + (cutByShape s).symm ⟨d,q⟩ = q.val := rfl + +lemma sum_cut_by_shape {R : Type*} [AddCommMonoid R] (s : Pack (A:=A)) + (F : PackConvolution.Cut s → R) : + ∑ q, F q = ∑ d : CutShape s,∑ q : SizedCut (fun i=>(d i).val) s,F q.val := by + rw [← (cutByShape s).symm.sum_comp,Fintype.sum_sigma] + rfl + +lemma sum_grid_by_shape {R : Type*} [AddCommMonoid R] {s : Pack (A:=A)} + (p : PackConvolution.Cut s) + (F : PackConvolution.Cut (left p) → PackConvolution.Cut (right p) → R) : + ∑ q,∑ r,F q r = + ∑ d : CutShape (left p),∑ e : CutShape (right p), + ∑ q : SizedCut (fun i=>(d i).val) (left p), + ∑ r : SizedCut (fun i=>(e i).val) (right p),F q.val r.val := by + rw [sum_cut_by_shape] + simp_rw [sum_cut_by_shape (right p)] + apply Finset.sum_congr rfl + intro d hd + exact Finset.sum_comm + +def shapeComplement {s : Pack (A:=A)} (d : CutShape s) : I → ℕ := + fun i=>(s i).card - (d i).val + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] in +lemma shape_add_complement {s : Pack (A:=A)} (d : CutShape s) : + (fun i=>(d i).val) + shapeComplement d = (fun i=>(s i).card) := by + funext i + exact Nat.add_sub_of_le (Nat.le_of_lt_succ (d i).isLt) + +noncomputable def shapeRealization {s : Pack (A:=A)} (d : CutShape s) : + Realization ((fun i=>(d i).val) + shapeComplement d) s := + defaultRealization (fun i=>(congrFun (shape_add_complement d) i).symm) + +noncomputable def shapeCutEquiv {s : Pack (A:=A)} (d : CutShape s) : + Cut (fun i=>(d i).val) (shapeComplement d) ≃ SizedCut (fun i=>(d i).val) s := + cutRealizationEquiv (shapeRealization d) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SeparationCoefficients.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SeparationCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..765af9e17c9addb4b4b5c151626d65b346a6b1ca --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SeparationCoefficients.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.TensorFiltration +import OAI.Combinatorics.Chromatic.Shuffle.CrossScalar +import OAI.Combinatorics.Chromatic.Walls.TensorFiltrationIdeals +import OAI.Combinatorics.Chromatic.Walls.LaurentPolynomialAction + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +namespace SeparationInfinity + +noncomputable def separationSeries (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + obtain ⟨u,v,f,g,hw,hf,hg,rfl⟩:=hx + rw [TensorProduct.map_tmul,LinearMap.id_apply] + exact tmul_mem_additiveTensorFiltration _ _ hw + (sourceFiltration_translation_mem a c η hc θ d u f hf t) hg + | zero => rw [map_zero]; exact (sourceTensorFiltration a c η hc θ d e W).zero_mem + | add x y _ _ hx hy => + rw [map_add] + exact (sourceTensorFiltration a c η hc θ d e W).add_mem hx hy + | smul q x _ hx => + rw [map_smul] + exact (sourceTensorFiltration a c η hc θ d e W).smul_mem q hx + +lemma restrictionRelativeB_coeff_filtration (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ)) _).sub + (isWeightedHomogeneous_X ℚ (fun _=>(1:ℤ)) _)) _ + have he : (∑ i,∑ j,∑ _x : Fin (d i),∑ _y : Fin (e j),inverseExponent a i j)=eulerForm a d e := by + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] + unfold eulerForm + rw [← ElementaryPositivity.inverseEuler_exponent a d e] + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + unfold inverseExponent + ring + rwa [he] at h +omit [Fintype I] [DecidableEq I] in +lemma relativeRaw_homogeneous (d e : I → ℕ) (f : MvPolynomial (CellVars d e) ℚ) + (ℓ : ℤ) (hf : f.IsWeightedHomogeneous (fun _=>(1:ℤ)) ℓ) : + IsHomogeneous (polynomial (relativeRaw d e f)) ℓ := by + apply homogeneous_ringHom (polynomial.comp (relativeRaw d e).toRingHom) _ _ f ℓ hf + · intro q + show IsHomogeneous (polynomial (relativeRaw d e (MvPolynomial.C q))) 0 + rw [show relativeRaw d e (MvPolynomial.C q)=Polynomial.C (MvPolynomial.C q) by simp [relativeRaw],polynomial_C] + change IsHomogeneous (single 0 (MvPolynomial.C q)) 0 + simpa only [sub_zero] using homogeneous_single 0 0 (MvPolynomial.C q) (isWeightedHomogeneous_C _ _) + · intro v + rcases v with (v|v) + · show IsHomogeneous (polynomial (relativeRaw d e (X (Sum.inl v)))) 1 + rw [show relativeRaw d e (X (Sum.inl v))=Polynomial.C (X (Sum.inl v))+Polynomial.X by simp [relativeRaw]] + rw [map_add,polynomial_C,polynomial_X,zUnit_val] + apply LaurentAtInfinity.IsHomogeneous.add + · change IsHomogeneous (single 0 (X (Sum.inl v))) 1 + simpa only [sub_zero] using homogeneous_single 0 1 (X (Sum.inl v)) (isWeightedHomogeneous_X ℚ _ _) + · simpa using homogeneous_single (-1) 0 (1 : MvPolynomial (CellVars d e) ℚ) (isWeightedHomogeneous_one _ _) + · show IsHomogeneous (polynomial (relativeRaw d e (X (Sum.inr v)))) 1 + rw [show relativeRaw d e (X (Sum.inr v))=Polynomial.C (X (Sum.inr v)) by simp [relativeRaw]] + rw [polynomial_C] + change IsHomogeneous (single 0 (X (Sum.inr v))) 1 + simpa only [sub_zero] using homogeneous_single 0 1 (X (Sum.inr v)) (isWeightedHomogeneous_X ℚ _ _) +noncomputable def rawSeparationSeries (a : I → I → ℕ) (d e : I → ℕ) (f : S (d+e)) : + LaurentSeries (MvPolynomial (CellVars d e) ℚ) := + (rawInverseKernelUnit a d e).val * polynomial (relativeRaw d e (rename (cutSplit (firstCut d e)).symm f.val)) +lemma rawSeparationSeries_homogeneous (a : I → I → ℕ) (d e : I → ℕ) + (f : S (d+e)) (ℓ : ℤ) (hf : f.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) ℓ) : + IsHomogeneous (rawSeparationSeries a d e f) (ℓ+eulerForm a d e) := by + have h:=(rawInverseKernel_homogeneous a d e).mul + (relativeRaw_homogeneous d e _ ℓ (constantWeight_rename (cutSplit (firstCut d e)).symm f.val hf)) + simpa only [rawSeparationSeries,add_comm] using h +end ElementaryPositivity.RawShuffle.SeparationInfinity + +end +section +namespace ElementaryPositivity.RawShuffle.SeparationInfinity +open MvPolynomial HahnSeries +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.SeparatedSymmetry ElementaryPositivity.Homogeneity +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +noncomputable def tensorSeparationSeries (a : I → I → ℕ) (d e : I → ℕ) (f : S (d+e)) : + LaurentSeries (S d ⊗[ℚ] S e) := + (inverseKernelUnit a d e).val * polynomial (R:=S d ⊗[ℚ] S e) (relativeTaylor d e (restrictTensor (firstCut d e) f)) +lemma realize_tensorSeparationSeries (a : I → I → ℕ) (d e : I → ℕ) (f : S (d+e)) : + mapRing (R:=S d ⊗[ℚ] S e) (S:=MvPolynomial (CellVars d e) ℚ) (tensorValueAlg d e).toRingHom (tensorSeparationSeries a d e f)=rawSeparationSeries a d e f := by + rw [tensorSeparationSeries,mapRing_mul_polynomial,realize_inverseKernelUnit, + map_relativeTaylor,tensorValue_restrictTensor] + rfl +lemma tensorSeparationSeries_coeff (a : I → I → ℕ) (d e : I → ℕ) (f : S (d+e)) (k : ℤ) : + (tensorSeparationSeries a d e f).coeff k= + separateTensor d e ((rawSeparationSeries a d e f).coeff k) := by + rw [← realize_tensorSeparationSeries,mapRing_coeff] + exact (separateTensor_tensorValue d e _).symm +lemma separationSeries_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ)) ℓ) + (hmn : m+n≠ℓ+eulerForm a d e-j) : + TensorProduct.map (componentB a (SlopeArithmetic.slope c η) d m) + (componentB a (SlopeArithmetic.slope c η) e n) + (separationCoefficient a c η hc hs j (quotientAlg a (SlopeArithmetic.slope c η) (d+e) f))=0 := by + rw [separationCoefficient_mk_raw,component_quotientTensor] + have h:=rawSeparationSeries_homogeneous a d e f ℓ hf (-j) + rw [component_separateTensor_homogeneous d e _ _ h m n (by simpa only [sub_eq_add_neg] using hmn),map_zero] + +theorem separationCoefficient_aboveDegree (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ)) ℓ) + (hj : ℓ+eulerForm a d e simp only [mul_add,map_add,hx,hy] + | tmul x y => + apply localizeS_injective + rw [←tensorShuffle_tensorValue,tensorValue_mul] + change tensorShuffle a (tensorValue d e (restrictTensor A f)*tensorValue d e (x⊗ₜ[ℚ]y))=_ + rw [tensorValue_restrictTensor,tensorValue_tmul,tensorShuffle_restricted_mul] + rw [←shufflePolynomial_eq,shuffleTensorLinear_tmul] + exact (map_mul (algebraMap (MvPolynomial (Σi,Fin (d i+e i)) ℚ) + (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ))) f.val (shufflePolynomial a x y).val).symm + +noncomputable def restrictRows (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + S (d₁+e₁)⊗[ℚ]S (d₂+e₂) →ₐ[ℚ] (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂) := + Algebra.TensorProduct.map (restrictTensorAlg A) (restrictTensorAlg B) + +lemma twoTarget_projection (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) + (f : S (d₁+e₁)⊗[ℚ]S (d₂+e₂)) + (x : (S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) : + twoTargetTransfer a d₁ e₁ d₂ e₂ (restrictRows d₁ e₁ d₂ e₂ A B f*x)= + f*twoTargetTransfer a d₁ e₁ d₂ e₂ x := + tensor_map_projection _ _ _ _ (shuffleTensor_projection a A) (shuffleTensor_projection a B) f x + +lemma twoTarget_Laurent_projection (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ e₁) (B : Cut d₂ e₂) + (f : LaurentSeries (S (d₁+e₁)⊗[ℚ]S (d₂+e₂))) + (x : LaurentSeries ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂))) : + mapLinear (twoTargetTransfer a d₁ e₁ d₂ e₂) + (mapRing (restrictRows d₁ e₁ d₂ e₂ A B).toRingHom f*x)= + f*mapLinear (twoTargetTransfer a d₁ e₁ d₂ e₂) x := + mapLinear_projection _ _ (twoTarget_projection a d₁ e₁ d₂ e₂ A B) f x + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.SeparatedSymmetry +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.RectangularKernel +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable local instance rowTensorRing (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance rowTensorAlgebra (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance rowFourRing (d₁ e₁ d₂ e₂ : I → ℕ) : + CommRing ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance +noncomputable local instance rowFourAlgebra (d₁ e₁ d₂ e₂ : I → ℕ) : + Algebra ℚ ((S d₁⊗[ℚ]S e₁)⊗[ℚ](S d₂⊗[ℚ]S e₂)) := inferInstance + +omit [Fintype I] [DecidableEq I] in +lemma cutSplit_pack {d e : I → ℕ} (A : Cut d e) (i : I) + (x : Fin (d i)⊕Fin (e i)) : + (cutSplit A).symm ⟨i,packSplit A i x⟩=(Equiv.sigmaSumDistrib _ _) ⟨i,x⟩ := by + apply (cutSplit A).injective + rw [Equiv.apply_symm_apply] + cases x <;> rfl + +noncomputable def rowSplitEquiv {d₁ e₁ d₂ e₂ : I → ℕ} + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + CellVars (d₁+e₁) (d₂+e₂) ≃ CellVars d₁ e₁⊕CellVars d₂ e₂ := + Equiv.sumCongr (cutSplit A).symm (cutSplit B).symm + +omit [Fintype I] in +lemma rowSplit_rawFactor (a : I → I → ℕ) {d₁ e₁ d₂ e₂ : I → ℕ} + (A : Cut d₁ e₁) (B : Cut d₂ e₂) (i j : I) + (x : Fin (d₁ i)⊕Fin (e₁ i)) (y : Fin (d₂ j)⊕Fin (e₂ j)) : + Units.map (mapRing (rename (rowSplitEquiv A B)).toRingHom).toMonoidHom + (SeparationInfinity.rawFactor a (d₁+e₁) (d₂+e₂) i j (packSplit A i x) (packSplit B j y))= + fourAffine d₁ e₁ d₂ e₂ i j x y ^ SeparationInfinity.inverseExponent a i j := by + unfold SeparationInfinity.rawFactor + rw [map_zpow,affineUnit_map] + congr 2 + simp only [AlgHom.toRingHom_eq_coe,RingHom.coe_coe,map_sub,rename_X,rowSplitEquiv, + Equiv.sumCongr_apply,Sum.map_inl,Sum.map_inr,cutSplit_pack] + rfl + +lemma rowSplit_inverseKernel (a : I → I → ℕ) {d₁ e₁ d₂ e₂ : I → ℕ} + (A : Cut d₁ e₁) (B : Cut d₂ e₂) : + Units.map (mapRing (rename (rowSplitEquiv A B)).toRingHom).toMonoidHom + (SeparationInfinity.rawInverseKernelUnit a (d₁+e₁) (d₂+e₂))= + fourTotalInverseUnit a d₁ e₁ d₂ e₂ := by + simp only [SeparationInfinity.rawInverseKernelUnit,map_prod,fourTotalInverseUnit,rectangular] + apply Finset.prod_congr rfl + intro i hi + apply Finset.prod_congr rfl + intro j hj + calc + _ = ∏ x : Fin (d₁ i)⊕Fin (e₁ i), ∏ y : Fin (d₂ j+e₂ j), + Units.map (mapRing (rename (rowSplitEquiv A B)).toRingHom).toMonoidHom + (SeparationInfinity.rawFactor a (d₁+e₁) (d₂+e₂) i j (packSplit A i x) y) := + (Equiv.prod_comp (packSplit A i) _).symm + _ = _ := by + apply Finset.prod_congr rfl + intro x hx + calc + _ = ∏ y : Fin (d₂ j)⊕Fin (e₂ j), + Units.map (mapRing (rename (rowSplitEquiv A B)).toRingHom).toMonoidHom + (SeparationInfinity.rawFactor a (d₁+e₁) (d₂+e₂) i j (packSplit A i x) (packSplit B j y)) := + (Equiv.prod_comp (packSplit B j) _).symm + _ = _ := Finset.prod_congr rfl (fun y hy=>rowSplit_rawFactor a A B i j x y) + +lemma fourValue_restrictRows {d₁ e₁ d₂ e₂ : I → ℕ} + (A : Cut d₁ e₁) (B : Cut d₂ e₂) (x : S (d₁+e₁)⊗[ℚ]S (d₂+e₂)) : + fourValue d₁ e₁ d₂ e₂ (restrictRows d₁ e₁ d₂ e₂ A B x)= + rename (rowSplitEquiv A B) (tensorValue (d₁+e₁) (d₂+e₂) x) := by + change fourValue d₁ e₁ d₂ e₂ (TensorProduct.map (restrictTensor A) (restrictTensor B) x)=_ + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => + change fourValue d₁ e₁ d₂ e₂ (restrictTensor A x⊗ₜ[ℚ]restrictTensor B y)=_ + rw [fourValue_tmul,tensorValue_restrictTensor,tensorValue_restrictTensor,tensorValue_tmul] + simp only [map_mul,rename_rename] + rfl + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/ShuffleUnits.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/ShuffleUnits.lean new file mode 100644 index 0000000000000000000000000000000000000000..de06b869eb0f90085a34815f147b91dd113f71ea --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/ShuffleUnits.lean @@ -0,0 +1,216 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.ComponentB + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + +omit [DecidableEq I] [∀ i,Fintype (A i)] in +lemma labeledValue_unit (s : Pack (A:=A)) : + labeledValue (1 : S (0 : I → ℕ)) s=if s=(fun _=>∅) then 1 else 0 := by + classical + by_cases hs : s=(fun _=>∅) + · subst s + simp [labeledValue,valueAt] + · have h : ¬∀ i,(s i).card=(0 : I → ℕ) i := by + intro h + exact hs (funext fun i=>Finset.card_eq_zero.mp (h i)) + simp only [labeledValue,dite_eq_right h,ite_eq_right hs] + +def emptyLeftCut (s : Pack (A:=A)) : PackConvolution.Cut s := + fun i=>⟨(∅,s i),by simp⟩ + +def emptyRightCut (s : Pack (A:=A)) : PackConvolution.Cut s := + fun i=>⟨(s i,∅),by simp⟩ + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +lemma eq_emptyLeftCut {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (h : left p=fun _=>∅) : p=emptyLeftCut s := by + funext i + apply Subtype.ext + apply Prod.ext + · exact congrFun h i + · have hh := (p i).property.2 + change (p i).val.1 ∪ (p i).val.2=s i at hh + have hi : (p i).val.1=∅ := congrFun h i + simpa only [emptyLeftCut,hi,Finset.empty_union] using hh + +omit [Fintype I] [DecidableEq I] [∀ i,Fintype (A i)] in +lemma eq_emptyRightCut {s : Pack (A:=A)} (p : PackConvolution.Cut s) + (h : right p=fun _=>∅) : p=emptyRightCut s := by + funext i + apply Subtype.ext + apply Prod.ext + · have hh := (p i).property.2 + change (p i).val.1 ∪ (p i).val.2=s i at hh + have hi : (p i).val.2=∅ := congrFun h i + simpa only [emptyRightCut,hi,Finset.union_empty] using hh + · exact congrFun h i + +lemma shuffle_labeled_unit_left (a : I → I → ℕ) (d : I → ℕ) (f : S d) + (s : Pack (A:=A)) : + PackConvolution.shuffle (pairKernel a) (labeledValue (1 : S (0 : I → ℕ))) + (labeledValue f) s=labeledValue f s := by + classical + unfold PackConvolution.shuffle + rw [Finset.sum_eq_single (emptyLeftCut s)] + · have hL : left (emptyLeftCut s)=fun _=>∅ := rfl + have hR : right (emptyLeftCut s)=s := rfl + rw [labeledValue_unit,ite_eq_left hL,hR] + simp [hL,PackConvolution.kernel] + · intro p hp hne + have h : left p≠(fun _=>∅) := fun hh=>hne (eq_emptyLeftCut p hh) + simp only [labeledValue_unit,ite_eq_right h,zero_mul] + · simp + +lemma shuffle_labeled_unit_right (a : I → I → ℕ) (d : I → ℕ) (f : S d) + (s : Pack (A:=A)) : + PackConvolution.shuffle (pairKernel a) (labeledValue f) + (labeledValue (1 : S (0 : I → ℕ))) s=labeledValue f s := by + classical + unfold PackConvolution.shuffle + rw [Finset.sum_eq_single (emptyRightCut s)] + · have hR : right (emptyRightCut s)=fun _=>∅ := rfl + have hL : left (emptyRightCut s)=s := rfl + rw [labeledValue_unit,ite_eq_left hR,hL] + simp [hR,PackConvolution.kernel] + · intro p hp hne + have h : right p≠(fun _=>∅) := fun hh=>hne (eq_emptyRightCut p hh) + simp only [labeledValue_unit,ite_eq_right h,mul_zero,zero_mul] + · simp + +lemma shufflePolynomial_unit_left (a : I → I → ℕ) (d : I → ℕ) (f : S d) : + shufflePolynomial a (1 : S (0 : I → ℕ)) f=castS (zero_add d).symm f := by + classical + let s : Pack (A:=fun i=>Fin ((0+d) i)) := fun _=>Finset.univ + let r : Realization (0+d) s := defaultRealization (by intro i; simp [s]) + apply labeledValue_injective r + dsimp only + rw [labeledValue_shuffle,labeledValue_cast] + exact shuffle_labeled_unit_left a d f s + +lemma shufflePolynomial_unit_right (a : I → I → ℕ) (d : I → ℕ) (f : S d) : + shufflePolynomial a f (1 : S (0 : I → ℕ))=castS (add_zero d).symm f := by + classical + let s : Pack (A:=fun i=>Fin ((d+0) i)) := fun _=>Finset.univ + let r : Realization (d+0) s := defaultRealization (by intro i; simp [s]) + apply labeledValue_injective r + dsimp only + rw [labeledValue_shuffle,labeledValue_cast] + exact shuffle_labeled_unit_right a d f s + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [Fintype I] [DecidableEq I] in +lemma S_zero_eq_scalar (f : S (0 : I → ℕ)) : + f=constantCoeff f.val • (1 : S (0 : I → ℕ)) := by + let : IsEmpty (Σi : I, Fin ((0 : I → ℕ) i)) := ⟨fun x => Fin.elim0 x.2⟩ + rw [←Algebra.algebraMap_eq_smul_one] + apply Subtype.ext + exact eq_C_of_isEmpty f.val + +lemma destabilizingSpace_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) : + destabilizingSpace a μ 0=⊥ := by + apply le_antisymm _ bot_le + apply Submodule.span_le.mpr + rintro f ⟨u,v,h,f',g',hu,hv,_,_⟩ + exact (hu (add_eq_zero.mp h).1).elim + +lemma castS_mem_destabilizing (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (h : d=e) {f : S d} (hf : f∈destabilizingSpace a μ d) : + castS h f∈destabilizingSpace a μ e := by + subst e + exact hf + +lemma destabilizing_shuffle_unit_left (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 (destabilizingSpace a (slope c η) e).mapQ J + (shuffleLinear a d e f) (by + intro g hg + exact destabilizing_shuffle_unit_right a c η hc hs f hg) + map_add' := by + intro f g + apply LinearMap.ext + intro x + induction x using Submodule.Quotient.induction_on with + | H x => exact congrArg J.mkQ (shufflePolynomial_add_left a f g x) + map_smul' := by + intro r f + apply LinearMap.ext + intro x + induction x using Submodule.Quotient.induction_on with + | H x => exact congrArg J.mkQ (shufflePolynomial_smul_left a r f x) } + exact (destabilizingSpace a (slope c η) d).liftQ L (by + intro f hf + apply LinearMap.mem_ker.mpr + apply LinearMap.ext + intro g + induction g using Submodule.Quotient.induction_on with + | H g => + exact (Submodule.Quotient.mk_eq_zero _).mpr + (destabilizing_shuffle_unit_left a c η hc hs hf g)) + +@[simp] lemma shuffleBUnit_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + induction g using Submodule.Quotient.induction_on with + | H g => rfl + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SignedCoproductGridGrade.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SignedCoproductGridGrade.lean new file mode 100644 index 0000000000000000000000000000000000000000..7051635ab3ebc272f104da2119496b6470e4029d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SignedCoproductGridGrade.lean @@ -0,0 +1,189 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.DimensionGrid +import OAI.Combinatorics.Chromatic.Shuffle.CellLeadingSum +import OAI.Combinatorics.Chromatic.Shuffle.UnitalGrade + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +variable {M : Type*} [AddCommGroup M] [Module ℚ M] +lemma mk_eq_mk_iff_sub_mem (F G : Submodule ℚ M) (x y : F) : + mk F G x = mk F G y ↔ x.val-y.val∈G := by + rw [←sub_eq_zero,←map_sub] + exact Submodule.Quotient.mk_eq_zero _ +end ElementaryPositivity.LinearFiltration + +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration +open ElementaryPositivity.PackConvolution ElementaryPositivity.LinearDetection +open SeparationInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + +lemma unitalSourceTensorFiltration_antitone (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 finCongr (congrArg (·+1) (congrFun (realization_card R) i)) + +omit [Fintype I] [DecidableEq I] [∀ index, Fintype (A index)] [∀ index, DecidableEq (A index)] in +@[simp] lemma cutShapeDimensionEquiv_left {d : I → ℕ} {s : Pack (A:=A)} + (R : Realization d s) (u : CutShape s) : + DimensionSplit.left (cutShapeDimensionEquiv R u) = (fun i=>(u i).val) := rfl + +omit [Fintype I] [DecidableEq I] [∀ index, Fintype (A index)] [∀ index, DecidableEq (A index)] in +@[simp] lemma cutShapeDimensionEquiv_right {d : I → ℕ} {s : Pack (A:=A)} + (R : Realization d s) (u : CutShape s) : + DimensionSplit.right (cutShapeDimensionEquiv R u) = shapeComplement u := by + funext i + change d i-(u i).val=(s i).card-(u i).val + exact congrArg (fun n=>n-(u i).val) (congrFun (realization_card R) i).symm + +omit [∀ index, Fintype (A index)] [∀ index, DecidableEq (A index)] in +lemma sum_cutShapeDimensionEquiv {d : I → ℕ} {s : Pack (A:=A)} + (R : Realization d s) {M : Type*} [AddCommMonoid M] (F : DimensionSplit d → M) : + ∑ u : CutShape s,F (cutShapeDimensionEquiv R u)=∑ u : DimensionSplit d,F u := + Equiv.sum_comp (cutShapeDimensionEquiv R) F + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.PackConvolution +open DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +noncomputable def dimensionRowLeadingB (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + ∑ v : DimensionSplit β,dimensionRowLeadingB a c η hc θ f g u v) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SignedTensorGradeProduct.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SignedTensorGradeProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a485deee2fb313d4534d0b3e94ee699a0c4ee23 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SignedTensorGradeProduct.lean @@ -0,0 +1,281 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalGradeAlgebra +import OAI.Combinatorics.Chromatic.Shuffle.DimensionColumnLeading + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearDetection +open ElementaryPositivity.LinearFiltration +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def signedCellMultiplyB (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0signedCellMultiplyB_filtered a c η hc θ hχ d₁ e₁ d₂ e₂ hon U V x y hx hy) + (fun x hx y hy=>by simpa only [add_right_comm] using + signedCellMultiplyB_filtered a c η hc θ hχ d₁ e₁ d₂ e₂ hon (U+1) V x y hx hy) + (fun x hx y hy=>by simpa only [add_assoc] using + signedCellMultiplyB_filtered a c η hc θ hχ d₁ e₁ d₂ e₂ hon U (V+1) x y hx hy) + +lemma signedCellGradeMultiply_mk (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0unitalSeparationSeries_coeff_filtration a c η hc θ _ _ (hp.1.compatible hp.2) W 0 x hx)).comp + (unitalFiltrationCast a c η hc θ (left_add_right p).symm rfl).toLinearMap + +noncomputable def splitCoproductGrade (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0signedCellMultiplyB a c η hc θ _ _ _ _ hon x y) + · exact splitCoproductFiltration_val_mk a c η hc θ _ _ U f hf + · exact splitCoproductFiltration_val_mk a c η hc θ _ _ V g hg + · rfl + +theorem unitalGradeCoproduct_shuffle_column (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + induction y using Submodule.Quotient.induction_on with + | H y => + rcases x with ⟨x,hx⟩ + rcases y with ⟨y,hy⟩ + induction x using Submodule.Quotient.induction_on with + | H f => + induction y using Submodule.Quotient.induction_on with + | H g => + simp only [unitalGradeShuffle_mk,unitalGradeCast_mk,unitalGradeCoproduct_mk, + columnGradeTerm_mk] + change mk _ _ _=∑ s : ColumnDimensionGrid d e α β, + mk _ _ (columnFiltrationTerm a c η hc θ hχ U V ⟨_,hx⟩ ⟨_,hy⟩ s) + rw [←map_sum] + apply (mk_eq_mk_iff_sub_mem _ _ _ _).mpr + dsimp only [Subtype.coe_mk] + rw [unitalFiltrationCast_val] + have hv : (∑ s : ColumnDimensionGrid d e α β, + columnFiltrationTerm a c η hc θ hχ U V ⟨_,hx⟩ ⟨_,hy⟩ s).val= + ∑ s : ColumnDimensionGrid d e α β,dimensionColumnLeadingB a c η hc θ f g s := by + rw [Submodule.coe_sum] + exact Finset.sum_congr rfl (fun s _=>columnFiltrationTerm_val_mk a c η hc θ hχ U V f g hx hy s) + rw [hv] + change (unitalSeparationSeries a c η hc (hα.compatible hβ) + (castB a (slope c η) h (quotientAlg a (slope c η) (d+e) (shufflePolynomial a f g)))).coeff 0-_∈_ + rw [castB_mk] + let R : Realization (α+β) (A:=fun i=>Fin ((α+β) i)) (fun _=>Finset.univ) := + fun _=>(Equiv.subtypeUnivEquiv (fun _=>Finset.mem_univ _)).symm + exact unitalSeparationConstant_shuffle_column a c η hc θ hχ h U V f g hx hy hα hβ hd R + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SlopeGridSum.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SlopeGridSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3be344c01490d9ffd68eff13b036760ee27879e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SlopeGridSum.lean @@ -0,0 +1,189 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalTensorGradeProduct + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +abbrev SlopeColumnGrid (c η : I → ℝ) (θ : ℝ) (d e α β : I → ℕ) := + {s : ColumnDimensionGrid d e α β // + CellsOnSlope c η θ (left s.val.1) (left s.val.2) (right s.val.1) (right s.val.2)} + +noncomputable def slopeColumnEquiv (c η : I → ℝ) (hc : ∀ i,0(⟨z.2.val.val.1,⟨z.2.property.1,z.2.property.2.2.1⟩⟩, + ⟨z.2.val.val.2,⟨z.2.property.2.1,z.2.property.2.2.2⟩⟩)) (by + constructor + · rintro ⟨t,s⟩ ⟨t',s'⟩ h + have h₁ : s.val.val.1=s'.val.val.1 := congrArg (fun z=>z.1.val) h + have h₂ : s.val.val.2=s'.val.val.2 := congrArg (fun z=>z.2.val) h + have ht : t=t' := by + apply Subtype.ext + apply DimensionSplit.ext + exact s.val.property.1.symm.trans ((congrArg₂ (fun p q=>left p+left q) h₁ h₂).trans s'.val.property.1) + subst t' + have hs : s=s' := Subtype.ext (Subtype.ext (Prod.ext h₁ h₂)) + exact congrArg (fun z=>Sigma.mk t z) hs + · rintro ⟨p,q⟩ + have hsum : (left p.val+left q.val)+(right p.val+right q.val)=d+e := by + calc + _=(left p.val+right p.val)+(left q.val+right q.val) := by abel + _=_ := by rw [left_add_right,left_add_right] + let t : SlopeSplit c η hc θ (d+e) := + ⟨ofPair (left p.val+left q.val) (right p.val+right q.val) hsum,by + simpa only [left_ofPair,right_ofPair] using + And.intro (p.property.1.add hc q.property.1) (p.property.2.add hc q.property.2)⟩ + let s : SlopeColumnGrid c η θ d e (left t.val) (right t.val) := + ⟨⟨(p.val,q.val),by simp [t]⟩,p.property.1,q.property.1,p.property.2,q.property.2⟩ + exact ⟨⟨t,s⟩,rfl⟩) + +lemma sum_dite_zero_subtype {A M : Type*} [Fintype A] [AddCommMonoid M] + (p : A → Prop) [DecidablePred p] (F : ∀ x,p x → M) : + (∑ x,if h : p x then F x h else 0)=∑ x : {x // p x},F x.val x.property := by + have h := (Fintype.sum_subtype_add_sum_subtype p (fun x=>if h:p x then F x h else 0)).symm + refine h.trans ?_ + have hn : (∑ x : {x // ¬p x},if hx:p x.val then F x.val hx else 0)=0 := by + apply Finset.sum_eq_zero + intro x _ + exact dite_eq_right x.property + rw [hn,add_zero] + exact Finset.sum_congr rfl (fun x _=>dite_eq_left x.property) + +lemma sum_slope_column (c η : I → ℝ) (hc : ∀ i,0F z.1 z.2) + _=_ := Fintype.sum_prod_type _ + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration DimensionSplit +open scoped TensorProduct DirectSum +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +lemma globalSplitCoproduct_eq (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0globalColumnGradeTerm a c η hc θ d e U V x y t s) + +lemma globalCoproduct_mul_lof (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0globalSplitCoproduct_shuffle a c η hc θ d e U V x y t) + _=_ := by + have h := sum_slope_column c η hc θ d.val e.val + (fun p q=>globalSignedTensorMultiply a c η hc θ + (globalSplitCoproduct a c η hc θ (d,U) p x) + (globalSplitCoproduct a c η hc θ (e,V) q y)) + exact h.trans (Finset.sum_comm) + +theorem globalCoproduct_mul (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [zero_mul,map_zero,LinearMap.zero_apply] + | add x x' hx hx' => simp only [add_mul,map_add,LinearMap.add_apply,hx,hx'] + | of k x => + induction y using DirectSum.induction_on with + | zero => simp only [mul_zero,map_zero] + | add y y' hy hy' => simp only [mul_add,map_add,hy,hy'] + | of l y => exact globalCoproduct_mul_lof a c η hc θ k.1 l.1 k.2 l.2 x y + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/Split.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/Split.lean new file mode 100644 index 0000000000000000000000000000000000000000..d727147a2b5a973202a1f0215c4d675c26e42380 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/Split.lean @@ -0,0 +1,139 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.ShuffleConvolution +variable {A R : Type*} [Fintype A] [DecidableEq A] [CommSemiring R] + +def Split (s : Finset A) := {p : Finset A × Finset A // Disjoint p.1 p.2 ∧ p.1 ∪ p.2 = s} +instance (s : Finset A) : Fintype (Split s) := by unfold Split; infer_instance +instance (s : Finset A) : DecidableEq (Split s) := by unfold Split; infer_instance + +omit [Fintype A] in +lemma Split.left_subset {s : Finset A} (p : Split s) : p.val.1 ⊆ s := by + intro a ha + have hm := Finset.mem_union_left p.val.2 ha + simpa only [p.property.2] using hm +omit [Fintype A] in +lemma Split.right_subset {s : Finset A} (p : Split s) : p.val.2 ⊆ s := by + intro a ha + have hm := Finset.mem_union_right p.val.1 ha + simpa only [p.property.2] using hm + +abbrev LeftIndex (s : Finset A) := Σ p : Split s, Split p.val.1 +abbrev RightIndex (s : Finset A) := Σ p : Split s, Split p.val.2 + +def rebracket (s : Finset A) : LeftIndex s ≃ RightIndex s where + toFun z := by + let a := z.2.val.1 + let b := z.2.val.2 + let c := z.1.val.2 + have hab : Disjoint a b := z.2.property.1 + have hac : Disjoint a c := z.1.property.1.mono_left z.2.left_subset + have hbc : Disjoint b c := z.1.property.1.mono_left z.2.right_subset + have hu : a ∪ (b ∪ c) = s := by + rw [← Finset.union_assoc, z.2.property.2, z.1.property.2] + exact ⟨⟨(a,b∪c),⟨Finset.disjoint_union_right.mpr ⟨hab,hac⟩,hu⟩⟩, + ⟨(b,c),⟨hbc,rfl⟩⟩⟩ + invFun z := by + let a := z.1.val.1 + let b := z.2.val.1 + let c := z.2.val.2 + have hab : Disjoint a b := z.1.property.1.mono_right z.2.left_subset + have hac : Disjoint a c := z.1.property.1.mono_right z.2.right_subset + have hbc : Disjoint b c := z.2.property.1 + have hu : (a∪b)∪c = s := by + rw [Finset.union_assoc, z.2.property.2, z.1.property.2] + exact ⟨⟨(a∪b,c),⟨Finset.disjoint_union_left.mpr ⟨hac,hbc⟩,hu⟩⟩, + ⟨(a,b),⟨hab,rfl⟩⟩⟩ + left_inv z := by + rcases z with ⟨⟨⟨ab,c⟩,hac,hu⟩,⟨⟨a,b⟩,hab,habu⟩⟩ + dsimp at habu + subst ab + rfl + right_inv z := by + rcases z with ⟨⟨⟨a,bc⟩,hac,hu⟩,⟨⟨b,c⟩,hbc,hbcu⟩⟩ + dsimp at hbcu + subst bc + rfl + +def kernel (w : A → A → R) (a b : Finset A) : R := ∏ x ∈ a, ∏ y ∈ b, w x y + +omit [Fintype A] in +lemma kernel_union_left (w : A → A → R) (a b c : Finset A) (hab : Disjoint a b) : + kernel w (a∪b) c = kernel w a c * kernel w b c := by + exact Finset.prod_union hab + +omit [Fintype A] in +lemma kernel_union_right (w : A → A → R) (a b c : Finset A) (hbc : Disjoint b c) : + kernel w a (b∪c) = kernel w a b * kernel w a c := by + simp only [kernel, Finset.prod_union hbc, Finset.prod_mul_distrib] + +omit [Fintype A] in +lemma kernel_cocycle (w : A → A → R) (a b c : Finset A) + (hab : Disjoint a b) (hbc : Disjoint b c) : + kernel w a b * kernel w (a∪b) c = + kernel w b c * kernel w a (b∪c) := by + rw [kernel_union_left w a b c hab, kernel_union_right w a b c hbc] + ac_rfl + +def shuffle (w : A → A → R) (f g : Finset A → R) (s : Finset A) : R := + ∑ p : Split s, f p.val.1 * g p.val.2 * kernel w p.val.1 p.val.2 + +lemma shuffle_assoc (w : A → A → R) (f g h : Finset A → R) : + shuffle w (shuffle w f g) h = shuffle w f (shuffle w g h) := by + funext s + have lhs : shuffle w (shuffle w f g) h s = + ∑ z : LeftIndex s, + (f z.2.val.1 * g z.2.val.2 * kernel w z.2.val.1 z.2.val.2) * + h z.1.val.2 * kernel w z.1.val.1 z.1.val.2 := by + simp only [shuffle, Fintype.sum_sigma, Finset.sum_mul] + have rhs : shuffle w f (shuffle w g h) s = + ∑ z : RightIndex s, + f z.1.val.1 * (g z.2.val.1 * h z.2.val.2 * kernel w z.2.val.1 z.2.val.2) * + kernel w z.1.val.1 z.1.val.2 := by + simp only [shuffle, Fintype.sum_sigma, Finset.mul_sum, Finset.sum_mul] + rw [lhs,rhs,← (rebracket s).sum_comp] + apply Finset.sum_congr rfl + intro z hz + change (f z.2.val.1 * g z.2.val.2 * kernel w z.2.val.1 z.2.val.2) * + h z.1.val.2 * kernel w z.1.val.1 z.1.val.2 = + f z.2.val.1 * (g z.2.val.2 * h z.1.val.2 * kernel w z.2.val.2 z.1.val.2) * + kernel w z.2.val.1 (z.2.val.2 ∪ z.1.val.2) + have hc := kernel_cocycle w z.2.val.1 z.2.val.2 z.1.val.2 z.2.property.1 + (z.1.property.1.mono_left z.2.right_subset) + rw [z.2.property.2] at hc + calc + _ = (f z.2.val.1 * g z.2.val.2 * h z.1.val.2) * + (kernel w z.2.val.1 z.2.val.2 * kernel w z.1.val.1 z.1.val.2) := by ac_rfl + _ = _ := by rw [hc]; ac_rfl + +lemma shuffle_add_left (w : A → A → R) (f f' g : Finset A → R) : + shuffle w (f+f') g = shuffle w f g + shuffle w f' g := by + funext s + simp only [shuffle, Pi.add_apply, add_mul, Finset.sum_add_distrib] +lemma shuffle_add_right (w : A → A → R) (f g g' : Finset A → R) : + shuffle w f (g+g') = shuffle w f g + shuffle w f g' := by + funext s + simp only [shuffle, Pi.add_apply, mul_add, add_mul, Finset.sum_add_distrib] + +lemma shuffle_supported_degree (w : A → A → R) (f g : Finset A → R) (d e : ℕ) + (hf : ∀ s, s.card ≠ d → f s = 0) (hg : ∀ s, s.card ≠ e → g s = 0) : + ∀ s, s.card ≠ d+e → shuffle w f g s = 0 := by + intro s hs + apply Finset.sum_eq_zero + intro p hp + by_cases hpd : p.val.1.card = d + · have hpe : p.val.2.card ≠ e := by + intro he + apply hs + rw [← p.property.2, Finset.card_union_of_disjoint p.property.1, hpd, he] + simp [hg _ hpe] + · simp [hf _ hpd] + +end ElementaryPositivity.ShuffleConvolution + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SumPackCut.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SumPackCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecd40e05f98747bb34e6f294fb93a5929594cbe6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SumPackCut.lean @@ -0,0 +1,270 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.LabeledPolynomial + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open ElementaryPositivity.SeparatedSymmetry +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A B : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + [∀ i,Fintype (B i)] [∀ i,DecidableEq (B i)] + +noncomputable def sumPackCut (A B : I → Type*) [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] + [∀ i,Fintype (B i)] [∀ i,DecidableEq (B i)] : + PackConvolution.Cut (fun i=>(Finset.univ : Finset (A i ⊕ B i))) := fun i=> + ⟨((Finset.univ.map Function.Embedding.inl),(Finset.univ.map Function.Embedding.inr)),by + constructor + · apply Finset.disjoint_left.mpr + intro x hx hy + simp only [Finset.mem_map,Finset.mem_univ,true_and] at hx hy + obtain ⟨x,rfl⟩ := hx + obtain ⟨y,h⟩ := hy + change Sum.inr y = Sum.inl x at h + cases h + · ext x + cases x <;> simp⟩ + +abbrev FourPacks (d₁ e₁ d₂ e₂ : I → ℕ) (i : I) := + (Fin (d₁ i) ⊕ Fin (e₁ i)) ⊕ (Fin (d₂ i) ⊕ Fin (e₂ i)) + +noncomputable def canonicalGridCut (d₁ e₁ d₂ e₂ : I → ℕ) := + sumPackCut (fun i=>Fin (d₁ i) ⊕ Fin (e₁ i)) (fun i=>Fin (d₂ i) ⊕ Fin (e₂ i)) + +noncomputable def canonicalLeftCut (d₁ e₁ d₂ e₂ : I → ℕ) : + PackConvolution.Cut (left (canonicalGridCut d₁ e₁ d₂ e₂)) := + embedPackCut (fun _=>Function.Embedding.inl) + (sumPackCut (fun i=>Fin (d₁ i)) (fun i=>Fin (e₁ i))) + +noncomputable def canonicalRightCut (d₁ e₁ d₂ e₂ : I → ℕ) : + PackConvolution.Cut (right (canonicalGridCut d₁ e₁ d₂ e₂)) := + embedPackCut (fun _=>Function.Embedding.inr) + (sumPackCut (fun i=>Fin (d₂ i)) (fun i=>Fin (e₂ i))) + +noncomputable def canonicalGridPolynomial (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g : S e) (d₁ e₁ d₂ e₂ : I → ℕ) : + MvPolynomial (Σi,FourPacks d₁ e₁ d₂ e₂ i) ℚ := + gridPolynomial a f g (canonicalGridCut d₁ e₁ d₂ e₂) + (canonicalLeftCut d₁ e₁ d₂ e₂) (canonicalRightCut d₁ e₁ d₂ e₂) + +def fourPackAction (d₁ e₁ d₂ e₂ : I → ℕ) + (σ : CellGroup d₁ e₁ × CellGroup d₂ e₂) (i : I) : + Equiv.Perm (FourPacks d₁ e₁ d₂ e₂ i) := + Equiv.sumCongr (Equiv.sumCongr (σ.1.1 i) (σ.1.2 i)) + (Equiv.sumCongr (σ.2.1 i) (σ.2.2 i)) + +lemma gridPolynomial_stabilized {C : I → Type*} [∀ i,Fintype (C i)] [∀ i,DecidableEq (C i)] + (σ : ∀ i,Equiv.Perm (C i)) (a : I → I → ℕ) {d e : I → ℕ} (f : S d) (g : S e) + {s : Pack (A:=C)} (p : PackConvolution.Cut s) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) + (hp₁ : mapPack σ (left p) = left p) (hp₂ : mapPack σ (right p) = right p) + (hq₁ : mapPack σ (left q) = left q) (hq₂ : mapPack σ (right q) = right q) + (hr₁ : mapPack σ (left r) = left r) (hr₂ : mapPack σ (right r) = right r) : + rename (packAction C σ) (gridPolynomial a f g p q r) = gridPolynomial a f g p q r := by + have hc : rename (packAction C σ) (crossKernelPolynomial a p q r) = + crossKernelPolynomial a p q r := by + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,C i) ℚ)) + rw [← renameFraction_algebraMap (packAction C σ),← crossKernelPolynomial_spec, + map_mul,map_mul,renameFraction_algebraMap,rename_sameDen, + rename_pack_kernel,rename_pack_kernel,hp₁,hp₂,hq₁,hq₂,hr₁,hr₂] + simp only [gridPolynomial,map_mul,rename_labeledPolynomial,mapPack_union,hq₁,hq₂,hr₁,hr₂,hc] + +lemma canonicalGridPolynomial_invariant (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g : S e) (d₁ e₁ d₂ e₂ : I → ℕ) + (σ : CellGroup d₁ e₁ × CellGroup d₂ e₂) : + rename (packAction (FourPacks d₁ e₁ d₂ e₂) (fourPackAction d₁ e₁ d₂ e₂ σ)) + (canonicalGridPolynomial a f g d₁ e₁ d₂ e₂) = + canonicalGridPolynomial a f g d₁ e₁ d₂ e₂ := by + apply gridPolynomial_stabilized + all_goals + funext i + ext x + rcases x with (x|x) <;> rcases x with (x|x) <;> + simp [mapPack,canonicalGridCut,canonicalLeftCut,canonicalRightCut, + sumPackCut,left,right,embedPackCut,fourPackAction,Finset.mem_map,Equiv.sumCongr] + +def fourPackEquiv (d₁ e₁ d₂ e₂ : I → ℕ) : + (Σi,FourPacks d₁ e₁ d₂ e₂ i) ≃ (CellVars d₁ e₁ ⊕ CellVars d₂ e₂) where + toFun + | ⟨i,Sum.inl (Sum.inl x)⟩ => Sum.inl (Sum.inl ⟨i,x⟩) + | ⟨i,Sum.inl (Sum.inr x)⟩ => Sum.inl (Sum.inr ⟨i,x⟩) + | ⟨i,Sum.inr (Sum.inl x)⟩ => Sum.inr (Sum.inl ⟨i,x⟩) + | ⟨i,Sum.inr (Sum.inr x)⟩ => Sum.inr (Sum.inr ⟨i,x⟩) + invFun + | Sum.inl (Sum.inl ⟨i,x⟩) => ⟨i,Sum.inl (Sum.inl x)⟩ + | Sum.inl (Sum.inr ⟨i,x⟩) => ⟨i,Sum.inl (Sum.inr x)⟩ + | Sum.inr (Sum.inl ⟨i,x⟩) => ⟨i,Sum.inr (Sum.inl x)⟩ + | Sum.inr (Sum.inr ⟨i,x⟩) => ⟨i,Sum.inr (Sum.inr x)⟩ + left_inv := by rintro ⟨i,((x|x)|(x|x))⟩ <;> rfl + right_inv := by rintro ((⟨i,x⟩|⟨i,x⟩)|(⟨i,x⟩|⟨i,x⟩)) <;> rfl + +noncomputable def fourGridPolynomial (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g : S e) (d₁ e₁ d₂ e₂ : I → ℕ) := + rename (fourPackEquiv d₁ e₁ d₂ e₂) (canonicalGridPolynomial a f g d₁ e₁ d₂ e₂) + +lemma fourGridPolynomial_invariant (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g : S e) (d₁ e₁ d₂ e₂ : I → ℕ) + (σ : CellGroup d₁ e₁ × CellGroup d₂ e₂) : + rename (sumAction (cellAction d₁ e₁) (cellAction d₂ e₂) σ) + (fourGridPolynomial a f g d₁ e₁ d₂ e₂) = fourGridPolynomial a f g d₁ e₁ d₂ e₂ := by + have he : (sumAction (cellAction d₁ e₁) (cellAction d₂ e₂) σ) ∘ + fourPackEquiv d₁ e₁ d₂ e₂ = fourPackEquiv d₁ e₁ d₂ e₂ ∘ + packAction (FourPacks d₁ e₁ d₂ e₂) (fourPackAction d₁ e₁ d₂ e₂ σ) := by + funext z + rcases z with ⟨i,z⟩ + rcases z with (x|x) <;> rcases x with (x|x) <;> rfl + unfold fourGridPolynomial + rw [rename_rename,he,← rename_rename,canonicalGridPolynomial_invariant] + +lemma fourGridPolynomial_transfer (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g : S e) (d₁ e₁ d₂ e₂ : I → ℕ) : + doubleTensorShuffle a d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂) = + localizeTensor (d₁+e₁) (d₂+e₂) + (cellTransfer a d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂)) := + doubleTensorShuffle_invariant a d₁ e₁ d₂ e₂ _ + (fourGridPolynomial_invariant a f g d₁ e₁ d₂ e₂) + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,DecidableEq (A i)] + +lemma gridPolynomial_congr (a : I → I → ℕ) {d e : I → ℕ} (f : S d) (g : S e) + {s t : Pack (A:=A)} (p : PackConvolution.Cut s) (p' : PackConvolution.Cut t) + (q : PackConvolution.Cut (left p)) (r : PackConvolution.Cut (right p)) + (q' : PackConvolution.Cut (left p')) (r' : PackConvolution.Cut (right p')) + (hp₁ : left p = left p') (hp₂ : right p = right p') + (hq₁ : left q = left q') (hq₂ : right q = right q') + (hr₁ : left r = left r') (hr₂ : right r = right r') : + gridPolynomial a f g p q r = gridPolynomial a f g p' q' r' := by + have hc : crossKernelPolynomial a p q r = crossKernelPolynomial a p' q' r' := by + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) + rw [← crossKernelPolynomial_spec,← crossKernelPolynomial_spec] + exact congrArg₂ (· * ·) (congrArg₂ (· * ·) + (congrArg (algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ))) + (congrArg₂ sameDen hp₁ hp₂)) + (congrArg₂ (kernel (pairKernel a)) hq₁ hr₂)) + (congrArg₂ (kernel (pairKernel a)) hr₁ hq₂) + simp only [gridPolynomial,hq₁,hq₂,hr₁,hr₂,hc] + +noncomputable def gridEmbedding {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) (i : I) : + FourPacks d₁ e₁ d₂ e₂ i ↪ A i where + toFun := Sum.elim (fun x=>↑(R i (packSplit u i x))) (fun x=>↑(T i (packSplit v i x))) + inj' := by + rintro (x|x) (y|y) h + · congr 1 + exact (packSplit u i).injective ((R i).injective (Subtype.ext h)) + · change (R i (packSplit u i x)).val = (T i (packSplit v i y)).val at h + exact (Finset.disjoint_left.mp (p i).property.1 + (R i (packSplit u i x)).property (h.symm ▸ (T i (packSplit v i y)).property)).elim + · change (T i (packSplit v i x)).val = (R i (packSplit u i y)).val at h + exact (Finset.disjoint_left.mp (p i).property.1 + (R i (packSplit u i y)).property (h ▸ (T i (packSplit v i x)).property)).elim + · congr 1 + exact (packSplit v i).injective ((T i).injective (Subtype.ext h)) + +omit [Fintype I] [DecidableEq I] in +lemma gridEmbedding_outer_left {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + embedPack (gridEmbedding p R T u v) (left (canonicalGridCut d₁ e₁ d₂ e₂)) = left p := by + funext i + change Finset.map _ (Finset.univ.map Function.Embedding.inl) = _ + rw [Finset.map_map] + change Finset.univ.map ((packSplit u i).toEmbedding.trans (PackEnumeration.embedding (R i))) = _ + rw [← Finset.map_map,Finset.map_univ_equiv,PackEnumeration.map_univ] + +omit [Fintype I] [DecidableEq I] in +lemma gridEmbedding_outer_right {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + embedPack (gridEmbedding p R T u v) (right (canonicalGridCut d₁ e₁ d₂ e₂)) = right p := by + funext i + change Finset.map _ (Finset.univ.map Function.Embedding.inr) = _ + rw [Finset.map_map] + change Finset.univ.map ((packSplit v i).toEmbedding.trans (PackEnumeration.embedding (T i))) = _ + rw [← Finset.map_map,Finset.map_univ_equiv,PackEnumeration.map_univ] + +omit [Fintype I] [DecidableEq I] in +lemma gridEmbedding_cell₁ {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + embedPack (gridEmbedding p R T u v) (left (canonicalLeftCut d₁ e₁ d₂ e₂)) = + left (cutRealizationEquiv R u).val := by + funext i + change Finset.map _ ((Finset.univ.map Function.Embedding.inl).map Function.Embedding.inl) = _ + rw [Finset.map_map,Finset.map_map] + change Finset.univ.map ((PackEnumeration.embedding (leftEnum u i)).trans + (PackEnumeration.embedding (R i))) = _ + rw [← Finset.map_map,PackEnumeration.map_univ] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma gridEmbedding_cell₂ {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + embedPack (gridEmbedding p R T u v) (right (canonicalLeftCut d₁ e₁ d₂ e₂)) = + right (cutRealizationEquiv R u).val := by + funext i + change Finset.map _ ((Finset.univ.map Function.Embedding.inr).map Function.Embedding.inl) = _ + rw [Finset.map_map,Finset.map_map] + change Finset.univ.map ((PackEnumeration.embedding (rightEnum u i)).trans + (PackEnumeration.embedding (R i))) = _ + rw [← Finset.map_map,PackEnumeration.map_univ] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma gridEmbedding_cell₃ {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + embedPack (gridEmbedding p R T u v) (left (canonicalRightCut d₁ e₁ d₂ e₂)) = + left (cutRealizationEquiv T v).val := by + funext i + change Finset.map _ ((Finset.univ.map Function.Embedding.inl).map Function.Embedding.inr) = _ + rw [Finset.map_map,Finset.map_map] + change Finset.univ.map ((PackEnumeration.embedding (leftEnum v i)).trans + (PackEnumeration.embedding (T i))) = _ + rw [← Finset.map_map,PackEnumeration.map_univ] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma gridEmbedding_cell₄ {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + embedPack (gridEmbedding p R T u v) (right (canonicalRightCut d₁ e₁ d₂ e₂)) = + right (cutRealizationEquiv T v).val := by + funext i + change Finset.map _ ((Finset.univ.map Function.Embedding.inr).map Function.Embedding.inr) = _ + rw [Finset.map_map,Finset.map_map] + change Finset.univ.map ((PackEnumeration.embedding (rightEnum v i)).trans + (PackEnumeration.embedding (T i))) = _ + rw [← Finset.map_map,PackEnumeration.map_univ] + rfl + +lemma gridPolynomial_realization (a : I → I → ℕ) {d e : I → ℕ} (f : S d) (g : S e) + {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + rename (packEmbedding (gridEmbedding p R T u v)) (canonicalGridPolynomial a f g d₁ e₁ d₂ e₂) = + gridPolynomial a f g p (cutRealizationEquiv R u).val (cutRealizationEquiv T v).val := by + rw [canonicalGridPolynomial,embed_gridPolynomial] + apply gridPolynomial_congr + · exact gridEmbedding_outer_left p R T u v + · exact gridEmbedding_outer_right p R T u v + · exact gridEmbedding_cell₁ p R T u v + · exact gridEmbedding_cell₂ p R T u v + · exact gridEmbedding_cell₃ p R T u v + · exact gridEmbedding_cell₄ p R T u v + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SymbolDetection.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SymbolDetection.lean new file mode 100644 index 0000000000000000000000000000000000000000..244dc4ff3dd7a5a39474da8b69c701d7edc77a75 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SymbolDetection.lean @@ -0,0 +1,140 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.LeadingIndex +import OAI.Combinatorics.Chromatic.Shuffle.PointEvaluation + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.CenterCalculus +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +def SlopeEulerSymmetric (a : I → I → ℕ) (c η : I → ℝ) (θ : ℝ) : Prop := + ∀ d e : I → ℕ, d≠0 → e≠0 → SlopeArithmetic.slope c η d=θ → + SlopeArithmetic.slope c η e=θ → eulerForm a d e=eulerForm a e d + +namespace SplitTree +omit [DecidableEq I] in +lemma leafDimension_onSlope (T : SplitTree I) (c η : I → ℝ) (θ : ℝ) + (hT : T.OnSlope c η θ) (i : T.Centers) : + T.leafDimension i≠0 ∧ SlopeArithmetic.slope c η (T.leafDimension i)=θ := by + induction T with + | leaf d => exact hT + | node l r hl hr => + cases i with + | inl i => exact hl hT.1 i + | inr i => exact hr hT.2 i + +omit [DecidableEq I] in +lemma pairSymmetric_of_slope (a : I → I → ℕ) (c η : I → ℝ) (θ : ℝ) + (hχ : SlopeEulerSymmetric a c η θ) (T : SplitTree I) (hT : T.OnSlope c η θ) : + T.PairSymmetric a := by + intro ij _ + obtain ⟨hi,hsi⟩:=T.leafDimension_onSlope c η θ hT ij.1 + obtain ⟨hj,hsj⟩:=T.leafDimension_onSlope c η θ hT ij.2 + exact hχ _ _ hi hj hsi hsj + +lemma totalLeadingPolynomial_next_zero (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0componentTensor a (SlopeArithmetic.slope c η) T k + (AddMonoidAlgebra.coeff polynomial z)) hf + simpa [totalLeadingPolynomial,coeff_mapLinear,componentTensor_weightComponent,hw, + restrictionTest,dimensionEquivB] using h +end SplitTree + +structure SymbolIndex (c η : I → ℝ) (θ : ℝ) (d : I → ℕ) where + tree : SplitTree I + ordered : tree.IsOrderedList + onSlope : tree.OnSlope c η θ + dimension : tree.dim=d + +noncomputable def filtrationDimensionEquiv (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + apply (Submodule.Quotient.mk_eq_zero _).mpr + rw [← symbolFamily_ker a c η hc θ hχ d W] + exact hf + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SymbolInternalWeight.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SymbolInternalWeight.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe009e31fbf97f8f4bdac6fc4bf0834a7c2d0363 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SymbolInternalWeight.lean @@ -0,0 +1,101 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.NormalizedTensorSymbol +import OAI.Combinatorics.Chromatic.Walls.CenterCoefficientScalarLinear + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial ElementaryPositivity.CenterCalculus +open ElementaryPositivity.ShufflePolynomiality +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma weightComponent_weightComponent (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (U W : ℤ) (x : tensor (quotientFamily a μ) T) : + weightComponent a μ T U (weightComponent a μ T W x)= + if U=W then weightComponent a μ T W x else 0 := by + classical + apply sub_eq_zero.mp + apply componentTensor_detect a μ T + intro k + rw [map_sub,componentTensor_weightComponent,componentTensor_weightComponent] + by_cases h : U=W <;> by_cases hw : 2*T.totalDegree k+T.doubleShift a=W <;> + by_cases hu : 2*T.totalDegree k+T.doubleShift a=U <;> + simp_all [componentTensor_weightComponent] + +lemma mapLinear_weight_weight (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (U W : ℤ) (p : MvPolynomial T.Centers (tensor (quotientFamily a μ) T)) : + mapLinear (weightComponent a μ T U) (mapLinear (weightComponent a μ T W) p)= + if U=W then mapLinear (weightComponent a μ T W) p else 0 := by + ext z + by_cases h : U=W <;> + simp only [coeff_mapLinear,weightComponent_weightComponent,h,ite_true,ite_false, + AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply] + +lemma clearedLeading_internal_weight (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0crossPairs_injective L R h), + Fintype.prod_prod_type,map_prod,map_pow,diagonal,map_sub,rename_X,leafDimension,crossPower] + +omit [DecidableEq I] in +lemma crossPower_swap (a : I → I → ℕ) (L R : SplitTree I) (φ : ℤ → ℕ) + (hs : ∀ z t,eulerForm a (L.leafDimension z) (R.leafDimension t)= + eulerForm a (R.leafDimension t) (L.leafDimension z)) : + rename (Equiv.sumComm L.Centers R.Centers) (crossPower a L R φ)= + C (crossSign a L R φ)*crossPower a R L φ := by + classical + unfold crossPower crossSign + simp only [map_prod,map_pow,diagonal,map_sub,rename_X,Equiv.sumComm_apply, + Sum.swap_inl,Sum.swap_inr] + rw [Finset.prod_comm (f:=fun (t : R.Centers) (z : L.Centers)=> + (X (Sum.inr z)-X (Sum.inl t))^φ (eulerForm a (R.leafDimension t) (L.leafDimension z))), + ←Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro z hz + rw [←Finset.prod_mul_distrib] + apply Finset.prod_congr rfl + intro t ht + rw [hs z t,←mul_pow] + congr 1 + simp only [map_neg,map_one] + ring + +omit [DecidableEq I] in +lemma centerPower_swap (a : I → I → ℕ) (L R : SplitTree I) (φ : ℤ → ℕ) + (hs : ∀ z t,eulerForm a (L.leafDimension z) (R.leafDimension t)= + eulerForm a (R.leafDimension t) (L.leafDimension z)) : + rename (Equiv.sumComm L.Centers R.Centers) (centerPower a (L.node R) φ)= + C (crossSign a L R φ)*centerPower a (R.node L) φ := by + rw [centerPower_node,centerPower_node,map_mul,map_mul,crossPower_swap a L R φ hs] + simp only [rename_rename,Equiv.sumComm_apply,Function.comp_def,Sum.swap_inl,Sum.swap_inr] + ring + +omit [DecidableEq I] in +lemma crossSign_sq (a : I → I → ℕ) (L R : SplitTree I) (φ : ℤ → ℕ) : + crossSign a L R φ*crossSign a L R φ=1 := by + unfold crossSign + rw [←Finset.prod_mul_distrib] + simp only [←Finset.prod_mul_distrib,←mul_pow,neg_mul_neg,one_mul,one_pow,Finset.prod_const_one] + +omit [DecidableEq I] in +lemma sum_leaf_euler_left (a : I → I → ℕ) (L : SplitTree I) (d : I → ℕ) : + (∑ z : L.Centers,eulerForm a (L.leafDimension z) d)=eulerForm a L.dim d := by + classical + induction L with + | leaf d => simp [Centers,leafDimension,dim] + | node T U hT hU => + change (∑ z : T.Centers ⊕ U.Centers,eulerForm a ((T.node U).leafDimension z) d)=_ + rw [Fintype.sum_sum_type] + change (∑ z : T.Centers,eulerForm a (T.leafDimension z) d)+ + (∑ z : U.Centers,eulerForm a (U.leafDimension z) d)=eulerForm a (T.dim+U.dim) d + rw [hT,hU,eulerForm_add_left] + +omit [DecidableEq I] in +lemma sum_leaf_euler_right (a : I → I → ℕ) (d : I → ℕ) (R : SplitTree I) : + (∑ z : R.Centers,eulerForm a d (R.leafDimension z))=eulerForm a d R.dim := by + classical + induction R with + | leaf d => simp [Centers,leafDimension,dim] + | node T U hT hU => + change (∑ z : T.Centers ⊕ U.Centers,eulerForm a d ((T.node U).leafDimension z))=_ + rw [Fintype.sum_sum_type] + change (∑ z : T.Centers,eulerForm a d (T.leafDimension z))+ + (∑ z : U.Centers,eulerForm a d (U.leafDimension z))=eulerForm a d (T.dim+U.dim) + rw [hT,hU,eulerForm_add_right] + +lemma negOne_pos_neg (e : ℤ) : (-1:ℚ)^e.toNat*(-1)^(-e).toNat=(-1)^e := by + cases e with + | ofNat n => simp + | negSucc n => + have h : Int.negSucc n = -((n+1:ℕ):ℤ) := by omega + have h0 : (-((n+1:ℕ):ℤ)).toNat=0 := Int.toNat_eq_zero.mpr (by omega) + rw [h,h0,pow_zero,one_mul,neg_neg,Int.toNat_natCast,zpow_neg,zpow_natCast] + simp only [←inv_pow,inv_neg,inv_one] + +lemma prod_negOne {α : Type*} (s : Finset α) (f : α → ℤ) : + (∏ i∈s,(-1:ℚ)^f i)=(-1)^(∑ i∈s,f i) := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert x s hx ih => + rw [Finset.prod_insert hx,Finset.sum_insert hx,ih,zpow_add₀ (by norm_num : (-1:ℚ)≠0)] + +omit [DecidableEq I] in +lemma crossSign_pos_neg (a : I → I → ℕ) (L R : SplitTree I) : + crossSign a L R Int.toNat*crossSign a L R (fun e=>(-e).toNat)= + (-1:ℚ)^eulerForm a L.dim R.dim := by + unfold crossSign + rw [←Finset.prod_mul_distrib] + simp only [←Finset.prod_mul_distrib,negOne_pos_neg,prod_negOne, + sum_leaf_euler_right,sum_leaf_euler_left] + +namespace Regroup +lemma clearedLeading_swap (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(-e).toNat) • + extendPolynomial ((Regroup.swap L R).equivalence + (quotientFamily a (SlopeArithmetic.slope c η))).toAlgHom + (Regroup.swap L R).centers + (clearedLeading a c η hc θ (.node L R) ⟨hL,hR⟩ + (pairSymmetric_of_slope a c η θ hχ _ ⟨hL,hR⟩) W f) := by + have hs (z : L.Centers) (t : R.Centers) : + eulerForm a (L.leafDimension z) (R.leafDimension t)= + eulerForm a (R.leafDimension t) (L.leafDimension z) := by + obtain ⟨hz,hzs⟩:=L.leafDimension_onSlope c η θ hL z + obtain ⟨ht,hts⟩:=R.leafDimension_onSlope c η θ hR t + exact hχ _ _ hz ht hzs hts + have hd : rename (Regroup.swap L R).centers + (centerDenominator a (L.node R) (L.node R).centerPairs)= + C (crossSign a L R (fun e=>(-e).toNat))* + centerDenominator a (R.node L) (R.node L).centerPairs := + centerPower_swap a L R (fun e=>(-e).toNat) hs + apply scalar_mul_injective _ (centerDenominator_ne_zero a (R.node L)) + dsimp only + rw [denominator_clearedLeading a c η hc θ (R.node L) ⟨hR,hL⟩ + (pairSymmetric_of_slope a c η θ hχ _ ⟨hR,hL⟩) W, + filtrationDimensionEquiv_val, + totalLeadingPolynomial_natural a c η hc θ (Regroup.swap L R) ⟨hL,hR⟩ ⟨hR,hL⟩ W, + ←denominator_clearedLeading a c η hc θ (L.node R) ⟨hL,hR⟩ + (pairSymmetric_of_slope a c η θ hχ _ ⟨hL,hR⟩) W f, + map_mul,extendPolynomial_map_algebra,hd,map_mul,map_C] + rw [Algebra.smul_def] + simp only [MvPolynomial.algebraMap_apply] + ring + +lemma normalizedSymbol_swap (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(-e).toNat) := by + rw [←crossSign_pos_neg] + calc + _ = (crossSign a L R Int.toNat*crossSign a L R Int.toNat)* + crossSign a L R (fun e=>(-e).toNat) := by ring + _ = _ := by rw [crossSign_sq,one_mul] + change map _ (centerNumerator a (R.node L) (R.node L).centerPairs)* + clearedLeading a c η hc θ (.node R L) ⟨hR,hL⟩ + (pairSymmetric_of_slope a c η θ hχ _ ⟨hR,hL⟩) W _ = + (-1:ℚ)^eulerForm a L.dim R.dim • + extendPolynomial _ _ (map _ (centerNumerator a (L.node R) (L.node R).centerPairs)* + clearedLeading a c η hc θ (.node L R) ⟨hL,hR⟩ + (pairSymmetric_of_slope a c η θ hχ _ ⟨hL,hR⟩) W f) + rw [clearedLeading_swap a c η hc θ hχ L R hL hR W f, + map_mul,extendPolynomial_map_algebra,hn,map_mul,map_C] + simp only [Algebra.smul_def,MvPolynomial.algebraMap_apply] + have hh:=congrArg (fun r : ℚ => + (C ((algebraMap ℚ (tensor (quotientFamily a (SlopeArithmetic.slope c η)) (.node R L))) r) : + MvPolynomial (R.node L).Centers (tensor (quotientFamily a (SlopeArithmetic.slope c η)) (.node R L)))) hsign + simp only [map_mul] at hh + rw [←hh] + ring + +end Regroup +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/SymmetricSpace.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/SymmetricSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..f80b543d043a448ef07e9320eaa16a42b091049d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/SymmetricSpace.lean @@ -0,0 +1,279 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Cut + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +variable {I : Type*} [Fintype I] [DecidableEq I] + +def symmetricSpace (d : I → ℕ) : Subalgebra ℚ (MvPolynomial (Σi, Fin (d i)) ℚ) where + carrier := {f | PackSymmetric d f} + mul_mem' := by intro f g hf hg σ; simp only [map_mul, hf σ, hg σ] + one_mem' := by intro σ; exact map_one _ + add_mem' := by intro f g hf hg σ; simp only [map_add, hf σ, hg σ] + zero_mem' := by intro σ; exact map_zero _ + algebraMap_mem' := by intro r σ; simp + +abbrev S (d : I → ℕ) := ↥(symmetricSpace d) + +noncomputable def shufflePolynomial (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g : S e) : S (d+e) := + ⟨Classical.choose (rawShuffle_polynomial a f.val f.property g.val g.property), + (Classical.choose_spec (rawShuffle_polynomial a f.val f.property g.val g.property)).1⟩ + +lemma shufflePolynomial_eq (a : I → I → ℕ) {d e : I → ℕ} (f : S d) (g : S e) : + algebraMap _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + (shufflePolynomial a f g).val = rawShuffle a f.val g.val := + (Classical.choose_spec (rawShuffle_polynomial a f.val f.property g.val g.property)).2.symm + +lemma rawShuffle_add_left (a : I → I → ℕ) {d e : I → ℕ} + (f f' : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + rawShuffle a (f+f') g = rawShuffle a f g + rawShuffle a f' g := by + simp only [rawShuffle, cutNumerator, map_add, add_mul, add_div, + Finset.sum_add_distrib] + +lemma rawShuffle_add_right (a : I → I → ℕ) {d e : I → ℕ} + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g g' : MvPolynomial (Σi,Fin (e i)) ℚ) : + rawShuffle a f (g+g') = rawShuffle a f g + rawShuffle a f g' := by + simp only [rawShuffle, cutNumerator, map_add, mul_add, add_mul, add_div, + Finset.sum_add_distrib] + +lemma rawShuffle_smul_left (a : I → I → ℕ) {d e : I → ℕ} (r : ℚ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + rawShuffle a (r • f) g = r • rawShuffle a f g := by + let : DistribSMul ℚ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) := + (inferInstance : Module ℚ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ))).toDistribMulAction.toDistribSMul + simp only [rawShuffle, cutNumerator, map_smul, map_rat_smul, smul_mul_assoc, + div_eq_mul_inv, smul_mul_assoc, Finset.smul_sum] + +lemma rawShuffle_smul_right (a : I → I → ℕ) {d e : I → ℕ} (r : ℚ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + rawShuffle a f (r • g) = r • rawShuffle a f g := by + let : DistribSMul ℚ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) := + (inferInstance : Module ℚ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ))).toDistribMulAction.toDistribSMul + simp only [rawShuffle, cutNumerator, map_smul, map_rat_smul, mul_smul_comm, smul_mul_assoc, + div_eq_mul_inv, smul_mul_assoc, Finset.smul_sum] + +@[simp] lemma shufflePolynomial_add_left (a : I → I → ℕ) {d e : I → ℕ} + (f f' : S d) (g : S e) : + shufflePolynomial a (f+f') g = shufflePolynomial a f g + shufflePolynomial a f' g := by + apply Subtype.ext + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + simp only [Subalgebra.coe_add, map_add, shufflePolynomial_eq, rawShuffle_add_left] + +@[simp] lemma shufflePolynomial_add_right (a : I → I → ℕ) {d e : I → ℕ} + (f : S d) (g g' : S e) : + shufflePolynomial a f (g+g') = shufflePolynomial a f g + shufflePolynomial a f g' := by + apply Subtype.ext + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + simp only [Subalgebra.coe_add, map_add, shufflePolynomial_eq, rawShuffle_add_right] + +@[simp] lemma shufflePolynomial_smul_left (a : I → I → ℕ) {d e : I → ℕ} (r : ℚ) + (f : S d) (g : S e) : shufflePolynomial a (r • f) g = r • shufflePolynomial a f g := by + apply Subtype.ext + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + simp only [Subalgebra.coe_smul, map_rat_smul, shufflePolynomial_eq, rawShuffle_smul_left] + +@[simp] lemma shufflePolynomial_smul_right (a : I → I → ℕ) {d e : I → ℕ} (r : ℚ) + (f : S d) (g : S e) : shufflePolynomial a f (r • g) = r • shufflePolynomial a f g := by + apply Subtype.ext + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + simp only [Subalgebra.coe_smul, map_rat_smul, shufflePolynomial_eq, rawShuffle_smul_right] + +noncomputable def shuffleLinear (a : I → I → ℕ) (d e : I → ℕ) : + S d →ₗ[ℚ] S e →ₗ[ℚ] S (d+e) where + toFun f := + { toFun := shufflePolynomial a f + map_add' := shufflePolynomial_add_right a f + map_smul' := fun r g => shufflePolynomial_smul_right a r f g } + map_add' f f' := by apply LinearMap.ext; intro g; exact shufflePolynomial_add_left a f f' g + map_smul' r f := by apply LinearMap.ext; intro g; exact shufflePolynomial_smul_left a r f g + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def translation {α : Type*} (t : ℚ) : + MvPolynomial α ℚ →ₐ[ℚ] MvPolynomial α ℚ := + aeval fun i => X i + C t + +@[simp] lemma translation_X {α : Type*} (t : ℚ) (i : α) : + translation t (X i) = X i + C t := by simp [translation] +@[simp] lemma translation_C {α : Type*} (t r : ℚ) : + translation (α := α) t (C r) = C r := by simp [translation] + +lemma translation_rename {α β : Type*} (t : ℚ) (f : α → β) (p : MvPolynomial α ℚ) : + translation t (rename f p) = rename f (translation t p) := by + have h : (translation t).comp (rename f) = (rename f).comp (translation t) := by + ext i; simp + exact DFunLike.congr_fun h p + +lemma translation_add {α : Type*} (t s : ℚ) (p : MvPolynomial α ℚ) : + translation t (translation s p) = translation (t+s) p := by + have h : (translation (α := α) t).comp (translation s) = translation (t+s) := by + ext i; simp [map_add]; ring + exact DFunLike.congr_fun h p + +@[simp] lemma translation_zero {α : Type*} (p : MvPolynomial α ℚ) : + translation 0 p = p := by + have h : translation (α := α) 0 = AlgHom.id ℚ _ := by ext i; simp + exact DFunLike.congr_fun h p + +noncomputable def translationEquiv {α : Type*} (t : ℚ) : + MvPolynomial α ℚ ≃ₐ[ℚ] MvPolynomial α ℚ := + AlgEquiv.ofAlgHom (translation t) (translation (-t)) + (by ext p; simp [AlgHom.comp_apply]) + (by ext p; simp [AlgHom.comp_apply]) + +noncomputable def translationFraction {α : Type*} (t : ℚ) : + FractionRing (MvPolynomial α ℚ) →+* FractionRing (MvPolynomial α ℚ) := + IsFractionRing.lift (g := (algebraMap _ _).comp (translation (α := α) t).toRingHom) + ((IsFractionRing.injective _ (FractionRing (MvPolynomial α ℚ))).comp + (translationEquiv t).injective) + +@[simp] lemma translationFraction_algebraMap {α : Type*} (t : ℚ) (p : MvPolynomial α ℚ) : + translationFraction t (algebraMap _ (FractionRing (MvPolynomial α ℚ)) p) = + algebraMap _ (FractionRing (MvPolynomial α ℚ)) (translation t p) := by + apply IsFractionRing.lift_algebraMap + +@[simp] lemma translation_diagonal {α : Type*} (t : ℚ) (i j : α) : + translation t (diagonal i j) = diagonal i j := by + simp [diagonal] + +omit [Fintype I] [DecidableEq I] in +lemma translation_cutFactor {d e : I → ℕ} (t : ℚ) (A : Cut d e) (i j : I) (k : ℕ) : + translation t (cutFactor A i j k) = cutFactor A i j k := by + simp [cutFactor] + +omit [DecidableEq I] in +lemma translation_cutDenominator {d e : I → ℕ} (t : ℚ) (A : Cut d e) : + translation t (cutDenominator A) = cutDenominator A := by + simp [cutDenominator, translation_cutFactor] + +omit [DecidableEq I] in +lemma translation_cutNumerator (a : I → I → ℕ) {d e : I → ℕ} (t : ℚ) (A : Cut d e) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + translation t (cutNumerator a A f g) = + cutNumerator a A (translation t f) (translation t g) := by + simp [cutNumerator, translation_rename, translation_cutFactor] + +lemma translation_rawShuffle (a : I → I → ℕ) {d e : I → ℕ} (t : ℚ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (g : MvPolynomial (Σi,Fin (e i)) ℚ) : + translationFraction t (rawShuffle a f g) = + rawShuffle a (translation t f) (translation t g) := by + simp only [rawShuffle, map_sum, map_div₀, translationFraction_algebraMap, + translation_cutNumerator, translation_cutDenominator] + +omit [Fintype I] [DecidableEq I] in +lemma translation_symmetric {d : I → ℕ} (t : ℚ) + (f : MvPolynomial (Σi,Fin (d i)) ℚ) (hf : PackSymmetric d f) : + PackSymmetric d (translation t f) := by + intro σ + rw [← translation_rename, hf σ] + +noncomputable def translationS (d : I → ℕ) (t : ℚ) : S d →ₗ[ℚ] S d := + { toFun := fun f => ⟨translation t f.val, translation_symmetric t f.val f.property⟩ + map_add' := by intros; apply Subtype.ext; apply map_add + map_smul' := by intros; apply Subtype.ext; apply map_smul } + +lemma translation_shufflePolynomial (a : I → I → ℕ) {d e : I → ℕ} (t : ℚ) + (f : S d) (g : S e) : + translationS (d+e) t (shufflePolynomial a f g) = + shufflePolynomial a (translationS d t f) (translationS e t g) := by + apply Subtype.ext + apply IsFractionRing.injective _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + change algebraMap _ _ (translation t (shufflePolynomial a f g).val) = _ + calc + _ = translationFraction t + (algebraMap _ (FractionRing (MvPolynomial (Σi,Fin (d i+e i)) ℚ)) + (shufflePolynomial a f g).val) := + (translationFraction_algebraMap t (shufflePolynomial a f g).val).symm + _ = _ := by + rw [shufflePolynomial_eq, translation_rawShuffle, shufflePolynomial_eq] + rfl + +noncomputable def dimensionCast {d e : I → ℕ} (h : d = e) : S d →ₗ[ℚ] S e := + h ▸ LinearMap.id + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma dimensionCast_rfl (d : I → ℕ) (f : S d) : + dimensionCast rfl f = f := rfl + +omit [Fintype I] [DecidableEq I] in +lemma translation_dimensionCast {d e : I → ℕ} (h : d = e) (t : ℚ) (f : S d) : + translationS e t (dimensionCast h f) = dimensionCast h (translationS d t f) := by + subst e; rfl + +def destabilizingGenerators (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : Set (S d) := + { F | ∃ (u v : I → ℕ) (h : u+v=d) (f : S u) (g : S v), + u ≠ 0 ∧ v ≠ 0 ∧ μ u > μ d ∧ F = dimensionCast h (shufflePolynomial a f g) } + +noncomputable def destabilizingSpace (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + Submodule ℚ (S d) := Submodule.span ℚ (destabilizingGenerators a μ d) + +lemma translation_generator (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (t : ℚ) {f : S d} (hf : f ∈ destabilizingGenerators a μ d) : + translationS d t f ∈ destabilizingGenerators a μ d := by + obtain ⟨u,v,h,f,g,hu,hv,hμ,rfl⟩ := hf + refine ⟨u,v,h,translationS u t f,translationS v t g,hu,hv,hμ,?_⟩ + rw [translation_dimensionCast, translation_shufflePolynomial] + +lemma translation_destabilizing (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (t : ℚ) : + destabilizingSpace a μ d ≤ + (destabilizingSpace a μ d).comap (translationS d t) := by + apply Submodule.span_le.mpr + intro f hf + exact Submodule.subset_span (translation_generator a μ d t hf) + +abbrev B (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) := + S d ⧸ destabilizingSpace a μ d + +noncomputable def translationB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (t : ℚ) : B a μ d →ₗ[ℚ] B a μ d := + (destabilizingSpace a μ d).mapQ (destabilizingSpace a μ d) (translationS d t) + (translation_destabilizing a μ d t) + +@[simp] lemma translationB_mk (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (t : ℚ) (f : S d) : + translationB a μ d t ((destabilizingSpace a μ d).mkQ f) = + (destabilizingSpace a μ d).mkQ (translationS d t f) := rfl + +omit [Fintype I] [DecidableEq I] in +lemma translationS_add (d : I → ℕ) (t s : ℚ) (f : S d) : + translationS d t (translationS d s f) = translationS d (t+s) f := by + apply Subtype.ext + exact translation_add t s f.val + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma translationS_zero (d : I → ℕ) (f : S d) : translationS d 0 f = f := by + apply Subtype.ext + exact translation_zero f.val + +lemma translationB_add (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (t s : ℚ) (f : B a μ d) : + translationB a μ d t (translationB a μ d s f) = translationB a μ d (t+s) f := by + induction f using Submodule.Quotient.induction_on with + | H f => exact congrArg (destabilizingSpace a μ d).mkQ (translationS_add d t s f) + +@[simp] lemma translationB_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (f : B a μ d) : translationB a μ d 0 f = f := by + induction f using Submodule.Quotient.induction_on with + | H f => exact congrArg (destabilizingSpace a μ d).mkQ (translationS_zero d f) + +noncomputable def translationBEquiv (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (t : ℚ) : B a μ d ≃ₗ[ℚ] B a μ d := + LinearEquiv.ofLinearMap (translationB a μ d t) (translationB a μ d (-t)) + (by ext f; simp [LinearMap.comp_apply, translationB_add]) + (by ext f; simp [LinearMap.comp_apply, translationB_add]) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/TargetEmbedding.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/TargetEmbedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..f832bab998795d1e5df11fcf3b524be5777fd235 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/TargetEmbedding.lean @@ -0,0 +1,236 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SumPackCut + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,DecidableEq (A i)] + +noncomputable def targetEmbedding {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) : + CellVars d e ↪ (Σi,A i) where + toFun := Sum.elim (realizationMap R) (realizationMap T) + inj' := by + rintro (x|x) (y|y) h + · exact congrArg Sum.inl (realizationMap_injective R h) + · rcases x with ⟨i,x⟩ + rcases y with ⟨j,y⟩ + have hij := congrArg Sigma.fst h + change i=j at hij + subst j + have hxy : (R i x).val = (T i y).val := eq_of_heq (Sigma.mk.inj_iff.mp h).2 + exact (Finset.disjoint_left.mp (p i).property.1 (R i x).property + (hxy.symm ▸ (T i y).property)).elim + · rcases x with ⟨i,x⟩ + rcases y with ⟨j,y⟩ + have hij := congrArg Sigma.fst h + change i=j at hij + subst j + have hxy : (T i x).val = (R i y).val := eq_of_heq (Sigma.mk.inj_iff.mp h).2 + exact (Finset.disjoint_left.mp (p i).property.1 (R i y).property + (hxy ▸ (T i x).property)).elim + · exact congrArg Sum.inr (realizationMap_injective T h) + +omit [Fintype I] [DecidableEq I] in +lemma gridEmbedding_square {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + targetEmbedding p R T ∘ Sum.map (cutSplit u) (cutSplit v) ∘ fourPackEquiv d₁ e₁ d₂ e₂ = + packEmbedding (gridEmbedding p R T u v) := by + funext z + rcases z with ⟨i,z⟩ + rcases z with (x|x) <;> rcases x with (x|x) <;> rfl + +lemma gridPolynomial_four_realization (a : I → I → ℕ) {d e : I → ℕ} (f : S d) (g : S e) + {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) (v : Cut d₂ e₂) : + rename (targetEmbedding p R T) (rename (Sum.map (cutSplit u) (cutSplit v)) + (fourGridPolynomial a f g d₁ e₁ d₂ e₂)) = + gridPolynomial a f g p (cutRealizationEquiv R u).val (cutRealizationEquiv T v).val := by + simp only [fourGridPolynomial,rename_rename] + change rename (targetEmbedding p R T ∘ Sum.map (cutSplit u) (cutSplit v) ∘ + fourPackEquiv d₁ e₁ d₂ e₂) _ = _ + rw [gridEmbedding_square,gridPolynomial_realization] + +omit [Fintype I] [DecidableEq I] in +lemma targetEmbedding_algebraMap {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) + (P : MvPolynomial (CellVars d e) ℚ) : + renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (algebraMap _ (FractionRing (MvPolynomial (CellVars d e) ℚ)) P) = + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (rename (targetEmbedding p R T) P) := + renameInjFraction_algebraMap (targetEmbedding p R T) (targetEmbedding p R T).injective P + +lemma targetEmbedding_left_kernel (a : I → I → ℕ) + {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (u : Cut d₁ e₁) : + renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (renameInjFraction Sum.inl Sum.inl_injective (cutKernel a u)) = + kernel (pairKernel a) (left (cutRealizationEquiv R u).val) + (right (cutRealizationEquiv R u).val) := by + have hpoly (P : MvPolynomial (Σ i, Fin (d₁ i + e₁ i)) ℚ) : + renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (renameInjFraction (Sum.inl : (Σ i, Fin (d₁ i + e₁ i)) → CellVars (d₁+e₁) (d₂+e₂)) Sum.inl_injective + (algebraMap _ (FractionRing (MvPolynomial (Σ i, Fin (d₁ i + e₁ i)) ℚ)) P)) = + algebraMap _ (FractionRing (MvPolynomial (Σ i,A i) ℚ)) (rename (realizationMap R) P) := by + have h₁ := renameInjFraction_algebraMap + (Sum.inl : (Σ i, Fin (d₁ i + e₁ i)) → CellVars (d₁+e₁) (d₂+e₂)) Sum.inl_injective P + have h₂ := renameInjFraction_algebraMap (targetEmbedding p R T) (targetEmbedding p R T).injective + (rename (Sum.inl : (Σ i, Fin (d₁ i + e₁ i)) → CellVars (d₁+e₁) (d₂+e₂)) P) + calc + _ = _ := congrArg (renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective) h₁ + _ = _ := h₂ + _ = _ := by rw [rename_rename]; rfl + simp only [cutKernel,map_div₀,hpoly] + rw [mapped_cut_kernel] + +lemma targetEmbedding_right_kernel (a : I → I → ℕ) + {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) (v : Cut d₂ e₂) : + renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (renameInjFraction Sum.inr Sum.inr_injective (cutKernel a v)) = + kernel (pairKernel a) (left (cutRealizationEquiv T v).val) + (right (cutRealizationEquiv T v).val) := by + have hpoly (P : MvPolynomial (Σ i, Fin (d₂ i + e₂ i)) ℚ) : + renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (renameInjFraction (Sum.inr : (Σ i, Fin (d₂ i + e₂ i)) → CellVars (d₁+e₁) (d₂+e₂)) Sum.inr_injective + (algebraMap _ (FractionRing (MvPolynomial (Σ i, Fin (d₂ i + e₂ i)) ℚ)) P)) = + algebraMap _ (FractionRing (MvPolynomial (Σ i,A i) ℚ)) (rename (realizationMap T) P) := by + have h₁ := renameInjFraction_algebraMap + (Sum.inr : (Σ i, Fin (d₂ i + e₂ i)) → CellVars (d₁+e₁) (d₂+e₂)) Sum.inr_injective P + have h₂ := targetEmbedding_algebraMap p R T + (rename (Sum.inr : (Σ i, Fin (d₂ i + e₂ i)) → CellVars (d₁+e₁) (d₂+e₂)) P) + calc + _ = _ := congrArg (renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective) h₁ + _ = _ := h₂ + _ = _ := by rw [rename_rename]; rfl + simp only [cutKernel,map_div₀,hpoly] + rw [mapped_cut_kernel] + +lemma grid_shape_transfer [∀ i,Fintype (A i)] (a : I → I → ℕ) + {d e : I → ℕ} (f : S d) (g : S e) + {d₁ e₁ d₂ e₂ : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization (d₁+e₁) (left p)) + (T : Realization (d₂+e₂) (right p)) : + (∑ q : SizedCut d₁ (left p),∑ r : SizedCut d₂ (right p), + algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ)) (gridPolynomial a f g p q.val r.val) * + kernel (pairKernel a) (left q.val) (right q.val) * + kernel (pairKernel a) (left r.val) (right r.val)) = + renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (localizeTensor (d₁+e₁) (d₂+e₂) + (cellTransfer a d₁ e₁ d₂ e₂ (fourGridPolynomial a f g d₁ e₁ d₂ e₂))) := by + rw [← fourGridPolynomial_transfer,doubleTensorShuffle] + simp only [LinearMap.coe_mk,AddHom.coe_mk,map_sum,map_mul, + targetEmbedding_left_kernel,targetEmbedding_right_kernel] + rw [← (cutRealizationEquiv R).sum_comp] + apply Finset.sum_congr rfl + intro u hu + rw [← (cutRealizationEquiv T).sum_comp] + apply Finset.sum_congr rfl + intro v hv + apply congrArg (fun z => z * + kernel (pairKernel a) (left (cutRealizationEquiv R u).val) (right (cutRealizationEquiv R u).val) * + kernel (pairKernel a) (left (cutRealizationEquiv T v).val) (right (cutRealizationEquiv T v).val)) + symm + calc + _ = _ := renameInjFraction_algebraMap (targetEmbedding p R T) (targetEmbedding p R T).injective _ + _ = _ := congrArg (algebraMap _ (FractionRing (MvPolynomial (Σi,A i) ℚ))) + (gridPolynomial_four_realization a f g p R T u v) + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {A : I → Type*} [∀ i,DecidableEq (A i)] + +noncomputable def castTensor {d e d' e' : I → ℕ} (h : d=d') (k : e=e') : + S d ⊗[ℚ] S e →ₗ[ℚ] S d' ⊗[ℚ] S e' := by + subst d' + subst e' + exact LinearMap.id + +lemma quotientTensor_cast_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e d' e' : I → ℕ} (h : d=d') (k : e=e') (t : S d ⊗[ℚ] S e) + (ht : quotientTensor a μ d e t = 0) : + quotientTensor a μ d' e' (castTensor h k t) = 0 := by + subst d' + subst e' + exact ht + +noncomputable def targetValueAt {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) : + S d ⊗[ℚ] S e →+ FractionRing (MvPolynomial (Σi,A i) ℚ) where + toFun t := renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (localizeTensor d e t) + map_zero' := by rw [map_zero,map_zero] + map_add' := by intro f g; rw [map_add,map_add] + +omit [Fintype I] [DecidableEq I] in +@[simp] lemma targetValueAt_apply {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) + (f : S d ⊗[ℚ] S e) : + targetValueAt p R T f = renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (localizeTensor d e f) := rfl + +lemma targetValueAt_injective {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) : + Function.Injective (targetValueAt p R T) := + (renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective).injective.comp + (localizeTensor_injective d e) + +omit [DecidableEq I] in +lemma targetValueAt_tmul {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) + (f : S d) (g : S e) : + targetValueAt p R T (f ⊗ₜ[ℚ] g) = labeledValue f (left p) * labeledValue g (right p) := by + rw [labeledValue_eq R,labeledValue_eq T] + simp only [targetValueAt_apply,LinearMap.coe_mk,AddHom.coe_mk,localizeTensor,tensorValue_tmul, + targetEmbedding_algebraMap,map_mul,rename_rename,valueAt] + rfl + +omit [DecidableEq I] in +lemma targetValueAt_independent {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R R' : Realization d (left p)) (T T' : Realization e (right p)) : + targetValueAt p R T = targetValueAt p R' T' := by + apply AddMonoidHom.ext + intro t + induction t using TensorProduct.inductionOn with + | tmul f g => rw [targetValueAt_tmul,targetValueAt_tmul] + | add f g hf hg => simp only [map_add,hf,hg] + +omit [DecidableEq I] in +lemma targetValueAt_cast {d e d' e' : I → ℕ} (h : d=d') (k : e=e') {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (R' : Realization d' (left p)) + (T : Realization e (right p)) (T' : Realization e' (right p)) (t : S d ⊗[ℚ] S e) : + targetValueAt p R' T' (castTensor h k t) = targetValueAt p R T t := by + subst d' + subst e' + rw [targetValueAt_independent p R' R T' T] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma targetValueAt_mul {d e : I → ℕ} {s : Pack (A:=A)} + (p : PackConvolution.Cut s) (R : Realization d (left p)) (T : Realization e (right p)) + (f g : S d ⊗[ℚ] S e) : + targetValueAt p R T (f*g) = targetValueAt p R T f * targetValueAt p R T g := by + change renameInjFraction (targetEmbedding p R T) (targetEmbedding p R T).injective + (algebraMap (MvPolynomial (CellVars d e) ℚ) (FractionRing (MvPolynomial (CellVars d e) ℚ)) + (tensorValue d e (f*g))) = _ + rw [tensorValue_mul,map_mul,map_mul] + rfl + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/TaylorSCoeffHomogeneous.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/TaylorSCoeffHomogeneous.lean new file mode 100644 index 0000000000000000000000000000000000000000..96c1ba7e0b12eb78d5eeb5bac583ea36f061ffd3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/TaylorSCoeffHomogeneous.lean @@ -0,0 +1,180 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GradeBInternal +import OAI.Combinatorics.Chromatic.GradedAlgebra.DHomogeneous + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.Homogeneity ElementaryPositivity.CommonTranslation +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +lemma taylorS_coeff_homogeneous (d : I → ℕ) (f : S d) (k : ℤ) + (hf : f.val.IsWeightedHomogeneous (fun _=>(1:ℤ)) k) (n : ℕ) : + ((taylorS d f).coeff n).val.IsWeightedHomogeneous (fun _=>(1:ℤ)) (k-n) := by + have h := congrArg (fun p : Polynomial (MvPolynomial (Σi,Fin (d i)) ℚ)=>p.coeff n) + (map_taylorSValue d f) + rw [Polynomial.coeff_map] at h + change ((taylorSValue d f).coeff n).val = (taylor f.val).coeff n at h + change ((taylorSValue d f).coeff n).val.IsWeightedHomogeneous _ _ + rw [h] + exact taylor_coeff_homogeneous f.val k hf n + +lemma taylorB_coeff_graded (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (f : B a μ d) (k : ℤ) (hf : f∈gradeB a μ d k) (n : ℕ) : + (taylorB a μ d f).coeff n ∈ gradeB a μ d (k-n) := by + obtain ⟨g,hg,rfl⟩ := gradeB_homogeneous_representative a μ d k f hf + change (taylorB a μ d (quotientAlg a μ d g)).coeff n ∈ _ + rw [taylorB_mk,Polynomial.coeff_map] + change (destabilizingSpace a μ d).mkQ ((taylorS d g).coeff n) ∈ _ + rw [mem_gradeB_iff,componentB_mk,componentS_of_homogeneous _ _ + (taylorS_coeff_homogeneous d g k hg n),ite_eq_left rfl] + +@[simp] lemma taylorB_coeff_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) + (f : B a μ d) : (taylorB a μ d f).coeff 0=f := by + induction f using Submodule.Quotient.induction_on with + | H f => + change (taylorB a μ d (quotientAlg a μ d f)).coeff 0=quotientAlg a μ d f + rw [taylorB_mk,Polynomial.coeff_map] + apply congrArg (quotientAlg a μ d) + apply Subtype.ext + have h := congrArg (fun p : Polynomial (MvPolynomial (Σ i,Fin (d i)) ℚ)=>p.coeff 0) + (map_taylorSValue d f) + rw [Polynomial.coeff_map,taylor_coeff_zero] at h + change ((taylorSValue d f).coeff 0).val=f.val + exact h + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +@[reducible] def Degrees : SplitTree I → Type + | .leaf _ => ℤ + | .node l r => l.Degrees × r.Degrees + +noncomputable instance degreesDecidableEq (T : SplitTree I) : DecidableEq T.Degrees := Classical.decEq _ + +@[reducible] def totalDegree : (T : SplitTree I) → T.Degrees → ℤ + | .leaf _, k => k + | .node l r, k => l.totalDegree k.1 + r.totalDegree k.2 + +@[reducible] def NonnegativeDegree : (T : SplitTree I) → T.Degrees → Prop + | .leaf _, k => 0≤k + | .node l r, k => l.NonnegativeDegree k.1 ∧ r.NonnegativeDegree k.2 + +omit [Fintype I] [DecidableEq I] in +lemma totalDegree_nonnegative (T : SplitTree I) (k : T.Degrees) (h : T.NonnegativeDegree k) : + 0≤T.totalDegree k := by + induction T with + | leaf d => exact h + | node l r ihl ihr => exact add_nonneg (ihl k.1 h.1) (ihr k.2 h.2) + +noncomputable def componentTensor (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) : + (T : SplitTree I) → T.Degrees → + tensor (quotientFamily a μ) T →ₗ[ℚ] tensor (quotientFamily a μ) T + | .leaf d, k => componentB a μ d k + | .node l r, k => TensorProduct.map (componentTensor a μ l k.1) (componentTensor a μ r k.2) + +lemma componentTensor_negative (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (k : T.Degrees) (h : ¬T.NonnegativeDegree k) : + componentTensor a μ T k=0 := by + classical + induction T with + | leaf d => + apply LinearMap.ext + intro f + exact componentB_negative a μ d k (lt_of_not_ge h) f + | node l r ihl ihr => + change TensorProduct.map (componentTensor a μ l k.1) (componentTensor a μ r k.2)=0 + by_cases hl : l.NonnegativeDegree k.1 + · have hr : ¬r.NonnegativeDegree k.2 := fun hr=>h ⟨hl,hr⟩ + rw [ihr k.2 hr,TensorProduct.map_zero_right] + · rw [ihl k.1 hl,TensorProduct.map_zero_left] + +lemma componentTensor_componentTensor (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (k l : T.Degrees) (f : tensor (quotientFamily a μ) T) : + componentTensor a μ T k (componentTensor a μ T l f) = + if k=l then componentTensor a μ T l f else 0 := by + classical + induction T with + | leaf d => + split_ifs with h + · subst l + change componentB a μ d k (componentB a μ d k f) = componentB a μ d k f + exact (componentB_componentB a μ d k k f).trans (ite_eq_left rfl) + · change componentB a μ d k (componentB a μ d l f) = 0 + exact (componentB_componentB a μ d k l f).trans (ite_eq_right h) + | node A B ihA ihB => + induction f using TensorProduct.inductionOn with + | tmul x y => + by_cases hA : k.1=l.1 <;> by_cases hB : k.2=l.2 <;> + simp [componentTensor,TensorProduct.map_tmul,ihA,ihB,Prod.ext_iff,hA,hB] + | add x y hx hy => + simp only [map_add,hx,hy] + split_ifs <;> simp + +theorem componentTensor_finite_decomposition (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (f : tensor (quotientFamily a μ) T) : + ∃ s : Finset T.Degrees, (∀ k∉s,componentTensor a μ T k f=0) ∧ + (∑ k ∈ s,componentTensor a μ T k f)=f := by + classical + induction T with + | leaf d => exact componentB_finite_decomposition a μ d f + | node A B ihA ihB => + induction f using TensorProduct.inductionOn with + | tmul x y => + obtain ⟨s,hs,he⟩ := ihA x + obtain ⟨t,ht,hf⟩ := ihB y + refine ⟨s×ˢt,?_,?_⟩ + · intro k hk + change componentTensor a μ A k.1 x ⊗ₜ[ℚ] componentTensor a μ B k.2 y = 0 + by_cases hx : k.1∈s + · have hy : k.2∉t := fun hy=>hk (Finset.mem_product.mpr ⟨hx,hy⟩) + rw [ht _ hy,TensorProduct.tmul_zero] + · rw [hs _ hx,TensorProduct.zero_tmul] + · change (∑ k ∈ s×ˢt,componentTensor a μ A k.1 x ⊗ₜ[ℚ] componentTensor a μ B k.2 y)=x⊗ₜ[ℚ]y + rw [Finset.sum_product] + simp_rw [← TensorProduct.tmul_sum] + rw [← TensorProduct.sum_tmul,he,hf] + | add x y hx hy => + obtain ⟨s,hs,he⟩ := hx + obtain ⟨t,ht,hf⟩ := hy + refine ⟨s∪t,?_,?_⟩ + · intro k hk + rw [map_add,hs k (fun h=>hk (Finset.mem_union_left t h)), + ht k (fun h=>hk (Finset.mem_union_right s h)),add_zero] + · simp only [map_add,Finset.sum_add_distrib] + have hx : (∑ k ∈ s∪t,componentTensor a μ (.node A B) k x)=x := by + exact (Finset.sum_subset Finset.subset_union_left + (fun k hk hks=>hs k hks)).symm.trans he + have hy : (∑ k ∈ s∪t,componentTensor a μ (.node A B) k y)=y := by + exact (Finset.sum_subset Finset.subset_union_right + (fun k hk hkt=>ht k hkt)).symm.trans hf + rw [hx,hy] + +theorem componentTensor_detect (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T : SplitTree I) (f : tensor (quotientFamily a μ) T) + (h : ∀ k,componentTensor a μ T k f=0) : f=0 := by + obtain ⟨s,hs,he⟩ := componentTensor_finite_decomposition a μ T f + rw [← he] + simp [h] + +@[reducible] def IsOrderedList : SplitTree I → Prop + | .leaf _ => True + | .node (.leaf _) r => r.IsOrderedList + | .node (.node _ _) _ => False + +@[reducible] def doubleShift (a : I → I → ℕ) : SplitTree I → ℤ + | .leaf d => eulerForm a d d + | .node l r => l.doubleShift a + r.doubleShift a + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorColumnNaturality.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorColumnNaturality.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa0d1d838f130d2025a16be2cc97573ea531d6e2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorColumnNaturality.lean @@ -0,0 +1,169 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentMapNaturality +import OAI.Combinatorics.Chromatic.Shuffle.TensorColumnSeriesFiltration + +namespace OAI + +section +namespace ElementaryPositivity.TensorColumns +open scoped TensorProduct +variable {K A B C D A' B' C' D' : Type*} [Field K] + [CommRing A] [CommRing B] [CommRing C] [CommRing D] + [CommRing A'] [CommRing B'] [CommRing C'] [CommRing D'] + [Algebra K A] [Algebra K B] [Algebra K C] [Algebra K D] + [Algebra K A'] [Algebra K B'] [Algebra K C'] [Algebra K D'] + +lemma map_first (f : A →ₐ[K] A') (g : B →ₐ[K] B') (h : C →ₐ[K] C') (k : D →ₐ[K] D') + (x : A⊗[K]B) : + Algebra.TensorProduct.map (Algebra.TensorProduct.map f h) (Algebra.TensorProduct.map g k) + (first x)=first (Algebra.TensorProduct.map f g x) := by + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul a b => simp only [first_tmul,Algebra.TensorProduct.map_tmul,map_one] + +lemma map_second (f : A →ₐ[K] A') (g : B →ₐ[K] B') (h : C →ₐ[K] C') (k : D →ₐ[K] D') + (x : C⊗[K]D) : + Algebra.TensorProduct.map (Algebra.TensorProduct.map f h) (Algebra.TensorProduct.map g k) + (second x)=second (Algebra.TensorProduct.map h k x) := by + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul c d => simp only [second_tmul,Algebra.TensorProduct.map_tmul,map_one] + +lemma map_middle (f : A →ₐ[K] A') (g : B →ₐ[K] B') (h : C →ₐ[K] C') (k : D →ₐ[K] D') + (x : C⊗[K]B) : + Algebra.TensorProduct.map (Algebra.TensorProduct.map f h) (Algebra.TensorProduct.map g k) + (ElementaryPositivity.LinearDetection.middleEmbedding x)= + ElementaryPositivity.LinearDetection.middleEmbedding (Algebra.TensorProduct.map h g x) := by + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul c b => + change Algebra.TensorProduct.map (Algebra.TensorProduct.map f h) (Algebra.TensorProduct.map g k) + ((1⊗ₜ[K]c)⊗ₜ[K](b⊗ₜ[K]1))=(1⊗ₜ[K]h c)⊗ₜ[K](g b⊗ₜ[K]1) + simp only [Algebra.TensorProduct.map_tmul,map_one] + +end ElementaryPositivity.TensorColumns + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.LinearDetection +open ElementaryPositivity.SlopeArithmetic +open HahnSeries SeparationInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] cancelTensorRing cancelTensorAlg cancelFourRing cancelFourAlg +attribute [local instance] cancelTensorSelf cancelTensorNonUnital cancelFourNonUnital cancelSeriesRing +attribute [local instance] cellSepTensorSemiring cellSepTensorNonAssoc cellSepFourSemiring cellSepFourNonAssoc cellSepFourModule +attribute [local instance] braidFourTensor braidFourTensorAlg braidFourRing braidFourAlg +attribute [local instance] braidFourTensorN braidFourTensorM braidFourN braidFourM + +noncomputable local instance quotientFourSemiring (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d₁ e₁ d₂ e₂ : I → ℕ) : + Semiring ((B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂)) := + (braidFourRing a μ d₁ e₁ d₂ e₂).toSemiring +noncomputable local instance quotientFourNonAssoc (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d₁ e₁ d₂ e₂ : I → ℕ) : + NonAssocSemiring ((B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂)) := + (braidFourRing a μ d₁ e₁ d₂ e₂).toNonAssocSemiring + +noncomputable def firstColumnBAlg (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + B a μ d₁⊗[ℚ]B a μ d₂ →ₐ[ℚ](B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂) := + ElementaryPositivity.TensorColumns.first +noncomputable def secondColumnBAlg (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + B a μ e₁⊗[ℚ]B a μ e₂ →ₐ[ℚ](B a μ d₁⊗[ℚ]B a μ e₁)⊗[ℚ](B a μ d₂⊗[ℚ]B a μ e₂) := + ElementaryPositivity.TensorColumns.second + +lemma fourQuotient_firstColumn (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) + (x : S d₁⊗[ℚ]S d₂) : + fourQuotient a μ d₁ e₁ d₂ e₂ (firstColumnAlg d₁ e₁ d₂ e₂ x)= + firstColumnBAlg a μ d₁ e₁ d₂ e₂ (quotientTensor a μ d₁ d₂ x) := + ElementaryPositivity.TensorColumns.map_first + (quotientAlg a μ d₁) (quotientAlg a μ d₂) (quotientAlg a μ e₁) (quotientAlg a μ e₂) x + +lemma fourQuotient_secondColumn (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) + (x : S e₁⊗[ℚ]S e₂) : + fourQuotient a μ d₁ e₁ d₂ e₂ (secondColumnAlg d₁ e₁ d₂ e₂ x)= + secondColumnBAlg a μ d₁ e₁ d₂ e₂ (quotientTensor a μ e₁ e₂ x) := + ElementaryPositivity.TensorColumns.map_second + (quotientAlg a μ d₁) (quotientAlg a μ d₂) (quotientAlg a μ e₁) (quotientAlg a μ e₂) x + +lemma fourQuotient_crossingColumn (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) + (x : S e₁⊗[ℚ]S d₂) : + fourQuotient a μ d₁ e₁ d₂ e₂ (crossingColumnAlg d₁ e₁ d₂ e₂ x)= + crossingColumnBAlg a μ d₁ e₁ d₂ e₂ (quotientTensor a μ e₁ d₂ x) := + ElementaryPositivity.TensorColumns.map_middle + (quotientAlg a μ d₁) (quotientAlg a μ d₂) (quotientAlg a μ e₁) (quotientAlg a μ e₂) x + +lemma fourSeriesQuotient_firstColumn (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) + (F : LaurentSeries (S d₁⊗[ℚ]S d₂)) : + mapRing (fourQuotient a μ d₁ e₁ d₂ e₂).toRingHom + (mapRing (firstColumnAlg d₁ e₁ d₂ e₂).toRingHom F)= + mapRing (firstColumnBAlg a μ d₁ e₁ d₂ e₂).toRingHom + (mapRing (quotientTensor a μ d₁ d₂).toRingHom F) := by + apply HahnSeries.ext + funext j + exact fourQuotient_firstColumn a μ d₁ e₁ d₂ e₂ (F.coeff j) + +lemma fourSeriesQuotient_secondColumn (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) + (F : LaurentSeries (S e₁⊗[ℚ]S e₂)) : + mapRing (fourQuotient a μ d₁ e₁ d₂ e₂).toRingHom + (mapRing (secondColumnAlg d₁ e₁ d₂ e₂).toRingHom F)= + mapRing (secondColumnBAlg a μ d₁ e₁ d₂ e₂).toRingHom + (mapRing (quotientTensor a μ e₁ e₂).toRingHom F) := by + apply HahnSeries.ext + funext j + exact fourQuotient_secondColumn a μ d₁ e₁ d₂ e₂ (F.coeff j) + +lemma fourSeriesQuotient_crossingUnit (a b : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + Units.map (mapRing (fourQuotient a μ d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (mappedInverseKernel b e₁ d₂ (crossingColumnAlg d₁ e₁ d₂ e₂))= + Units.map (mapRing (crossingColumnBAlg a μ d₁ e₁ d₂ e₂).toRingHom).toMonoidHom + (mixedInverseKernelUnit a b μ e₁ d₂) := + mapUnit_square (crossingColumnAlg d₁ e₁ d₂ e₂).toRingHom + (crossingColumnBAlg a μ d₁ e₁ d₂ e₂).toRingHom + (quotientTensor a μ e₁ d₂).toRingHom (fourQuotient a μ d₁ e₁ d₂ e₂).toRingHom + (fourQuotient_crossingColumn a μ d₁ e₁ d₂ e₂) (inverseKernelUnit b e₁ d₂) + +lemma unit_map_ratio_square {R S T : Type*} [Ring R] [Ring S] [Ring T] + (f : R →+* T) (g : S →+* T) (x y : Rˣ) (x' y' : Sˣ) + (hx : Units.map f.toMonoidHom x=Units.map g.toMonoidHom x') + (hy : Units.map f.toMonoidHom y=Units.map g.toMonoidHom y') : + f (x*y⁻¹).val=g (x'*y'⁻¹).val := by + have h : Units.map f.toMonoidHom (x*y⁻¹)=Units.map g.toMonoidHom (x'*y'⁻¹) := by + rw [map_mul,map_inv,map_mul,map_inv,hx,hy] + exact congrArg Units.val h + +lemma fourSeriesQuotient_crossingRatio (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d₁ e₁ d₂ e₂ : I → ℕ) : + mapRing (fourQuotient a μ d₁ e₁ d₂ e₂).toRingHom + (mappedInverseKernel a e₁ d₂ (crossingColumnAlg d₁ e₁ d₂ e₂) * + (mappedInverseKernel (fun i j=>a j i) e₁ d₂ (crossingColumnAlg d₁ e₁ d₂ e₂))⁻¹).val= + mapRing (crossingColumnBAlg a μ d₁ e₁ d₂ e₂).toRingHom (braidingRatioUnit a μ e₁ d₂).val := by + exact unit_map_ratio_square + (mapRing (fourQuotient a μ d₁ e₁ d₂ e₂).toRingHom) + (mapRing (crossingColumnBAlg a μ d₁ e₁ d₂ e₂).toRingHom) _ _ _ _ + (fourSeriesQuotient_crossingUnit a a μ d₁ e₁ d₂ e₂) + (fourSeriesQuotient_crossingUnit a (fun i j=>a j i) μ d₁ e₁ d₂ e₂) + +lemma fourInputSeriesB_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0unitalSeparationSeries_coeff_positive_next a c η hc θ hχ d₁ d₂ hd U j hj f hf) + (fun j hj=>unitalSeparationSeries_coeff_positive_next a c η hc θ hχ e₁ e₂ he V j hj g hg) + rw [coeff_sub] at h₁ + have h:=Submodule.add_mem (fourUnitalFiltration a c η hc θ d₁ e₁ d₂ e₂ (U+V+1)) h₁ h₂ + simpa only [fourInputSeriesB,fourInterchangeB,F,G,H,sub_add_sub_cancel] using h + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle.SeparationInfinity +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +noncomputable local instance unitalNatS (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance unitalNatSA (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance unitalNatB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + CommRing (B a μ d⊗[ℚ]B a μ e) := inferInstance +noncomputable local instance unitalNatBA (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Algebra ℚ (B a μ d⊗[ℚ]B a μ e) := inferInstance + +lemma unitalRestrictionRelativeB_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + obtain ⟨U,V,x,y,hw,hx,hy,rfl⟩:=hz + have hy' := sourceFiltration_antitone a c η hc θ R.dim (show W-U≤V by omega) hy + have he : W=U+(W-U) := by omega + rw [he,refinedLeadingPolynomial_tmul a c η hc θ L R hL hR U (W-U) x y hx hy'] + obtain ⟨p,hp⟩:=totalLeadingPolynomial_denominator_divisible a c η hc θ L hL U x hx + L.centerPairs L.centerPairs_ne L.centerPairs_norev hχL + obtain ⟨q,hq⟩:=totalLeadingPolynomial_denominator_divisible a c η hc θ R hR (W-U) y hy' + R.centerPairs R.centerPairs_ne R.centerPairs_norev hχR + refine ⟨box p q,?_⟩ + rw [hp,hq,box_scalar_left] + rfl + | zero => + simp only [refinedCenterPolynomial,map_zero] + exact dvd_zero _ + | add x y hx hy ihx ihy => + simp only [refinedCenterPolynomial,map_add] at ihx ihy ⊢ + exact dvd_add ihx ihy + | smul r x hx ih => + obtain ⟨q,hq⟩:=ih + refine ⟨r • q,?_⟩ + simp only [refinedCenterPolynomial,map_smul] at hq ⊢ + rw [hq,mul_smul_comm] +end ElementaryPositivity.RawShuffle.SplitTree + +end +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +omit [Fintype I] [DecidableEq I] in +lemma centerPairs_prod_node {A : Type*} [CommMonoid A] (L R : SplitTree I) + (f : (L.node R).Centers × (L.node R).Centers → A) : + (∏ ij∈(L.node R).centerPairs,f ij)= + (∏ ij∈L.centerPairs,f (Sum.inl ij.1,Sum.inl ij.2))* + (∏ ij∈R.centerPairs,f (Sum.inr ij.1,Sum.inr ij.2))* + (∏ ij∈crossPairs L R,f ij) := by + classical + have hLL (x y : L.Centers) : + @LT.lt (L.node R).Centers (centersLinearOrder (L.node R)).toLT + (Sum.inl x) (Sum.inl y) ↔ xcrossPairs_injective L R h), + Fintype.prod_prod_type] + simp only [hLL,hRR,hLR,hRL,ite_true,ite_false,Finset.prod_const_one,one_mul, + Finset.prod_mul_distrib] + ac_rfl + +omit [DecidableEq I] in +lemma centerNumerator_node (a : I → I → ℕ) (L R : SplitTree I) : + centerNumerator a (.node L R) (L.node R).centerPairs = + rename Sum.inl (centerNumerator a L L.centerPairs)* + rename Sum.inr (centerNumerator a R R.centerPairs)* + centerNumerator a (.node L R) (crossPairs L R) := by + unfold centerNumerator + rw [centerPairs_prod_node] + simp only [map_prod,map_pow,diagonal,map_sub,rename_X,leafDimension] + +omit [DecidableEq I] in +lemma centerDenominator_node (a : I → I → ℕ) (L R : SplitTree I) : + centerDenominator a (.node L R) (L.node R).centerPairs = + rename Sum.inl (centerDenominator a L L.centerPairs)* + rename Sum.inr (centerDenominator a R R.centerPairs)* + centerDenominator a (.node L R) (crossPairs L R) := by + unfold centerDenominator + rw [centerPairs_prod_node] + simp only [map_prod,map_pow,diagonal,map_sub,rename_X,leafDimension] +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorFiltration.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorFiltration.lean new file mode 100644 index 0000000000000000000000000000000000000000..232aa7dab17848969d05ca7a2a777c7f4d601d3f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorFiltration.lean @@ -0,0 +1,189 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.DimensionEquivBTrans +import OAI.Combinatorics.Chromatic.Walls.RationalTensorDetection + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.LinearDetection +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +structure RestrictionIndex (c η : I → ℝ) (θ : ℝ) (d : I → ℕ) where + tree : SplitTree I + ordered : tree.IsOrderedList + onSlope : tree.OnSlope c η θ + dimension : tree.dim=d + degree : tree.Degrees + center : tree.Centers →₀ ℕ + +def RestrictionIndex.weight (a : I → I → ℕ) {c η : I → ℝ} {θ : ℝ} {d : I → ℕ} + (j : RestrictionIndex c η θ d) : ℤ := + 2*j.tree.totalDegree j.degree+j.tree.doubleShift a + +noncomputable def indexedRestriction (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0f (Sum.inl i)) h + · ext i; exact congrArg (fun f : α ⊕ β →₀ ℕ=>f (Sum.inr i)) h + · rintro ⟨rfl,rfl⟩; rfl + +lemma coeff_independent_product (p : MvPolynomial α R) (q : MvPolynomial β R) + (z : α →₀ ℕ) (w : β →₀ ℕ) : + (rename Sum.inl p * rename Sum.inr q).coeff (z.sumElim w)=p.coeff z*q.coeff w := by + classical + induction p using MvPolynomial.induction_on' with + | add p r hp hr => simp only [map_add,add_mul,AddMonoidAlgebra.coeff_add,Finsupp.add_apply,hp,hr] + | monomial a c => + induction q using MvPolynomial.induction_on' with + | add q r hq hr => simp only [map_add,mul_add,AddMonoidAlgebra.coeff_add,Finsupp.add_apply,hq,hr] + | monomial b d => + rw [rename_monomial,rename_monomial,monomial_mul_monomial,←Finsupp.sumElim_eq_add] + simp only [coeff_monomial,sumElim_eq_iff] + by_cases ha : a=z <;> by_cases hb : b=w <;> simp [ha,hb] + +end ElementaryPositivity.IndependentCoefficientTensor + +end +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.IndependentCoefficientTensor +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +namespace SplitTree + +lemma centerTranslation_node_coeff (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (T U : SplitTree I) (z : T.Centers →₀ ℕ) (w : U.Centers →₀ ℕ) + (x : tensor (quotientFamily a μ) (.node T U)) : + (centerTranslation (quotientFamily a μ) (taylorB a μ) (.node T U) x).coeff (z.sumElim w)= + TensorProduct.map + (((lcoeff _ z).restrictScalars ℚ).comp (centerTranslation (quotientFamily a μ) (taylorB a μ) T).toLinearMap) + (((lcoeff _ w).restrictScalars ℚ).comp (centerTranslation (quotientFamily a μ) (taylorB a μ) U).toLinearMap) x := by + induction x using TensorProduct.inductionOn with + | tmul x y => + erw [centerTranslation_tmul] + change + (rename Sum.inl (map (Algebra.TensorProduct.includeLeft : tensor (quotientFamily a μ) T →ₐ[ℚ] + tensor (quotientFamily a μ) T ⊗[ℚ] tensor (quotientFamily a μ) U).toRingHom + (centerTranslation (quotientFamily a μ) (taylorB a μ) T x)) * + rename Sum.inr (map (Algebra.TensorProduct.includeRight : tensor (quotientFamily a μ) U →ₐ[ℚ] + tensor (quotientFamily a μ) T ⊗[ℚ] tensor (quotientFamily a μ) U).toRingHom + (centerTranslation (quotientFamily a μ) (taylorB a μ) U y))).coeff (z.sumElim w)=_ + rw [coeff_independent_product,coeff_map,coeff_map] + change (_⊗ₜ[ℚ]1)*(1⊗ₜ[ℚ]_)=_ + rw [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + rfl + | add x y hx hy => simp only [map_add,AddMonoidAlgebra.coeff_add,Finsupp.add_apply,hx,hy] + +lemma restrictionTest_node (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 rfl + | add x y hx hy => simp only [map_add,hx,hy] +end SplitTree + +lemma restrictionB_sourceTensorFiltration (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0TensorProduct.curry + (((-1:ℚ)^eulerForm a k.1.val l.1.val) • TensorProduct.map + (DirectSum.lof ℚ (SlopeWeight c η hc θ) (unitalComponent a c η hc θ) k) + (DirectSum.lof ℚ (SlopeWeight c η hc θ) (unitalComponent a c η hc θ) l)))) + +lemma globalSignOperator_tmul_lof (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0((-1:ℚ)^eulerForm a l.1.val m.1.val) • t) + (Algebra.TensorProduct.tmul_mul_tmul _ _ _ _) + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +lemma signedCellMultiplyB_tmul (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + induction y using Submodule.Quotient.induction_on with + | H y => + induction z using Submodule.Quotient.induction_on with + | H z => + induction w using Submodule.Quotient.induction_on with + | H w => + simp only [unitalGradeShuffle_mk,unitalGradeCast_mk,unitalTensorGradeInclusionW] + apply mk_eq_smul_of_val_eq + change signedCellMultiplyB a c η hc θ _ _ _ _ hon + (x.val⊗ₜ[ℚ]y.val) (z.val⊗ₜ[ℚ]w.val)= + ((-1:ℚ)^eulerForm a d₂ e₁) • + (shuffleBUnit a c η hc d₁ e₁ _ x.val z.val⊗ₜ[ℚ] + (unitalFiltrationCast a c η hc θ rfl _ _).val) + rw [unitalFiltrationCast_val] + exact signedCellMultiplyB_tmul a c η hc θ d₁ e₁ d₂ e₂ hon x.val y.val z.val w.val + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorPolynomialAssoc.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorPolynomialAssoc.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce86b8418bc126567824d1ce0dcaaab4f63050f5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorPolynomialAssoc.lean @@ -0,0 +1,33 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.TensorPolynomialBox + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial ElementaryPositivity.CenterCalculus +open scoped TensorProduct + +lemma box_assoc {A B C α β γ : Type*} [CommRing A] [CommRing B] [CommRing C] + [Algebra ℚ A] [Algebra ℚ B] [Algebra ℚ C] + (p : MvPolynomial α A) (q : MvPolynomial β B) (r : MvPolynomial γ C) : + extendPolynomial (Algebra.TensorProduct.assoc ℚ ℚ ℚ A B C).toAlgHom (Equiv.sumAssoc α β γ) + (box (box p q) r)=box p (box q r) := by + change extendPolynomial _ _ + (extendPolynomial (Algebra.TensorProduct.includeLeft : A⊗[ℚ]B →ₐ[ℚ] (A⊗[ℚ]B)⊗[ℚ]C) Sum.inl + (extendPolynomial (Algebra.TensorProduct.includeLeft : A →ₐ[ℚ] A⊗[ℚ]B) Sum.inl p * + extendPolynomial (Algebra.TensorProduct.includeRight : B →ₐ[ℚ] A⊗[ℚ]B) Sum.inr q) * + extendPolynomial (Algebra.TensorProduct.includeRight : C →ₐ[ℚ] (A⊗[ℚ]B)⊗[ℚ]C) Sum.inr r)= + extendPolynomial (Algebra.TensorProduct.includeLeft : A →ₐ[ℚ] A⊗[ℚ](B⊗[ℚ]C)) Sum.inl p * + extendPolynomial (Algebra.TensorProduct.includeRight : B⊗[ℚ]C →ₐ[ℚ] A⊗[ℚ](B⊗[ℚ]C)) Sum.inr + (extendPolynomial (Algebra.TensorProduct.includeLeft : B →ₐ[ℚ] B⊗[ℚ]C) Sum.inl q * + extendPolynomial (Algebra.TensorProduct.includeRight : C →ₐ[ℚ] B⊗[ℚ]C) Sum.inr r) + simp only [map_mul,extendPolynomial_comp] + rw [mul_assoc] + congr 2 + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorPolynomialBox.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorPolynomialBox.lean new file mode 100644 index 0000000000000000000000000000000000000000..56c5222b21eb47085f19ea499e4f756644ba333c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/TensorPolynomialBox.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.DegreeIdeals +import OAI.Combinatorics.Chromatic.Shuffle.TensorFiltration + +namespace OAI + +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +open scoped TensorProduct +variable {α β A B : Type*} [CommRing A] [CommRing B] [Algebra ℚ A] [Algebra ℚ B] + +noncomputable def box (p : MvPolynomial α A) (q : MvPolynomial β B) : + MvPolynomial (α ⊕ β) (A ⊗[ℚ] B) := + rename Sum.inl (map (Algebra.TensorProduct.includeLeft : A →ₐ[ℚ] A ⊗[ℚ] B).toRingHom p) * + rename Sum.inr (map (Algebra.TensorProduct.includeRight : B →ₐ[ℚ] A ⊗[ℚ] B).toRingHom q) + +lemma coeff_box (p : MvPolynomial α A) (q : MvPolynomial β B) + (z : α →₀ ℕ) (w : β →₀ ℕ) : + (box p q).coeff (z.sumElim w) = p.coeff z ⊗ₜ[ℚ] q.coeff w := by + rw [box,IndependentCoefficientTensor.coeff_independent_product,coeff_map,coeff_map] + change (_ ⊗ₜ[ℚ] 1) * (1 ⊗ₜ[ℚ] _) = _ + rw [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + +lemma box_mul (p p' : MvPolynomial α A) (q q' : MvPolynomial β B) : + box (p*p') (q*q') = box p q * box p' q' := by + simp only [box,map_mul] + ring + +lemma box_scalar (p : MvPolynomial α ℚ) (q : MvPolynomial β ℚ) : + box (map (algebraMap ℚ A) p) (map (algebraMap ℚ B) q) = + map (algebraMap ℚ (A ⊗[ℚ] B)) (rename Sum.inl p * rename Sum.inr q) := by + have hL : (Algebra.TensorProduct.includeLeft : A →ₐ[ℚ] A ⊗[ℚ] B).toRingHom.comp + (algebraMap ℚ A)=algebraMap ℚ (A ⊗[ℚ] B) := by + ext r + exact (Algebra.TensorProduct.includeLeft : A →ₐ[ℚ] A ⊗[ℚ] B).commutes r + have hR : (Algebra.TensorProduct.includeRight : B →ₐ[ℚ] A ⊗[ℚ] B).toRingHom.comp + (algebraMap ℚ B)=algebraMap ℚ (A ⊗[ℚ] B) := by + ext r + exact (Algebra.TensorProduct.includeRight : B →ₐ[ℚ] A ⊗[ℚ] B).commutes r + simp only [box,map_mul,map_rename,map_map,hL,hR] + +lemma box_scalar_left (p : MvPolynomial α ℚ) (q : MvPolynomial β ℚ) + (f : MvPolynomial α A) (g : MvPolynomial β B) : + box (map (algebraMap ℚ A) p*f) (map (algebraMap ℚ B) q*g)= + map (algebraMap ℚ (A ⊗[ℚ] B)) (rename Sum.inl p*rename Sum.inr q)*box f g := by + rw [box_mul,box_scalar] +end ElementaryPositivity.CenterCalculus + +end +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open ElementaryPositivity.CenterCalculus +open scoped TensorProduct +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma weightComponent_node_tmul (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (L R : SplitTree I) (U V : ℤ) + (x : tensor (quotientFamily a μ) L) (y : tensor (quotientFamily a μ) R) + (hx : x∈degreeCutSubmodule a μ L U) (hy : y∈degreeCutSubmodule a μ R V) : + weightComponent a μ (.node L R) (U+V) (x⊗ₜ[ℚ]y)= + weightComponent a μ L U x ⊗ₜ[ℚ] weightComponent a μ R V y := by + classical + apply sub_eq_zero.mp + apply componentTensor_detect a μ (.node L R) + rintro ⟨k,l⟩ + rw [map_sub,componentTensor_weightComponent] + change (if 2*(L.totalDegree k+R.totalDegree l)+(L.doubleShift a+R.doubleShift a)=U+V + then componentTensor a μ L k x⊗ₜ[ℚ]componentTensor a μ R l y else 0)- + (componentTensor a μ L k (weightComponent a μ L U x)⊗ₜ[ℚ] + componentTensor a μ R l (weightComponent a μ R V y))=0 + rw [componentTensor_weightComponent,componentTensor_weightComponent] + by_cases hk : 2*L.totalDegree k+L.doubleShift a (try simp only [TensorProduct.zero_tmul,TensorProduct.tmul_zero,sub_self]) <;> omega + +lemma centeredRestrictionB_coeff_degreeCut (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + rw [sourceGradeDimensionEquiv_mk a c η hc θ (add_comm d e) W f, + separationCoproduct_mk a c η hc θ e d hs.symm W, + separationCoproduct_mk a c η hc θ d e hs W, + sourceTensorGradeComm_mk a c η hc θ d e W] + apply sub_eq_zero.mp + change Submodule.Quotient.mk + (separationCoefficientRestricted a c η hc θ e d hs.symm W 0 + (filtrationDimensionEquiv a c η hc θ (add_comm d e) W f) - + (-1:ℚ)^eulerForm a d e • + SplitTree.sourceTensorComm a c η hc θ d e W + (separationCoefficientRestricted a c η hc θ d e hs W 0 f))=0 + apply (Submodule.Quotient.mk_eq_zero _).mpr + let x := separationCoefficientRestricted a c η hc θ e d hs.symm W 0 + (filtrationDimensionEquiv a c η hc θ (add_comm d e) W f) - + (-1:ℚ)^eulerForm a d e • SplitTree.sourceTensorComm a c η hc θ d e W + (separationCoefficientRestricted a c η hc θ d e hs W 0 f) + change x.val ∈ sourceTensorFiltration a c η hc θ e d (W+1) + apply SplitTree.normalizedTensorSymbol_detect a c η hc θ hχ e d W x + intro R L hR hL he hd + subst d + subst e + let N := SplitTree.normalizedTensorSymbol a c η hc θ R L hR hL + (SplitTree.pairSymmetric_of_slope a c η θ hχ R hR) + (SplitTree.pairSymmetric_of_slope a c η θ hχ L hL) W + let C := separationCoefficientRestricted a c η hc θ L.dim R.dim hs W 0 f + let C' := separationCoefficientRestricted a c η hc θ R.dim L.dim hs.symm W 0 + (filtrationDimensionEquiv a c η hc θ (add_comm L.dim R.dim) W f) + change N (C' - (-1:ℚ)^eulerForm a L.dim R.dim • + SplitTree.sourceTensorComm a c η hc θ L.dim R.dim W C)=0 + rw [N.map_sub, N.map_smul] + change SplitTree.normalizedTensorSymbol a c η hc θ R L hR hL _ _ W C' - + (-1:ℚ)^eulerForm a L.dim R.dim • + SplitTree.normalizedTensorSymbol a c η hc θ R L hR hL _ _ W + (SplitTree.sourceTensorComm a c η hc θ L.dim R.dim W C)=0 + have hC := SplitTree.coproduct_normalized_symbol a c η hc θ hχ L R hL hR W f + have hC' := SplitTree.coproduct_normalized_symbol a c η hc θ hχ R L hR hL W + (filtrationDimensionEquiv a c η hc θ (add_comm L.dim R.dim) W f) + change SplitTree.normalizedTensorSymbol a c η hc θ L R hL hR _ _ W C=_ at hC + change SplitTree.normalizedTensorSymbol a c η hc θ R L hR hL _ _ W C'=_ at hC' + rw [hC',SplitTree.normalizedTensorSymbol_swap,hC, + SplitTree.Regroup.normalizedSymbol_swap a c η hc θ hχ L R hL hR] + exact sub_self _ + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/TripleAssociativity.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/TripleAssociativity.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e3505553ee653a48973f991afb6838d8e271a86 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/TripleAssociativity.lean @@ -0,0 +1,173 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.CoproductIteration +import OAI.Combinatorics.Chromatic.Walls.FilteredTensorInsert +import OAI.Combinatorics.Chromatic.Shuffle.TensorPolynomialAssoc +import OAI.Combinatorics.Chromatic.Walls.TensorPolynomialLinear + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial ElementaryPositivity.CenterCalculus +open ElementaryPositivity.LinearDetection +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def normalizedRightTripleSymbol (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0h) (fun w=>separationCoefficient_filtration a c η hc θ e f hs w 0) W x hx + +noncomputable def tensorSeparationRight (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0tensorSeparationRight_filtration a c η hc θ d e f hs W x.val x.property) + +namespace SplitTree +open MvPolynomial ElementaryPositivity.CenterCalculus + +lemma normalizedRightTripleSymbol_tmul_eq (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + exact tmul_mem_additiveTensorFiltration F G (le_refl _) (hF ▸ trivial) (hG ▸ trivial) + | add x y hx hy => exact (additiveTensorFiltration F G (U+V)).add_mem hx hy +end ElementaryPositivity.LinearDetection + +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.LinearDetection +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def sourceTripleFiltration (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0j.1.weight a+j.2.weight a) W := by + ext x + rw [sourceTensorFiltration_iff,mem_testFiltration] + constructor + · exact fun h j=>h j.1 j.2 + · exact fun h i j=>h (i,j) + +lemma sourceTensorFiltration_lower (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0j.1.weight a+j.2.weight a) (RestrictionIndex.weight a) + (-interaction a d d+-interaction a e e) (-interaction a f f) + (by rw [←hd,sourceTensorFiltration_lower]) (by rw [←hf,sourceFiltration_lower]) W x + apply ht.trans + constructor + · exact fun h i j k=>h (i,j) k + · exact fun h ij k=>h ij.1 ij.2 k + +lemma triple_leading_restrictions_detect (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0F.coeff 0) (unitalSeparationSeries_shuffle_grid a c η hc h hs f g R) + +omit [∀ i, Fintype (A i)] in +lemma clearedConstantB_grid_sameSlope_support (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(u i).val) (shapeComplement u) (fun i=>(v i).val) (shapeComplement v) + then clearedConstantB a (slope c η) α β + (quotientTensor a (slope c η) α β (gridShapeTensor a f g p R T u v)) else 0 := by + classical + rw [quotient_gridTensor_sameSlope_support a c η hc f g p R T ht hs] + simp only [map_sum,apply_ite,(clearedConstantB a (slope c η) α β).map_zero] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductCoassociative.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductCoassociative.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee87a467739114b6be87d72df653c9831284696c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductCoassociative.lean @@ -0,0 +1,186 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalCoproductComparison +import OAI.Combinatorics.Chromatic.Walls.UnitalCoproductNaturality +import OAI.Combinatorics.Chromatic.Shuffle.PolynomialExtendInjective +import OAI.Combinatorics.Chromatic.Walls.TensorGradeFunctor + +namespace OAI + +section +namespace ElementaryPositivity.TensorTransport +open scoped TensorProduct +lemma assoc_sub_symm {M N P : Type*} [AddCommGroup M] [Module ℚ M] + [AddCommGroup N] [Module ℚ N] [AddCommGroup P] [Module ℚ P] + (x : (M⊗[ℚ]N)⊗[ℚ]P) (y : M⊗[ℚ](N⊗[ℚ]P)) : + TensorProduct.assoc ℚ M N P (x-(TensorProduct.assoc ℚ M N P).symm y)= + TensorProduct.assoc ℚ M N P x-y := by + simp only [map_sub,LinearEquiv.apply_symm_apply] +end ElementaryPositivity.TensorTransport + +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearDetection + ElementaryPositivity.LinearFiltration SeparationInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] naturalTensorAdd naturalTensorModule pairAdd tripleAdd tripleFilterAdd + +noncomputable local instance unitalTripleRightAdd (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d e f : I → ℕ) : AddCommGroup (B a μ d⊗[ℚ](B a μ e⊗[ℚ]B a μ f)) := + TensorProduct.addCommGroup +noncomputable local instance unitalTripleRightModule (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d e f : I → ℕ) : Module ℚ (B a μ d⊗[ℚ](B a μ e⊗[ℚ]B a μ f)) := + TensorProduct.leftModule + +lemma unitalSeparationConstant_eq_linear (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0h) W + +noncomputable def unitalTensorCoproductRight (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0h) (unitalSeparationConstant_filtered a c η hc θ e f hs) W + +theorem unitalGradeCoproduct_coassociative (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + rw [unitalGradeCast_mk,unitalGradeCoproduct_mk,unitalGradeCoproduct_mk] + apply sub_eq_zero.mp + change mk _ _ ⟨TensorProduct.assoc ℚ _ _ _ + (TensorProduct.map (unitalSeparationConstant a c η hc d e (hd.compatible he)) LinearMap.id + (unitalSeparationConstant a c η hc (d+e) f ((hd.add hc he).compatible hf) x.val)),_⟩ - + mk _ _ ⟨TensorProduct.map LinearMap.id + (unitalSeparationConstant a c η hc e f (he.compatible hf)) + (unitalSeparationConstant a c η hc d (e+f) (hd.compatible (he.add hc hf)) + (unitalFiltrationCast a c η hc θ (add_assoc d e f) rfl x).val),_⟩=0 + rw [←LinearMap.map_sub] + apply (Submodule.Quotient.mk_eq_zero _).mpr + change TensorProduct.assoc ℚ _ _ _ + (TensorProduct.map (unitalSeparationConstant a c η hc d e (hd.compatible he)) LinearMap.id + (unitalSeparationConstant a c η hc (d+e) f ((hd.add hc he).compatible hf) x.val)) - + TensorProduct.map LinearMap.id + (unitalSeparationConstant a c η hc e f (he.compatible hf)) + (unitalSeparationConstant a c η hc d (e+f) (hd.compatible (he.add hc hf)) + (unitalFiltrationCast a c η hc θ (add_assoc d e f) rfl x).val)∈ + additiveTensorFiltration (unitalSourceFiltration a c η hc θ d) + (unitalSourceTensorFiltration a c η hc θ e f) (W+1) + rw [unitalFiltrationCast_val] + exact unitalCoproduct_coassoc_filtration a c η hc θ hχ d e f hd he hf W x.val x.property +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductComparison.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..e954f74d6b694070ec494030c59c4eb2ca4d12c4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductComparison.lean @@ -0,0 +1,102 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.TensorSymbolSwap + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration +open SeparationInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] cocommTensorBCommRing cocommTensorBAlgebra + +lemma unitalSeparationConstant_eq (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0.resolve_left he0 + rw [unitalSourceFiltration_nonzero a c η hc θ (d+e) (add_ne_zero_left _ _ hd0) W] at hx + rw [unitalSourceTensorFiltration_nonzero a c η hc θ e d he0 hd0, + unitalSeparationConstant_eq a c η hc e d _ hde.symm, + unitalSeparationConstant_eq a c η hc d e _ hde] + exact separationCoproduct_cocommutative_filtration a c η hc θ hχ d e hde W x hx + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductUnits.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductUnits.lean new file mode 100644 index 0000000000000000000000000000000000000000..396881fb2641cd56799cf731b85ab971da055ce7 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalCoproductUnits.lean @@ -0,0 +1,184 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalGrade + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LaurentAtInfinity +open SeparationInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] unitalSepTensor unitalSepTensorA unitalSepTensorN unitalSepTensorM + +lemma unitalSeparationConstant_zero_left (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 < c i) (d : I → ℕ) (f : B a (slope c η) d) : + unitalSeparationConstant a c η hc 0 d (Or.inl rfl) + (castB a (slope c η) (zero_add d).symm f) = + (1 : B a (slope c η) 0) ⊗ₜ[ℚ] f := by + change ((quotientInverseKernelUnit a (slope c η) 0 d).val * + polynomial (unitalRestrictionRelativeB a c η hc (Or.inl rfl) + (castB a (slope c η) (zero_add d).symm f))).coeff 0 = _ + rw [quotientInverseKernelUnit_zero_left, Units.val_one, one_mul] + rw [show (0 : ℤ) = -(0 : ℕ) by simp, polynomial_coeff] + change (relativeTaylorB a (slope c η) 0 d + (restrictionBUnit a c η hc (Or.inl rfl) (firstCut 0 d) + (castB a (slope c η) (zero_add d).symm f))).coeff 0 = _ + rw [relativeTaylorB_coeff_zero, restrictionBUnit_zero_left] + +lemma unitalSeparationConstant_zero_right (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i, 0 < c i) (d : I → ℕ) (f : B a (slope c η) d) : + unitalSeparationConstant a c η hc d 0 (Or.inr (Or.inl rfl)) + (castB a (slope c η) (add_zero d).symm f) = + f ⊗ₜ[ℚ] (1 : B a (slope c η) 0) := by + change ((quotientInverseKernelUnit a (slope c η) d 0).val * + polynomial (unitalRestrictionRelativeB a c η hc (Or.inr (Or.inl rfl)) + (castB a (slope c η) (add_zero d).symm f))).coeff 0 = _ + rw [quotientInverseKernelUnit_zero_right, Units.val_one, one_mul] + rw [show (0 : ℤ) = -(0 : ℕ) by simp, polynomial_coeff] + change (relativeTaylorB a (slope c η) d 0 + (restrictionBUnit a c η hc (Or.inr (Or.inl rfl)) (firstCut d 0) + (castB a (slope c η) (add_zero d).symm f))).coeff 0 = _ + rw [relativeTaylorB_coeff_zero, restrictionBUnit_zero_right] + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial ElementaryPositivity.CenterCalculus +open ElementaryPositivity.ShufflePolynomiality +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma extendPolynomial_map_algebra {A B α β : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (f : A →ₐ[ℚ] B) (j : α → β) (p : MvPolynomial α ℚ) : + extendPolynomial f j (map (algebraMap ℚ A) p)= + map (algebraMap ℚ B) (rename j p) := by + induction p using MvPolynomial.induction_on with + | C r => simp only [map_C,extendPolynomial_C,AlgHom.commutes,rename_C] + | add p q hp hq => simp only [map_add,hp,hq] + | mul_X p i hp => simp only [map_mul,map_X,extendPolynomial_X,rename_X,hp] + +omit [Fintype I] [DecidableEq I] in +lemma node_le_iff (T U : SplitTree I) (x y : (SplitTree.node T U).Centers) : + @LE.le _ (centersLinearOrder (SplitTree.node T U)).toLE x y ↔ + Sum.Lex (· ≤ · : T.Centers → T.Centers → Prop) + (· ≤ · : U.Centers → U.Centers → Prop) x y := Iff.rfl + +namespace Regroup +lemma filtrationDimensionEquiv_val (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0(weightComponent_natural a _ e W x).symm) _ + +def OrderPreserving {T U : SplitTree I} (e : Regroup T U) : Prop := + ∀ i j : T.Centers,e.centers i rcases j with (j|j)|j <;> + simp [Equiv.sumAssoc,Sum.lex_inl_inl,Sum.lex_inr_inr,Sum.lex_inr_inl,Sum.Lex.sep] + +omit [DecidableEq I] in +lemma centerPower_natural (a : I → I → ℕ) {T U : SplitTree I} (e : Regroup T U) + (he : e.OrderPreserving) (φ : ℤ → ℕ) : + rename e.centers (∏ ij∈T.centerPairs, + diagonal ij.1 ij.2 ^ φ (eulerForm a (T.leafDimension ij.1) (T.leafDimension ij.2)))= + ∏ ij∈U.centerPairs, + diagonal ij.1 ij.2 ^ φ (eulerForm a (U.leafDimension ij.1) (U.leafDimension ij.2)) := by + classical + simp only [centerPairs,Finset.prod_filter,map_prod,apply_ite,map_pow,map_one, + diagonal,map_sub,rename_X] + apply Fintype.prod_equiv (Equiv.prodCongr e.centers e.centers) + intro ij + simp only [Equiv.prodCongr_apply,Prod.map_fst,Prod.map_snd,he ij.1 ij.2,e.leafDimension] + +omit [DecidableEq I] in +lemma centerNumerator_natural (a : I → I → ℕ) {T U : SplitTree I} (e : Regroup T U) + (he : e.OrderPreserving) : + rename e.centers (centerNumerator a T T.centerPairs)=centerNumerator a U U.centerPairs := + centerPower_natural a e he Int.toNat + +omit [DecidableEq I] in +lemma centerDenominator_natural (a : I → I → ℕ) {T U : SplitTree I} (e : Regroup T U) + (he : e.OrderPreserving) : + rename e.centers (centerDenominator a T T.centerPairs)=centerDenominator a U U.centerPairs := + centerPower_natural a e he (fun z=>(-z).toNat) + +lemma clearedLeading_natural (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 lhs; rw [←centerDenominator_natural a e he] + rw [←extendPolynomial_map_algebra + (e.equivalence (quotientFamily a (SlopeArithmetic.slope c η))).toAlgHom e.centers, + ←map_mul,denominator_clearedLeading] + +lemma normalizedSymbol_natural (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 funext w + · exact unitalSourceFiltration_nonzero a c η hc θ d hd w + · exact unitalSourceFiltration_nonzero a c η hc θ e he w + +lemma restrictionBUnit_independent (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 exact congrArg (quotientTensor a (slope c η) d e) (restrictTensor_independent A C f) + +lemma restrictionBUnit_unitalSourceTensorFiltration (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0.resolve_left he + rw [unitalSourceFiltration_nonzero a c η hc θ (d+e) hde W] at hf + rw [unitalSourceTensorFiltration_nonzero a c η hc θ d e hd he W, + restrictionBUnit_independent a c η hc hs A (firstCut d e), + show restrictionBUnit a c η hc hs (firstCut d e)=restrictionB a c η hc hs' (firstCut d e) from rfl] + exact restrictionB_sourceTensorFiltration a c η hc θ d e hs' W f hf + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open HahnSeries SeparationInfinity +open ElementaryPositivity.LaurentAtInfinity +variable {I : Type*} [Fintype I] [DecidableEq I] +noncomputable local instance braidCoeffTensorS (d e : I → ℕ) : CommRing (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance braidCoeffTensorSA (d e : I → ℕ) : Algebra ℚ (S d⊗[ℚ]S e) := inferInstance +noncomputable local instance braidCoeffTensorB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + CommRing (B a μ d⊗[ℚ]B a μ e) := inferInstance +noncomputable local instance braidCoeffTensorBA (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Algebra ℚ (B a μ d⊗[ℚ]B a μ e) := inferInstance + +noncomputable local instance braidCoeffTensorBN (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + NonUnitalNonAssocSemiring (B a μ d⊗[ℚ]B a μ e) := (braidCoeffTensorB a μ d e).toNonUnitalNonAssocSemiring +noncomputable local instance braidCoeffTensorBM (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Module (B a μ d⊗[ℚ]B a μ e) (B a μ d⊗[ℚ]B a μ e) := Semiring.toModule + +namespace SeparationInfinity +lemma inverseKernelUnit_zero_left (b : I → I → ℕ) (e : I → ℕ) : + inverseKernelUnit b 0 e=1 := by + apply Units.ext + apply mapRing_injective (tensorValueAlg 0 e).toRingHom (tensorValue_injective 0 e) + rw [realize_inverseKernelUnit,Units.val_one,map_one] + simp only [rawInverseKernelUnit,Pi.zero_apply,Finset.univ_eq_empty,Finset.prod_empty, + Finset.prod_const_one,Units.val_one] + +lemma inverseKernelUnit_zero_right (b : I → I → ℕ) (d : I → ℕ) : + inverseKernelUnit b d 0=1 := by + apply Units.ext + apply mapRing_injective (tensorValueAlg d 0).toRingHom (tensorValue_injective d 0) + rw [realize_inverseKernelUnit,Units.val_one,map_one] + simp only [rawInverseKernelUnit,Pi.zero_apply,Finset.univ_eq_empty,Finset.prod_empty, + Finset.prod_const_one,Units.val_one] + +lemma braidingRatioUnit_zero_left (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (e : I → ℕ) : + braidingRatioUnit a μ 0 e=1 := by + simp only [braidingRatioUnit,mixedInverseKernelUnit,inverseKernelUnit_zero_left,map_one, + inv_one,mul_one] + +lemma braidingRatioUnit_zero_right (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + braidingRatioUnit a μ d 0=1 := by + simp only [braidingRatioUnit,mixedInverseKernelUnit,inverseKernelUnit_zero_right,map_one, + inv_one,mul_one] +end SeparationInfinity + +lemma braidingDifference_coeff_mul_next (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0?_) k + · have he : ((braidingRatioUnit a (SlopeArithmetic.slope c η) d e).val-1)*single (0 : ℤ) x= + (braidingRatioUnit a (SlopeArithmetic.slope c η) d e).val*single (0 : ℤ) x-single (0 : ℤ) x := by + rw [sub_mul,one_mul] + rw [←he,coeff_mul_single_zero] at H + exact H + · by_cases hj : j=0 + · subst j; simpa only [coeff_single_same] using hx + · rw [coeff_single_of_ne hj] + exact Submodule.zero_mem _ + +lemma braidingDifference_coeff_mul_unital_next (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0shuffleBUnit_filtered a c η hc θ hχ d e hd he U V f g hf hg) + (fun f hf g hg=>by + simpa only [add_assoc,add_comm (1:ℤ) V] using + shuffleBUnit_filtered a c η hc θ hχ d e hd he (U+1) V f g hf hg) + (fun f hf g hg=>by + simpa only [add_assoc] using + shuffleBUnit_filtered a c η hc θ hχ d e hd he U (V+1) f g hf hg) + +lemma unitalGradeShuffle_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0unitalSeparationSeries_coeff_filtration a c η hc θ d e hs W 0 f hf) + (fun f hf=>unitalSeparationSeries_coeff_filtration a c η hc θ d e hs (W+1) 0 f hf) + +lemma unitalGradeCoproduct_mk (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + induction g using Submodule.Quotient.induction_on with + | H g => + induction h using Submodule.Quotient.induction_on with + | H h => + change castB a (slope c η) (add_assoc d e b) + (quotientAlg a (slope c η) ((d+e)+b) (shufflePolynomial a (shufflePolynomial a f g) h))= + quotientAlg a (slope c η) (d+(e+b)) (shufflePolynomial a f (shufflePolynomial a g h)) + rw [castB_mk,shufflePolynomial_assoc] + +noncomputable def unitalFiltrationCast (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + induction g using Submodule.Quotient.induction_on with + | H g => + induction h using Submodule.Quotient.induction_on with + | H h => + simp only [unitalGradeShuffle_mk,unitalGradeCast_mk] + congr 1 + apply Subtype.ext + rw [unitalFiltrationCast_val] + exact shuffleBUnit_assoc a c η hc θ d e b hd he hb f.val g.val h.val + +noncomputable def unitalGradeOne (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + rw [unitalGradeOne,unitalGradeShuffle_mk,unitalGradeCast_mk] + congr 1 + apply Subtype.ext + rw [unitalFiltrationCast_val] + exact shuffleBUnit_one_left a c η hc d _ f.val + +lemma unitalGradeShuffle_one_right (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + rw [unitalGradeOne,unitalGradeShuffle_mk,unitalGradeCast_mk] + congr 1 + apply Subtype.ext + rw [unitalFiltrationCast_val] + exact shuffleBUnit_one_right a c η hc d _ f.val +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +open scoped DirectSum +variable {I : Type*} [Fintype I] [DecidableEq I] + +abbrev slopeDimensions (c η : I → ℝ) (hc : ∀ i,0hd.add hc he + +abbrev SlopeWeight (c η : I → ℝ) (hc : ∀ i,0map_zero _) + (fun {i j} x=>by + change unitalGradeShuffle a c η hc θ hχ.out i.1.val j.1.val + i.1.property j.1.property i.2 j.2 0 x=0 + rw [map_zero] + rfl) + (fun _ _ _=>map_add _ _ _) + (fun {i j} x y z=>by + change unitalGradeShuffle a c η hc θ hχ.out i.1.val j.1.val + i.1.property j.1.property i.2 j.2 (x+y) z=_ + rw [map_add] + rfl) + +lemma component_smul_mul (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + simp only [unitalGradeCast_mk,unitalGradeOne,unitalTensorGradeInclusionW, + unitalGradeCoproduct_mk] + apply congrArg (mk _ _) + apply Subtype.ext + change unitalSeparationConstant a c η hc 0 d (Or.inl rfl) + (unitalFiltrationCast a c η hc θ (zero_add d).symm rfl f).val= + (1:B a (slope c η) 0)⊗ₜ[ℚ] + (unitalFiltrationCast a c η hc θ rfl (sub_zero W).symm f).val + rw [unitalFiltrationCast_val,unitalFiltrationCast_val] + exact unitalSeparationConstant_zero_left a c η hc d f.val + +lemma unitalGradeCoproduct_zero_right (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + simp only [unitalGradeCast_mk,unitalGradeOne,unitalTensorGradeInclusionW, + unitalGradeCoproduct_mk] + apply congrArg (mk _ _) + apply Subtype.ext + change unitalSeparationConstant a c η hc d 0 (Or.inr (Or.inl rfl)) + (unitalFiltrationCast a c η hc θ (add_zero d).symm rfl f).val= + f.val⊗ₜ[ℚ](unitalFiltrationCast a c η hc θ rfl (sub_self W).symm _).val + rw [unitalFiltrationCast_val,unitalFiltrationCast_val] + exact unitalSeparationConstant_zero_right a c η hc d f.val + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct DirectSum +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +noncomputable def zeroGradeCounit (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + rw [zeroGradeCounit_mk,unitalGradeOne] + change mk _ _ x = mk _ _ (_ • _) + apply congrArg (mk _ _) + apply Subtype.ext + change x.val=zeroQuotientEquiv a (slope c η) x.val • (1 : B a (slope c η) 0) + apply (zeroQuotientEquiv a (slope c η)).injective + rw [map_smul] + change zeroQuotientEquiv a (slope c η) x.val = + zeroQuotientEquiv a (slope c η) x.val • MvPolynomial.constantCoeff (1 : S (0:I → ℕ)).val + simp + +noncomputable def globalUnit (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy,add_zero] + | ht u x y => + rw [globalTensorGradeInclusion_part,TensorProduct.map_tmul, + globalCounit_lof_ne a c η hc θ (d,u) (by intro h; exact hd (congrArg (fun k=>k.1.val) h)), + TensorProduct.zero_tmul] + +lemma globalCounit_tensor_nonzero_right (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy,add_zero] + | ht u x y => + rw [globalTensorGradeInclusion_part,TensorProduct.map_tmul, + globalCounit_lof_ne a c η hc θ (e,W-u) (by intro h; exact he (congrArg (fun k=>k.1.val) h)), + TensorProduct.tmul_zero] +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalOriginalDegree.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalOriginalDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..c518c21e13990afd4e49a161e17a403845defc4e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalOriginalDegree.lean @@ -0,0 +1,238 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveStrings + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + simp only [unitalAssociatedComponent_mk] + apply congrArg Submodule.Quotient.mk + apply Subtype.ext + exact (componentB_componentB a _ d ℓ m f.val).trans (ite_eq_left h) + · rw [ite_eq_right h] + induction f using Submodule.Quotient.induction_on with + | H f => + rw [unitalAssociatedComponent_mk,unitalAssociatedComponent_mk] + apply (Submodule.Quotient.mk_eq_zero _).mpr + change componentB a _ d ℓ (componentB a _ d m f.val)∈unitalSourceFiltration a c η hc θ d (W+1) + rw [componentB_componentB,ite_eq_right h] + exact Submodule.zero_mem _ + +lemma unitalAssociatedComponent_nonzero (d : I → ℕ) (hd : d≠0) (W ℓ : ℤ) + (x : UnitalSourceGrade a c η hc θ d W) : + unitalGradeNonzeroEquiv a c η hc θ d hd W (unitalAssociatedComponent a c η hc θ d W ℓ x)= + associatedComponent a c η hc θ d W ℓ (unitalGradeNonzeroEquiv a c η hc θ d hd W x) := by + induction x using Submodule.Quotient.induction_on with + | H x => + rw [unitalAssociatedComponent_mk,unitalGradeNonzeroEquiv_mk,unitalGradeNonzeroEquiv_mk,associatedComponent_mk] + +noncomputable def unitalOriginalHomogeneous (d : I → ℕ) (W ℓ : ℤ) : + Submodule ℚ (UnitalSourceGrade a c η hc θ d W) := + LinearMap.ker (unitalAssociatedComponent a c η hc θ d W ℓ-LinearMap.id) + +lemma mem_unitalOriginalHomogeneous (d : I → ℕ) (W ℓ : ℤ) (x : UnitalSourceGrade a c η hc θ d W) : + x∈unitalOriginalHomogeneous a c η hc θ d W ℓ ↔ unitalAssociatedComponent a c η hc θ d W ℓ x=x := by + simp only [unitalOriginalHomogeneous,LinearMap.mem_ker,LinearMap.sub_apply,LinearMap.id_apply,sub_eq_zero] + +lemma unitalOriginalHomogeneous_representative (d : I → ℕ) (W ℓ : ℤ) + (x : UnitalSourceGrade a c η hc θ d W) (hx : x∈unitalOriginalHomogeneous a c η hc θ d W ℓ) : + ∃ f : unitalSourceFiltration a c η hc θ d W, + f.val∈gradeB a (slope c η) d ℓ ∧ Submodule.Quotient.mk f=x := by + obtain ⟨f,rfl⟩:=(LinearFiltration.next _ _).mkQ_surjective x + refine ⟨⟨componentB a (slope c η) d ℓ f.val, + unitalSourceFiltration_component_mem a c η hc θ d W ℓ f.val f.property⟩,⟨f.val,rfl⟩,?_⟩ + exact (mem_unitalOriginalHomogeneous a c η hc θ d W ℓ _).mp hx + +lemma unitalOriginalHomogeneous_mk (d : I → ℕ) (W ℓ : ℤ) + (f : unitalSourceFiltration a c η hc θ d W) (hf : f.val∈gradeB a (slope c η) d ℓ) : + (Submodule.Quotient.mk f : UnitalSourceGrade a c η hc θ d W)∈ + unitalOriginalHomogeneous a c η hc θ d W ℓ := by + apply (mem_unitalOriginalHomogeneous a c η hc θ d W ℓ _).mpr + rw [unitalAssociatedComponent_mk] + apply congrArg Submodule.Quotient.mk + apply Subtype.ext + exact (mem_gradeB_iff a (slope c η) d ℓ f.val).mp hf + +lemma shuffleBUnit_graded (d e : I → ℕ) + (hs : d=0 ∨ e=0 ∨ slope c η d=slope c η e) (m n : ℤ) + (f : B a (slope c η) d) (g : B a (slope c η) e) + (hf : f∈gradeB a (slope c η) d m) (hg : g∈gradeB a (slope c η) e n) : + shuffleBUnit a c η hc d e hs f g∈gradeB a (slope c η) (d+e) (m+n-eulerForm a d e) := by + obtain ⟨f,hfp,rfl⟩:=gradeB_homogeneous_representative a _ d m f hf + obtain ⟨g,hgp,rfl⟩:=gradeB_homogeneous_representative a _ e n g hg + rw [shuffleBUnit_mk,mem_gradeB_iff,componentB_mk, + componentS_of_homogeneous _ _ (shufflePolynomial_homogeneous a f g hfp hgp),ite_eq_left rfl] + +lemma unitalGradeShuffle_original (hχ : SlopeEulerSymmetric a c η θ) (d e : I → ℕ) + (hd : OnSlopeOrZero c η θ d) (he : OnSlopeOrZero c η θ e) (U V m n : ℤ) + (x : UnitalSourceGrade a c η hc θ d U) (y : UnitalSourceGrade a c η hc θ e V) + (hx : x∈unitalOriginalHomogeneous a c η hc θ d U m) + (hy : y∈unitalOriginalHomogeneous a c η hc θ e V n) : + unitalGradeShuffle a c η hc θ hχ d e hd he U V x y∈ + unitalOriginalHomogeneous a c η hc θ (d+e) (U+V) (m+n-eulerForm a d e) := by + obtain ⟨x,hfx,rfl⟩:=unitalOriginalHomogeneous_representative a c η hc θ d U m x hx + obtain ⟨y,hgy,rfl⟩:=unitalOriginalHomogeneous_representative a c η hc θ e V n y hy + rw [unitalGradeShuffle_mk] + exact unitalOriginalHomogeneous_mk a c η hc θ _ _ _ _ + (shuffleBUnit_graded a c η hc d e (hd.compatible he) m n x.val y.val hfx hgy) + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped DirectSum +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(1:ℤ))),ite_eq_left rfl] + +omit hχ in +lemma globalOriginalHomogeneous_one : (1 : UnitalShuffle a c η hc θ)∈globalOriginalHomogeneous a c η hc θ 0 0 := by + refine ⟨unitalGradeOne a c η hc θ,?_,rfl⟩ + exact unitalOriginalHomogeneous_mk a c η hc θ 0 0 0 _ (gradeB_one a c η 0) + +lemma localPrimitiveGlobal_original (k : NonzeroSlopeWeight c η hc θ) (ℓ : ℤ) + (x : primitiveSpace a c η hc θ hχ.out k.val.1.val k.val.2) + (hx : associatedComponent a c η hc θ k.val.1.val k.val.2 ℓ x.val=x.val) : + localPrimitiveGlobal a c η hc θ k x∈globalOriginalHomogeneous a c η hc θ k.val ℓ := by + refine ⟨localPrimitiveInclusion a c η hc θ k x,?_,rfl⟩ + apply (mem_unitalOriginalHomogeneous a c η hc θ _ _ _ _).mpr + apply (unitalGradeNonzeroEquiv a c η hc θ k.val.1.val k.property k.val.2).injective + rw [unitalAssociatedComponent_nonzero] + change associatedComponent a c η hc θ k.val.1.val k.val.2 ℓ + ((unitalGradeNonzeroEquiv a c η hc θ k.val.1.val k.property k.val.2) + ((unitalGradeNonzeroEquiv a c η hc θ k.val.1.val k.property k.val.2).symm x.val))=_ + rw [LinearEquiv.apply_symm_apply] + simpa only [localPrimitiveInclusion,LinearMap.comp_apply,Submodule.subtype_apply, + LinearEquiv.coe_coe,LinearEquiv.apply_symm_apply] using hx + +noncomputable def globalStringPolynomialDegree (i : GlobalStringIndex a c η hc θ) : ℤ := + stringBaseDegree a c η hc θ hχ.out i.1.val.1.val i.1.val.2 i.2.2+i.2.1 + +lemma globalStringFamily_original (i : GlobalStringIndex a c η hc θ) : + globalStringFamily a c η hc θ i∈globalOriginalHomogeneous a c η hc θ i.1.val + (globalStringPolynomialDegree a c η hc θ i) := by + apply localPrimitiveGlobal_original a c η hc θ + exact congrArg Subtype.val (homogeneousPrimitiveStringBasis_degree a c η hc θ hχ.out + i.1.val.1.val i.1.val.2 i.1.property i.2) + +omit [DecidableEq I] in +lemma eulerForm_slopeDimensions_symm (d e : slopeDimensions c η hc θ) : + eulerForm a d.val e.val=eulerForm a e.val d.val := by + by_cases hd : d.val=0 + · rw [hd]; simp [eulerForm] + by_cases he : e.val=0 + · rw [he]; simp [eulerForm] + exact hχ.out _ _ hd he (d.property.resolve_left hd) (e.property.resolve_left he) + +omit [DecidableEq I] in +lemma doubleShift_product (d e : slopeDimensions c η hc θ) (m n : ℤ) : + 2*(m+n-eulerForm a d.val e.val)+eulerForm a (d+e).val (d+e).val= + (2*m+eulerForm a d.val d.val)+(2*n+eulerForm a e.val e.val) := by + change 2*(m+n-eulerForm a d.val e.val)+eulerForm a (d.val+e.val) (d.val+e.val)=_ + rw [eulerForm_add_left,eulerForm_add_right,eulerForm_add_right,eulerForm_slopeDimensions_symm a c η hc θ e d] + ring + +variable {J : Type*} +noncomputable def wordPolynomialDegree (w : J → SlopeWeight c η hc θ) (p : J → ℤ) : List J → ℤ + | [] => 0 + | i::l => p i + wordPolynomialDegree w p l-eulerForm a (w i).1.val (wordWeight c η hc θ w l).1.val + +lemma primitiveWord_original (w : J → SlopeWeight c η hc θ) (p : J → ℤ) + (b : J → UnitalShuffle a c η hc θ) + (hb : ∀ i,b i∈globalOriginalHomogeneous a c η hc θ (w i) (p i)) (l : List J) : + primitiveWord a c η hc θ b l∈globalOriginalHomogeneous a c η hc θ + (wordWeight c η hc θ w l) (wordPolynomialDegree a c η hc θ w p l) := by + induction l with + | nil => exact globalOriginalHomogeneous_one a c η hc θ + | cons i l ih => exact globalOriginalHomogeneous_mul a c η hc θ (hb i) ih + +omit [DecidableEq I] in +lemma wordPolynomialDegree_shift (w : J → SlopeWeight c η hc θ) (p : J → ℤ) (l : List J) : + 2*wordPolynomialDegree a c η hc θ w p l+ + eulerForm a (wordWeight c η hc θ w l).1.val (wordWeight c η hc θ w l).1.val= + (l.map (fun i=>2*p i+eulerForm a (w i).1.val (w i).1.val)).sum := by + induction l with + | nil => simp [wordPolynomialDegree,wordWeight,eulerForm] + | cons i l ih => + change 2*(p i+wordPolynomialDegree a c η hc θ w p l- + eulerForm a (w i).1.val (wordWeight c η hc θ w l).1.val)+ + eulerForm a ((w i).1+(wordWeight c η hc θ w l).1).val + ((w i).1+(wordWeight c η hc θ w l).1).val=_ + rw [doubleShift_product,ih] + rfl + +lemma globalStringPBWBasis_original + (l : PBWWord a c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val)) : + globalStringPBWBasis a c η hc θ l∈globalOriginalHomogeneous a c η hc θ + (wordWeight c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val) l.val) + (wordPolynomialDegree a c η hc θ (fun i : GlobalStringIndex a c η hc θ=>i.1.val) + (globalStringPolynomialDegree a c η hc θ) l.val) := by + rw [globalStringPBWBasis_apply] + exact primitiveWord_original a c η hc θ _ _ _ (globalStringFamily_original a c η hc θ) l.val + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalShuffleCoproduct.lean b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalShuffleCoproduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f9de8158b6fed9610c2f929416551ac1e16354e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Shuffle/UnitalShuffleCoproduct.lean @@ -0,0 +1,67 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.DimensionGrid +import OAI.Combinatorics.Chromatic.Shuffle.UnitalGradeAlgebra + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration +open scoped TensorProduct DirectSum +open DimensionSplit +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +abbrev SlopeSplit (c η : I → ℝ) (_hc : ∀ i,0TensorProduct.map + (DirectSum.lof ℚ (SlopeWeight c η hc θ) (unitalComponent a c η hc θ) (d,u)) + (DirectSum.lof ℚ (SlopeWeight c η hc θ) (unitalComponent a c η hc θ) (e,W-u)))).comp + (unitalSourceTensorGradeEquiv a c η hc θ d.val e.val W).symm.toLinearMap + +noncomputable def globalSplitCoproduct (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 simpa only [map_zero] using hz + | add x y hx hy => rw [map_add]; exact ha _ _ hx hy + | of u z => + change P (tensorGradeEquiv F G hF hG W (DirectSum.lof ℚ ℤ (TensorGradePart F G W) u z)) + rw [tensorGradeEquiv_lof] + induction z using TensorProduct.inductionOn with + | add x y hx hy => rw [map_add]; exact ha _ _ hx hy + | tmul x y => exact ht u x y +end ElementaryPositivity.LinearFiltration + +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration +open scoped TensorProduct DirectSum +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] Classical.propDecidable + +noncomputable def unitalTensorGradeInclusionW (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0Fin (d i)) σ) _ + +omit [DecidableEq I] in +lemma derivativeS_variableSum (d : I → ℕ) : + derivativeS d (variableSum d)=(Fintype.card (Σi,Fin (d i)) : S d) := by + classical + apply Subtype.ext + rw [derivativeS_val] + change D (∑ v : Σi,Fin (d i),X v)=_ + simp only [map_sum,D_X,Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one] + rfl + +omit [Fintype I] [DecidableEq I] in +lemma variables_nonempty_of_ne_zero (d : I → ℕ) (hd : d≠0) : Nonempty (Σi,Fin (d i)) := by + classical + by_contra h + apply hd + funext i + by_contra hi + exact h ⟨⟨i,⟨0,Nat.pos_of_ne_zero hi⟩⟩⟩ + +noncomputable def meanS (d : I → ℕ) : S d := + (Fintype.card (Σi,Fin (d i)) : ℚ)⁻¹ • variableSum d + +omit [DecidableEq I] in +lemma derivativeS_meanS (d : I → ℕ) (hd : d≠0) : derivativeS d (meanS d)=1 := by + have :=variables_nonempty_of_ne_zero d hd + have hn : (Fintype.card (Σi,Fin (d i)) : ℚ)≠0 := by + exact_mod_cast Fintype.card_ne_zero + rw [meanS,map_smul,derivativeS_variableSum] + change _ • (algebraMap ℚ (S d) (Fintype.card (Σi,Fin (d i))))=1 + rw [Algebra.smul_def,←map_mul,inv_mul_cancel₀ hn,map_one] + +noncomputable def meanB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : B a μ d := + quotientAlg a μ d (meanS d) + +lemma derivativeB_meanB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) (hd : d≠0) : + derivativeB a μ d (meanB a μ d)=1 := by + rw [meanB,derivativeB_mk,derivativeS_meanS d hd,map_one] + +noncomputable def meanMultiplyB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + Module.End ℚ (B a μ d) := Algebra.lmul ℚ _ (meanB a μ d) + +lemma derivativeB_meanMultiply_weyl (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d : I → ℕ) (hd : d≠0) (f : B a μ d) : + derivativeB a μ d (meanMultiplyB a μ d f)= + meanMultiplyB a μ d (derivativeB a μ d f)+f := by + change derivativeB a μ d (meanB a μ d*f)=meanB a μ d*derivativeB a μ d f+f + rw [derivativeB_mul,derivativeB_meanB a μ d hd,one_mul,add_comm] + +lemma meanMultiplyB_filtered (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0meanMultiplyB_filtered a c η hc θ d W f hf) + (fun f hf=>meanMultiplyB_filtered a c η hc θ d (W+1) f hf) + +lemma gradeDerivative_meanMultiply_weyl (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 False + | .node _ _ => True +end SplitTree + +noncomputable def properSourceFiltration (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0AddMonoidAlgebra.coeff polynomial z) h1 + change P ((SplitTree.centeredRestrictionB a c η hc θ T hs + (translationB a (SlopeArithmetic.slope c η) T.dim t f)).coeff z)=0 + simpa only [coeff_mapLinear,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply] using he + +lemma properSourceFiltration_mul_mem (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0rfl) + (fun j hj=>(coeff_cut_of_le X hj).symm),cut_eq_monomial_sum,adjoint_sum,map_sum] + apply Finset.sum_congr rfl + intro j hj + rw [adjoint_monomial,coeff_mul_X_pow',ite_eq_left (by have H:=Finset.mem_range.mp hj; omega)] +lemma coeff_adjoint_lower (F X : PowerSeries A) (hF : constantCoeff F=1) (N : ℕ) : + coeff N (adjoint F X)=coeff N X+ + ∑j∈Finset.range N,coeff (N-j) (adjoint F (PowerSeries.C (coeff j X))) := by + rw [coeff_adjoint_expansion,Finset.sum_range_succ,Nat.sub_self,coeff_zero_eq_constantCoeff, + constant_adjoint F _ hF,constantCoeff_C,add_comm] +variable {R : Type*} [CommRing R] [Algebra R A] +lemma adjoint_smul (F X : PowerSeries A) (r : R) : adjoint F (r • X)=r • adjoint F X := by + simp only [adjoint,mul_smul_comm,smul_mul_assoc] +end +end ElementaryPositivity.PowerSeriesAdjoint + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/AffineCutTelescoping.lean b/lean/OAI/Combinatorics/Chromatic/Walls/AffineCutTelescoping.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ea1724acd70cb9f3a09b530d766617897e27141 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/AffineCutTelescoping.lean @@ -0,0 +1,128 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.AffineCut +noncomputable section + +def beforeSide (u v t : ℝ) : Bool := + decide (0 < u+t*v ∨ (u+t*v=0 ∧ v<0)) +def afterSide (u v t : ℝ) : Bool := + decide (0 < u+t*v ∨ (u+t*v=0 ∧ 0 u+t*v) (Set.Icc lo hi) by fun_prop) + (show (0:ℝ)∈Set.Icc (u+lo*v) (u+hi*v) from ⟨hl.le,hh.le⟩) + have hl' : lo u+t*v) (Set.Icc lo hi) by fun_prop) + (show (0:ℝ)∈Set.Icc (u+hi*v) (u+lo*v) from ⟨hh.le,hl.le⟩) + have hl' : lohstraddle' ⟨H,hl⟩)),hv⟩ + · linarith + · rintro (hh | ⟨hh,_⟩) <;> exact Or.inl (by linarith) + · subst v + have hu : u≠0 := hne.resolve_right (by simp) + simp + · have hm : u+lo*v exact Or.inl (by linarith) + · rintro (hh | ⟨hh,hv'⟩) + · by_cases hl : 0hstraddle ⟨H,hh⟩)),hv⟩ + · linarith + +theorem telescope {A B : Type*} (u v : ℝ) (hne : u≠0 ∨ v≠0) + (old : ℝ → A → A) (new : ℝ → B → B) (chart : Bool → A → B) + (l : List ℝ) (hsort : l.Pairwise (· > ·)) (lo hi : ℝ) (hlohi : lo + simp only [List.foldr_nil] + rw [gap_sides u v lo hi hlohi hne] + intro t hlt hth ht + exact List.not_mem_nil (hcut t hlt hth ht) + | cons a l ih => + obtain ⟨has,hsort⟩:=List.pairwise_cons.mp hsort + obtain ⟨hla,hah⟩:=hmem a (by simp) + have hlmem : ∀t∈l,lohlocal t (by simp [ht])), + hlocal a (by simp),hg] + +lemma sort_strict (S : Finset ℝ) : (S.sort (· ≥ ·)).Pairwise (· > ·) := by + have hn : (S.sort (· ≥ ·)).Pairwise (· ≠ ·) := S.sort_nodup _ + exact ((S.pairwise_sort (· ≥ ·)).and hn).imp (fun h=>lt_of_le_of_ne h.1 (Ne.symm h.2)) + +theorem telescope_sort {A B : Type*} (u v : ℝ) (hne : u≠0 ∨ v≠0) + (old : ℝ → A → A) (new : ℝ → B → B) (chart : Bool → A → B) + (S : Finset ℝ) (lo hi : ℝ) (hlohi : lo⟨hgen.1,?_⟩⟩ + intro n hn hnK m hm hm0 + have hpS:=realRoot_mem e C (max N K) d (hd.trans (le_max_left _ _)) p hp + have hmS:=realRoot_mem e C (max N K) n (hnK.trans (le_max_right _ _)) m hm + have HH:=(H (max N K)).joint_plane hpS hmS hv a hgen.1 hm0 + apply positive_ray_of_mem_span e he C L hdeg p m d n hd0 hn hp hm + obtain ⟨x,y,hxy⟩:=Submodule.mem_span_pair.mp HH + exact Submodule.mem_span_singleton.mpr ⟨y,by simpa only [smul_zero,zero_add] using hxy⟩ +end +section Existence +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) + +lemma section_all_order_offset (P : Finset (ℝ×E)) (v k : Module.Dual ℝ E) : + ∃h : Module.Dual ℝ E,(∀N,GenericOffset (realRootsThrough e C N) 0 v h) ∧ ∀as∈P, + (0<(k+as.1 • v) as.2 → 0<(h+as.1 • v) as.2) ∧ + ((k+as.1 • v) as.2<0 → (h+as.1 • v) as.2<0) := + exists_all_generic_offsets_with_probes (realRootsThrough e C) 0 P v k (map_zero k) +end +end Existence +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +include hdeg in +lemma line_chamber_of_not_event (N : ℕ) (v k : Module.Dual ℝ E) + (H : GenericOffset (realRootsThrough e C N) 0 v k) + (a : ℝ) (ha : a∉lineEvents (realRootsThrough e C N) v k) : + ChamberGeneric C N ((k+a • v).toAddMonoidHom.comp e) := by + intro n hn hnN m hm hm0 + have hs:=realRoot_mem e C N n hnN m hm + by_cases hv : v (e m)=0 + · have hk : k (e m)=0:=by + change k (e m)+a*v (e m)=0 at hm0 + simpa only [hv,mul_zero,add_zero] using hm0 + apply H.avoid (e m) hs _ hk + simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using + realRoot_ne_zero C e L hdeg n hn m hm + · exact ha ((mem_lineEvents_iff _ _ _ _).mpr ⟨e m,hs,hv,hm0⟩) + +variable (u : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) +lemma chamber_chart_trivial (F : CompletedPositive u Ω C) (N : ℕ) + (h : M →+ ℝ) (H : ChamberGeneric C N h) : + ∀n≤N,coeff n (chartZero u Ω C h F).val=coeff n 1 := by + intro n hn + cases n with + | zero=>simpa only [coeff_zero_eq_constantCoeff,map_one] using + (chartZero u Ω C h F).property.1 + | succ n=> + rw [coeff_one,ite_eq_right (Nat.succ_ne_zero n)] + apply Finsupp.ext + intro m + by_contra hm + have hm' : coeff (n+1) (chartZero u Ω C h F).val m≠0:=hm + exact H (n+1) (by omega) hn m + (chart_root_of_ne u Ω C (chartZero u Ω C h F) (n+1) m hm') + ((chart_three_support u Ω C h F).2.1 n m hm') + +include hdeg in +lemma line_chart_trivial (F : CompletedPositive u Ω C) (N : ℕ) + (v k : Module.Dual ℝ E) (H : GenericOffset (realRootsThrough e C N) 0 v k) + (a : ℝ) (ha : a∉lineEvents (realRootsThrough e C N) v k) : + ∀n≤N,coeff n (chartZero u Ω C ((k+a • v).toAddMonoidHom.comp e) F).val=coeff n 1 := + chamber_chart_trivial C u Ω F N _ (line_chamber_of_not_event C e L hdeg N v k H a ha) + +omit [Module ℝ E] in +lemma realRootsThrough_mono {N K : ℕ} (h : N≤K) : realRootsThrough e C N⊆realRootsThrough e C K := by + intro s hs + obtain ⟨p,d,hd,hp,rfl⟩:=realRoot_exists C e N s hs + exact realRoot_mem e C K d (hd.trans h) p hp + +lemma lineEvents_mono {S T : Finset E} (h : S⊆T) (v k : Module.Dual ℝ E) : + lineEvents S v k⊆lineEvents T v k := by + intro a ha + obtain ⟨s,hs,hv,hsa⟩:=(mem_lineEvents_iff _ _ _ _).mp ha + exact (mem_lineEvents_iff _ _ _ _).mpr ⟨s,h hs,hv,hsa⟩ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/Average.lean b/lean/OAI/Combinatorics/Chromatic/Walls/Average.lean new file mode 100644 index 0000000000000000000000000000000000000000..4342ec74122ecccc1363f1166c3fd470bbba29c5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/Average.lean @@ -0,0 +1,120 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.SeparatedSymmetry +open MvPolynomial + +variable {α β G H : Type*} [Group G] [Fintype G] [Group H] [Fintype H] + +noncomputable def average (ρ : G →* Equiv.Perm α) : + MvPolynomial α ℚ →ₗ[ℚ] MvPolynomial α ℚ := + (Fintype.card G : ℚ)⁻¹ • ∑ g : G, (rename (ρ g)).toLinearMap + +lemma average_apply (ρ : G →* Equiv.Perm α) (p : MvPolynomial α ℚ) : + average ρ p = (Fintype.card G : ℚ)⁻¹ • ∑ g : G, rename (ρ g) p := by + simp [average] + +lemma rename_average (ρ : G →* Equiv.Perm α) (g : G) (p : MvPolynomial α ℚ) : + rename (ρ g) (average ρ p) = average ρ p := by + rw [average_apply, map_smul, map_sum] + congr 1 + calc + _ = ∑ h : G, rename (ρ (g*h)) p := by + apply Finset.sum_congr rfl + intro h _ + rw [rename_rename] + congr 1 + ext a + simp + _ = _ := Function.Bijective.sum_comp (Group.mulLeft_bijective g) (fun h => rename (ρ h) p) + +lemma average_fixed (ρ : G →* Equiv.Perm α) (p : MvPolynomial α ℚ) + (hp : ∀ g, rename (ρ g) p = p) : average ρ p = p := by + rw [average_apply] + simp only [hp, Finset.sum_const, Finset.card_univ] + rw [← Nat.cast_smul_eq_nsmul ℚ, smul_smul, inv_mul_cancel₀, one_smul] + exact_mod_cast Fintype.card_ne_zero + +def sumAction (ρ : G →* Equiv.Perm α) (τ : H →* Equiv.Perm β) : + G × H →* Equiv.Perm (α ⊕ β) where + toFun g := Equiv.sumCongr (ρ g.1) (τ g.2) + map_one' := by ext x; cases x <;> simp + map_mul' := by intro g h; ext x; cases x <;> simp + +omit [Fintype G] [Fintype H] in +lemma rename_sumAction_left (ρ : G →* Equiv.Perm α) (τ : H →* Equiv.Perm β) + (g : G) (h : H) (p : MvPolynomial α ℚ) : + rename (sumAction ρ τ (g,h)) (rename Sum.inl p) = rename Sum.inl (rename (ρ g) p) := by + simp only [rename_rename] + rfl + +omit [Fintype G] [Fintype H] in +lemma rename_sumAction_right (ρ : G →* Equiv.Perm α) (τ : H →* Equiv.Perm β) + (g : G) (h : H) (p : MvPolynomial β ℚ) : + rename (sumAction ρ τ (g,h)) (rename Sum.inr p) = rename Sum.inr (rename (τ h) p) := by + simp only [rename_rename] + rfl + +lemma average_separated (ρ : G →* Equiv.Perm α) (τ : H →* Equiv.Perm β) + (f : MvPolynomial α ℚ) (g : MvPolynomial β ℚ) : + average (sumAction ρ τ) (rename Sum.inl f * rename Sum.inr g) = + rename Sum.inl (average ρ f) * rename Sum.inr (average τ g) := by + simp only [average_apply, map_mul, Fintype.sum_prod_type, + rename_sumAction_left, rename_sumAction_right, map_smul, map_sum, + Fintype.card_prod, Nat.cast_mul, mul_inv_rev, smul_mul_smul_comm, + Finset.sum_mul, Finset.mul_sum] + rw [mul_comm (Fintype.card H : ℚ)⁻¹ (Fintype.card G : ℚ)⁻¹] + congr 1 + exact Finset.sum_comm + +lemma separated_span (p : MvPolynomial (α ⊕ β) ℚ) : + p ∈ Submodule.span ℚ {q | ∃ (f : MvPolynomial α ℚ) (g : MvPolynomial β ℚ), + q = rename Sum.inl f * rename Sum.inr g} := by + let V : Submodule ℚ (MvPolynomial (α ⊕ β) ℚ) := Submodule.span ℚ + {q | ∃ (f : MvPolynomial α ℚ) (g : MvPolynomial β ℚ), + q = rename Sum.inl f * rename Sum.inr g} + change p ∈ V + induction p using MvPolynomial.induction_on with + | C r => exact Submodule.subset_span ⟨C r, 1, by simp⟩ + | add p q hp hq => exact V.add_mem hp hq + | mul_X p x hp => + induction hp using Submodule.span_induction with + | mem q hq => + obtain ⟨f,g,rfl⟩ := hq + cases x with + | inl a => + apply Submodule.subset_span + exact ⟨f * X a, g, by simp; ring⟩ + | inr b => + apply Submodule.subset_span + exact ⟨f, g * X b, by simp [mul_assoc]⟩ + | zero => simp + | add q r hq hr ihq ihr => simpa [add_mul] using V.add_mem ihq ihr + | smul c q hq ih => simpa [smul_mul_assoc] using V.smul_mem c ih + +theorem invariant_separated_span (ρ : G →* Equiv.Perm α) (τ : H →* Equiv.Perm β) + (p : MvPolynomial (α ⊕ β) ℚ) + (hp : ∀ x, rename (sumAction ρ τ x) p = p) : + p ∈ Submodule.span ℚ {q | ∃ (f : MvPolynomial α ℚ) (g : MvPolynomial β ℚ), + (∀ x, rename (ρ x) f = f) ∧ (∀ y, rename (τ y) g = g) ∧ + q = rename Sum.inl f * rename Sum.inr g} := by + rw [← average_fixed (sumAction ρ τ) p hp] + clear hp + have h := separated_span p + induction h using Submodule.span_induction with + | mem q hq => + obtain ⟨f,g,rfl⟩ := hq + rw [average_separated] + exact Submodule.subset_span ⟨average ρ f, average τ g, + fun x => rename_average ρ x f, fun y => rename_average τ y g, rfl⟩ + | zero => simp + | add q r hq hr ihq ihr => simpa using (Submodule.span ℚ _).add_mem ihq ihr + | smul c q hq ih => simpa using (Submodule.span ℚ _).smul_mem c ih + +end ElementaryPositivity.SeparatedSymmetry + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/BraidingFiltration.lean b/lean/OAI/Combinatorics/Chromatic/Walls/BraidingFiltration.lean new file mode 100644 index 0000000000000000000000000000000000000000..7af406e4789bdfb86b6b2c141660b86ccef674d9 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/BraidingFiltration.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.CellTransferSeparation +import OAI.Combinatorics.Chromatic.Walls.TripleSymbols +import OAI.Combinatorics.Chromatic.GradedAlgebra.CenterCoefficientMembership + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open SplitTree SeparationInfinity +open ElementaryPositivity.LaurentAtInfinity ElementaryPositivity.CenterCalculus +variable {I : Type*} [Fintype I] [DecidableEq I] +noncomputable local instance braidTensorCommRing (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + CommRing (B a μ d⊗[ℚ]B a μ e) := inferInstance +noncomputable local instance braidTensorAlgebra (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Algebra ℚ (B a μ d⊗[ℚ]B a μ e) := inferInstance +noncomputable local instance braidTensorNUSemiring (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + NonUnitalNonAssocSemiring (B a μ d⊗[ℚ]B a μ e) := + (braidTensorCommRing a μ d e).toNonUnitalNonAssocSemiring + +lemma refinedAtB_mem_degreeCut (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0refinedAtB_mem_degreeCut a c η hc θ L R hL hR v w W _ (hF k)) + (by rw [map_one]; exact refined_braidingRatio_degreeZero a c η hc θ hχ L R hL hR v w) + simpa only [map_one,one_mul] using h + +theorem braidingRatio_coeff_next (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0S.coeff k) + (braidingRatio_refined_leading a c η hc θ hχ L R hL hR v w W F hF) + change weightComponent a (SlopeArithmetic.slope c η) (.node L R) W + (refinedAtB a c η hc θ L R hL hR v w _)=_ at hh + rw [HahnSeries.coeff_sub,map_sub,map_sub,sub_eq_zero] + exact hh + · change (2*L.totalDegree j+L.doubleShift a)+(2*R.totalDegree l+R.doubleShift a)=W at hjl + change 2*(L.totalDegree j+R.totalDegree l)+(L.doubleShift a+R.doubleShift a)=W + omega + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CenterCoefficientScalarLinear.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CenterCoefficientScalarLinear.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a835fb74ce7708069a8e88d802761d0683639f2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CenterCoefficientScalarLinear.lean @@ -0,0 +1,24 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.HNSpanning + +namespace OAI + +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +variable {A B σ : Type*} [CommRing A] [CommRing B] [Algebra ℚ A] [Algebra ℚ B] + +lemma mapLinear_scalar_mul (l : A →ₗ[ℚ] B) (p : MvPolynomial σ ℚ) (f : MvPolynomial σ A) : + mapLinear l (map (algebraMap ℚ A) p*f)=map (algebraMap ℚ B) p*mapLinear l f := by + classical + ext m + simp only [coeff_mapLinear,coeff_mul,coeff_map,map_sum] + apply Finset.sum_congr rfl + intro x hx + simpa only [Algebra.smul_def] using l.map_smul (p.coeff x.1) (f.coeff x.2) + +end ElementaryPositivity.CenterCalculus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CenterLineNaturality.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CenterLineNaturality.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea6d183c400e19e52919d4e9cb230d5769381d0c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CenterLineNaturality.lean @@ -0,0 +1,29 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CenterLineSpecialization + +namespace OAI + +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +variable {A B σ : Type*} [CommRing A] [CommRing B] [Algebra ℚ A] [Algebra ℚ B] +lemma lineSpecialization_map (v h : σ → ℚ) (f : A →ₐ[ℚ] B) (p : MvPolynomial σ A) : + lineSpecialization v h (map f.toRingHom p)= + (lineSpecialization v h p).map f.toRingHom := by + have hf (r : ℚ) : f.toRingHom (algebraMap ℚ A r)=algebraMap ℚ B r := f.commutes r + induction p using MvPolynomial.induction_on with + | C a => simp only [map_C,lineSpecialization_C,Polynomial.map_C] + | add p q hp hq => simp only [map_add,Polynomial.map_add,hp,hq] + | mul_X p i hp => + simp only [map_mul,map_X,lineSpecialization_X,Polynomial.map_add,Polynomial.map_mul, + Polynomial.map_C,Polynomial.map_X,hf,hp] + +lemma lineSpecialization_map_algebra (v h : σ → ℚ) (p : MvPolynomial σ ℚ) : + lineSpecialization (A:=A) v h (map (algebraMap ℚ A) p)= + (lineSpecialization v h p).map (algebraMap ℚ A) := + lineSpecialization_map v h (Algebra.ofId ℚ A) p +end ElementaryPositivity.CenterCalculus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CenterLineSpecialization.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CenterLineSpecialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4cd988330079e96075289ce1b1c2547c6bb876a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CenterLineSpecialization.lean @@ -0,0 +1,152 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Histories.KernelEvaluation + +namespace OAI + +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +variable {A B σ : Type*} [CommRing A] [CommRing B] [Algebra ℚ A] [Algebra ℚ B] + +noncomputable def lineSpecialization (v h : σ → ℚ) : MvPolynomial σ A →+* Polynomial A := + eval₂Hom Polynomial.C (fun i=>Polynomial.C (algebraMap ℚ A (v i))+ + Polynomial.C (algebraMap ℚ A (h i))*Polynomial.X) + +@[simp] lemma lineSpecialization_C (v h : σ → ℚ) (a : A) : + lineSpecialization v h (C a)=Polynomial.C a := by + simp only [lineSpecialization,eval₂Hom_C] +@[simp] lemma lineSpecialization_X (v h : σ → ℚ) (i : σ) : + lineSpecialization (A:=A) v h (X i)=Polynomial.C (algebraMap ℚ A (v i))+ + Polynomial.C (algebraMap ℚ A (h i))*Polynomial.X := by + simp only [lineSpecialization,coe_eval₂Hom,eval₂_X] + +lemma lineSpecialization_eval (v h : σ → ℚ) (p : MvPolynomial σ A) (t : ℚ) : + (lineSpecialization v h p).eval (algebraMap ℚ A t)= + evalRat (fun i=>v i+h i*t) p := by + induction p using MvPolynomial.induction_on with + | C a => simp only [lineSpecialization_C,Polynomial.eval_C,evalRat_C] + | add p q hp hq => simp only [map_add,Polynomial.eval_add,hp,hq] + | mul_X p i hp => + simp only [map_mul,Polynomial.eval_mul,hp,lineSpecialization_X,evalRat_X, + Polynomial.eval_add,Polynomial.eval_C,Polynomial.eval_mul,Polynomial.eval_X,map_add,map_mul] + +lemma lineSpecialization_mapLinear (v h : σ → ℚ) (l : A →ₗ[ℚ] B) + (p : MvPolynomial σ A) : + lineSpecialization v h (mapLinear l p)= + RawShuffle.polynomialMapLinear l (lineSpecialization v h p) := by + apply RawShuffle.polynomial_eq_of_rat_evals + intro t + rw [lineSpecialization_eval,RawShuffle.polynomialMapLinear_eval_rat, + lineSpecialization_eval,evalRat_mapLinear] +end ElementaryPositivity.CenterCalculus + +end +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.CenterCalculus +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +noncomputable def refinedAtB (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 rfl + | add x y hx hy => simp only [map_add,hx,hy] + +lemma refinedAtB_relative_eval (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0v z+t) w) + (centeredRestrictionB a c η hc θ (.node L R) ⟨hL,hR⟩ f) := by + change refinedAtB a c η hc θ L R hL hR v w + ((relativeTaylorB a (SlopeArithmetic.slope c η) L.dim R.dim + (RawShuffle.restrictionB a c η hc ((slope_dim c η hc hL).trans (slope_dim c η hc hR).symm) (firstCut L.dim R.dim) f)).eval _) = _ + rw [relativeTaylorB_eval] + trans translationAtB a (SlopeArithmetic.slope c η) (.node L R) + (Sum.elim (fun z=>v z+t) w) (restrictionB a c η hc θ (.node L R) ⟨hL,hR⟩ f) + · simp only [restrictionB,AlgHom.comp_apply] + generalize RawShuffle.restrictionB a c η hc ((slope_dim c η hc hL).trans (slope_dim c η hc hR).symm) + (firstCut L.dim R.dim) f=x + induction x using TensorProduct.inductionOn with + | tmul x y => + change translationAtAlgB a (SlopeArithmetic.slope c η) L v + (restrictionB a c η hc θ L hL (translationB a (SlopeArithmetic.slope c η) L.dim t x)) ⊗ₜ[ℚ] + translationAtAlgB a (SlopeArithmetic.slope c η) R w (restrictionB a c η hc θ R hR y)=_ + rw [translationAtAlgB_apply,translationAtAlgB_apply,restrictionB_translationAt,translationAtB_add] + rfl + | add x y hx hy => simp only [map_add,hx,hy] + · exact (centerTranslation_evalRat a (SlopeArithmetic.slope c η) (.node L R) + (restrictionB a c η hc θ (.node L R) ⟨hL,hR⟩ f) _).symm + +lemma refinedAtB_relative_polynomial (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,01) (fun _=>0)) + (centeredRestrictionB a c η hc θ (.node L R) ⟨hL,hR⟩ f) := by + apply polynomial_eq_of_rat_evals + intro t + rw [eval_map_rat,lineSpecialization_eval,refinedAtB_relative_eval] + have he : Sum.elim (fun z=>v z+t) w = + (fun i=>Sum.elim v w i+Sum.elim (fun _=>1) (fun _=>0) i*t) := by + funext z + cases z <;> simp + rw [he] + +lemma centeredRestrictionB_eval_degreeCut (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + rw [coeff_zero_eq_constantCoeff,(chartZero v Ω C h F).property.1] + change (Finsupp.single 0 (1:R)) m=0 + apply Finsupp.single_eq_of_ne + intro he + exact hm (he ▸ h.ker.zero_mem) + | succ n=> + by_contra hn + exact hm ((chart_three_support v Ω C h F).2.1 n m hn) + +def LexSigns (h k H : M→+ℝ) (m : M) : Prop := + (000H m<0) (coeff (n+1) D.val):=by + intro n hn m hm + by_contra hx + exact hm ((hsign _ hn m (chart_root_of_ne v Ω C D _ m hx)).2.1 (hs.2.2 n m hx)) + have hD0 : ∀n,n+1≤N→SupportedOn v Ω (fun m=>H m<0) (coeff (n+1) D0.val):=by + intro n hn m hm + by_contra hx + have hz : h m=0:=by by_contra hh; exact hx (hker.2.2 (n+1) m hh) + exact hm (((hsign _ hn m (chart_root_of_ne v Ω C D0 _ m hx)).2.2 hz).2.2 (hs0.2.2 n m hx)) + have hB0 : ∀n,n+1≤N→∀m,coeff (n+1) B0.val m≠0→H m=0:=by + intro n hn m hm + have hz : h m=0:=by by_contra hh; exact hm (hker.2.1 (n+1) m hh) + exact ((hsign _ hn m (chart_root_of_ne v Ω C B0 _ m hm)).2.2 hz).2.1 (hs0.2.1 n m hm) + have hAA:=strict_mul_through v Ω (fun m=>0by rw [map_add]; linarith) A.val A0.val N A.property.1 A0.property.1 hA hA0 + have hDD:=strict_mul_through v Ω (fun m=>H m<0) + (fun a b ha hb=>by rw [map_add]; linarith) D0.val D.val N D0.property.1 D.property.1 hD0 hD + have hu:=chart_three_truncated_unique v Ω C H F (A.val*A0.val) B0.val (D0.val*D.val) N + (by simp [A.property.1,A0.property.1]) B0.property.1 + (by simp [D0.property.1,D.property.1]) hfact + (fun n hn m hm=>by by_contra hh; exact hm (hAA n hn m hh)) hB0 + (fun n hn m hm=>by by_contra hh; exact hm (hDD n hn m hh)) + exact fun n hn=>(hu n hn).2.1.symm +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesSplit +noncomputable section +variable {R M I : Type*} [CommRing R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) +theorem chart_negative_refinement (h k H : M→+ℝ) (F : CompletedPositive v Ω C) (N : ℕ) + (hsign : ∀n≤N,∀m,HasRootDegree C n m→LexSigns h k H m) : + ∀n≤N,coeff n (chartNegative v Ω C H F).val= + coeff n ((chartNegative v Ω C k (chartZero v Ω C h F)).val * + (chartNegative v Ω C h F).val) :=by + let A:=chartPositive v Ω C h F + let B:=chartZero v Ω C h F + let D:=chartNegative v Ω C h F + let A0:=chartPositive v Ω C k B + let B0:=chartZero v Ω C k B + let D0:=chartNegative v Ω C k B + have hfact : (A.val*A0.val)*B0.val*(D0.val*D.val)=F.val :=by + calc + _=A.val*(A0.val*B0.val*D0.val)*D.val:=by simp only [mul_assoc] + _=A.val*B.val*D.val:=by rw [chart_three_factorization v Ω C k B] + _=F.val:=chart_three_factorization v Ω C h F + have hs:=chart_three_support v Ω C h F + have hs0:=chart_three_support v Ω C k B + have hker:=chartThree_supported v Ω C k h.ker.toAddSubmonoid B + (chartZero_supported_kernel v Ω C h F) + have hA : ∀n,n+1≤N→SupportedOn v Ω (fun m=>00H m<0) (coeff (n+1) D.val):=by + intro n hn m hm + by_contra hx + exact hm ((hsign _ hn m (chart_root_of_ne v Ω C D _ m hx)).2.1 (hs.2.2 n m hx)) + have hD0 : ∀n,n+1≤N→SupportedOn v Ω (fun m=>H m<0) (coeff (n+1) D0.val):=by + intro n hn m hm + by_contra hx + have hz : h m=0:=by by_contra hh; exact hx (hker.2.2 (n+1) m hh) + exact hm (((hsign _ hn m (chart_root_of_ne v Ω C D0 _ m hx)).2.2 hz).2.2 (hs0.2.2 n m hx)) + have hB0 : ∀n,n+1≤N→∀m,coeff (n+1) B0.val m≠0→H m=0:=by + intro n hn m hm + have hz : h m=0:=by by_contra hh; exact hm (hker.2.1 (n+1) m hh) + exact ((hsign _ hn m (chart_root_of_ne v Ω C B0 _ m hm)).2.2 hz).2.1 (hs0.2.1 n m hm) + have hAA:=strict_mul_through v Ω (fun m=>0by rw [map_add]; linarith) A.val A0.val N A.property.1 A0.property.1 hA hA0 + have hDD:=strict_mul_through v Ω (fun m=>H m<0) + (fun a b ha hb=>by rw [map_add]; linarith) D0.val D.val N D0.property.1 D.property.1 hD0 hD + have hu:=chart_three_truncated_unique v Ω C H F (A.val*A0.val) B0.val (D0.val*D.val) N + (by simp [A.property.1,A0.property.1]) B0.property.1 + (by simp [D0.property.1,D.property.1]) hfact + (fun n hn m hm=>by by_contra hh; exact hm (hAA n hn m hh)) hB0 + (fun n hn m hm=>by by_contra hh; exact hm (hDD n hn m hh)) + exact fun n hn=>(hu n hn).2.2.symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/ComparisonLine.lean b/lean/OAI/Combinatorics/Chromatic/Walls/ComparisonLine.lean new file mode 100644 index 0000000000000000000000000000000000000000..59a3cce6ffd5ad4a6e5fc64c5caf4839c3d28101 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/ComparisonLine.lean @@ -0,0 +1,161 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallRegrade +import OAI.Combinatorics.Chromatic.Walls.AllOrderSectionLine +import OAI.Combinatorics.Chromatic.Walls.ComparisonRefinement + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +structure LineRayData (v k : Module.Dual ℝ E) (a : ℝ) where + root : M + degree : ℕ + degree_pos : 0 + split + · next hp=> + exact False.elim (ha (lineEvents_mono + (realRootsThrough_mono C e hN) v k (line_cut_event C pc e L hdeg v k H a hp))) + · apply orientedBounded_trivial + exact line_chart_trivial C e L hdeg LaurentRay.vUnit Ω (simpleTotalTransport Ω C) + N v k (H N) a ha + · exact .bounded 1 (RegradeBound.one _ _ _ _) (RegradeBound.one _ _ _ _) (fun _ _=>rfl) +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +lemma sort_filter_subset {A : Type*} [LinearOrder A] (S T : Finset A) (h : S⊆T) : + (T.sort (· ≥ ·)).filter (fun a=>decide (a∈S))=S.sort (· ≥ ·) := by + classical + have Hp : ((T.sort (· ≥ ·)).filter (fun a=>decide (a∈S))).Perm (S.sort (· ≥ ·)):=by + apply (List.perm_ext_iff_of_nodup ((T.sort_nodup _).filter _) (S.sort_nodup _)).mpr + intro a + simp only [List.mem_filter,Finset.mem_sort,decide_eq_true_eq] + exact ⟨fun ha=>ha.2,fun ha=>⟨h ha,ha⟩⟩ + exact Hp.eq_of_pairwise' (List.Pairwise.filter _ (T.pairwise_sort _)) (S.pairwise_sort _) + +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) (v k : Module.Dual ℝ E) +def intervalLineEvents (lo hi : ℝ) (N : ℕ) : Finset ℝ := by + classical + exact (lineEvents (realRootsThrough e C N) v k).filter (fun a=>lodecide (a∈intervalLineEvents C e v k lo hi N))= + intervalEventList C e v k lo hi N := + sort_filter_subset _ _ (intervalLineEvents_mono C e v k lo hi h) + +lemma event_not_retained (lo hi : ℝ) {N K : ℕ} (a : ℝ) + (ha : a∈intervalEventList C e v k lo hi K) + (hn : a∉intervalLineEvents C e v k lo hi N) : + a∉lineEvents (realRootsThrough e C N) v k := by + classical + have haF : a∈intervalLineEvents C e v k lo hi K:=Finset.mem_sort _ |>.mp ha + intro ham + exact hn (Finset.mem_filter.mpr ⟨ham,(Finset.mem_filter.mp haF).2⟩) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/ComparisonRefinement.lean b/lean/OAI/Combinatorics/Chromatic/Walls/ComparisonRefinement.lean new file mode 100644 index 0000000000000000000000000000000000000000..409a88964c853d318a114292d12b61720f97b83c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/ComparisonRefinement.lean @@ -0,0 +1,146 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.PureComparisonIdentification + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (δ k : M →+ ℤ) (p : M) (hp : k p=1) (B : ℕ) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +inductive CrossingClose (D : ℕ) : ComparisonCrossing v Ω δ k B → ComparisonCrossing v Ω δ k B → Prop where + | pure (b : Bool) : CrossingClose D (.pure b) (.pure b) + | bounded (u w : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hi : RegradeBound v Ω δ B u.inv.val) + (hf' : RegradeBound v Ω δ B w.val.val) (hi' : RegradeBound v Ω δ B w.inv.val) + (he : ∀n≤B*D,coeff n u.val.val=coeff n w.val.val) : + CrossingClose D (.bounded u hf hi) (.bounded w hf' hi') +lemma CrossingClose.action {D : ℕ} {c c' : ComparisonCrossing v Ω δ k B} + (hc : CrossingClose v Ω δ k B D c c') + (f g : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) + (hf : ∀n≤D,coeff n f=coeff n g) : + ∀d≤D,coeff d (comparisonAction v Ω hΩ δ k p hp B c f)= + coeff d (comparisonAction v Ω hΩ δ k p hp B c' g) := by + cases hc with + | pure b=> + intro d hd + exact comparisonAction_input_congr v Ω hΩ δ k p hp B (.pure b) f g d + (fun n hn=>hf n (hn.trans hd)) + | bounded u w hf hi hf' hi' he=>exact bounded_action_congr v Ω hΩ δ k p hp B D u w hf hi hf' hi' he f g ‹_› +lemma bounded_action_trivial (D : ℕ) (u : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hi : RegradeBound v Ω δ B u.inv.val) + (he : ∀n≤B*D,coeff n u.val.val=coeff n 1) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + ∀d≤D,coeff d (comparisonAction v Ω hΩ δ k p hp B (.bounded u hf hi) f)=coeff d f := by + have H:=bounded_action_congr v Ω hΩ δ k p hp B D u 1 hf hi + (RegradeBound.one v Ω δ B) (RegradeBound.one v Ω δ B) he f f (fun _ _=>rfl) + intro d hd + have HE:=H d hd + change coeff d (comparisonAction v Ω hΩ δ k p hp B (.bounded u hf hi) f)= + coeff d (rationalRegrade v Ω hΩ k p hp δ B 1*f*rationalRegrade v Ω hΩ k p hp δ B 1) at HE + simpa only [rationalRegrade_one,one_mul,mul_one] using HE +inductive WordRefines (D : ℕ) : List (ComparisonCrossing v Ω δ k B) → + List (ComparisonCrossing v Ω δ k B) → Prop where + | nil : WordRefines D [] [] + | cons {c c' l l'} (hc : CrossingClose v Ω δ k B D c c') (hl : WordRefines D l l') : + WordRefines D (c::l) (c'::l') + | insert {l l'} (u : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hi : RegradeBound v Ω δ B u.inv.val) + (he : ∀n≤B*D,coeff n u.val.val=coeff n 1) (hl : WordRefines D l l') : + WordRefines D l (.bounded u hf hi::l') +lemma WordRefines.action {D : ℕ} {l l' : List (ComparisonCrossing v Ω δ k B)} + (hl : WordRefines v Ω δ k B D l l') + (f g : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) + (hf : ∀n≤D,coeff n f=coeff n g) : + ∀d≤D,coeff d (comparisonWordAction v Ω hΩ δ k p hp B l f)= + coeff d (comparisonWordAction v Ω hΩ δ k p hp B l' g) := by + induction hl with + | nil=>exact hf + | cons hc hl ih=>exact hc.action v Ω hΩ δ k p hp B _ _ ih + | insert u hv hi he hl ih=> + intro d hd + rw [ih d hd] + exact (bounded_action_trivial v Ω hΩ δ k p hp B D u hv hi he _ d hd).symm +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (δ k : M →+ ℤ) (B : ℕ) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +inductive CrossingTrivial (N : ℕ) : ComparisonCrossing v Ω δ k B → Prop where + | bounded (u : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hi : RegradeBound v Ω δ B u.inv.val) + (he : ∀n≤N,coeff n u.val.val=coeff n 1) : + CrossingTrivial N (.bounded u hf hi) + +lemma CrossingTrivial.mono {N K : ℕ} {c : ComparisonCrossing v Ω δ k B} + (hc : CrossingTrivial v Ω δ k B N c) (h : K≤N) : + CrossingTrivial v Ω δ k B K c := by + cases hc with + | bounded u hf hi he=>exact .bounded u hf hi (fun n hn=>he n (hn.trans h)) + +lemma CrossingClose.refl (D : ℕ) (c : ComparisonCrossing v Ω δ k B) : + CrossingClose v Ω δ k B D c c := by + cases c with + | pure b=>exact .pure b + | bounded u hf hi=>exact .bounded u u hf hi hf hi (fun _ _=>rfl) + +def orientedBounded (u : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hi : RegradeBound v Ω δ B u.inv.val) + (b : Bool) : ComparisonCrossing v Ω δ k B := + if b then .bounded u hf hi else .bounded u⁻¹ hi hf + +lemma orientedBounded_trivial (u : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hi : RegradeBound v Ω δ B u.inv.val) + (b : Bool) (N : ℕ) (he : ∀n≤N,coeff n u.val.val=coeff n 1) : + CrossingTrivial v Ω δ k B N (orientedBounded v Ω δ k B u hf hi b) := by + cases b + · exact .bounded u⁻¹ hi hf (oldUnit_inverse_congr v Ω δ k u 1 N he) + · exact .bounded u hf hi he + +lemma CrossingTrivial.insert {D : ℕ} {c : ComparisonCrossing v Ω δ k B} + (hc : CrossingTrivial v Ω δ k B (B*D) c) + {l l' : List (ComparisonCrossing v Ω δ k B)} + (hl : WordRefines v Ω δ k B D l l') : + WordRefines v Ω δ k B D l (c::l') := by + cases hc with + | bounded u hf hi he=>exact .insert u hf hi he hl + +lemma filter_word_refines {A : Type*} (keep : A → Bool) + (letter : A → ComparisonCrossing v Ω δ k B) (D : ℕ) (l : List A) + (H : ∀a∈l,keep a=false → CrossingTrivial v Ω δ k B (B*D) (letter a)) : + WordRefines v Ω δ k B D ((l.filter keep).map letter) (l.map letter) := by + induction l with + | nil=>exact .nil + | cons a l ih=> + have ih':=ih (fun a ha=>H a (List.mem_cons_of_mem _ ha)) + cases hh : keep a + · simp only [List.filter_cons,hh,List.map_cons] + exact (H a List.mem_cons_self hh).insert v Ω δ k B ih' + · simp only [List.filter_cons,hh,↓reduceIte,List.map_cons] + exact .cons (CrossingClose.refl v Ω δ k B D (letter a)) ih' +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CompleteUnitRecursion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CompleteUnitRecursion.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e93cc740c5656c0aee0f82adf06c9e838a84ce6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CompleteUnitRecursion.lean @@ -0,0 +1,50 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallUnits + +namespace OAI + +section +section +namespace ElementaryPositivity.WallUnits +open PowerSeries +variable {K : Type*} [Field K] +lemma complete_tail (q u : K) (hq : ∀ n : ℕ,1-q^(n+1)≠0) : + PowerSeries.rescale q (complete q u)=(1+PowerSeries.C (-u)*PowerSeries.X)*complete q u := by + rw [complete,rescale_inv_of_const_one _ _ (constant_elementary _ _)] + symm + apply (PowerSeries.eq_inv_iff_mul_eq_one (by + rw [←PowerSeries.coeff_zero_eq_constantCoeff,coeff_rescale,pow_zero,one_mul, + PowerSeries.coeff_zero_eq_constantCoeff,constant_elementary] + exact one_ne_zero)).mpr + calc + ((1+C (-u)*X)*(elementary q (-u))⁻¹)*PowerSeries.rescale q (elementary q (-u))= + (elementary q (-u))⁻¹*((1+C (-u)*X)*PowerSeries.rescale q (elementary q (-u))) := by ring + _=(elementary q (-u))⁻¹*elementary q (-u) := by rw [←elementary_tail q (-u) hq] + _=1 := PowerSeries.inv_mul_cancel _ (by rw [constant_elementary]; exact one_ne_zero) + +lemma complete_coeff_recursion (q u : K) (hq : ∀ n : ℕ,1-q^(n+1)≠0) (n : ℕ) : + coeff (n+1) (complete q u)*(1-q^(n+1))=u*coeff n (complete q u) := by + have h:=congrArg (coeff (n+1)) (complete_tail q u hq) + rw [add_mul,one_mul,map_add,mul_assoc,coeff_C_mul,coeff_succ_X_mul,coeff_rescale] at h + linear_combination -h + +lemma complete_coeff_zero (q u : K) : coeff 0 (complete q u)=1 := by + rw [complete,coeff_zero_eq_constantCoeff,PowerSeries.constantCoeff_inv,constant_elementary,inv_one] +end ElementaryPositivity.WallUnits +namespace ElementaryPositivity.WallUnits +open PowerSeries +variable {K : Type*} [Field K] +lemma elementaryCoeff_eq_complete (q u : K) (hq : ∀ n : ℕ,1-q^(n+1)≠0) (n : ℕ) : + elementaryCoeff q u n=q^(∑i∈Finset.range n,i)*coeff n (complete q u) := by + induction n with + | zero => simp [elementaryCoeff,complete_coeff_zero] + | succ n ih => + have hh : coeff (n+1) (complete q u)=u*coeff n (complete q u)/(1-q^(n+1)) := + (eq_div_iff (hq n)).mpr (complete_coeff_recursion q u hq n) + rw [elementaryCoeff,ih,Finset.sum_range_succ,pow_add,hh] + ring +end ElementaryPositivity.WallUnits +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CompletedBiUnit.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedBiUnit.lean new file mode 100644 index 0000000000000000000000000000000000000000..6952ccca83a616ce596805f683101b79f38b983d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedBiUnit.lean @@ -0,0 +1,41 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CompletedInverse +import OAI.Combinatorics.Chromatic.Walls.LaurentCompletion + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (u : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance completedBiUnitRing : Ring (Torus u Ω) := Torus.instRing u Ω +local instance completedBiUnitAddCommMonoid : AddCommMonoid (Torus u Ω) := + (Torus.instRing u Ω).toAddCommMonoid +local instance completedBiUnitAddGroup : AddGroup (Torus u Ω) := (Torus.instRing u Ω).toAddGroup +local instance completedBiUnitNonUnitalSemiring : NonUnitalSemiring (Torus u Ω) := + (Torus.instRing u Ω).toNonUnitalSemiring +local instance completedBiUnitNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus u Ω) := + (Torus.instRing u Ω).toNonUnitalNonAssocSemiring + +def completedBiUnit (F : CompletedPositive u Ω C) : + (biSupportedSubring u Ω (nonpDegree coord pc) (pureDegree coord pc))ˣ where + val:=⟨F.val,completed_biSupported u Ω C coord hcoord pc F⟩ + inv:=⟨(completedInverse u Ω C F).val, + completed_biSupported u Ω C coord hcoord pc (completedInverse u Ω C F)⟩ + val_inv:=Subtype.ext (mul_completedInverse u Ω C F) + inv_val:=Subtype.ext (completedInverse_mul u Ω C F) + +@[simp] lemma completedBiUnit_val (F : CompletedPositive u Ω C) : + (completedBiUnit u Ω C coord hcoord pc F).val.val=F.val := rfl +@[simp] lemma completedBiUnit_inv (F : CompletedPositive u Ω C) : + (completedBiUnit u Ω C coord hcoord pc F).inv.val=invOfUnit F.val 1 := rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CompletedCutAction.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedCutAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..74754aa7ca19b8b7a88d46c36dfeadfd4527c3b4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedCutAction.lean @@ -0,0 +1,167 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CompletedPathIndependence +import OAI.Combinatorics.Chromatic.GradedAlgebra.RationalShearEmbedding + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (α : M →+ ℤ) +lemma shearRatio_inv_val_add (t u : ℤ) : (↑((shearRatio v (t+u))⁻¹):RatFunc K)= + (↑((shearRatio v t)⁻¹):RatFunc K)*scale (v^(-2*t)) (↑((shearRatio v u)⁻¹):RatFunc K) := by + simp only [Units.val_inv_eq_inv_val,shearRatio_val_add,map_inv₀,mul_inv_rev] + exact mul_comm _ _ +def shearActionInvHom : FiberTorus v Ω α →+* FiberTorus v Ω α := + FiberTorus.gauge v Ω α (fun t=>(↑((shearRatio v t)⁻¹):RatFunc K)) (by simp) + (shearRatio_inv_val_add v) +lemma shearAction_cancel (f : FiberTorus v Ω α) : + shearActionHom v Ω α (shearActionInvHom v Ω α f)=f := by + change FiberTorus.gaugeAdd v Ω α _ (FiberTorus.gaugeAdd v Ω α _ f)=_ + rw [FiberTorus.gauge_comp] + simpa only [←Units.val_mul,inv_mul_cancel,Units.val_one] using + FiberTorus.gaugeAdd_trivial v Ω α f +lemma shearActionInv_cancel (f : FiberTorus v Ω α) : + shearActionInvHom v Ω α (shearActionHom v Ω α f)=f := by + change FiberTorus.gaugeAdd v Ω α _ (FiberTorus.gaugeAdd v Ω α _ f)=_ + rw [FiberTorus.gauge_comp] + simpa only [←Units.val_mul,mul_inv_cancel,Units.val_one] using + FiberTorus.gaugeAdd_trivial v Ω α f +def shearAction : FiberTorus v Ω α ≃+* FiberTorus v Ω α := + RingEquiv.ofRingHom (shearActionHom v Ω α) (shearActionInvHom v Ω α) + (RingHom.ext (shearAction_cancel v Ω α)) (RingHom.ext (shearActionInv_cancel v Ω α)) +def completedShearAction : PowerSeries (FiberTorus v Ω α) ≃+* PowerSeries (FiberTorus v Ω α) := + RingEquiv.ofRingHom (PowerSeries.map (shearAction v Ω α).toRingHom) + (PowerSeries.map (shearAction v Ω α).symm.toRingHom) + (by apply RingHom.ext; intro f; ext n; simp [PowerSeries.coeff_map]) + (by apply RingHom.ext; intro f; ext n; simp [PowerSeries.coeff_map]) + +def completedOppositeInverseAction : PowerSeries (FiberTorus v Ω α) ≃+* + PowerSeries (FiberTorus v Ω α) := + (completedPureAction v Ω α).trans (completedShearAction v Ω α) + +lemma completed_cut_identity (f : PowerSeries (FiberTorus v Ω α)) : + completedShearAction v Ω α (completedPureAction v Ω α f)= + PowerSeries.map (oppositeInverseActionHom v Ω α) f := by + apply PowerSeries.ext + intro D + change coeff D (PowerSeries.map (shearActionHom v Ω α) + (PowerSeries.map (pureActionHom v Ω α) f))=_ + simp only [coeff_map] + exact congrArg (fun F : FiberTorus v Ω α →+* FiberTorus v Ω α=>F (coeff D f)) + (rational_cut_identity v Ω α) + +lemma completedOppositeInverseAction_eq (f : PowerSeries (FiberTorus v Ω α)) : + completedOppositeInverseAction v Ω α f= + PowerSeries.map (oppositeInverseActionHom v Ω α) f := + completed_cut_identity v Ω α f + +include v in +lemma completedShearAction_embed (hΩ : ∀m,Ω m m=0) (k : M →+ ℤ) (p : M) (hp : k p=1) + (f : PowerSeries (Torus v Ω)) : + completedShearAction v (complementOmega k Ω) (complementAlpha k p Ω) + (PowerSeries.map (embed v Ω hΩ k p hp) f)= + PowerSeries.map (embed v Ω hΩ k p hp) + (PowerSeries.map (Torus.push v Ω Ω (mutationShear Ω p) (mutationShear_pairing Ω hΩ p)) f) := by + apply PowerSeries.ext + intro D + change coeff D (PowerSeries.map (shearActionHom v (complementOmega k Ω) (complementAlpha k p Ω)) + (PowerSeries.map (embed v Ω hΩ k p hp) f))=_ + simp only [coeff_map] + exact shearAction_embed v Ω hΩ k p hp (coeff D f) +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (α : M →+ ℤ) +def mutationSideAction (pos : Bool) : PowerSeries (FiberTorus v Ω α) ≃+* + PowerSeries (FiberTorus v Ω α) := + if pos then RingEquiv.refl _ else completedShearAction v Ω α + +lemma mutationSideAction_cut (f : PowerSeries (FiberTorus v Ω α)) : + mutationSideAction v Ω α false (completedPureAction v Ω α + ((mutationSideAction v Ω α true).symm f))= + PowerSeries.map (oppositeInverseActionHom v Ω α) f := by + exact completed_cut_identity v Ω α f + +lemma mutationSideAction_cut_reverse (f : PowerSeries (FiberTorus v Ω α)) : + mutationSideAction v Ω α true ((completedPureAction v Ω α).symm + ((mutationSideAction v Ω α false).symm f))= + (completedOppositeInverseAction v Ω α).symm f := by + rfl + +lemma mutationSideAction_inner (pos : Bool) (u : (PowerSeries (FiberTorus v Ω α))ˣ) + (f : PowerSeries (FiberTorus v Ω α)) : + mutationSideAction v Ω α pos (innerHom u ((mutationSideAction v Ω α pos).symm f))= + innerHom (Units.map (mutationSideAction v Ω α pos).toMonoidHom u) f := by + rw [show mutationSideAction v Ω α pos (innerHom u ((mutationSideAction v Ω α pos).symm f))= + (mutationSideAction v Ω α pos).toRingHom (innerHom u ((mutationSideAction v Ω α pos).symm f)) from rfl] + rw [map_innerHom] + simp only [RingEquiv.toRingHom_eq_coe,RingEquiv.coe_toRingHom,RingEquiv.apply_symm_apply] + rfl +end + +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +def covectorSideAction (a : Module.Dual ℝ E) : + PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω)) ≃+* + PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω)) := + mutationSideAction LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω) + (decide (0 -f i) (-F) := + fun m=>(hf m).neg l + +lemma SeriesGraded.mul {F G : PowerSeries (Torus v Ω)} + (hF : SeriesGraded v Ω C F) (hG : SeriesGraded v Ω C G) : + SeriesGraded v Ω C (F*G) := by + intro n + rw [coeff_mul] + apply (rootGrade v Ω C n).sum_mem + intro p hp + have H := Finset.HasAntidiagonal.mem_antidiagonal.mp hp + rw [←H] + exact rootGrade_mul v Ω C p.1 p.2 _ _ (hF p.1) (hG p.2) + +lemma SeriesGraded.one : SeriesGraded v Ω C 1 := by + intro n + rw [coeff_one] + split_ifs with h + · subst n; exact rootGrade_one v Ω C + · exact (rootGrade v Ω C n).zero_mem + +lemma SeriesGraded.sub {F G : PowerSeries (Torus v Ω)} + (hF : SeriesGraded v Ω C F) (hG : SeriesGraded v Ω C G) : + SeriesGraded v Ω C (F-G) := fun n=> (rootGrade v Ω C n).sub_mem (hF n) (hG n) + +lemma SeriesGraded.pow {F : PowerSeries (Torus v Ω)} (hF : SeriesGraded v Ω C F) (k : ℕ) : + SeriesGraded v Ω C (F^k) := by + induction k with + | zero => simpa only [pow_zero] using SeriesGraded.one v Ω C + | succ k ih => simpa only [pow_succ] using ih.mul v Ω C hF + +lemma SeriesConverges.pow {f : ι → PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) + (hfg : ∀i,SeriesGraded v Ω C (f i)) (hF : SeriesGraded v Ω C F) (k : ℕ) : + SeriesConverges v Ω l (fun i=>f i^k) (F^k) := by + induction k with + | zero => simpa only [pow_zero] using seriesConverges_const v Ω l 1 + | succ k ih => + simpa only [pow_succ] using ih.mul v Ω C l hf + (fun i=>(hfg i).pow v Ω C k) hfg (hF.pow v Ω C k) hF + +lemma coeff_inverse_one (F : PowerSeries (Torus v Ω)) (n : ℕ) : + coeff n (PowerSeries.invOfUnit F 1) = + if n=0 then 1 else -∑p∈Finset.HasAntidiagonal.antidiagonal n, + if p.2 + rw [coeff_inverse_one] + split_ifs with hn + · subst n; exact rootGrade_one v Ω C + · apply (rootGrade v Ω C n).neg_mem + intro m hm + rw [Finsupp.finsetSum_apply] + apply Finset.sum_eq_zero + intro p hp + split_ifs with hp2 + · have H := Finset.HasAntidiagonal.mem_antidiagonal.mp hp + rw [←H] at hm + exact rootGrade_mul v Ω C p.1 p.2 _ _ (hF p.1) (ih p.2 hp2) m hm + · rfl + +theorem SeriesConverges.inverse {f : ι → PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) + (hfg : ∀i,SeriesGraded v Ω C (f i)) (hF : SeriesGraded v Ω C F) : + SeriesConverges v Ω l (fun i=>PowerSeries.invOfUnit (f i) 1) (PowerSeries.invOfUnit F 1) := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + change TorusConverges v Ω l (fun i=>coeff n (PowerSeries.invOfUnit (f i) 1)) _ + have he := fun i=>coeff_inverse_one v Ω (f i) n + simp_rw [funext he] + rw [coeff_inverse_one] + by_cases hn : n=0 + · simp only [ite_eq_left hn] + exact torusConverges_const v Ω l 1 + · simp only [ite_eq_right hn] + apply TorusConverges.neg + apply TorusConverges.sum + intro p hp + by_cases hp2 : p.2hfg i p.1) (fun i=>(hfg i).inverse v Ω C p.2) + (hF p.1) (hF.inverse v Ω C p.2) + · simp only [ite_eq_right hp2] + exact torusConverges_const v Ω l 0 + +def completedInverse (F : CompletedPositive v Ω C) : CompletedPositive v Ω C := + ⟨PowerSeries.invOfUnit F.val 1, by simp, + SeriesGraded.inverse v Ω C F.property.2⟩ + +lemma completedInverse_mul (F : CompletedPositive v Ω C) : + (completedInverse v Ω C F).val*F.val=1 := + PowerSeries.invOfUnit_mul F.val 1 F.property.1 +lemma mul_completedInverse (F : CompletedPositive v Ω C) : + F.val*(completedInverse v Ω C F).val=1 := + PowerSeries.mul_invOfUnit F.val 1 F.property.1 + +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.PowerSeriesAdjoint +open PowerSeries +noncomputable section +variable {A : Type*} [Ring A] +def adjoint (F X : PowerSeries A) : PowerSeries A := F*X*invOfUnit F 1 +@[simp] lemma constant_adjoint (F X : PowerSeries A) (hF : constantCoeff F=1) : + constantCoeff (adjoint F X)=constantCoeff X := by simp [adjoint,hF] +lemma inverse_mul (F G : PowerSeries A) (hF : constantCoeff F=1) (hG : constantCoeff G=1) : + invOfUnit (F*G) 1=invOfUnit G 1*invOfUnit F 1 := by + have hh : F*G*(invOfUnit G 1*invOfUnit F 1)=1:=by + calc + _=F*(G*invOfUnit G 1)*invOfUnit F 1:=by simp only [mul_assoc] + _=1:=by rw [mul_invOfUnit G 1 hG,mul_one,mul_invOfUnit F 1 hF] + calc + _=invOfUnit (F*G) 1*(F*G*(invOfUnit G 1*invOfUnit F 1)):=by rw [hh,mul_one] + _=(invOfUnit (F*G) 1*(F*G))*(invOfUnit G 1*invOfUnit F 1):=by simp only [mul_assoc] + _=invOfUnit G 1*invOfUnit F 1:=by rw [invOfUnit_mul _ 1 (by simp [hF,hG]),one_mul] +lemma adjoint_mul (F G X : PowerSeries A) (hF : constantCoeff F=1) (hG : constantCoeff G=1) : + adjoint (F*G) X=adjoint F (adjoint G X) := by + simp only [adjoint,inverse_mul F G hF hG,mul_assoc] +lemma inverse_coeff_congr (F G : PowerSeries A) (N : ℕ) (h : ∀n≤N,coeff n F=coeff n G) : + ∀n≤N,coeff n (invOfUnit F 1)=coeff n (invOfUnit G 1) := by + intro n hn + induction n using Nat.strong_induction_on with + | h n ih => + rw [coeff_invOfUnit,coeff_invOfUnit] + split_ifs with h0 + · rfl + · congr 1 + apply Finset.sum_congr rfl + intro p hp + split_ifs with hpn + · rw [h p.1 (by have H:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp; omega),ih p.2 hpn (by omega)] + · rfl +lemma adjoint_coeff_congr (F G X Y : PowerSeries A) (N : ℕ) + (hFG : ∀n≤N,coeff n F=coeff n G) (hXY : ∀n≤N,coeff n X=coeff n Y) : + coeff N (adjoint F X)=coeff N (adjoint G Y) := by + apply FormalLog.mul_coeff_congr + · intro j hj + exact FormalLog.mul_coeff_congr F X G Y j (fun k hk=>hFG k (hk.trans hj)) (fun k hk=>hXY k (hk.trans hj)) + · exact inverse_coeff_congr F G N hFG +lemma coeff_mul_vanish_right (F U : PowerSeries A) (n : ℕ) (hU : ∀jhU k (hk.trans hj)),hU j hj,mul_zero] + rw [←map_sub,←adjoint_sub,adjoint,coeff_mul_vanish_left _ _ n hFU, + coeff_mul_vanish_right F _ n hU,hF,one_mul,constantCoeff_invOfUnit] + simp only [inv_one,Units.val_one,mul_one,map_sub] +end +end ElementaryPositivity.PowerSeriesAdjoint + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPathAction.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPathAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..a28fc412cdefc429ba6d8201b026af398b2bf983 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPathAction.lean @@ -0,0 +1,203 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PathOldTransport +import OAI.Combinatorics.Chromatic.Walls.GenericLineJoining + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +lemma comparisonWordAction_append {K M : Type*} [Field K] [AddCommGroup M] + (u : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) + (δ k : M →+ ℤ) (p : M) (hp : k p=1) (B : ℕ) + (l l' : List (ComparisonCrossing u Ω δ k B)) + (f : PowerSeries (FiberTorus u (complementOmega k Ω) (complementAlpha k p Ω))) : + comparisonWordAction u Ω hΩ δ k p hp B (l++l') f= + comparisonWordAction u Ω hΩ δ k p hp B l (comparisonWordAction u Ω hΩ δ k p hp B l' f) := by + simp only [comparisonWordAction,List.foldr_append] + +lemma comparisonWordAction_input_congr {K M : Type*} [Field K] [AddCommGroup M] + (u : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) + (δ k : M →+ ℤ) (p : M) (hp : k p=1) (B : ℕ) + (l : List (ComparisonCrossing u Ω δ k B)) + (f g : PowerSeries (FiberTorus u (complementOmega k Ω) (complementAlpha k p Ω))) + (N : ℕ) (hg : ∀n≤N,coeff n f=coeff n g) : + ∀n≤N,coeff n (comparisonWordAction u Ω hΩ δ k p hp B l f)= + coeff n (comparisonWordAction u Ω hΩ δ k p hp B l g) := by + induction l with + | nil=>exact hg + | cons c l ih=> + intro n hn + exact comparisonAction_input_congr u Ω hΩ δ k p hp B c _ _ n + (fun j hj=>ih j (hj.trans hn)) + +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +lemma actualPathWord_trans {a b c : Module.Dual ℝ E} + (p : GenericLinePath C e a b) (q : GenericLinePath C e b c) (N : ℕ) : + actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg (p.trans C e q) N= + actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg q N++ + actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p N := by + induction q with + | nil=>rfl + | append s q ih=> + simp only [GenericLinePath.trans,actualPathWord,ih,List.append_assoc] + +def actualPathAction {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) := + PowerSeries.mk (fun D=>coeff D + (comparisonWordAction LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p + (max 1 ((mutationSize Ω C pc+1)*D))) f)) + +lemma actualPathAction_coeff {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) + (D A : ℕ) (hA : 1≤A) (hDA : (mutationSize Ω C pc+1)*D≤A) : + coeff D (actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f)= + coeff D (comparisonWordAction LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p A) f) := by + simp only [actualPathAction,PowerSeries.coeff_mk] + exact (actualPathWord_refines Ω C coord hcoord pc e he S hS hcomp L hdeg p D + (max 1 ((mutationSize Ω C pc+1)*D)) A (le_max_left _ _) (le_max_right _ _) + (max_le hA hDA)).action _ _ _ _ _ _ _ _ f f (fun _ _=>rfl) D le_rfl + +include he hdeg in +theorem actualPathAction_loop {a : Module.Dual ℝ E} (p : GenericLinePath C e a a) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f=f := by + apply PowerSeries.ext + intro D + simp only [actualPathAction,PowerSeries.coeff_mk] + exact actualPath_rational_loop_coefficient Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p D f + +theorem actualPathAction_trans {a b c : Module.Dual ℝ E} + (p : GenericLinePath C e a b) (q : GenericLinePath C e b c) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg (p.trans C e q) f= + actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg q + (actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f) := by + apply PowerSeries.ext + intro D + let A:=max 1 ((mutationSize Ω C pc+1)*D) + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg _ _ D A + (le_max_left _ _) (le_max_right _ _),actualPathWord_trans,comparisonWordAction_append] + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg q _ D A + (le_max_left _ _) (le_max_right _ _)] + apply comparisonWordAction_input_congr _ _ _ _ _ _ _ _ _ _ _ D _ D le_rfl + intro n hn + exact (actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f n A + (le_max_left _ _) ((Nat.mul_le_mul_left _ hn).trans (le_max_right _ _))).symm +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +def GenericLineSegment.avoidsCut (s : GenericLineSegment C e) (z : E) : Prop := + ∀t,s.lo ≤ t → t ≤ s.hi → (s.offset+t • s.direction) z≠0 + +def GenericLinePath.avoidsCut {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) (z : E) : Prop := + match p with + | .nil _=>True + | .append s p=>s.avoidsCut C e z ∧ p.avoidsCut z + +def GenericLinePath.castEnds {a b a' b' : Module.Dual ℝ E} + (h0 : a=a') (h1 : b=b') (p : GenericLinePath C e a b) : GenericLinePath C e a' b' := + h0 ▸ h1 ▸ p +lemma GenericLinePath.avoidsCut_castEnds {a b a' b' : Module.Dual ℝ E} + (h0 : a=a') (h1 : b=b') (p : GenericLinePath C e a b) (z : E) : + (p.castEnds C e h0 h1).avoidsCut C e z ↔ p.avoidsCut C e z := by + subst a'; subst b'; rfl + +lemma GenericLinePath.avoidsCut_trans {a b c : Module.Dual ℝ E} + (p : GenericLinePath C e a b) (q : GenericLinePath C e b c) (z : E) + (hp : p.avoidsCut C e z) (hq : q.avoidsCut C e z) : + (p.trans C e q).avoidsCut C e z := by + induction q with + | nil=>exact hp + | append s q ih=>exact ⟨hq.1,ih hq.2⟩ + +lemma segment_avoidsCut_of_sign (s : GenericLineSegment C e) (z : E) + (H : (0(Ha N).join (HA N)) + let t:=segmentBetween C e h b HH HB (fun N=>(Hb N).join_reverse (HB N)) + have hs : s.avoidsCut C e z:=by + apply segment_avoidsCut_of_sign C e + simp only [s,segmentBetween_start,segmentBetween_finish] + rcases Hside with H|H + · exact Or.inl ⟨H.1,Hsign.1 H.1⟩ + · exact Or.inr ⟨H.1,Hsign.2 H.1⟩ + have ht : t.avoidsCut C e z:=by + apply segment_avoidsCut_of_sign C e + simp only [t,segmentBetween_start,segmentBetween_finish] + rcases Hside with H|H + · exact Or.inl ⟨Hsign.1 H.1,H.2⟩ + · exact Or.inr ⟨Hsign.2 H.1,H.2⟩ + let p:=(GenericLinePath.single C e s).castEnds C e + (segmentBetween_start C e a h HA HH _) (segmentBetween_finish C e a h HA HH _) + let q:=(GenericLinePath.single C e t).castEnds C e + (segmentBetween_start C e h b HH HB _) (segmentBetween_finish C e h b HH HB _) + have hp : p.avoidsCut C e z:=by + apply (GenericLinePath.avoidsCut_castEnds C e _ _ _ z).mpr + exact ⟨hs,True.intro⟩ + have hq : q.avoidsCut C e z:=by + apply (GenericLinePath.avoidsCut_castEnds C e _ _ _ z).mpr + exact ⟨ht,True.intro⟩ + exact ⟨p.trans C e q,p.avoidsCut_trans C e q z hp hq⟩ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPathIndependence.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPathIndependence.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c33efbcd270ac109d28900ab2fa2bdf9d5d72ce --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPathIndependence.lean @@ -0,0 +1,195 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CompletedPathAction + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +theorem actualPathAction_independent {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (p q : GenericLinePath C e a b) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f= + actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg q f := by + obtain ⟨r⟩:=generic_path_exists C e b a HB HA + have H1:=actualPathAction_loop Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + (p.trans C e r) f + have H2:=actualPathAction_loop Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + (r.trans C e q) (actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f) + rw [actualPathAction_trans] at H1 H2 + rw [H1] at H2 + exact H2.symm + +def completedTransport {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) := + actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + (Classical.choice (generic_path_exists C e a b HA HB)) + +lemma completedTransport_eq_path {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (p : GenericLinePath C e a b) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + completedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HB f= + actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f := by + exact actualPathAction_independent Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HB _ p f + +lemma completedTransport_self {a : Module.Dual ℝ E} + (HA : RegularCovector C e a) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + completedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HA f=f := by + exact actualPathAction_loop Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg _ f + +lemma completedTransport_trans {a b c : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) (HC : RegularCovector C e c) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + completedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HC f= + completedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HB HC + (completedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HB f) := by + let p:=Classical.choice (generic_path_exists C e a b HA HB) + let q:=Classical.choice (generic_path_exists C e b c HB HC) + rw [completedTransport_eq_path Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HC (p.trans C e q)] + exact actualPathAction_trans Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p q f +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (u : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (δ k : M →+ ℤ) (p : M) (hp : k p=1) (B : ℕ) +def comparisonWordHom (l : List (ComparisonCrossing u Ω δ k B)) : + PowerSeries (FiberTorus u (complementOmega k Ω) (complementAlpha k p Ω)) →+* + PowerSeries (FiberTorus u (complementOmega k Ω) (complementAlpha k p Ω)) := + l.foldr (fun c f=>(comparisonAction u Ω hΩ δ k p hp B c).comp f) (RingHom.id _) +lemma comparisonWordHom_apply (l : List (ComparisonCrossing u Ω δ k B)) + (f : PowerSeries (FiberTorus u (complementOmega k Ω) (complementAlpha k p Ω))) : + comparisonWordHom u Ω hΩ δ k p hp B l f=comparisonWordAction u Ω hΩ δ k p hp B l f := by + induction l with + | nil=>rfl + | cons c l ih=> + change comparisonAction u Ω hΩ δ k p hp B c (comparisonWordHom u Ω hΩ δ k p hp B l f)=_ + rw [ih] + rfl +end +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +local instance : AddCommMonoid (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω)) := + (FiberTorus.instRing LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω)).toAddCommMonoid + +def actualPathHom {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) : + PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω)) →+* + PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω)) where + toFun:=actualPathAction Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p + map_one':=by + apply PowerSeries.ext + intro D + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p 1 D + (max 1 ((mutationSize Ω C pc+1)*D)) (le_max_left _ _) (le_max_right _ _)] + rw [←comparisonWordHom_apply,map_one] + map_zero':=by + apply PowerSeries.ext + intro D + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p 0 D + (max 1 ((mutationSize Ω C pc+1)*D)) (le_max_left _ _) (le_max_right _ _)] + rw [←comparisonWordHom_apply,map_zero] + map_add':=by + intro f g + apply PowerSeries.ext + intro D + let A:=max 1 ((mutationSize Ω C pc+1)*D) + rw [map_add] + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p (f+g) D A + (le_max_left _ _) (le_max_right _ _)] + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f D A + (le_max_left _ _) (le_max_right _ _)] + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p g D A + (le_max_left _ _) (le_max_right _ _)] + simp only [←comparisonWordHom_apply,map_add] + map_mul':=by + intro f g + apply PowerSeries.ext + intro D + let A:=max 1 ((mutationSize Ω C pc+1)*D) + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p (f*g) D A + (le_max_left _ _) (le_max_right _ _)] + rw [←comparisonWordHom_apply,map_mul] + simp only [coeff_mul] + apply Finset.sum_congr rfl + intro ij hij + have H:=Finset.HasAntidiagonal.mem_antidiagonal.mp hij + have hi : ij.1≤D:=by omega + have hj : ij.2≤D:=by omega + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p f ij.1 A + (le_max_left _ _) ((Nat.mul_le_mul_left _ hi).trans (le_max_right _ _))] + rw [actualPathAction_coeff Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p g ij.2 A + (le_max_left _ _) ((Nat.mul_le_mul_left _ hj).trans (le_max_right _ _))] + simp only [comparisonWordHom_apply] +end + +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +def completedTransportEquiv {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) : + PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω)) ≃+* + PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω)) where + toFun:=completedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HB + invFun:=completedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HB HA + left_inv:=by + intro f + rw [←completedTransport_trans,completedTransport_self] + right_inv:=by + intro f + rw [←completedTransport_trans,completedTransport_self] + map_mul':=(actualPathHom Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + (Classical.choice (generic_path_exists C e a b HA HB))).map_mul + map_add':=(actualPathHom Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + (Classical.choice (generic_path_exists C e a b HA HB))).map_add +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPureComparison.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPureComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..114a09346ddfab82de369a8f100d6cbfc5d3fb2f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CompletedPureComparison.lean @@ -0,0 +1,214 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentPureAction + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +def completedPureUnit : (PowerSeries (HahnSeries ℤ (Torus v Ω)))ˣ := + Units.map (PowerSeries.C (R:=HahnSeries ℤ (Torus v Ω))) (pureLaurentUnit v Ω hΩ p) +lemma completed_expand_pure + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + PowerSeries.map (expandFiber v Ω hΩ k p) (completedPureAction v _ _ f)= + innerHom (completedPureUnit v Ω hΩ p) (PowerSeries.map (expandFiber v Ω hΩ k p) f) := by + apply PowerSeries.ext + intro d + change expandFiber v Ω hΩ k p + (coeff d (completedPureAction v (complementOmega k Ω) (complementAlpha k p Ω) f))= + coeff d (PowerSeries.C (↑(pureLaurentUnit v Ω hΩ p):HahnSeries ℤ (Torus v Ω))* + PowerSeries.map (expandFiber v Ω hΩ k p) f* + PowerSeries.C (↑((pureLaurentUnit v Ω hΩ p)⁻¹):HahnSeries ℤ (Torus v Ω))) + change expandFiber v Ω hΩ k p + (coeff d (PowerSeries.map (pureAction v (complementOmega k Ω) (complementAlpha k p Ω)).toRingHom f))=_ + rw [coeff_map,coeff_mul_C,coeff_C_mul,coeff_map] + exact expand_pure_conjugate v Ω hΩ p k hq (coeff d f) +lemma innerHom_one {A : Type*} [Ring A] (a : A) : innerHom (1:Aˣ) a=a := by + simp [innerHom] +lemma innerHom_mul {A : Type*} [Ring A] (u w : Aˣ) (a : A) : + innerHom (u*w) a=innerHom u (innerHom w a) := by + simp [innerHom,mul_assoc] +lemma innerHom_inv_cancel {A : Type*} [Ring A] (u : Aˣ) (a : A) : + innerHom u⁻¹ (innerHom u a)=a := by + rw [←innerHom_mul,inv_mul_cancel,innerHom_one] +lemma innerHom_cancel_inv {A : Type*} [Ring A] (u : Aˣ) (a : A) : + innerHom u (innerHom u⁻¹ a)=a := by + rw [←innerHom_mul,mul_inv_cancel,innerHom_one] +lemma completed_expand_pure_inverse + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + PowerSeries.map (expandFiber v Ω hΩ k p) ((completedPureAction v _ _).symm f)= + innerHom (completedPureUnit v Ω hΩ p)⁻¹ (PowerSeries.map (expandFiber v Ω hΩ k p) f) := by + have H:=completed_expand_pure v Ω hΩ k p hq ((completedPureAction v _ _).symm f) + rw [RingEquiv.apply_symm_apply] at H + have HH:=congrArg (innerHom (completedPureUnit v Ω hΩ p)⁻¹) H + rw [innerHom_inv_cancel] at HH + exact HH.symm +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (δ k : M →+ ℤ) (p : M) (hp : k p=1) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +def oldUnitExpand (u : (biSupportedSubring v Ω δ k)ˣ) : + (PowerSeries (HahnSeries ℤ (Torus v Ω)))ˣ := + Units.map (oldLaurentHom v Ω δ k) u + +def boundedRationalUnit (B : ℕ) (u : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hg : RegradeBound v Ω δ B u.inv.val) : + (PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)))ˣ where + val:=rationalRegrade v Ω hΩ k p hp δ B u.val.val + inv:=rationalRegrade v Ω hΩ k p hp δ B u.inv.val + val_inv:=by + rw [←rationalRegrade_mul v Ω hΩ k p hp δ B hf hg] + have H:=congrArg (fun a : biSupportedSubring v Ω δ k=>a.val) u.val_inv + change u.val.val*u.inv.val=1 at H + rw [H,rationalRegrade_one] + inv_val:=by + rw [←rationalRegrade_mul v Ω hΩ k p hp δ B hg hf] + have H:=congrArg (fun a : biSupportedSubring v Ω δ k=>a.val) u.inv_val + change u.inv.val*u.val.val=1 at H + rw [H,rationalRegrade_one] +lemma boundedUnit_expansion (B : ℕ) (u : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hg : RegradeBound v Ω δ B u.inv.val) : + Units.map (PowerSeries.map (expandFiber v Ω hΩ k p)) + (boundedRationalUnit v Ω hΩ δ k p hp B u hf hg)=oldUnitExpand v Ω δ k u := by + apply Units.ext + change PowerSeries.map (expandFiber v Ω hΩ k p) + (rationalRegrade v Ω hΩ k p hp δ B u.val.val)=oldLaurent v Ω δ k u.val.val + exact rational_old_square v Ω hΩ k p hp δ B u.val.property hf + +variable (hδ : δ p=0) +def oldPureUnit : (biSupportedSubring v Ω δ k)ˣ where + val:=⟨raySeries v Ω p (shiftedElementary v 0),pure_biSupported v Ω δ k p hδ hp _⟩ + inv:=⟨raySeries v Ω p (shiftedElementary v 0)⁻¹,pure_biSupported v Ω δ k p hδ hp _⟩ + val_inv:=Subtype.ext (rayUnit v Ω p (hΩ p) _ (shiftedElementary_constant v 0)).val_inv + inv_val:=Subtype.ext (rayUnit v Ω p (hΩ p) _ (shiftedElementary_constant v 0)).inv_val +lemma oldPureUnit_expansion : + oldUnitExpand v Ω δ k (oldPureUnit v Ω hΩ δ k p hp hδ)=completedPureUnit v Ω hΩ p := by + apply Units.ext + exact oldLaurent_pure v Ω hΩ δ k p hδ hp _ +lemma map_innerHom {A B : Type*} [Ring A] [Ring B] (F : A →+* B) (u : Aˣ) (x : A) : + F (innerHom u x)=innerHom (Units.map F u) (F x) := by + simp [innerHom] +lemma bounded_conjugation_expansion (B : ℕ) (u : (biSupportedSubring v Ω δ k)ˣ) + (hf : RegradeBound v Ω δ B u.val.val) (hg : RegradeBound v Ω δ B u.inv.val) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + PowerSeries.map (expandFiber v Ω hΩ k p) + (innerHom (boundedRationalUnit v Ω hΩ δ k p hp B u hf hg) f)= + innerHom (oldUnitExpand v Ω δ k u) (PowerSeries.map (expandFiber v Ω hΩ k p) f) := by + rw [map_innerHom,boundedUnit_expansion] +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries HahnSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (δ k : M →+ ℤ) (p : M) (hp : k p=1) (hδ : δ p=0) (B : ℕ) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +inductive ComparisonCrossing where + | bounded (u : (biSupportedSubring v Ω δ k)ˣ) + (forward_bound : RegradeBound v Ω δ B u.val.val) + (inverse_bound : RegradeBound v Ω δ B u.inv.val) + | pure (forward : Bool) + +def comparisonOld : ComparisonCrossing v Ω δ k B → (biSupportedSubring v Ω δ k)ˣ + | .bounded u _ _=>u + | .pure true=>oldPureUnit v Ω hΩ δ k p hp hδ + | .pure false=>(oldPureUnit v Ω hΩ δ k p hp hδ)⁻¹ + +def comparisonAction (c : ComparisonCrossing v Ω δ k B) : + PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) →+* + PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) := + match c with + | .bounded u hf hg=>innerHom (boundedRationalUnit v Ω hΩ δ k p hp B u hf hg) + | .pure true=>(completedPureAction v _ _).toRingHom + | .pure false=>(completedPureAction v _ _).symm.toRingHom +lemma comparison_expansion (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (c : ComparisonCrossing v Ω δ k B) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + PowerSeries.map (expandFiber v Ω hΩ k p) (comparisonAction v Ω hΩ δ k p hp B c f)= + innerHom (oldUnitExpand v Ω δ k (comparisonOld v Ω hΩ δ k p hp hδ B c)) + (PowerSeries.map (expandFiber v Ω hΩ k p) f) := by + cases c with + | bounded u hf hg=>exact bounded_conjugation_expansion v Ω hΩ δ k p hp B u hf hg f + | pure b=> + cases b + · change _=innerHom (oldUnitExpand v Ω δ k (oldPureUnit v Ω hΩ δ k p hp hδ)⁻¹) _ + have H : oldUnitExpand v Ω δ k (oldPureUnit v Ω hΩ δ k p hp hδ)⁻¹= + (completedPureUnit v Ω hΩ p)⁻¹ := by + rw [oldUnitExpand,map_inv,←oldPureUnit_expansion v Ω hΩ δ k p hp hδ] + rfl + rw [H] + exact completed_expand_pure_inverse v Ω hΩ k p hq f + · change _=innerHom (oldUnitExpand v Ω δ k (oldPureUnit v Ω hΩ δ k p hp hδ)) _ + rw [oldPureUnit_expansion] + exact completed_expand_pure v Ω hΩ k p hq f + +def comparisonWordOld (l : List (ComparisonCrossing v Ω δ k B)) : + (biSupportedSubring v Ω δ k)ˣ := (l.map (comparisonOld v Ω hΩ δ k p hp hδ B)).prod + +def comparisonWordAction (l : List (ComparisonCrossing v Ω δ k B)) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) := + l.foldr (fun c a=>comparisonAction v Ω hΩ δ k p hp B c a) f +lemma comparisonWord_expansion (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (l : List (ComparisonCrossing v Ω δ k B)) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + PowerSeries.map (expandFiber v Ω hΩ k p) (comparisonWordAction v Ω hΩ δ k p hp B l f)= + innerHom (oldUnitExpand v Ω δ k (comparisonWordOld v Ω hΩ δ k p hp hδ B l)) + (PowerSeries.map (expandFiber v Ω hΩ k p) f) := by + induction l with + | nil=>simp [comparisonWordAction,comparisonWordOld,oldUnitExpand,innerHom_one] + | cons c l ih=> + change PowerSeries.map (expandFiber v Ω hΩ k p) + (comparisonAction v Ω hΩ δ k p hp B c (comparisonWordAction v Ω hΩ δ k p hp B l f))=_ + rw [comparison_expansion v Ω hΩ δ k p hp hδ B hq,ih] + change _=innerHom (oldUnitExpand v Ω δ k + (comparisonOld v Ω hΩ δ k p hp hδ B c*comparisonWordOld v Ω hΩ δ k p hp hδ B l)) _ + simp only [oldUnitExpand,map_mul,innerHom_mul] + +lemma comparisonWord_loop (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (l : List (ComparisonCrossing v Ω δ k B)) + (hloop : comparisonWordOld v Ω hΩ δ k p hp hδ B l=1) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + comparisonWordAction v Ω hΩ δ k p hp B l f=f := by + apply completed_expandFiber_injective v Ω hΩ k p hp + rw [comparisonWord_expansion v Ω hΩ δ k p hp hδ B hq,hloop,oldUnitExpand,map_one,innerHom_one] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CoproductSymbol.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CoproductSymbol.lean new file mode 100644 index 0000000000000000000000000000000000000000..b890dec2b5bc9be663431fff8e17ce87621f2eca --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CoproductSymbol.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RefinedTensorDetection + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open ElementaryPositivity.CenterCalculus ElementaryPositivity.ShufflePolynomiality +open ElementaryPositivity.LaurentAtInfinity SeparationInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +lemma centerNumerator_crossPairs_line (a : I → I → ℕ) (L R : SplitTree I) + (v : L.Centers → ℚ) (w : R.Centers → ℚ) : + lineSpecialization (Sum.elim v w) (Sum.elim (fun _=>1) (fun _=>0)) + (centerNumerator a (L.node R) (crossPairs L R))= + crossPolynomial a L R v w Int.toNat := by + classical + unfold centerNumerator crossPairs + rw [Finset.prod_image (fun p _ q _ h=>crossPairs_injective L R h)] + simp only [map_prod,map_pow] + rw [Fintype.prod_prod_type] + unfold crossPolynomial + apply Finset.prod_congr rfl + intro z hz + apply Finset.prod_congr rfl + intro t ht + congr 1 + simp only [diagonal,map_sub,lineSpecialization_X,Sum.elim_inl,Sum.elim_inr, + _root_.map_zero,_root_.map_one,zero_mul,one_mul,add_zero,Algebra.algebraMap_self_apply, + affinePolynomial] + ring + +lemma refined_leading_zero_factor (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 rfl + have h:=refined_leading_separation_formula a c η hc θ L R hL hR + (v ∘ Sum.inl) (v ∘ Sum.inr) W f hf + rw [hq,map_mul,lineSpecialization_map_algebra,centerDenominator_crossPairs_line, + map_mul,←polynomial_map,←mul_assoc,←map_mul,scalarCrossKernel_denominator, + polynomial_map] at h + have hh:=congrArg (fun x : LaurentSeries (tensor (quotientFamily a (SlopeArithmetic.slope c η)) (.node L R))=>x.coeff (-(0:ℤ))) h + rw [LaurentAtInfinity.mapLinear_coeff,mapRing_coeff,←map_mul] at hh + simp only [neg_zero] at hh + rw [show ∀ p : Polynomial (tensor (quotientFamily a (SlopeArithmetic.slope c η)) (.node L R)), + (polynomial p).coeff 0=p.coeff 0 from fun p=>by simpa using polynomial_coeff p 0, + Polynomial.mul_coeff_zero,Polynomial.coeff_map, + ←centerNumerator_crossPairs_line,lineSpecialization_coeff_zero, + lineSpecialization_coeff_zero,hv] at hh + rw [evalRat_mapLinear,refinedCenterPolynomial_eval,map_mul,evalRat_map_algebra_eq] + exact hh + +theorem coproductSymbol_cross_cleared (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0even (e a))) : CountSelection even := + ⟨f.val.embDomain e,by + intro b hb + by_cases H : b∈Set.range e + · obtain ⟨a,rfl⟩:=H + rw [Finsupp.embDomain_apply_self] + exact f.property a hb + · rw [Finsupp.embDomain_of_notMem_range _ _ _ H] + exact Nat.zero_le _⟩ + +lemma embedCount_injective : Function.Injective (embedCount e even) := by + intro f g H + apply Subtype.ext + exact Finsupp.embDomain_injective e (congrArg Subtype.val H) + +lemma embedCount_support (f : CountSelection (fun a=>even (e a))) : + ↑(embedCount e even f).val.support ⊆ Set.range e := by + intro b hb + by_contra H + exact Finsupp.mem_support_iff.mp hb (Finsupp.embDomain_of_notMem_range _ _ _ H) + +lemma embedCount_sum {T : Type*} [AddCommMonoid T] (f : CountSelection (fun a=>even (e a))) + (k : B → T) : + (embedCount e even f).val.sum (fun b n=>n • k b)=f.val.sum (fun a n=>n • k (e a)) := by + exact Finsupp.sum_embDomain + +def restrictCount (f : CountSelection even) : CountSelection (fun a=>even (e a)) := + ⟨f.val.comapDomain e e.injective.injOn,fun a ha=>f.property (e a) ha⟩ + +def countSupportEquiv : CountSelection (fun a=>even (e a)) ≃ + {f : CountSelection even // ↑f.val.support ⊆ Set.range e} where + toFun f:=⟨embedCount e even f,embedCount_support e even f⟩ + invFun f:=restrictCount e even f.val + left_inv f:=by + apply Subtype.ext + exact Finsupp.comapDomain_embDomain e f.val + right_inv f:=by + apply Subtype.ext + apply Subtype.ext + exact Finsupp.embDomain_comapDomain f.property + +variable {I : Type*} (dim : B → (I→ℕ)) + +def dimensionSupportEquiv (d : I→ℕ) : + DimensionCounts (fun a=>even (e a)) (fun a=>dim (e a)) d ≃ + {f : DimensionCounts even dim d // ↑f.val.val.support ⊆ Set.range e} where + toFun f:=⟨⟨embedCount e even f.val,by + change (embedCount e even f.val).val.sum _=d + rw [embedCount_sum] + exact f.property⟩,embedCount_support e even f.val⟩ + invFun f:=⟨restrictCount e even f.val.val,by + have H:=embedCount_sum e even (restrictCount e even f.val.val) dim + have HE : embedCount e even (restrictCount e even f.val.val)=f.val.val := + Subtype.ext (Finsupp.embDomain_comapDomain f.property) + rw [HE] at H + exact H.symm.trans f.val.property⟩ + left_inv f:=by + apply Subtype.ext + exact (countSupportEquiv e even).symm_apply_apply f.val + right_inv f:=by + apply Subtype.ext + apply Subtype.ext + exact Subtype.ext (Finsupp.embDomain_comapDomain f.property) + +lemma dimensionSupport_energy (k : B → ℤ) (d : I→ℕ) + (f : DimensionCounts (fun a=>even (e a)) (fun a=>dim (e a)) d) : + countEnergy even k (dimensionSupportEquiv e even dim d f).val.val= + countEnergy (fun a=>even (e a)) (fun a=>k (e a)) f.val := + embedCount_sum e even f.val k +end +end ElementaryPositivity.SignedMultiplicity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/CountSumDimension.lean b/lean/OAI/Combinatorics/Chromatic/Walls/CountSumDimension.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a1c07158a955ebe23d03b4a43cea1e99bd8d247 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/CountSumDimension.lean @@ -0,0 +1,119 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNThreshold +import OAI.Combinatorics.Chromatic.QuantumTorus.StringStripDimension + +namespace OAI + +section +namespace ElementaryPositivity.SignedMultiplicity +open RawShuffle EnergyLaurent +noncomputable section +variable {A B I : Type*} [Fintype I] [DecidableEq I] +variable (ea : A → Prop) (eb : B → Prop) (da : A → (I→ℕ)) (db : B → (I→ℕ)) +variable (ka : A → ℤ) (kb : B → ℤ) + +def countSumDimensionEquiv (d : I→ℕ) : + DimensionCounts (Sum.elim ea eb) (Sum.elim da db) d ≃ + Σs : DimensionSplit d,DimensionCounts ea da s.left × DimensionCounts eb db s.right := + ((countSumEquiv ea eb).subtypeEquiv (fun x=>by + change countDimension _ _ x=d ↔ _ + rw [countDimension,countSum_sum] + rfl)).trans (dimensionProduct (countDimension ea da) (countDimension eb db) d).symm + +omit [Fintype I] [DecidableEq I] in +lemma countSumDimension_energy (d : I→ℕ) + (f : DimensionCounts (Sum.elim ea eb) (Sum.elim da db) d) : + countEnergy (Sum.elim ea eb) (Sum.elim ka kb) f.val= + countEnergy ea ka (countSumDimensionEquiv ea eb da db d f).2.1.val+ + countEnergy eb kb (countSumDimensionEquiv ea eb da db d f).2.2.val := + countSum_sum ea eb f.val (Sum.elim ka kb) + +variable (ha : ∀d,Admissible (fun f : DimensionCounts ea da d=>countEnergy ea ka f.val)) +variable (hb : ∀d,Admissible (fun f : DimensionCounts eb db d=>countEnergy eb kb f.val)) + +include ha hb in +lemma countSum_admissible (d : I→ℕ) : + Admissible (fun f : DimensionCounts (Sum.elim ea eb) (Sum.elim da db) d=> + countEnergy (Sum.elim ea eb) (Sum.elim ka kb) f.val) := by + let k (s : DimensionSplit d) (f : DimensionCounts ea da s.left × DimensionCounts eb db s.right) := + countEnergy ea ka f.1.val+countEnergy eb kb f.2.val + exact admissible_injective (admissible_sigma k (fun s=>admissible_prod (ha s.left) (hb s.right))) + (countSumDimensionEquiv ea eb da db d) (countSumDimensionEquiv ea eb da db d).injective + (fun f=>(countSumDimension_energy ea eb da db ka kb d f).symm) + +lemma countSum_series (d : I→ℕ) : + series _ (countSum_admissible ea eb da db ka kb ha hb d)= + ∑s : DimensionSplit d,series _ (ha s.left)*series _ (hb s.right) := by + let k (s : DimensionSplit d) (f : DimensionCounts ea da s.left × DimensionCounts eb db s.right) := + countEnergy ea ka f.1.val+countEnergy eb kb f.2.val + rw [series_equiv _ (admissible_sigma k (fun s=>admissible_prod (ha s.left) (hb s.right))) + (countSumDimensionEquiv ea eb da db d) (fun f=>(countSumDimension_energy ea eb da db ka kb d f).symm), + series_sigma] + apply Finset.sum_congr rfl + intro s hs + exact (series_mul (ha s.left) (hb s.right)).symm +end +end ElementaryPositivity.SignedMultiplicity + +end +section +namespace ElementaryPositivity.SignedMultiplicity +open EnergyLaurent +noncomputable section +variable {A B I : Type*} (e : A ≃ B) (even : B→Prop) (dim : B→(I→ℕ)) (k : B→ℤ) + +def dimensionReindex (d : I→ℕ) : DimensionCounts (fun a=>even (e a)) (fun a=>dim (e a)) d ≃ + DimensionCounts even dim d := + (countReindex e _ _ (fun _=>Iff.rfl)).subtypeEquiv (fun f=>by + change f.val.sum (fun a n=>n • dim (e a))=d ↔ _ + change _ ↔ (countReindex e _ _ (fun _=>Iff.rfl) f).val.sum (fun b n=>n • dim b)=d + rw [countReindex_sum]) + +lemma dimensionReindex_energy (d : I→ℕ) + (f : DimensionCounts (fun a=>even (e a)) (fun a=>dim (e a)) d) : + countEnergy even k (dimensionReindex e even dim d f).val= + countEnergy (fun a=>even (e a)) (fun a=>k (e a)) f.val := + countReindex_sum e _ _ (fun _=>Iff.rfl) f.val k + +variable (he : ∀d,Admissible (fun f : DimensionCounts even dim d=>countEnergy even k f.val)) +include he in +lemma dimensionReindex_admissible (d : I→ℕ) : + Admissible (fun f : DimensionCounts (fun a=>even (e a)) (fun a=>dim (e a)) d=> + countEnergy _ (fun a=>k (e a)) f.val) := + admissible_injective (he d) (dimensionReindex e even dim d) + (dimensionReindex e even dim d).injective (dimensionReindex_energy e even dim k d) + +lemma dimensionReindex_series (d : I→ℕ) : + series _ (dimensionReindex_admissible e even dim k he d)=series _ (he d) := + series_equiv _ _ (dimensionReindex e even dim d) (dimensionReindex_energy e even dim k d) +end +end ElementaryPositivity.SignedMultiplicity + +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity EnergyLaurent +noncomputable section +variable {S T I : Type*} (e : S ≃ T) (a : T→ℕ) (dim : T→(I→ℕ)) (k : T→ℤ) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) + +def stringReindex (d : I→ℕ) : + StringCounts (fun s=>a (e s)) (fun s=>dim (e s)) d ≃ StringCounts a dim d := + dimensionReindex (Equiv.prodCongr e (Equiv.refl ℕ)) (fun x=>a x.1≠0) (fun x=>dim x.1) d + +lemma stringReindex_energy (d : I→ℕ) + (f : StringCounts (fun s=>a (e s)) (fun s=>dim (e s)) d) : + stringEnergy a dim k d (stringReindex e a dim d f)= + stringEnergy (fun s=>a (e s)) (fun s=>dim (e s)) (fun s=>k (e s)) d f := + dimensionReindex_energy (Equiv.prodCongr e (Equiv.refl ℕ)) + (fun x=>a x.1≠0) (fun x=>dim x.1) (fun x=>k x.1-2*(x.2:ℤ)) d f + +include he in +lemma stringReindex_admissible (d : I→ℕ) : + Admissible (stringEnergy (fun s=>a (e s)) (fun s=>dim (e s)) (fun s=>k (e s)) d) := + admissible_injective (he d) (stringReindex e a dim d) (stringReindex e a dim d).injective + (stringReindex_energy e a dim k d) +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/DegreeIsolatedReordering.lean b/lean/OAI/Combinatorics/Chromatic/Walls/DegreeIsolatedReordering.lean new file mode 100644 index 0000000000000000000000000000000000000000..17bd72300290f6046fc5c2fa4a6e84d67ce7b856 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/DegreeIsolatedReordering.lean @@ -0,0 +1,96 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RootTruncation + +namespace OAI + +section +namespace ElementaryPositivity +namespace RootTruncation +open PowerSeries +noncomputable section +variable {A : Type*} [Ring A] +def patchTop (n : ℕ) (G F : PowerSeries A) : PowerSeries A := + PowerSeries.mk (fun j=>if j≤n then coeff j G else if j=n+1 then coeff j F else 0) +@[simp] lemma coeff_patchTop (n j : ℕ) (G F : PowerSeries A) : + coeff j (patchTop n G F)=if j≤n then coeff j G else if j=n+1 then coeff j F else 0 := + coeff_mk _ _ +lemma patchTop_low (n : ℕ) (G F : PowerSeries A) (j : ℕ) (hj : j≤n) : + coeff j (patchTop n G F)=coeff j G := by simp [hj] +@[simp] lemma patchTop_last (n : ℕ) (G F : PowerSeries A) : + coeff (n+1) (patchTop n G F)=coeff (n+1) F := by simp +@[simp] lemma patchTop_constant (n : ℕ) (G F : PowerSeries A) : + constantCoeff (patchTop n G F)=constantCoeff G := by + rw [←coeff_zero_eq_constantCoeff,patchTop_low n G F 0 (Nat.zero_le _),coeff_zero_eq_constantCoeff] +end +end RootTruncation +namespace QuantumTorus +open PowerSeries PowerSeriesSplit RootTruncation LaurentPrecision Filter +noncomputable section +variable {M I A J : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) +lemma SeriesConverges.zero_middle (l : Filter J) (h : M→+ℝ) + {f : J→PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) (hg : ∀i,SeriesGraded v Ω C (f i)) + (hF : SeriesGraded v Ω C F) : + SeriesConverges v Ω l + (fun j=>zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) (f j)) + (zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) F) := by + have H:=filter_factors_converge v Ω C l (fun m=>0h m=0) H.2 + (fun j n=>by simpa only [rightFactor,coeff_mk] using (filter_pair_graded v Ω C (fun m=>0by simpa only [rightFactor,coeff_mk] using (filter_pair_graded v Ω C (fun m=>0RootTruncation.cut n (g j)) (RootTruncation.cut n F)) : + SeriesConverges v Ω l (fun j=>patchTop n (g j) F) (RootTruncation.cut (n+1) F) := by + intro k + simp only [coeff_patchTop,coeff_cut] + by_cases hk : k≤n + · simp only [hk,ite_true,show k≤n+1 by omega] + simpa only [coeff_cut,hk,ite_true] using hg k + · by_cases he : k=n+1 + · simp only [he,Nat.not_succ_le_self,ite_false,ite_true,le_refl] + exact torusConverges_const v Ω l _ + · simp only [hk,he,ite_false,show ¬k≤n+1 by omega] + exact torusConverges_const v Ω l _ +lemma zero_middle_off (h : M→+ℝ) (F : PowerSeries (Torus v Ω)) (n : ℕ) (m : M) (hm : h m≠0) : + coeff (n+1) (zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) F) m=0 := by + simp only [zeroFactor,leftFactor,coeff_mk] + rw [pairCoefficients] + exact Finsupp.filter_apply_neg _ _ hm + +lemma joint_middle_isolated_through (h : M→+ℝ) (l : List A) + (f g : A→PowerSeries (Torus v Ω)) (n : ℕ) + (hf : ∀a∈l,constantCoeff (f a)=1) (hg : ∀a∈l,constantCoeff (g a)=1) + (hlow : ∀a∈l,∀k≤n,coeff k (f a)=coeff k (g a)) + (hlast : ∀a∈l,∀m,h m=0 → coeff (n+1) (f a) m=coeff (n+1) (g a) m) : + RootTruncation.cut (n+1) (zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) (l.map f).prod)= + RootTruncation.cut (n+1) (zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) (l.map g).prod) := by + apply cut_congr + intro k hk + by_cases hkn : k≤n + · exact zero_coeff_congr _ _ _ _ k (fun j hj=>product_coeff_congr f g l j + (fun a ha i hi=>hlow a ha i (hi.trans (hj.trans hkn)))) + · have he : k=n+1:=by omega + subst k + apply Finsupp.ext + intro m + by_cases hm : h m=0 + · exact joint_middle_monomial_unaffected v Ω h f g l n m hf hg hlow (fun a ha=>hlast a ha m hm) + · rw [zero_middle_off v Ω h _ n m hm,zero_middle_off v Ω h _ n m hm] +end +end QuantumTorus +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/DirectSumBilinear.lean b/lean/OAI/Combinatorics/Chromatic/Walls/DirectSumBilinear.lean new file mode 100644 index 0000000000000000000000000000000000000000..a99a386bf352e0507e98d9666ebce053cfe89dd3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/DirectSumBilinear.lean @@ -0,0 +1,41 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +open scoped DirectSum +variable {ι κ : Type*} [DecidableEq ι] [DecidableEq κ] +variable (M : ι → Type*) (N : κ → Type*) +variable [∀ i,AddCommGroup (M i)] [∀ i,Module ℚ (M i)] +variable [∀ j,AddCommGroup (N j)] [∀ j,Module ℚ (N j)] +variable (P : Type*) [AddCommGroup P] [Module ℚ P] + +noncomputable def directSumBilinear (f : ∀ i j,M i →ₗ[ℚ] N j →ₗ[ℚ] P) : + (⨁ i,M i) →ₗ[ℚ] (⨁ j,N j) →ₗ[ℚ] P := + DirectSum.toModule ℚ ι ((⨁ j,N j) →ₗ[ℚ] P) (fun i=> + { toFun := fun x=>DirectSum.toModule ℚ κ P (fun j=>f i j x) + map_add' := by + intro x y + apply DirectSum.linearMap_ext + intro j + ext z + simp only [LinearMap.comp_apply,DirectSum.toModule_lof,LinearMap.add_apply,map_add] + map_smul' := by + intro r x + apply DirectSum.linearMap_ext + intro j + ext z + simp only [LinearMap.comp_apply,DirectSum.toModule_lof,LinearMap.smul_apply,map_smul] + rfl }) + +lemma directSumBilinear_lof (f : ∀ i j,M i →ₗ[ℚ] N j →ₗ[ℚ] P) + (i : ι) (j : κ) (x : M i) (y : N j) : + directSumBilinear M N P f (DirectSum.lof ℚ ι M i x) (DirectSum.lof ℚ κ N j y)=f i j x y := by + simp only [directSumBilinear,DirectSum.toModule_lof,LinearMap.coe_mk,AddHom.coe_mk] + +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/DirectSumSubtype.lean b/lean/OAI/Combinatorics/Chromatic/Walls/DirectSumSubtype.lean new file mode 100644 index 0000000000000000000000000000000000000000..57aaa4bbbe8b18b4742fad9d6fb4fa458d01f792 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/DirectSumSubtype.lean @@ -0,0 +1,54 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +open scoped DirectSum +universe u v +variable {K : Type u} [DecidableEq K] (M : K → Type v) [∀ k,AddCommGroup (M k)] [∀ k,Module ℚ (M k)] + (p : K → Prop) +attribute [local instance] Classical.propDecidable + +noncomputable def subfamilyInclusion : (⨁ k : {k // p k},M k.val) →ₗ[ℚ] ⨁ k,M k := + DirectSum.toModule ℚ _ _ (fun k=>DirectSum.lof ℚ K M k.val) + +lemma subfamilyInclusion_lof (k : {k // p k}) (x : M k.val) : + subfamilyInclusion M p (DirectSum.lof ℚ _ (fun k : {k // p k}=>M k.val) k x)= + DirectSum.lof ℚ K M k.val x := by + simp [subfamilyInclusion] + +lemma component_subfamilyInclusion (k : {k // p k}) (x : ⨁ k : {k // p k},M k.val) : + DirectSum.component ℚ K M k.val (subfamilyInclusion M p x)= + DirectSum.component ℚ _ (fun k : {k // p k}=>M k.val) k x := by + induction x using DirectSum.induction_on with + | zero => simp only [map_zero] + | add x y hx hy => simp only [map_add,hx,hy] + | of j x => + change DirectSum.component ℚ K M k.val (subfamilyInclusion M p + (DirectSum.lof ℚ _ (fun k : {k // p k}=>M k.val) j x))= + DirectSum.component ℚ _ (fun k : {k // p k}=>M k.val) k + (DirectSum.lof ℚ _ (fun k : {k // p k}=>M k.val) j x) + rw [subfamilyInclusion_lof] + by_cases h : j=k + · subst j; simp + · rw [DirectSum.component.of,DirectSum.component.of] + simp only [dite_eq_right (fun he=>h (Subtype.ext he)),dite_eq_right h] + +lemma subfamilyInclusion_injective : Function.Injective (subfamilyInclusion M p) := by + intro x y h + apply DirectSum.ext_component ℚ + intro k + rw [←component_subfamilyInclusion M p,←component_subfamilyInclusion M p,h] + +lemma directSum_map_independent {J : K → Type*} (f : ∀ k,J k → M k) + (hf : ∀ k,LinearIndependent ℚ (f k)) {V : Type*} [AddCommGroup V] [Module ℚ V] + (L : (⨁ k,M k) →ₗ[ℚ] V) (hL : Function.Injective L) : + LinearIndependent ℚ (fun i : Σ k,J k=>L (DirectSum.lof ℚ K M i.1 (f i.1 i.2))) := by + exact (DFinsupp.linearIndependent_single f hf).map' L ((LinearMap.ker_eq_bot).mpr hL) + +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/ElementaryMatrixDuality.lean b/lean/OAI/Combinatorics/Chromatic/Walls/ElementaryMatrixDuality.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d64cca94a90411b4824ee0a2a5f5174a111b547 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/ElementaryMatrixDuality.lean @@ -0,0 +1,92 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.ElementaryMatrix +open scoped BigOperators +open Classical +noncomputable section +variable {A B:Type*} [Fintype A] [Fintype B] [DecidableEq A] [DecidableEq B] + +def transpose (s:B → Finset A) : A → Finset B:=fun a=>Finset.univ.filter (fun b=>a∈s b) +lemma transpose_transpose (s:B → Finset A) : transpose (transpose s)=s := by + funext b + ext a + simp [transpose] +def transposeEquiv : (B → Finset A) ≃ (A → Finset B) where + toFun:=transpose + invFun:=transpose + left_inv:=transpose_transpose + right_inv:=transpose_transpose + +def rowCount (s:B → Finset A) : B →₀ ℕ:=Finsupp.equivFunOnFinite.symm (fun b=>(s b).card) +def colCount (s:B → Finset A) : A →₀ ℕ:=∑b,∑a∈s b,Finsupp.single a 1 +omit [Fintype A] [DecidableEq B] in +lemma colCount_apply (s:B → Finset A) (a:A) : colCount s a=(transpose s a).card := by + simp only [colCount,Finsupp.finsetSum_apply,Finsupp.single_apply] + simp only [Finset.sum_ite_eq',Finset.sum_boole] + rfl +omit [DecidableEq B] in +lemma rowCount_transpose (s:B → Finset A) : rowCount (transpose s)=colCount s := by + ext a + exact (colCount_apply s a).symm +lemma colCount_transpose (s:B → Finset A) : colCount (transpose s)=rowCount s := by + rw [←rowCount_transpose,transpose_transpose] +omit [Fintype A] [DecidableEq A] [DecidableEq B] in +lemma rowCount_eq (s:B → Finset A) (a:B →₀ ℕ) : rowCount s=a ↔ ∀b,(s b).card=a b := by + exact Finsupp.ext_iff + +variable {R:Type*} [CommSemiring R] +omit [DecidableEq A] in +lemma esymm_all (k:ℕ) : MvPolynomial.esymm A R k= + ∑s:Finset A,if s.card=k then MvPolynomial.monomial (∑a∈s,Finsupp.single a 1) (1:R) else 0 := by + rw [MvPolynomial.esymm_eq_sum_monomial] + have H:Finset.powersetCard k (Finset.univ:Finset A)=Finset.univ.filter (fun s:Finset A=>s.card=k):=by + ext s + simp + rw [H,Finset.sum_filter] + +omit [DecidableEq A] in +lemma elementary_product (a:B →₀ ℕ) : + (∏b: B,MvPolynomial.esymm A R (a b))= + ∑s:B → Finset A,if rowCount s=a then MvPolynomial.monomial (colCount s) (1:R) else 0 := by + simp only [esymm_all] + rw [Fintype.prod_sum] + apply Finset.sum_congr rfl + intro s hs + by_cases h:rowCount s=a + · rw [ite_eq_left h] + have h':∀b,(s b).card=a b:=(rowCount_eq s a).mp h + simp only [h',ite_true] + exact (MvPolynomial.monomial_sum_one Finset.univ (fun b=>∑a∈s b,Finsupp.single a 1)).symm + · rw [ite_eq_right h] + obtain ⟨b,hb⟩:=not_forall.mp (mt (rowCount_eq s a).mpr h) + exact Finset.prod_eq_zero (Finset.mem_univ b) (ite_eq_right hb) + +lemma elementary_product_coeff (a:B →₀ ℕ) (μ:A →₀ ℕ) : + (∏b:B,MvPolynomial.esymm A R (a b)).coeff μ= + ∑s:B → Finset A,if rowCount s=a ∧ colCount s=μ then (1:R) else 0 := by + rw [elementary_product,MvPolynomial.coeff_sum] + apply Finset.sum_congr rfl + intro s hs + by_cases h:rowCount s=a + · simp only [h,ite_true,true_and,MvPolynomial.coeff_monomial] + · simp only [h,ite_false,false_and,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply] + +theorem duality (a:B →₀ ℕ) (μ:A →₀ ℕ) : + (∏b:B,MvPolynomial.esymm A R (a b)).coeff μ= + (∏i:A,MvPolynomial.esymm B R (μ i)).coeff a := by + rw [elementary_product_coeff,elementary_product_coeff, + ←Equiv.sum_comp (transposeEquiv (A:=A) (B:=B))] + apply Finset.sum_congr rfl + intro s hs + change (if rowCount s=a ∧ colCount s=μ then (1:R) else 0)= + if rowCount (transpose s)=μ ∧ colCount (transpose s)=a then 1 else 0 + simp only [rowCount_transpose,colCount_transpose,and_comm] +end +end ElementaryPositivity.ElementaryMatrix + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/EulerFiniteProduct.lean b/lean/OAI/Combinatorics/Chromatic/Walls/EulerFiniteProduct.lean new file mode 100644 index 0000000000000000000000000000000000000000..d66da60dbad40fcfee28303d98f9c18b743ee9f9 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/EulerFiniteProduct.lean @@ -0,0 +1,42 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +open scoped BigOperators +variable {I M : Type*} [Fintype I] [DecidableEq I] [CommGroup M] +lemma prod_zpow_eq_zpow_sum {α : Type*} (s : Finset α) (f : α → ℤ) (m : M) : + (∏ x∈s,m ^ f x)=m ^ ∑ x∈s,f x := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert x s hx ih => simp only [Finset.prod_insert hx,Finset.sum_insert hx,zpow_add,ih] + +lemma inverseEuler_exponent (a : I → I → ℕ) (d e : I → ℕ) : + (∑ i,∑ j, ((if i=j then 1 else 0)-(a i j:ℤ))*(d i:ℤ)*e j)= + (∑ i,(d i:ℤ)*e i)-∑ i,∑ j,(a i j:ℤ)*d i*e j := by + simp only [sub_mul,Finset.sum_sub_distrib] + congr 1 + apply Finset.sum_congr rfl + intro i hi + simp only [ite_mul,one_mul,zero_mul,Finset.sum_ite_eq,Finset.mem_univ,ite_true] + +lemma inverseEuler_unit_product (a : I → I → ℕ) (d e : I → ℕ) (m : M) : + (∏ i,∏ j,∏ _x : Fin (d i),∏ _y : Fin (e j), + m ^ ((if i=j then 1 else 0)-(a i j:ℤ)))= + m ^ ((∑ i,(d i:ℤ)*e i)-∑ i,∑ j,(a i j:ℤ)*d i*e j) := by + simp only [Finset.prod_const,Finset.card_univ,Fintype.card_fin] + simp only [← zpow_natCast,← zpow_mul,prod_zpow_eq_zpow_sum] + congr 1 + rw [← inverseEuler_exponent a d e] + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + ring +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FilteredDualIndependence.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FilteredDualIndependence.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c1585087c8db6a4f6a0761cf8ffce2f267eb98c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FilteredDualIndependence.lean @@ -0,0 +1,36 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +attribute [local instance] Classical.propDecidable + +lemma linearIndependent_of_filtered_dual {J V : Type*} [AddCommGroup V] [Module ℚ V] + (v : J → V) (degree : J → ℕ) (f : J → V →ₗ[ℚ] ℚ) (diag : J → ℚ) + (hd : ∀ i,diag i ≠ 0) + (hf : ∀ i j,degree j ≤ degree i → f i (v j)=if i=j then diag i else 0) : + LinearIndependent ℚ v := by + classical + apply linearIndependent_iff.mpr + intro l hl + by_contra hn + have hs : l.support.Nonempty := Finsupp.support_nonempty_iff.mpr hn + obtain ⟨i,hi,hmax⟩ := l.support.exists_max_image degree hs + have he := congrArg (f i) hl + rw [map_zero,Finsupp.linearCombination_apply,Finsupp.sum] at he + simp only [map_sum,map_smul,smul_eq_mul] at he + have hh : (∑ j ∈ l.support,l j * f i (v j))=l i*diag i := by + rw [Finset.sum_eq_single i] + · rw [hf i i le_rfl,ite_eq_left rfl] + · intro j hj hji + rw [hf i j (hmax j hj),ite_eq_right (Ne.symm hji),mul_zero] + · exact fun h=>False.elim (h hi) + rw [hh] at he + exact (Finsupp.mem_support_iff.mp hi) ((mul_eq_zero.mp he).resolve_right (hd i)) + +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FilteredTensorComm.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FilteredTensorComm.lean new file mode 100644 index 0000000000000000000000000000000000000000..92c26761842c5d4d5253e58aaf06269513009a04 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FilteredTensorComm.lean @@ -0,0 +1,66 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TensorFiltrationInterchange + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +open LinearDetection +open scoped TensorProduct +variable {M N : Type*} [AddCommGroup M] [Module ℚ M] [AddCommGroup N] [Module ℚ N] + +lemma comm_mem_tensorFiltration (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (W : ℤ) (x : M ⊗[ℚ] N) (hx : x∈additiveTensorFiltration F G W) : + TensorProduct.comm ℚ M N x∈additiveTensorFiltration G F W := by + induction hx using Submodule.span_induction with + | mem x hx => + rcases hx with ⟨u,v,x,y,h,hx,hy,rfl⟩ + exact tmul_mem_additiveTensorFiltration G F (by omega) hy hx + | zero => simpa only [map_zero] using (additiveTensorFiltration G F W).zero_mem + | add x y hx hy hix hiy => simpa only [map_add] using (additiveTensorFiltration G F W).add_mem hix hiy + | smul r x hx hix => simpa only [map_smul] using (additiveTensorFiltration G F W).smul_mem r hix + +noncomputable def tensorFiltrationComm (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (W : ℤ) : additiveTensorFiltration F G W ≃ₗ[ℚ] additiveTensorFiltration G F W := + { restrict _ _ (TensorProduct.comm ℚ M N).toLinearMap (comm_mem_tensorFiltration F G W) with + invFun := fun x=>⟨TensorProduct.comm ℚ N M x.val,comm_mem_tensorFiltration G F W x.val x.property⟩ + left_inv := fun x=>by apply Subtype.ext; exact (TensorProduct.comm ℚ M N).symm_apply_apply x.val + right_inv := fun x=>by apply Subtype.ext; exact (TensorProduct.comm ℚ M N).apply_symm_apply x.val } + +noncomputable def tensorGradeComm (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (W : ℤ) : Grade (additiveTensorFiltration F G W) (additiveTensorFiltration F G (W+1)) →ₗ[ℚ] + Grade (additiveTensorFiltration G F W) (additiveTensorFiltration G F (W+1)) := + map _ _ _ _ (TensorProduct.comm ℚ M N).toLinearMap + (comm_mem_tensorFiltration F G W) (comm_mem_tensorFiltration F G (W+1)) + +lemma tensorGradeComm_mk (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (W : ℤ) (x : additiveTensorFiltration F G W) : + tensorGradeComm F G W (Submodule.Quotient.mk x)= + Submodule.Quotient.mk (tensorFiltrationComm F G W x) := rfl + +end ElementaryPositivity.LinearFiltration + +end +section +namespace ElementaryPositivity + +lemma linearMap_span_ext {K M N : Type*} [Semiring K] [AddCommMonoid M] [Module K M] + [AddCommMonoid N] [Module K N] (s : Set M) + (f g : Submodule.span K s →ₗ[K] N) + (h : ∀ x (hx : x∈s),f ⟨x,Submodule.subset_span hx⟩=g ⟨x,Submodule.subset_span hx⟩) : f=g := by + ext ⟨x,hx⟩ + induction hx using Submodule.span_induction with + | mem x hx => exact h x hx + | zero => change f 0=g 0; rw [map_zero,map_zero] + | add x y hx hy hix hiy => + change f (⟨x,hx⟩+⟨y,hy⟩)=g (⟨x,hx⟩+⟨y,hy⟩) + rw [map_add,map_add,hix,hiy] + | smul r x hx hix => + change f (r • ⟨x,hx⟩)=g (r • ⟨x,hx⟩) + rw [map_smul,map_smul,hix] + +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FilteredTensorInsert.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FilteredTensorInsert.lean new file mode 100644 index 0000000000000000000000000000000000000000..415938626f83e77696138e5a4e6ace559030c65a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FilteredTensorInsert.lean @@ -0,0 +1,36 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TensorFiltrationInterchange + +namespace OAI + +section +namespace ElementaryPositivity.LinearDetection +open scoped TensorProduct +variable {K A B C : Type*} [Field K] + [AddCommGroup A] [Module K A] [AddCommGroup B] [Module K B] + [AddCommGroup C] [Module K C] + +noncomputable def tensorFiltrationAssoc (F : ℤ → Submodule K A) (G : ℤ → Submodule K B) + (H : ℤ → Submodule K C) (W : ℤ) : + additiveTensorFiltration (additiveTensorFiltration F G) H W ≃ₗ[K] + additiveTensorFiltration F (additiveTensorFiltration G H) W := + { toFun := fun x=>⟨TensorProduct.assoc K A B C x.val,assoc_mem_tensorFiltration F G H W x.val x.property⟩ + invFun := fun x=>⟨(TensorProduct.assoc K A B C).symm x.val,unassoc_mem_tensorFiltration F G H W x.val x.property⟩ + left_inv := by intro x; apply Subtype.ext; exact (TensorProduct.assoc K A B C).symm_apply_apply x.val + right_inv := by intro x; apply Subtype.ext; exact (TensorProduct.assoc K A B C).apply_symm_apply x.val + map_add' := by intro x y; apply Subtype.ext; exact (TensorProduct.assoc K A B C).map_add x.val y.val + map_smul' := by intro r x; apply Subtype.ext; exact (TensorProduct.assoc K A B C).map_smul r x.val } + +noncomputable def unassocTensorFixedLeft (F : ℤ → Submodule K A) (G : ℤ → Submodule K B) + (H : ℤ → Submodule K C) (U V : ℤ) (x : F U) : + additiveTensorFiltration G H V →ₗ[K] additiveTensorFiltration (additiveTensorFiltration F G) H (U+V) := + (((TensorProduct.assoc K A B C).symm.toLinearMap.comp (TensorProduct.mk K A (B⊗[K]C) x.val)).comp + (additiveTensorFiltration G H V).subtype).codRestrict _ (fun y=> + unassoc_mem_tensorFiltration F G H (U+V) (x.val⊗ₜ[K]y.val) + (tmul_mem_additiveTensorFiltration F (additiveTensorFiltration G H) (le_refl _) x.property y.property)) + +end ElementaryPositivity.LinearDetection + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiltrationHomogeneousRank.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiltrationHomogeneousRank.lean new file mode 100644 index 0000000000000000000000000000000000000000..c38ab5536d574df48d86497d6c9f3473a753f4b5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiltrationHomogeneousRank.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TensorFiltrationInterchange + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +variable {M : Type*} [AddCommGroup M] [Module ℚ M] +variable (F G : Submodule ℚ M) (p : Module.End ℚ M) +variable (hp : ∀ x,p (p x)=p x) +variable (hF : ∀ x∈F,p x∈F) (hG : ∀ x∈G,p x∈G) + +noncomputable def homogeneousMk : F.comap (LinearMap.range p).subtype →ₗ[ℚ] Grade F G := + (mk F G).comp + ({ toFun := fun x=>⟨x.val.val,x.property⟩ + map_add' := by intros; rfl + map_smul' := by intros; rfl } : F.comap (LinearMap.range p).subtype →ₗ[ℚ] F) + +include hp in +lemma homogeneousMk_range : + LinearMap.range (homogeneousMk F G p)=LinearMap.range (map F G F G p hF hG) := by + apply le_antisymm + · rintro _ ⟨x,rfl⟩ + refine ⟨mk F G ⟨x.val.val,x.property⟩,?_⟩ + change Submodule.Quotient.mk (⟨p x.val.val,hF _ x.property⟩ : F)=Submodule.Quotient.mk (⟨x.val.val,x.property⟩ : F) + apply congrArg Submodule.Quotient.mk + apply Subtype.ext + obtain ⟨y,hy⟩:=x.val.property + exact (congrArg p hy).symm.trans ((hp y).trans hy) + · rintro _ ⟨x,rfl⟩ + induction x using Submodule.Quotient.induction_on with + | H x => exact ⟨⟨⟨p x.val,⟨x.val,rfl⟩⟩,hF _ x.property⟩,rfl⟩ + +include hp in +lemma homogeneousMap_finite [Module.Finite ℚ (LinearMap.range p)] : + Module.Finite ℚ (LinearMap.range (map F G F G p hF hG)) := by + rw [←homogeneousMk_range F G p hp hF hG] + exact Module.Finite.range (homogeneousMk F G p) + +lemma homogeneousMk_ker : + LinearMap.ker (homogeneousMk F G p)= + next (F.comap (LinearMap.range p).subtype) (G.comap (LinearMap.range p).subtype) := by + ext x + change Submodule.Quotient.mk (⟨x.val.val,x.property⟩ : F)=0 ↔ _ + exact Submodule.Quotient.mk_eq_zero (next F G) + +include hp hF hG in +lemma homogeneousGrade_rank [Module.Finite ℚ (LinearMap.range p)] (hGF : G≤F) : + Module.finrank ℚ (LinearMap.range (map F G F G p hF hG))+ + Module.finrank ℚ (G.comap (LinearMap.range p).subtype)= + Module.finrank ℚ (F.comap (LinearMap.range p).subtype) := by + have H := (homogeneousMk F G p).finrank_range_add_finrank_ker + rw [homogeneousMk_range F G p hp hF hG,homogeneousMk_ker] at H + have E := (Submodule.comapSubtypeEquivOfLe + (Submodule.comap_mono hGF : G.comap (LinearMap.range p).subtype≤F.comap (LinearMap.range p).subtype)).finrank_eq + exact E ▸ H + +include hp in +lemma homogeneousGrade_rank_eq [Module.Finite ℚ (LinearMap.range p)] (hGF : G≤F) : + Module.finrank ℚ (LinearMap.range (map F G F G p hF hG))= + Module.finrank ℚ (Grade (F.comap (LinearMap.range p).subtype) + (G.comap (LinearMap.range p).subtype)) := by + have H := homogeneousGrade_rank F G p hp hF hG hGF + have H' := (next (F.comap (LinearMap.range p).subtype) + (G.comap (LinearMap.range p).subtype)).finrank_quotient_add_finrank + have E := (Submodule.comapSubtypeEquivOfLe + (Submodule.comap_mono hGF : G.comap (LinearMap.range p).subtype≤F.comap (LinearMap.range p).subtype)).finrank_eq + have H'' : Module.finrank ℚ (Grade (F.comap (LinearMap.range p).subtype) + (G.comap (LinearMap.range p).subtype))+ + Module.finrank ℚ (G.comap (LinearMap.range p).subtype)= + Module.finrank ℚ (F.comap (LinearMap.range p).subtype) := E ▸ H' + omega +end ElementaryPositivity.LinearFiltration + +namespace ElementaryPositivity +variable {M : Type*} [AddCommGroup M] [Module ℚ M] [Module.Finite ℚ M] +variable (F : ℤ → Submodule ℚ M) (hF : Antitone F) + +include hF +lemma finiteFiltration_rank_step (w : ℤ) : + Module.finrank ℚ (LinearFiltration.Grade (F w) (F (w+1)))+Module.finrank ℚ (F (w+1))= + Module.finrank ℚ (F w) := by + have H := (LinearFiltration.next (F w) (F (w+1))).finrank_quotient_add_finrank + have E := (Submodule.comapSubtypeEquivOfLe (hF (show w≤w+1 by omega))).finrank_eq + exact E ▸ H + +lemma finiteFiltration_rank_sum (L : ℤ) (n : ℕ) : + (∑ j∈Finset.range n,Module.finrank ℚ (LinearFiltration.Grade (F (L+j)) (F (L+j+1))))+ + Module.finrank ℚ (F (L+n))=Module.finrank ℚ (F L) := by + induction n with + | zero => + change 0+Module.finrank ℚ (F (L+0))=Module.finrank ℚ (F L) + rw [add_zero,zero_add] + | succ n ih => + rw [Finset.sum_range_succ,Nat.cast_add,Nat.cast_one,←add_assoc,add_assoc] + rw [finiteFiltration_rank_step F hF (L+n)] + exact ih + +lemma finiteFiltration_rank_total (L : ℤ) (n : ℕ) (hL : F L=⊤) (hU : F (L+n)=⊥) : + (∑ j∈Finset.range n,Module.finrank ℚ (LinearFiltration.Grade (F (L+j)) (F (L+j+1))))= + Module.finrank ℚ M := by + have H := finiteFiltration_rank_sum F hF L n + rw [hL,hU,finrank_bot,add_zero,finrank_top] at H + exact H +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteElementaryAdjoint.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteElementaryAdjoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..e67329d6480a8be3b5a407c88be4b1758c9be046 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteElementaryAdjoint.lean @@ -0,0 +1,128 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CompletedInverse +import OAI.Combinatorics.Chromatic.Walls.QuantumTorusRaySeries + +namespace OAI + +section +namespace ElementaryPositivity.WallUnits +open PowerSeries +noncomputable section +variable {R : Type*} [CommRing R] +def DegreeBound (d : ℕ) (f : PowerSeries R) : Prop := ∀ n,dsimpa using (degreeBound_one (R:=R)) + | succ t ih=> + rw [Finset.prod_range_succ] + exact ih.mul (degreeBound_linear (u t)) +lemma DegreeBound.rescale {d : ℕ} {f : PowerSeries R} (hf : DegreeBound d f) (u : R) : + DegreeBound d (PowerSeries.rescale u f) := by + intro n hn + rw [coeff_rescale,hf n hn,mul_zero] +end +section +variable {K : Type*} [Field K] +lemma elementary_ratio_degree (q u : K) (hq : q≠0) + (hq' : ∀n : ℕ,1-q^(n+1)≠0) (t : ℕ) : + DegreeBound t (PowerSeries.rescale (q⁻¹^t) (elementary q u)*(elementary q u)⁻¹) := by + rw [elementary_ratio q u hq hq' t] + exact degreeBound_product_linear _ t +lemma elementary_inverse_ratio_degree (q u : K) (hq : q≠0) + (hq' : ∀n : ℕ,1-q^(n+1)≠0) (t : ℕ) : + DegreeBound t (PowerSeries.rescale (q^t) (elementary q u)⁻¹*elementary q u) := by + have he : PowerSeries.rescale (q^t) (elementary q u)⁻¹*elementary q u= + PowerSeries.rescale (q^t) (PowerSeries.rescale (q⁻¹^t) (elementary q u)*(elementary q u)⁻¹) := by + rw [map_mul,PowerSeries.rescale_rescale,←mul_pow,inv_mul_cancel₀ hq,one_pow, + PowerSeries.rescale_one,RingHom.id_apply,mul_comm] + rw [he] + exact (elementary_ratio_degree q u hq hq' t).rescale _ +end +end ElementaryPositivity.WallUnits +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) +lemma monomial_ray_support (a m x : M) (f : PowerSeries K) (t N : ℕ) + (hf : DegreeBound t f) + (hx : coeff N (PowerSeries.C (Torus.X v Ω m)*raySeries v Ω a f) x≠0) : + N≤t ∧ x=m+N • a := by + rw [coeff_C_mul,coeff_raySeries,Torus.X,Torus.monomial_mul_monomial,one_mul] at hx + constructor + · by_contra h + rw [hf N (by omega),zero_mul,Torus.monomial_zero] at hx + exact hx rfl + · by_contra h + exact hx (Finsupp.single_eq_of_ne h) +lemma elementary_adjoint_support (hΩ : ∀m,Ω m m=0) (a m x : M) + (q u : K) (hq : q≠0) (hq' : ∀n : ℕ,1-q^(n+1)≠0) (t N : ℕ) + (hshift : (↑(v^(2*Ω a m)):K)=q⁻¹^t) + (hx : coeff N ((rayUnit v Ω a (hΩ a) (elementary q u) (constant_elementary _ _)).val * + PowerSeries.C (Torus.X v Ω m)* + (rayUnit v Ω a (hΩ a) (elementary q u) (constant_elementary _ _)).inv) x≠0) : + N≤t ∧ x=m+N • a := by + rw [ray_adjoint v Ω hΩ,hshift] at hx + exact monomial_ray_support v Ω a m x _ t N (elementary_ratio_degree q u hq hq' t) hx +lemma elementary_inverse_adjoint_support (hΩ : ∀m,Ω m m=0) (a m x : M) + (q u : K) (hq : q≠0) (hq' : ∀n : ℕ,1-q^(n+1)≠0) (t N : ℕ) + (hshift : (↑(v^(2*Ω a m)):K)=q^t) + (hx : coeff N ((rayUnit v Ω a (hΩ a) (elementary q u) (constant_elementary _ _)).inv * + PowerSeries.C (Torus.X v Ω m)* + (rayUnit v Ω a (hΩ a) (elementary q u) (constant_elementary _ _)).val) x≠0) : + N≤t ∧ x=m+N • a := by + rw [ray_inverse_adjoint v Ω hΩ,hshift] at hx + exact monomial_ray_support v Ω a m x _ t N (elementary_inverse_ratio_degree q u hq hq' t) hx +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.PowerSeriesAdjoint +open PowerSeries +noncomputable section +variable {A : Type*} [Ring A] +lemma inverse_inverse (F : PowerSeries A) (hF : constantCoeff F=1) : + invOfUnit (invOfUnit F 1) 1=F := by + have hI : constantCoeff (invOfUnit F 1)=1:=by simp + calc + _=invOfUnit (invOfUnit F 1) 1*((invOfUnit F 1)*F):=by rw [invOfUnit_mul F 1 hF,mul_one] + _=(invOfUnit (invOfUnit F 1) 1*(invOfUnit F 1))*F:=by rw [mul_assoc] + _=F:=by rw [invOfUnit_mul _ 1 hI,one_mul] +lemma adjoint_one (X : PowerSeries A) : adjoint 1 X=X := by + have hI : invOfUnit (1:PowerSeries A) 1=1:=by + have H:=mul_invOfUnit (1:PowerSeries A) 1 (by simp) + simpa using H + simp only [adjoint,one_mul,hI,mul_one] +lemma adjoint_inverse (F X : PowerSeries A) (hF : constantCoeff F=1) : + adjoint (invOfUnit F 1) X=invOfUnit F 1*X*F := by rw [adjoint,inverse_inverse F hF] +lemma adjoint_inverse_cancel (F X : PowerSeries A) (hF : constantCoeff F=1) : + adjoint (invOfUnit F 1) (adjoint F X)=X := by + rw [←adjoint_mul _ _ _ (by simp) hF,invOfUnit_mul F 1 hF,adjoint_one] +lemma adjoint_inverse_coeff (F X Y : PowerSeries A) (hF : constantCoeff F=1) (N : ℕ) + (hXY : ∀n≤N,coeff n X=coeff n (adjoint F Y)) : + coeff N (adjoint (invOfUnit F 1) X)=coeff N Y := by + rw [adjoint_coeff_congr _ _ _ _ N (fun _ _=>rfl) hXY,adjoint_inverse_cancel F Y hF] +end +end ElementaryPositivity.PowerSeriesAdjoint + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteFiberInfinity.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteFiberInfinity.lean new file mode 100644 index 0000000000000000000000000000000000000000..53420b650a06cebb37f225d9c52ed500d8a8e37c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteFiberInfinity.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationLaurentTransport + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +@[simp] lemma expandInfinity_constant (a : K) : + expandInfinity (RatFunc.C a)=HahnSeries.C a := by + change expandZero (reciprocal (RatFunc.C a))=_ + rw [reciprocal_constant,expandZero_constant] +lemma expandInfinity_centeredScalar (n a : ℤ) (b : K) : + expandInfinity (RatFunc.C b*centeredScalar v n a)= + HahnSeries.single (-n) (b*(↑(v^(-n*a)):K)) := by + rw [centeredScalar,←mul_assoc,←map_mul,map_mul,expandInfinity_constant,expandInfinity_X_zpow] + simp [HahnSeries.C] + +def readFiberInfinity (m : M) : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω) →+ K where + toFun f:=(expandInfinity (f (off k p hp m))).coeff (-k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K) + map_zero':=by simp + map_add' f g:=by simp [add_mul] +lemma readFiberInfinity_monomial (m n : M) (a : K) : + readFiberInfinity v Ω k p hp m (embedAdd v Ω k p hp (Torus.monomial v Ω n a))= + (Torus.monomial v Ω n a) m := by + classical + rw [embedAdd_monomial] + change (expandInfinity ((Finsupp.single (off k p hp n) + (RatFunc.C a*centeredScalar v (k n) (complementAlpha k p Ω (off k p hp n)))) + (off k p hp m))).coeff (-k m)* + (↑(v^(k m*complementAlpha k p Ω (off k p hp m))):K)=Finsupp.single n a m + by_cases ho : off k p hp n=off k p hp m + · rw [Finsupp.single_apply,ite_eq_left ho,expandInfinity_centeredScalar] + by_cases hk : k n=k m + · have hn : n=m:=split_injective k p hp hk ho + subst n + rw [HahnSeries.coeff_single,ite_eq_left rfl,Finsupp.single_eq_same] + rw [mul_assoc,←Units.val_mul,←zpow_add] + simp + · have hn : n≠m:=fun h=>hk (congrArg k h) + simp [Ne.symm hk,Finsupp.single_eq_of_ne (Ne.symm hn)] + · have hn : n≠m:=fun h=>ho (congrArg (off k p hp) h) + rw [Finsupp.single_apply,ite_eq_right ho] + simp [Finsupp.single_eq_of_ne (Ne.symm hn)] +lemma readFiberInfinity_embedAdd (f : Torus v Ω) (m : M) : + readFiberInfinity v Ω k p hp m (embedAdd v Ω k p hp f)=f m := by + induction f using Finsupp.induction_linear with + | zero=>simp + | add f g hf hg=>simp [map_add,hf,hg] + | single n a=>exact readFiberInfinity_monomial v Ω k p hp m n a +lemma finite_fiber_zero_infinity (f : Torus v Ω) (m : M) : + readFiber v Ω k p hp m (embedAdd v Ω k p hp f)= + readFiberInfinity v Ω k p hp m (embedAdd v Ω k p hp f) := by + rw [readFiber_embedAdd,readFiberInfinity_embedAdd] +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) (pos : Bool) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +theorem mutation_rational_compatibility (f : CompletedPositive LaurentRay.vUnit Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + mutationSideAction LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω) pos + (rationalRegrade LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) (nonpDegree coord pc) (mutationSize Ω C pc+1) f.val)= + rationalRegrade LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) + (nonpDegree (mutatedCoordinates Ω C coord pc) pc) (mutationSize Ω C pc+1) + (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f.val) := by + unfold rationalRegrade + rw [mutationSideAction_embed Ω hΩ C coord hcoord pc] + change PowerSeries.map _ (PowerSeries.map (mutationTorusPush Ω hΩ C pc pos LaurentRay.vUnit) _)=_ + rw [mutation_regrade_compatibility LaurentRay.vUnit Ω hΩ C coord hcoord pc pos f hf] + +theorem mutation_rational_new_coefficient (f : CompletedPositive LaurentRay.vUnit Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) + (d : ℕ) (m : M) : + readFiberInfinity LaurentRay.vUnit Ω (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) m + (coeff d (mutationSideAction LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω) pos + (rationalRegrade LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) (nonpDegree coord pc) (mutationSize Ω C pc+1) f.val)))= + coeff d (regrade LaurentRay.vUnit Ω (nonpDegree (mutatedCoordinates Ω C coord pc) pc) + (mutationSize Ω C pc+1) (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f.val)) m := by + rw [mutation_rational_compatibility Ω hΩ C coord hcoord pc pos f hf,rationalRegrade,coeff_map] + exact readFiberInfinity_embedAdd LaurentRay.vUnit Ω _ _ _ _ _ +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteFibreFinsupp.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteFibreFinsupp.lean new file mode 100644 index 0000000000000000000000000000000000000000..38728e493e9ffa7bb42cd87205bd0b16fb55f011 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteFibreFinsupp.lean @@ -0,0 +1,58 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +open Function +attribute [local instance] Classical.propDecidable +variable {A B : Type*} (p : A → B) + +def fibreConstant : Submodule ℚ (A →₀ ℚ) where + carrier := {f | ∀ a a',p a=p a' → f a=f a'} + zero_mem' := by intro a a' h; rfl + add_mem' := by intro f g hf hg a a' h; simp only [Finsupp.add_apply,hf a a' h,hg a a' h] + smul_mem' := by intro r f hf a a' h; simp only [Finsupp.smul_apply,hf a a' h] + +noncomputable def finiteFibrePullback (hp : ∀ b,Set.Finite {a | p a=b}) : + (B →₀ ℚ) →ₗ[ℚ] (A →₀ ℚ) where + toFun f := Finsupp.ofSupportFinite (fun a=>f (p a)) (by + have H:=(f.support.finite_toSet.biUnion (fun b (_ : b∈f.support)=>hp b)) + apply H.subset + intro a ha + exact Set.mem_iUnion₂.mpr ⟨p a,Finsupp.mem_support_iff.mpr ha,rfl⟩) + map_add' f g := by ext a; rfl + map_smul' r f := by ext a; rfl + +@[simp] lemma finiteFibrePullback_apply (hp : ∀ b,Set.Finite {a | p a=b}) + (f : B →₀ ℚ) (a : A) : finiteFibrePullback p hp f a=f (p a) := rfl + +noncomputable def fibreConstantEquiv (hp : ∀ b,Set.Finite {a | p a=b}) + (s : B → A) (hs : Function.RightInverse s p) : + fibreConstant p ≃ₗ[ℚ] (B →₀ ℚ) where + toFun f := Finsupp.lcomapDomain s hs.injective f.val + invFun f := ⟨finiteFibrePullback p hp f,by intro a a' h; simp only [finiteFibrePullback_apply,h]⟩ + left_inv f := by + apply Subtype.ext + ext a + exact f.property _ _ (hs (p a)) + right_inv f := by ext b; exact congrArg f (hs b) + map_add' f g := map_add (Finsupp.lcomapDomain s hs.injective) f.val g.val + map_smul' r f := map_smul (Finsupp.lcomapDomain s hs.injective) r f.val + +noncomputable def fibreConstantBasis (hp : ∀ b,Set.Finite {a | p a=b}) + (s : B → A) (hs : Function.RightInverse s p) : + Module.Basis B ℚ (fibreConstant p) := + (Finsupp.basisSingleOne : Module.Basis B ℚ (B →₀ ℚ)).map (fibreConstantEquiv p hp s hs).symm + +lemma fibreConstantBasis_apply (hp : ∀ b,Set.Finite {a | p a=b}) + (s : B → A) (hs : Function.RightInverse s p) (b : B) (a : A) : + (fibreConstantBasis p hp s hs b).val a=if p a=b then 1 else 0 := by + classical + change Finsupp.single b (1:ℚ) (p a)=_ + simp [Finsupp.single_apply,eq_comm] +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteLatticePairing.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteLatticePairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..610247daca11dd2cf500efe758239333bb41d674 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteLatticePairing.lean @@ -0,0 +1,249 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularLateStationarity + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators + +variable {V : Type*} [Fintype V] [DecidableEq V] + +noncomputable def matrixPairing (K : Matrix V V ℤ) : (V → ℤ) →+ (V → ℤ) →+ ℤ where + toFun x := (Matrix.toBilin' K x).toAddMonoidHom + map_zero' := by ext y; simp + map_add' x y := by ext z; simp + +lemma matrixPairing_apply (K : Matrix V V ℤ) (x y : V → ℤ) : + matrixPairing K x y = ∑ a, ∑ b, x a * K a b * y b := + Matrix.toBilin'_apply _ _ _ + +@[simp] lemma matrixPairing_single (K : Matrix V V ℤ) (a b : V) : + matrixPairing K (Pi.single a 1) (Pi.single b 1) = K a b := + Matrix.toBilin'_single .. + +lemma matrixPairing_single_left (K : Matrix V V ℤ) (a : V) (m : V → ℤ) : + matrixPairing K (Pi.single a 1) m = ∑ b, K a b * m b := by + rw [matrixPairing_apply,Finset.sum_eq_single a] + · simp + · intro b _ hb + simp [hb] + · simp + +lemma matrixPairing_skew (K : Matrix V V ℤ) (hK : ∀ a b, K a b = -K b a) + (x y : V → ℤ) : matrixPairing K x y = -matrixPairing K y x := by + rw [matrixPairing_apply,matrixPairing_apply,Finset.sum_comm] + simp only [←Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro a _ + apply Finset.sum_congr rfl + intro b _ + rw [hK b a] + ring + +lemma matrixPairing_self (K : Matrix V V ℤ) (hK : ∀ a b, K a b = -K b a) + (m : V → ℤ) : matrixPairing K m m = 0 := by + have := matrixPairing_skew K hK m m + omega + +variable {n : ℕ} {B : Type*} [Fintype B] [DecidableEq B] + +def chartMatrix (level : B → Fin n) (bb : B → B → ℤ) : Matrix (Vertex n B) (Vertex n B) ℤ + | .inl _, .inl _ => 0 + | .inl a, .inr b => (if a = (level b).succ then 1 else 0) - + (if a = (level b).castSucc then 1 else 0) + | .inr b, .inl a => (if a = (level b).castSucc then 1 else 0) - + (if a = (level b).succ then 1 else 0) + | .inr b, .inr c => bb b c + +noncomputable def chartPairing (level : B → Fin n) (bb : B → B → ℤ) := + matrixPairing (chartMatrix level bb) + +omit [Fintype B] [DecidableEq B] in +lemma chartMatrix_skew (level : B → Fin n) (bb : B → B → ℤ) + (hbb : ∀ b c, bb b c = -bb c b) (a c : Vertex n B) : + chartMatrix level bb a c = -chartMatrix level bb c a := by + cases a <;> cases c <;> simp only [chartMatrix] + · rfl + · ring + · ring + · apply hbb + +lemma chartPairing_self (level : B → Fin n) (bb : B → B → ℤ) + (hbb : ∀ b c, bb b c = -bb c b) (m : Lattice n B) : + chartPairing level bb m m = 0 := + matrixPairing_self _ (chartMatrix_skew level bb hbb) m + +omit [DecidableEq B] in +lemma total_as_sum (level : B → Fin n) (m : Lattice n B) (k : ℕ) : + extendedTotal level m k = ∑ b, if (level b).val+1=k then m (.inr b) else 0 := by + unfold extendedTotal + split_ifs with hk + · change (∑ b, if level b = ⟨k-1,by omega⟩ then m (.inr b) else 0) = _ + apply Finset.sum_congr rfl + intro b _ + have hh : level b = (⟨k-1,by omega⟩ : Fin n) ↔ (level b).val+1=k := by + constructor + · intro h; have := congrArg Fin.val h; dsimp at this; omega + · intro h; apply Fin.ext; dsimp; omega + simp only [hh] + · symm + apply Finset.sum_eq_zero + intro b _ + have hne : ¬(level b).val+1=k := by have := (level b).isLt; omega + simp [hne] + +lemma chartPairing_anchor (level : B → Fin n) (bb : B → B → ℤ) + (a : Fin (n+1)) (m : Lattice n B) : + chartPairing level bb (anchor a) m = + extendedTotal level m a.val - extendedTotal level m (a.val+1) := by + change matrixPairing (chartMatrix level bb) (Pi.single (.inl a) 1) m = _ + rw [matrixPairing_single_left,Fintype.sum_sum_type] + simp only [chartMatrix,zero_mul,Finset.sum_const_zero,zero_add] + rw [total_as_sum,total_as_sum,←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro b _ + have h1 : a = (level b).succ ↔ (level b).val+1=a.val := by + rw [Fin.ext_iff]; simp only [Fin.val_succ]; omega + have h2 : a = (level b).castSucc ↔ (level b).val+1=a.val+1 := by + rw [Fin.ext_iff]; simp only [Fin.val_castSucc]; omega + simp only [h1,h2] + split_ifs <;> ring + +lemma chartPairing_delta (level : B → Fin n) (bb : B → B → ℤ) + (b : B) (m : Lattice n B) : + chartPairing level bb (delta level b) m = + 2*extendedTotal level m ((level b).val+1) - extendedTotal level m (level b).val - + extendedTotal level m ((level b).val+2) := by + simp only [delta,map_sub,AddMonoidHom.sub_apply,chartPairing_anchor, + Fin.val_succ,Fin.val_castSucc] + ring + +lemma chart_tropical_stationary (level : B → Fin n) (hl : Function.Surjective level) + (bb : B → B → ℤ) (hbb : ∀ b c, bb b c = -bb c b) + (cycle : List B) (hcycle : ∀ b, b ∈ cycle) (m : Lattice n B) (N : ℕ) + (hs : ∀ L i, 0 ≤ cutDeficit level i N L + (history (chartPairing level bb) level cycle m L)) : + (∀ i, levelTotal level i m = 0) ∧ + (∀ b, 0 ≤ chartPairing level bb (eventRoot level 0 b) m) ∧ + (∀ L, history (chartPairing level bb) level cycle m L = m) := + tropical_history_stationary _ (chartPairing_self level bb hbb) level hl cycle hcycle + (chartPairing_delta level bb) m N hs + +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators + +abbrev Cell (n : ℕ) := (i : Fin n) × Fin (i.val+1) +def cellLevel {n : ℕ} (b : Cell n) : Fin n := b.1 +def cellRow {n : ℕ} (b : Cell n) : ℕ := b.2.val + +def phaseEarlier {n : ℕ} (b c : Cell n) : Prop := + cellRow c < cellRow b ∨ (cellRow b = cellRow c ∧ b.1 < c.1) +instance {n : ℕ} (b c : Cell n) : Decidable (phaseEarlier b c) := + inferInstanceAs (Decidable (_ ∨ (_ ∧ _))) + +lemma cell_ext {n : ℕ} {b c : Cell n} (hl : b.1=c.1) (hr : cellRow b=cellRow c) : b=c := by + cases b with | mk i r => + cases c with | mk j s => + dsimp only at hl + subst j + have HH:r=s:=Fin.ext hr + subst s + rfl + +lemma phaseEarlier_trichotomy {n : ℕ} (b c : Cell n) : + phaseEarlier b c ∨ b=c ∨ phaseEarlier c b := by + by_cases hr : cellRow b=cellRow c + · rcases lt_trichotomy b.1 c.1 with h|h|h + · exact Or.inl (Or.inr ⟨hr,h⟩) + · exact Or.inr (Or.inl (cell_ext h hr)) + · exact Or.inr (Or.inr (Or.inr ⟨hr.symm,h⟩)) + · rcases lt_or_gt_of_ne hr with h|h + · exact Or.inr (Or.inr (Or.inl h)) + · exact Or.inl (Or.inl h) + +@[simp] lemma phaseEarlier_irrefl {n : ℕ} (b : Cell n) : ¬phaseEarlier b b := by + simp [phaseEarlier] +lemma phaseEarlier_asymm {n : ℕ} {b c : Cell n} (h : phaseEarlier b c) : + ¬phaseEarlier c b := by + unfold phaseEarlier at * + rcases h with h|⟨h,h'⟩ <;> intro H + · rcases H with H|⟨H,_⟩ <;> omega + · rcases H with H|⟨_,H⟩ + · omega + · exact lt_asymm h' H + +def bridgePositive {n : ℕ} (b c : Cell n) : ℤ := + if b.1=c.1 ∧ phaseEarlier c b then 1 + else if c.1.val+1=b.1.val ∧ phaseEarlier b c then 1 else 0 + +def triangularBB {n : ℕ} (b c : Cell n) : ℤ := bridgePositive b c-bridgePositive c b + +lemma triangularBB_skew {n : ℕ} (b c : Cell n) : triangularBB b c= -triangularBB c b := by + unfold triangularBB + ring + +noncomputable def triangularOmega (n : ℕ) := chartPairing (@cellLevel n) (@triangularBB n) +lemma triangularOmega_self {n : ℕ} (m : Lattice n (Cell n)) : triangularOmega n m m=0 := + chartPairing_self _ _ triangularBB_skew m + +lemma eventRoot_anchor {n : ℕ} (b : Cell n) (a : Fin (n+1)) : + triangularOmega n (eventRoot cellLevel 0 b) (anchor a) = + (if a=b.1.castSucc then 1 else 0)-(if a=b.1.succ then 1 else 0) := by + simp only [eventRoot,Nat.cast_zero,zero_smul,add_zero,map_sub,AddMonoidHom.sub_apply] + change matrixPairing (chartMatrix cellLevel triangularBB) (bridge b) (anchor a)- + matrixPairing (chartMatrix cellLevel triangularBB) (anchor b.1.castSucc) (anchor a)=_ + simp only [bridge,anchor,matrixPairing_single,chartMatrix,cellLevel,sub_zero] + rfl + +lemma eventRoot_bridge_value {n : ℕ} (b c : Cell n) : + triangularOmega n (eventRoot cellLevel 0 b) (bridge c) = + if c.1=b.1 then + (if phaseEarlier c b then 2 else if c=b then 1 else 0) + else if c.1.val+1=b.1.val ∨ b.1.val+1=c.1.val then + (if phaseEarlier c b then -1 else 0) + else 0 := by + simp only [eventRoot,Nat.cast_zero,zero_smul,add_zero,map_sub,AddMonoidHom.sub_apply] + change matrixPairing (chartMatrix cellLevel triangularBB) (bridge b) (bridge c)- + matrixPairing (chartMatrix cellLevel triangularBB) (anchor b.1.castSucc) (bridge c)=_ + simp only [bridge,anchor,matrixPairing_single] + change triangularBB b c - ((if b.1.castSucc=c.1.succ then 1 else 0)- + (if b.1.castSucc=c.1.castSucc then 1 else 0)) = + (if c.1=b.1 then (if phaseEarlier c b then 2 else if c=b then 1 else 0) + else if c.1.val+1=b.1.val ∨ b.1.val+1=c.1.val then + (if phaseEarlier c b then -1 else 0) else 0) + have h1 : b.1.castSucc=c.1.succ ↔ b.1.val=c.1.val+1 := by rw [Fin.ext_iff]; rfl + have h2 : b.1.castSucc=c.1.castSucc ↔ b.1=c.1 := Fin.castSucc_inj + simp only [triangularBB,bridgePositive,h1,h2] + rcases phaseEarlier_trichotomy b c with H|H|H + · have H' := phaseEarlier_asymm H + have Hne : c≠b := by intro h; subst c; exact phaseEarlier_irrefl b H + simp only [H,H',Hne,ite_false,and_false,and_true] + by_cases hl : b.1=c.1 + · have hv := congrArg Fin.val hl + simp only [hl,ite_true] + split_ifs <;> omega + · have hl' := Ne.symm hl + simp only [hl,hl',ite_false] + split_ifs <;> omega + · subst c + simp + · have H' := phaseEarlier_asymm H + simp only [H,H',ite_false,ite_true,and_false,and_true] + by_cases hl : b.1=c.1 + · have hv := congrArg Fin.val hl + simp only [hl,ite_true] + split_ifs <;> omega + · have hl' := Ne.symm hl + simp only [hl,hl',ite_false] + split_ifs <;> omega + +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FinitePathPerturbation.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FinitePathPerturbation.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee6017518c0006bebfdff5656ba3272c9ee3d82d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FinitePathPerturbation.lean @@ -0,0 +1,168 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteRayGeometry + +namespace OAI + +section +namespace ElementaryPositivity.FiniteRayGeometry +open Module +noncomputable section +variable {E : Type*} [AddCommGroup E] [Module ℝ E] +lemma preserve_finite_affine_signs (P : Finset (ℝ×E)) (k g v : Module.Dual ℝ E) : + ∃ε>0,∀δ:ℝ,0<δ → δ<ε → ∀as∈P, + (0<(k+as.1 • v) as.2 → 0<(k+δ • g+as.1 • v) as.2) ∧ + ((k+as.1 • v) as.2<0 → (k+δ • g+as.1 • v) as.2<0) := by + classical + induction P using Finset.induction_on with + | empty=>exact ⟨1,one_pos,fun _ _ _ _ hs=>False.elim (Finset.notMem_empty _ hs)⟩ + | @insert a P ha ih=> + obtain ⟨ε,hε,Hε⟩:=ih + obtain ⟨η,hη,Hη⟩:=scalar_sign_epsilon ((k+a.1 • v) a.2) (g a.2) + refine ⟨min ε η,lt_min hε hη,?_⟩ + intro δ hd he as has + rcases Finset.mem_insert.mp has with rfl|has + · have H:=Hη δ hd (lt_of_lt_of_le he (min_le_right _ _)) + simpa only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul,add_right_comm] + using And.intro H.1 H.2.1 + · exact Hε δ hd (lt_of_lt_of_le he (min_le_left _ _)) as has + +lemma exists_generic_offset_with_probes (T : Finset E) (r : E) + (P : Finset (ℝ×E)) (v k : Module.Dual ℝ E) (hk : k r=0) : + ∃h : Module.Dual ℝ E,GenericOffset T r v h ∧ ∀as∈P, + (0<(k+as.1 • v) as.2 → 0<(h+as.1 • v) as.2) ∧ + ((k+as.1 • v) as.2<0 → (h+as.1 • v) as.2<0) := by + classical + let W:=forbidden T r v + obtain ⟨g,hgr,hg⟩:=dual_avoid_in_annihilator r W + (fun w hw=>(Finset.mem_filter.mp hw).2) + obtain ⟨ε,hε,Hε⟩:=preserve_finite_signs W k g + obtain ⟨η,hη,Hη⟩:=preserve_finite_affine_signs P k g v + let δ:=min ε η/2 + have hd : 0<δ:=by dsimp [δ]; positivity + have hdε : δ<ε:=by dsimp [δ]; have :=min_le_left ε η; have :=lt_min hε hη; linarith + have hdη : δ<η:=by dsimp [δ]; have :=min_le_right ε η; have :=lt_min hε hη; linarith + have Havoid : ∀w∈W,(k+δ • g) w≠0:=by + intro w hw + have H:=Hε δ hd hdε w hw + rcases lt_trichotomy (k w) 0 with hz|hz|hz + · exact ne_of_lt (H.2.1 hz) + · exact H.2.2 hz (hg w hw) + · exact ne_of_gt (H.1 hz) + refine ⟨k+δ • g,⟨by simp [hk,hgr],?_,?_⟩,Hη δ hd hdη⟩ + · intro s hs hn + exact Havoid s (Finset.mem_filter.mpr ⟨Finset.mem_union_left _ hs,hn⟩) + · intro s hs t ht hn + exact Havoid _ (Finset.mem_filter.mpr ⟨Finset.mem_union_right _ + (Finset.mem_image.mpr ⟨(s,t),Finset.mem_product.mpr ⟨hs,ht⟩,rfl⟩),hn⟩) +lemma affine_event_between (u w a b : ℝ) (ha : u+a*w<0) (hb : 0h.val as.2+as.1*v as.2):= + ((ContinuousLinearMap.apply ℝ ℝ as.2).continuous.comp continuous_subtype_val).add continuous_const + by_cases hp : 0<(k+as.1 • v) as.2 <;> + by_cases hn : (k+as.1 • v) as.2<0 <;> + simp only [hp,hn,IsEmpty.forall_iff,forall_const,true_and,and_true] + · exact (isOpen_lt continuous_const hc).inter (isOpen_lt hc continuous_const) + · exact isOpen_lt continuous_const hc + · exact isOpen_lt hc continuous_const + · exact isOpen_univ + convert isOpen_biInter_finset (s:=P) (fun as _=>H as) using 1 + ext h; simp only [U,Set.mem_ofPred_eq,Set.mem_iInter] + have hnU : U.Nonempty:=by + let kc : E →L[ℝ] ℝ:=LinearMap.toContinuousLinearMap k + refine ⟨⟨kc,by change k r=0; exact hk⟩,?_⟩ + intro as _ + exact ⟨fun H=>H,fun H=>H⟩ + have Hd : Dense (⋂w∈W,{h:A|h.val w≠0}):=dense_biInter_of_isOpen + (fun w _=>isOpen_ne_fun ((ContinuousLinearMap.apply ℝ ℝ w).continuous.comp continuous_subtype_val) + continuous_const) hW (fun w hw=>dense_annihilator_avoid r w (hproper w hw)) + obtain ⟨h,hhU,hh⟩:=Hd.inter_open_nonempty U hU hnU + refine ⟨h.val.toLinearMap,by exact h.property,?_,?_⟩ + · change ∀w∈W,h.val w≠0 + simpa only [Set.mem_iInter,Set.mem_ofPred_eq] using hh + · exact hhU + +lemma exists_all_generic_offsets_with_probes (T : ℕ → Finset E) (r : E) + (P : Finset (ℝ×E)) (v k : Module.Dual ℝ E) (hk : k r=0) : + ∃h : Module.Dual ℝ E,(∀N,GenericOffset (T N) r v h) ∧ ∀as∈P, + (0<(k+as.1 • v) as.2 → 0<(h+as.1 • v) as.2) ∧ + ((k+as.1 • v) as.2<0 → (h+as.1 • v) as.2<0) := by + classical + let W : Set E:=⋃N,↑(forbidden (T N) r v) + have hW : W.Countable:=Set.countable_iUnion (fun N=>(forbidden (T N) r v).countable_toSet) + have hp : ∀w∈W,w∉Submodule.span ℝ {r}:=by + intro w hw + obtain ⟨N,hN⟩:=Set.mem_iUnion.mp hw + exact (Finset.mem_filter.mp hN).2 + obtain ⟨h,hr,havoid,H⟩:=countable_avoid_with_probes W hW r hp P v k hk + refine ⟨h,fun N=>⟨hr,?_,?_⟩,H⟩ + · intro s hs hn + exact havoid s (Set.mem_iUnion.mpr ⟨N,Finset.mem_filter.mpr + ⟨Finset.mem_union_left _ hs,hn⟩⟩) + · intro s hs t ht hn + exact havoid _ (Set.mem_iUnion.mpr ⟨N,Finset.mem_filter.mpr + ⟨Finset.mem_union_right _ (Finset.mem_image.mpr + ⟨(s,t),Finset.mem_product.mpr ⟨hs,ht⟩,rfl⟩),hn⟩⟩) + +end +end ElementaryPositivity.FiniteRayGeometry + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FinitePureMutation.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FinitePureMutation.lean new file mode 100644 index 0000000000000000000000000000000000000000..60d76f1514f8b2eae5a0848a8dc00341e4936d85 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FinitePureMutation.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.InfinityLaurentFinite +import OAI.Combinatorics.Chromatic.GradedAlgebra.PurePolynomialCoefficients + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries HahnSeries PowerSeriesAdjoint WallUnits +noncomputable section +lemma constantCoeff_inner_const_inv {A:Type*} [Ring A] (u:Aˣ) (f:PowerSeries A) : + constantCoeff (innerHom (Units.map (PowerSeries.C (R:=A)) u)⁻¹ f)= + innerHom u⁻¹ (constantCoeff f) := by + change constantCoeff (PowerSeries.C u.inv*f*PowerSeries.C u.val)=u.inv*constantCoeff f*u.val + rw [map_mul,map_mul,constantCoeff_C,constantCoeff_C] + +variable {M:Type*} [AddCommGroup M] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (k:M →+ ℤ) (p:M) (hp:k p=1) +local instance finitePureMutationRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance finitePureMutationAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance finitePureMutationAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance finitePureMutationNonUnitalSemiring : NonUnitalSemiring (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalSemiring +local instance finitePureMutationNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalNonAssocSemiring + +lemma expandFiberInfinity_lattice (F:Torus LaurentRay.vUnit Ω) : + expandFiberInfinity LaurentRay.vUnit Ω hΩ k p (embed LaurentRay.vUnit Ω hΩ k p hp F)= + latticeHahn LaurentRay.vUnit Ω (-k) F := by + apply HahnSeries.ext + funext j + apply Finsupp.ext + intro m + rw [expandFiberInfinity_embed_coeff LaurentRay.vUnit Ω hΩ k p hp,latticeHahn_coeff] + rfl + +lemma pureLaurentUnit_actual_val (q:M) : + (pureLaurentUnit LaurentRay.vUnit Ω hΩ q).val= + ofPowerSeries ℤ (Torus LaurentRay.vUnit Ω) (normalizedSimple Ω q) := by + change purePower LaurentRay.vUnit Ω hΩ q (shiftedElementary LaurentRay.vUnit 0)=_ + rw [purePower_eq,laurent_shiftedElementary_zero] + rfl +lemma pureLaurentUnit_actual_inv (q:M) : + ((pureLaurentUnit LaurentRay.vUnit Ω hΩ q)⁻¹).val= + ofPowerSeries ℤ (Torus LaurentRay.vUnit Ω) (invOfUnit (normalizedSimple Ω q) 1) := by + change purePower LaurentRay.vUnit Ω hΩ q (shiftedElementary LaurentRay.vUnit 0)⁻¹=_ + rw [purePower_eq,laurent_shiftedElementary_zero,normalizedSimple_inverse Ω hΩ] + +lemma inner_pure_hahn (q:M) (x:HahnSeries ℤ (Torus LaurentRay.vUnit Ω)) : + innerHom (pureLaurentUnit LaurentRay.vUnit Ω hΩ q) x=hahnAction (normalizedSimple Ω q) x := by + change (pureLaurentUnit LaurentRay.vUnit Ω hΩ q).val*x*((pureLaurentUnit LaurentRay.vUnit Ω hΩ q)⁻¹).val=_ + rw [pureLaurentUnit_actual_val,pureLaurentUnit_actual_inv] + rfl + +lemma expand_opposite_inverse_actual + (f:FiberTorus LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω)) : + expandFiberInfinity LaurentRay.vUnit Ω hΩ k p + (oppositeInverseActionHom LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω) f)= + innerHom (pureLaurentUnit LaurentRay.vUnit Ω hΩ (-p))⁻¹ + (expandFiberInfinity LaurentRay.vUnit Ω hΩ k p f) := by + have hq:∀n:ℕ,1-(↑(LaurentRay.vUnit^(-2:ℤ)):LaurentSeries ℚ)^(n+1)≠0:=by + intro n + rw [LaurentRay.vUnit_zpow] + exact UnitSelections.laurent_q_not_root n + have H:=completed_expand_opposite_inverse LaurentRay.vUnit Ω hΩ k p hq (PowerSeries.C f) + rw [completedOppositeInverseAction_eq,PowerSeries.map_C,PowerSeries.map_C] at H + have H0:=congrArg constantCoeff H + rw [constantCoeff_C,completedPureUnit,constantCoeff_inner_const_inv,PowerSeries.map_C,constantCoeff_C] at H0 + exact H0 + +include hΩ in +lemma finite_cut_hahn (F F':Torus LaurentRay.vUnit Ω) + (hF:embed LaurentRay.vUnit Ω hΩ k p hp F= + pureAction LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω) + (embed LaurentRay.vUnit Ω hΩ k p hp F')) : + hahnAction (normalizedSimple Ω (-p)) + (latticeHahn LaurentRay.vUnit Ω (-k) + (Torus.push LaurentRay.vUnit Ω Ω (mutationShear Ω p) (mutationShear_pairing Ω hΩ p) F))= + latticeHahn LaurentRay.vUnit Ω (-k) F' := by + have HC:=congrArg (fun g:FiberTorus LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω) →+* + FiberTorus LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω)=> + g (embed LaurentRay.vUnit Ω hΩ k p hp F')) + (rational_cut_identity LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω)) + change shearActionHom LaurentRay.vUnit _ _ + (pureAction LaurentRay.vUnit _ _ (embed LaurentRay.vUnit Ω hΩ k p hp F'))= + oppositeInverseActionHom LaurentRay.vUnit _ _ (embed LaurentRay.vUnit Ω hΩ k p hp F') at HC + rw [←hF,shearAction_embed LaurentRay.vUnit Ω hΩ k p hp F] at HC + have HE:=expand_opposite_inverse_actual Ω hΩ k p (embed LaurentRay.vUnit Ω hΩ k p hp F') + rw [←HC] at HE + have HH:=congrArg (innerHom (pureLaurentUnit LaurentRay.vUnit Ω hΩ (-p))) HE + rw [innerHom_cancel_inv,inner_pure_hahn,expandFiberInfinity_lattice Ω hΩ k p hp, + expandFiberInfinity_lattice Ω hΩ k p hp] at HH + exact HH + +include hΩ in +lemma finite_cut_actual (τ:M →+ ℤ) (hτ:τ (-p)=1) (F F':Torus LaurentRay.vUnit Ω) + (hF:embed LaurentRay.vUnit Ω hΩ k p hp F= + pureAction LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω) + (embed LaurentRay.vUnit Ω hΩ k p hp F')) (m:M) : + actualPolynomialAdjointCoefficient Ω τ (normalizedSimple Ω (-p)) + (Torus.push LaurentRay.vUnit Ω Ω (mutationShear Ω p) (mutationShear_pairing Ω hΩ p) F) m=F' m := by + have HH:=congrArg (fun x:HahnSeries ℤ (Torus LaurentRay.vUnit Ω)=>x.coeff ((-k) m) m) + (finite_cut_hahn Ω hΩ k p hp F F' hF) + rw [hahnAction_actual_coeff Ω hΩ,latticeHahn_coeff,ite_eq_left rfl] at HH + rw [actual_pure_order_independent Ω hΩ τ (-k) (-p) hτ (by simp [hp])] + exact HH +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRayGeometry.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRayGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..a098ac9be7dc09da0e28bc97340426cf1a809119 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRayGeometry.lean @@ -0,0 +1,242 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteSignCharts + +namespace OAI + +section +namespace ElementaryPositivity.FiniteRayGeometry +noncomputable section +open Module +variable {E : Type*} [AddCommGroup E] [Module ℝ E] + +lemma dual_avoid_in_annihilator (r : E) (W : Finset E) + (hW : ∀w∈W,w∉Submodule.span ℝ {r}) : + ∃g : Module.Dual ℝ E,g r=0 ∧ ∀w∈W,g w≠0 := by + let P:=Submodule.span ℝ {r} + let q:=P.mkQ + have H : ∀w : W,q w.val≠0:=by + intro w hw + exact hW w.val w.property ((Submodule.Quotient.mk_eq_zero P).mp hw) + obtain ⟨f,hf⟩:=Module.exists_dual_forall_apply_ne_zero (K:=ℝ) (fun w : W=>q w.val) H + refine ⟨f.comp q,?_,?_⟩ + · have hr : r∈P:=Submodule.subset_span (Set.mem_singleton r) + simp only [LinearMap.comp_apply,show q r=0 from (Submodule.Quotient.mk_eq_zero P).mpr hr,map_zero] + · intro w hw + exact hf ⟨w,hw⟩ + +lemma scalar_sign_epsilon (a b : ℝ) : ∃ε>0,∀δ:ℝ,0<δ → δ<ε → + (0False.elim (ha h)⟩ + · intro h; rw [abs_of_pos h] at H; nlinarith + · intro h; rw [abs_of_neg h] at H; nlinarith + +lemma preserve_finite_signs (S : Finset E) (k g : Module.Dual ℝ E) : + ∃ε>0,∀δ:ℝ,0<δ → δ<ε → ∀s∈S, + (0exact ⟨1,one_pos,fun _ _ _ _ hs=>False.elim (Finset.notMem_empty _ hs)⟩ + | @insert s S hs ih=> + obtain ⟨ε,he,Hε⟩:=ih + obtain ⟨η,hh,Hη⟩:=scalar_sign_epsilon (k s) (g s) + refine ⟨min ε η,lt_min he hh,?_⟩ + intro δ hd hδε x hx + rcases Finset.mem_insert.mp hx with rfl|hx + · exact Hη δ hd (lt_of_lt_of_le hδε (min_le_right _ _)) + · exact Hε δ hd (lt_of_lt_of_le hδε (min_le_left _ _)) x hx + +lemma generic_offset (r : E) (W S : Finset E) (k : Module.Dual ℝ E) + (hk : k r=0) (hW : ∀w∈W,w∉Submodule.span ℝ {r}) : + ∃h : Module.Dual ℝ E,h r=0 ∧ (∀w∈W,h w≠0) ∧ + ∀s∈S,(0v st.1 • st.2-v st.2 • st.1)).filter + (fun w=>w∉Submodule.span ℝ {r}) + +structure GenericOffset (S : Finset E) (r : E) (v h : Module.Dual ℝ E) : Prop where + on_ray : h r=0 + avoid : ∀s∈S,s∉Submodule.span ℝ {r} → h s≠0 + distinct : ∀s∈S,∀t∈S,v s • t-v t • s∉Submodule.span ℝ {r} → + h (v s • t-v t • s)≠0 + +lemma exists_generic_offset (S : Finset E) (r : E) (v k : Module.Dual ℝ E) + (hk : k r=0) : ∃h : Module.Dual ℝ E,GenericOffset S r v h ∧ + ∀s∈S,(0(Finset.mem_filter.mp hw).2) + refine ⟨h,⟨hr,?_,?_⟩,hS⟩ + · intro s hs hn + exact hW s (Finset.mem_filter.mpr ⟨Finset.mem_union_left _ hs,hn⟩) + · intro s hs t ht hn + exact hW _ (Finset.mem_filter.mpr ⟨Finset.mem_union_right _ + (Finset.mem_image.mpr ⟨(s,t),Finset.mem_product.mpr ⟨hs,ht⟩,rfl⟩),hn⟩) + +lemma GenericOffset.parallel_avoided {S : Finset E} {r : E} {v h : Module.Dual ℝ E} + (H : GenericOffset S r v h) {s : E} (hs : s∈S) (hn : s∉Submodule.span ℝ {r}) + (hv : v s=0) (a : ℝ) : (h+a • v) s≠0 := by + simpa only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul,hv,mul_zero,add_zero] + using H.avoid s hs hn + +lemma GenericOffset.joint_plane {S : Finset E} {r : E} {v h : Module.Dual ℝ E} + (H : GenericOffset S r v h) {s t : E} (hs : s∈S) (ht : t∈S) (hv : v s≠0) + (a : ℝ) (hsa : (h+a • v) s=0) (hta : (h+a • v) t=0) : + t∈Submodule.span ℝ {r,s} := by + classical + have hw : v s • t-v t • s∈Submodule.span ℝ {r}:=by + by_contra hn + apply H.distinct s hs t ht hn + simp only [map_sub,map_smul,smul_eq_mul] + simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] at hsa hta + have hs0 : h s = -a * v s := by linarith + have ht0 : h t = -a * v t := by linarith + rw [hs0,ht0] + ring + have hw' : v s • t-v t • s∈Submodule.span ℝ {r,s}:= + (Submodule.span_mono (by simp : ({r}:Set E)⊆{r,s})) hw + have hs' : s∈Submodule.span ℝ {r,s}:=Submodule.subset_span (by simp) + have Hst:= (Submodule.span ℝ {r,s}).add_mem hw' + ((Submodule.span ℝ {r,s}).smul_mem (v t) hs') + simp only [sub_add_cancel] at Hst + exact ((Submodule.span ℝ {r,s}).smul_mem_iff hv).mp Hst + +end +end ElementaryPositivity.FiniteRayGeometry + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (e : M →+ E) (he : Function.Injective e) (C : (I → ℤ) →+ M) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hdeg in +lemma positive_ray_of_mem_span (r p : M) (d n : ℕ) (hd : 0 < d) (hn : 0 < n) + (hr : HasRootDegree C d r) (hp : HasRootDegree C n p) + (H : e p∈Submodule.span ℝ {e r}) : OnPositiveRay r p := by + obtain ⟨a,ha⟩:=Submodule.mem_span_singleton.mp H + have HLa:=congrArg L ha + simp only [map_smul,smul_eq_mul,hdeg d r hr,hdeg n p hp] at HLa + refine ⟨d,n,hd,hn,he ?_⟩ + simp only [map_nsmul,←Nat.cast_smul_eq_nsmul ℝ] + rw [←ha,smul_smul] + congr 1 + nlinarith only [HLa] + +def lineEvents (S : Finset E) (v h : Module.Dual ℝ E) : Finset ℝ := by + classical + exact (S.filter (fun s => v s≠0)).image (fun s => -h s/v s) +lemma mem_lineEvents_iff (S : Finset E) (v h : Module.Dual ℝ E) (a : ℝ) : + a∈lineEvents S v h ↔ ∃s∈S,v s≠0 ∧ (h+a • v) s=0 := by + classical + constructor + · rintro ha + obtain ⟨s,hs,rfl⟩:=Finset.mem_image.mp ha + obtain ⟨hs,hn⟩:=Finset.mem_filter.mp hs + refine ⟨s,hs,hn,?_⟩ + simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] + field_simp + ring + · rintro ⟨s,hs,hn,H⟩ + apply Finset.mem_image.mpr + refine ⟨s,Finset.mem_filter.mpr ⟨hs,hn⟩,?_⟩ + apply (div_eq_iff hn).mpr + simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] at H + linarith + +def realRootsThrough (N : ℕ) : Finset E := by + classical + exact (rootsThrough C N).image e +omit [Module ℝ E] in +lemma realRoot_mem (N n : ℕ) (hn : n ≤ N) (m : M) (hm : HasRootDegree C n m) : + e m∈realRootsThrough e C N := by + classical + exact Finset.mem_image.mpr ⟨m,mem_rootsThrough C N n hn m hm,rfl⟩ +include he hdeg in +lemma line_generic (N d : ℕ) (r : M) (hd : 0 < d) (hr : HasRootDegree C d r) + (v h : Module.Dual ℝ E) (hv : v (e r)=0) + (H : GenericOffset (realRootsThrough e C N) (e r) v h) + (a : ℝ) (ha : a∉lineEvents (realRootsThrough e C N) v h) : + RayGeneric C N r ((h+a • v).toAddMonoidHom.comp e) := by + constructor + · change h (e r)+a*v (e r)=0 + rw [H.on_ray,hv,mul_zero,add_zero] + · intro n hn hnN m hm hm0 + have hmS:=realRoot_mem e C N n hnN m hm + by_cases hmP : e m∈Submodule.span ℝ {e r} + · exact positive_ray_of_mem_span e he C L hdeg r m d n hd hn hr hm hmP + · by_cases hvm : v (e m)=0 + · exact False.elim ((H.parallel_avoided hmS hmP hvm a) hm0) + · exact False.elim (ha ((mem_lineEvents_iff _ _ _ _).mpr ⟨e m,hmS,hvm,hm0⟩)) + +lemma real_line_signs (u w a b : ℝ) (hw : w≠0) (ha : a≠ -u/w) (hb : b≠ -u/w) + (H : a < -u/w ↔ b < -u/w) : + (0 < u+a*w → 0 < u+b*w) ∧ (u+a*w=0 → u+b*w=0) ∧ (u+a*w < 0 → u+b*w < 0) := by + have hz : u+(-u/w)*w=0:=by field_simp; ring + by_cases has : a < -u/w + · have hbs:=H.mp has + rcases lt_or_gt_of_ne hw with hw|hw + · have ha' : 0 < u+a*w:=by nlinarith + have hb' : 0 < u+b*w:=by nlinarith + exact ⟨fun _ => hb',fun h => by linarith,fun h => by linarith⟩ + · have ha' : u+a*w < 0:=by nlinarith + have hb' : u+b*w < 0:=by nlinarith + exact ⟨fun h => by linarith,fun h => by linarith,fun _ => hb'⟩ + · have hza : -u/w < a:=lt_of_le_of_ne (le_of_not_gt has) (Ne.symm ha) + have hzb : -u/w < b:=lt_of_le_of_ne (le_of_not_gt (fun hh => has (H.mpr hh))) (Ne.symm hb) + rcases lt_or_gt_of_ne hw with hw|hw + · have ha' : u+a*w < 0:=by nlinarith + have hb' : u+b*w < 0:=by nlinarith + exact ⟨fun h => by linarith,fun h => by linarith,fun _ => hb'⟩ + · have ha' : 0 < u+a*w:=by nlinarith + have hb' : 0 < u+b*w:=by nlinarith + exact ⟨fun _ => hb',fun h => by linarith,fun h => by linarith⟩ +lemma line_cell_signs (S : Finset E) (v h : Module.Dual ℝ E) (a b : ℝ) + (ha : a∉lineEvents S v h) (hb : b∉lineEvents S v h) + (H : ∀z∈lineEvents S v h,a < z ↔ b < z) (s : E) (hs : s∈S) : + (0 < (h+a • v) s → 0 < (h+b • v) s) ∧ + ((h+a • v) s=0 → (h+b • v) s=0) ∧ ((h+a • v) s < 0 → (h+b • v) s < 0) := by + classical + by_cases hw : v s=0 + · simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul,hw,mul_zero,add_zero] + exact ⟨id,id,id⟩ + · have hz : -h s/v s∈lineEvents S v h:=Finset.mem_image.mpr + ⟨s,Finset.mem_filter.mpr ⟨hs,hw⟩,rfl⟩ + exact real_line_signs (h s) (v s) a b hw (fun he => ha (he ▸ hz)) + (fun he => hb (he ▸ hz)) (H _ hz) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRefinementImport.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRefinementImport.lean new file mode 100644 index 0000000000000000000000000000000000000000..77586d59e1a6ec3a01f123681d1f8dde7cd7c06e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRefinementImport.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ComparisonRefinement + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (δ k : M →+ ℤ) (p : M) (hp : k p=1) (hδ : δ p=0) (B : ℕ) +local instance finiteRefinementImportRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance finiteRefinementImportAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance finiteRefinementImportAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance finiteRefinementImportNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance finiteRefinementImportNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +lemma finite_refinement_import_positive + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (D : ℕ) (l : List (ComparisonCrossing v Ω δ k B)) + (href : ∀N,∃l',WordRefines v Ω δ k B D l l' ∧ ∀n≤N, + coeff n (comparisonWordOld v Ω hΩ δ k p hp hδ B l').val.val=coeff n 1) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) + (F : PowerSeries (PowerSeries (Torus v Ω))) + (hf : PowerSeries.map (expandFiber v Ω hΩ k p) f= + PowerSeries.map (HahnSeries.ofPowerSeries ℤ (Torus v Ω)) F) : + coeff D (comparisonWordAction v Ω hΩ δ k p hp B l f)=coeff D f := by + apply expandFiber_injective v Ω hΩ k p hp + apply HahnSeries.ext + funext z + have HX (N : ℕ) (l' : List (ComparisonCrossing v Ω δ k B)) + (hR : WordRefines v Ω δ k B D l l') : + (expandFiber v Ω hΩ k p (coeff D (comparisonWordAction v Ω hΩ δ k p hp B l f))).coeff z= + (coeff D (oldLaurent v Ω δ k (comparisonWordOld v Ω hΩ δ k p hp hδ B l').val.val* + PowerSeries.map (HahnSeries.ofPowerSeries ℤ (Torus v Ω)) F* + oldLaurent v Ω δ k (comparisonWordOld v Ω hΩ δ k p hp hδ B l').inv.val)).coeff z := by + rw [hR.action v Ω hΩ δ k p hp B f f (fun _ _=>rfl) D le_rfl] + have H:=congrArg (fun a : PowerSeries (HahnSeries ℤ (Torus v Ω))=>(coeff D a).coeff z) + (comparisonWord_expansion v Ω hΩ δ k p hp hδ B hq l' f) + simp only [coeff_map] at H + rw [hf] at H + exact H + have HF:=congrArg (fun a : PowerSeries (HahnSeries ℤ (Torus v Ω))=>(coeff D a).coeff z) hf + simp only [coeff_map] at HF + rw [HF] + rcases le_or_gt 0 z with hz|hz + · lift z to ℕ using hz with e he + obtain ⟨l',hR,hN⟩:=href (D+e) + rw [HX (D+e) l' hR,HahnSeries.ofPowerSeries_apply_coeff] + apply oldLaurent_inner_through v Ω δ k (comparisonWordOld v Ω hΩ δ k p hp hδ B l') (D+e) hN + (oldUnit_inverse_congr v Ω δ k _ 1 (D+e) hN) F D e le_rfl + · obtain ⟨l',hR,hN⟩:=href 0 + rw [HX 0 l' hR,hahn_power_negative v Ω _ z hz] + unfold oldLaurent + rw [←map_mul,←map_mul,coeff_map,hahn_power_negative v Ω _ z hz] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRefinementImportAll.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRefinementImportAll.lean new file mode 100644 index 0000000000000000000000000000000000000000..61e77ce89c07a8a824d085dcc6e5b5d1204d036d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteRefinementImportAll.lean @@ -0,0 +1,184 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationSimpleIncoming +import OAI.Combinatorics.Chromatic.Walls.ComparisonLine +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentBiTruncation + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (δ k : M →+ ℤ) (p : M) (hp : k p=1) (hδ : δ p=0) (B : ℕ) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +lemma finite_refinement_import + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (D : ℕ) (l : List (ComparisonCrossing v Ω δ k B)) + (href : ∀N,∃l',WordRefines v Ω δ k B D l l' ∧ ∀n≤N, + coeff n (comparisonWordOld v Ω hΩ δ k p hp hδ B l').val.val=coeff n 1) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + coeff D (comparisonWordAction v Ω hΩ δ k p hp B l f)=coeff D f := by + apply expandFiber_injective v Ω hΩ k p hp + apply HahnSeries.ext + funext z + obtain ⟨N,hN⟩:=BiTruncation.inner_eventually + (PowerSeries.map (expandFiber v Ω hΩ k p) f) D z + obtain ⟨l',hR,hloop⟩:=href N + rw [hR.action v Ω hΩ δ k p hp B f f (fun _ _=>rfl) D le_rfl] + have HW:=congrArg (fun a : PowerSeries (HahnSeries ℤ (Torus v Ω))=>(coeff D a).coeff z) + (comparisonWord_expansion v Ω hΩ δ k p hp hδ B hq l' f) + simp only [coeff_map] at HW + rw [HW] + let u:=comparisonWordOld v Ω hΩ δ k p hp hδ B l' + have HU : BiTruncation.Through N (biRegrade v Ω δ k u.val.val) 1 := by + simpa only [biRegrade_one] using biRegrade_through v Ω δ k N hloop + have HI : BiTruncation.Through N (biRegrade v Ω δ k u.inv.val) 1 := by + simpa [biRegrade_one] using biRegrade_through v Ω δ k N + (oldUnit_inverse_congr v Ω δ k u 1 N hloop) + have HE:=hN _ _ HU HI + change (coeff D (oldLaurent v Ω δ k u.val.val* + PowerSeries.map (expandFiber v Ω hΩ k p) f*oldLaurent v Ω δ k u.inv.val)).coeff z=_ + simpa only [oldLaurent,coeff_map] using HE + +lemma all_finite_refinements_import + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (l : List (ComparisonCrossing v Ω δ k B)) + (href : ∀D N,∃l',WordRefines v Ω δ k B D l l' ∧ ∀n≤N, + coeff n (comparisonWordOld v Ω hΩ δ k p hp hδ B l').val.val=coeff n 1) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + comparisonWordAction v Ω hΩ δ k p hp B l f=f := by + apply PowerSeries.ext + intro D + exact finite_refinement_import v Ω hΩ δ k p hp hδ B hq D l (href D) f +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) + +def actualLineWord (lo hi : ℝ) (N : ℕ) : + List (ComparisonCrossing LaurentRay.vUnit Ω (nonpDegree coord pc) (pureDegree coord pc) + (mutationSize Ω C pc+1)) := + (intervalEventList C e v k lo hi N).map + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H) + +lemma actualLineWord_refines (lo hi : ℝ) (D A N : ℕ) + (hA : 1≤A) (hDA : (mutationSize Ω C pc+1)*D≤A) (hAN : A≤N) : + WordRefines LaurentRay.vUnit Ω (nonpDegree coord pc) (pureDegree coord pc) + (mutationSize Ω C pc+1) D + (actualLineWord Ω C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi A) + (actualLineWord Ω C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N) := by + classical + unfold actualLineWord + rw [←intervalEventList_filter C e v k lo hi hAN] + apply filter_word_refines + intro a ha hn + have hnot : a∉intervalLineEvents C e v k lo hi A:=of_decide_eq_false hn + exact (actualLineLetter_high Ω C coord hcoord pc e he S hS hcomp L hdeg v k H + a A hA (event_not_retained C e v k lo hi a ha hnot)).mono _ _ _ _ _ hDA + +lemma actualLineWord_refinements (lo hi : ℝ) (D : ℕ) : + ∀N,WordRefines LaurentRay.vUnit Ω (nonpDegree coord pc) (pureDegree coord pc) + (mutationSize Ω C pc+1) D + (actualLineWord Ω C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi + (max 1 ((mutationSize Ω C pc+1)*D))) + (actualLineWord Ω C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi + (max N (max 1 ((mutationSize Ω C pc+1)*D)))) := by + intro N + exact actualLineWord_refines Ω C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi + D _ _ (le_max_left _ _) (le_max_right _ _) (le_max_right _ _) +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry WallUnits +noncomputable section +variable {A : Type*} [Ring A] +def orientPowerSeries (forward : Bool) (f : PowerSeries A) : PowerSeries A := + if forward then f else PowerSeries.invOfUnit f 1 +lemma orientPowerSeries_trivial (forward : Bool) (f : PowerSeries A) (N : ℕ) + (hf : ∀n≤N,coeff n f=coeff n 1) : + ∀n≤N,coeff n (orientPowerSeries forward f)=coeff n 1 := by + cases forward + · have hi : PowerSeries.invOfUnit (1 : PowerSeries A) 1=1 := by + simpa only [mul_one] using (PowerSeries.invOfUnit_mul (1 : PowerSeries A) 1 (by simp)) + simpa only [orientPowerSeries,Bool.false_eq_true,ite_false,hi] using + PowerSeriesAdjoint.inverse_coeff_congr f 1 N hf + · exact hf + +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +def mutatedLineFactor (a : ℝ) : PowerSeries (Torus LaurentRay.vUnit Ω) := by + classical + exact if ha : ∃N,a∈lineEvents (realRootsThrough e C N) v k then + if (k+a • v) (e (simpleRoot C pc))=0 then + orientPowerSeries (!(decide (v (e (simpleRoot C pc))<0))) + (normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) pc)) + else + let data:=lineRayData C e he L hdeg v k H a ha + let pos:=decide (0<(k+a • v) (e (simpleRoot C pc))) + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit + (orientPowerSeries (decide (v (e data.root)<0)) + (chartZero LaurentRay.vUnit Ω C ((k+a • v).toAddMonoidHom.comp e) + (simpleTotalTransport Ω C)).val) + else 1 + +lemma mutatedLineFactor_high (D N : ℕ) (hN : 1≤N) + (hDN : (mutationSize Ω C pc+1)*D≤N) (a : ℝ) + (ha : a∉lineEvents (realRootsThrough e C N) v k) : + ∀n≤D,coeff n (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H a)=coeff n 1 := by + classical + unfold mutatedLineFactor + split + · next hevent=> + split + · next hp=> + exact False.elim (ha (lineEvents_mono (realRootsThrough_mono C e hN) v k + (RationalFiber.line_cut_event C pc e L hdeg v k H a hp))) + · have hf:=line_chart_trivial C e L hdeg LaurentRay.vUnit Ω (simpleTotalTransport Ω C) N v k (H N) a ha + intro n hn + rw [←mutationCompletion_one Ω hΩ C coord pc _ LaurentRay.vUnit] + exact mutationCompletion_congr_through Ω hΩ C coord pc _ LaurentRay.vUnit _ _ n N + ((Nat.mul_le_mul_left _ hn).trans hDN) (orientPowerSeries_trivial _ _ N hf) + · exact fun _ _=>rfl + +def mutatedLineProduct (lo hi : ℝ) (N : ℕ) : PowerSeries (Torus LaurentRay.vUnit Ω) := + ((intervalEventList C e v k lo hi N).map (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H)).prod +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteReorderingEnergy.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteReorderingEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..c18de8d876c7b9297fd49c65e5eccb43f1165d3d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteReorderingEnergy.lean @@ -0,0 +1,199 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.EnergyLaurentSeries +import OAI.Combinatorics.Chromatic.Shuffle.InputTorusEnergy + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +attribute [local instance] Classical.propDecidable + +lemma card_fibres_injective_regrade {X Y : Type*} (f : X → ℤ) (g : Y → ℤ) + (n : ℤ → ℤ) (hn : Function.Injective n) + (h : ∀ k,Nat.card {x : X // f x=k}=Nat.card {y : Y // g y=k}) (e : ℤ) : + Nat.card {x : X // n (f x)=e}=Nat.card {y : Y // n (g y)=e} := by + by_cases H : ∃ k,n k=e + · obtain ⟨k,hk⟩:=H + let ex : {x : X // n (f x)=e} ≃ {x : X // f x=k} := + Equiv.subtypeEquivRight (fun x=>by rw [←hk,hn.eq_iff]) + let ey : {y : Y // n (g y)=e} ≃ {y : Y // g y=k} := + Equiv.subtypeEquivRight (fun y=>by rw [←hk,hn.eq_iff]) + rw [Nat.card_congr ex,Nat.card_congr ey] + exact h k + · let : IsEmpty {x : X // n (f x)=e} := ⟨fun x=>H ⟨f x.val,x.property⟩⟩ + let : IsEmpty {y : Y // n (g y)=e} := ⟨fun y=>H ⟨g y.val,y.property⟩⟩ + simp + +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀ i,0stringStartParameter a κ c η hc (slope c η d) j-2*j.2.1)).sum + +lemma stringBlockEnergy_normalized (d : I → ℕ) (i : StringBlockIndex a c η hc d) : + stringBlockEnergy a κ c η hc d i=normalizedEnergy a κ d i.1 := by + have H:=stringWordEnergy a κ c η hc (slope c η d) i.2.2.val + rw [i.2.2.property] at H + exact H.symm + +noncomputable def hnStringEnergy : (l : List (I → ℕ)) → HNStringIndex a c η hc l → ℤ + | [],_ => 0 + | d::l,i => stringBlockEnergy a κ c η hc d i.1+hnStringEnergy l i.2+ + (eulerForm a d l.sum-eulerForm a l.sum d) + +lemma hnStringEnergy_normalized (l : List (I → ℕ)) (i : HNStringIndex a c η hc l) : + hnStringEnergy a κ c η hc l i=normalizedEnergy a κ l.sum (hnStringDegree a c η hc l i) := by + induction l with + | nil => simp [hnStringEnergy,hnStringDegree,normalizedEnergy,eulerForm] + | cons d l ih => + rcases i with ⟨i,j⟩ + change stringBlockEnergy a κ c η hc d i+hnStringEnergy a κ c η hc l j+ + (eulerForm a d l.sum-eulerForm a l.sum d)=_ + rw [stringBlockEnergy_normalized,ih] + exact (normalizedEnergy_product a κ d l.sum i.1 (hnStringDegree a c η hc l j)).symm + +omit [DecidableEq I] in +lemma normalizedEnergy_injective (d : I → ℕ) : Function.Injective (normalizedEnergy a κ d) := by + intro x y h + unfold normalizedEnergy at h + omega + +abbrev OutputEnergyCoefficient (d : I → ℕ) (e : ℤ) := + {i : Σ l : HNIndex c η d,HNStringIndex a c η hc l.val // hnStringEnergy a κ c η hc i.1.val i.2=e} + +theorem finiteReordering_energyCoefficient (ε : I → Bool) + (ha : ∀ i,a i i=elementaryDiagonal ε i) (d : I → ℕ) (e : ℤ) : + Nat.card {x : InputIndexLists ε d // inputTorusEnergy a κ ε d x=e}= + Nat.card (OutputEnergyCoefficient a κ c η hc d e) := by + let ex : {x : SortedPackExponent d // normalizedEnergy a κ d (sortedPackDegree d x)=e} ≃ + {x : InputIndexLists ε d // inputTorusEnergy a κ ε d x=e} := + (inputListEquiv ε d).subtypeEquiv (by intro x; rw [inputListEnergy_normalized a κ ε d ha]) + let ey : OutputEnergyCoefficient a κ c η hc d e ≃ + {i : Σ l : HNIndex c η d,HNStringIndex a c η hc l.val // + normalizedEnergy a κ d (hnStringDegree a c η hc i.1.val i.2)=e} := + Equiv.subtypeEquivRight (by + intro i + rw [hnStringEnergy_normalized,i.1.property.1]) + rw [←Nat.card_congr ex,Nat.card_congr ey] + exact card_fibres_injective_regrade _ _ _ (normalizedEnergy_injective a κ d) + (finiteStringReordering_coefficient a c η hc d) e +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.RawShuffle +open ElementaryPositivity.SlopeArithmetic +attribute [local instance] Classical.propDecidable +universe u + +lemma finite_injective_regrade {X : Type*} (f : X → ℤ) + (hf : ∀k,Finite {x : X // f x=k}) (n : ℤ → ℤ) + (hn : Function.Injective n) (e : ℤ) : Finite {x : X // n (f x)=e} := by + classical + by_cases H : ∃k,n k=e + · obtain ⟨k,hk⟩:=H + let := hf k + let E : {x : X // n (f x)=e} ≃ {x : X // f x=k} := + Equiv.subtypeEquivRight (fun _=>by rw [←hk,hn.eq_iff]) + exact Finite.of_equiv _ E.symm + · let : IsEmpty {x : X // n (f x)=e} := ⟨fun x=>H ⟨f x.val,x.property⟩⟩ + infer_instance + +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀ i,0(sortedPackDegree d i:ℤ)) (componentS d) (packOrbitBasis_component d) k + +omit [DecidableEq I] in +lemma inputEnergy_admissible (ε : I → Bool) + (ha : ∀i,a i i=elementaryDiagonal ε i) (d : I → ℕ) : + EnergyLaurent.Admissible (inputTorusEnergy a κ ε d) := by + have he (x : InputIndexLists ε d) : inputTorusEnergy a κ ε d x= + normalizedEnergy a κ d (sortedPackDegree d ((inputListEquiv ε d).symm x)) := by + simpa using inputListEnergy_normalized a κ ε d ha ((inputListEquiv ε d).symm x) + constructor + · refine ⟨inputShift a κ d-eulerForm a d d,fun x=>?_⟩ + rw [he] + unfold normalizedEnergy + have H : 0≤(sortedPackDegree d ((inputListEquiv ε d).symm x):ℤ) := by positivity + omega + · intro e + let E : {x : SortedPackExponent d // normalizedEnergy a κ d (sortedPackDegree d x)=e} ≃ + {x : InputIndexLists ε d // inputTorusEnergy a κ ε d x=e} := + (inputListEquiv ε d).subtypeEquiv (by intro x; rw [inputListEnergy_normalized a κ ε d ha]) + let := finite_injective_regrade (fun x : SortedPackExponent d=>(sortedPackDegree d x:ℤ)) + (sortedPackDegree_finite d) (normalizedEnergy a κ d) (normalizedEnergy_injective a κ d) e + exact Finite.of_equiv _ E + +lemma hnStringDegree_nonneg (d : I → ℕ) + (x : Σ l : HNIndex c η d,HNStringIndex a c η hc l.val) : + 0≤hnStringDegree a c η hc x.1.val x.2 := by + by_contra H + let k := hnStringDegree a c η hc x.1.val x.2 + have hk : k<0 := lt_of_not_ge H + let : IsEmpty {i : SortedPackExponent d // (sortedPackDegree d i:ℤ)=k} := + ⟨fun i=>by + have hi:=i.property + have hn : 0≤(sortedPackDegree d i.val:ℤ) := Int.natCast_nonneg _ + omega⟩ + let := hnStringCoefficient_finite a c η hc d k + let : Nonempty (HNStringCoefficient a c η hc d k) := ⟨⟨x,rfl⟩⟩ + have hpos : 0 + hnStringEnergy a κ c η hc x.1.val x.2) := by + constructor + · refine ⟨inputShift a κ d-eulerForm a d d,fun x=>?_⟩ + dsimp only + rw [hnStringEnergy_normalized,x.1.property.1] + have H:=hnStringDegree_nonneg a c η hc d x + unfold normalizedEnergy + omega + · intro e + let := finite_injective_regrade + (fun x : Σ l : HNIndex c η d,HNStringIndex a c η hc l.val=> + hnStringDegree a c η hc x.1.val x.2) + (hnStringCoefficient_finite a c η hc d) (normalizedEnergy a κ d) + (normalizedEnergy_injective a κ d) e + let E : OutputEnergyCoefficient a κ c η hc d e ≃ + {x : Σ l : HNIndex c η d,HNStringIndex a c η hc l.val // + normalizedEnergy a κ d (hnStringDegree a c η hc x.1.val x.2)=e} := + Equiv.subtypeEquivRight (fun x=>by rw [hnStringEnergy_normalized,x.1.property.1]) + exact Finite.of_equiv _ E.symm + +noncomputable def inputReorderingSeries (ε : I → Bool) + (ha : ∀i,a i i=elementaryDiagonal ε i) (d : I → ℕ) : LaurentSeries ℚ := + EnergyLaurent.series (inputTorusEnergy a κ ε d) (inputEnergy_admissible a κ ε ha d) + +noncomputable def outputReorderingSeries (d : I → ℕ) : LaurentSeries ℚ := + EnergyLaurent.series + (fun x : Σ l : HNIndex c η d,HNStringIndex a c η hc l.val=> + hnStringEnergy a κ c η hc x.1.val x.2) + (outputEnergy_admissible a κ c η hc d) + +theorem finiteReordering_laurent (ε : I → Bool) + (ha : ∀i,a i i=elementaryDiagonal ε i) (d : I → ℕ) : + inputReorderingSeries a κ ε ha d=outputReorderingSeries a κ c η hc d := by + apply EnergyLaurent.series_eq_of_cards + exact finiteReordering_energyCoefficient a κ c η hc ε ha d + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteSignCharts.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteSignCharts.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa3841578405f7a2b7a59d4d1d95d50471adc42c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteSignCharts.lean @@ -0,0 +1,156 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PlanarJointFactorization +import OAI.Combinatorics.Chromatic.Walls.IsolatedPositivePlane + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesSplit RootTruncation +noncomputable section +variable {R M I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +omit [Algebra ℚ R] in +lemma chartZero_congr_through (h : M →+ ℝ) (F G : CompletedPositive v Ω C) (N : ℕ) + (he : ∀n ≤ N,coeff n F.val=coeff n G.val) : + ∀n ≤ N,coeff n (chartZero v Ω C h F).val=coeff n (chartZero v Ω C h G).val := by + intro n hn + exact zero_coeff_congr _ _ _ _ n (fun j hj => he j (hj.trans hn)) +omit [Algebra ℚ R] in +lemma chart_sign_congr_through (h k : M →+ ℝ) (F : CompletedPositive v Ω C) (N : ℕ) + (hs : ∀n,0 < n → n ≤ N → ∀m,HasRootDegree C n m → + (0 < h m → 0 < k m) ∧ (h m=0 → k m=0) ∧ (h m < 0 → k m < 0)) : + ∀n ≤ N,coeff n (chartZero v Ω C h F).val=coeff n (chartZero v Ω C k F).val := by + have H:=chart_three_support v Ω C h F + have HU:=chart_three_truncated_unique v Ω C k F + (chartPositive v Ω C h F).val (chartZero v Ω C h F).val (chartNegative v Ω C h F).val N + (chartPositive v Ω C h F).property.1 (chartZero v Ω C h F).property.1 + (chartNegative v Ω C h F).property.1 (chart_three_factorization v Ω C h F) + (fun n hn m hm => (hs (n+1) (by omega) hn m + (chart_root_of_ne v Ω C _ _ _ hm)).1 (H.1 n m hm)) + (fun n hn m hm => (hs (n+1) (by omega) hn m + (chart_root_of_ne v Ω C _ _ _ hm)).2.1 (H.2.1 n m hm)) + (fun n hn m hm => (hs (n+1) (by omega) hn m + (chart_root_of_ne v Ω C _ _ _ hm)).2.2 (H.2.2 n m hm)) + exact fun n hn => (HU n hn).2.1 + +def RayGeneric (N : ℕ) (r : M) (h : M →+ ℝ) : Prop := + h r=0 ∧ ∀n,0 < n → n ≤ N → ∀m,HasRootDegree C n m → h m=0 → OnPositiveRay r m +lemma RayGeneric.mono {N K : ℕ} {r : M} {h : M →+ ℝ} + (H : RayGeneric C N r h) (hK : K ≤ N) : RayGeneric C K r h := + ⟨H.1,fun n hn hN m hm h0 => H.2 n hn (hN.trans hK) m hm h0⟩ +omit [Algebra ℚ R] in +lemma RayGeneric.ray_supported {N : ℕ} {r : M} {h : M →+ ℝ} + (H : RayGeneric C N r h) (F : CompletedPositive v Ω C) : + ∀n,0 < n → n ≤ N → SupportedOn v Ω (OnPositiveRay r) + (coeff n (chartZero v Ω C h F).val) := by + intro n hn hN m hm + by_contra hx + have hr:=chart_root_of_ne v Ω C _ _ m hx + cases n with + | zero => omega + | succ n => exact hm (H.2 (n+1) hn hN m hr ((chart_three_support v Ω C h F).2.1 n m hx)) +end +section Closure +open PowerSeries RootTruncation +noncomputable section +variable {M : Type*} [AddCommGroup M] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) +lemma RootClosedThrough.reduce {N K : ℕ} {A : Set (PowerSeries (Torus v Ω))} + {F : PowerSeries (Torus v Ω)} (H : RootClosedThrough v Ω N A F) (hK : K ≤ N) : + RootClosedThrough v Ω K A F := by + intro T + obtain ⟨G,hG,hagree⟩:=rootClosedThrough_approx_exists v Ω H T + refine ⟨cut K G,⟨G,hG,rfl⟩,?_⟩ + intro t ht + simp only [coeff_cut] + by_cases hn : t.1 ≤ K + · simp only [hn,ite_true] + have Ht:=hagree t ht + simpa only [coeff_cut,show t.1 ≤ N from hn.trans hK,ite_true] using Ht + · simp only [hn,ite_false]; exact LaurentPrecision.agrees_refl _ _ +end +end Closure +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesSplit RootTruncation WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in +theorem positive_joint_transport (n dr : ℕ) (r : M) (s : E) + (hdr : 0 < dr) (hrd : HasRootDegree C dr r) (hrs : B (e r) s≠0) + (F : CompletedPositive LaurentRay.vUnit Ω C) + (hF : ∀j,coeff j F.val∈supportedSubring LaurentRay.vUnit Ω (planeRoots e (e r) s)) + (hincoming : ∀p d,0 < d → d ≤ n+1 → HasRootDegree C d p → p∈planeRoots e (e r) s → + RootClosedThrough LaurentRay.vUnit Ω (if Ω p r=0 then n+1 else n) + (literalRootProducts Ω C (OnPositiveRay p)) + (chartZero LaurentRay.vUnit Ω C (incomingCovector Ω p) F).val) : + RootClosedThrough LaurentRay.vUnit Ω (n+1) (literalRootProducts Ω C (OnPositiveRay r)) + (chartZero LaurentRay.vUnit Ω C (-incomingCovector Ω r) F).val := by + classical + have hr : 0 < L (e r):=by rw [hdeg dr r hrd]; exact_mod_cast hdr + have hΩ : ∀m,Ω m m=0:=by + intro m; have H:=hB (e m); rw [hcomp] at H; exact_mod_cast H + obtain ⟨l,hl,hpair,hRay,hfact⟩:=planar_joint_factorization LaurentRay.vUnit Ω C e he B hB hcomp L hdeg + (e r) s hr hrs F hF (n+1) + let V:=planeRoots e (e r) s + let h : M →+ ℝ:= -incomingCovector Ω r + let Lm : M →+ ℝ:=L.toAddMonoidHom.comp e + let J (p : M):=chartZero LaurentRay.vUnit Ω C (incomingCovector Ω p) F + have hpP : ∀p∈l,e p∈Submodule.span ℝ {e r,s}:=by + intro p hp; obtain ⟨d,hd,hdN,hdp,hpP⟩:=hl p hp; exact hpP + have hpL : ∀p∈l,0 < Lm p:=by + intro p hp; obtain ⟨d,hd,hdN,hdp,hpP⟩:=hl p hp + change 0 < L (e p); rw [hdeg d p hdp]; exact_mod_cast hd + have hplane : ∀p∈V,∀q∈V,(Ω p q:ℝ)=(-1/L (e r))*(h p*Lm q-Lm p*h q):=by + intro p hp q hq + have HH:=PlanarRayOrder.plane_determinant B hB L (e r) s (e p) (e q) hp hq + simp only [hcomp] at HH + change (Ω p q:ℝ)=(-1/L (e r))* (-(Ω p r:ℝ)*L (e q)-L (e p)* -(Ω q r:ℝ)) + field_simp [ne_of_gt hr] + nlinarith only [HH] + have H:=isolated_positive_plane Ω C hΩ Lm h V (-1/L (e r)) hplane n l + (fun p => decide (Ω p r=0)) (fun p => OnPositiveRay p) J + (fun p hp => by + obtain ⟨d,hd,hdN,hdp,hpP⟩:=hl p hp + simpa only [decide_eq_true_eq,J] using hincoming p d hd hdN hdp hpP) + (fun p hp a b ha hb => ha.add hb) + (fun p hp a ha => ⟨ha.mem_submodule e _ (hpP p hp), (ha.eval Lm).1.mpr (hpL p hp)⟩) + (fun p hp a b ha hb => le_of_eq (ha.pair_zero Ω hb (hΩ p)).symm) + (hpair.imp (fun {a b} hab p q hp hq => hp.pair_nonneg Ω hq hab.le)) + (fun p hp hact a ha => by + have hn : Ω p r≠0:=by simpa only [decide_eq_false_iff_not] using hact + intro hz + have hz' : incomingCovector Ω r a=0:=by simpa only [h,AddMonoidHom.neg_apply,neg_eq_zero] using hz + have hz'' := (ha.eval (incomingCovector Ω r)).2.1.mp hz' + change (Ω p r:ℝ)=0 at hz'' + exact hn (by exact_mod_cast hz'')) + (fun p hp a ha => by + by_contra hh + exact ha (hRay p hp n (by omega) a hh)) + have Hn:=H.mono LaurentRay.vUnit Ω (literalRootProducts_allowed_mono Ω C _ (OnPositiveRay r) (by + intro d hd p hp hpV + have hz : B (e p) (e r)=0:=by + rw [hcomp] + have Hz:=hpV.2 + change -(Ω p r:ℝ)=0 at Hz + exact neg_eq_zero.mp Hz + exact positive_ray_of_pairing_zero e he B hB L (e r) s C hdeg hrs p r d dr hd hdr hp hrd + hpV.1 (Submodule.subset_span (by simp)) hz)) + apply Hn.congr LaurentRay.vUnit Ω + intro j hj + exact zero_coeff_congr _ _ _ _ j (fun i hi => (hfact i (hi.trans hj)).symm) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteStringReordering.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteStringReordering.lean new file mode 100644 index 0000000000000000000000000000000000000000..99dc28bb682a8600a808d955f330f9767c51322a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteStringReordering.lean @@ -0,0 +1,144 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNHilbert +import OAI.Combinatorics.Chromatic.Shuffle.PrimitiveStringBounds +import OAI.Combinatorics.Chromatic.Shuffle.PackOrbitBasis + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic +attribute [local instance] Classical.propDecidable +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0by + letI := slopeStringCoefficient_finite a c η hc (slope c η d) d hd rfl k + exact (Finite.equivFinOfCardEq (slopeStringHilbert_coefficient a c η hc + (slope c η d) d hd rfl k).symm).symm) + +lemma homogeneousBStringEquiv_degree (d : I → ℕ) (hd : d≠0) (i : HomogeneousBIndex a c η d) : + (homogeneousBStringEquiv a c η hc d hd i).1=i.1 := rfl + +def HNStringIndex : List (I → ℕ) → Type u + | [] => ULift.{u} Unit + | d::l => StringBlockIndex a c η hc d × HNStringIndex l + +def hnStringDegree : (l : List (I → ℕ)) → HNStringIndex a c η hc l → ℤ + | [],_ => 0 + | d::l,i => i.1.1+hnStringDegree l i.2-eulerForm a d l.sum + +noncomputable def hnStringEquiv : (l : List (I → ℕ)) → (∀ d∈l,d≠0) → + HNBasisIndex a c η l ≃ HNStringIndex a c η hc l + | [],_ => Equiv.ulift.symm + | d::l,h => Equiv.prodCongr (homogeneousBStringEquiv a c η hc d (h d (by simp))) + (hnStringEquiv l (fun e he=>h e (List.mem_cons_of_mem d he))) + +lemma hnStringEquiv_degree (l : List (I → ℕ)) (h : ∀ d∈l,d≠0) (i : HNBasisIndex a c η l) : + hnStringDegree a c η hc l (hnStringEquiv a c η hc l h i)=hnBasisDegree a c η l i := by + induction l with + | nil => rfl + | cons d l ih => + rcases i with ⟨i,j⟩ + change (homogeneousBStringEquiv a c η hc d _ i).1 + + hnStringDegree a c η hc l (hnStringEquiv a c η hc l _ j) - eulerForm a d l.sum = _ + rw [homogeneousBStringEquiv_degree, ih] + rfl + +abbrev HNStringCoefficient (d : I → ℕ) (k : ℤ) := + {i : Σ l : HNIndex c η d,HNStringIndex a c η hc l.val // + hnStringDegree a c η hc i.1.val i.2=k} + +noncomputable def hnStringCoefficientEquiv (d : I → ℕ) (k : ℤ) : + HNGradedIndex a c η d k ≃ HNStringCoefficient a c η hc d k := + (Equiv.sigmaCongrRight (fun l : HNIndex c η d=> + hnStringEquiv a c η hc l.val l.property.2.1)).subtypeEquiv (by + intro i + exact (congrArg (·=k) (hnStringEquiv_degree a c η hc i.1.val i.1.property.2.1 i.2)).symm.to_iff) + +lemma hnStringCoefficient_finite (d : I → ℕ) (k : ℤ) : + Finite (HNStringCoefficient a c η hc d k) := by + let := hnGradedIndex_finite a c η hc d k + exact Finite.of_equiv _ (hnStringCoefficientEquiv a c η hc d k) + +theorem finiteStringReordering_coefficient (d : I → ℕ) (k : ℤ) : + Nat.card {i : SortedPackExponent d // (sortedPackDegree d i : ℤ)=k}= + Nat.card (HNStringCoefficient a c η hc d k) := by + rw [←packHilbert_coefficient,hnHilbert_coefficient a c η hc] + exact Nat.card_congr (hnStringCoefficientEquiv a c η hc d k) +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity +variable {J : Type*} [LinearOrder J] (even : J → Prop) + +def OrderedSignedWord := {l : List J // l.Pairwise (fun i j=>i≤j ∧ (i=j → even i))} +def SignedSelection := {m : Multiset J // ∀ i, ¬even i → m.count i≤1} + +lemma count_le_one_of_signed_pairwise {l : List J} + (h : l.Pairwise (fun i j=>i≤j ∧ (i=j → even i))) (i : J) (hi : ¬even i) : + l.count i≤1 := by + induction l with + | nil => simp + | cons j l ih => + obtain ⟨hh,ht⟩:=List.pairwise_cons.mp h + by_cases e : i=j + · subst j + have hn : i∉l := fun hm=>hi ((hh i hm).2 rfl) + simp [List.count_eq_zero.mpr hn] + · simpa [List.count_cons,Ne.symm e] using ih ht + +lemma signed_pairwise_of_count {l : List J} (h : l.Pairwise (·≤·)) + (hc : ∀ i, ¬even i → l.count i≤1) : + l.Pairwise (fun i j=>i≤j ∧ (i=j → even i)) := by + induction l with + | nil => simp + | cons j l ih => + obtain ⟨hh,ht⟩:=List.pairwise_cons.mp h + apply List.pairwise_cons.mpr + constructor + · intro i hi + refine ⟨hh i hi,?_⟩ + rintro rfl + by_contra he + have H:=hc j he + have Hp:=List.count_pos_iff.mpr hi + simp only [List.count_cons_self] at H + omega + · apply ih ht + intro i hi + have H:=hc i hi + simp only [List.count_cons] at H + split_ifs at H <;> omega + +noncomputable def signedWordSelectionEquiv : OrderedSignedWord even ≃ SignedSelection even where + toFun l := ⟨(l.val : Multiset J),by + intro i hi + simpa only [Multiset.coe_count] using count_le_one_of_signed_pairwise even l.property i hi⟩ + invFun m := ⟨m.val.sort (·≤·),signed_pairwise_of_count even (m.val.pairwise_sort (·≤·)) (by + intro i hi + have H:=m.property i hi + have E:=congrArg (Multiset.count i) (m.val.sort_eq (·≤·)) + simpa only [Multiset.coe_count] using E.le.trans H)⟩ + left_inv l := by + apply Subtype.ext + exact List.Perm.eq_of_pairwise' ((l.val : Multiset J).pairwise_sort (·≤·)) + (l.property.imp (fun h=>h.1)) (Multiset.coe_eq_coe.mp ((l.val : Multiset J).sort_eq (·≤·))) + right_inv m := Subtype.ext (m.val.sort_eq (·≤·)) + +lemma signedWordSelectionEquiv_val (l : OrderedSignedWord even) : + (signedWordSelectionEquiv even l).val=(l.val : Multiset J) := rfl +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteWallCrossing.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteWallCrossing.lean new file mode 100644 index 0000000000000000000000000000000000000000..49be5c5365893045c313ce41896aa56e1290e124 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteWallCrossing.lean @@ -0,0 +1,174 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteElementaryAdjoint +import OAI.Combinatorics.Chromatic.QuantumTorus.SectionMonomialExpansion +import OAI.Combinatorics.Chromatic.Walls.IsotropicLiteralPositive + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits LaurentPrecision Filter RootTruncation +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +lemma inverse_adjoint_coeff_congr (F G X : PowerSeries (Torus LaurentRay.vUnit Ω)) (N : ℕ) + (h : ∀n≤N,coeff n F=coeff n G) : + coeff N (invOfUnit F 1*X*F)=coeff N (invOfUnit G 1*X*G) := by + apply FormalLog.mul_coeff_congr + · intro j hj + exact FormalLog.mul_coeff_congr _ _ _ _ j + (fun k hk=>PowerSeriesAdjoint.inverse_coeff_congr F G j + (fun t ht=>h t (ht.trans hj)) k hk) (fun _ _=>rfl) + · exact h +lemma cut_adjoint_coeff (F X : PowerSeries (Torus LaurentRay.vUnit Ω)) (N n : ℕ) (hn : n≤N) : + coeff n (PowerSeriesAdjoint.adjoint (cut N F) X)=coeff n (PowerSeriesAdjoint.adjoint F X) := + PowerSeriesAdjoint.adjoint_coeff_congr _ _ _ _ n + (fun j hj=>by rw [coeff_cut,ite_eq_left (hj.trans hn)]) (fun _ _=>rfl) +lemma cut_inverse_adjoint_coeff (F X : PowerSeries (Torus LaurentRay.vUnit Ω)) (N n : ℕ) (hn : n≤N) : + coeff n (invOfUnit (cut N F) 1*X*cut N F)=coeff n (invOfUnit F 1*X*F) := + inverse_adjoint_coeff_congr Ω _ _ _ n (fun j hj=>by rw [coeff_cut,ite_eq_left (hj.trans hn)]) +lemma rootClosed_isotropic_adjoint (V : AddSubmonoid M) (hΩ : ∀p,Ω p p=0) + (hV : ∀p∈V,∀q∈V,Ω p q=0) {N : ℕ} {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : RootClosedThrough LaurentRay.vUnit Ω N (literalRootProducts Ω C (fun p=>p∈V)) F) : + (∀m,(∀p∈V,0≤Ω p m) → ∀n≤N,TorusPositive Ω + (coeff n (F*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit F 1))) ∧ + (∀m,(∀p∈V,Ω p m≤0) → ∀n≤N,TorusPositive Ω + (coeff n (invOfUnit F 1*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*F))) := by + let g:=rootApprox LaurentRay.vUnit Ω hF + have hg:=rootApprox_converges LaurentRay.vUnit Ω hF + have hgg : ∀T,SeriesGraded LaurentRay.vUnit Ω C (cut N (g T)):= + fun T=>(literalRootProducts_graded Ω C _ (rootApprox_mem LaurentRay.vUnit Ω hF T)).cut LaurentRay.vUnit Ω C N + have hFG : SeriesGraded LaurentRay.vUnit Ω C (cut N F):=by + apply hF.graded Ω C + rintro G ⟨G',hG,rfl⟩ + exact (literalRootProducts_graded Ω C _ hG).cut LaurentRay.vUnit Ω C N + have hp:=fun T=>literal_isotropic_adjoint Ω C V hΩ hV (rootApprox_mem LaurentRay.vUnit Ω hF T) + constructor + · intro m hm n hn r + have H:=hg.adjoint LaurentRay.vUnit Ω C Filter.atTop hgg hFG (Torus.X LaurentRay.vUnit Ω m) + have he : ∀G,coeff n (cut N G*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit (cut N G) 1)= + coeff n (G*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit G 1):= + fun G=>cut_adjoint_coeff Ω G _ N n hn + have Hn:=H n r + simp only [he] at Hn + exact LaurentPositive.of_converges Filter.atTop Hn (Eventually.of_forall (fun T=>(hp T).1 m hm n r)) + · intro m hm n hn r + have H:=hg.inverse_adjoint Ω C Filter.atTop hgg hFG (Torus.X LaurentRay.vUnit Ω m) + have he:=fun G=>cut_inverse_adjoint_coeff Ω G (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)) N n hn + have Hn:=H n r + simp only [he] at Hn + exact LaurentPositive.of_converges Filter.atTop Hn (Eventually.of_forall (fun T=>(hp T).2 m hm n r)) +lemma rootClosed_ray_adjoint (hΩ : ∀p,Ω p p=0) (r : M) + {N : ℕ} {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : RootClosedThrough LaurentRay.vUnit Ω N (literalRootProducts Ω C (OnPositiveRay r)) F) : + (∀m,0≤Ω r m → ∀n≤N,TorusPositive Ω + (coeff n (F*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit F 1))) ∧ + (∀m,Ω r m≤0 → ∀n≤N,TorusPositive Ω + (coeff n (invOfUnit F 1*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*F))) := by + have H:=rootClosed_isotropic_adjoint Ω C (positiveRayWithZero r) hΩ + (positiveRayWithZero_isotropic Ω hΩ r) + (hF.mono LaurentRay.vUnit Ω (literalRootProducts_allowed_mono Ω C _ _ (fun n hn p hr hp=>Or.inr hp))) + constructor + · intro m hm + apply H.1 m + intro p hp + rcases hp with rfl|hp + · simp + exact hp.pair_nonneg Ω (OnPositiveRay.refl m) hm + · intro m hm + apply H.2 m + intro p hp + rcases hp with rfl|hp + · simp + have he:=hp.eval (incomingCovector Ω m) + by_contra hx + have hp0 : (0:ℝ)<Ω p m:=by exact_mod_cast (lt_of_not_ge hx) + have hr0:=he.1.mp hp0 + change (0:ℝ)<Ω r m at hr0 + have hr1 : (Ω r m:ℝ)≤0:=by exact_mod_cast hm + linarith +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint LaurentPositive WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) (hΩ : ∀m,Ω m m=0) +include hΩ in +lemma ray_charge_through (p : M) (F : CompletedPositive LaurentRay.vUnit Ω C) (N : ℕ) + (hs : ∀n,0 + rw [coeff_zero_eq_constantCoeff,F.property.1] + exact chargeGrade_one LaurentRay.vUnit Ω (Ω p) + | succ n => + intro m hm + by_contra hx + exact hm ((OnPositiveRay.refl p).pair_zero Ω (hs _ (by omega) hn m hx) (hΩ p)) +include hΩ in +lemma ray_increment_positive (p r : M) (F : CompletedPositive LaurentRay.vUnit Ω C) + (X : PowerSeries (Torus LaurentRay.vUnit Ω)) (N : ℕ) + (hs : ∀n,0hq n (hn.trans hd)) m r (Ne.symm hh) + change Positive (coeff d (adjoint F.val (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m))) r) + rw [H]; exact positive_zero + · intro hr d hd m + by_cases hh:Ω p m=Ω p r + · unfold monomialJump + rw [adjoint_inverse F.val _ F.property.1] + exact (hp.2 m (by rw [hh]; exact hr) d hd) r + · have H:=adjoint_charge LaurentRay.vUnit Ω (Ω p) (invOfUnit F.val 1) d + (chargeGrade_inverse LaurentRay.vUnit Ω (Ω p) F.val d (fun n hn=>hq n (hn.trans hd))) m r (Ne.symm hh) + change Positive (coeff d (adjoint (invOfUnit F.val 1) (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m))) r) + rw [H]; exact positive_zero + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FiniteWallPositive.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteWallPositive.lean new file mode 100644 index 0000000000000000000000000000000000000000..42f87a4efc4d7d051443ae27b1b4f5a95f24c961 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FiniteWallPositive.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.StringPositiveFactor +import OAI.Combinatorics.Chromatic.Shuffle.HNZeroFactor + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic SignedMultiplicity UnitSelections EnergyLaurent +open QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0s.1.val.1.val + let τ : (I→ℕ) →+ ℤ := (Ω.flip m).comp P + let t : SlopeStringStart a c η hc θ → ℕ := fun s=>(τ (dim s)).toNat + have hdim : ∀s,dim s∈slopeDimensions c η hc θ := fun s=>s.1.val.1.property + have ht : ∀s,(t s:ℤ)=τ (dim s) := fun s=>Int.toNat_of_nonneg (hm _ (hdim s)) + have hi : ∀d∈slopeDimensions c η hc θ,∀e∈slopeDimensions c η hc θ,Ω (P d) (P e)=0 := by + intro d hd e he + rw [hgeom,eulerForm_slopeDimensions_symm a c η hc θ ⟨d,hd⟩ ⟨e,he⟩,sub_self] + exact stringSeries_adjoint_positive (slopeStartRowType a c η hc θ) t dim + (slopeStartParameter a κ c η hc θ) (primitiveCountsEnergy_admissible a κ c η hc θ) + (slopeDimensions c η hc θ) hdim τ ht Ω P hi m (fun _=>rfl) w hΩ + (primitiveCountsSeries_zero a κ c η hc θ) + +variable (h : M →+ ℝ) (hh : ∀d,h (P d)=slopeValue c η θ d) +include hΩ hgeom hm hh in + +theorem finiteInput_zero_adjoint_positive (ε : I → Bool) + (ha : ∀i,a i i=elementaryDiagonal ε i) : + let F := PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) (push w LaurentRay.vUnit Ω P (literalInputCoefficient a κ ε)) + IntegralPositive Ω (F*C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit F 1) := by + dsimp only + rw [←literalInput_primitiveFactor a κ c η hc w Ω P hgeom h θ hh ε ha] + exact primitiveFactor_adjoint_positive a κ c η hc w Ω P hΩ hgeom θ m hm + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/ForwardChartMutation.lean b/lean/OAI/Combinatorics/Chromatic/Walls/ForwardChartMutation.lean new file mode 100644 index 0000000000000000000000000000000000000000..e5d4138c85eb065c728d3e6e96b21dc2b5f5ae9d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/ForwardChartMutation.lean @@ -0,0 +1,196 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ForwardInventoryRotation + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus +open Classical +noncomputable section +variable {n:ℕ} {M E I:Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] + +structure FreeChart (e:M →+ E) where + roots : (I → ℤ) →+ M + coord : M →+ (I → ℤ) + retract : ∀d,coord (roots d)=d + independent : LinearIndependent ℝ (fun i=>e (simpleRoot roots i)) + +def FreeChart.mutate (Ω:M →+ M →+ ℤ) {e:M →+ E} (ch:FreeChart (I:=I) e) (pc:I) : FreeChart (I:=I) e where + roots := mutatedRoots Ω ch.roots pc + coord := mutatedCoordinates Ω ch.roots ch.coord pc + retract := mutatedCoordinates_retraction Ω ch.roots ch.coord ch.retract pc + independent := mutatedRoots_realIndependent Ω ch.roots pc e ch.independent + +variable (Ω:M →+ M →+ ℤ) {e:M →+ E} +lemma freeChart_inventory_step (ch:FreeChart (I:=I) e) (is:List I) + (his:is.Nodup) (_hall:∀i,i∈is) + (d:Fin (n+1) → M) (w:Cell n → M) (b:Cell n) (q:List (Cell n)) + (hb:b∉q) (hinv:(is.map (simpleRoot ch.roots)).Perm (forwardInventory d w (b::q))) + (p:M) (hp:p=w b-d b.1.castSucc) + (hd:∀j,Ω p (d j)=(if j=b.1.castSucc then 1 else 0)-(if j=b.1.succ then 1 else 0)) + (hw:∀c,Ω p (w c)=if c=b then 1 else 0) : + ∃pc:I,simpleRoot ch.roots pc=p ∧ + (is.map (simpleRoot (ch.mutate Ω pc).roots)).Perm + (forwardInventory d (Function.update w b (d b.1.succ+p)) (q++[b])) := by + have hmem:p∈forwardInventory d w (b::q):=by rw [hp]; exact forwardInventory_root_mem d w b q + have hm:p∈is.map (simpleRoot ch.roots):=hinv.mem_iff.mpr hmem + obtain ⟨pc,_,hpc⟩:=List.mem_map.mp hm + refine ⟨pc,hpc,?_⟩ + have hnd:(forwardInventory d w (b::q)).Nodup:= + hinv.nodup_iff.mp (his.map (simpleRoot_injective ch.roots ch.coord ch.retract)) + change (is.map (simpleRoot (mutatedRoots Ω ch.roots pc))).Perm _ + rw [mutatedRoot_list Ω ch.roots ch.coord ch.retract pc,hpc] + exact (hinv.map (rootMutation Ω p)).trans (forwardInventory_rotation Ω d w b q hb hnd p hp hd hw) +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.ForwardChain +variable {M : Type*} [AddCommGroup M] +lemma gaps_ofFn_nodes {k:ℕ} (x:Fin (k+2) → M) : + gaps (x 0) (List.ofFn (fun j:Fin k=>x j.succ.castSucc)) (x (Fin.last (k+1)))= + List.ofFn (fun j:Fin (k+1)=>x j.succ-x j.castSucc) := by + induction k with + | zero => simp [gaps,List.ofFn_succ] + | succ k ih => + rw [List.ofFn_succ,gaps,List.ofFn_succ] + congr 1 + exact ih (fun j=>x j.succ) +end ElementaryPositivity.ForwardChain + +end +section +namespace ElementaryPositivity.TriangularDynamics +open Classical +noncomputable section +variable {n : ℕ} {R : Type*} [CommRing R] + +@[simp] lemma levelNode_zero (i:Fin n) : levelNode i 0=.inl i.castSucc := by + simp [levelNode] +@[simp] lemma levelNode_last (i:Fin n) : levelNode i (Fin.last (i.val+2))=.inl i.succ := by + simp [levelNode] +lemma levelNode_middle (i:Fin n) (j:Fin (i.val+1)) : + levelNode i j.succ.castSucc=.inr ⟨i,j.rev⟩ := by + simp only [levelNode,Fin.val_castSucc,Fin.val_succ] + rw [dite_eq_right (by omega),dite_eq_right (by have := j.isLt; omega)] + congr 2 + +def gapIndices (n:ℕ) : List (GapIndex n) := + (List.finRange n).flatMap (fun i=>(List.finRange (i.val+2)).map (Sigma.mk i)) +lemma mem_gapIndices (g:GapIndex n) : g∈gapIndices n := by + rcases g with ⟨i,j⟩ + exact List.mem_flatMap.mpr ⟨i,List.mem_finRange _,List.mem_map.mpr ⟨j,List.mem_finRange _,rfl⟩⟩ +lemma gapIndices_nodup : (gapIndices n).Nodup := by + rw [gapIndices,List.nodup_flatMap] + constructor + · intro i _ + exact (List.nodup_finRange _).map (fun a b h=>by cases h; rfl) + · apply (List.nodup_finRange n).pairwise_of_forall_ne + intro i j _ _ hij g hg hg' + obtain ⟨a,_,ha⟩:=List.mem_map.mp hg + obtain ⟨b,_,hb⟩:=List.mem_map.mp hg' + exact hij (by simpa using congrArg Sigma.fst (ha.trans hb.symm)) + +lemma initial_levelGaps (i:Fin n) : + levelGaps (anchor (n:=n)) bridge (phaseCycle n) i= + (List.finRange (i.val+2)).map (fun j=>forwardGap (R:=ℤ) ⟨i,j⟩) := by + rw [levelGaps,phaseCycle_levelQueue,initialLevelQueue,List.map_ofFn] + have H:=ForwardChain.gaps_ofFn_nodes (fun j:Fin (i.val+3)=> + (Pi.single (levelNode i j) 1:Vertex n (Cell n) → ℤ)) + simpa only [levelNode_zero,levelNode_last,levelNode_middle,anchor,bridge, + forwardGap,List.ofFn_eq_map,Function.comp_def] using H + +lemma initial_forwardInventory : + forwardInventory anchor bridge (phaseCycle n)= + (gapIndices n).map (forwardGap (R:=ℤ)) := by + rw [forwardInventory,gapIndices,List.map_flatMap] + congr 1 + funext i + rw [initial_levelGaps,List.map_map] + rfl + +lemma simpleRoot_forwardRoots (i:GapIndex n) : + QuantumTorus.simpleRoot (forwardRoots (R:=ℤ)).toAddMonoidHom i=forwardGap i := by + rw [QuantumTorus.simpleRoot,LinearMap.toAddMonoidHom_coe,forwardRoots_apply] + rw [Finset.sum_eq_single i] + · simp + · intro j _ hj + simp [Ne.symm hj] + · simp +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.LatticeExtension +open scoped BigOperators +variable {V : Type*} [Fintype V] +abbrev Extended (V : Type*) := (V → ℤ) × (V → ℤ) + +def dot (x : V → ℤ) : (V → ℤ) →+ ℤ where + toFun y := ∑ i,x i*y i + map_zero' := by simp + map_add' y z := by simp [mul_add,Finset.sum_add_distrib] + +lemma dot_apply (x y : V → ℤ) : dot x y=∑i,x i*y i := by simp [dot] +lemma dot_add (x y z : V → ℤ) : dot (x+y) z=dot x z+dot y z := by + simp only [dot_apply,Pi.add_apply,add_mul,Finset.sum_add_distrib] +lemma dot_zero (y : V → ℤ) : dot 0 y=0 := by simp [dot_apply] +@[simp] lemma dot_single [DecidableEq V] (x : V → ℤ) (i : V) : dot x (Pi.single i 1)=x i := by + simp [dot_apply,Pi.single_apply] + +variable (Ω : (V → ℤ) →+ (V → ℤ) →+ ℤ) +def form : Extended V →+ Extended V →+ ℤ where + toFun x := ((Ω x.1).comp (AddMonoidHom.fst _ _)) + + ((dot x.2).comp (AddMonoidHom.fst _ _)) - + ((dot x.1).comp (AddMonoidHom.snd _ _)) + map_zero' := by ext y; simp [dot_zero] + map_add' x x' := by ext y; simp [dot_add]; abel + +lemma form_apply (x y : Extended V) : + form Ω x y=Ω x.1 y.1+dot x.2 y.1-dot x.1 y.2 := rfl + +lemma form_self (hΩ : ∀m,Ω m m=0) (x : Extended V) : form Ω x x=0 := by + rw [form_apply,hΩ,zero_add] + have H : dot x.2 x.1=dot x.1 x.2 := by + simp only [dot_apply] + apply Finset.sum_congr rfl + intro i _ + ring + rw [H,sub_self] + +def includeVertices : (V → ℤ) →+ Extended V := (AddMonoidHom.id _).prod 0 +omit [Fintype V] in +@[simp] lemma includeVertices_apply (m : V → ℤ) : includeVertices m=(m,0) := rfl +omit [Fintype V] in +lemma includeVertices_injective : Function.Injective (includeVertices (V:=V)) := by + intro a b h + exact congrArg Prod.fst h +@[simp] lemma form_original (m m' : V → ℤ) : + form Ω (includeVertices m) (includeVertices m')=Ω m m' := by + simp [form_apply,dot_zero] + +lemma form_nondegenerate [DecidableEq V] : ∀r≠0,∃m,form Ω r m≠0 := by + intro r hr + by_contra hh + push Not at hh + have hfirst : r.1=0 := by + ext i + have H:=hh (0,Pi.single i 1) + simp only [form_apply,map_zero,dot_single,zero_add,zero_sub,neg_eq_zero] at H + exact H + have hsecond : r.2=0 := by + ext i + have H:=hh (Pi.single i 1,0) + simp only [form_apply,hfirst,map_zero,AddMonoidHom.zero_apply,zero_add, + dot_single,sub_zero] at H + exact H + exact hr (Prod.ext hfirst hsecond) +end ElementaryPositivity.LatticeExtension + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/ForwardInventoryRotation.lean b/lean/OAI/Combinatorics/Chromatic/Walls/ForwardInventoryRotation.lean new file mode 100644 index 0000000000000000000000000000000000000000..5865d9e09d4f951302dd78f90eb3a4553bd9288a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/ForwardInventoryRotation.lean @@ -0,0 +1,206 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RealRootCoordinates +import OAI.Combinatorics.Chromatic.GradedAlgebra.RootMutationInventory + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus +open Classical +noncomputable section +variable {n : ℕ} {M : Type*} [AddCommGroup M] + +def levelGaps (d : Fin (n+1) → M) (w : Cell n → M) (q : List (Cell n)) (i : Fin n) : List M := + ForwardChain.gaps (d i.castSucc) ((levelQueue q i).map w) (d i.succ) +def forwardInventory (d : Fin (n+1) → M) (w : Cell n → M) (q : List (Cell n)) : List M := + (List.finRange n).flatMap (levelGaps d w q) + +lemma forwardInventory_level_nodup (d : Fin (n+1) → M) (w : Cell n → M) (q : List (Cell n)) + (hnd : (forwardInventory d w q).Nodup) (i : Fin n) : (levelGaps d w q i).Nodup := + (List.nodup_flatMap.mp hnd).1 i (List.mem_finRange i) + +lemma levelGaps_root_mem (d : Fin (n+1) → M) (w : Cell n → M) (b : Cell n) (q : List (Cell n)) : + w b-d b.1.castSucc ∈ levelGaps d w (b::q) b.1 := by + simp [levelGaps,levelQueue_cons,ForwardChain.gaps] + +lemma forwardInventory_root_mem (d : Fin (n+1) → M) (w : Cell n → M) (b : Cell n) (q : List (Cell n)) : + w b-d b.1.castSucc ∈ forwardInventory d w (b::q) := by + exact List.mem_flatMap.mpr ⟨b.1,List.mem_finRange _,levelGaps_root_mem d w b q⟩ + +private lemma pairwise_distinct {A : Type*} {R : A → A → Prop} (hs:Std.Symm R) + {l:List A} (h:l.Pairwise R) {a b:A} (ha:a∈l) (hb:b∈l) (hab:a≠b) : R a b := by + induction l with + | nil => simp at ha + | cons x xs ih => + obtain ⟨hhead,htail⟩:=List.pairwise_cons.mp h + rcases List.mem_cons.mp ha with hax|hax + · subst a + rcases List.mem_cons.mp hb with hbx|hbx + · exact (hab hbx.symm).elim + · exact hhead b hbx + · rcases List.mem_cons.mp hb with hbx|hbx + · subst b; exact hs.symm _ _ (hhead a hax) + · exact ih htail hax hbx + +variable (Ω : M →+ M →+ ℤ) +lemma forwardInventory_rotation (d : Fin (n+1) → M) (w : Cell n → M) (b : Cell n) (q : List (Cell n)) + (hb : b∉q) (hnd : (forwardInventory d w (b::q)).Nodup) + (p : M) (hp : p=w b-d b.1.castSucc) + (hd : ∀j, Ω p (d j)=(if j=b.1.castSucc then 1 else 0)-(if j=b.1.succ then 1 else 0)) + (hw : ∀c,Ω p (w c)=if c=b then 1 else 0) : + ((forwardInventory d w (b::q)).map (rootMutation Ω p)).Perm + (forwardInventory d (Function.update w b (d b.1.succ+p)) (q++[b])) := by + have hwb:Ω p (w b)=1:=by rw [hw,ite_eq_left rfl] + have hda:Ω p (d b.1.castSucc)=1:=by rw [hd]; simp [Fin.ext_iff] + have hdc:Ω p (d b.1.succ)= -1:=by rw [hd]; simp [Fin.ext_iff] + have ho (i:Fin n) : ((levelQueue q i).map (Function.update w b (d b.1.succ+p)))= + (levelQueue q i).map w := by + apply queue_update_off + intro hh + exact hb (List.mem_of_mem_filter hh) + have hlevel (i:Fin n) : ((levelGaps d w (b::q) i).map (rootMutation Ω p)).Perm + (levelGaps d (Function.update w b (d b.1.succ+p)) (q++[b]) i) := by + by_cases hi:b.1=i + · subst i + have hni:=forwardInventory_level_nodup d w (b::q) hnd b.1 + simp only [levelGaps,levelQueue_cons,ite_true,List.map_cons] at hni ⊢ + rw [levelQueue_rotate,ite_eq_left rfl,List.map_append,ho] + simp only [List.map_cons,List.map_nil,Function.update_self] + apply rootMutation_rotation_perm Ω p (d b.1.castSucc) (w b) (d b.1.succ) _ hp hda hwb hdc _ hni + intro x hx + obtain ⟨c,hc,rfl⟩:=List.mem_map.mp hx + have hcb:c≠b:=by intro h; subst c; exact hb (List.mem_of_mem_filter hc) + rw [hw,ite_eq_right hcb] + · have hnot:p∉levelGaps d w (b::q) i := by + have H:=(List.nodup_flatMap.mp hnd).2 + have hbi:b.1∈List.finRange n:=List.mem_finRange _ + have hii:i∈List.finRange n:=List.mem_finRange _ + have hpp:p∈levelGaps d w (b::q) b.1:=by rw [hp]; exact levelGaps_root_mem d w b q + have hdis:List.Disjoint (levelGaps d w (b::q) b.1) (levelGaps d w (b::q) i):=by + exact pairwise_distinct ⟨fun _ _ hdisjoint=>hdisjoint.symm⟩ H hbi hii hi + exact fun hpi=>hdis hpp hpi + have ha:Ω p (d i.castSucc)≤0:=by + rw [hd] + have hn:i.castSucc≠b.1.castSucc:=fun h=>hi (Fin.castSucc_inj.mp h).symm + simp only [ite_eq_right hn] + split_ifs <;> norm_num + have hc:0≤Ω p (d i.succ):=by + rw [hd] + have hn:i.succ≠b.1.succ:=fun h=>hi (Fin.succ_inj.mp h).symm + simp only [ite_eq_right hn,sub_zero] + split_ifs <;> norm_num + simp only [levelGaps,levelQueue_cons,ite_eq_right hi] at hnot ⊢ + rw [levelQueue_rotate,ite_eq_right hi,List.append_nil,ho] + apply List.Perm.of_eq + apply rootMutation_gaps_fixed Ω p _ _ _ ha hc _ hnot + intro x hx + obtain ⟨c,hc,rfl⟩:=List.mem_map.mp hx + have hcb:c≠b:=by intro h; subst c; exact hb (List.mem_of_mem_filter hc) + rw [hw,ite_eq_right hcb] + rw [forwardInventory,List.map_flatMap] + exact (List.Perm.refl _).flatMap (fun i _=>hlevel i) +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.QuantumTorus +open Classical +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] + +private def pivotMap (pc:I) (a:I → ℝ) : (I → ℝ) →ₗ[ℝ] (I → ℝ) where + toFun d i:=if i=pc then -d pc+∑j∈Finset.univ.erase pc,a j*d j else d i + map_add' x y:=by + ext i + by_cases hi:i=pc + · subst i; simp only [ite_true,Pi.add_apply,neg_add,mul_add,Finset.sum_add_distrib]; ring + · simp [hi] + map_smul' r x:=by + ext i + by_cases hi:i=pc + · subst i + simp only [ite_true,Pi.smul_apply,smul_eq_mul,RingHom.id_apply,mul_add,mul_neg,Finset.mul_sum] + congr 1 + apply Finset.sum_congr rfl + intro j _ + ring + · simp [hi] + +private lemma pivot_involutive (pc:I) (a:I → ℝ) : Function.Involutive (pivotMap pc a) := by + intro d + ext i + by_cases hi:i=pc + · subst i + simp only [pivotMap,LinearMap.coe_mk,AddHom.coe_mk,ite_true] + have hh:(∑j∈Finset.univ.erase pc,a j*(if j=pc then -d pc+∑k∈Finset.univ.erase pc,a k*d k else d j))= + ∑j∈Finset.univ.erase pc,a j*d j:=by + apply Finset.sum_congr rfl + intro j hj + rw [ite_eq_right (Finset.mem_erase.mp hj).1] + rw [hh]; ring + · simp [pivotMap,hi] + +private lemma pivot_single (pc i:I) (a:I → ℝ) : + pivotMap pc a (Pi.single i 1)=if i=pc then -Pi.single pc 1 else Pi.single i 1+a i • Pi.single pc 1 := by + ext j + by_cases hip:i=pc + · subst i + simp only [pivotMap,LinearMap.coe_mk,AddHom.coe_mk,ite_true] + have hs:(∑k∈Finset.univ.erase pc,a k*(Pi.single pc 1:I → ℝ) k)=0:=by + apply Finset.sum_eq_zero + intro k hk + simp [Ne.symm (Finset.mem_erase.mp hk).1] + rw [hs] + by_cases hj:j=pc + · subst j; simp + · simp [hj] + · simp only [pivotMap,LinearMap.coe_mk,AddHom.coe_mk,ite_eq_right hip] + have hs:(∑k∈Finset.univ.erase pc,a k*(Pi.single i 1:I → ℝ) k)=a i:=by + rw [Finset.sum_eq_single i] + · simp + · intro k _ hk; simp [Ne.symm hk] + · simp [hip] + rw [hs] + by_cases hj:j=pc + · subst j; simp [Ne.symm hip] + · simp [hj,Pi.single_apply] + +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) (pc:I) (e:M →+ E) +lemma mutatedRoots_realIndependent (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) : + LinearIndependent ℝ (fun i=>e (simpleRoot (mutatedRoots Ω C pc) i)) := by + obtain ⟨D,hD⟩:=realRootCoordinates_exists C e hC + let a:I → ℝ:=fun i=>(max 0 (-mutationPairing Ω C pc i):ℤ) + have hmap (i:I) : D (e (simpleRoot (mutatedRoots Ω C pc) i))= + pivotMap pc a (Pi.single i 1) := by + rw [pivot_single] + by_cases hi:i=pc + · subst i + rw [ite_eq_left rfl,mutatedRoot_p,map_neg,map_neg,real_coordinate_simple C e D hD] + · rw [ite_eq_right hi,mutatedRoot_off Ω C pc i hi,map_add,map_zsmul,map_add,map_zsmul, + real_coordinate_simple C e D hD,real_coordinate_simple C e D hD] + simp only [a,Int.cast_smul_eq_zsmul] + have hind:LinearIndependent ℝ (fun i=>pivotMap pc a (Pi.single i 1)):= + (Pi.linearIndependent_single_one I ℝ).map' (pivotMap pc a) + (LinearMap.ker_eq_bot.mpr (pivot_involutive pc a).injective) + have hd:LinearIndependent ℝ (fun i=>D (e (simpleRoot (mutatedRoots Ω C pc) i))):=by + simpa only [hmap] using hind + exact hd.of_comp D + +lemma rootDegreeCovector_exists (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) : + ∃L:Module.Dual ℝ E,∀n m,HasRootDegree C n m → L (e m)=(n:ℝ) := by + obtain ⟨D,hD⟩:=realRootCoordinates_exists C e hC + let L:Module.Dual ℝ E:=∑i,(LinearMap.proj i).comp D + refine ⟨L,fun n m hm=>covector_root_eval C e L ?_ hm⟩ + intro i + simp only [L,LinearMap.sum_apply,LinearMap.comp_apply,LinearMap.proj_apply, + real_coordinate_simple C e D hD] + simp +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/ForwardPolynomialMutation.lean b/lean/OAI/Combinatorics/Chromatic/Walls/ForwardPolynomialMutation.lean new file mode 100644 index 0000000000000000000000000000000000000000..16dab3fb08f3f8bdb6046a09cb56c240fc25784d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/ForwardPolynomialMutation.lean @@ -0,0 +1,180 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ForwardChartMutation +import OAI.Combinatorics.Chromatic.Walls.PolynomialIncomingProbes + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits +open Classical +noncomputable section +variable {n:ℕ} {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (hnd:∀r≠0,∃m,Ω r m≠0) + +def vertexDisplay (d:Fin (n+1) → M) (w:Cell n → M) : Vertex n (Cell n) → M := Sum.elim d w +omit [AddCommGroup M] in +lemma vertexDisplay_update (d:Fin (n+1) → M) (w:Cell n → M) (b:Cell n) (w':M) : + vertexDisplay d (Function.update w b w')=Function.update (vertexDisplay d w) (.inr b) w' := by + funext a + cases a with + | inl a => simp [vertexDisplay] + | inr a => by_cases h:a=b <;> simp [vertexDisplay,h] + +include hΩ he hS hcomp hnd in +lemma freeChart_polynomial_step (ch:FreeChart (I:=I) e) (is:List I) + (his:is.Nodup) (hall:∀i,i∈is) + (d:Fin (n+1) → M) (w:Cell n → M) (b:Cell n) (q:List (Cell n)) + (hb:b∉q) (hinv:(is.map (simpleRoot ch.roots)).Perm (forwardInventory d w (b::q))) + (p:M) (hp:p=w b-d b.1.castSucc) + (hd:∀j,Ω p (d j)=(if j=b.1.castSucc then 1 else 0)-(if j=b.1.succ then 1 else 0)) + (hw:∀c,Ω p (w c)=if c=b then 1 else 0) + (hdd:Ω (d b.1.castSucc) (d b.1.succ)=0) {N:ℕ} (f:ElementaryExpr N) : + ∃pc:I,simpleRoot ch.roots pc=p ∧ + (is.map (simpleRoot (ch.mutate Ω pc).roots)).Perm + (forwardInventory d (Function.update w b (d b.1.succ+p)) (q++[b])) ∧ + ∀r,polynomialSectionIncoming Ω ch.roots ch.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay d w)) r= + polynomialSectionIncoming Ω (ch.mutate Ω pc).roots (ch.mutate Ω pc).coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay d (Function.update w b (d b.1.succ+p)))) + (mutationIncomingLabel Ω p r) := by + obtain ⟨pc,hpc,hpi⟩:=freeChart_inventory_step Ω ch is his hall d w b q hb hinv p hp hd hw + cases hpc + refine ⟨pc,rfl,hpi,?_⟩ + have hF:PureInitialRelation Ω hΩ ch.roots ch.coord ch.retract pc + (f.eval LaurentRay.vUnit Ω (vertexDisplay d w)) + (f.eval LaurentRay.vUnit Ω (vertexDisplay d (Function.update w b (d b.1.succ+simpleRoot ch.roots pc)))) := by + unfold PureInitialRelation + rw [vertexDisplay_update] + symm + apply ElementaryExpr.rotation LaurentRay.vUnit Ω hΩ _ (simpleRoot ch.roots pc) _ (vertexDisplay d w) + (.inl b.1.castSucc) (.inr b) (.inl b.1.succ) (by simp) (by simp) + (by simp [Fin.ext_iff]) _ _ _ hdd _ f + · change w b=d b.1.castSucc+simpleRoot ch.roots pc + rw [hp]; abel + · change Ω (simpleRoot ch.roots pc) (d b.1.castSucc)=1 + rw [hd]; simp [Fin.ext_iff] + · change Ω (simpleRoot ch.roots pc) (d b.1.succ)= -1 + rw [hd]; simp [Fin.ext_iff] + · intro x hxa hxb hxc + cases x with + | inl a => + change Ω (simpleRoot ch.roots pc) (d a)=0 + rw [hd] + have ha:a≠b.1.castSucc:=by simpa using hxa + have hc:a≠b.1.succ:=by simpa using hxc + simp [ha,hc] + | inr c => + change Ω (simpleRoot ch.roots pc) (w c)=0 + rw [hw,ite_eq_right (by simpa using hxb)] + obtain ⟨L,hL⟩:=rootDegreeCovector_exists ch.roots e ch.independent + intro r + have H:=polynomialSectionIncoming_mutation Ω hΩ ch.roots ch.coord ch.retract pc e he S hS hcomp + L hL hnd ch.independent _ _ hF r + simpa only [FreeChart.mutate] using H +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open Classical +noncomputable section +variable {n:ℕ} + +def periodBridge (L:ℕ) (c:Cell n) : Lattice n (Cell n) := + bridge c+(L:ℤ) • delta cellLevel c + +def partialBridge (L:ℕ) (pre:List (Cell n)) (c:Cell n) : Lattice n (Cell n) := + bridge c+((L:ℤ)+(if c∈pre then 1 else 0)) • delta cellLevel c +@[simp] lemma partialBridge_nil (L:ℕ) : partialBridge (n:=n) L []=periodBridge L := by + funext c + simp [partialBridge,periodBridge] +@[simp] lemma partialBridge_cycle (L:ℕ) : partialBridge (n:=n) L (phaseCycle n)=periodBridge (L+1) := by + funext c + simp [partialBridge,periodBridge,Nat.cast_add] +lemma partialBridge_scheduled (L:ℕ) {pre post:List (Cell n)} {b:Cell n} + (hc:phaseCycle n=pre++b::post) : partialBridge L pre=scheduledBridge L b := by + funext c + simp only [partialBridge,scheduledBridge,prefix_before hc] +lemma eventRoot_partial (L:ℕ) {pre post:List (Cell n)} {b:Cell n} + (hc:phaseCycle n=pre++b::post) : eventRoot cellLevel L b=partialBridge L pre b-anchor b.1.castSucc := by + rw [partialBridge_scheduled L hc,scheduledBridge_self] + simp only [eventRoot,cellLevel] + abel +lemma cycle_head_not_mem {pre post:List (Cell n)} {b:Cell n} + (hc:phaseCycle n=pre++b::post) : b∉post++pre := by + have hn:=phaseCycle_nodup (n:=n) + rw [hc] at hn + obtain ⟨hpre,hrest,hdis⟩:=List.nodup_append.mp hn + have hpost: b∉post:=(List.nodup_cons.mp hrest).1 + have hp:b∉pre:=fun hb=>hdis b hb b (by simp) rfl + simpa using And.intro hpost hp + +lemma partialBridge_step (L:ℕ) (pre:List (Cell n)) (b:Cell n) (_hb:b∉pre) : + partialBridge L (pre++[b])= + Function.update (partialBridge L pre) b (anchor b.1.succ+eventRoot cellLevel L b) := by + funext c + by_cases hc:c=b + · subst c + simp only [partialBridge,List.mem_append,List.mem_singleton,or_true,ite_true,Function.update_self, + eventRoot,delta,cellLevel,add_zsmul,one_zsmul] + abel + · simp only [partialBridge,List.mem_append,List.mem_singleton,hc,or_false, + Function.update_of_ne hc] + +lemma periodFunctional_anchor (i:Fin n) (L:ℕ) (a:Fin (n+1)) : + periodFunctional cellLevel i L (anchor a)=if a.val≤ i.val then 1 else 0 := by + change cutPrefix cellLevel i (anchor a)+(L:ℤ) • levelTotal cellLevel i (anchor a)=_ + rw [levelTotal_anchor,smul_zero,add_zero] + exact cutPrefix_single cellLevel i (.inl a) 1 +lemma periodFunctional_bridge (i:Fin n) (L:ℕ) (b:Cell n) : + periodFunctional cellLevel i L (periodBridge L b)=if b.1.val≤ i.val then 1 else 0 := by + have hb:eventRoot cellLevel L b=periodBridge L b-anchor b.1.castSucc:=by + unfold eventRoot periodBridge cellLevel; abel + have H:=periodFunctional_eventRoot cellLevel i L b + rw [hb,map_sub,periodFunctional_anchor] at H + simpa only [Fin.val_castSucc] using sub_eq_zero.mp H + +lemma gaps_cut_nonpos {M:Type*} [AddCommGroup M] (ell:M →+ ℤ) (a c:M) (bs:List M) (K:ℤ) + (ha:K≤ell a) (hc:ell c≤K) (hb:∀b∈bs,ell b=K) : + ∀r∈ForwardChain.gaps a bs c,ell r≤0 := by + induction bs generalizing a with + | nil => + intro r hr + have hr:r=c-a:=by simpa [ForwardChain.gaps] using hr + rw [hr,map_sub] + omega + | cons b bs ih => + have hbb:=hb b (by simp) + intro r hr + rcases List.mem_cons.mp hr with hr|hr + · rw [hr,map_sub,hbb]; omega + · apply ih b (by omega) (fun x hx=>hb x (by simp [hx])) r hr + +lemma periodInventory_cut_nonpos (i:Fin n) (L:ℕ) (q:List (Cell n)) : + ∀r∈forwardInventory anchor (periodBridge L) q,periodFunctional cellLevel i L r≤0 := by + intro r hr + obtain ⟨j,_,hr⟩:=List.mem_flatMap.mp hr + apply gaps_cut_nonpos (periodFunctional cellLevel i L) (anchor j.castSucc) (anchor j.succ) + ((levelQueue q j).map (periodBridge L)) (if j.val≤ i.val then 1 else 0) _ _ _ r hr + · rw [periodFunctional_anchor]; rfl + · rw [periodFunctional_anchor] + simp only [Fin.val_succ] + split_ifs <;> omega + · intro x hx + obtain ⟨b,hb,rfl⟩:=List.mem_map.mp hx + have hbj: b.1=j:=(mem_levelQueue q j b).mp hb |>.2 + rw [periodFunctional_bridge,hbj] + +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/FourCellFactorization.lean b/lean/OAI/Combinatorics/Chromatic/Walls/FourCellFactorization.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2aa4012cf1088ddca4fca84c3e28f03f50cdc49 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/FourCellFactorization.lean @@ -0,0 +1,100 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SumPackCut + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.ShufflePolynomiality ElementaryPositivity.PackConvolution +open ElementaryPositivity.SeparatedSymmetry +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +def firstColumn (d₁ e₁ d₂ e₂ : I → ℕ) (i : I) : + (Fin (d₁ i) ⊕ Fin (d₂ i)) ↪ FourPacks d₁ e₁ d₂ e₂ i := + Function.Embedding.sumMap Function.Embedding.inl Function.Embedding.inl + +def secondColumn (d₁ e₁ d₂ e₂ : I → ℕ) (i : I) : + (Fin (e₁ i) ⊕ Fin (e₂ i)) ↪ FourPacks d₁ e₁ d₂ e₂ i := + Function.Embedding.sumMap Function.Embedding.inr Function.Embedding.inr + +omit [Fintype I] [DecidableEq I] in +lemma canonical_first_column (d₁ e₁ d₂ e₂ : I → ℕ) : + (fun i=>left (canonicalLeftCut d₁ e₁ d₂ e₂) i ∪ + left (canonicalRightCut d₁ e₁ d₂ e₂) i) = + embedPack (firstColumn d₁ e₁ d₂ e₂) (fun _=>Finset.univ) := by + funext i + ext x + rcases x with ((x|x)|(x|x)) <;> + simp [canonicalLeftCut,canonicalRightCut,left,embedPackCut,sumPackCut, + embedPack,firstColumn,Finset.mem_map,Function.Embedding.sumMap] + +omit [Fintype I] [DecidableEq I] in +lemma canonical_second_column (d₁ e₁ d₂ e₂ : I → ℕ) : + (fun i=>right (canonicalLeftCut d₁ e₁ d₂ e₂) i ∪ + right (canonicalRightCut d₁ e₁ d₂ e₂) i) = + embedPack (secondColumn d₁ e₁ d₂ e₂) (fun _=>Finset.univ) := by + funext i + ext x + rcases x with ((x|x)|(x|x)) <;> + simp [canonicalLeftCut,canonicalRightCut,right,embedPackCut,sumPackCut, + embedPack,secondColumn,Finset.mem_map,Function.Embedding.sumMap] + +noncomputable def cutUnivRealization {d e : I → ℕ} (A : Cut d e) : + Realization (d+e) (A:=fun i=>Fin (d i) ⊕ Fin (e i)) (fun _=>Finset.univ) := + fun i=>(packSplit A i).symm.trans (Equiv.subtypeUnivEquiv (fun _=>Finset.mem_univ _)).symm + +lemma labeledPolynomial_univ_restrict {d e : I → ℕ} (A : Cut d e) (f : S (d+e)) : + labeledPolynomial (A:=fun i=>Fin (d i) ⊕ Fin (e i)) f (fun _=>Finset.univ) = + rename (Equiv.sigmaSumDistrib _ _).symm (tensorValue d e (restrictTensor A f)) := by + rw [labeledPolynomial_eq (cutUnivRealization A),tensorValue_restrictTensor,rename_rename] + congr 2 + funext x + obtain ⟨y,rfl⟩ := (cutSplit A).surjective x + simp only [Function.comp_apply,Equiv.symm_apply_apply] + cases y with + | inl x => + change (⟨x.1, (packSplit A x.1).symm (packSplit A x.1 (.inl x.2))⟩ : Σi,Fin (d i) ⊕ Fin (e i))=_ + rw [Equiv.symm_apply_apply] + rfl + | inr x => + change (⟨x.1, (packSplit A x.1).symm (packSplit A x.1 (.inr x.2))⟩ : Σi,Fin (d i) ⊕ Fin (e i))=_ + rw [Equiv.symm_apply_apply] + rfl + +def firstColumnVars (d₁ e₁ d₂ e₂ : I → ℕ) : + CellVars d₁ d₂ → CellVars d₁ e₁ ⊕ CellVars d₂ e₂ + | Sum.inl x => Sum.inl (Sum.inl x) + | Sum.inr x => Sum.inr (Sum.inl x) + +def secondColumnVars (d₁ e₁ d₂ e₂ : I → ℕ) : + CellVars e₁ e₂ → CellVars d₁ e₁ ⊕ CellVars d₂ e₂ + | Sum.inl x => Sum.inl (Sum.inr x) + | Sum.inr x => Sum.inr (Sum.inr x) + +lemma fourGridPolynomial_factor (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (A : Cut d₁ d₂) (B : Cut e₁ e₂) (f : S (d₁+d₂)) (g : S (e₁+e₂)) : + fourGridPolynomial a f g d₁ e₁ d₂ e₂ = + rename (firstColumnVars d₁ e₁ d₂ e₂) (tensorValue d₁ d₂ (restrictTensor A f)) * + rename (secondColumnVars d₁ e₁ d₂ e₂) (tensorValue e₁ e₂ (restrictTensor B g)) * + rename (fourPackEquiv d₁ e₁ d₂ e₂) + (crossKernelPolynomial a (canonicalGridCut d₁ e₁ d₂ e₂) + (canonicalLeftCut d₁ e₁ d₂ e₂) (canonicalRightCut d₁ e₁ d₂ e₂)) := by + unfold fourGridPolynomial canonicalGridPolynomial gridPolynomial + rw [canonical_first_column,canonical_second_column,←embed_labeledPolynomial, + ←embed_labeledPolynomial,labeledPolynomial_univ_restrict A,labeledPolynomial_univ_restrict B] + simp only [map_mul,rename_rename] + congr 2 + · congr 2 + funext x + cases x <;> rfl + · congr 2 + funext x + cases x <;> rfl + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/GenericAffineProbes.lean b/lean/OAI/Combinatorics/Chromatic/Walls/GenericAffineProbes.lean new file mode 100644 index 0000000000000000000000000000000000000000..d436ec04b4ff10a685468cbd385b63e8e0161cd3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/GenericAffineProbes.lean @@ -0,0 +1,85 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedPathIndependent + +namespace OAI + +section +namespace ElementaryPositivity.FiniteRayGeometry +noncomputable section +variable {E:Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [FiniteDimensional ℝ E] +lemma generic_for_two_directions_with_probes (T : ℕ → Finset E) (a b k : Module.Dual ℝ E) + (P : Finset (ℝ×E)) (v:Module.Dual ℝ E) : + ∃h : Module.Dual ℝ E,(∀N,GenericOffset (T N) 0 a h) ∧ + (∀N,GenericOffset (T N) 0 b h) ∧ + ∀s∈P,(0<(k+s.1 • v) s.2 → 0<(h+s.1 • v) s.2) ∧ + ((k+s.1 • v) s.2<0 → (h+s.1 • v) s.2<0) := by + classical + let W : Set E:=⋃N,↑(forbidden (T N) 0 a∪forbidden (T N) 0 b) + have hc : W.Countable:=Set.countable_iUnion (fun N=>(forbidden (T N) 0 a∪forbidden (T N) 0 b).countable_toSet) + have hp : ∀w∈W,w∉Submodule.span ℝ {(0:E)}:=by + intro w hw + obtain ⟨N,hN⟩:=Set.mem_iUnion.mp hw + rcases Finset.mem_union.mp hN with hh|hh + · exact (Finset.mem_filter.mp hh).2 + · exact (Finset.mem_filter.mp hh).2 + obtain ⟨h,h0,havoid,hprobe⟩:=countable_avoid_with_probes W hc 0 hp + P v k (map_zero k) + have hGa : ∀N,GenericOffset (T N) 0 a h:=by + intro N + refine ⟨h0,?_,?_⟩ + · intro s hs hn + exact havoid s (Set.mem_iUnion.mpr ⟨N,Finset.mem_union_left _ + (Finset.mem_filter.mpr ⟨Finset.mem_union_left _ hs,hn⟩)⟩) + · intro s hs t ht hn + exact havoid _ (Set.mem_iUnion.mpr ⟨N,Finset.mem_union_left _ + (Finset.mem_filter.mpr ⟨Finset.mem_union_right _ (Finset.mem_image.mpr + ⟨(s,t),Finset.mem_product.mpr ⟨hs,ht⟩,rfl⟩),hn⟩)⟩) + have hGb : ∀N,GenericOffset (T N) 0 b h:=by + intro N + refine ⟨h0,?_,?_⟩ + · intro s hs hn + exact havoid s (Set.mem_iUnion.mpr ⟨N,Finset.mem_union_right _ + (Finset.mem_filter.mpr ⟨Finset.mem_union_left _ hs,hn⟩)⟩) + · intro s hs t ht hn + exact havoid _ (Set.mem_iUnion.mpr ⟨N,Finset.mem_union_right _ + (Finset.mem_filter.mpr ⟨Finset.mem_union_right _ (Finset.mem_image.mpr + ⟨(s,t),Finset.mem_product.mpr ⟨hs,ht⟩,rfl⟩),hn⟩)⟩) + exact ⟨h,hGa,hGb,hprobe⟩ +end +end ElementaryPositivity.FiniteRayGeometry +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] +variable (C:(I → ℤ) →+ M) (e:M →+ E) +lemma generic_region_path_via_probes (a b k : Module.Dual ℝ E) (P : Finset (ℝ×E)) (v:Module.Dual ℝ E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (U : Set (Module.Dual ℝ E)) + (hU : ∀h : Module.Dual ℝ E, + (∀x∈P,(0<(k+x.1 • v) x.2 → 0<(h+x.1 • v) x.2) ∧ + ((k+x.1 • v) x.2<0 → (h+x.1 • v) x.2<0)) → + (∀t:ℝ,0≤t → t≤1 → (1-t) • a+t • h∈U) ∧ + (∀t:ℝ,0≤t → t≤1 → (1-t) • h+t • b∈U)) : + ∃p : GenericLinePath C e a b,p.InRegion C e U := by + obtain ⟨h,Ha,Hb,HP⟩:=generic_for_two_directions_with_probes (realRootsThrough e C) a b k P v + have HH : RegularCovector C e h:=by + intro N s hs hn + exact (Ha N).avoid s hs (by simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using hn) + let s:=segmentBetween C e a h HA HH (fun N=>(Ha N).join (HA N)) + let t:=segmentBetween C e h b HH HB (fun N=>(Hb N).join_reverse (HB N)) + let p:=(GenericLinePath.single C e s).castEnds C e + (segmentBetween_start C e a h HA HH _) (segmentBetween_finish C e a h HA HH _) + let q:=(GenericLinePath.single C e t).castEnds C e + (segmentBetween_start C e h b HH HB _) (segmentBetween_finish C e h b HH HB _) + have hp : p.InRegion C e U := + (segmentBetween_inRegion C e a h HA HH _ (hU h HP).1).castEnds C e _ _ + have hq : q.InRegion C e U := + (segmentBetween_inRegion C e h b HH HB _ (hU h HP).2).castEnds C e _ _ + exact ⟨p.trans C e q,hp.trans C e hq⟩ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/GenericLineJoining.lean b/lean/OAI/Combinatorics/Chromatic/Walls/GenericLineJoining.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc75650a3dd06e02260a7fb10fe075be29167ec8 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/GenericLineJoining.lean @@ -0,0 +1,207 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.LineOldTransport + +namespace OAI + +section +namespace ElementaryPositivity.FiniteRayGeometry +open Module +noncomputable section +variable {E : Type*} [AddCommGroup E] [Module ℝ E] + +lemma wedge_ne_of_difference_ne (a h : Module.Dual ℝ E) (s t : E) + (ha : s≠0 → a s≠0) (hw : (h-a) s • t-(h-a) t • s≠0) : + a s • t-a t • s≠0 := by + intro hz + by_cases hs : s=0 + · apply hw + simp only [hs,map_zero,zero_smul,smul_zero,sub_self] + · have has:=ha hs + have ht : t=(a t/a s) • s:=by + calc + t=(a s)⁻¹ • (a s • t):=(inv_smul_smul₀ has t).symm + _=(a t/a s) • s:=by rw [sub_eq_zero.mp hz,smul_smul]; congr 1; ring + apply hw + rw [ht] + simp only [map_smul,smul_smul,smul_eq_mul,mul_comm,sub_self] + +lemma GenericOffset.join {T : Finset E} {a h : Module.Dual ℝ E} + (H : GenericOffset T 0 a h) (ha : ∀s∈T,s≠0 → a s≠0) : + GenericOffset T 0 (h-a) a := by + refine ⟨map_zero _,?_,?_⟩ + · intro s hs hn + exact ha s hs (by simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using hn) + · intro s hs t ht hn + have hw : (h-a) s • t-(h-a) t • s≠0:=by + simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using hn + have hz:=H.distinct s hs t ht (by + simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using + wedge_ne_of_difference_ne a h s t (ha s hs) hw) + intro hh + apply hz + simp only [map_sub,map_smul,smul_eq_mul,LinearMap.sub_apply] at hh ⊢ + nlinarith + +lemma GenericOffset.join_reverse {T : Finset E} {a h : Module.Dual ℝ E} + (H : GenericOffset T 0 a h) (ha : ∀s∈T,s≠0 → a s≠0) : + GenericOffset T 0 (a-h) h := by + refine ⟨map_zero _,H.avoid,?_⟩ + intro s hs t ht hn + have hw : (h-a) s • t-(h-a) t • s≠0:=by + intro hz + apply hn + have he : (a-h) s • t-(a-h) t • s= -((h-a) s • t-(h-a) t • s):=by + simp only [LinearMap.sub_apply,neg_sub,sub_smul] + abel + rw [he,hz,neg_zero] + exact (Submodule.span ℝ {(0:E)}).zero_mem + have hz:=H.distinct s hs t ht (by + simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using + wedge_ne_of_difference_ne a h s t (ha s hs) hw) + intro hh + apply hz + simp only [map_sub,map_smul,smul_eq_mul,LinearMap.sub_apply] at hh ⊢ + nlinarith +end + +section Simultaneous +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] [FiniteDimensional ℝ E] +noncomputable section +lemma generic_for_two_directions (T : ℕ → Finset E) (a b k : Module.Dual ℝ E) + (P : Finset E) : + ∃h : Module.Dual ℝ E,(∀N,GenericOffset (T N) 0 a h) ∧ + (∀N,GenericOffset (T N) 0 b h) ∧ + ∀s∈P,(0(forbidden (T N) 0 a∪forbidden (T N) 0 b).countable_toSet) + have hp : ∀w∈W,w∉Submodule.span ℝ {(0:E)}:=by + intro w hw + obtain ⟨N,hN⟩:=Set.mem_iUnion.mp hw + rcases Finset.mem_union.mp hN with hh|hh + · exact (Finset.mem_filter.mp hh).2 + · exact (Finset.mem_filter.mp hh).2 + obtain ⟨h,h0,havoid,hprobe⟩:=countable_avoid_with_probes W hc 0 hp + (P.image (fun s=>((0:ℝ),s))) 0 k (map_zero k) + have hGa : ∀N,GenericOffset (T N) 0 a h:=by + intro N + refine ⟨h0,?_,?_⟩ + · intro s hs hn + exact havoid s (Set.mem_iUnion.mpr ⟨N,Finset.mem_union_left _ + (Finset.mem_filter.mpr ⟨Finset.mem_union_left _ hs,hn⟩)⟩) + · intro s hs t ht hn + exact havoid _ (Set.mem_iUnion.mpr ⟨N,Finset.mem_union_left _ + (Finset.mem_filter.mpr ⟨Finset.mem_union_right _ (Finset.mem_image.mpr + ⟨(s,t),Finset.mem_product.mpr ⟨hs,ht⟩,rfl⟩),hn⟩)⟩) + have hGb : ∀N,GenericOffset (T N) 0 b h:=by + intro N + refine ⟨h0,?_,?_⟩ + · intro s hs hn + exact havoid s (Set.mem_iUnion.mpr ⟨N,Finset.mem_union_right _ + (Finset.mem_filter.mpr ⟨Finset.mem_union_left _ hs,hn⟩)⟩) + · intro s hs t ht hn + exact havoid _ (Set.mem_iUnion.mpr ⟨N,Finset.mem_union_right _ + (Finset.mem_filter.mpr ⟨Finset.mem_union_right _ (Finset.mem_image.mpr + ⟨(s,t),Finset.mem_product.mpr ⟨hs,ht⟩,rfl⟩),hn⟩)⟩) + refine ⟨h,hGa,hGb,?_⟩ + intro s hs + simpa only [zero_smul,add_zero] using hprobe (0,s) (Finset.mem_image.mpr ⟨s,hs,rfl⟩) +end +end Simultaneous +end ElementaryPositivity.FiniteRayGeometry + +end +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +def RegularCovector (a : Module.Dual ℝ E) : Prop := + ∀N,∀s∈realRootsThrough e C N,s≠0 → a s≠0 + +def segmentBetween (a b : Module.Dual ℝ E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (H : ∀N,GenericOffset (realRootsThrough e C N) 0 (b-a) a) : + GenericLineSegment C e where + direction:=b-a + offset:=a + lo:=0 + hi:=1 + ordered:=zero_lt_one + generic:=H + start_regular:=by + intro N hh + obtain ⟨s,hs,hv,hsa⟩:=(mem_lineEvents_iff _ _ _ _).mp hh + exact HA N s hs (fun hz=>hv (by rw [hz,map_zero])) (by simpa only [zero_smul,add_zero] using hsa) + finish_regular:=by + intro N hh + obtain ⟨s,hs,hv,hsa⟩:=(mem_lineEvents_iff _ _ _ _).mp hh + exact HB N s hs (fun hz=>hv (by rw [hz,map_zero])) (by simpa only [one_smul,add_sub_cancel] using hsa) + +@[simp] lemma segmentBetween_start (a b : Module.Dual ℝ E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (H : ∀N,GenericOffset (realRootsThrough e C N) 0 (b-a) a) : + (segmentBetween C e a b HA HB H).start C e=a := by + simp only [segmentBetween,GenericLineSegment.start,zero_smul,add_zero] +@[simp] lemma segmentBetween_finish (a b : Module.Dual ℝ E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (H : ∀N,GenericOffset (realRootsThrough e C N) 0 (b-a) a) : + (segmentBetween C e a b HA HB H).finish C e=b := by + simp only [segmentBetween,GenericLineSegment.finish,one_smul,add_sub_cancel] + +def GenericLinePath.single (s : GenericLineSegment C e) : + GenericLinePath C e (s.start C e) (s.finish C e) := + .append s (.nil _) + +def GenericLinePath.trans {a b c : Module.Dual ℝ E} + (p : GenericLinePath C e a b) (q : GenericLinePath C e b c) : + GenericLinePath C e a c := + match q with + | .nil _=>p + | .append s q=>.append s (p.trans q) +end + +section Existence +open FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +lemma regularCovector_exists (P : Finset E) (k : Module.Dual ℝ E) : + ∃h : Module.Dual ℝ E,RegularCovector C e h ∧ + ∀s∈P,(0(Ha N).join (HA N)) + have p:=GenericLinePath.single C e s + exact ⟨by simpa only [s,segmentBetween_start,segmentBetween_finish] using p⟩ + · let s:=segmentBetween C e h b HH HB (fun N=>(Hb N).join_reverse (HB N)) + have p:=GenericLinePath.single C e s + exact ⟨by simpa only [s,segmentBetween_start,segmentBetween_finish] using p⟩ + +theorem generic_path_exists (a b : Module.Dual ℝ E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) : + Nonempty (GenericLinePath C e a b) := by + obtain ⟨h,_,_,⟨p⟩,⟨q⟩⟩:=generic_paths_via_intermediate C e a b 0 ∅ HA HB + exact ⟨p.trans C e q⟩ +end +end Existence +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/GeometricFinitePositive.lean b/lean/OAI/Combinatorics/Chromatic/Walls/GeometricFinitePositive.lean new file mode 100644 index 0000000000000000000000000000000000000000..761de2310aa95797e5a115e2586b141f18615625 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/GeometricFinitePositive.lean @@ -0,0 +1,65 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.InputProduct +import OAI.Combinatorics.Chromatic.Walls.FiniteWallPositive +import OAI.Combinatorics.Chromatic.Walls.WeightedInverseAdjoint + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {I M : Type*} [Fintype I] [DecidableEq I] [AddCommGroup M] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀p,Ω p p=0) +variable (p : I → M) (κ : I → ℤ) (ε : I → Bool) +variable (w : I → ℕ) [Fact (∀i,00≤Ω (p i) (p j))) +variable (h : M →+ ℝ) (θ : ℝ) (hh : ∀d,h (rootSum p d)=slopeValue c η θ d) +variable (m : M) + +include hΩ hc hp hn hall hl hh in +lemma geometric_zero_adjoint_positive + (hm : ∀d∈slopeDimensions c η hc θ,0≤Ω (rootSum p d) m) : + let F := PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) + ((l.map (literalAxis κ ε Ω (rootSum p) w)).prod) + IntegralPositive Ω (F*C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit F 1) := by + let a:=geometricQuiver Ω p ε + let : Fact (∀θ,SlopeEulerSymmetric a c η θ) := + ⟨geometricQuiver_symmetric Ω p ε hΩ c η hc t hp⟩ + have H:=literalInput_ordered a κ ε Ω (rootSum p) w + (geometricQuiver_euler Ω p ε hΩ) l hn hall + (geometricQuiver_pairwise Ω p ε hΩ l hn hl) + dsimp only + rw [←H] + exact finiteInput_zero_adjoint_positive a κ c η hc w Ω (rootSum p) + hΩ (geometricQuiver_euler Ω p ε hΩ) θ m hm h hh ε + (geometricQuiver_diag Ω p ε) + +include hΩ hc hp hn hall hl hh in +lemma geometric_zero_inverse_adjoint_positive + (hm : ∀d∈slopeDimensions c η hc θ,Ω (rootSum p d) m≤0) : + let F := PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) + ((l.map (literalAxis κ ε Ω (rootSum p) w)).prod) + IntegralPositive Ω (invOfUnit F 1*C (Torus.X LaurentRay.vUnit Ω m)*F) := by + let a:=geometricQuiver Ω p ε + let : Fact (∀θ,SlopeEulerSymmetric a c η θ) := + ⟨geometricQuiver_symmetric Ω p ε hΩ c η hc t hp⟩ + have H:=literalInput_ordered a κ ε Ω (rootSum p) w + (geometricQuiver_euler Ω p ε hΩ) l hn hall + (geometricQuiver_pairwise Ω p ε hΩ l hn hl) + dsimp only + rw [←H] + exact finiteInput_zero_inverse_adjoint_positive a κ c η hc w Ω (rootSum p) + hΩ (geometricQuiver_euler Ω p ε hΩ) θ m hm h hh ε + (geometricQuiver_diag Ω p ε) +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/GeometricMutationLines.lean b/lean/OAI/Combinatorics/Chromatic/Walls/GeometricMutationLines.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ed8f191fbcb50bb657fd362b638892c9b969663 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/GeometricMutationLines.lean @@ -0,0 +1,158 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallRegrade +import OAI.Combinatorics.Chromatic.QuantumTorus.GeometricMutation + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] +variable (Ω : M →+ M →+ ℤ) (e : M →+ E) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (p : M) +variable (hS : ∀x,S x x=0) (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +lemma realShearCovector_add (h k : Module.Dual ℝ E) : + realShearCovector e S p (h+k)=realShearCovector e S p h+realShearCovector e S p k := by + ext x + simp only [realShearCovector,LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] + ring +lemma realShearCovector_smul (t : ℝ) (h : Module.Dual ℝ E) : + realShearCovector e S p (t • h)=t • realShearCovector e S p h := by + ext x + simp only [realShearCovector,LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] + ring +include hS hcomp in +lemma realShearCovector_incoming (r : M) : + realShearCovector e S p (S.flip (e r))=S.flip (e (mutationShear Ω p r)) := by + have hs : ∀a b,S a b= -S b a:=by + intro a b + have H:=hS (a+b) + simp only [map_add,LinearMap.add_apply,hS] at H + linarith + ext x + change S x (e r)+S (e p) (e r)*S (e p) x=S x (e (r-Ω p r • p)) + rw [map_sub,map_zsmul,map_sub,map_zsmul,hcomp,hs x (e p)] + simp only [zsmul_eq_mul] + ring +include hS hcomp in +lemma realShearCovector_incidence (h : Module.Dual ℝ E) (m : M) : + realShearCovector e S p h (e (mutationShear Ω p m))=h (e m) := by + have hp : Ω p p=0:=by + have H:=hS (e p) + rw [hcomp] at H + exact_mod_cast H + change ((realShearCovector e S p h).toAddMonoidHom.comp e) (mutationShear Ω p m)=_ + rw [realShearCovector_lattice Ω e S p hcomp] + change h (e (mutationShearInverse Ω p (mutationShear Ω p m)))=_ + rw [mutationShear_left_inverse Ω p hp] + +def realSideCovector (pos : Bool) (h : Module.Dual ℝ E) : Module.Dual ℝ E := + if pos then h else realShearCovector e S p h +lemma realMutationCovector_eq_side (pos : Bool) (h : Module.Dual ℝ E) + (hside : if pos then 0≤h (e p) else h (e p)≤0) : + realMutationCovector e S p h=realSideCovector e S p pos h := by + cases pos + · change h (e p)≤0 at hside + change (if 0≤h (e p) then h else realShearCovector e S p h)=realShearCovector e S p h + by_cases hh : 0≤h (e p) + · rw [ite_eq_left hh,realShearCovector,le_antisymm hside hh,zero_smul,add_zero] + · rw [ite_eq_right hh] + · change 0≤h (e p) at hside + exact ite_eq_left hside + +include hS hcomp in +lemma realSideCovector_incoming_line (pos : Bool) (k : Module.Dual ℝ E) (r : M) (t : ℝ) : + realSideCovector e S p pos (k+t • S.flip (e r))= + realSideCovector e S p pos k+t • S.flip (e (if pos then r else mutationShear Ω p r)) := by + cases pos + · change realShearCovector e S p (k+t • S.flip (e r))= + realShearCovector e S p k+t • S.flip (e (mutationShear Ω p r)) + rw [realShearCovector_add,realShearCovector_smul,realShearCovector_incoming Ω e S p hS hcomp] + · rfl +include hS hcomp in +lemma realSideCovector_incidence (pos : Bool) (h : Module.Dual ℝ E) (r : M) : + realSideCovector e S p pos h (e (if pos then r else mutationShear Ω p r))=h (e r) := by + cases pos + · exact realShearCovector_incidence Ω e S p hS hcomp h r + · rfl +include hS hcomp in +lemma realMutationCovector_incoming_line (pos : Bool) (k : Module.Dual ℝ E) (r : M) (t : ℝ) + (hside : if pos then 0≤(k+t • S.flip (e r)) (e p) else (k+t • S.flip (e r)) (e p)≤0) : + realMutationCovector e S p (k+t • S.flip (e r))= + realSideCovector e S p pos k+t • S.flip (e (if pos then r else mutationShear Ω p r)) := by + rw [realMutationCovector_eq_side e S p pos _ hside] + exact realSideCovector_incoming_line Ω e S p hS hcomp pos k r t +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (pc : I) (pos : Bool) +omit [Fintype I] in +lemma mutationLinearPiece_positive_ray (r m : M) (hr : OnPositiveRay r m) : + OnPositiveRay (mutationLinearPiece Ω C pc pos r) (mutationLinearPiece Ω C pc pos m) := by + obtain ⟨a,b,ha,hb,he⟩:=hr + refine ⟨a,b,ha,hb,?_⟩ + simpa only [map_nsmul] using congrArg (mutationLinearPiece Ω C pc pos) he + +variable {R : Type*} [CommRing R] (v : Rˣ) +local instance geometricMutationLinesRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance geometricMutationLinesAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance geometricMutationLinesAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +lemma mutationCompletion_ray_support (f : PowerSeries (Torus v Ω)) (hc : constantCoeff f=1) + (r : M) (hr : ∀n m,coeff (n+1) f m≠0 → OnPositiveRay r m) : + ∀d m,coeff (d+1) (mutationCompletion Ω hΩ C coord pc pos v f) m≠0 → + OnPositiveRay (mutationLinearPiece Ω C pc pos r) m := by + classical + intro d m hm + obtain ⟨a,rfl⟩:=mutationLinearPiece_surjective Ω hΩ C pc pos m + rw [mutationCompletion_coeff_read] at hm + split_ifs at hm with hd + · obtain ⟨n,hn,hna⟩:=Finset.exists_ne_zero_of_sum_ne_zero hm + cases n with + | zero => + rw [coeff_zero_eq_constantCoeff_apply,hc] at hna + have ha : a=0:=by + by_contra hh + exact hna (Finsupp.single_eq_of_ne hh) + rw [ha,map_zero,Int.toNat_zero] at hd + omega + | succ n =>exact mutationLinearPiece_positive_ray Ω C pc pos r a (hr n a hna) + · exact (hm rfl).elim + +variable (hcoord : ∀d,coord (C d)=d) +variable {E : Type*} [AddCommGroup E] [Module ℝ E] +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) +lemma actualMutatedWall_ray_support (r : M) (dr : ℕ) (hdr : 0 + intro r d hd hr h hg + have H:=rootClosedThrough_self LaurentRay.vUnit Ω (N:=0) (literalRootProducts_one Ω C (OnPositiveRay r)) + apply H.congr LaurentRay.vUnit Ω + intro i hi + have hi0 : i=0:=by omega + subst i + rw [coeff_zero_eq_constantCoeff,map_one,(chartZero LaurentRay.vUnit Ω C _ F).property.1] + | succ n ih => + intro r d hd hr h hg + let S:=realRootsThrough e C (n+1) + let vR:=B.flip (e r) + obtain ⟨k,Hk,Hsign⟩:=exists_generic_offset S (e r) vR h hg.1 + let events:=lineEvents S vR k + let P (a : ℝ):=RootClosedThrough LaurentRay.vUnit Ω (n+1) + (literalRootProducts Ω C (OnPositiveRay r)) + (chartZero LaurentRay.vUnit Ω C ((k+a • vR).toAddMonoidHom.comp e) F).val + have h0 : (0:ℝ)∉events:=by + intro hevent + obtain ⟨s,hs,hv,hs0⟩:=(mem_lineEvents_iff S vR k 0).mp hevent + have hn : s∉Submodule.span ℝ {e r}:=by + intro hmem + obtain ⟨c,hc⟩:=Submodule.mem_span_singleton.mp hmem + apply hv + rw [←hc,map_smul] + change c*B (e r) (e r)=0 + rw [hB,mul_zero] + apply Hk.avoid s hs hn + simpa only [zero_smul,add_zero] using hs0 + have hstart : ∃b,0 ≤ b ∧ (∀a∈events,a < b) ∧ P b:=by + obtain ⟨D,hD,hpos,hpres⟩:=incoming r d hd hr + obtain ⟨b,hb,hbound,hwall⟩:=incoming_positive_at_far Ω C e he B hB hcomp L hdeg + (n+1) d r hd hr k Hk F D hD (hpos.cut LaurentRay.vUnit Ω (n+1)) + (fun j hj m hm => hpres j m hm) + exact ⟨b,hb.le,hbound,hwall⟩ + have hcell : ∀a b,0 ≤ a → 0 ≤ b → a∉events → b∉events → + (∀z∈events,a < z ↔ b < z) → P a → P b:=by + intro a b ha hb haS hbS Hside hpa + apply hpa.congr LaurentRay.vUnit Ω + apply chart_sign_congr_through LaurentRay.vUnit Ω C _ _ F (n+1) + intro j hj hjN m hm + exact line_cell_signs S vR k a b haS hbS Hside (e m) (realRoot_mem e C (n+1) j hjN m hm) + have hstep : ∀a∈events,0 < a → ∃ε > 0,∀δ : ℝ,0 < δ → δ < ε → P (a+δ) → P (a-δ):=by + intro a ha ha0 + exact wall_joint_induction Ω C e he B hB hcomp L hdeg n d r hd hr F ih k Hk a ha + have HK : RootClosedThrough LaurentRay.vUnit Ω (n+1) (literalRootProducts Ω C (OnPositiveRay r)) + (chartZero LaurentRay.vUnit Ω C (k.toAddMonoidHom.comp e) F).val:=by + have HH:=descend events P hstart hcell hstep 0 (le_refl 0) h0 + simpa only [P,zero_smul,add_zero] using HH + have Hchart:=chart_sign_congr_through LaurentRay.vUnit Ω C (h.toAddMonoidHom.comp e) + (k.toAddMonoidHom.comp e) F (n+1) (by + intro j hj hjN m hm + have HS:=Hsign (e m) (realRoot_mem e C (n+1) j hjN m hm) + refine ⟨HS.1,?_,HS.2⟩ + intro hh + exact ((hg.2 j hj hjN m hm hh).eval (k.toAddMonoidHom.comp e)).2.1.mpr Hk.on_ray) + exact HK.congr LaurentRay.vUnit Ω (fun j hj => (Hchart j hj).symm) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +attribute [local instance] Classical.propDecidable +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) + +def literalIncomingRay (l : List (WallUnitDatum M)) (r : M) : + PowerSeries (Torus LaurentRay.vUnit Ω) := by + classical + exact ((l.filter (fun u => OnPositiveRay r u.root)).map (WallUnitDatum.value Ω)).prod +lemma literalIncomingRay_mem (l : List (WallUnitDatum M)) + (hl : ∀u∈l,u.Allowed C (fun _=>True)) (r : M) : + literalIncomingRay Ω l r∈literalRootProducts Ω C (OnPositiveRay r) := by + classical + refine ⟨l.filter (fun u => OnPositiveRay r u.root),?_,rfl⟩ + intro u hu + have H:=List.mem_filter.mp hu + exact ⟨(hl u H.1).1,(hl u H.1).2.1,by simpa using H.2⟩ +lemma literalIncomingRay_eq (l : List (WallUnitDatum M)) {r m : M} + (hm : OnPositiveRay r m) : literalIncomingRay Ω l r=literalIncomingRay Ω l m := by + classical + unfold literalIncomingRay + rw [hm.eq_pred] +def literalIncomingCompleted (l : List (WallUnitDatum M)) + (hl : ∀u∈l,u.Allowed C (fun _=>True)) (r : M) : CompletedPositive LaurentRay.vUnit Ω C := + ⟨literalIncomingRay Ω l r, + literalRootProducts_constant Ω C _ (literalIncomingRay_mem Ω C l hl r), + literalRootProducts_graded Ω C _ (literalIncomingRay_mem Ω C l hl r)⟩ + +def literalIncomingLog (l : List (WallUnitDatum M)) (n : ℕ) : Torus LaurentRay.vUnit Ω := by + classical + exact Finsupp.onFinset (rootDegree_finite C n).toFinset + (fun m => if HasRootDegree C n m then coeff n (FormalLog.log (literalIncomingRay Ω l m)) m else 0) + (by intro m hm; rw [Set.Finite.mem_toFinset]; by_contra hn; exact hm (ite_eq_right hn)) +lemma literalIncomingLog_apply (l : List (WallUnitDatum M)) (n : ℕ) (m : M) : + literalIncomingLog Ω C l n m= + if HasRootDegree C n m then coeff n (FormalLog.log (literalIncomingRay Ω l m)) m else 0 := by + classical + rfl +lemma literalIncomingLog_graded (l : List (WallUnitDatum M)) (n : ℕ) : + literalIncomingLog Ω C l n∈rootGrade LaurentRay.vUnit Ω C n := by + classical + intro m hm + rw [literalIncomingLog_apply,ite_eq_right hm] + +def literalTotalTransport (l : List (WallUnitDatum M)) : CompletedPositive LaurentRay.vUnit Ω C := + ⟨incomingSolution LaurentRay.vUnit Ω C (literalIncomingLog Ω C l), + incomingSolution_constant LaurentRay.vUnit Ω C _, + incomingSolution_graded LaurentRay.vUnit Ω C _ (literalIncomingLog_graded Ω C l)⟩ +lemma literalTotalTransport_prescription (hΩ : ∀m,Ω m m=0) + (l : List (WallUnitDatum M)) (hl : ∀u∈l,u.Allowed C (fun _=>True)) : + PositiveIncomingPrescription Ω C (literalTotalTransport Ω C l) := by + classical + intro r d hd hr + let D:=literalIncomingCompleted Ω C l hl r + refine ⟨D,?_,inPrecisionClosure_self LaurentRay.vUnit Ω (literalIncomingRay_mem Ω C l hl r),?_⟩ + · intro n m hm + by_contra hh + exact hm (literalRootProducts_strictSupport Ω C (OnPositiveRay r) + (fun a b ha hb=>ha.add hb) (literalIncomingRay_mem Ω C l hl r) n m hh) + · intro n m hm + cases n with + | zero => simp only [coeff_zero_eq_constantCoeff,FormalLog.log_constant,Finsupp.zero_apply] + | succ n => + by_cases hroot : HasRootDegree C (n+1) m + · have H:=congrArg (fun x : Torus LaurentRay.vUnit Ω=>x m) + (incomingSolution_prescription LaurentRay.vUnit Ω C hΩ _ (literalIncomingLog_graded Ω C l) n) + rw [incomingCoefficient_apply,ite_eq_left hroot,literalIncomingLog_apply,ite_eq_left hroot] at H + change coeff (n+1) (FormalLog.log (chartZero LaurentRay.vUnit Ω C (incomingCovector Ω m) + (literalTotalTransport Ω C l)).val) m=coeff (n+1) (FormalLog.log (literalIncomingRay Ω l r)) m + rw [literalIncomingRay_eq Ω l hm] + exact H + · rw [root_graded_log LaurentRay.vUnit Ω C _ (n+1) m hroot, + root_graded_log LaurentRay.vUnit Ω C D (n+1) m hroot] + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/Grade.lean b/lean/OAI/Combinatorics/Chromatic/Walls/Grade.lean new file mode 100644 index 0000000000000000000000000000000000000000..f8de7ab84fce7d9f8bc2bedffc0d42487491b636 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/Grade.lean @@ -0,0 +1,65 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalGrade + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +variable {M : Type*} [AddCommGroup M] [Module ℚ M] +noncomputable def gradeTopBotEquiv : Grade (⊤ : Submodule ℚ M) ⊥ ≃ₗ[ℚ] M := + ((next (⊤ : Submodule ℚ M) ⊥).quotEquivOfEqBot (by + ext x + simp [next])).trans (Submodule.topEquiv) + +lemma grade_same_subsingleton (F : Submodule ℚ M) : Subsingleton (Grade F F) := by + have h : next F F=⊤ := by ext x; simp [next] + change Subsingleton (F ⧸ next F F) + rw [h] + infer_instance +end ElementaryPositivity.LinearFiltration + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial ElementaryPositivity.SlopeArithmetic ElementaryPositivity.LinearFiltration +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [Fintype I] [DecidableEq I] in +noncomputable def zeroPolynomialEquiv : S (0 : I → ℕ) ≃ₗ[ℚ] ℚ where + toFun f := constantCoeff f.val + invFun r := r • (1 : S (0 : I → ℕ)) + left_inv := fun f=>(S_zero_eq_scalar f).symm + right_inv := by intro r; simp + map_add' f g := by simp + map_smul' r f := by simp + +noncomputable def zeroQuotientEquiv (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) : + B a μ 0 ≃ₗ[ℚ] ℚ := + ((destabilizingSpace a μ 0).quotEquivOfEqBot (destabilizingSpace_zero a μ)).trans zeroPolynomialEquiv + +lemma unitalSourceFiltration_zero (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0if j < i then f i j else 0),←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro i hi + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro j hj + split_ifs <;> simp + +namespace NaturalUnitIntervalGraph +open QuantumTorus +variable {n r:ℕ} (G:NaturalUnitIntervalGraph n) +variable {M V:Type*} [AddCommGroup M] [Fintype V] [DecidableEq V] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) (u:V → M) (b:Fin n ↪ V) +variable (hp:∀i j,i < j → Ω (u (b i)) (u (b j))= -(if G.Edge i j then 1 else 0)) + +include hΩ hp in +omit [Fintype V] [DecidableEq V] in +lemma pairing_zero_iff (i j:Fin n) : Ω (u (b i)) (u (b j))=0 ↔ ¬G.Edge i j := by + rcases lt_trichotomy i j with h|h|h + · rw [hp i j h] + by_cases he:G.Edge i j <;> simp [he] + · subst j; simp [hΩ] + · rw [QuantumTorus.alternating_skew Ω hΩ, hp j i h,G.edge_comm i j] + simp + +include hΩ hp in +omit [Fintype V] [DecidableEq V] in +lemma independent_blocks_iff (κ:Fin n → Fin r) : + (∀c,IsIndependent Ω u (SquarefreeBlocks.blocks b κ c)) ↔ G.Proper κ := by + constructor + · intro h i j he heq + have H:=h (κ i) (b i) ((SquarefreeBlocks.mem_blocks b κ _ _).mpr ⟨i,rfl,rfl⟩) + (b j) ((SquarefreeBlocks.mem_blocks b κ _ _).mpr ⟨j,heq.symm,rfl⟩) + exact ((G.pairing_zero_iff Ω hΩ u b hp i j).mp H) he + · intro h c x hx y hy + obtain ⟨i,hi,rfl⟩:=(SquarefreeBlocks.mem_blocks b κ c x).mp hx + obtain ⟨j,hj,rfl⟩:=(SquarefreeBlocks.mem_blocks b κ c y).mp hy + apply (G.pairing_zero_iff Ω hΩ u b hp i j).mpr + exact fun he=>h i j he (hi.trans hj.symm) + +include hΩ hp in +omit [Fintype V] [DecidableEq V] in +lemma blockValid_iff (κ:Fin n → Fin r) (a:Fin r → ℕ) : + BlockValid Ω u a (SquarefreeBlocks.blocks b κ) ↔ + G.Proper κ ∧ ∀c,(Finset.univ.filter (fun i=>κ i=c)).card=a c := by + rw [BlockValid,forall_and,G.independent_blocks_iff Ω hΩ u b hp] + simp only [SquarefreeBlocks.blocks,Finset.card_map] + +include hΩ hp in +omit [Fintype V] [DecidableEq V] in +lemma blocks_energy (κ:Fin n → Fin r) (hκ:G.Proper κ) : + wordEnergy Ω (blockLabels u (SquarefreeBlocks.blocks b κ))= + 2*(G.coloringInversions κ:ℤ)-(G.edgeCount:ℤ) := by + rw [wordEnergy_blocks,ordered_pair_sum _ (by intro i; simp)] + have H:∀i j:Fin n,(if i < j then + (if κ i<κ j then Ω (u (b i)) (u (b j)) else 0)+ + (if κ j<κ i then Ω (u (b j)) (u (b i)) else 0) else 0)= + (if i < j ∧ G.Edge i j ∧ κ j<κ i then (1:ℤ) else 0)- + (if i < j ∧ G.Edge i j ∧ κ i<κ j then (1:ℤ) else 0) := by + intro i j + by_cases hij:i < j + · rw [ite_eq_left hij,QuantumTorus.alternating_skew Ω hΩ (u (b j)) (u (b i)),hp i j hij] + by_cases he:G.Edge i j + · rcases lt_or_gt_of_ne (hκ i j he) with h|h + · simp [hij,he,h,not_lt_of_gt h] + · simp [hij,he,h,not_lt_of_gt h] + · simp [hij,he] + · simp [hij] + simp only [H,Finset.sum_sub_distrib] + have hi:(G.coloringInversions κ:ℤ)= + ∑i:Fin n,∑j:Fin n,if i < j ∧ G.Edge i j ∧ κ j<κ i then (1:ℤ) else 0 := by + simp only [coloringInversions,edges,Finset.filter_filter,Finset.card_eq_sum_ones, + Nat.cast_sum,Finset.sum_filter,Fintype.sum_prod_type,apply_ite,Nat.cast_one,Nat.cast_zero] + congr 2 + funext i + congr 1 + funext j + simp [and_assoc] + have ha:(G.coloringAscents κ:ℤ)= + ∑i:Fin n,∑j:Fin n,if i < j ∧ G.Edge i j ∧ κ i<κ j then (1:ℤ) else 0 := by + simp only [coloringAscents,Finset.card_eq_sum_ones, + Nat.cast_sum,Finset.sum_filter,Fintype.sum_prod_type,apply_ite,Nat.cast_one,Nat.cast_zero] + rw [←hi,←ha] + have hc: (G.coloringInversions κ:ℤ)+(G.coloringAscents κ:ℤ)=(G.edgeCount:ℤ):=by + exact_mod_cast G.coloringInversions_add_ascents κ hκ + omega +end NaturalUnitIntervalGraph +end +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/GraphTriangularEmbedding.lean b/lean/OAI/Combinatorics/Chromatic/Walls/GraphTriangularEmbedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfbbffd93159655f48c875d10c9a401f29eefcce --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/GraphTriangularEmbedding.lean @@ -0,0 +1,129 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteLatticePairing +import OAI.Combinatorics.Chromatic.QuantumTorus.GraphRationalModel + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators +open Classical +noncomputable section + +def rankedCell {n:ℕ} (l:Fin n → ℕ) (r:Equiv.Perm (Fin n)) (i:Fin n) : + Cell (n+1+∑j,l j) := + ⟨⟨n+l i,by have H:=Finset.single_le_sum (f:=l) (fun _ _=>Nat.zero_le _) (Finset.mem_univ i); omega⟩, + ⟨(r i).rev.val,by change (r i).rev.val < n+l i+1; have H: (r i).rev.val < n:=(r i).rev.isLt; omega⟩⟩ + +lemma rankedCell_level {n:ℕ} (l:Fin n → ℕ) (r:Equiv.Perm (Fin n)) (i:Fin n) : + (rankedCell l r i).1.val=n+l i := rfl +lemma rankedCell_row {n:ℕ} (l:Fin n → ℕ) (r:Equiv.Perm (Fin n)) (i:Fin n) : + cellRow (rankedCell l r i)=(r i).rev.val := rfl +lemma rankedCell_injective {n:ℕ} (l:Fin n → ℕ) (r:Equiv.Perm (Fin n)) : + Function.Injective (rankedCell l r) := by + intro i j h + have H:=congrArg cellRow h + exact r.injective (Fin.rev_injective (Fin.ext H)) +lemma rankedCell_phase {n:ℕ} (l:Fin n → ℕ) (r:Equiv.Perm (Fin n)) (i j:Fin n) : + phaseEarlier (rankedCell l r i) (rankedCell l r j) ↔ r i < r j := by + unfold phaseEarlier + rw [rankedCell_row,rankedCell_row] + have hrev: (r j).rev.val < (r i).rev.val ↔ r i < r j:=Fin.rev_lt_rev + rw [hrev] + constructor + · rintro (h|⟨h,h'⟩) + · exact h + · have hij:=r.injective (Fin.rev_injective (Fin.ext h)) + subst j + exact (lt_irrefl _ h').elim + · exact Or.inl + +lemma floor_pair_comparisons {x y:ℚ} (_hx:0≤x) (hy:0≤y) (hxy:x < y) : + ⌊x⌋₊≤⌊y⌋₊ ∧ + (⌊x⌋₊=⌊y⌋₊ → x-(⌊x⌋₊:ℚ) < y-(⌊y⌋₊:ℚ)) ∧ + (⌊y⌋₊=⌊x⌋₊+1 → (y < x+1 ↔ y-(⌊y⌋₊:ℚ) < x-(⌊x⌋₊:ℚ))) ∧ + (⌊x⌋₊+2≤⌊y⌋₊ → x+1 < y) := by + refine ⟨Nat.floor_mono (le_of_lt hxy),?_,?_,?_⟩ + · intro h + rw [h] + linarith + · intro h + rw [h,Nat.cast_add,Nat.cast_one] + constructor <;> intro H <;> linarith + · intro h + have h':(⌊x⌋₊:ℚ)+2≤(⌊y⌋₊:ℚ):=by exact_mod_cast h + linarith [Nat.lt_floor_add_one x,Nat.floor_le hy] + +theorem graph_triangular_embedding {n:ℕ} (G:NaturalUnitIntervalGraph n) : + ∃d:ℕ,∃b:Fin n ↪ Cell d,∀i j,i < j → + bridgePositive (b j) (b i)=(if G.Edge i j then 1 else 0) ∧ + bridgePositive (b i) (b j)=0 := by + obtain ⟨t,ht,hm,he⟩:=G.rational_model + let l:Fin n → ℕ:=fun i=>⌊t i⌋₊ + let f:Fin n → ℚ:=fun i=>t i-(l i:ℚ) + obtain ⟨r,hr⟩:=phase_rank f + refine ⟨n+1+∑j,l j,⟨rankedCell l r,rankedCell_injective l r⟩,?_⟩ + intro i j hij + have H:=floor_pair_comparisons (le_of_lt (ht i)) (le_of_lt (ht j)) (hm hij) + change l i≤l j ∧ (l i=l j → f i < f j) ∧ + (l j=l i+1 → (t j < t i+1 ↔ f j < f i)) ∧ (l i+2≤l j → t i+1 < t j) at H + have hedge:G.Edge i j ↔ j≤G.h i:=by + simp only [NaturalUnitIntervalGraph.Edge,hij,true_and,not_lt_of_gt hij,false_and,or_false] + have hclose:G.Edge i j ↔ t j < t i+1:=by + rw [hedge] + constructor + · exact (he i j hij).1 + · intro hh + by_contra hn + linarith [(he i j hij).2 (lt_of_not_ge hn)] + have heq:(rankedCell l r i).1=(rankedCell l r j).1 ↔ l i=l j:=by + simp only [Fin.ext_iff,rankedCell_level,Nat.add_left_cancel_iff] + have hnot:(rankedCell l r i).1.val+1≠(rankedCell l r j).1.val ↔ l i+1≠l j:=by + simp only [rankedCell_level]; omega + have hji: ¬((rankedCell l r j).1.val+1=(rankedCell l r i).1.val):=by + simp only [rankedCell_level] + omega + by_cases hl:l i=l j + · have hp:r i < r j:=(hr i j).mpr (Or.inl (H.2.1 hl)) + have htime:t j < t i+1:=by + have hf0:0≤f i:=sub_nonneg.mpr (Nat.floor_le (le_of_lt (ht i))) + have hf1:f j < 1:=by dsimp [f,l]; linarith [Nat.lt_floor_add_one (t j)] + dsimp [f] at hf0 hf1 + rw [←hl] at hf1 + linarith + have hed:=hclose.mpr htime + constructor + · simp [bridgePositive,rankedCell_phase,(heq.mpr hl).symm,hp,hed] + · simp [bridgePositive,rankedCell_phase,heq.mpr hl,not_lt_of_gt hp] + · have hl':l i < l j:=lt_of_le_of_ne H.1 hl + have hpnot:¬(rankedCell l r j).1=(rankedCell l r i).1:=by + intro he'; exact hl (heq.mp he'.symm) + have hsmall:¬(rankedCell l r i).1=(rankedCell l r j).1:=by + intro he'; exact hl (heq.mp he') + constructor + · rw [bridgePositive,ite_eq_right (by simp [hpnot])] + have hequiv: (rankedCell l r i).1.val+1=(rankedCell l r j).1.val ∧ + phaseEarlier (rankedCell l r j) (rankedCell l r i) ↔ G.Edge i j:=by + rw [rankedCell_phase,rankedCell_level,rankedCell_level,hclose] + constructor + · rintro ⟨hl1,hp⟩ + have hll:l j=l i+1:=by omega + rcases (hr j i).mp hp with hf|⟨_,hji'⟩ + · exact (H.2.2.1 hll).mpr hf + · exact (lt_asymm hij hji').elim + · intro hh + have hll:l j=l i+1:=by + by_contra hn + have hh':l i+2≤l j:=by omega + linarith [H.2.2.2 hh'] + refine ⟨by omega,(hr j i).mpr (Or.inl ((H.2.2.1 hll).mp hh))⟩ + change (if (rankedCell l r i).1.val+1=(rankedCell l r j).1.val ∧ + phaseEarlier (rankedCell l r j) (rankedCell l r i) then (1:ℤ) else 0)=_ + simp only [hequiv] + · simp [bridgePositive,hsmall,hji] +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/Grid.lean b/lean/OAI/Combinatorics/Chromatic/Walls/Grid.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7a6d1f1c2fdafa87077c3996ea367f723c521d4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/Grid.lean @@ -0,0 +1,63 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.Pack +import OAI.Combinatorics.Chromatic.Shuffle.RestrictSplit + +namespace OAI + +section +namespace ElementaryPositivity.PackConvolution +open ElementaryPositivity.ShuffleConvolution +variable {I : Type*} {A : I → Type*} +variable [∀ i,DecidableEq (A i)] +variable {R : Type*} [CommSemiring R] + +def grid {s : Pack (A:=A)} (p : Cut s) : Cut s ≃ Cut (left p) × Cut (right p) := + (Equiv.piCongrRight fun i => ShuffleConvolution.grid (p i)).trans + { toFun := fun q => (fun i => (q i).1, fun i => (q i).2) + invFun := fun q i => (q.1 i,q.2 i) + left_inv := by intro q; rfl + right_inv := by intro q; rfl } + +lemma grid_inverse_left {s : Pack (A:=A)} (p : Cut s) (q : Cut (left p)) (r : Cut (right p)) : + left ((grid p).symm (q,r)) = fun i => left q i ∪ left r i := rfl +lemma grid_inverse_right {s : Pack (A:=A)} (p : Cut s) (q : Cut (left p)) (r : Cut (right p)) : + right ((grid p).symm (q,r)) = fun i => right q i ∪ right r i := rfl + +variable [Fintype I] + +lemma grid_kernel (w : (Σi,A i) → (Σi,A i) → R) + {s : Pack (A:=A)} (p : Cut s) (q : Cut (left p)) (r : Cut (right p)) : + kernel w (left ((grid p).symm (q,r))) (right ((grid p).symm (q,r))) = + kernel w (left q) (right q) * kernel w (left r) (right r) * + kernel w (left q) (right r) * kernel w (left r) (right q) := by + have hl : ∀ i,Disjoint (left q i) (left r i) := fun i => + (p i).property.1.mono (q i).left_subset (r i).left_subset + have hr : ∀ i,Disjoint (right q i) (right r i) := fun i => + (p i).property.1.mono (q i).right_subset (r i).right_subset + rw [grid_inverse_left,grid_inverse_right, + kernel_union_left w (left q) (left r) (fun i => right q i ∪ right r i) hl, + kernel_union_right w (left q) (right q) (right r) hr, + kernel_union_right w (left r) (right q) (right r) hr] + ac_rfl + +variable [DecidableEq I] [∀ i,Fintype (A i)] + +theorem shuffle_grid (w : (Σi,A i) → (Σi,A i) → R) + (f g : Pack (A:=A) → R) {s : Pack (A:=A)} (p : Cut s) : + shuffle w f g s = ∑ q : Cut (left p), ∑ r : Cut (right p), + f (fun i => left q i ∪ left r i) * g (fun i => right q i ∪ right r i) * + (kernel w (left q) (right q) * kernel w (left r) (right r) * + kernel w (left q) (right r) * kernel w (left r) (right q)) := by + rw [shuffle,← (grid p).symm.sum_comp] + simp only [Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro q hq + apply Finset.sum_congr rfl + intro r hr + rw [grid_kernel,grid_inverse_left,grid_inverse_right] + +end ElementaryPositivity.PackConvolution + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/HNGeometry.lean b/lean/OAI/Combinatorics/Chromatic/Walls/HNGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..f13c3fc75681c7fabfb5da27a26874cde9aa9e36 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/HNGeometry.lean @@ -0,0 +1,233 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.Mass + +namespace OAI + +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] +variable (c η : I → ℝ) +noncomputable def slopeCross (d e : I → ℕ) : ℝ := mass η d*mass c e-mass c d*mass η e +@[simp] lemma slopeCross_zero_left (e : I → ℕ) : slopeCross c η 0 e=0 := by simp [slopeCross] +@[simp] lemma slopeCross_zero_right (d : I → ℕ) : slopeCross c η d 0=0 := by simp [slopeCross] +lemma slopeCross_add_left (d e b : I → ℕ) : + slopeCross c η (d+e) b=slopeCross c η d b+slopeCross c η e b := by simp [slopeCross,mass_add]; ring +lemma slopeCross_add_right (d e b : I → ℕ) : + slopeCross c η d (e+b)=slopeCross c η d e+slopeCross c η d b := by simp [slopeCross,mass_add]; ring +lemma slopeCross_eq (hc : ∀ i,0 < c i) (d e : I → ℕ) : + slopeCross c η d e=(slope c η d-slope c η e)*(mass c d*mass c e) := by + rw [slopeCross,mass_eq c η hc d,mass_eq c η hc e] + ring +lemma slopeCross_pos_iff (hc : ∀ i,0 < c i) {d e : I → ℕ} (hd : d≠0) (he : e≠0) : + 0 < slopeCross c η d e ↔ slope c η e < slope c η d := by + rw [slopeCross_eq c η hc,mul_pos_iff_of_pos_right (mul_pos (mass_pos c hc d hd) (mass_pos c hc e he)),sub_pos] +lemma slopeCross_nonpos_iff (hc : ∀ i,0 < c i) {d e : I → ℕ} (hd : d≠0) (he : e≠0) : + slopeCross c η d e ≤ 0 ↔ slope c η d ≤ slope c η e := by + rw [←not_lt, slopeCross_pos_iff c η hc hd he,not_lt] + +noncomputable def polygonArea : List (I → ℕ) → ℝ + | [] => 0 + | d::l => slopeCross c η d l.sum+polygonArea l +@[simp] lemma polygonArea_nil : polygonArea c η []=0 := rfl +@[simp] lemma polygonArea_cons (d : I → ℕ) (l : List (I → ℕ)) : + polygonArea c η (d::l)=slopeCross c η d l.sum+polygonArea c η l := rfl +@[simp] lemma polygonArea_singleton (d : I → ℕ) : polygonArea c η [d]=0 := by simp +lemma slopeCross_list_sum (d : I → ℕ) (l : List (I → ℕ)) : + slopeCross c η d l.sum=(l.map (slopeCross c η d)).sum := by + induction l with + | nil => simp + | cons e l ih => simp [slopeCross_add_right,ih] +lemma polygonArea_append (l r : List (I → ℕ)) : + polygonArea c η (l++r)=polygonArea c η l+polygonArea c η r+slopeCross c η l.sum r.sum := by + induction l with + | nil => simp + | cons d l ih => simp [ih,slopeCross_add_right,slopeCross_add_left]; ring + +def HNOrdered (l : List (I → ℕ)) : Prop := + (∀ d∈l,d≠0) ∧ l.Pairwise (fun d e=>slope c η e < slope c η d) + +lemma polygonArea_nonneg (hc : ∀ i,0 < c i) {l : List (I → ℕ)} (hl : HNOrdered c η l) : + 0 ≤ polygonArea c η l := by + induction l with + | nil => exact le_refl 0 + | cons d l ih => + have hpair := List.pairwise_cons.mp hl.2 + have htail : HNOrdered c η l := ⟨fun e he=>hl.1 e (List.mem_cons_of_mem _ he),hpair.2⟩ + rw [polygonArea_cons,slopeCross_list_sum] + apply add_nonneg _ (ih htail) + apply List.sum_nonneg + intro x hx + obtain ⟨e,he,rfl⟩ := List.mem_map.mp hx + exact ((slopeCross_pos_iff c η hc (hl.1 d (by simp)) (htail.1 e he)).mpr (hpair.1 e he)).le + +lemma polygonArea_pos (hc : ∀ i,0 < c i) {l : List (I → ℕ)} (hl : HNOrdered c η l) + (hlen : 2 ≤ l.length) : 0 < polygonArea c η l := by + cases l with + | nil => simp at hlen + | cons d l => + cases l with + | nil => simp at hlen + | cons e l => + have hp := List.pairwise_cons.mp hl.2 + have ht : HNOrdered c η (e::l) := ⟨fun x hx=>hl.1 x (List.mem_cons_of_mem _ hx),hp.2⟩ + have hrest : 0 ≤ slopeCross c η d l.sum := by + rw [slopeCross_list_sum] + apply List.sum_nonneg + intro x hx + obtain ⟨y,hy,rfl⟩ := List.mem_map.mp hx + exact ((slopeCross_pos_iff c η hc (hl.1 d (by simp)) + (hl.1 y (by simp [hy]))).mpr (hp.1 y (by simp [hy]))).le + have hde : 0 < slopeCross c η d e := + (slopeCross_pos_iff c η hc (hl.1 d (by simp)) (hl.1 e (by simp))).mpr (hp.1 e (by simp)) + simpa only [polygonArea_cons,List.sum_cons,slopeCross_add_right] using + add_pos_of_pos_of_nonneg (add_pos_of_pos_of_nonneg hde hrest) (polygonArea_nonneg c η hc ht) + +lemma polygonArea_replace (l r q : List (I → ℕ)) (d e : I → ℕ) (hq : q.sum=d+e) : + polygonArea c η (l++q++r)-polygonArea c η (l++[d,e]++r)= + polygonArea c η q-slopeCross c η d e := by + simp only [polygonArea_append,List.sum_append,hq,List.sum_cons,List.sum_nil,add_zero, + polygonArea_cons,polygonArea_nil,slopeCross_zero_right] + ring + +lemma reorder_progress (hc : ∀ i,0 < c i) (l r q : List (I → ℕ)) {d e : I → ℕ} + (hd : d≠0) (he : e≠0) (hde : slope c η d ≤ slope c η e) + (hq : q.sum=d+e) (ho : HNOrdered c η q) : + polygonArea c η (l++[d,e]++r) < polygonArea c η (l++q++r) ∨ + (polygonArea c η (l++[d,e]++r)=polygonArea c η (l++q++r) ∧ + (l++q++r).length < (l++[d,e]++r).length) := by + have hdiff := polygonArea_replace c η l r q d e hq + have hq₀ := polygonArea_nonneg c η hc ho + have hde₀ := (slopeCross_nonpos_iff c η hc hd he).mpr hde + by_cases hlt : polygonArea c η (l++[d,e]++r) < polygonArea c η (l++q++r) + · exact Or.inl hlt + right + have heq : polygonArea c η (l++[d,e]++r)=polygonArea c η (l++q++r) := by linarith + have hlen : q.length < 2 := by + by_contra hh + have := polygonArea_pos c η hc ho (by omega) + linarith + exact ⟨heq,by simp only [List.length_append,List.length_cons,List.length_nil]; omega⟩ + +end ElementaryPositivity.SlopeArithmetic + +end +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] + +abbrev HNComposition (d : I → ℕ) := {l : List (I → ℕ) // l.sum=d ∧ ∀ e∈l,e≠0} + +def hnSize (d : I → ℕ) := ∑ i,d i +lemma hnSize_add (d e : I → ℕ) : hnSize (d+e)=hnSize d+hnSize e := Finset.sum_add_distrib +@[simp] lemma hnSize_zero : hnSize (0 : I → ℕ)=0 := by simp [hnSize] +lemma hnSize_eq_zero (d : I → ℕ) : hnSize d=0 ↔ d=0 := by + simp only [hnSize,Finset.sum_eq_zero_iff,Finset.mem_univ,true_implies] + exact ⟨fun h=>funext h,fun h i=>congrFun h i⟩ +lemma hnSize_list_sum (l : List (I → ℕ)) : hnSize l.sum=(l.map hnSize).sum := by + induction l with + | nil => simp + | cons d l ih => simp [hnSize_add,ih] +lemma HNComposition.length_le (d : I → ℕ) (l : HNComposition d) : l.val.length ≤ hnSize d := by + have h := List.length_le_sum_of_one_le (l.val.map hnSize) (by + intro n hn + obtain ⟨e,he,rfl⟩ := List.mem_map.mp hn + have := (hnSize_eq_zero e).not.mpr (l.property.2 e he) + omega) + have h' : l.val.length ≤ (l.val.map hnSize).sum := by simpa only [List.length_map] using h + exact h'.trans_eq ((hnSize_list_sum l.val).symm.trans (congrArg hnSize l.property.1)) + +instance (d : I → ℕ) : Finite (HNComposition d) := by + classical + let E := {e : I → ℕ // e ≤ d} + let : Finite E := (Set.finite_Iic d).to_subtype + have hs : {l : List (I → ℕ) | l.sum=d ∧ ∀ e∈l,e≠0}.Finite := by + apply ((List.finite_length_le E (hnSize d)).image (List.map Subtype.val)).subset + intro l hl + let q : List E := l.attach.map (fun e=>⟨e.val,by + have := List.le_sum_of_mem e.property + simpa only [hl.1] using this⟩) + refine ⟨q,?_,?_⟩ + · change q.length ≤ hnSize d + simpa only [q,List.length_map,List.length_attach] using HNComposition.length_le d ⟨l,hl⟩ + · simp only [q,List.map_map] + change l.attach.map (fun x=>x.val)=l + simp + exact hs.to_subtype + +variable (c η : I → ℝ) + +def HNBefore {d : I → ℕ} (l r : HNComposition d) : Prop := + polygonArea c η r.val < polygonArea c η l.val ∨ + (polygonArea c η r.val=polygonArea c η l.val ∧ l.val.length < r.val.length) + +instance (d : I → ℕ) : IsStrictOrder (HNComposition d) (HNBefore c η) where + irrefl l := by simp [HNBefore] + trans l r s hl hr := by + rcases hl with hl|⟨hl,hl'⟩ <;> rcases hr with hr|⟨hr,hr'⟩ + · exact Or.inl (lt_trans hr hl) + · exact Or.inl (hr ▸ hl) + · exact Or.inl (hl ▸ hr) + · exact Or.inr ⟨hr.trans hl,lt_trans hl' hr'⟩ + +lemma hnBefore_wellFounded (d : I → ℕ) : WellFounded (HNBefore c η (d:=d)) := + Set.wellFoundedOn_univ.mp Set.finite_univ.wellFoundedOn + +lemma not_hnOrdered_adjacent {l : List (I → ℕ)} (hn : ∀ d∈l,d≠0) (ho : ¬HNOrdered c η l) : + ∃ p q d e,l=p++[d,e]++q ∧ slope c η d ≤ slope c η e := by + have h : ¬l.IsChain (fun d e=>slope c η e exact (h (by simp)).elim + | cons d l ih => + cases l with + | nil => exact (h (by simp)).elim + | cons e l => + by_cases hde : slope c η eq i.succ) k j := by + simp only [matrixPrefix,Fin.sum_univ_succ,Fin.val_zero,Nat.zero_lt_succ,ite_true,Fin.val_succ, + Nat.add_lt_add_iff_right] + +structure HNSplitMatrix {m n : ℕ} (l : Fin m → I → ℕ) (r : Fin n → I → ℕ) + (q : Fin m → Fin n → I → ℕ) : Prop where + rowSum : ∀ i,∑ j,q i j=l i + colSum : ∀ j,∑ i,q i j=r j + prefixes : ∀ k j,mass η (matrixPrefix q k j) ≤ slope c η (r j)*mass c (matrixPrefix q k j) + +lemma split_cell_le {m n : ℕ} {l : Fin m → I → ℕ} {r : Fin n → I → ℕ} + {q : Fin m → Fin n → I → ℕ} (h : HNSplitMatrix c η l r q) (i : Fin m) (j : Fin n) : q i j ≤ r j := by + rw [←h.colSum j] + exact Finset.single_le_sum (f:=fun i=>q i j) (fun i _=>by exact zero_le) (Finset.mem_univ i) + +include hc in +lemma split_first_row {m n : ℕ} {l : Fin (m+1) → I → ℕ} {r : Fin (n+1) → I → ℕ} + {q : Fin (m+1) → Fin (n+1) → I → ℕ} (h : HNSplitMatrix c η l r q) + (hl : l 0≠0) (hr : ∀ j,0 < j → slope c η (r j) < slope c η (r 0)) : + hnKeyLT c η (l 0) (r 0) ∨ + (l 0=r 0 ∧ q 0 0=r 0 ∧ (∀ j,j≠0 → q 0 j=0) ∧ ∀ i,i≠0 → q i 0=0) := by + have ht (j : Fin (n+1)) : slope c η (r j) ≤ slope c η (r 0) := by + by_cases hj : j=0 + · rw [hj] + · exact (hr j (Fin.pos_iff_ne_zero.mpr hj)).le + have hp (j : Fin (n+1)) : mass η (q 0 j) ≤ slope c η (r j)*mass c (q 0 j) := by + simpa only [matrixPrefix_one] using h.prefixes 1 j + have hs := split_row_slope_le c η hc _ (q 0) r (l 0) hl (h.rowSum 0) ht hp + rcases lt_or_eq_of_le hs with hs|hs + · exact Or.inl (Or.inl hs) + obtain ⟨hd,hz⟩:=split_row_max_single c η hc 0 (q 0) r (l 0) (h.rowSum 0) hs + (fun j hj=>hr j (Fin.pos_iff_ne_zero.mpr hj)) hp + have hle : l 0 ≤ r 0 := hd ▸ split_cell_le c η h 0 0 + have hm := mass_mono c hc hle + rcases lt_or_eq_of_le hm with hm|hm + · exact Or.inl (Or.inr ⟨hs,hm⟩) + have he := mass_eq_of_le c hc hle hm + refine Or.inr ⟨he,hd.trans he,hz,?_⟩ + intro i hi + have hsum : (∑ b : Fin m,q b.succ 0)=0 := by + have hh:=h.colSum 0 + rw [Fin.sum_univ_succ,hd,he] at hh + exact add_eq_left.mp hh + obtain ⟨b,rfl⟩:=Fin.eq_succ_of_ne_zero hi + exact (Finset.sum_eq_zero_iff).mp hsum b (Finset.mem_univ b) + +lemma split_tail {m n : ℕ} {l : Fin (m+1) → I → ℕ} {r : Fin (n+1) → I → ℕ} + {q : Fin (m+1) → Fin (n+1) → I → ℕ} (h : HNSplitMatrix c η l r q) + (hrow : ∀ j,j≠0 → q 0 j=0) (hcol : ∀ i,i≠0 → q i 0=0) : + HNSplitMatrix c η (fun i=>l i.succ) (fun j=>r j.succ) (fun i j=>q i.succ j.succ) where + rowSum i := by simpa only [Fin.sum_univ_succ,hcol i.succ (Fin.succ_ne_zero _),zero_add] using h.rowSum i.succ + colSum j := by simpa only [Fin.sum_univ_succ,hrow j.succ (Fin.succ_ne_zero _),zero_add] using h.colSum j.succ + prefixes k j := by + have hh:=h.prefixes (k+1) j.succ + simp only [matrixPrefix,Fin.sum_univ_succ,Fin.val_zero,Nat.zero_lt_succ,ite_true,Fin.val_succ, + Nat.add_lt_add_iff_right,hrow j.succ (Fin.succ_ne_zero _),zero_add] at hh + simpa only [matrixPrefix] using hh + +include hc in + +theorem hn_split_triangular {m n : ℕ} (l : Fin m → I → ℕ) (r : Fin n → I → ℕ) + (q : Fin m → Fin n → I → ℕ) (h : HNSplitMatrix c η l r q) + (hl : ∀ i,l i≠0) (hr : ∀ j,r j≠0) + (ho : ∀ j k,j < k → slope c η (r k) < slope c η (r j)) : + List.Lex (hnKeyLT c η) (List.ofFn l) (List.ofFn r) ∨ List.ofFn l=List.ofFn r := by + induction m generalizing n with + | zero => + cases n with + | zero => exact Or.inr (by simp) + | succ n => + have hh := h.colSum 0 + simp only [Finset.univ_eq_empty,Finset.sum_empty] at hh + exact (hr 0 hh.symm).elim + | succ m ih => + cases n with + | zero => + have hh:=h.rowSum 0 + simp only [Finset.univ_eq_empty,Finset.sum_empty] at hh + exact (hl 0 hh.symm).elim + | succ n => + rcases split_first_row c η hc h (hl 0) (fun j hj=>ho 0 j hj) with hk|⟨he,_,hrow,hcol⟩ + · exact Or.inl (by simpa only [List.ofFn_succ] using List.Lex.rel hk) + obtain htail|htail:=ih (fun i=>l i.succ) (fun j=>r j.succ) (fun i j=>q i.succ j.succ) + (split_tail c η h hrow hcol) (fun i=>hl i.succ) (fun j=>hr j.succ) + (fun j k hjk=>ho j.succ k.succ (Fin.succ_lt_succ_iff.mpr hjk)) + · exact Or.inl (by simpa only [List.ofFn_succ,he] using List.Lex.cons htail) + · exact Or.inr (by simp only [List.ofFn_succ,he,htail]) +end ElementaryPositivity.SlopeArithmetic + +end +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] +variable (c η : I → ℝ) (hc : ∀ i,0 simp [mass] + | cons d l ih => + simp only [List.sum_cons,mass_add,mul_add] + exact add_le_add (h d (by simp)) (ih (fun e he=>h e (by simp [he]))) +lemma list_slope_le (θ : ℝ) (l : List (I → ℕ)) (hn : l.sum≠0) + (h : ∀ d∈l,slope c η d ≤ θ) : slope c η l.sum ≤ θ := by + apply (div_le_iff₀ (mass_pos c hc _ hn)).mpr + apply list_mass_bound c η θ l + intro d hd + rw [mass_eq c η hc d] + exact mul_le_mul_of_nonneg_right (h d hd) (mass_nonneg c (fun i=>(hc i).le) d) +omit hc [Fintype I] in +lemma list_sum_ne_zero {l : List (I → ℕ)} (hn : ∀ d∈l,d≠0) (hl : l≠[]) : l.sum≠0 := by + obtain ⟨d,l,rfl⟩:=List.exists_cons_of_ne_nil hl + exact add_ne_zero_left d l.sum (hn d (by simp)) +lemma ordered_sum_le_head {d : I → ℕ} {l : List (I → ℕ)} (h : HNOrdered c η (d::l)) : + slope c η (d::l).sum ≤ slope c η d := by + apply list_slope_le c η hc + · exact list_sum_ne_zero h.1 (by simp) + · intro e he + rcases List.mem_cons.mp he with rfl|he + · rfl + · exact ((List.pairwise_cons.mp h.2).1 e he).le +lemma ordered_tail_lt_head {d : I → ℕ} {l : List (I → ℕ)} (h : HNOrdered c η (d::l)) + (hl : l≠[]) : slope c η l.sumh.1 x (by simp [hx]),h.2.tail⟩).trans_lt + ((List.pairwise_cons.mp h.2).1 e (by simp)) + +omit hc in +lemma exists_uniform_cutoff (d : I → ℕ) (θ : ℝ) : + ∃ κ : ℝ, κ<θ ∧ ∀ e : I → ℕ,e ≤ d → e≠0 → slope c η e<θ → slope c η e ≤ κ := by + classical + let E : Set (I → ℕ) := {e | e ≤ d ∧ e≠0 ∧ slope c η e<θ} + have hE : E.Finite := (Set.finite_Iic d).subset (fun _ h=>h.1) + by_cases hn : E.Nonempty + · obtain ⟨e,he,hm⟩:=Set.exists_max_image E (slope c η) hE hn + exact ⟨slope c η e,he.2.2,fun f hf hz hs=>hm f ⟨hf,hz,hs⟩⟩ + · refine ⟨θ-1,by linarith,?_⟩ + intro e hd he hs + exact (hn ⟨e,hd,he,hs⟩).elim +end ElementaryPositivity.SlopeArithmetic + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/HNRestrictionOrder.lean b/lean/OAI/Combinatorics/Chromatic/Walls/HNRestrictionOrder.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca9cd52a97d7c12008b7d6fbbe1e92583b4c737b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/HNRestrictionOrder.lean @@ -0,0 +1,212 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.RestrictionB +import OAI.Combinatorics.Chromatic.GradedAlgebra.Product + +namespace OAI + +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I J : Type*} [Fintype I] [Fintype J] +variable (c η : I → ℝ) (hc : ∀ i,0 < c i) +lemma mass_sum (f : J → I → ℕ) : mass c (∑ j,f j)=∑ j,mass c (f j) := by + simp only [mass,Finset.sum_apply,Nat.cast_sum,Finset.sum_mul] + exact Finset.sum_comm +include hc +lemma mass_mono {d e : I → ℕ} (h : d ≤ e) : mass c d ≤ mass c e := by + apply Finset.sum_le_sum + intro i _ + exact mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (h i)) (le_of_lt (hc i)) +lemma mass_eq_of_le {d e : I → ℕ} (h : d ≤ e) (he : mass c d=mass c e) : d=e := by + have hh : ∀ i, (d i : ℝ)*c i=(e i : ℝ)*c i := by + intro i + exact (Finset.sum_eq_sum_iff_of_le (fun i _=> + mul_le_mul_of_nonneg_right (Nat.cast_le.mpr (h i)) (le_of_lt (hc i)))).mp he i (Finset.mem_univ i) + funext i + exact Nat.cast_injective (mul_right_cancel₀ (hc i).ne' (hh i)) + +lemma split_row_slope_le (β : ℝ) (q r : J → I → ℕ) (d : I → ℕ) + (hd : d≠0) (hq : ∑ j,q j=d) + (ht : ∀ j,slope c η (r j) ≤ β) + (hp : ∀ j,mass η (q j) ≤ slope c η (r j)*mass c (q j)) : + slope c η d ≤ β := by + apply (div_le_iff₀ (mass_pos c hc d hd)).mpr + calc + mass η d = ∑ j,mass η (q j) := hq ▸ mass_sum η q + _ ≤ ∑ j,β*mass c (q j) := Finset.sum_le_sum (fun j _=> + (hp j).trans (mul_le_mul_of_nonneg_right (ht j) (mass_nonneg c (fun i=>(hc i).le) (q j)))) + _ = β*mass c d := by rw [←Finset.mul_sum,←mass_sum, hq] + +lemma split_row_max_zero (β : ℝ) (q r : J → I → ℕ) (d : I → ℕ) + (hq : ∑ j,q j=d) (hd : mass η d=β*mass c d) + (ht : ∀ j,slope c η (r j) ≤ β) + (hp : ∀ j,mass η (q j) ≤ slope c η (r j)*mass c (q j)) + {j : J} (hj : slope c η (r j) < β) : q j=0 := by + have hn (k : J) : 0 ≤ β*mass c (q k)-mass η (q k) := by + exact sub_nonneg.mpr ((hp k).trans (mul_le_mul_of_nonneg_right (ht k) + (mass_nonneg c (fun i=>(hc i).le) (q k)))) + have hs : ∑ k,(β*mass c (q k)-mass η (q k))=0 := by + rw [Finset.sum_sub_distrib,←Finset.mul_sum,←mass_sum,←mass_sum,hq,hd,sub_self] + have hz := (Finset.sum_eq_zero_iff_of_nonneg (fun k _=>hn k)).mp hs j (Finset.mem_univ j) + by_contra hjq + have hpos := mass_pos c hc (q j) hjq + have hlt := mul_lt_mul_of_pos_right hj hpos + linarith [hp j] + +lemma split_row_max_single [DecidableEq J] (j₀ : J) (q r : J → I → ℕ) (d : I → ℕ) + (hq : ∑ j,q j=d) (hd : slope c η d=slope c η (r j₀)) + (ht : ∀ j,j≠j₀ → slope c η (r j) < slope c η (r j₀)) + (hp : ∀ j,mass η (q j) ≤ slope c η (r j)*mass c (q j)) : + q j₀=d ∧ ∀ j,j≠j₀ → q j=0 := by + have hmax (j : J) : slope c η (r j) ≤ slope c η (r j₀) := by + by_cases hj : j=j₀ + · rw [hj] + · exact (ht j hj).le + have hzero (j : J) (hj : j≠j₀) : q j=0 := + split_row_max_zero c η hc _ q r d hq (by rw [←hd]; exact mass_eq c η hc d) hmax hp (ht j hj) + refine ⟨?_,hzero⟩ + rw [←hq] + symm + exact Finset.sum_eq_single j₀ (fun j _ hj=>hzero j hj) (by simp) + +lemma split_row_equal_key [DecidableEq J] (j₀ : J) (q r : J → I → ℕ) (d : I → ℕ) + (hq : ∑ j,q j=d) (hd : slope c η d=slope c η (r j₀)) + (ht : ∀ j,j≠j₀ → slope c η (r j) < slope c η (r j₀)) + (hp : ∀ j,mass η (q j) ≤ slope c η (r j)*mass c (q j)) + (hle : ∀ j,q j ≤ r j) (hm : mass c d=mass c (r j₀)) : + d=r j₀ ∧ q j₀=r j₀ ∧ ∀ j,j≠j₀ → q j=0 := by + obtain ⟨hs,hz⟩:=split_row_max_single c η hc j₀ q r d hq hd ht hp + have he : d=r j₀ := mass_eq_of_le c hc (hs ▸ hle j₀) hm + exact ⟨he,hs.trans he,hz⟩ +end ElementaryPositivity.SlopeArithmetic + +end +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] +variable (c η : I → ℝ) +noncomputable def clippedSlope (θ : ℝ) (d : I → ℕ) : ℝ := max (slope c η d) θ +lemma clippedSlope_of_le {θ : ℝ} {d : I → ℕ} (h : slope c η d ≤ θ) : + clippedSlope c η θ d=θ := max_eq_right h +lemma clippedSlope_of_ge {θ : ℝ} {d : I → ℕ} (h : θ ≤ slope c η d) : + clippedSlope c η θ d=slope c η d := max_eq_left h +lemma clippedSlope_le (θ : ℝ) (d : I → ℕ) : slope c η d ≤ clippedSlope c η θ d := le_max_left _ _ +lemma clipped_mass_bound (hc : ∀ i,0(hc i).le) d) + +lemma clipped_high_mass (hc : ∀ i,0(hc i).le) d)).trans_lt h + obtain ⟨hd,he,_⟩:=high_mass_destabilizes c η hc d e hm + refine ⟨hd,he,lt_of_lt_of_le ?_ (clippedSlope_le c η θ d)⟩ + exact (lt_div_iff₀ (mass_pos c hc d hd)).mpr h + +lemma clipped_split_destabilizes (hc : ∀ i,0(hc i).le) d₁)) + have hqd := (mul_le_mul_of_nonneg_right h₂ (mass_nonneg c (fun i=>(hc i).le) d₂)) + have hh := (lt_div_iff₀ (mass_pos c hc (d₁+d₂) hd)).mp hs + rw [mass_add,mass_add] at hh + push Not at hp hq + nlinarith +end ElementaryPositivity.SlopeArithmetic + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open ElementaryPositivity.SlopeArithmetic ElementaryPositivity.PackConvolution +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) +lemma clipped_destabilizingSpace_eq (κ : ℝ) (d : I → ℕ) (h : κ ≤ slope c η d) : + destabilizingSpace a (clippedSlope c η κ) d=destabilizingSpace a (slope c η) d := by + unfold destabilizingSpace + congr 1 + ext f + constructor <;> rintro ⟨u,v,he,x,y,hu,hv,hs,hf⟩ + · refine ⟨u,v,he,x,y,hu,hv,?_,hf⟩ + rw [clippedSlope_of_ge c η h,clippedSlope] at hs + exact (lt_max_iff.mp hs).resolve_right (not_lt_of_ge h) + · refine ⟨u,v,he,x,y,hu,hv,?_,hf⟩ + rw [clippedSlope_of_ge c η h] + exact hs.trans_le (le_max_left _ _) + +variable {A : I → Type*} [∀ i,Fintype (A i)] [∀ i,DecidableEq (A i)] +omit [∀ i, Fintype (A i)] in +lemma clipped_gridShape_zero (hc : ∀ i,0(u i).val)+(fun i=>(v i).val)=d + · apply quotient_cellTransfer_zero + apply clipped_split_destabilizes c η hc κ θ + · rwa [(shape_add_complement u).trans (realization_card R)] + · rwa [(shape_add_complement v).trans (realization_card T)] + · rwa [hs] + · rwa [hs] + · rw [fourGridPolynomial_zero_of_source_mismatch a f g _ _ _ _ hs,map_zero,map_zero] +omit [∀ i, Fintype (A i)] in +lemma clipped_grid_zero (hc : ∀ i,0Fin ((α+β) i)) := fun _=>Finset.univ + let R : Realization (α+β) s := defaultRealization (by intro i; simp [s]) + rw [cleared_restrictTensor a h f g R u,map_smul, + clipped_grid_zero a c η hc κ θ f g _ _ _ hd hα hβ hμ,smul_zero] + +lemma clipped_restrict_ideal (hc : ∀ i,0 + obtain ⟨d,e,h,x,y,hd,he,hs,rfl⟩:=hf + have hs' : θ < slope c η d := by + rw [clippedSlope_of_le c η hμ,clippedSlope] at hs + exact (lt_max_iff.mp hs).resolve_right (lt_irrefl θ) + exact clipped_restrict_high a c η hc κ θ h x y u hd hα hβ hs' + | zero => rw [map_zero,map_zero] + | add f g _ _ hf hg => rw [map_add,map_add,hf,hg,add_zero] + | smul q f _ hf => rw [map_smul,map_smul,hf,smul_zero] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/HNSpanning.lean b/lean/OAI/Combinatorics/Chromatic/Walls/HNSpanning.lean new file mode 100644 index 0000000000000000000000000000000000000000..305e3fbad9176e064d18ec9bbd78563e8fedd910 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/HNSpanning.lean @@ -0,0 +1,301 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.Eval +import OAI.Combinatorics.Chromatic.Walls.HNGeometry + +namespace OAI + +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] +variable {A : Type*} [Ring A] [Algebra ℚ A] +variable (c η : I → ℝ) (V : (I → ℕ) → Submodule ℚ A) +noncomputable def hnWordSpace (l : List (I → ℕ)) : Submodule ℚ A := (l.map V).prod +omit [Fintype I] in +@[simp] lemma hnWordSpace_nil : hnWordSpace V []=1 := rfl +omit [Fintype I] in +@[simp] lemma hnWordSpace_cons (d : I → ℕ) (l : List (I → ℕ)) : + hnWordSpace V (d::l)=V d*hnWordSpace V l := rfl +omit [Fintype I] in +@[simp] lemma hnWordSpace_singleton (d : I → ℕ) : hnWordSpace V [d]=V d := by simp +omit [Fintype I] in +lemma hnWordSpace_append (l r : List (I → ℕ)) : + hnWordSpace V (l++r)=hnWordSpace V l*hnWordSpace V r := by simp [hnWordSpace,List.prod_append] + +noncomputable def hnOrderedSpan (d : I → ℕ) : Submodule ℚ A := + ⨆ (l : List (I → ℕ)) (_ : l.sum=d) (_ : HNOrdered c η l),hnWordSpace V l +lemma hnWordSpace_le {d : I → ℕ} (l : List (I → ℕ)) (hs : l.sum=d) (ho : HNOrdered c η l) : + hnWordSpace V l ≤ hnOrderedSpan c η V d := + le_iSup_of_le l (le_iSup_of_le hs (le_iSup_of_le ho le_rfl)) + +variable (hc : ∀ i,0 < c i) (W : (I → ℕ) → Submodule ℚ A) +variable (hV : ∀ d,V d ≤ W d) +variable (hW : ∀ d e,W d*W e ≤ W (d+e)) +variable (hzero : W 0 ≤ 1) +variable (hdec : ∀ d,d≠0 → W d ≤ V d ⊔ + ⨆ (u : I → ℕ) (v : I → ℕ) (_ : u+v=d) (_ : u≠0) (_ : v≠0) + (_ : slope c η d < slope c η u),W u*W v) + +include hc hV hW hzero hdec in + +theorem hn_spanning (d : I → ℕ) : W d ≤ hnOrderedSpan c η V d := by + suffices ∀ n (d : I → ℕ),hnSize d=n → W d ≤ hnOrderedSpan c η V d from this _ d rfl + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro d hdn + have small : ∀ e,hnSize e < hnSize d → W e ≤ hnOrderedSpan c η V e := + fun e he=>ih _ (by omega) e rfl + have words : ∀ s : HNComposition d,0 < polygonArea c η s.val → + hnWordSpace V s.val ≤ hnOrderedSpan c η V d := by + intro s + induction s using (hnBefore_wellFounded c η d).induction with + | h s ihs => + intro ha + by_cases ho : HNOrdered c η s.val + · exact hnWordSpace_le c η V s.val s.property.1 ho + obtain ⟨p,q,u,v,hs,huv⟩:=not_hnOrdered_adjacent c η s.property.2 ho + have hn : ∀ b∈p++[u,v]++q,b≠0 := by simpa only [←hs] using s.property.2 + have hsum : (p++[u,v]++q).sum=d := hs ▸ s.property.1 + have hp : 0 < polygonArea c η (p++[u,v]++q) := hs ▸ ha + have hdim : hnSize (u+v) < hnSize d := + (hnSize_pair_lt c η hc hn huv hp).trans_eq (congrArg hnSize hsum) + have hmerge : V u*V v ≤ hnOrderedSpan c η V (u+v) := + (mul_le_mul' (hV u) (hV v)).trans ((hW u v).trans (small (u+v) hdim)) + calc + hnWordSpace V s.val = hnWordSpace V p*(V u*V v)*hnWordSpace V q := by + rw [hs]; simp only [hnWordSpace_append,hnWordSpace_cons,hnWordSpace_nil,mul_one] + _ ≤ hnWordSpace V p*hnOrderedSpan c η V (u+v)*hnWordSpace V q := by + exact mul_le_mul' (mul_le_mul' le_rfl hmerge) le_rfl + _ ≤ hnOrderedSpan c η V d := by + unfold hnOrderedSpan + simp only [Submodule.mul_iSup,Submodule.iSup_mul] + refine iSup_le fun r=>iSup_le fun hr=>iSup_le fun hor=>?_ + let t : HNComposition d := ⟨p++r++q,by + constructor + · simpa only [List.sum_append,hr,List.sum_cons,List.sum_nil,add_zero] using hsum + · intro b hb + rcases List.mem_append.mp hb with hb|hb + · rcases List.mem_append.mp hb with hb|hb + · exact hn b (by simp [hb]) + · exact hor.1 b hb + · exact hn b (by simp [hb])⟩ + have ht : HNBefore c η t s := by + have := reorder_progress c η hc p q r (hn u (by simp)) (hn v (by simp)) huv hr hor + simpa only [HNBefore,t,hs] using this + have hat : 0 < polygonArea c η t.val := by + rcases ht with ht|⟨ht,_⟩ + · exact lt_trans ha ht + · exact ha.trans_eq ht + have h := ihs t ht hat + simpa only [t,hnWordSpace_append,hnOrderedSpan] using h + by_cases hd : d=0 + · subst d + exact hzero.trans (hnWordSpace_le c η V [] rfl ⟨by simp,by simp⟩) + apply (hdec d hd).trans + apply sup_le + · simpa only [hnWordSpace_singleton] using (hnWordSpace_le c η V (d:=d) [d] (by simp) ⟨by simpa using hd,by simp⟩) + refine iSup_le fun u=>iSup_le fun v=>iSup_le fun huv=>iSup_le fun hu=> + iSup_le fun hv=>iSup_le fun hμ=>?_ + have hsize : hnSize u+hnSize v=hnSize d := by rw [←hnSize_add,huv] + have hu₀ : hnSize u≠0 := (hnSize_eq_zero u).not.mpr hu + have hv₀ : hnSize v≠0 := (hnSize_eq_zero v).not.mpr hv + apply (mul_le_mul' (small u (by omega)) (small v (by omega))).trans + unfold hnOrderedSpan + simp only [Submodule.mul_iSup,Submodule.iSup_mul] + refine iSup_le fun r=>iSup_le fun hr=>iSup_le fun hor=> + iSup_le fun l=>iSup_le fun hl=>iSup_le fun hol=>?_ + let s : HNComposition d := ⟨l++r,by + constructor + · simpa only [List.sum_append,hl,hr] using huv + · intro b hb + rcases List.mem_append.mp hb with hb|hb + · exact hol.1 b hb + · exact hor.1 b hb⟩ + have hp : 0 < polygonArea c η s.val := by + change 0 < polygonArea c η (l++r) + rw [polygonArea_append,hl,hr] + exact add_pos_of_nonneg_of_pos (add_nonneg (polygonArea_nonneg c η hc hol) + (polygonArea_nonneg c η hc hor)) + (slopeCross_of_destabilizing c η hc hu (by simpa only [huv] using hμ)) + simpa only [s,hnWordSpace_append,hnOrderedSpan] using words s hp + +end ElementaryPositivity.SlopeArithmetic + +end +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial + +noncomputable def mapLinear {A B σ : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (l : A →ₗ[ℚ] B) : + MvPolynomial σ A →ₗ[ℚ] MvPolynomial σ B where + toFun p := AddMonoidAlgebra.ofCoeff ((AddMonoidAlgebra.coeff p).mapRange l l.map_zero) + map_add' p q := by ext s; exact l.map_add (p.coeff s) (q.coeff s) + map_smul' r p := by ext s; exact l.map_smul r (p.coeff s) + +@[simp] lemma coeff_mapLinear {A B σ : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (l : A →ₗ[ℚ] B) + (p : MvPolynomial σ A) (s : σ →₀ ℕ) : + (mapLinear l p).coeff s = l (p.coeff s) := rfl + +@[simp] lemma mapLinear_monomial {A B σ : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (l : A →ₗ[ℚ] B) (s : σ →₀ ℕ) (a : A) : + mapLinear l (monomial s a) = monomial s (l a) := by + classical + ext t + simp only [coeff_mapLinear,coeff_monomial] + split_ifs <;> simp + +noncomputable def evalRat {A σ : Type*} [CommRing A] [Algebra ℚ A] + (v : σ → ℚ) : MvPolynomial σ A →ₐ[ℚ] A := + (aeval (fun i => algebraMap ℚ A (v i))).restrictScalars ℚ + +@[simp] lemma evalRat_C {A σ : Type*} [CommRing A] [Algebra ℚ A] + (v : σ → ℚ) (a : A) : evalRat v (C a) = a := by + simp only [evalRat,AlgHom.restrictScalars_apply,aeval_C,Algebra.algebraMap_self,RingHom.id_apply] + +@[simp] lemma evalRat_X {A σ : Type*} [CommRing A] [Algebra ℚ A] + (v : σ → ℚ) (i : σ) : evalRat v (X i : MvPolynomial σ A) = algebraMap ℚ A (v i) := by + simp only [evalRat,AlgHom.restrictScalars_apply,aeval_X] + +@[simp] lemma evalRat_monomial {A σ : Type*} [CommRing A] [Algebra ℚ A] + (v : σ → ℚ) (s : σ →₀ ℕ) (a : A) : + evalRat v (monomial s a) = (s.prod fun i n => v i ^ n) • a := by + simp only [evalRat,AlgHom.restrictScalars_apply,aeval_monomial,Algebra.algebraMap_self] + simp only [RingHom.id_apply,Algebra.smul_def,Finsupp.prod,map_prod,map_pow] + exact mul_comm _ _ + +lemma evalRat_mapLinear {A B σ : Type*} [CommRing A] [CommRing B] + [Algebra ℚ A] [Algebra ℚ B] (l : A →ₗ[ℚ] B) + (p : MvPolynomial σ A) (v : σ → ℚ) : + evalRat v (mapLinear l p) = l (evalRat v p) := by + induction p using MvPolynomial.induction_on' with + | add p q hp hq => simp only [map_add,hp,hq] + | monomial s a => rw [mapLinear_monomial,evalRat_monomial,evalRat_monomial,map_smul] + +theorem eq_of_evalRat {A σ : Type*} [CommRing A] [Algebra ℚ A] + {p q : MvPolynomial σ A} (h : ∀ v : σ → ℚ, evalRat v p = evalRat v q) : p = q := by + apply sub_eq_zero.mp + have hzero : ∀ v : σ → ℚ, evalRat v (p-q)=0 := by + intro v + rw [map_sub,h v,sub_self] + ext s + simp only [AddMonoidAlgebra.coeff_zero, Finsupp.zero_apply] + apply (Module.forall_dual_apply_eq_zero_iff ℚ _).mp + intro l + have hp : mapLinear l (p-q) = 0 := by + apply MvPolynomial.funext + intro v + have ht := evalRat_mapLinear l (p-q) v + rw [hzero,map_zero] at ht + simpa only [evalRat,AlgHom.restrictScalars_apply,aeval_def,Algebra.algebraMap_self, + RingHom.id_apply,coe_eval₂Hom,MvPolynomial.eval,eval₂_zero] using ht + have he := congrArg (fun polynomial => AddMonoidAlgebra.coeff polynomial s) hp + simpa only [coeff_mapLinear, AddMonoidAlgebra.coeff_zero, Finsupp.zero_apply] using he + +end ElementaryPositivity.CenterCalculus + +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +variable {A α : Type*} [CommRing A] + +noncomputable def toRelative : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A →ₐ[A] + MvPolynomial (Unit ⊕ α) (Polynomial A) := + aeval (fun i => match i with + | Sum.inl (Sum.inl _) => C Polynomial.X + X (Sum.inl ()) + | Sum.inl (Sum.inr _) => X (Sum.inl ()) + | Sum.inr i => X (Sum.inr i)) + +noncomputable def fromRelative : MvPolynomial (Unit ⊕ α) (Polynomial A) →+* + MvPolynomial ((Unit ⊕ Unit) ⊕ α) A := + eval₂Hom (Polynomial.aeval (X (Sum.inl (Sum.inl ())) - X (Sum.inl (Sum.inr ())))).toRingHom + (fun i => match i with + | Sum.inl _ => X (Sum.inl (Sum.inr ())) + | Sum.inr i => X (Sum.inr i)) + +@[simp] lemma toRelative_C (a : A) : + toRelative (C a : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A) = C (Polynomial.C a) := by + simp [toRelative] + +@[simp] lemma toRelative_first : + toRelative (X (Sum.inl (Sum.inl ())) : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A) = + C Polynomial.X + X (Sum.inl ()) := by simp [toRelative] + +@[simp] lemma toRelative_second : + toRelative (X (Sum.inl (Sum.inr ())) : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A) = + X (Sum.inl ()) := by simp [toRelative] + +@[simp] lemma toRelative_other (i : α) : + toRelative (X (Sum.inr i) : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A) = X (Sum.inr i) := by + simp [toRelative] + +@[simp] lemma fromRelative_C (p : Polynomial A) : + fromRelative (C p : MvPolynomial (Unit ⊕ α) (Polynomial A)) = + Polynomial.aeval (X (Sum.inl (Sum.inl ())) - X (Sum.inl (Sum.inr ()))) p := by + simp [fromRelative] + +@[simp] lemma fromRelative_common : + fromRelative (X (Sum.inl ()) : MvPolynomial (Unit ⊕ α) (Polynomial A)) = + X (Sum.inl (Sum.inr ())) := by simp [fromRelative] + +@[simp] lemma fromRelative_other (i : α) : + fromRelative (X (Sum.inr i) : MvPolynomial (Unit ⊕ α) (Polynomial A)) = X (Sum.inr i) := by + simp [fromRelative] + +@[simp] lemma fromRelative_toRelative (p : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A) : + fromRelative (toRelative p) = p := by + induction p using MvPolynomial.induction_on with + | C a => simp only [toRelative_C,fromRelative_C,Polynomial.aeval_C,algebraMap_eq] + | add p q hp hq => simp only [map_add,hp,hq] + | mul_X p i hp => + rw [map_mul,map_mul,hp] + apply congrArg (p * ·) + rcases i with (u | u) | i + · cases u; simp + · cases u; simp + · simp + +theorem diagonal_dvd_of_relative_coeff (p : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A) + (n : ℕ) (h : ∀ z s, s < n → ((toRelative p).coeff z).coeff s = 0) : + (X (Sum.inl (Sum.inl ())) - X (Sum.inl (Sum.inr ()))) ^ n ∣ p := by + have hd : C (Polynomial.X ^ n) ∣ toRelative p := by + apply (C_dvd_iff_dvd_coeff _ _).mpr + intro z + exact Polynomial.X_pow_dvd_iff.mpr (h z) + have he := map_dvd fromRelative hd + simpa only [fromRelative_C,map_pow,Polynomial.aeval_X, + fromRelative_toRelative] using he + +def relativePoint (t : ℚ) (v : Unit ⊕ α → ℚ) : (Unit ⊕ Unit) ⊕ α → ℚ + | Sum.inl (Sum.inl _) => t + v (Sum.inl ()) + | Sum.inl (Sum.inr _) => v (Sum.inl ()) + | Sum.inr i => v (Sum.inr i) + +variable [Algebra ℚ A] + +lemma polynomial_eval_rat_algebraMap (r t : ℚ) : + Polynomial.eval (algebraMap ℚ A t) (algebraMap ℚ (Polynomial A) r) = algebraMap ℚ A r := by + exact Polynomial.eval_C + +lemma evalRat_toRelative (p : MvPolynomial ((Unit ⊕ Unit) ⊕ α) A) + (v : Unit ⊕ α → ℚ) (t : ℚ) : + (evalRat v (toRelative p)).eval (algebraMap ℚ A t) = evalRat (relativePoint t v) p := by + induction p using MvPolynomial.induction_on with + | C a => rw [toRelative_C,evalRat_C,Polynomial.eval_C,evalRat_C] + | add p q hp hq => simp only [map_add,Polynomial.eval_add,hp,hq] + | mul_X p i hp => + simp only [map_mul,Polynomial.eval_mul,hp] + apply congrArg (evalRat (relativePoint t v) p * ·) + rcases i with (u | u) | i + · cases u + simp only [toRelative_first,map_add,evalRat_C,evalRat_X,Polynomial.eval_add, + Polynomial.eval_X,polynomial_eval_rat_algebraMap,relativePoint] + · cases u + simp only [toRelative_second,evalRat_X,polynomial_eval_rat_algebraMap,relativePoint] + · simp only [toRelative_other,evalRat_X,polynomial_eval_rat_algebraMap,relativePoint] + +end ElementaryPositivity.CenterCalculus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/HNTorusFactor.lean b/lean/OAI/Combinatorics/Chromatic/Walls/HNTorusFactor.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f117ab83cbb16335d6d417935c47cbcf1189d72 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/HNTorusFactor.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplit +import OAI.Combinatorics.Chromatic.GradedAlgebra.HNSeries + +namespace OAI + +section +namespace ElementaryPositivity.WallUnits.LaurentRay +noncomputable section +def vUnit : (LaurentSeries ℚ)ˣ := Units.map atInfinity.toMonoidHom PositiveRay.vUnit +lemma vUnit_zpow (k : ℤ) : (↑(vUnit^k) : LaurentSeries ℚ)=HahnSeries.single (-k) 1 := by + rw [Units.val_zpow_eq_zpow_val] + change (atInfinity (↑PositiveRay.vUnit))^k=_ + rw [← map_zpow₀] + exact atInfinity_v_pow k +end +end ElementaryPositivity.WallUnits.LaurentRay + +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic EnergyLaurent QuantumTorus WeightedTorusSeries WallUnits +open PowerSeries +noncomputable section +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0by + rw [hh] + exact highSeries_support a κ c η hc θ d hd) + · intro n + exact project_push_killed w _ _ _ h _ (fun d hd=>by + rw [hh] + exact lowSeries_support a κ c η hc θ d hd) (n+1) + +include hΩ hh in +theorem literalInput_canonical_factors (ε : I → Bool) (ha : ∀i,a i i=elementaryDiagonal ε i) : + push w LaurentRay.vUnit Ω P (highSeries a κ c η hc θ)= + PowerSeriesSplit.leftFactor (positiveProject LaurentRay.vUnit Ω h) + (push w LaurentRay.vUnit Ω P (literalInputCoefficient a κ ε)) ∧ + push w LaurentRay.vUnit Ω P (lowSeries a κ c η hc θ)= + PowerSeriesSplit.rightFactor (positiveProject LaurentRay.vUnit Ω h) + (push w LaurentRay.vUnit Ω P (literalInputCoefficient a κ ε)) := by + have he : literalInputCoefficient a κ ε=hnSeries a κ c η hc := + funext (literalInput_hnSeries a κ c η hc ε ha) + rw [he] + exact hnTorus_canonical_factors a κ c η hc w Ω P hΩ h θ hh + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/HalfspaceLaurentTransport.lean b/lean/OAI/Combinatorics/Chromatic/Walls/HalfspaceLaurentTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c239b034139de6b2ca437f88b4f1c84eddfffa7 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/HalfspaceLaurentTransport.lean @@ -0,0 +1,59 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.BoundedWordLaurent +import OAI.Combinatorics.Chromatic.Walls.CompletedPathIndependence + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +theorem completedTransport_finite_laurent {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (Hside : (0filter_supported v Ω V _ f hf) F.val hF + have H0:=factors_mem (zeroProject v Ω h) (supportedSubring v Ω V) + (fun f hf=>filter_supported v Ω V _ f hf) (rightFactor (positiveProject v Ω h) F.val) H.2 + exact ⟨H.1,H0.1,H0.2⟩ + +lemma kernel_zero_log (hΩ : ∀m,Ω m m=0) (r : M) (h : M→+ℝ) (hr : h r=0) + (F : CompletedPositive v Ω C) + (hF : ∀n,coeff n F.val∈supportedSubalgebra v Ω (kernelSupport Ω r)) (n : ℕ) : + coeff n (FormalLog.log (chartZero v Ω C h F).val) r=coeff n (FormalLog.log F.val) r := by + let A:=chartPositive v Ω C h F + let B:=chartZero v Ω C h F + let D:=chartNegative v Ω C h F + have H:=chartThree_supported v Ω C h (kernelSupport Ω r) F hF + have H1:=kernel_trace_log_product v Ω hΩ r A.val B.val A.property.1 B.property.1 H.1 H.2.1 n + have H2:=kernel_trace_log_product v Ω hΩ r (A.val*B.val) D.val + (by simp [A.property.1,B.property.1]) D.property.1 + (PowerSeriesSplit.mul_mem (supportedSubring v Ω (kernelSupport Ω r)) _ _ H.1 H.2.1) H.2.2 n + have HS:=chart_three_support v Ω C h F + have hp:=log_positive_zero v Ω h A.val A.property.1 HS.1 r hr n + have hn:=log_negative_zero v Ω h D.val D.property.1 HS.2.2 r hr n + rw [H1,hp,hn,zero_add,add_zero] at H2 + rw [show A.val*B.val*D.val=F.val from chart_three_factorization v Ω C h F] at H2 + exact H2.symm + +lemma incoming_chart_supported (r : M) (F : CompletedPositive v Ω C) : + ∀n,coeff n (chartZero v Ω C (incomingCovector Ω r) F).val∈ + supportedSubalgebra v Ω (kernelSupport Ω r) := by + intro n m hm + cases n with + | zero=> + rw [coeff_zero_eq_constantCoeff,(chartZero v Ω C (incomingCovector Ω r) F).property.1] + change (Finsupp.single 0 (1:R)) m=0 + apply Finsupp.single_eq_of_ne + intro he + exact hm (he ▸ (kernelSupport Ω r).zero_mem) + | succ n=> + by_contra hn + have H:=(chart_three_support v Ω C (incomingCovector Ω r) F).2.1 n m hn + apply hm + change Ω m r=0 + change (Ω m r:ℝ)=0 at H + exact_mod_cast H + +theorem incoming_displacement_log (hΩ : ∀m,Ω m m=0) (r : M) (h : M→+ℝ) + (hr : h r=0) (F : CompletedPositive v Ω C) (n : ℕ) : + coeff n (FormalLog.log (chartZero v Ω C h + (chartZero v Ω C (incomingCovector Ω r) F)).val) r= + coeff n (FormalLog.log (chartZero v Ω C (incomingCovector Ω r) F).val) r := + kernel_zero_log v Ω C hΩ r h hr _ (incoming_chart_supported v Ω C r F) n +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/IncomingEquality.lean b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingEquality.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e4b1f5a6a3b5ec65580e45dfc41372ae1fb45c0 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingEquality.lean @@ -0,0 +1,195 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationRootMap + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +lemma literalTotalTransport_log_ray (hΩ : ∀m,Ω m m=0) + (l : List (WallUnitDatum M)) (hl : ∀u∈l,u.Allowed C (fun _=>True)) + (r : M) (n : ℕ) (m : M) (hm : OnPositiveRay r m) : + coeff n (FormalLog.log (chartZero LaurentRay.vUnit Ω C (incomingCovector Ω m) + (literalTotalTransport Ω C l)).val) m= + coeff n (FormalLog.log (literalIncomingRay Ω l r)) m := by + classical + cases n with + | zero => simp only [coeff_zero_eq_constantCoeff,FormalLog.log_constant,Finsupp.zero_apply] + | succ n => + by_cases hroot : HasRootDegree C (n+1) m + · have H:=congrArg (fun x : Torus LaurentRay.vUnit Ω=>x m) + (incomingSolution_prescription LaurentRay.vUnit Ω C hΩ _ (literalIncomingLog_graded Ω C l) n) + rw [incomingCoefficient_apply,ite_eq_left hroot,literalIncomingLog_apply,ite_eq_left hroot] at H + rw [literalIncomingRay_eq Ω l hm] + exact H + · exact (root_graded_log LaurentRay.vUnit Ω C _ (n+1) m hroot).trans + (root_graded_log LaurentRay.vUnit Ω C (literalIncomingCompleted Ω C l hl r) + (n+1) m hroot).symm + +variable {E : Type*} [AddCommGroup E] [Module ℝ E] +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in +lemma literal_incoming_at_far_through + (l : List (WallUnitDatum M)) (hl : ∀u∈l,u.Allowed C (fun _=>True)) + (N d : ℕ) (r : M) (hd : 0Hgen.2 n hn hnN m hm hkm) + (by + intro n m hm + by_contra hh + exact hm (literalRootProducts_strictSupport Ω C (OnPositiveRay r) + (fun a b ha hb=>ha.add hb) (literalIncomingRay_mem Ω C l hl r) n m hh)) + (by intro n hn m hm; exact literalTotalTransport_log_ray Ω C hΩ l hl r n m hm) + have Href:=chart_zero_refinement LaurentRay.vUnit Ω C (incomingCovector Ω r) + (k.toAddMonoidHom.comp e) ((k+b • B.flip (e r)).toAddMonoidHom.comp e) + (literalTotalTransport Ω C l) N (by + intro n hn m hm + have HH:=far_line_lex (realRootsThrough e C N) (B.flip (e r)) k b hb + (e m) (realRoot_mem e C N n hn m hm) + simp only [LinearMap.flip_apply,hcomp] at HH + exact HH) + intro n hn + exact (Href n hn).trans (Hinc n hn) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M : Type*} [AddCommGroup M] +variable (Ω : M →+ M →+ ℤ) (p : M) (hp : Ω p p=0) + +def shearCovector (h : M →+ ℝ) : M →+ ℝ := h.comp (mutationShearInverse Ω p) +def shearCovectorInverse (h : M →+ ℝ) : M →+ ℝ := h.comp (mutationShear Ω p) +include hp in +lemma shearCovector_at_p (h : M →+ ℝ) : shearCovector Ω p h p=h p := by + change h (p+Ω p p • p)=h p + rw [hp,zero_zsmul,add_zero] +include hp in +lemma shearCovectorInverse_at_p (h : M →+ ℝ) : shearCovectorInverse Ω p h p=h p := by + change h (p-Ω p p • p)=h p + rw [hp,zero_zsmul,sub_zero] +include hp in +lemma shearCovector_inv (h : M →+ ℝ) : + shearCovector Ω p (shearCovectorInverse Ω p h)=h := by + ext m + exact congrArg h (mutationShear_right_inverse Ω p hp m) +include hp in +lemma shearCovector_inv' (h : M →+ ℝ) : + shearCovectorInverse Ω p (shearCovector Ω p h)=h := by + ext m + exact congrArg h (mutationShear_left_inverse Ω p hp m) +lemma shearCovector_on_cut (h : M →+ ℝ) (hh : h p=0) : shearCovector Ω p h=h := by + ext m + change h (m+Ω p m • p)=h m + rw [map_add,map_zsmul,hh,smul_zero,add_zero] + +def mutationCovector (h : M →+ ℝ) : M →+ ℝ := + if 0≤h p then h else shearCovector Ω p h +def mutationCovectorInverse (h : M →+ ℝ) : M →+ ℝ := + if 0≤h p then h else shearCovectorInverse Ω p h +include hp in +lemma mutationCovector_at_p (h : M →+ ℝ) : mutationCovector Ω p h p=h p := by + unfold mutationCovector + split_ifs <;> first | rfl | exact shearCovector_at_p Ω p hp h +include hp in +lemma mutationCovectorInverse_at_p (h : M →+ ℝ) : mutationCovectorInverse Ω p h p=h p := by + unfold mutationCovectorInverse + split_ifs <;> first | rfl | exact shearCovectorInverse_at_p Ω p hp h +include hp in +lemma mutationCovector_left_inverse (h : M →+ ℝ) : + mutationCovectorInverse Ω p (mutationCovector Ω p h)=h := by + unfold mutationCovectorInverse + rw [mutationCovector_at_p Ω p hp] + unfold mutationCovector + split_ifs <;> first | rfl | exact shearCovector_inv' Ω p hp h +include hp in +lemma mutationCovector_right_inverse (h : M →+ ℝ) : + mutationCovector Ω p (mutationCovectorInverse Ω p h)=h := by + unfold mutationCovector + rw [mutationCovectorInverse_at_p Ω p hp] + unfold mutationCovectorInverse + split_ifs <;> first | rfl | exact shearCovector_inv Ω p hp h + +def mutationCovectorEquiv : (M →+ ℝ) ≃ (M →+ ℝ) where + toFun:=mutationCovector Ω p + invFun:=mutationCovectorInverse Ω p + left_inv:=mutationCovector_left_inverse Ω p hp + right_inv:=mutationCovector_right_inverse Ω p hp + +lemma incoming_shear_covariance (hΩ : ∀m,Ω m m=0) (r : M) : + incomingCovector Ω (mutationShear Ω p r)=shearCovector Ω p (incomingCovector Ω r) := by + ext m + change (Ω m (mutationShear Ω p r):ℝ)=(Ω (mutationShearInverse Ω p m) r:ℝ) + have H:=mutationShear_pairing Ω hΩ p (mutationShearInverse Ω p m) r + rw [mutationShear_right_inverse Ω p (hΩ p)] at H + exact congrArg (fun z : ℤ=>(z:ℝ)) H + +def mutationIncomingLabel (m : M) : M := m+max 0 (-Ω p m) • p +def mutationIncomingLabelInverse (m : M) : M := m-max 0 (-Ω p m) • p +include hp in +lemma mutationIncomingLabel_pairing (m : M) : Ω p (mutationIncomingLabel Ω p m)=Ω p m := by + change Ω p (m+max 0 (-Ω p m) • p)=Ω p m + rw [map_add,map_zsmul,hp,smul_zero,add_zero] +include hp in +lemma mutationIncomingLabelInverse_pairing (m : M) : Ω p (mutationIncomingLabelInverse Ω p m)=Ω p m := by + change Ω p (m-max 0 (-Ω p m) • p)=Ω p m + rw [map_sub,map_zsmul,hp,smul_zero,sub_zero] +include hp in +lemma mutationIncomingLabel_left_inverse (m : M) : + mutationIncomingLabelInverse Ω p (mutationIncomingLabel Ω p m)=m := by + unfold mutationIncomingLabelInverse + rw [mutationIncomingLabel_pairing Ω p hp] + exact add_sub_cancel_right m _ +include hp in +lemma mutationIncomingLabel_right_inverse (m : M) : + mutationIncomingLabel Ω p (mutationIncomingLabelInverse Ω p m)=m := by + unfold mutationIncomingLabel + rw [mutationIncomingLabelInverse_pairing Ω p hp] + exact sub_add_cancel m _ +def mutationIncomingLabelEquiv : M ≃ M where + toFun:=mutationIncomingLabel Ω p + invFun:=mutationIncomingLabelInverse Ω p + left_inv:=mutationIncomingLabel_left_inverse Ω p hp + right_inv:=mutationIncomingLabel_right_inverse Ω p hp +lemma mutationIncomingLabel_nonnegative (m : M) (hm : 0≤Ω p m) : mutationIncomingLabel Ω p m=m := by + rw [mutationIncomingLabel,max_eq_left (by omega),zero_zsmul,add_zero] +lemma mutationIncomingLabel_nonpositive (m : M) (hm : Ω p m≤0) : + mutationIncomingLabel Ω p m=mutationShear Ω p m := by + rw [mutationIncomingLabel,max_eq_right (by omega),neg_zsmul] + exact (sub_eq_add_neg _ _).symm +lemma incoming_mutation_covariance (hΩ : ∀m,Ω m m=0) (r : M) : + incomingCovector Ω (mutationIncomingLabel Ω p r)=mutationCovector Ω p (incomingCovector Ω r) := by + by_cases hr : 0≤Ω p r + · rw [mutationIncomingLabel_nonnegative Ω p r hr,mutationCovector,ite_eq_left] + change (0:ℝ)≤(Ω p r:ℝ) + exact_mod_cast hr + · have hr' : Ω p r≤0:=le_of_lt (lt_of_not_ge hr) + rw [mutationIncomingLabel_nonpositive Ω p r hr',incoming_shear_covariance Ω p hΩ r, + mutationCovector,ite_eq_right] + change ¬(0:ℝ)≤(Ω p r:ℝ) + exact_mod_cast hr +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/IncomingExtremalLocality.lean b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingExtremalLocality.lean new file mode 100644 index 0000000000000000000000000000000000000000..a45339106b15c1cf6b54680086bf4f465b246a49 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingExtremalLocality.lean @@ -0,0 +1,86 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PolynomialIncomingPerturbation +import OAI.Combinatorics.Chromatic.GradedAlgebra.RootSectionHalfspace + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits +open Classical +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) +local instance incomingExtremalLocalityTorusRing : Ring (Torus LaurentRay.vUnit Ω) := + Torus.instRing LaurentRay.vUnit Ω +local instance incomingExtremalLocalityTorusAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance incomingExtremalLocalityTorusAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma inverse_pairing_nonnegative (m:M) (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf:∀k r,coeff k f r≠0 → 0 ≤ Ω r m) : + ∀k r,coeff k (invOfUnit f 1) r≠0 → 0 ≤ Ω r m := by + intro k r hr + let P:=nonpositiveCone (-(incomingCovector Ω m)) + have H:=inverse_support_addSubmonoid LaurentRay.vUnit Ω P f (by + intro d x hx + change -(Ω x m:ℝ) ≤ 0 + have hh:0 ≤ (Ω x m:ℝ):=by exact_mod_cast hf d x hx + linarith) k r hr + change -(Ω r m:ℝ) ≤ 0 at H + have hh:0 ≤ (Ω r m:ℝ):=by linarith + exact_mod_cast hh + +include hΩ in +lemma adjoint_pairing_nonnegative (m b:M) (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf0:constantCoeff f=1) (hf:∀k r,coeff k f r≠0 → 0 ≤ Ω r m) + (hb:0 ≤ Ω b m) (N:ℕ) : + coeff N (adjoint f (PowerSeries.C (Torus.X LaurentRay.vUnit Ω b))) m= + coeff N (PowerSeries.C (Torus.X LaurentRay.vUnit Ω b)) m := by + apply adjoint_target_cyclic LaurentRay.vUnit Ω hΩ f b m N hf0 + intro i j hij r hr s hs he + have h1:=hf i r (Finsupp.mem_support_iff.mp hr) + have h2:=inverse_pairing_nonnegative Ω m f hf j s (Finsupp.mem_support_iff.mp hs) + have H:Ω (r+(s+b)) m=0:=by rw [he,hΩ] + simp only [map_add,AddMonoidHom.add_apply] at H + omega + +include hΩ in +lemma actualMonomialAdjoint_extremal (τ:M →+ ℤ) (m b:M) + (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf0:constantCoeff f=1) (hf:∀k r,coeff k f r≠0 → 0 ≤ Ω r m) + (hb:0 ≤ Ω b m) : + actualMonomialAdjointCoefficient Ω τ f b m=actualMonomialAdjointCoefficient Ω τ 1 b m := by + unfold actualMonomialAdjointCoefficient actualRootCoefficient + split_ifs + · have H1:=adjoint_monomial_coeff LaurentRay.vUnit Ω hΩ f b (m-b) ((τ (m-b)).toNat) + have H2:=adjoint_monomial_coeff LaurentRay.vUnit Ω hΩ 1 b (m-b) ((τ (m-b)).toNat) + rw [sub_add_cancel] at H1 H2 + rw [←H1,←H2,adjoint_pairing_nonnegative Ω hΩ m b f hf0 hf hb] + have hi:invOfUnit (1:PowerSeries (Torus LaurentRay.vUnit Ω)) 1=1:=by + simpa only [mul_one] using (invOfUnit_mul (1:PowerSeries (Torus LaurentRay.vUnit Ω)) 1 (by simp)) + simp only [adjoint,hi,one_mul,mul_one] + · rfl + +include hΩ in +lemma polynomialSectionIncoming_extremal (F:Torus LaurentRay.vUnit Ω) (m:M) + (hF:∀b∈F.support,0 ≤ Ω b m) : polynomialSectionIncoming Ω C coord F m=F m := by + rw [←actualPolynomialAdjointCoefficient_one Ω hΩ (rootOrder coord) F m] + unfold polynomialSectionIncoming polynomialSectionCoefficient actualPolynomialAdjointCoefficient Finsupp.sum + apply Finset.sum_congr rfl + intro b hb + apply congrArg (fun x=>F b*x) + apply actualMonomialAdjoint_extremal Ω hΩ (rootOrder coord) m b _ + (rootSectionChart Ω C (incomingCovector Ω m)).property.1 _ (hF b hb) + intro k r hr + have H:=rootSectionChart_nonnegative Ω C (incomingCovector Ω m) k r hr + change 0 ≤ (Ω r m:ℝ) at H + exact_mod_cast H +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/IncomingRayElement.lean b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingRayElement.lean new file mode 100644 index 0000000000000000000000000000000000000000..e996689d45bbfbb4f5e59e1768414c68d7aef5a2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingRayElement.lean @@ -0,0 +1,271 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ChartRefinement +import OAI.Combinatorics.Chromatic.Walls.RayIncomingIdentification +import OAI.Combinatorics.Chromatic.GradedAlgebra.GradedFormalLog + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) + +lemma root_graded_log (F : CompletedPositive v Ω C) (n : ℕ) : + coeff n (FormalLog.log F.val)∈rootGrade v Ω C n := by + apply FormalLog.log_graded (rootGrade v Ω C) (rootGrade_one v Ω C) + (rootGrade_mul v Ω C) _ F.val F.property.2 n + intro j a x hx m hm + change a • x m=0 + rw [hx m hm,smul_zero] + +lemma OnPositiveRay.add {r a b : M} (ha : OnPositiveRay r a) (hb : OnPositiveRay r b) : + OnPositiveRay r (a+b) := by + obtain ⟨u,v,hu,hv,he⟩:=ha + obtain ⟨s,t,hs,ht,hf⟩:=hb + refine ⟨u*s,s*v+u*t,Nat.mul_pos hu hs,by positivity,?_⟩ + calc + (u*s) • (a+b)=s • (u • a)+u • (s • b):=by + rw [nsmul_add,mul_nsmul,mul_nsmul]; + congr 1; rw [←mul_nsmul,←mul_nsmul,Nat.mul_comm] + _=s • (v • r)+u • (t • r):=by rw [he,hf] + _=(s*v+u*t) • r:=by simp only [smul_smul,add_nsmul] + +lemma incoming_ray_log_support (r : M) (k : M→+ℝ) (F : CompletedPositive v Ω C) (n : ℕ) : + SupportedOn v Ω (fun m=>Ω m r=0 ∧ k m=0) + (coeff n (FormalLog.log (chartZero v Ω C k + (chartZero v Ω C (incomingCovector Ω r) F)).val)) := by + let B:=chartZero v Ω C (incomingCovector Ω r) F + let D:=chartZero v Ω C k B + have hr:= (chartThree_supported v Ω C k (kernelSupport Ω r) B + (incoming_chart_supported v Ω C r F)).2.1 + have hk:=chartZero_supported_kernel v Ω C k B + apply strict_log_support v Ω + (fun a b ha hb=>by + constructor + · simp only [map_add,AddMonoidHom.add_apply,ha.1,hb.1,add_zero] + · simp only [map_add,ha.2,hb.2,add_zero]) + D.val D.property.1 _ n + intro j m hm + by_contra hx + apply hm + constructor + · by_contra hn + exact hx (hr (j+1) m hn) + · by_contra hn + exact hx (hk (j+1) m hn) + +theorem incoming_ray_element_through (hΩ : ∀m,Ω m m=0) (r : M) (k : M→+ℝ) + (hk : k r=0) (F D : CompletedPositive v Ω C) (N : ℕ) + (hgeneric : ∀n,0ha.add hb) D.val D.property.1 + (fun j m hm=>not_not.mp (fun hx=>hm (hD j m hx))) n m hm + rw [hD0] + by_cases hn0 : n=0 + · subst n + simp only [coeff_zero_eq_constantCoeff,FormalLog.log_constant,Finsupp.zero_apply] + · by_contra hx + have hr : HasRootDegree C n m:=by + by_contra hh; exact hx (root_graded_log v Ω C B n m hh) + have hker : Ω m r=0 ∧ k m=0:=by + by_contra hh; exact hx (incoming_ray_log_support v Ω C r k F n m hh) + exact hm (hgeneric n (by omega) hn m hr hker.1 hker.2) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub + +lemma incoming_unique_through (hΩ : ∀m,Ω m m=0) + (F G : CompletedPositive v Ω C) (N : ℕ) + (H : ∀n≤N,incomingCoefficient v Ω C n F.val=incomingCoefficient v Ω C n G.val) : + ∀n≤N,coeff n F.val=coeff n G.val := by + intro n hn + induction n using Nat.strong_induction_on with + | h n ih=> + cases n with + | zero=>simp only [coeff_zero_eq_constantCoeff,F.property.1,G.property.1] + | succ n=> + have hEq:=incomingCoefficient_leading v Ω C hΩ F.val G.val n + (fun j hj=>ih j (by omega) (by omega)) (F.property.2 _) (G.property.2 _) + rw [H (n+1) hn,sub_self] at hEq + exact sub_eq_zero.mp hEq.symm +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M I A : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M→+M→+ℤ) (C : (I → ℤ)→+M) + +omit [Algebra ℚ R] in +lemma completed_list_constant (l : List A) (F : A → CompletedPositive v Ω C) : + constantCoeff (l.map (fun a=>(F a).val)).prod=1 := by + induction l with + | nil=>simp + | cons a l ih=>simp only [List.map_cons,List.prod_cons,map_mul,(F a).property.1,ih,one_mul] +omit [Algebra ℚ R] in +lemma completed_list_graded (l : List A) (F : A → CompletedPositive v Ω C) : + ∀n,coeff n (l.map (fun a=>(F a).val)).prod∈rootGrade v Ω C n := by + induction l with + | nil=>simpa using FormalLog.graded_one (rootGrade v Ω C) (rootGrade_one v Ω C) + | cons a l ih=> + simpa only [List.map_cons,List.prod_cons] using + FormalLog.graded_multiply (rootGrade v Ω C) (rootGrade_mul v Ω C) _ _ (F a).property.2 ih + +def completedListProduct (l : List A) (F : A → CompletedPositive v Ω C) : CompletedPositive v Ω C := + ⟨(l.map (fun a=>(F a).val)).prod,completed_list_constant v Ω C l F,completed_list_graded v Ω C l F⟩ + +omit [Algebra ℚ R] in +lemma completed_list_supported (l : List A) (F : A → CompletedPositive v Ω C) + (V : AddSubmonoid M) (H : ∀a∈l,∀n,coeff n (F a).val∈supportedSubring v Ω V) : + ∀n,coeff n (completedListProduct v Ω C l F).val∈supportedSubring v Ω V := by + induction l with + | nil=> + intro n + simp only [completedListProduct,List.map_nil,List.prod_nil,coeff_one] + split_ifs + · exact (supportedSubring v Ω V).one_mem + · exact (supportedSubring v Ω V).zero_mem + | cons a l ih=> + exact PowerSeriesSplit.mul_mem (supportedSubring v Ω V) _ _ (H a (by simp)) + (ih (fun a ha=>H a (by simp [ha]))) + +lemma incoming_coefficient_supported (V : AddSubmonoid M) (F : CompletedPositive v Ω C) + (H : ∀n,coeff n F.val∈supportedSubring v Ω V) (n : ℕ) : + incomingCoefficient v Ω C n F.val∈supportedSubring v Ω V := by + intro m hm + rw [incomingCoefficient_apply] + split_ifs with hr + · exact strict_log_support v Ω (V:=fun x=>x∈V) (fun a b ha hb=>V.add_mem ha hb) + (chartZero v Ω C (incomingCovector Ω m) F).val + (chartZero v Ω C (incomingCovector Ω m) F).property.1 + (fun j=> (chartThree_supported v Ω C (incomingCovector Ω m) V F H).2.1 (j+1)) n m hm + · rfl + +omit [Algebra ℚ R] in +lemma strict_list_product_through (l : List A) (F : A → CompletedPositive v Ω C) + (P : M → Prop) (hP : ∀a b,P a → P b → P (a+b)) (N : ℕ) + (H : ∀a∈l,∀n,n+1≤N → SupportedOn v Ω P (coeff (n+1) (F a).val)) : + ∀n,n+1≤N → SupportedOn v Ω P (coeff (n+1) (completedListProduct v Ω C l F).val) := by + induction l with + | nil=>intro n hn; simp only [completedListProduct,List.map_nil,List.prod_nil,coeff_one,show n+1≠0 by omega,ite_false]; exact SupportedOn.zero v Ω P + | cons a l ih=> + exact strict_mul_through v Ω P hP (F a).val (completedListProduct v Ω C l F).val N + (F a).property.1 (completed_list_constant v Ω C l F) (H a (by simp)) + (ih (fun a ha=>H a (by simp [ha]))) + +omit [Algebra ℚ R] in +lemma ordered_ray_middle (hΩ : ∀m,Ω m m=0) (l : List M) + (F : M → CompletedPositive v Ω C) (N : ℕ) + (H : ∀p∈l,∀n,n+1≤N → ∀m,coeff (n+1) (F p).val m≠0 → OnPositiveRay p m) + (hpair : l.Pairwise (fun a b=>0<Ω a b)) (p : M) (hp : p∈l) : + ∀n≤N,coeff n (F p).val= + coeff n (chartZero v Ω C (incomingCovector Ω p) (completedListProduct v Ω C l F)).val := by + classical + obtain ⟨a,b,he⟩:=List.mem_iff_append.mp hp + subst l + have hsplit:=List.pairwise_append.mp hpair + have hbefore : ∀q∈a,0 < incomingCovector Ω p q:=by + intro q hq + change (0:ℝ)<(Ω q p:ℝ) + exact_mod_cast hsplit.2.2 q hq p (by simp) + have hafter : ∀q∈b,incomingCovector Ω p q<0:=by + intro q hq + have Hpq:=(List.pairwise_cons.mp hsplit.2.1).1 q hq + have Hsk : Ω q p= -Ω p q:=by + have hh:=hΩ (p+q) + simp only [map_add,AddMonoidHom.add_apply,hΩ,zero_add,add_zero] at hh + omega + change (Ω q p:ℝ)<0 + rw [Hsk,Int.cast_neg] + exact neg_neg_of_pos (by exact_mod_cast Hpq) + let ga:=completedListProduct v Ω C a F + let gb:=completedListProduct v Ω C b F + have hA:=strict_list_product_through v Ω C a F (fun x=>0 < incomingCovector Ω p x) + (fun x y hx hy=>by simpa only [map_add] using add_pos hx hy) N + (fun q hq j hj m hm=>by + by_contra hn + exact hm (((H q (by simp [hq]) j hj m hn).eval (incomingCovector Ω p)).1.mpr (hbefore q hq))) + have hB:=strict_list_product_through v Ω C b F (fun x=>incomingCovector Ω p x<0) + (fun x y hx hy=>by simpa only [map_add] using add_neg hx hy) N + (fun q hq j hj m hm=>by + by_contra hn + exact hm (((H q (by simp [hq]) j hj m hn).eval (incomingCovector Ω p)).2.2.mpr (hafter q hq))) + have heq : ga.val*(F p).val*gb.val=(completedListProduct v Ω C (a++p::b) F).val:=by + simp only [ga,gb,completedListProduct,List.map_append,List.prod_append,List.map_cons,List.prod_cons,mul_assoc] + have ht:=chart_three_truncated_unique v Ω C (incomingCovector Ω p) + (completedListProduct v Ω C (a++p::b) F) ga.val (F p).val gb.val N + ga.property.1 (F p).property.1 gb.property.1 heq + (fun j hj m hm=>not_not.mp (fun hh=>hm (hA j hj m hh))) + (fun j hj m hm=>((H p (by simp) j hj m hm).eval (incomingCovector Ω p)).2.1.mpr + (by change (Ω p p:ℝ)=0; rw [hΩ,Int.cast_zero])) + (fun j hj m hm=>not_not.mp (fun hh=>hm (hB j hj m hh))) + exact fun n hn=>(ht n hn).2.1 + +theorem joint_recovered_from_incoming (hΩ : ∀m,Ω m m=0) + (l : List M) (F : CompletedPositive v Ω C) (N : ℕ) + (V : AddSubmonoid M) (hF : ∀n,coeff n F.val∈supportedSubring v Ω V) + (hcover : ∀n,00<Ω a b)) + (hRay : ∀p∈l,∀n,n+1≤N → ∀m, + coeff (n+1) (chartZero v Ω C (incomingCovector Ω p) F).val m≠0 → OnPositiveRay p m) : + ∀n≤N,coeff n F.val=coeff n (completedListProduct v Ω C l + (fun p=>chartZero v Ω C (incomingCovector Ω p) F)).val := by + let G:=completedListProduct v Ω C l (fun p=>chartZero v Ω C (incomingCovector Ω p) F) + apply incoming_unique_through v Ω C hΩ F G N + intro n hn + by_cases hn0 : n=0 + · subst n; rw [incomingCoefficient_zero,incomingCoefficient_zero] + apply Finsupp.ext + intro m + by_cases hmV : m∈V + · rw [incomingCoefficient_apply,incomingCoefficient_apply] + split_ifs with hm + · obtain ⟨p,hp,hpm⟩:=hcover n (by omega) hn m hm hmV + have hmid:=ordered_ray_middle v Ω C hΩ l + (fun p=>chartZero v Ω C (incomingCovector Ω p) F) N hRay hpair p hp + have Hlog:=FormalLog.log_coeff_congr + (chartZero v Ω C (incomingCovector Ω p) F).val + (chartZero v Ω C (incomingCovector Ω p) G).val n (fun j hj=>hmid j (hj.trans hn)) + have hF:=incoming_same_ray v Ω C hpm F + have hG:=incoming_same_ray v Ω C hpm G + rw [hF,hG] at Hlog + exact congrArg (fun x : Torus v Ω=>x m) Hlog + · rfl + · rw [incoming_coefficient_supported v Ω C V F hF n m hmV, + incoming_coefficient_supported v Ω C V G + (completed_list_supported v Ω C l _ V + (fun p _=>(chartThree_supported v Ω C (incomingCovector Ω p) V F hF).2.1)) n m hmV] + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/IncomingSystem.lean b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingSystem.lean new file mode 100644 index 0000000000000000000000000000000000000000..f273124ced6d5b5c6683605db606a2ab11dff76e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingSystem.lean @@ -0,0 +1,227 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.QuantumTorusWallLeading + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries ElementaryPositivity.PowerSeriesSplit +noncomputable section + +variable {R M I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub +local instance : @Module ℚ (Torus v Ω) _ (Torus.instRing v Ω).toAddCommMonoid := by + let finsuppModule := (inferInstance : Module ℚ (M →₀ R)) + letI : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid + exact + { smul := finsuppModule.smul + one_smul := finsuppModule.one_smul + mul_smul := finsuppModule.mul_smul + smul_zero := finsuppModule.smul_zero + smul_add := finsuppModule.smul_add + add_smul := finsuppModule.add_smul + zero_smul := finsuppModule.zero_smul } +attribute [local instance] Classical.propDecidable + +lemma rootDegree_finite (n : ℕ) : {m | HasRootDegree C n m}.Finite := by + let F : (I → Fin (n+1)) → M := fun d => C (fun i => (d i : ℤ)) + apply (Set.finite_range F).subset + rintro m ⟨d,hd,hm⟩ + have hi : ∀i,d i≤n := by + intro i + rw [←hd] + exact Finset.single_le_sum (fun j _ => Nat.zero_le (d j)) (Finset.mem_univ i) + exact ⟨fun i => ⟨d i,by have := hi i; omega⟩,hm⟩ + +def incomingCovector (r : M) : M →+ ℝ where + toFun a := (Ω a r : ℝ) + map_zero' := by simp + map_add' := by intro a b; simp + +def incomingMiddle (r : M) (f : PowerSeries (Torus v Ω)) : PowerSeries (Torus v Ω) := + zeroFactor (positiveProject v Ω (incomingCovector Ω r)) + (zeroProject v Ω (incomingCovector Ω r)) f + +omit [Algebra ℚ R] in +lemma incomingMiddle_constant (r : M) (f : PowerSeries (Torus v Ω)) : + constantCoeff (incomingMiddle v Ω r f)=1 := + left_constant _ _ + +omit [Algebra ℚ R] in +lemma incomingMiddle_coeff_congr (r : M) (f g : PowerSeries (Torus v Ω)) (n : ℕ) + (h : ∀k≤n,coeff k f=coeff k g) : + coeff n (incomingMiddle v Ω r f)=coeff n (incomingMiddle v Ω r g) := + zero_coeff_congr _ _ _ _ _ h + +def incomingCoefficient (n : ℕ) (f : PowerSeries (Torus v Ω)) : Torus v Ω := + Finsupp.onFinset (rootDegree_finite C n).toFinset + (fun m => if HasRootDegree C n m then + (coeff n (FormalLog.log (incomingMiddle v Ω m f))) m else 0) + (by + intro m hm + rw [Set.Finite.mem_toFinset] + change HasRootDegree C n m + by_contra hn + exact hm (ite_eq_right hn)) + +lemma incomingCoefficient_apply (n : ℕ) (f : PowerSeries (Torus v Ω)) (m : M) : + incomingCoefficient v Ω C n f m = if HasRootDegree C n m then + (coeff n (FormalLog.log (incomingMiddle v Ω m f))) m else 0 := rfl + +lemma incomingCoefficient_graded (n : ℕ) (f : PowerSeries (Torus v Ω)) : + incomingCoefficient v Ω C n f ∈ rootGrade v Ω C n := by + intro m hm + rw [incomingCoefficient_apply,ite_eq_right hm] + +lemma incomingCoefficient_zero (f : PowerSeries (Torus v Ω)) : + incomingCoefficient v Ω C 0 f=0 := by + ext m + rw [incomingCoefficient_apply] + simp only [coeff_zero_eq_constantCoeff_apply,FormalLog.log_constant] + split_ifs <;> rfl + +lemma incomingCoefficient_congr (f g : PowerSeries (Torus v Ω)) (n : ℕ) + (h : ∀k≤n,coeff k f=coeff k g) : + incomingCoefficient v Ω C n f=incomingCoefficient v Ω C n g := by + ext m + rw [incomingCoefficient_apply,incomingCoefficient_apply] + split_ifs with hm + · congr 1 + apply FormalLog.log_coeff_congr + intro j hj + exact incomingMiddle_coeff_congr v Ω m f g j (fun k hk => h k (hk.trans hj)) + · rfl + +omit [Algebra ℚ R] in +lemma torus_sub_apply (x y : Torus v Ω) (m : M) : (x-y) m=x m-y m := by + rw [sub_eq_add_neg] + change x m + -y m = x m-y m + exact (sub_eq_add_neg _ _).symm + +lemma incomingCoefficient_leading (hΩ : ∀m,Ω m m=0) + (f g : PowerSeries (Torus v Ω)) (n : ℕ) + (h : ∀k≤n,coeff k f=coeff k g) + (hf : coeff (n+1) f∈rootGrade v Ω C (n+1)) + (hg : coeff (n+1) g∈rootGrade v Ω C (n+1)) : + incomingCoefficient v Ω C (n+1) f-incomingCoefficient v Ω C (n+1) g = + coeff (n+1) f-coeff (n+1) g := by + classical + ext m + rw [torus_sub_apply,torus_sub_apply] + rw [incomingCoefficient_apply,incomingCoefficient_apply] + by_cases hm : HasRootDegree C (n+1) m + · rw [ite_eq_left hm,ite_eq_left hm] + have hlog := FormalLog.log_leading_difference (incomingMiddle v Ω m f) + (incomingMiddle v Ω m g) n (incomingMiddle_constant v Ω m f) + (incomingMiddle_constant v Ω m g) + (fun k hk => incomingMiddle_coeff_congr v Ω m f g k (fun j hj => h j (hj.trans hk))) + have hmid := zero_leading_difference (positiveProject v Ω (incomingCovector Ω m)) + (zeroProject v Ω (incomingCovector Ω m)) + (zero_positive_project v Ω (incomingCovector Ω m)) f g n h + have he := congrArg (fun t : Torus v Ω => t m) (hlog.trans hmid) + rw [torus_sub_apply] at he + change _-_=(Finsupp.filter (fun x => incomingCovector Ω m x=0) + (coeff (n+1) f-coeff (n+1) g)) m at he + rw [Finsupp.filter_apply] at he + have hzero : incomingCovector Ω m m=0 := by change (Ω m m : ℝ)=0; rw [hΩ,Int.cast_zero] + rw [ite_eq_left hzero,torus_sub_apply] at he + exact he + · rw [ite_eq_right hm,ite_eq_right hm,hf m hm,hg m hm] + +def incomingSolutionCoefficients (l : ℕ → Torus v Ω) : ℕ → Torus v Ω + | 0 => 1 + | n+1 => l (n+1)-incomingCoefficient v Ω C (n+1) + (PowerSeries.mk (fun k => if _ : k≤n then incomingSolutionCoefficients l k else 0)) +termination_by n => n + +def incomingSolution (l : ℕ → Torus v Ω) : PowerSeries (Torus v Ω) := + PowerSeries.mk (incomingSolutionCoefficients v Ω C l) + +lemma incomingSolution_constant (l : ℕ → Torus v Ω) : + constantCoeff (incomingSolution v Ω C l)=1 := by + rw [←coeff_zero_eq_constantCoeff_apply] + simp only [incomingSolution,coeff_mk,incomingSolutionCoefficients] + +lemma incomingSolution_graded (l : ℕ → Torus v Ω) + (hl : ∀n,l n∈rootGrade v Ω C n) (n : ℕ) : + coeff n (incomingSolution v Ω C l)∈rootGrade v Ω C n := by + cases n with + | zero => simpa only [coeff_zero_eq_constantCoeff_apply,incomingSolution_constant] using rootGrade_one v Ω C + | succ n => + simp only [incomingSolution,coeff_mk,incomingSolutionCoefficients] + intro m hm + rw [torus_sub_apply,hl _ m hm,incomingCoefficient_graded v Ω C _ _ m hm,sub_self] + +def incomingTruncation (l : ℕ → Torus v Ω) (n : ℕ) : PowerSeries (Torus v Ω) := + PowerSeries.mk (fun k => if k≤n then incomingSolutionCoefficients v Ω C l k else 0) + +lemma incomingTruncation_lower (l : ℕ → Torus v Ω) (n k : ℕ) (hk : k≤n) : + coeff k (incomingSolution v Ω C l)=coeff k (incomingTruncation v Ω C l n) := by + simp only [incomingSolution,incomingTruncation,coeff_mk,ite_eq_left hk] + +lemma incomingTruncation_top (l : ℕ → Torus v Ω) (n : ℕ) : + coeff (n+1) (incomingTruncation v Ω C l n)=0 := by + simp only [incomingTruncation,coeff_mk,show ¬n+1≤n by omega,ite_false] + +lemma incomingSolution_step (l : ℕ → Torus v Ω) (n : ℕ) : + coeff (n+1) (incomingSolution v Ω C l)= + l (n+1)-incomingCoefficient v Ω C (n+1) (incomingTruncation v Ω C l n) := by + simp only [incomingSolution,coeff_mk,incomingSolutionCoefficients,incomingTruncation,dite_eq_ite] + +lemma incomingSolution_prescription_difference (hΩ : ∀m,Ω m m=0) (l : ℕ → Torus v Ω) + (hl : ∀n,l n∈rootGrade v Ω C n) (n : ℕ) : + incomingCoefficient v Ω C (n+1) (incomingSolution v Ω C l)- + incomingCoefficient v Ω C (n+1) (incomingTruncation v Ω C l n)= + coeff (n+1) (incomingSolution v Ω C l)-0 := by + have hpgrade : coeff (n+1) (incomingTruncation v Ω C l n)∈rootGrade v Ω C (n+1) := by + intro m hm + rw [incomingTruncation_top] + rfl + have H := incomingCoefficient_leading v Ω C hΩ + (incomingSolution v Ω C l) (incomingTruncation v Ω C l n) n + (incomingTruncation_lower v Ω C l n) (incomingSolution_graded v Ω C l hl _) hpgrade + rw [incomingTruncation_top] at H + exact H + +lemma incomingSolution_prescription (hΩ : ∀m,Ω m m=0) (l : ℕ → Torus v Ω) + (hl : ∀n,l n∈rootGrade v Ω C n) (n : ℕ) : + incomingCoefficient v Ω C (n+1) (incomingSolution v Ω C l)=l (n+1) := by + have H := incomingSolution_prescription_difference v Ω C hΩ l hl n + rw [incomingSolution_step] at H + ext m + have he := congrArg (fun x : Torus v Ω => x m) H + simp only [torus_sub_apply,Finsupp.zero_apply,sub_zero] at he + exact sub_left_inj.mp he + +theorem existsUnique_incoming (hΩ : ∀m,Ω m m=0) (l : ℕ → Torus v Ω) + (hl : ∀n,l n∈rootGrade v Ω C n) : + ∃! g : CompletedPositive v Ω C, + ∀n,incomingCoefficient v Ω C (n+1) g.val=l (n+1) := by + let g : CompletedPositive v Ω C := ⟨incomingSolution v Ω C l, + incomingSolution_constant v Ω C l,incomingSolution_graded v Ω C l hl⟩ + refine ⟨g,fun n => incomingSolution_prescription v Ω C hΩ l hl n,?_⟩ + intro f hf + apply Subtype.ext + apply PowerSeries.ext + intro n + induction n using Nat.strong_induction_on with + | h n ih => + cases n with + | zero => rw [coeff_zero_eq_constantCoeff_apply,coeff_zero_eq_constantCoeff_apply,f.property.1,g.property.1] + | succ n => + have H := incomingCoefficient_leading v Ω C hΩ f.val g.val n + (fun k hk => ih k (by omega)) (f.property.2 _) (g.property.2 _) + rw [hf n,incomingSolution_prescription v Ω C hΩ l hl n] at H + ext m + have he := congrArg (fun x : Torus v Ω => x m) H + simp only [torus_sub_apply,sub_self] at he + exact sub_eq_zero.mp he.symm + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/IncomingTransportTrace.lean b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingTransportTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf69a995ec15f1d8a25ef9f3b9fc01a998bcf24c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/IncomingTransportTrace.lean @@ -0,0 +1,138 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationOrientedCompatibility + +namespace OAI + +section +namespace ElementaryPositivity.FormalLog +open PowerSeries +noncomputable section +variable {A : Type*} [Ring A] +lemma inverse_coeff_congr (F G : PowerSeries A) (hF : constantCoeff F=1) + (hG : constantCoeff G=1) (N : ℕ) (H : ∀n≤N,coeff n F=coeff n G) : + ∀n≤N,coeff n (invOfUnit F 1)=coeff n (invOfUnit G 1) := by + intro n hn + have HH:=mul_coeff_congr (invOfUnit F 1) (F*invOfUnit G 1) + (invOfUnit F 1) (G*invOfUnit G 1) n (fun _ _=>rfl) (by + intro j hj + exact mul_coeff_congr _ _ _ _ j (fun k hk=>H k (hk.trans (hj.trans hn))) (fun _ _=>rfl)) + rw [←mul_assoc,invOfUnit_mul F 1 hF,one_mul,mul_invOfUnit G 1 hG,mul_one] at HH + exact HH.symm +variable [Module ℚ A] +@[simp] lemma log_one : FormalLog.log (1 : PowerSeries A)=0 := by + ext n + simp [FormalLog.log] +end +end ElementaryPositivity.FormalLog +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesSplit +noncomputable section +variable {R M I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +local instance incomingTransportTraceRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance incomingTransportTraceAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance incomingTransportTraceAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +lemma chartNegative_log_positive (h : M →+ ℝ) (F : CompletedPositive v Ω C) + (r : M) (hr : 0≤h r) (n : ℕ) : + coeff n (FormalLog.log (chartNegative v Ω C h F).val) r=0 := by + exact strict_log_support v Ω (V:=fun m=>h m<0) + (fun a b ha hb=>by simpa only [map_add] using add_neg ha hb) _ + (chartNegative v Ω C h F).property.1 + (fun j m hm=>by by_contra hh; exact hm ((chart_three_support v Ω C h F).2.2 j m hh)) + n r (not_lt.mpr hr) + +lemma chartNegative_log_negative_kernel (hΩ : ∀m,Ω m m=0) (r : M) + (F : CompletedPositive v Ω C) + (hf : ∀n,coeff n F.val∈supportedSubalgebra v Ω (kernelSupport Ω r)) + (h : M →+ ℝ) (hr : h r<0) (n : ℕ) : + coeff n (FormalLog.log (chartNegative v Ω C h F).val) r= + coeff n (FormalLog.log F.val) r := by + let A:=chartPositive v Ω C h F + let B:=chartZero v Ω C h F + let D:=chartNegative v Ω C h F + have hs:=chartThree_supported v Ω C h (kernelSupport Ω r) F hf + have H1:=kernel_trace_log_product v Ω hΩ r A.val B.val A.property.1 B.property.1 hs.1 hs.2.1 n + have H2:=kernel_trace_log_product v Ω hΩ r (A.val*B.val) D.val + (by simp [A.property.1,B.property.1]) D.property.1 + (PowerSeriesSplit.mul_mem (supportedSubring v Ω (kernelSupport Ω r)) _ _ hs.1 hs.2.1) hs.2.2 n + have hp : coeff n (FormalLog.log A.val) r=0:=by + exact strict_log_support v Ω (V:=fun m=>0by simpa only [map_add] using add_pos ha hb) A.val A.property.1 + (fun j m hm=>by by_contra hh; exact hm ((chart_three_support v Ω C h F).1 j m hh)) + n r (not_lt.mpr hr.le) + have hz : coeff n (FormalLog.log B.val) r=0:=by + exact strict_log_support v Ω (V:=fun m=>h m=0) + (fun a b ha hb=>by rw [map_add,ha,hb,add_zero]) B.val B.property.1 + (fun j m hm=>by by_contra hh; exact hm ((chart_three_support v Ω C h F).2.1 j m hh)) + n r (ne_of_lt hr) + rw [H1,hp,hz,zero_add,zero_add] at H2 + rw [show A.val*B.val*D.val=F.val from chart_three_factorization v Ω C h F] at H2 + exact H2.symm + +lemma kernel_trace_log_inverse (hΩ : ∀m,Ω m m=0) (r : M) + (F : PowerSeries (Torus v Ω)) (hf : constantCoeff F=1) + (hs : ∀n,coeff n F∈supportedSubalgebra v Ω (kernelSupport Ω r)) (n : ℕ) : + coeff n (FormalLog.log (invOfUnit F 1)) r= -coeff n (FormalLog.log F) r := by + have hi : ∀j,coeff j (invOfUnit F 1)∈supportedSubalgebra v Ω (kernelSupport Ω r):=by + intro j m hm + by_contra hh + exact hm (inverse_support_addSubmonoid v Ω (kernelSupport Ω r) F + (fun k a ha=>by by_contra hn; exact ha (hs k a hn)) j m hh) + have H:=kernel_trace_log_product v Ω hΩ r F (invOfUnit F 1) hf (by simp) hs hi n + rw [mul_invOfUnit F 1 hf,FormalLog.log_one,map_zero,Finsupp.zero_apply] at H + exact eq_neg_of_add_eq_zero_right H.symm + +lemma incoming_negative_ratio_log (hΩ : ∀m,Ω m m=0) (r : M) + (F : CompletedPositive v Ω C) (x y : M →+ ℝ) (N : ℕ) + (hx : ∀n≤N,∀m,HasRootDegree C n m → + (0 < incomingCovector Ω r m → 0⟨id,id,id⟩⟩) + have Hy:=chart_negative_refinement v Ω C (incomingCovector Ω r) y y F N (by + intro n hn m hm + exact ⟨(hy n hn m hm).1,(hy n hn m hm).2,fun _=>⟨id,id,id⟩⟩) + have hi:=FormalLog.inverse_coeff_congr _ _ (chartNegative v Ω C x F).property.1 + (by change constantCoeff (X.val*D.val)=1; simp [X.property.1,D.property.1]) N Hx + have hinv : invOfUnit (X.val*D.val) 1=invOfUnit D.val 1*invOfUnit X.val 1:=by + apply left_inv_eq_right_inv (PowerSeries.invOfUnit_mul _ 1 (by simp [X.property.1,D.property.1])) + simp only [mul_assoc,←mul_assoc D.val,PowerSeries.mul_invOfUnit D.val 1 D.property.1, + one_mul,PowerSeries.mul_invOfUnit X.val 1 X.property.1] + have he : ∀n≤N,coeff n ((chartNegative v Ω C y F).val*invOfUnit (chartNegative v Ω C x F).val 1)= + coeff n (Y.val*invOfUnit X.val 1):=by + intro n hn + have H:=FormalLog.mul_coeff_congr _ _ _ _ n + (fun j hj=>Hy j (hj.trans hn)) (fun j hj=>hi j (hj.trans hn)) + rw [hinv,mul_assoc,←mul_assoc D.val,PowerSeries.mul_invOfUnit D.val 1 D.property.1,one_mul] at H + exact H + have hB:=incoming_chart_supported v Ω C r F + have hsX:=(chartThree_supported v Ω C x (kernelSupport Ω r) B hB).2.2 + have hsY:=(chartThree_supported v Ω C y (kernelSupport Ω r) B hB).2.2 + have hsI : ∀j,coeff j (invOfUnit X.val 1)∈supportedSubalgebra v Ω (kernelSupport Ω r):=by + intro j m hm + by_contra hh + exact hm (inverse_support_addSubmonoid v Ω _ X.val + (fun k a ha=>by by_contra hn; exact ha (hsX k a hn)) j m hh) + intro n hn + rw [FormalLog.log_coeff_congr _ _ n (fun j hj=>he j (hj.trans hn)), + kernel_trace_log_product v Ω hΩ r Y.val (invOfUnit X.val 1) Y.property.1 (by simp) hsY hsI n, + kernel_trace_log_inverse v Ω hΩ r X.val X.property.1 hsX n, + chartNegative_log_positive v Ω C x B r hxr n,neg_zero,add_zero] + exact chartNegative_log_negative_kernel v Ω C hΩ r B hB y hyr n +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/IndependentRotationComparison.lean b/lean/OAI/Combinatorics/Chromatic/Walls/IndependentRotationComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..72c8e2b14fc84f8e7bf0d7c18fda5beac8822ef6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/IndependentRotationComparison.lean @@ -0,0 +1,95 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RotationLocalPolynomials +import OAI.Combinatorics.Chromatic.QuantumTorus.IndependentSetElements + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus +open scoped BigOperators +open Classical +noncomputable section +variable {K M W : Type*} [Field K] [AddCommGroup M] [DecidableEq W] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (ell : M →+ ℤ) (p : M) (hp : ell p=1) + +include hΩ in +lemma independent_rotation_slice (a c : M) (hpa : Ω p a=1) (hpc : Ω p c= -1) + (hac : Ω a c=0) (w : W → M) (hw : ∀y,Ω p (w y)=0) + (t : Finset W) (k : ℕ) : + pureAction v (complementOmega ell Ω) (complementAlpha ell p Ω) + (embed v Ω hΩ ell p hp (∑ s : Finset (Fin 3), + independentTerm v Ω (Sum.elim ![a,c+p,c] w) k (s.disjSum t))) = + embed v Ω hΩ ell p hp (∑ s : Finset (Fin 3), + independentTerm v Ω (Sum.elim ![a,a+p,c] w) k (s.disjSum t)) := by + have hap : Ω a p= -1 := by rw [alternating_skew Ω hΩ a p,hpa] + have oldab : Ω a (a+p)≠0 := by simp [map_add,hΩ,hap] + have oldbc : Ω (a+p) c≠0 := by simp [map_add,hac,hpc] + have newab : Ω a (c+p)≠0 := by simp [map_add,hac,hap] + have newbc : Ω (c+p) c≠0 := by simp [map_add,hΩ,hpc] + have hwp : Compatible Ω p w t := fun y _ => hw y + have HA := compatible_add Ω a p w t hwp + have HC := compatible_add Ω c p w t hwp + rw [independent_triple_sum v Ω hΩ a (c+p) c newab newbc hac, + independent_triple_sum v Ω hΩ a (a+p) c oldab oldbc hac] + simp only [HA,HC] + by_cases ht : IsIndependent Ω w t + swap + · simp only [ht,ite_false,map_zero] + simp only [ht,ite_true] + let z := ∑y∈t,w y + have hpz : Ω p z=0 := by simp [z,map_sum,hw] + have hpa' : Ω p (a+z)=1 := by rw [map_add,hpa,hpz,add_zero] + have hpc' : Ω p (c+z)= -1 := by rw [map_add,hpc,hpz,add_zero] + have hpac : Ω p (a+c+z)=0 := by rw [map_add,map_add,hpa,hpc,hpz]; norm_num + have HA' := pureAction_pairing_one v Ω hΩ ell p hp (a+z) hpa' + have HC' := pureAction_pairing_neg_one v Ω hΩ ell p hp (c+z) hpc' + have H0 := pureAction_pairing_zero v Ω hΩ ell p hp z hpz + have HAC := pureAction_pairing_zero v Ω hΩ ell p hp (a+c+z) hpac + have hza : a+p+z=a+z+p := by abel + have hzc : c+p+z=c+z+p := by abel + change pureAction v _ _ (embed v Ω hΩ ell p hp + ((if t.card=k then Torus.X v Ω z else 0)+ + (if t.card+1=k ∧ Compatible Ω a w t then Torus.X v Ω (a+z) else 0)+ + (if t.card+1=k ∧ Compatible Ω c w t then Torus.X v Ω (c+p+z) else 0)+ + (if t.card+1=k ∧ Compatible Ω c w t then Torus.X v Ω (c+z) else 0)+ + (if t.card+2=k ∧ Compatible Ω a w t ∧ Compatible Ω c w t then Torus.X v Ω (a+c+z) else 0))) = _ + rw [hza,hzc] + have groupNew (A B C D E : Torus v Ω) : A+B+C+D+E=A+B+(D+C)+E := by abel + rw [groupNew] + simp only [ite_add_ite,zero_add] + have groupOld (A B C D E : Torus v Ω) : A+B+C+D+E=A+(B+C)+D+E := by abel + conv_rhs => rw [groupOld] + simp only [ite_add_ite,zero_add] + simp only [map_add] + have embite (P : Prop) [Decidable P] (x : Torus v Ω) : + embed v Ω hΩ ell p hp (if P then x else 0) = + if P then embed v Ω hΩ ell p hp x else 0 := by + split_ifs <;> simp + have actite (P : Prop) [Decidable P] (x) : + pureAction v (complementOmega ell Ω) (complementAlpha ell p Ω) + (if P then x else 0) = + if P then pureAction v (complementOmega ell Ω) (complementAlpha ell p Ω) x else 0 := by + split_ifs <;> simp + simp only [embite,actite] + simp only [H0,HA',HC',HAC] + rfl + +include hΩ in +lemma independentElement_rotation [Fintype W] (a c : M) + (hpa : Ω p a=1) (hpc : Ω p c= -1) (hac : Ω a c=0) + (w : W → M) (hw : ∀y,Ω p (w y)=0) (k : ℕ) : + pureAction v (complementOmega ell Ω) (complementAlpha ell p Ω) + (embed v Ω hΩ ell p hp (independentElement v Ω (Sum.elim ![a,c+p,c] w) k)) = + embed v Ω hΩ ell p hp (independentElement v Ω (Sum.elim ![a,a+p,c] w) k) := by + rw [independent_sum_decomposition,independent_sum_decomposition,map_sum,map_sum,map_sum] + apply Finset.sum_congr rfl + intro t _ + exact independent_rotation_slice v Ω hΩ ell p hp a c hpa hpc hac w hw t k +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/InfinityCutCharts.lean b/lean/OAI/Combinatorics/Chromatic/Walls/InfinityCutCharts.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f0034a452f76c76bd8caa582aa3c949402479be --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/InfinityCutCharts.lean @@ -0,0 +1,152 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.InfinityLaurentFinite +import OAI.Combinatorics.Chromatic.QuantumTorus.InfinityUnitAlgebra +import OAI.Combinatorics.Chromatic.Walls.MutationInfinityAlgebra + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +def infinitySideHom (pos : Bool) : + PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) →+* + PowerSeries (HahnSeries ℤ (Torus v Ω)) := + (PowerSeries.map (expandFiberInfinity v Ω hΩ k p)).comp + (mutationSideAction v (complementOmega k Ω) (complementAlpha k p Ω) pos).toRingHom + +lemma infinitySide_cut (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + innerHom (completedPureUnit v Ω hΩ (-p))⁻¹ (infinitySideHom v Ω hΩ k p true f)= + infinitySideHom v Ω hΩ k p false (completedPureAction v _ _ f) := by + change innerHom _ (PowerSeries.map (expandFiberInfinity v Ω hΩ k p) f)=_ + rw [←completed_expand_opposite_inverse v Ω hΩ k p hq] + change PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + (completedOppositeInverseAction v _ _ f)= + PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + (mutationSideAction v _ _ false (completedPureAction v _ _ f)) + congr 1 + +lemma infinitySide_cut_reverse (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + innerHom (completedPureUnit v Ω hΩ (-p)) + (infinitySideHom v Ω hΩ k p false f)= + infinitySideHom v Ω hΩ k p true ((completedPureAction v _ _).symm f) := by + rw [show infinitySideHom v Ω hΩ k p false f= + PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + (mutationSideAction v _ _ false f) from rfl] + rw [←completed_expand_opposite v Ω hΩ k p hq] + change PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + ((completedOppositeInverseAction v _ _).symm + (mutationSideAction v _ _ false f))=_ + congr 1 + have H:=mutationSideAction_cut_reverse v (complementOmega k Ω) (complementAlpha k p Ω) + (mutationSideAction v _ _ false f) + rw [RingEquiv.symm_apply_apply] at H + exact H.symm +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance : NonUnitalSemiring (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalNonAssocSemiring + +lemma mutation_infinity_oriented (pos b : Bool) (F : CompletedPositive LaurentRay.vUnit Ω C) + (hf : ∀n m,coeff n F.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) + (G : CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc)) + (hG : G.val=mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (orientPowerSeries b F.val)) : + infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) pos + (rationalRegrade LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) (nonpDegree coord pc) (mutationSize Ω C pc+1) + (orientPowerSeries b F.val)) = mutatedLaurent Ω C coord hcoord pc LaurentRay.vUnit G := by + let f : CompletedPositive LaurentRay.vUnit Ω C:=⟨orientPowerSeries b F.val, + orientPowerSeries_constant b F.val F.property.1,orientPowerSeries_graded Ω C b F.val F.property.2⟩ + have hg : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos):=by + cases b + · exact inverse_support_addSubmonoid LaurentRay.vUnit Ω _ F.val hf + · exact hf + have hb : RegradeBound LaurentRay.vUnit Ω + (nonpDegree (mutatedCoordinates Ω C coord pc) pc) (mutationSize Ω C pc+1) G.val := by + rw [hG] + exact mutationCompletion_nonp_bound LaurentRay.vUnit Ω hΩ C coord hcoord pc pos f hg + have HT:=congrArg (PowerSeries.map (expandFiberInfinity LaurentRay.vUnit Ω hΩ + (pureDegree coord pc) (simpleRoot C pc))) + (mutation_rational_oriented_compatibility Ω hΩ C coord hcoord pc pos b F hf) + have HG:=congrArg (fun t : PowerSeries (Torus LaurentRay.vUnit Ω) => + PowerSeries.map (expandFiberInfinity LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc)) + (rationalRegrade LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) (nonpDegree (mutatedCoordinates Ω C coord pc) pc) + (mutationSize Ω C pc+1) t)) hG.symm + exact HT.trans (HG.trans (expandInfinity_rationalRegrade LaurentRay.vUnit Ω hΩ + (pureDegree coord pc) (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) _ _ _ G.val + (mutated_series_laurentBounded Ω C coord hcoord pc LaurentRay.vUnit G.property.2) hb)) +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma mutation_infinity_oriented_square (pos b : Bool) (F : CompletedPositive LaurentRay.vUnit Ω C) + (hf : ∀n m,coeff n F.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) + (hbf : RegradeBound LaurentRay.vUnit Ω (nonpDegree coord pc) (mutationSize Ω C pc+1) F.val) + (hbi : RegradeBound LaurentRay.vUnit Ω (nonpDegree coord pc) (mutationSize Ω C pc+1) (invOfUnit F.val 1)) + (G : CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc)) + (hG : G.val=mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (orientPowerSeries b F.val)) + (x : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + innerHom (infinityCompletedUnit Ω C coord hcoord pc LaurentRay.vUnit G) + (infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) pos x)= + infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) pos + (comparisonAction LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (orientedBounded LaurentRay.vUnit Ω (nonpDegree coord pc) (pureDegree coord pc) + (mutationSize Ω C pc+1) (completedBiUnit LaurentRay.vUnit Ω C coord hcoord pc F) hbf hbi b) x) := by + have hh:=mutation_infinity_oriented Ω hΩ C coord hcoord pc pos b F hf G hG + cases b + · exact mapped_unit_square + (infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) pos) + (boundedRationalUnit LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (completedBiUnit LaurentRay.vUnit Ω C coord hcoord pc F)⁻¹ hbi hbf) + (infinityCompletedUnit Ω C coord hcoord pc LaurentRay.vUnit G) hh x + · exact mapped_unit_square + (infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) pos) + (boundedRationalUnit LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (completedBiUnit LaurentRay.vUnit Ω C coord hcoord pc F) hbf hbi) + (infinityCompletedUnit Ω C coord hcoord pc LaurentRay.vUnit G) hh x +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/InfinityFiniteLoop.lean b/lean/OAI/Combinatorics/Chromatic/Walls/InfinityFiniteLoop.lean new file mode 100644 index 0000000000000000000000000000000000000000..5abf2a05a83efef3b7ebd37ee7ea83109cc33d48 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/InfinityFiniteLoop.lean @@ -0,0 +1,144 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.InfinityPath + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance : NonUnitalSemiring (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalNonAssocSemiring + +lemma actualInfinityPath_loop_commute {a : Module.Dual ℝ E} (p : GenericLinePath C e a a) + (d N : ℕ) (hN : 1≤N) (hdN : (mutationSize Ω C pc+1)*d≤N) (m : M) : + coeff d ((actualInfinityPathProductUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p N).val* + PowerSeries.C (HahnSeries.single (-pureDegree coord pc m) (Torus.X LaurentRay.vUnit Ω m)))= + coeff d (PowerSeries.C (HahnSeries.single (-pureDegree coord pc m) (Torus.X LaurentRay.vUnit Ω m))* + (actualInfinityPathProductUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p N).val) := by + classical + let pos:=decide (0f.coeff (z-pureDegree coord pc m)) + (actualInfinityPath_loop_commute Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p d N hN hdN m) + rw [coeff_mul_C,coeff_C_mul,HahnSeries.coeff_mul_single,HahnSeries.coeff_single_mul] at H + have heq : z-pureDegree coord pc m-(-pureDegree coord pc m)=z:=by omega + rw [heq] at H + exact H +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {K M I : Type*} [Field K] [AddCommGroup M] [Fintype I] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +lemma positive_root_ne_zero (hC : Function.Injective C) {n : ℕ} (hn : 0(d i:ℤ))=0:=hC (hc.trans (map_zero C).symm) + have hd0 : d=0:=by + funext i + have H:=congrFun hz i + change (d i:ℤ)=0 at H + change d i=0 + exact_mod_cast H + have hn0 : n=0:=by simpa only [hd0,Pi.zero_apply,Finset.sum_const_zero] using hd.symm + omega + +lemma completed_central_through + (hv : Function.Injective (fun z : ℤ=>(↑(v^z):K))) + (hΩ : ∀m,Ω m m=0) (hnd : ∀r≠0,∃m,Ω r m≠0) (hC : Function.Injective C) + (F : CompletedPositive v Ω C) (N : ℕ) + (hf : ∀m n,n≤N → coeff n (F.val*PowerSeries.C (Torus.X v Ω m))= + coeff n (PowerSeries.C (Torus.X v Ω m)*F.val)) : + ∀n≤N,coeff n F.val=coeff n 1 := by + intro n hn + by_cases hn0 : n=0 + · subst n + simpa only [coeff_zero_eq_constantCoeff,map_one] using F.property.1 + · have hc : ∀m,coeff n F.val*Torus.X v Ω m=Torus.X v Ω m*coeff n F.val:=by + intro m + simpa only [coeff_mul_C,coeff_C_mul] using hf m n hn + rw [coeff_one,ite_eq_right hn0] + apply Finsupp.ext + intro r + by_cases hr : r=0 + · subst r + exact F.property.2 n 0 (positive_root_ne_zero C hC (Nat.pos_of_ne_zero hn0)) + · exact central_support_zero v Ω hv hΩ hnd (coeff n F.val) hc r hr + +lemma completed_adjoint_faithful_through + (hv : Function.Injective (fun z : ℤ=>(↑(v^z):K))) + (hΩ : ∀m,Ω m m=0) (hnd : ∀r≠0,∃m,Ω r m≠0) (hC : Function.Injective C) + (F : CompletedPositive v Ω C) (N : ℕ) + (hf : ∀m n,n≤N → coeff n (F.val*PowerSeries.C (Torus.X v Ω m)*invOfUnit F.val 1)= + coeff n (PowerSeries.C (Torus.X v Ω m))) : + ∀n≤N,coeff n F.val=coeff n 1 := by + apply completed_central_through v Ω C hv hΩ hnd hC F N + intro m n hn + have H:=FormalLog.mul_coeff_congr + (F.val*PowerSeries.C (Torus.X v Ω m)*invOfUnit F.val 1) + F.val (PowerSeries.C (Torus.X v Ω m)) F.val n + (fun j hj=>hf m j (hj.trans hn)) (fun _ _=>rfl) + simpa only [mul_assoc,invOfUnit_mul F.val 1 F.property.1,mul_one] using H + +lemma completed_adjoint_faithful + (hv : Function.Injective (fun z : ℤ=>(↑(v^z):K))) + (hΩ : ∀m,Ω m m=0) (hnd : ∀r≠0,∃m,Ω r m≠0) (hC : Function.Injective C) + (F : CompletedPositive v Ω C) + (hf : ∀m,F.val*PowerSeries.C (Torus.X v Ω m)*invOfUnit F.val 1= + PowerSeries.C (Torus.X v Ω m)) : F.val=1 := by + apply PowerSeries.ext + intro n + exact completed_adjoint_faithful_through v Ω C hv hΩ hnd hC F n + (fun m j _=>congrArg (coeff j) (hf m)) n le_rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/InfinityLine.lean b/lean/OAI/Combinatorics/Chromatic/Walls/InfinityLine.lean new file mode 100644 index 0000000000000000000000000000000000000000..c653d164c90af24717a856930aa518925aea7dba --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/InfinityLine.lean @@ -0,0 +1,194 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.InfinityCutCharts + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) +local instance infinityLineRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance infinityLineAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance infinityLineAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +def mutatedLineFactorPositive (a : ℝ) : CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc) := + ⟨mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H a, + mutatedLineFactor_constant Ω hΩ C coord pc e he L hdeg v k H a, + mutatedLineFactor_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a⟩ + +def actualInfinityLineUnit (a : ℝ) : (PowerSeries (HahnSeries ℤ (Torus LaurentRay.vUnit Ω)))ˣ := + infinityCompletedUnit Ω C coord hcoord pc LaurentRay.vUnit + (mutatedLineFactorPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a) + +lemma actualInfinityLine_nocut (a : ℝ) + (hp : (k+a • v) (e (simpleRoot C pc))≠0) + (x : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + innerHom (actualInfinityLineUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a) + (infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (decide (0<(k+a • v) (e (simpleRoot C pc)))) x)= + infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (decide (0<(k+a • v) (e (simpleRoot C pc)))) + (comparisonAction LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a) x) := by + classical + let pos:=decide (0<(k+a • v) (e (simpleRoot C pc))) + have hs:=cutSide_decide ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc) hp + unfold actualLineLetter + split + · next ha=> + simp only + let data:=lineRayData C e he L hdeg v k H a ha + let F:=chartZero LaurentRay.vUnit Ω C ((k+a • v).toAddMonoidHom.comp e) (simpleTotalTransport Ω C) + let G:=mutatedLineFactorPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a + have hf:=simple_fiber_bound Ω C coord hcoord pc e he S hS hcomp L hdeg + data.root data.degree data.degree_pos data.root_degree (k+a • v) data.generic pos hs + have hG : G.val=mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit + (orientPowerSeries (decide (v (e data.root)<0)) F.val) := by + simp only [G,mutatedLineFactorPositive,mutatedLineFactor,dite_eq_left ha,ite_eq_right hp] + rfl + have hbf:=simple_regrade_bound C coord hcoord Ω pc e he S hS hcomp L hdeg + data.root data.degree data.degree_pos data.root_degree (k+a • v) data.generic pos hs + have hbi:=simple_inverse_regrade_bound C coord hcoord Ω pc e he S hS hcomp L hdeg + data.root data.degree data.degree_pos data.root_degree (k+a • v) data.generic pos hs + exact mutation_infinity_oriented_square Ω hΩ C coord hcoord pc pos + (decide (v (e data.root)<0)) F hf hbf hbi G hG x + · next ha=> + have hg : (mutatedLineFactorPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a).val=1 := by + simp only [mutatedLineFactorPositive,mutatedLineFactor,dite_eq_right ha] + have hu:=infinityCompletedUnit_one Ω C coord hcoord pc LaurentRay.vUnit _ hg + change innerHom _ _=infinitySideHom _ _ _ _ _ _ (innerHom _ x) + rw [show actualInfinityLineUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a=1 from hu, + innerHom_one] + have h1 : boundedRationalUnit LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + 1 (RegradeBound.one _ _ _ _) (RegradeBound.one _ _ _ _)=1 := by + apply Units.ext + exact rationalRegrade_one _ _ _ _ _ _ _ _ + rw [h1,innerHom_one] +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) +local instance infinityLineCutRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance infinityLineCutAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance infinityLineCutAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma actualInfinityLine_cut_unit (a : ℝ) + (hp : (k+a • v) (e (simpleRoot C pc))=0) : + actualInfinityLineUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a= + if decide (v (e (simpleRoot C pc))<0) then + (completedPureUnit LaurentRay.vUnit Ω hΩ (-simpleRoot C pc))⁻¹ + else completedPureUnit LaurentRay.vUnit Ω hΩ (-simpleRoot C pc) := by + classical + have ha : ∃N,a∈lineEvents (realRootsThrough e C N) v k := + ⟨1,line_cut_event C pc e L hdeg v k H a hp⟩ + let P : CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc) := + ⟨normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) pc), + normalizedSimple_constant Ω _,by + rw [←simpleDatum_value Ω (mutatedRoots Ω C pc) pc] + exact WallUnitDatum.graded Ω _ (fun _=>True) _ (simpleDatum_allowed _ pc)⟩ + have hP : P.val=raySeries LaurentRay.vUnit Ω (-simpleRoot C pc) (shiftedElementary LaurentRay.vUnit 0) := by + rw [laurent_shiftedElementary_zero] + change normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) pc)=_ + rw [mutatedRoot_p] + rfl + have hU:=infinityCompletedUnit_pure Ω C coord hcoord pc LaurentRay.vUnit hΩ P hP + let G:=mutatedLineFactorPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a + have hG : G.val=orientPowerSeries (!(decide (v (e (simpleRoot C pc))<0))) P.val := by + simp only [G,mutatedLineFactorPositive,mutatedLineFactor,dite_eq_left ha,ite_eq_left hp,P] + cases hb : decide (v (e (simpleRoot C pc))<0) + · simp only [Bool.false_eq_true,ite_false] + change infinityCompletedUnit Ω C coord hcoord pc LaurentRay.vUnit G=_ + rw [show G=P from Subtype.ext (by simpa only [hb,Bool.not_false,orientPowerSeries,ite_true] using hG)] + exact hU + · simp only [ite_true] + change infinityCompletedUnit Ω C coord hcoord pc LaurentRay.vUnit G=_ + rw [infinityCompletedUnit_inverse Ω C coord hcoord pc LaurentRay.vUnit P G + (by simpa only [hb,Bool.not_true,orientPowerSeries,Bool.false_eq_true,ite_false] using hG),hU] + +include hdeg H in +lemma line_cut_offset_ne : k (e (simpleRoot C pc))≠0 := by + have hr : e (simpleRoot C pc)∈realRootsThrough e C 1 := by + exact realRoot_mem e C 1 1 le_rfl (simpleRoot C pc) (simpleRoot_degree C pc) + apply (H 1).avoid _ hr + rw [Submodule.span_singleton_eq_bot.mpr rfl,Submodule.mem_bot] + intro hz + have HH:=hdeg 1 (simpleRoot C pc) (simpleRoot_degree C pc) + rw [hz,map_zero] at HH + norm_num at HH + +include hdeg H in +lemma line_cut_direction_ne (a : ℝ) (hp : (k+a • v) (e (simpleRoot C pc))=0) : + v (e (simpleRoot C pc))≠0 := by + intro hz + have hp' : k (e (simpleRoot C pc))+a*v (e (simpleRoot C pc))=0:=hp + rw [hz,mul_zero,add_zero] at hp' + exact line_cut_offset_ne C pc e L hdeg v k H hp' +lemma actualInfinityLine_square (a : ℝ) + (x : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + innerHom (actualInfinityLineUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a) + (infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (AffineCut.beforeSide (k (e (simpleRoot C pc))) (v (e (simpleRoot C pc))) a) x)= + infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (AffineCut.afterSide (k (e (simpleRoot C pc))) (v (e (simpleRoot C pc))) a) + (comparisonAction LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a) x) := by + classical + by_cases hp : (k+a • v) (e (simpleRoot C pc))=0 + · have hs:=AffineCut.sides_at_zero (k (e (simpleRoot C pc))) (v (e (simpleRoot C pc))) a hp + rw [hs.1,hs.2,actualInfinityLine_cut_unit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a hp] + have ha : ∃N,a∈lineEvents (realRootsThrough e C N) v k := + ⟨1,line_cut_event C pc e L hdeg v k H a hp⟩ + have hv:=line_cut_direction_ne C pc e L hdeg v k H a hp + have hq : ∀n : ℕ,1-(↑(LaurentRay.vUnit^(-2:ℤ)):LaurentSeries ℚ)^(n+1)≠0 := by + intro n + rw [LaurentRay.vUnit_zpow] + exact UnitSelections.laurent_q_not_root n + unfold actualLineLetter + simp only [dite_eq_left ha,dite_eq_left hp] + by_cases hn : v (e (simpleRoot C pc))<0 + · have hn' : ¬0exact constantCoeff_one + | append s p ih=> + simp only [mutatedPathProduct,map_mul,mutatedLineProduct_constant,ih,one_mul] + +include hcoord hS hcomp in +lemma mutatedPathProduct_graded {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) (N : ℕ) : + SeriesGraded LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (mutatedPathProduct Ω hΩ C coord pc e he L hdeg p N) := by + induction p with + | nil=>exact SeriesGraded.one LaurentRay.vUnit Ω _ + | append s p ih=> + exact (mutatedLineProduct_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi N).mul LaurentRay.vUnit Ω _ ih + +def mutatedPathProductPositive {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) (N : ℕ) : + CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc) := + ⟨mutatedPathProduct Ω hΩ C coord pc e he L hdeg p N, + mutatedPathProduct_constant Ω hΩ C coord pc e he L hdeg p N, + mutatedPathProduct_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p N⟩ + +def actualInfinityPathProductUnit {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) (N : ℕ) : + (PowerSeries (HahnSeries ℤ (Torus LaurentRay.vUnit Ω)))ˣ := + infinityCompletedUnit Ω C coord hcoord pc LaurentRay.vUnit + (mutatedPathProductPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p N) + +lemma actualInfinityPathProductUnit_nil (a : Module.Dual ℝ E) (N : ℕ) : + actualInfinityPathProductUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg (.nil a) N=1 := + infinityCompletedUnit_one Ω C coord hcoord pc LaurentRay.vUnit _ rfl + +lemma actualInfinityPathProductUnit_append {a : Module.Dual ℝ E} (s : GenericLineSegment C e) + (p : GenericLinePath C e a (s.start C e)) (N : ℕ) : + actualInfinityPathProductUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg (.append s p) N= + actualInfinityLineProductUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi N* + actualInfinityPathProductUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p N := by + rw [actualInfinityLineProductUnit_eq] + exact infinityCompletedUnit_mul Ω C coord hcoord pc LaurentRay.vUnit _ _ _ rfl + +lemma actualInfinityPath_product_square {a b : Module.Dual ℝ E} + (p : GenericLinePath C e a b) (N : ℕ) (hN : 1≤N) + (x : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + innerHom (actualInfinityPathProductUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p N) + (infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (decide (0rw [actualInfinityPathProductUnit_nil,innerHom_one]; rfl + | append s p ih=> + rw [actualInfinityPathProductUnit_append,innerHom_mul,ih] + exact (actualInfinityLine_product_square Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi s.ordered (s.start_regular 1) (s.finish_regular 1) + N hN _).trans (by rw [actualPathWord,comparisonWordAction_append]; rfl) +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +lemma infinitySideHom_coeff_congr (pos : Bool) + (f g : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) + (d : ℕ) (h : coeff d f=coeff d g) : + coeff d (infinitySideHom v Ω hΩ k p pos f)=coeff d (infinitySideHom v Ω hΩ k p pos g) := by + cases pos + · change coeff d (PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + (PowerSeries.map (shearAction v _ _).toRingHom f))= + coeff d (PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + (PowerSeries.map (shearAction v _ _).toRingHom g)) + simp only [coeff_map,h] + · change coeff d (PowerSeries.map (expandFiberInfinity v Ω hΩ k p) f)= + coeff d (PowerSeries.map (expandFiberInfinity v Ω hΩ k p) g) + simp only [coeff_map,h] + +lemma infinity_embed_X (m : M) : + expandFiberInfinity v Ω hΩ k p (embed v Ω hΩ k p hp (Torus.X v Ω m))= + HahnSeries.single (-k m) (Torus.X v Ω m) := by + classical + apply HahnSeries.ext + funext z + ext n + rw [expandFiberInfinity_embed_coeff] + by_cases hm : m=n + · subst n + simp only [HahnSeries.coeff_single,Torus.X,Torus.monomial,Finsupp.single_eq_same] + split <;> simp_all + · simp only [Torus.X,Torus.monomial,Finsupp.single_eq_of_ne (Ne.symm hm),ite_self, + HahnSeries.coeff_single] + split <;> simp_all + +def infinityTestInput (pos : Bool) (m : M) : + PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)) := + (mutationSideAction v (complementOmega k Ω) (complementAlpha k p Ω) pos).symm + (PowerSeries.C (embed v Ω hΩ k p hp (Torus.X v Ω m))) + +lemma infinitySideHom_test (pos : Bool) (m : M) : + infinitySideHom v Ω hΩ k p pos (infinityTestInput v Ω hΩ k p hp pos m)= + PowerSeries.C (HahnSeries.single (-k m) (Torus.X v Ω m)) := by + change PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + (mutationSideAction v _ _ pos ((mutationSideAction v _ _ pos).symm _))=_ + rw [RingEquiv.apply_symm_apply,PowerSeries.map_C,infinity_embed_X] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/IsolatedPositivePlane.lean b/lean/OAI/Combinatorics/Chromatic/Walls/IsolatedPositivePlane.lean new file mode 100644 index 0000000000000000000000000000000000000000..4edd9118c15489b98a6b70085047a8c10ce6b740 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/IsolatedPositivePlane.lean @@ -0,0 +1,171 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RayIncomingIdentification +import OAI.Combinatorics.Chromatic.GradedAlgebra.TruncatedPrecisionClosure +import OAI.Combinatorics.Chromatic.Walls.OrderedRootReordering +import OAI.Combinatorics.Chromatic.Walls.DegreeIsolatedReordering +import OAI.Combinatorics.Chromatic.GradedAlgebra.Strict + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesSplit RootTruncation LaurentPrecision Filter WallUnits +noncomputable section +variable {M I A : Type*} [AddCommGroup M] [Fintype I] +variable (Ω : M →+M →+ℤ) (C : (I → ℤ) →+M) +variable (hΩ : ∀m,Ω m m=0) (L h : M →+ℝ) (V : AddSubmonoid M) (t : ℝ) +variable (hplane : ∀p∈V,∀q∈V,(Ω p q:ℝ)=t*(h p*L q-L p*h q)) +include hΩ hplane in +theorem isolated_positive_plane (n : ℕ) (s : List A) (active : A → Bool) (P : A → M → Prop) + (F : A → CompletedPositive LaurentRay.vUnit Ω C) + (hF : ∀a∈s,RootClosedThrough LaurentRay.vUnit Ω (if active a then n+1 else n) + (literalRootProducts Ω C (P a)) (F a).val) + (hadd : ∀a∈s,∀p q,P a p → P a q → P a (p+q)) + (hP : ∀a∈s,∀p,P a p → p∈V ∧ 0∀p q,P a p → P b q → 0 ≤ Ω p q)) + (hker : ∀a∈s,active a=false → ∀p,P a p → h p≠0) + (hsupport : ∀a∈s,SupportedOn LaurentRay.vUnit Ω (P a) (coeff (n+1) (F a).val)) : + RootClosedThrough LaurentRay.vUnit Ω (n+1) + (literalRootProducts Ω C (fun p=>p∈V ∧ h p=0)) + (zeroFactor (positiveProject LaurentRay.vUnit Ω h) (zeroProject LaurentRay.vUnit Ω h) + (s.map (fun a=>(F a).val)).prod) := by + classical + let g (a : A) (T : Finset (PrecisionTest (M:=M))) := + if ha : a∈s then rootApprox LaurentRay.vUnit Ω (hF a ha) T else 1 + have hg : ∀a∈s,∀T,g a T∈literalRootProducts Ω C (P a):=by + intro a ha T + dsimp [g]; rw [dite_eq_left ha] + exact rootApprox_mem LaurentRay.vUnit Ω (hF a ha) T + have hconv : ∀a∈s,SeriesConverges LaurentRay.vUnit Ω Filter.atTop + (fun T=>cut (if active a then n+1 else n) (g a T)) + (cut (if active a then n+1 else n) (F a).val):=by + intro a ha + have he : g a=rootApprox LaurentRay.vUnit Ω (hF a ha):=by + funext T; dsimp [g]; rw [dite_eq_left ha] + rw [he] + exact rootApprox_converges LaurentRay.vUnit Ω (hF a ha) + let k (a : A) (T : Finset (PrecisionTest (M:=M))) := + if active a then cut (n+1) (g a T) else patchTop n (g a T) (F a).val + have hkg : ∀a∈s,∀T,SeriesGraded LaurentRay.vUnit Ω C (k a T):=by + intro a ha T + dsimp [k] + split_ifs + · exact (literalRootProducts_graded Ω C (P a) (hg a ha T)).cut LaurentRay.vUnit Ω C (n+1) + · exact (literalRootProducts_graded Ω C (P a) (hg a ha T)).patchTop LaurentRay.vUnit Ω C n (F a).property.2 + have hkconv : ∀a∈s,SeriesConverges LaurentRay.vUnit Ω Filter.atTop (k a) (cut (n+1) (F a).val):=by + intro a ha + cases he : active a + · have H:=hconv a ha + simp only [he,Bool.false_eq_true,ite_false] at H + simpa only [k,he,Bool.false_eq_true,ite_false] using + H.patchTop LaurentRay.vUnit Ω Filter.atTop n + · simpa only [k,he,ite_true] using hconv a ha + have hcprod:=SeriesConverges.list_prod Ω C Filter.atTop s k + (fun a=>cut (n+1) (F a).val) hkconv hkg + (fun a ha=>SeriesGraded.cut LaurentRay.vUnit Ω C (n+1) (F a).property.2) + have hcmid:=hcprod.zero_middle LaurentRay.vUnit Ω C Filter.atTop h + (fun T=>SeriesGraded.list_prod Ω C s (fun a=>k a T) (fun a ha=>hkg a ha T)) + (SeriesGraded.list_prod Ω C s (fun a=>cut (n+1) (F a).val) + (fun a ha=>SeriesGraded.cut LaurentRay.vUnit Ω C (n+1) (F a).property.2)) + have hout : RootClosedThrough LaurentRay.vUnit Ω (n+1) + (literalRootProducts Ω C (fun p=>p∈V ∧ h p=0)) + (zeroFactor (positiveProject LaurentRay.vUnit Ω h) (zeroProject LaurentRay.vUnit Ω h) + (s.map (fun a=>cut (n+1) (F a).val)).prod):=by + apply RootClosedThrough.of_converges LaurentRay.vUnit Ω Filter.atTop + (hcmid.cut LaurentRay.vUnit Ω Filter.atTop (n+1)) + apply Eventually.of_forall + intro T + have hraw:=orderedPlane_zero_finite Ω C L h V hΩ t hplane + (literal_lists_ordered_product Ω C L V s P (fun a=>g a T) (fun a ha=>hg a ha T) hP hself hpair) + have he:=joint_middle_isolated_through LaurentRay.vUnit Ω h s (fun a=>k a T) (fun a=>g a T) n + (fun a ha=>by + dsimp [k]; split_ifs <;> + simpa using literalRootProducts_constant Ω C (P a) (hg a ha T)) + (fun a ha=>literalRootProducts_constant Ω C (P a) (hg a ha T)) + (fun a ha j hj=>by + dsimp [k]; split_ifs + · exact coeff_cut_of_le _ (by omega) + · exact patchTop_low n _ _ j hj) + (fun a ha m hm=>by + dsimp [k] + cases hn : active a + · simp only [Bool.false_eq_true,ite_false,coeff_patchTop,Nat.not_succ_le_self,ite_true,ite_false] + have hp : ¬P a m:=fun H=>hker a ha hn m H hm + rw [hsupport a ha m hp,literalRootProducts_strictSupport Ω C (P a) (hadd a ha) (hg a ha T) n m hp] + · simp only [ite_true,coeff_cut,le_refl,ite_true]) + change InPrecisionClosure LaurentRay.vUnit Ω _ _ + rw [he] + exact hraw.cut LaurentRay.vUnit Ω (n+1) + apply hout.congr LaurentRay.vUnit Ω + intro j hj + exact zero_coeff_congr _ _ _ _ j (fun z hz=>product_coeff_congr _ _ s z + (fun a ha i hi=>coeff_cut_of_le _ (hi.trans (hz.trans hj)))) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +lemma OnPositiveRay.symm {r p : M} (H : OnPositiveRay r p) : OnPositiveRay p r := by + obtain ⟨a,b,ha,hb,he⟩:=H + exact ⟨b,a,hb,ha,he.symm⟩ +lemma OnPositiveRay.trans {r p q : M} (H : OnPositiveRay r p) (K : OnPositiveRay p q) : + OnPositiveRay r q := by + obtain ⟨a,b,ha,hb,he⟩:=H + obtain ⟨c,d,hc,hd,hf⟩:=K + refine ⟨a*c,b*d,Nat.mul_pos ha hc,Nat.mul_pos hb hd,?_⟩ + calc + (a*c) • q=a • (c • q):=by rw [smul_smul] + _=a • (d • p):=by rw [hf] + _=d • (a • p):=by rw [smul_smul,smul_smul,Nat.mul_comm] + _=d • (b • r):=by rw [he] + _=(b*d) • r:=by rw [smul_smul,Nat.mul_comm] +lemma OnPositiveRay.eq_pred {r p : M} (H : OnPositiveRay r p) : + OnPositiveRay r=OnPositiveRay p := by + funext q + apply propext + exact ⟨fun h=>H.symm.trans h,fun h=>H.trans h⟩ +lemma OnPositiveRay.mem_submodule (e : M→+E) (V : Submodule ℝ E) + {r p : M} (H : OnPositiveRay r p) (hr : e r∈V) : e p∈V := by + obtain ⟨a,b,ha,hb,he⟩:=H + have H:=congrArg e he + simp only [map_nsmul,←Nat.cast_smul_eq_nsmul ℝ] at H + have hA : (a:ℝ)≠0:=by exact_mod_cast (Nat.ne_of_gt ha) + exact (V.smul_mem_iff hA).mp (H.symm ▸ V.smul_mem (b:ℝ) hr) +variable (Ω : M→+M→+ℤ) +lemma OnPositiveRay.pair_nonneg {r s p q : M} (hp : OnPositiveRay r p) (hq : OnPositiveRay s q) + (h : 0≤Ω r s) : 0≤Ω p q := by + have hright:=hq.incomingSigns Ω r + have hleft:=hp.eval (incomingCovector Ω q) + by_contra hn + have hn' : incomingCovector Ω q p < 0:=by change (Ω p q:ℝ)<0; exact_mod_cast (lt_of_not_ge hn) + have H:=hright.2.2.mpr (hleft.2.2.mp hn') + change (Ω r s:ℝ)<0 at H + have h' : (0:ℝ)≤Ω r s:=by exact_mod_cast h + linarith +lemma OnPositiveRay.pair_zero {r p q : M} (hp : OnPositiveRay r p) (hq : OnPositiveRay r q) + (hΩ : Ω r r=0) : Ω p q=0 := by + have hright:=hq.incomingSigns Ω r + have hleft:=hp.eval (incomingCovector Ω q) + have H : incomingCovector Ω r r=0:=by change (Ω r r:ℝ)=0; rw [hΩ,Int.cast_zero] + have HH:=hleft.2.1.mpr (hright.2.1.mp H) + change (Ω p q:ℝ)=0 at HH + exact_mod_cast HH +lemma literalRootProducts_allowed_mono (C : (I→ℤ)→+M) (P Q : M→Prop) + (H : ∀n,0p∈V)) : + (∀m,(∀p∈V,0≤Ω p m)→IntegralPositive Ω + (F*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit F 1)) ∧ + (∀m,(∀p∈V,Ω p m≤0)→IntegralPositive Ω + (invOfUnit F 1*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*F)) := by + classical + have hconstant:=literalRootProducts_constant Ω C (fun p=>p∈V) hF + obtain ⟨l,hl,rfl⟩:=hF + let p : Fin l.length→M:=fun i=>(l.get i).root + let w : Fin l.length→ℕ:=fun i=>(l.get i).degree + let c : Fin l.length→ℝ:=fun i=>w i + let κ : Fin l.length→ℤ:=fun i=>(l.get i).parameter + let ε : Fin l.length→Bool:=fun i=>decide ((l.get i).kind=0) + have hall : ∀i,(l.get i).Allowed C (fun p=>p∈V):=fun i=>hl _ (List.get_mem _ _) + let : Fact (∀i,0(hall i).1⟩ + have hc : ∀i,0by + change 0<((l.get i).degree:ℝ) + exact_mod_cast (hall i).1 + have hp : ∀i j,(Ω (p i) (p j):ℝ)=(0:ℝ)*((0:ℝ)*c j-c i*0):=by + intro i j + rw [hV _ (hall i).2.2 _ (hall j).2.2] + simp + have ho : (List.finRange l.length).Pairwise (fun i j=>0≤Ω (p i) (p j)):=by + apply List.pairwise_of_forall + intro i j + rw [hV _ (hall i).2.2 _ (hall j).2.2] + have hh : ∀d,(0 : M→+ℝ) (rootSum p d)=slopeValue c (fun _=>0) 0 d:=by + intro d + simp [slopeValue,mass] + have Hprod:=listLiteral_product Ω l + change ((List.finRange l.length).map (literalAxis κ ε Ω (rootSum p) w)).prod=_ at Hprod + have Hzero : PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω (0:M→+ℝ)) + (zeroProject LaurentRay.vUnit Ω (0:M→+ℝ)) + (((List.finRange l.length).map (literalAxis κ ε Ω (rootSum p) w)).prod)= + (l.map (WallUnitDatum.value Ω)).prod := by + rw [Hprod,zeroFactor_zero _ _ _ hconstant] + constructor + · intro m hm + have H:=geometric_zero_adjoint_positive Ω hΩ p κ ε w c (fun _=>0) hc 0 hp + (List.finRange l.length) (List.nodup_finRange _) (List.toFinset_finRange _) ho + (0:M→+ℝ) 0 hh m (fun d hd=>hm _ (rootSum_mem p V (fun i=>(hall i).2.2) d)) + dsimp only at H + rwa [Hzero] at H + · intro m hm + have H:=geometric_zero_inverse_adjoint_positive Ω hΩ p κ ε w c (fun _=>0) hc 0 hp + (List.finRange l.length) (List.nodup_finRange _) (List.toFinset_finRange _) ho + (0:M→+ℝ) 0 hh m (fun d hd=>hm _ (rootSum_mem p V (fun i=>(hall i).2.2) d)) + dsimp only at H + rwa [Hzero] at H +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries LaurentPrecision Filter WallUnits +noncomputable section +variable {M J ι : Type*} [AddCommGroup M] [Fintype J] +variable (Ω : M→+M→+ℤ) (C : (J→ℤ)→+M) (l : Filter ι) +lemma SeriesConverges.inverse_adjoint + {f : ι→PowerSeries (Torus LaurentRay.vUnit Ω)} {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hf : SeriesConverges LaurentRay.vUnit Ω l f F) + (hfg : ∀i,SeriesGraded LaurentRay.vUnit Ω C (f i)) + (hF : SeriesGraded LaurentRay.vUnit Ω C F) (x : Torus LaurentRay.vUnit Ω) : + SeriesConverges LaurentRay.vUnit Ω l (fun i=>invOfUnit (f i) 1*PowerSeries.C x*f i) + (invOfUnit F 1*PowerSeries.C x*F) := by + have H:=hf.inverse LaurentRay.vUnit Ω C l hfg hF + have hi : ∀i,SeriesGraded LaurentRay.vUnit Ω C (invOfUnit (f i) 1):= + fun i=>(hfg i).inverse LaurentRay.vUnit Ω C + have hI:=hF.inverse LaurentRay.vUnit Ω C + exact (H.mul_C LaurentRay.vUnit Ω C l hi hI x).mul_of_support LaurentRay.vUnit Ω l hf + (fun n=>sumSupport (rootDegree_finite C n).toFinset x.support) + (fun n=>(rootDegree_finite C n).toFinset) + (fun i n=>(hi i).mul_C_support LaurentRay.vUnit Ω C x n) + (fun i n=>rootGrade_support LaurentRay.vUnit Ω C n _ (hfg i n)) + (fun n=>hI.mul_C_support LaurentRay.vUnit Ω C x n) + (fun n=>rootGrade_support LaurentRay.vUnit Ω C n _ (hF n)) + +variable (V : AddSubmonoid M) (hΩ : ∀p,Ω p p=0) (hV : ∀p∈V,∀q∈V,Ω p q=0) +include hΩ hV in + +theorem closed_isotropic_adjoint {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : InPrecisionClosure LaurentRay.vUnit Ω (literalRootProducts Ω C (fun p=>p∈V)) F) : + (∀m,(∀p∈V,0≤Ω p m)→IntegralPositive Ω + (F*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit F 1)) ∧ + (∀m,(∀p∈V,Ω p m≤0)→IntegralPositive Ω + (invOfUnit F 1*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*F)) := by + let f:=precisionApprox LaurentRay.vUnit Ω hF + have hf:=precisionApprox_converges LaurentRay.vUnit Ω hF + have hg : ∀T,SeriesGraded LaurentRay.vUnit Ω C (f T):=fun T=> + literalRootProducts_graded Ω C (fun p=>p∈V) (precisionApprox_mem LaurentRay.vUnit Ω hF T) + have hFG:=hF.graded Ω C (fun G hG=>literalRootProducts_graded Ω C (fun p=>p∈V) hG) + have hpositive : ∀T, + (∀m,(∀p∈V,0≤Ω p m)→IntegralPositive Ω + (f T*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit (f T) 1)) ∧ + (∀m,(∀p∈V,Ω p m≤0)→IntegralPositive Ω + (invOfUnit (f T) 1*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*f T)):=fun T=> + literal_isotropic_adjoint Ω C V hΩ hV (precisionApprox_mem LaurentRay.vUnit Ω hF T) + constructor + · intro m hm + exact IntegralPositive.of_converges Ω Filter.atTop + (hf.adjoint LaurentRay.vUnit Ω C Filter.atTop hg hFG _) + (Eventually.of_forall (fun T=>(hpositive T).1 m hm)) + · intro m hm + exact IntegralPositive.of_converges Ω Filter.atTop + (hf.inverse_adjoint Ω C Filter.atTop hg hFG _) + (Eventually.of_forall (fun T=>(hpositive T).2 m hm)) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits LaurentPrecision +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +lemma inPrecisionClosure_of_cuts (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) + (A : Set (PowerSeries (Torus v Ω))) (F : PowerSeries (Torus v Ω)) + (hF : ∀N,RootClosedThrough v Ω N A F) : InPrecisionClosure v Ω A F := by + classical + intro T + let N:=T.sup (fun t=>t.1) + obtain ⟨G,hG,H⟩:=rootClosedThrough_approx_exists v Ω (hF N) T + refine ⟨G,hG,?_⟩ + intro t ht + have hn : t.1≤N:=Finset.le_sup (f:=fun t : PrecisionTest (M:=M)=>t.1) ht + have hh:=H t ht + simpa only [RootTruncation.coeff_cut,ite_eq_left hn] using hh + +def positiveRayWithZero (r : M) : AddSubmonoid M where + carrier:={m | m=0 ∨ OnPositiveRay r m} + zero_mem':=Or.inl rfl + add_mem':=by + intro a b ha hb + rcases ha with rfl|ha + · simpa using hb + rcases hb with rfl|hb + · simpa using Or.inr ha + · exact Or.inr (ha.add hb) +variable (Ω : M →+ M →+ ℤ) +lemma positiveRayWithZero_isotropic (hΩ : ∀r,Ω r r=0) (r : M) : + ∀p∈positiveRayWithZero r,∀q∈positiveRayWithZero r,Ω p q=0 := by + intro p hp q hq + rcases hp with rfl|hp + · simp + rcases hq with rfl|hq + · simp + exact hp.pair_zero Ω hq (hΩ r) +variable (C : (I → ℤ) →+ M) +lemma closed_ray_crossing (hΩ : ∀r,Ω r r=0) (r : M) + {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : InPrecisionClosure LaurentRay.vUnit Ω (literalRootProducts Ω C (OnPositiveRay r)) F) : + (∀m,0≤Ω r m → IntegralPositive Ω + (F*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit F 1)) ∧ + (∀m,Ω r m≤0 → IntegralPositive Ω + (invOfUnit F 1*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*F)) := by + have hFF : InPrecisionClosure LaurentRay.vUnit Ω + (literalRootProducts Ω C (fun p=>p∈positiveRayWithZero r)) F:= + hF.mono LaurentRay.vUnit Ω (literalRootProducts_allowed_mono Ω C _ _ (fun n hn p hr hp=>Or.inr hp)) + have H:=closed_isotropic_adjoint Ω C (positiveRayWithZero r) hΩ + (positiveRayWithZero_isotropic Ω hΩ r) hFF + constructor + · intro m hm + apply H.1 m + intro p hp + rcases hp with rfl|hp + · simp + exact hp.pair_nonneg Ω (OnPositiveRay.refl m) hm + · intro m hm + apply H.2 m + intro p hp + rcases hp with rfl|hp + · simp + have hh:=hp.eval (incomingCovector Ω m) + by_contra hx + have hp0 : (0:ℝ)<Ω p m:=by exact_mod_cast (lt_of_not_ge hx) + have hr0:=hh.1.mp hp0 + change (0:ℝ)<Ω r m at hr0 + have hr1 : (Ω r m:ℝ)≤0:=by exact_mod_cast hm + linarith +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in +theorem global_ray_closure (F : CompletedPositive LaurentRay.vUnit Ω C) + (incoming : PositiveIncomingPrescription Ω C F) (r : M) (d : ℕ) + (hd : 0True)) (r : M) (d : ℕ) + (hd : 0simp + | add f g hf hg=> + simp only [map_add,HahnSeries.coeff_add,Finsupp.add_apply,hf,hg] + split_ifs <;> simp + | single l a=> + change ((expandFiber v Ω hΩ k p (embed v Ω hΩ k p hp (Torus.monomial v Ω l a))).coeff n) m=_ + rw [expansion_embed_monomial,HahnSeries.coeff_single] + by_cases hl : l=m + · subst l; split_ifs <;> rfl + · by_cases hn : n=k l + · rw [ite_eq_left hn] + simp [Torus.monomial,Finsupp.single_eq_of_ne (Ne.symm hl)] + · rw [ite_eq_right hn] + simp [Finsupp.single_eq_of_ne (Ne.symm hl)] +lemma hahn_power_negative (f : PowerSeries (Torus v Ω)) (n : ℤ) (hn : n<0) : + (HahnSeries.ofPowerSeries ℤ (Torus v Ω) f).coeff n=0 := by + rw [HahnSeries.ofPowerSeries_apply] + apply HahnSeries.embDomain_of_notMem_range + rintro ⟨a,ha⟩ + change (a:ℤ)=n at ha + omega +variable (δ : M →+ ℤ) (B : ℕ) +lemma regrade_eval_vanish (f : PowerSeries (Torus v Ω)) (d : ℕ) (m : M) + (hz : ∀n,PowerSeries.coeff n f m=0) : PowerSeries.coeff d (regrade v Ω δ B f) m=0 := by + rw [regrade_coeff_eval] + simp [hz] +lemma regrade_expand_nat {f : PowerSeries (Torus v Ω)} + (hf : BiSupported v Ω δ k f) (hb : RegradeBound v Ω δ B f) (d e : ℕ) (m : M) : + ((expandFiber v Ω hΩ k p (embed v Ω hΩ k p hp (PowerSeries.coeff d (regrade v Ω δ B f)))).coeff (e:ℤ)) m= + PowerSeries.coeff e (PowerSeries.coeff d (biRegrade v Ω δ k f)) m := by + rw [expand_embed_coeff,biRegrade_coeff,biHomogenize_coeff] + by_cases hδ : 0≤δ m + · by_cases hk : 0≤k m + · have hd : ((δ m).toNat:ℤ)=δ m:=Int.toNat_of_nonneg hδ + have he : ((k m).toNat:ℤ)=k m:=Int.toNat_of_nonneg hk + by_cases hD : d=(δ m).toNat + · by_cases hE : e=(k m).toNat + · have Hk : (e:ℤ)=k m:=by omega + rw [ite_eq_left Hk,ite_eq_left ⟨hD,hE⟩] + have Hτ : FullHomogeneous v Ω (δ+k) f:=by + intro n m hm + exact (hf n m hm).2.2.symm + simpa only [hD] using (regrade_read v Ω δ B (δ+k) hb Hτ (d+e) m (by + change δ m+k m=((d+e:ℕ):ℤ) + rw [Nat.cast_add] + omega)) + · have Hk : (e:ℤ)≠k m:=by omega + rw [ite_eq_right Hk,ite_eq_right (by tauto)] + · rw [ite_eq_right (by tauto : ¬(d=(δ m).toNat ∧ e=(k m).toNat))] + rw [regrade_coeff_eval,ite_eq_right hD] + split_ifs <;> rfl + · have hz : ∀j,PowerSeries.coeff j f m=0:=by + intro j; by_contra H; exact hk (hf j m H).2.1 + rw [regrade_eval_vanish v Ω δ B f d m hz,hz] + split_ifs <;> rfl + · have hz : ∀j,PowerSeries.coeff j f m=0:=by + intro j; by_contra H; exact hδ (hf j m H).1 + rw [regrade_eval_vanish v Ω δ B f d m hz,hz] + split_ifs <;> rfl +lemma rational_old_square {f : PowerSeries (Torus v Ω)} + (hf : BiSupported v Ω δ k f) (hb : RegradeBound v Ω δ B f) : + PowerSeries.map (expandFiber v Ω hΩ k p) + (rationalRegrade v Ω hΩ k p hp δ B f)=oldLaurent v Ω δ k f := by + apply PowerSeries.ext + intro d + apply HahnSeries.ext + funext n + apply Finsupp.ext + intro m + simp only [rationalRegrade,oldLaurent,PowerSeries.coeff_map] + rcases le_or_gt 0 n with hn|hn + · lift n to ℕ using hn with e he + rw [HahnSeries.ofPowerSeries_apply_coeff] + exact regrade_expand_nat v Ω hΩ k p hp δ B hf hb d e m + · rw [hahn_power_negative v Ω _ n hn,expand_embed_coeff] + by_cases he : n=k m + · rw [ite_eq_left he] + apply regrade_eval_vanish + intro j + by_contra H + have HH:=(hf j m H).2.1 + omega + · rw [ite_eq_right he] + rfl +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentCompletionFaithful.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentCompletionFaithful.lean new file mode 100644 index 0000000000000000000000000000000000000000..e268de3a1f070f3134feabaf8526736d9e9fba2b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentCompletionFaithful.lean @@ -0,0 +1,159 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.InfinityFiniteLoop + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {K M I : Type*} [Field K] [AddCommGroup M] [Fintype I] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (δ κ η : M →+ ℤ) (B : ℕ) +local instance laurentCompletionFaithfulRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance laurentCompletionFaithfulAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance laurentCompletionFaithfulAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance laurentCompletionFaithfulNonUnitalSemiring : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance laurentCompletionFaithfulNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +lemma laurentRegrade_central_faithful + (hv : Function.Injective (fun z : ℤ=>(↑(v^z):K))) + (hΩ : ∀m,Ω m m=0) (hnd : ∀r≠0,∃m,Ω r m≠0) (hC : Function.Injective C) + (F : CompletedPositive v Ω C) (hF : LaurentBounded v Ω δ κ B F.val) + (hhom : FullHomogeneous v Ω η F.val) (z : M → ℤ) + (hcentral : ∀m,laurentRegrade v Ω δ κ B F.val hF* + PowerSeries.C (HahnSeries.single (z m) (Torus.X v Ω m))= + PowerSeries.C (HahnSeries.single (z m) (Torus.X v Ω m))* + laurentRegrade v Ω δ κ B F.val hF) : F.val=1 := by + have hcoeff (d : ℕ) (w : ℤ) : + ∀m,((coeff d (laurentRegrade v Ω δ κ B F.val hF)).coeff w)*Torus.X v Ω m= + Torus.X v Ω m*((coeff d (laurentRegrade v Ω δ κ B F.val hF)).coeff w) := by + intro m + have H:=congrArg (fun f : PowerSeries (HahnSeries ℤ (Torus v Ω))=> + (coeff d f).coeff (w+z m)) (hcentral m) + rw [coeff_mul_C,coeff_C_mul] at H + rw [HahnSeries.coeff_mul_single_add,HahnSeries.coeff_single_mul_add] at H + exact H + apply PowerSeries.ext + intro n + by_cases hn : n=0 + · subst n + simpa only [coeff_zero_eq_constantCoeff,map_one] using F.property.1 + · rw [coeff_one,ite_eq_right hn] + ext r + by_cases hr : r=0 + · subst r + exact F.property.2 n 0 (positive_root_ne_zero C hC (Nat.pos_of_ne_zero hn)) + · by_contra hh + have hd:=(hF n r hh).1 + have H:=central_support_zero v Ω hv hΩ hnd + ((coeff (δ r).toNat (laurentRegrade v Ω δ κ B F.val hF)).coeff (κ r)) + (hcoeff (δ r).toNat (κ r)) r hr + rw [laurentRegrade_read v Ω δ κ η B hF hhom n _ (κ r) r (hhom n r hh) + (Int.toNat_of_nonneg hd).symm rfl] at H + exact hh H +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.WallUnits.LaurentRay +lemma vUnit_zpow_injective : Function.Injective (fun z : ℤ=>(↑(vUnit^z):LaurentSeries ℚ)) := by + intro a b hab + change (↑(vUnit^a):LaurentSeries ℚ)=↑(vUnit^b) at hab + rw [vUnit_zpow,vUnit_zpow] at hab + have H:=congrArg (fun f : LaurentSeries ℚ=>f.coeff (-a)) hab + by_contra hh + simp [hh] at H +end ElementaryPositivity.WallUnits.LaurentRay +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +lemma laurent_completed_adjoint_faithful + (hΩ : ∀m,Ω m m=0) (hnd : ∀r≠0,∃m,Ω r m≠0) (hC : Function.Injective C) + (F : CompletedPositive LaurentRay.vUnit Ω C) + (hf : ∀m,F.val*PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)*invOfUnit F.val 1= + PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)) : F.val=1 := + completed_adjoint_faithful LaurentRay.vUnit Ω C LaurentRay.vUnit_zpow_injective hΩ hnd hC F hf +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance : NonUnitalSemiring (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus LaurentRay.vUnit Ω) := + (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalNonAssocSemiring + +lemma mutatedPathCompleted_loop_row_commute {a : Module.Dual ℝ E} (p : GenericLinePath C e a a) + (d : ℕ) (z : ℤ) (m : M) : + ((coeff d (mutatedLaurent Ω C coord hcoord pc LaurentRay.vUnit + (mutatedPathCompletedPositive Ω hΩ C coord pc e he L hdeg hcoord S hS hcomp p))).coeff z)* + Torus.X LaurentRay.vUnit Ω m= + Torus.X LaurentRay.vUnit Ω m* + ((coeff d (mutatedLaurent Ω C coord hcoord pc LaurentRay.vUnit + (mutatedPathCompletedPositive Ω hΩ C coord pc e he L hdeg hcoord S hS hcomp p))).coeff z) := by + let D:=(z+(mutationSize Ω C pc+1:ℤ)*(d:ℤ)).toNat + let N:=max 1 ((mutationSize Ω C pc+1)*max d D) + have hN : 1≤N:=le_max_left _ _ + have hdN : (mutationSize Ω C pc+1)*d≤N:= + (Nat.mul_le_mul_left _ (le_max_left d D)).trans (le_max_right _ _) + have hDN : (mutationSize Ω C pc+1)*D≤N:= + (Nat.mul_le_mul_left _ (le_max_right d D)).trans (le_max_right _ _) + let F:=mutatedPathCompletedPositive Ω hΩ C coord pc e he L hdeg hcoord S hS hcomp p + let G:=mutatedPathProductPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p N + have hc:=mutatedLaurent_coeff_congr Ω C coord hcoord pc LaurentRay.vUnit F G d z + (mutatedPathCompletion_coeff Ω hΩ C coord pc e he L hdeg p D N hN hDN) + have HH:=actualInfinityPath_loop_row_commute Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p d N hN hdN z m + calc + _ = ((coeff d (mutatedLaurent Ω C coord hcoord pc LaurentRay.vUnit G)).coeff z)* + Torus.X LaurentRay.vUnit Ω m := congrArg (fun t=>t*Torus.X LaurentRay.vUnit Ω m) hc + _ = Torus.X LaurentRay.vUnit Ω m* + ((coeff d (mutatedLaurent Ω C coord hcoord pc LaurentRay.vUnit G)).coeff z) := HH + _ = _ := congrArg (fun t=>Torus.X LaurentRay.vUnit Ω m*t) hc.symm + +include hcoord hS hcomp in +lemma mutatedPathCompletion_loop (hnd : ∀r≠0,∃m,Ω r m≠0) + {a : Module.Dual ℝ E} (p : GenericLinePath C e a a) : + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p=1 := by + let F:=mutatedPathCompletedPositive Ω hΩ C coord pc e he L hdeg hcoord S hS hcomp p + have hC : Function.Injective (mutatedRoots Ω C pc) := + Function.LeftInverse.injective (mutatedCoordinates_retraction Ω C coord hcoord pc) + refine laurentRegrade_central_faithful LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (nonpDegree (mutatedCoordinates Ω C coord pc) pc) (-pureDegree coord pc) + (rootOrder (mutatedCoordinates Ω C coord pc)) (mutationSize Ω C pc) + LaurentRay.vUnit_zpow_injective hΩ hnd hC F + (mutated_series_laurentBounded Ω C coord hcoord pc LaurentRay.vUnit F.property.2) + (completed_full_homogeneous LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) (mutatedCoordinates_retraction Ω C coord hcoord pc) F) + (fun m=> -pureDegree coord pc m) ?_ + intro m + apply PowerSeries.ext + intro d + apply HahnSeries.ext + funext z + rw [coeff_mul_C,coeff_C_mul,HahnSeries.coeff_mul_single,HahnSeries.coeff_single_mul] + exact mutatedPathCompleted_loop_row_commute Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p d _ m +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentFiniteDecorations.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentFiniteDecorations.lean new file mode 100644 index 0000000000000000000000000000000000000000..5aa0bdca21e2f907f1fb5ce24ec3bc252b9bb476 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentFiniteDecorations.lean @@ -0,0 +1,99 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RootProducts + +namespace OAI + +section +namespace ElementaryPositivity.LaurentPositive +open WallUnits +open scoped BigOperators +open Classical +noncomputable section + +def multiplicity (w:LaurentSeries ℚ) (h:Positive w) (j:ℤ) : ℕ:=(h j).choose +lemma multiplicity_cast (w:LaurentSeries ℚ) (h:Positive w) (j:ℤ) : + (multiplicity w h j:ℚ)=w.coeff j:=(h j).choose_spec.symm +lemma coeff_nonneg (w:LaurentSeries ℚ) (h:Positive w) (j:ℤ) : 0≤w.coeff j:=by + rw [←multiplicity_cast w h j] + exact Nat.cast_nonneg _ + +lemma coeff_mul_natCast (w:LaurentSeries ℚ) (k:ℕ) (j:ℤ) : + (w*k).coeff j=w.coeff j*k := by + calc + _ = (k • w).coeff j:=by rw [nsmul_eq_mul,mul_comm] + _ = k • w.coeff j:=congrFun HahnSeries.coeff_nsmul j + _ = _:=by simp only [nsmul_eq_mul,mul_comm] + +lemma support_of_positive_sum {L:Type*} [Fintype L] (w:L → LaurentSeries ℚ) + (hw:∀l,Positive (w l)) (c:L → ℕ) (hc:∀l,0mul_nonneg (coeff_nonneg _ (hw i) j) (Nat.cast_nonneg _) + have hle:=Finset.single_le_sum (f:=fun i=>(w i).coeff j*(c i:ℚ)) + (fun i _=>hnon i) (Finset.mem_univ l) + rw [Hz] at hle + have hp:0<(w l).coeff j:=lt_of_le_of_ne (coeff_nonneg _ (hw l) j) (Ne.symm hj) + have hcp:0<(c l:ℚ):=Nat.cast_pos.mpr (hc l) + exact (not_lt_of_ge hle) (mul_pos hp hcp) + +lemma exponent_injective (M:ℕ) : Function.Injective (fun k:Fin (M+1)=>(M:ℤ)-2*(k.val:ℤ)) := by + intro k l h + change (M:ℤ)-2*(k.val:ℤ)=(M:ℤ)-2*(l.val:ℤ) at h + apply Fin.ext + omega + +lemma finite_expansion (w:LaurentSeries ℚ) (hw:Positive w) (M:ℕ) + (hs:∀j,w.coeff j≠0 → ∃k:Fin (M+1),j=(M:ℤ)-2*(k.val:ℤ)) : + w=∑k:Fin (M+1),HahnSeries.single ((M:ℤ)-2*k.val) + (multiplicity w hw ((M:ℤ)-2*k.val):ℚ) := by + ext j + rw [HahnSeries.coeff_sum] + by_cases he:∃k:Fin (M+1),j=(M:ℤ)-2*(k.val:ℤ) + · obtain ⟨k,rfl⟩:=he + rw [Finset.sum_eq_single k] + · rw [HahnSeries.coeff_single,ite_eq_left rfl,multiplicity_cast] + · intro l hl hlk + exact HahnSeries.coeff_single_of_ne (fun H=>hlk ((exponent_injective M) H.symm)) + · simp + · rw [not_exists] at he + have hz:w.coeff j=0:=by + by_contra hn + obtain ⟨k,hk⟩:=hs j hn + exact he k hk + rw [hz] + apply Eq.symm + apply Finset.sum_eq_zero + intro k hk + exact HahnSeries.coeff_single_of_ne (he k) + +abbrev Decoration (w:LaurentSeries ℚ) (hw:Positive w) (M:ℕ) := + Σk:Fin (M+1),Fin (multiplicity w hw ((M:ℤ)-2*k.val)) + +lemma decoration_expansion (w:LaurentSeries ℚ) (hw:Positive w) (M:ℕ) + (hs:∀j,w.coeff j≠0 → ∃k:Fin (M+1),j=(M:ℤ)-2*(k.val:ℤ)) : + w=∑d:Decoration w hw M,(↑(LaurentRay.vUnit^(2*(d.1.val:ℤ)-(M:ℤ))):LaurentSeries ℚ) := by + calc + w = ∑k:Fin (M+1),HahnSeries.single ((M:ℤ)-2*k.val) + (multiplicity w hw ((M:ℤ)-2*k.val):ℚ) := finite_expansion w hw M hs + _ = _ := ?_ + unfold Decoration + rw [Fintype.sum_sigma] + apply Finset.sum_congr rfl + intro k hk + simp only [LaurentRay.vUnit_zpow,Finset.sum_const,Finset.card_univ,Fintype.card_fin] + have he:-(2*(k.val:ℤ)-(M:ℤ))=(M:ℤ)-2*k.val:=by omega + rw [he] + ext j + simp only [HahnSeries.coeff_nsmul,HahnSeries.coeff_single] + by_cases hj:j=(M:ℤ)-2*k.val <;> simp [hj,nsmul_eq_mul] +end +end ElementaryPositivity.LaurentPositive + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentGradedFibers.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentGradedFibers.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0839a4ce1ad563e14861ee1eb292873698153ee --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentGradedFibers.lean @@ -0,0 +1,44 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.HNTorusFactor +import OAI.Combinatorics.Chromatic.Witness.WitnessTransport + +namespace OAI + +section +namespace ElementaryPositivity.LaurentPositive +open WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {A B:Type*} [Fintype A] [Fintype B] + +lemma coefficient_energy_sum (M:ℕ) (E:A → ℕ) (k:ℕ) : + (∑a,(↑(LaurentRay.vUnit^(2*(E a:ℤ)-(M:ℤ))):LaurentSeries ℚ)).coeff ((M:ℤ)-2*(k:ℤ))= + (Fintype.card {a // E a=k}:ℚ) := by + rw [HahnSeries.coeff_sum] + simp only [LaurentRay.vUnit_zpow,HahnSeries.coeff_single] + have he:∀a,((M:ℤ)-2*(k:ℤ)= -(2*(E a:ℤ)-(M:ℤ))) ↔ E a=k:=by intro a; omega + simp_rw [he] + rw [←Finset.sum_filter] + simp [Fintype.card_subtype] + +lemma fiber_card_of_energy_sum (M:ℕ) (EA:A → ℕ) (EB:B → ℕ) + (h:(∑a,(↑(LaurentRay.vUnit^(2*(EA a:ℤ)-(M:ℤ))):LaurentSeries ℚ))= + ∑b,(↑(LaurentRay.vUnit^(2*(EB b:ℤ)-(M:ℤ))):LaurentSeries ℚ)) (k:ℕ) : + Fintype.card {a // EA a=k}=Fintype.card {b // EB b=k} := by + have H:=congrArg (fun w:LaurentSeries ℚ=>w.coeff ((M:ℤ)-2*(k:ℤ))) h + rw [coefficient_energy_sum,coefficient_energy_sum] at H + exact_mod_cast H + +def gradedEquivOfEnergySum (M:ℕ) (EA:A → ℕ) (EB:B → ℕ) + (h:(∑a,(↑(LaurentRay.vUnit^(2*(EA a:ℤ)-(M:ℤ))):LaurentSeries ℚ))= + ∑b,(↑(LaurentRay.vUnit^(2*(EB b:ℤ)-(M:ℤ))):LaurentSeries ℚ)) : + ExactMasks.GradedEquiv EA EB := + ⟨Equiv.ofFiberEquiv (fun k=>Fintype.equivOfCardEq (fiber_card_of_energy_sum M EA EB h k)), + Equiv.ofFiberEquiv_map _⟩ +end +end ElementaryPositivity.LaurentPositive + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentLinearNaturality.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentLinearNaturality.lean new file mode 100644 index 0000000000000000000000000000000000000000..05757f1ae6d97ba913df9204f7b5fdeba519015f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentLinearNaturality.lean @@ -0,0 +1,28 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.BothTaylorB +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +open HahnSeries +variable {R S : Type*} [CommRing R] [CommRing S] [Algebra ℚ R] [Algebra ℚ S] +@[simp] lemma mapLinear_single (f : R →ₗ[ℚ] S) (n : ℤ) (r : R) : + mapLinear f (single n r)=single n (f r) := by + apply HahnSeries.ext + funext k + simp only [mapLinear_coeff,coeff_single] + split_ifs <;> simp + +lemma polynomial_mapLinear (f : R →ₗ[ℚ] S) (p : Polynomial R) : + mapLinear f (polynomial p)=polynomial (RawShuffle.polynomialMapLinear f p) := by + induction p using Polynomial.induction_on' with + | add p q hp hq => simp only [map_add,hp,hq] + | monomial n r => rw [RawShuffle.polynomialMapLinear_monomial,polynomial_monomial, + polynomial_monomial,mapLinear_single] +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPolynomialAction.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPolynomialAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..47279693df835df0c87d9ed6bb1a7e999f2abdae --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPolynomialAction.lean @@ -0,0 +1,38 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.LaurentIdealCoefficients + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +open HahnSeries +variable {R : Type*} [CommRing R] [Algebra ℚ R] + +noncomputable def polynomialLinear : Polynomial R →ₗ[ℚ] LaurentSeries R where + toFun := polynomial + map_add' := polynomial.map_add + map_smul' q p := by + change polynomial (q • p)=q • polynomial p + induction p using Polynomial.induction_on' with + | add p r hp hr => simp only [smul_add,map_add,hp,hr] + | monomial n r => + simp only [Polynomial.smul_monomial,polynomial_monomial] + exact (single.linearMap (R:=ℚ) (-(n:ℤ))).map_smul q r + +noncomputable def mulPolynomial (k : LaurentSeries R) : Polynomial R →ₗ[ℚ] LaurentSeries R := + (LinearMap.mulLeft ℚ k).comp polynomialLinear +@[simp] lemma mulPolynomial_apply (k : LaurentSeries R) (p : Polynomial R) : + mulPolynomial k p=k*polynomial p := rfl +noncomputable def mulPolynomialCoeff (k : LaurentSeries R) (j : ℤ) : Polynomial R →ₗ[ℚ] R := + (coeff.linearMap (R:=ℚ) (-j)).comp (mulPolynomial k) +@[simp] lemma mulPolynomialCoeff_apply (k : LaurentSeries R) (j : ℤ) (p : Polynomial R) : + mulPolynomialCoeff k j p=(k*polynomial p).coeff (-j) := rfl +lemma mulPolynomialCoeff_mem (J : Ideal R) (k : LaurentSeries R) (j : ℤ) (p : Polynomial R) + (hp : ∀ n,p.coeff n∈J) : mulPolynomialCoeff k j p∈J := by + rw [mulPolynomialCoeff_apply,mul_comm] + exact coeff_mul_mem J _ _ (polynomial_coeff_mem J p hp) _ +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPolynomialEnergy.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPolynomialEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..26f6742d2bc91e2914b01b3a47c6490686f81692 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPolynomialEnergy.lean @@ -0,0 +1,66 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.HNTorusFactor + +namespace OAI + +section +namespace ElementaryPositivity.LaurentPositive +open WallUnits +open scoped BigOperators +open Classical +noncomputable section + +def qLaurent : Polynomial ℕ →+* LaurentSeries ℚ:= + Polynomial.eval₂RingHom (Nat.castRingHom _) (HahnSeries.single (-2) 1) +lemma qLaurent_monomial (k a:ℕ) : qLaurent (Polynomial.monomial k a)=HahnSeries.single (-2*(k:ℤ)) (a:ℚ) := by + change Polynomial.eval₂ (Nat.castRingHom _) (HahnSeries.single (-2) 1) (Polynomial.monomial k a)=_ + rw [Polynomial.eval₂_monomial] + change (a:LaurentSeries ℚ)*HahnSeries.single (-2) 1 ^ k=_ + rw [←HahnSeries.single_zero_natCast,HahnSeries.single_pow,HahnSeries.single_mul_single] + simp [mul_comm] + +def centered (M:ℕ) (p:Polynomial ℕ):LaurentSeries ℚ:=HahnSeries.single (M:ℤ) 1*qLaurent p +lemma centered_zero (M:ℕ) : centered M 0=0:=by simp [centered] +lemma centered_add (M:ℕ) (p q:Polynomial ℕ) : centered M (p+q)=centered M p+centered M q:=by + simp [centered,mul_add] +lemma centered_sum {A:Type*} [Fintype A] (M:ℕ) (p:A → Polynomial ℕ) : + centered M (∑a,p a)=∑a,centered M (p a):=by simp [centered,Finset.mul_sum] +lemma centered_mul (M:ℕ) (p q:Polynomial ℕ) : centered M (p*q)=centered M p*qLaurent q:=by + simp [centered,mul_assoc] +lemma centered_monomial (M k a:ℕ) : + centered M (Polynomial.monomial k a)=HahnSeries.single ((M:ℤ)-2*(k:ℤ)) (a:ℚ) := by + rw [centered,qLaurent_monomial,HahnSeries.single_mul_single,one_mul] + congr 1 +lemma centered_coeff (M:ℕ) (p:Polynomial ℕ) (k:ℕ) : + (centered M p).coeff ((M:ℤ)-2*(k:ℤ))=(p.coeff k:ℚ) := by + induction p using Polynomial.induction_on' with + | add p q hp hq=>rw [centered_add,HahnSeries.coeff_add,Polynomial.coeff_add,Nat.cast_add,hp,hq] + | monomial e a=> + rw [centered_monomial,HahnSeries.coeff_single,Polynomial.coeff_monomial] + have he:((M:ℤ)-2*(k:ℤ)=(M:ℤ)-2*(e:ℤ)) ↔ e=k:=by omega + simp only [he] + split_ifs <;> simp +lemma centered_injective (M:ℕ) : Function.Injective (centered M) := by + intro p q h + ext k + have H:=congrArg (fun w:LaurentSeries ℚ=>w.coeff ((M:ℤ)-2*(k:ℤ))) h + rw [centered_coeff,centered_coeff] at H + exact_mod_cast H +lemma centered_X_pow (M k:ℕ) : + centered M (Polynomial.X^k)=(↑(LaurentRay.vUnit^(2*(k:ℤ)-(M:ℤ))):LaurentSeries ℚ) := by + rw [←Polynomial.monomial_one_right_eq_X_pow,centered_monomial,LaurentRay.vUnit_zpow] + congr 1 + ring_nf + +lemma map_elementary_coeff {A B:Type*} [Fintype A] [Fintype B] + (μ:A →₀ ℕ) (a:B →₀ ℕ) : + qLaurent ((∏i:A,MvPolynomial.esymm B (Polynomial ℕ) (μ i)).coeff a)= + (∏i:A,MvPolynomial.esymm B (LaurentSeries ℚ) (μ i)).coeff a := by + rw [←MvPolynomial.coeff_map] + simp only [map_prod,MvPolynomial.map_esymm] +end +end ElementaryPositivity.LaurentPositive + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPositiveDomination.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPositiveDomination.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9b37638a03f14c35ef6e483f99f06ace766edcd --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentPositiveDomination.lean @@ -0,0 +1,186 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.ConeSectionDomination +import OAI.Combinatorics.Chromatic.Walls.TriangularPositivePowers + +namespace OAI + +section +namespace ElementaryPositivity.LaurentPositive +noncomputable section +lemma Positive.nonneg {f:LaurentSeries ℚ} (hf:Positive f) (j:ℤ) : 0 ≤ f.coeff j := by + obtain ⟨k,hk⟩:=hf j + rw [hk] + positivity +lemma Positive.eq_zero_of_neg {f:LaurentSeries ℚ} (hf:Positive f) (hn:Positive (-f)) : f=0 := by + apply HahnSeries.ext + funext j + have H:=hn.nonneg j + simp only [HahnSeries.coeff_neg] at H + simpa only [HahnSeries.coeff_zero] using (le_antisymm (by linarith) (hf.nonneg j)) +lemma Positive.eq_zero_of_sub {f g:LaurentSeries ℚ} (hf:Positive f) (hgf:Positive (g-f)) + (hg:g=0) : f=0 := by + apply hf.eq_zero_of_neg + simpa only [hg,zero_sub] using hgf +lemma Positive.ne_zero_of_sub_one {f:LaurentSeries ℚ} (h:Positive (f-1)) : f≠0 := by + intro hf + have H:=h.nonneg 0 + simp only [hf,zero_sub,HahnSeries.coeff_neg,HahnSeries.coeff_one,ite_true] at H + norm_num at H +end +end ElementaryPositivity.LaurentPositive + +end +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization PowerSeries PowerSeriesAdjoint LaurentPositive +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} +local instance : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance : AddCommMonoid (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommMonoid +local instance : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup +local instance : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup +local instance : Sub (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toSub + +def triangularBase (N:ℕ) : Extended (Vertex n (Cell n)) := includeVertices ((N:ℤ) • anchor 0) +lemma triangularBase_order (N:ℕ) : rootOrder (extendedCoord n) (triangularBase N)=0 := by + rw [triangularBase,map_zsmul,map_zsmul,rootOrder_anchor_zero,zsmul_zero] +lemma triangularExpression_initial_graded {N:ℕ} (f:ElementaryExpr N) : + ShiftGraded LaurentRay.vUnit (extendedOmega n) (extendedRoots n) (triangularBase N) + (polynomialInitial (extendedOmega n) (extendedRoots n) (extendedCoord n) (triangularExpression f)) := by + apply polynomialInitial_graded (extendedOmega n) (extendedRoots n) (extendedCoord n) + extendedCoord_roots (triangularBase N) (triangularBase_order N) + intro m hm + exact triangularSeed_in_rootCone f m (Finsupp.mem_support_iff.mpr hm) +lemma triangularPower_incoming_retain (N:ℕ) (μ:Fin (n+1) → ℕ) (hμ:∑a,μ a=N) + (hdom:∀i:Fin n,μ i.succ ≤ μ i.castSucc) (d:ℕ) + (hm:HasRootDegree (extendedRoots n) d (includeVertices (natAnchor μ)-triangularBase N)) (k:ℕ) : + TorusPositive (extendedOmega n) + (sectionIncoming LaurentRay.vUnit (extendedOmega n) (extendedRoots n) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) (triangularBase N) k + (polynomialInitial (extendedOmega n) (extendedRoots n) (extendedCoord n) (triangularExpression (linearPower N)))- + coneDelta (extendedOmega n) d (includeVertices (natAnchor μ)) k) := by + by_cases hk:k=d + · subst k + rw [coneDelta,ite_eq_left rfl] + intro m + rw [torus_sub_apply] + by_cases he:m=includeVertices (natAnchor μ) + · subst m + rw [polynomialInitial_incoming (extendedOmega n) extendedOmega_self (extendedRoots n) + (extendedCoord n) extendedCoord_roots (triangularBase N) (triangularBase_order N) + (triangularExpression (linearPower N)) (by intro m hm; exact triangularSeed_in_rootCone _ m (Finsupp.mem_support_iff.mpr hm)) d _ hm] + have H:=triangularPure_incoming (linearPower N) (fun a=>(μ a:ℤ)) (fun i=>Int.ofNat_le.mpr (hdom i)) + change polynomialSectionIncoming _ _ _ _ (includeVertices (natAnchor μ))=_ at H + rw [H] + simpa only [torus_sub_apply,natAnchor] using triangularPower_ordinary_retain N μ hμ (includeVertices (natAnchor μ)) + · have HX:Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (natAnchor μ)) m=0:=by + exact Finsupp.single_eq_of_ne he + rw [HX,sub_zero] + exact triangularPower_incoming_positive N d m + · rw [coneDelta,ite_eq_right hk,sub_zero] + exact triangularPower_incoming_positive N k + +def triangularConeTheta (N d:ℕ) (μ:Fin (n+1) → ℕ) (h:Extended (Vertex n (Cell n)) →+ ℝ) := + coneThetaValue (extendedOmega n) (extendedRoots n) (simpleTotalTransport (extendedOmega n) (extendedRoots n)) + (triangularBase N) d (includeVertices (natAnchor μ)) h + +lemma triangularConeTheta_positive (N d:ℕ) (μ:Fin (n+1) → ℕ) + (hm:HasRootDegree (extendedRoots n) d (includeVertices (natAnchor μ)-triangularBase N)) + (h:Module.Dual ℝ ((Vertex n (Cell n) → ℝ) × (Vertex n (Cell n) → ℝ))) : + IntegralPositive (extendedOmega n) (triangularConeTheta N d μ (h.toAddMonoidHom.comp extendedCast)) := by + obtain ⟨L,hL⟩:=real_covector_prescribe (extendedRoots n) extendedCast extendedRoots_realIndependent (fun _=>1) + exact coneThetaValue_positive (extendedOmega n) (extendedRoots n) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) (triangularBase N) + extendedCast extendedCast_injective (triangularRealForm n) triangularRealForm_self triangularRealForm_compatible + L (fun _ _ hm=>covector_root_eval (extendedRoots n) extendedCast L hL hm) + (simpleTotalTransport_positive_prescription _ _ extendedOmega_self) d _ hm h + +lemma triangularPower_domination (N d:ℕ) (μ:Fin (n+1) → ℕ) (hμ:∑a,μ a=N) + (hdom:∀i:Fin n,μ i.succ ≤ μ i.castSucc) + (hm:HasRootDegree (extendedRoots n) d (includeVertices (natAnchor μ)-triangularBase N)) + (h:Module.Dual ℝ ((Vertex n (Cell n) → ℝ) × (Vertex n (Cell n) → ℝ))) : + IntegralPositive (extendedOmega n) + (adjoint (rootSectionChart (extendedOmega n) (extendedRoots n) (h.toAddMonoidHom.comp extendedCast)).val + (homogenize LaurentRay.vUnit (extendedOmega n) (rootOrder (extendedCoord n)) (triangularExpression (linearPower N)))- + triangularConeTheta N d μ (h.toAddMonoidHom.comp extendedCast)) := by + rw [rootSectionChart_action] + obtain ⟨L,hL⟩:=real_covector_prescribe (extendedRoots n) extendedCast extendedRoots_realIndependent (fun _=>1) + exact coneTheta_domination (extendedOmega n) (extendedRoots n) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) (triangularBase N) + extendedCast extendedCast_injective (triangularRealForm n) triangularRealForm_self triangularRealForm_compatible + L (fun _ _ hm=>covector_root_eval (extendedRoots n) extendedCast L hL hm) + (simpleTotalTransport_positive_prescription _ _ extendedOmega_self) _ + (triangularExpression_initial_graded (linearPower N)) d _ hm + (triangularPower_incoming_retain N μ hμ hdom d hm) h + +lemma adjoint_one_torus (X:PowerSeries (Torus LaurentRay.vUnit (extendedOmega n))) : adjoint 1 X=X := by + have hi:invOfUnit (1:PowerSeries (Torus LaurentRay.vUnit (extendedOmega n))) 1=1:=by + simpa only [mul_one] using (invOfUnit_mul (1:PowerSeries (Torus LaurentRay.vUnit (extendedOmega n))) 1 (by simp)) + simp only [adjoint,one_mul,hi,mul_one] + +lemma triangularTheta_support (N d:ℕ) (μ:Fin (n+1) → ℕ) (hμ:∑a,μ a=N) + (hdom:∀i:Fin n,μ i.succ ≤ μ i.castSucc) + (hm:HasRootDegree (extendedRoots n) d (includeVertices (natAnchor μ)-triangularBase N)) + (h:Module.Dual ℝ ((Vertex n (Cell n) → ℝ) × (Vertex n (Cell n) → ℝ))) + (hneg:∀k,0m (.inl a)) he + simpa only [pureAnchor_apply_anchor] using H + +lemma stationary_pure_dominant (μ:Fin (n+1) → ℤ) + (hxi:∀b:Cell n,0 ≤ triangularOmega n (eventRoot cellLevel 0 b) (pureAnchor μ)) : + ∀i:Fin n,μ i.succ ≤ μ i.castSucc := by + intro i + let b:Cell n:=⟨i,⟨0,by omega⟩⟩ + have H:=hxi b + simp only [eventRoot,Nat.cast_zero,zero_smul,add_zero,map_sub,AddMonoidHom.sub_apply, + bridge_pair_pure,anchor_pair_pure,sub_zero] at H + change 0 ≤ μ i.castSucc-μ i.succ at H + omega + +lemma triangularPureIncoming_dominant {N:ℕ} (f:ElementaryExpr N) (μ:Fin (n+1) → ℤ) + (h:triangularIncoming f (pureAnchor μ)≠0) : ∀i:Fin n,μ i.succ ≤ μ i.castSucc := + stationary_pure_dominant μ (triangularExpression_stationary f (pureAnchor μ) h).2.1 + +lemma triangularPureIncoming_delta {N:ℕ} (f:ElementaryExpr N) (μ:Fin (n+1) → ℤ) + (hμ:∀i:Fin n,μ i.succ ≤ μ i.castSucc) + (hp:∀ν:Fin (n+1) → ℤ,(∀i:Fin n,ν i.succ ≤ ν i.castSucc) → + triangularExpression f (includeVertices (pureAnchor ν))=if ν=μ then 1 else 0) + (ν:Fin (n+1) → ℤ) : + triangularIncoming f (pureAnchor ν)=if ν=μ then 1 else 0 := by + by_cases hd:∀i:Fin n,ν i.succ ≤ ν i.castSucc + · rw [triangularPure_incoming f ν hd,hp ν hd] + · have hne:ν≠μ:=by intro h; subst ν; exact hd hμ + rw [ite_eq_right hne] + by_contra hh + exact hd (triangularPureIncoming_dominant f ν hh) +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentProjectionFormula.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentProjectionFormula.lean new file mode 100644 index 0000000000000000000000000000000000000000..4508782faa9af3858966c8b4f53dc8cc23ee4aa5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentProjectionFormula.lean @@ -0,0 +1,29 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +open HahnSeries +variable {K A B : Type*} [CommSemiring K] [CommRing A] [CommRing B] + [Algebra K A] [Algebra K B] + +lemma mapLinear_projection (T : A →ₗ[K] B) (ι : B →+* A) + (hT : ∀ b x,T (ι b*x)=b*T x) (P : LaurentSeries B) (X : LaurentSeries A) : + mapLinear T (mapRing ι P * X)=P*mapLinear T X := by + apply HahnSeries.ext + funext k + have hP : (mapRing ι P).support⊆P.support := HahnSeries.support_map_subset P ι.toZeroHom + have hX : (mapLinear T X).support⊆X.support := HahnSeries.support_map_subset X ⟨T,T.map_zero⟩ + rw [mapLinear_coeff,coeff_mul_left' P.isPWO_support hP, + coeff_mul_right' X.isPWO_support hX,map_sum] + apply Finset.sum_congr rfl + intro xy hxy + exact hT _ _ + +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentRayEmbedding.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentRayEmbedding.lean new file mode 100644 index 0000000000000000000000000000000000000000..befcf8151a21c55c3d9f31ede39231f176c82469 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentRayEmbedding.lean @@ -0,0 +1,94 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open HahnSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (p : M) +local instance laurentRayRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance laurentRayAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance laurentRayAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance laurentRayNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring + +def laurentRay (f : HahnSeries ℤ R) : HahnSeries ℤ (Torus v Ω) where + coeff n:=Torus.monomial v Ω (n • p) (f.coeff n) + isPWO_support':=f.isPWO_support.mono (by + intro n hn + change Torus.monomial v Ω (n • p) (f.coeff n)≠0 at hn + change f.coeff n≠0 + intro he + exact hn (by rw [he]; exact Finsupp.single_zero _)) +lemma laurentRay_coeff (f : HahnSeries ℤ R) (n : ℤ) : + (laurentRay v Ω p f).coeff n=Torus.monomial v Ω (n • p) (f.coeff n) := rfl +lemma laurentRay_support (f : HahnSeries ℤ R) : (laurentRay v Ω p f).support=f.support := by + ext n + simp only [HahnSeries.mem_support,laurentRay_coeff] + constructor + · intro hn hz + apply hn + rw [hz] + exact Finsupp.single_zero _ + · intro hn hz + have H:=congrArg (fun a : Torus v Ω=>a (n • p)) hz + exact hn (by simpa [Torus.monomial] using H) +lemma laurentRay_zero : laurentRay v Ω p 0=0 := by + apply HahnSeries.ext + funext n + simp [laurentRay_coeff] +lemma laurentRay_add (f g : HahnSeries ℤ R) : + laurentRay v Ω p (f+g)=laurentRay v Ω p f+laurentRay v Ω p g := by + apply HahnSeries.ext + funext n + simp [laurentRay_coeff,Torus.monomial] +lemma laurentRay_single (n : ℤ) (a : R) : + laurentRay v Ω p (HahnSeries.single n a)=HahnSeries.single n (Torus.monomial v Ω (n • p) a) := by + apply HahnSeries.ext + funext j + simp only [laurentRay_coeff,HahnSeries.coeff_single] + by_cases hj : j=n + · subst j; simp + · simp [hj,Torus.monomial] +lemma laurentRay_one : laurentRay v Ω p 1=1 := by + change laurentRay v Ω p (HahnSeries.single 0 1)=HahnSeries.single 0 1 + rw [laurentRay_single,zero_smul] + rfl +lemma laurentRay_mul (hp : Ω p p=0) (f g : HahnSeries ℤ R) : + laurentRay v Ω p (f*g)=laurentRay v Ω p f*laurentRay v Ω p g := by + classical + apply HahnSeries.ext + funext n + rw [laurentRay_coeff,HahnSeries.coeff_mul,HahnSeries.coeff_mul] + have HS : Finset.antidiagonal (laurentRay v Ω p f).isPWO_support + (laurentRay v Ω p g).isPWO_support n= + Finset.antidiagonal f.isPWO_support g.isPWO_support n := by + ext ij + simp only [Finset.mem_antidiagonal,laurentRay_support] + rw [HS] + change (Finsupp.singleAddHom (n • p)) _=_ + rw [_root_.map_sum] + apply Finset.sum_congr rfl + intro ij hij + have H:=(Finset.mem_antidiagonal.mp hij).2.2 + simp only [laurentRay_coeff,Torus.monomial_mul_monomial,map_zsmul, + AddMonoidHom.zsmul_apply,hp,smul_zero,zpow_zero,Units.val_one,mul_one] + rw [←add_zsmul,H] + rfl + +def laurentRayHom (hp : Ω p p=0) : HahnSeries ℤ R →+* HahnSeries ℤ (Torus v Ω) where + toFun:=laurentRay v Ω p + map_zero':=laurentRay_zero v Ω p + map_one':=laurentRay_one v Ω p + map_add':=laurentRay_add v Ω p + map_mul':=laurentRay_mul v Ω p hp +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LaurentScalarAction.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentScalarAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ceac50b62c64fcca1ed66932ea4fdbc1c75ec90 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LaurentScalarAction.lean @@ -0,0 +1,31 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity + +namespace OAI + +section +namespace ElementaryPositivity.LaurentAtInfinity +open HahnSeries +variable {R : Type*} [CommRing R] [Algebra ℚ R] + +lemma mapLinear_scalar_mul (f : R →ₗ[ℚ] R) (q : LaurentSeries ℚ) (p : LaurentSeries R) : + mapLinear f (mapRing (algebraMap ℚ R) q*p)= + mapRing (algebraMap ℚ R) q*mapLinear f p := by + apply HahnSeries.ext + funext k + rw [mapLinear_coeff,coeff_mul, + coeff_mul_right' p.isPWO_support (by + intro n hn + change f (p.coeff n)≠0 at hn + exact fun h=>hn (h ▸ f.map_zero))] + rw [map_sum] + apply Finset.sum_congr rfl + intro ij hij + change f (algebraMap ℚ R (q.coeff ij.1)*p.coeff ij.2)= + algebraMap ℚ R (q.coeff ij.1)*f (p.coeff ij.2) + rw [←Algebra.smul_def,←Algebra.smul_def,f.map_smul] +end ElementaryPositivity.LaurentAtInfinity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LineOldTransport.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LineOldTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f18dff91ebfef140d8002f678d67e5fe2b0fdd9 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LineOldTransport.lean @@ -0,0 +1,152 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationMonomialAction +import OAI.Combinatorics.Chromatic.Walls.NegativeRayCrossing + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) + +def oldCoefficientsEqual (N : ℕ) + (a b : (biSupportedSubring LaurentRay.vUnit Ω (nonpDegree coord pc) (pureDegree coord pc))ˣ) : Prop := + ∀n≤N,coeff n a.val.val=coeff n b.val.val +lemma oldCoefficientsEqual_equivalence (N : ℕ) : + Equivalence (oldCoefficientsEqual Ω coord pc N) := by + refine ⟨fun _ _ _=>rfl,?_,?_⟩ + · intro a b hab n hn; exact (hab n hn).symm + · intro a b c hab hbc n hn; exact (hab n hn).trans (hbc n hn) +lemma oldCoefficientsEqual_mul (N : ℕ) + (a b c d : (biSupportedSubring LaurentRay.vUnit Ω (nonpDegree coord pc) (pureDegree coord pc))ˣ) + (hab : oldCoefficientsEqual Ω coord pc N a b) (hcd : oldCoefficientsEqual Ω coord pc N c d) : + oldCoefficientsEqual Ω coord pc N (a*c) (b*d) := by + intro n hn + exact FormalLog.mul_coeff_congr a.val.val c.val.val b.val.val d.val.val n + (fun j hj=>hab j (hj.trans hn)) (fun j hj=>hcd j (hj.trans hn)) + +def lineNegativeUnit (a : ℝ) := completedBiUnit LaurentRay.vUnit Ω C coord hcoord pc + (chartNegative LaurentRay.vUnit Ω C ((k+a • v).toAddMonoidHom.comp e) (simpleTotalTransport Ω C)) + +include he hdeg H in +lemma actualLine_old_step (N : ℕ) (a : ℝ) + (ha : a∈lineEvents (realRootsThrough e C N) v k) : + ∃ε>0,∀δ,0<δ → δ<ε → oldCoefficientsEqual Ω coord pc N + (comparisonOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a)* + lineNegativeUnit Ω C coord hcoord pc e v k (a-δ)) + (lineNegativeUnit Ω C coord hcoord pc e v k (a+δ)) := by + obtain ⟨r,d,hd,hr,hv,Hg,HOld⟩:=actualLineLetter_old Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a ⟨N,ha⟩ + let h:=(k+a • v).toAddMonoidHom.comp e + let V:=v.toAddMonoidHom.comp e + obtain ⟨ε,hε,Hε⟩:=root_lex_epsilon C N h V + obtain ⟨η,hη,Hη⟩:=root_lex_epsilon C N h (-V) + refine ⟨min ε η,lt_min hε hη,?_⟩ + intro δ hδ hsmall n hn + have Hp : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h V + ((k+(a+δ) • v).toAddMonoidHom.comp e) m:=by + rw [line_covector_add] + exact Hε δ hδ (hsmall.trans_le (min_le_left _ _)) + have Hm : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h (-V) + ((k+(a-δ) • v).toAddMonoidHom.comp e) m:=by + rw [line_covector_sub] + exact Hη δ hδ (hsmall.trans_le (min_le_right _ _)) + have HH:=negative_ray_forward LaurentRay.vUnit Ω C (simpleTotalTransport Ω C) N r h V + ((k+(a+δ) • v).toAddMonoidHom.comp e) ((k+(a-δ) • v).toAddMonoidHom.comp e) + (Hg N) hv Hp Hm n hn + change coeff n ((comparisonOld _ _ _ _ _ _ _ _ _ _).val.val* + (lineNegativeUnit Ω C coord hcoord pc e v k (a-δ)).val.val)=_ + rw [HOld] + by_cases hk : v (e r)<0 + · rw [ite_eq_left hk] + rw [ite_eq_left (show V r<0 from hk)] at HH + exact HH + · rw [ite_eq_right hk] + rw [ite_eq_right (show ¬V r<0 from hk)] at HH + exact HH + +lemma actualLine_old_cell (N : ℕ) (a b : ℝ) + (ha : a∉lineEvents (realRootsThrough e C N) v k) + (hb : b∉lineEvents (realRootsThrough e C N) v k) + (hc : ∀z∈lineEvents (realRootsThrough e C N) v k,acomparisonOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a)) + (lineNegativeUnit Ω C coord hcoord pc e v k) + (actualLine_old_cell Ω C coord hcoord pc e v k N) + (actualLine_old_step Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H N) + lo hi hlo hhi horder + simpa only [FiniteEventTraversal.intervalWord,comparisonWordOld,actualLineWord, + intervalEventList,intervalLineEvents,List.map_map,Function.comp_def] using HH +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +structure GenericLineSegment where + direction : Module.Dual ℝ E + offset : Module.Dual ℝ E + lo : ℝ + hi : ℝ + ordered : lo exact congrArg (mk H H') (μ₀.map_add₂ x y z) + map_smul' := by + intro r x + ext z + induction z using Submodule.Quotient.induction_on with + | H z => + change mk H H' (μ₀ (r • x) z) = r • mk H H' (μ₀ x z) + rw [μ₀.map_smul₂, map_smul] } + exact (next F F').liftQ L (by + intro x hx + ext y + induction y using Submodule.Quotient.induction_on with + | H y => exact (Submodule.Quotient.mk_eq_zero _).mpr (hl x.val hx y.val y.property)) + +lemma bilinear_mk (F F' : Submodule ℚ M) (G G' : Submodule ℚ N) + (H H' : Submodule ℚ P) (μ : M →ₗ[ℚ] N →ₗ[ℚ] P) + (h : ∀ x∈F,∀ y∈G,μ x y∈H) + (hl : ∀ x∈F',∀ y∈G,μ x y∈H') (hr : ∀ x∈F,∀ y∈G',μ x y∈H') + (x : F) (y : G) : + bilinear F F' G G' H H' μ h hl hr (mk F F' x) (mk G G' y)= + mk H H' ⟨μ x.val y.val,h x.val x.property y.val y.property⟩ := rfl + +end ElementaryPositivity.LinearFiltration + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LinearFiltrationFinite.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LinearFiltrationFinite.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3f37a8a02c1c639546b81b7f165b24e14ea6055 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LinearFiltrationFinite.lean @@ -0,0 +1,38 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TensorFiltrationInterchange + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +variable {M : Type*} [AddCommGroup M] [Module ℚ M] + +lemma map_range_finite (F F' : Submodule ℚ M) (f : Module.End ℚ M) + (h : ∀ x∈F,f x∈F) (h' : ∀ x∈F',f x∈F') + [Module.Finite ℚ (LinearMap.range f)] : + Module.Finite ℚ (LinearMap.range (map F F' F F' f h h')) := by + let R:=LinearMap.range (restrict F F f h) + let J : R →ₗ[ℚ] LinearMap.range f := + (F.subtype.comp R.subtype).codRestrict _ (by + rintro ⟨x,⟨y,rfl⟩⟩ + exact ⟨y.val,rfl⟩) + have hJ : Function.Injective J := by + intro x y hxy + apply Subtype.ext + apply Subtype.ext + exact congrArg (fun z : LinearMap.range f => (z : M)) hxy + let : Module.Finite ℚ R:=Module.Finite.of_injective J hJ + let H:=map F F' F F' f h h' + let L : R →ₗ[ℚ] LinearMap.range H := + ((mk F F').comp R.subtype).codRestrict _ (by + rintro ⟨x,⟨y,rfl⟩⟩ + exact ⟨mk F F' y,rfl⟩) + apply Module.Finite.of_surjective L + rintro ⟨x,⟨y,rfl⟩⟩ + induction y using Submodule.Quotient.induction_on with + | H y => exact ⟨⟨restrict F F f h y,⟨y,rfl⟩⟩,rfl⟩ +end ElementaryPositivity.LinearFiltration + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/LinearFiltrationOperators.lean b/lean/OAI/Combinatorics/Chromatic/Walls/LinearFiltrationOperators.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab3f5180af2883d2c7c9734d5c85802e178252b6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/LinearFiltrationOperators.lean @@ -0,0 +1,60 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TensorFiltrationInterchange + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +variable {M : Type*} [AddCommGroup M] [Module ℚ M] + +lemma restrict_pow_val (F : Submodule ℚ M) (D : Module.End ℚ M) + (h : ∀ x∈F,D x∈F) (n : ℕ) (x : F) : + ((restrict F F D h ^n) x).val=(D^n) x.val := by + induction n with + | zero => rfl + | succ n ih => + simp only [pow_succ',Module.End.mul_apply] + change D ((restrict F F D h^n) x).val=_ + rw [ih] + +lemma map_pow_mk (F F' : Submodule ℚ M) (D : Module.End ℚ M) + (h : ∀ x∈F,D x∈F) (h' : ∀ x∈F',D x∈F') (n : ℕ) (x : F) : + (map F F' F F' D h h'^n) (mk F F' x)=mk F F' ((restrict F F D h^n) x) := by + induction n with + | zero => rfl + | succ n ih => simp only [pow_succ',Module.End.mul_apply,ih]; rfl + +lemma map_locally_nilpotent (F F' : Submodule ℚ M) (D : Module.End ℚ M) + (h : ∀ x∈F,D x∈F) (h' : ∀ x∈F',D x∈F') + (hnil : ∀ x,∃ N : ℕ,(D^N) x=0) (x : Grade F F') : + ∃ N : ℕ,(map F F' F F' D h h'^N) x=0 := by + induction x using Submodule.Quotient.induction_on with + | H x => + obtain ⟨N,hN⟩:=hnil x.val + refine ⟨N,?_⟩ + change (map F F' F F' D h h'^N) (mk F F' x)=0 + rw [map_pow_mk] + have hz : (restrict F F D h^N) x=0 := by + apply Subtype.ext + rw [restrict_pow_val,hN] + rfl + rw [hz,map_zero] + +lemma map_weyl (F F' : Submodule ℚ M) (D T : Module.End ℚ M) + (hD : ∀ x∈F,D x∈F) (hD' : ∀ x∈F',D x∈F') + (hT : ∀ x∈F,T x∈F) (hT' : ∀ x∈F',T x∈F') + (h : ∀ x,D (T x)=T (D x)+x) (x : Grade F F') : + map F F' F F' D hD hD' (map F F' F F' T hT hT' x)= + map F F' F F' T hT hT' (map F F' F F' D hD hD' x)+x := by + induction x using Submodule.Quotient.induction_on with + | H x => + change mk F F' (restrict F F D hD (restrict F F T hT x)) = + mk F F' (restrict F F T hT (restrict F F D hD x)) + mk F F' x + rw [←map_add] + exact congrArg (mk F F') (Subtype.ext (h x.val)) + +end ElementaryPositivity.LinearFiltration + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/Mass.lean b/lean/OAI/Combinatorics/Chromatic/Walls/Mass.lean new file mode 100644 index 0000000000000000000000000000000000000000..61c133c7960b4ef51fb8778edc4402863efba602 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/Mass.lean @@ -0,0 +1,131 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] + +def mass (c : I → ℝ) (d : I → ℕ) : ℝ := ∑ i,(d i : ℝ) * c i + +noncomputable def slope (c η : I → ℝ) (d : I → ℕ) : ℝ := mass η d / mass c d + +lemma mass_add (c : I → ℝ) (d e : I → ℕ) : mass c (d+e) = mass c d + mass c e := by + simp [mass,Nat.cast_add,add_mul,Finset.sum_add_distrib] + +@[simp] lemma mass_zero (c : I → ℝ) : mass c 0 = 0 := by simp [mass] + +lemma mass_nonneg (c : I → ℝ) (hc : ∀ i,0 ≤ c i) (d : I → ℕ) : 0 ≤ mass c d := by + apply Finset.sum_nonneg + intro i hi + exact mul_nonneg (Nat.cast_nonneg _) (hc i) + +lemma mass_pos (c : I → ℝ) (hc : ∀ i,0 < c i) (d : I → ℕ) (hd : d ≠ 0) : + 0 < mass c d := by + classical + obtain ⟨i,hi⟩ : ∃ i,d i ≠ 0 := by + by_contra hn + push Not at hn + apply hd + funext i + exact hn i + apply Finset.sum_pos' + · intro j hj + exact mul_nonneg (Nat.cast_nonneg _) (hc j).le + · exact ⟨i,Finset.mem_univ _,mul_pos (by exact_mod_cast Nat.pos_of_ne_zero hi) (hc i)⟩ + +lemma mass_eq (c η : I → ℝ) (hc : ∀ i,0 < c i) (d : I → ℕ) : + mass η d = slope c η d * mass c d := by + by_cases hd : d=0 + · subst d; simp + · exact (div_mul_cancel₀ _ (mass_pos c hc d hd).ne').symm + +omit [Fintype I] in +lemma add_ne_zero_left (d e : I → ℕ) (hd : d ≠ 0) : d+e ≠ 0 := by + intro h + apply hd + funext i + have hi := congrFun h i + simp only [Pi.add_apply,Pi.zero_apply] at hi + change d i = 0 + omega + +omit [Fintype I] in +lemma add_ne_zero_right (d e : I → ℕ) (he : e ≠ 0) : d+e ≠ 0 := by + rw [add_comm] + exact add_ne_zero_left e d he + +lemma slope_add (c η : I → ℝ) (hc : ∀ i,0 < c i) {d e : I → ℕ} + (hd : d ≠ 0) (hs : slope c η d = slope c η e) : + slope c η (d+e) = slope c η d := by + apply (div_eq_iff (mass_pos c hc (d+e) (add_ne_zero_left d e hd)).ne').mpr + rw [mass_add,mass_add,mass_eq c η hc d,mass_eq c η hc e,← hs] + ring + +lemma slope_add_same (c η : I → ℝ) (hc : ∀ i,0 < c i) {d e : I → ℕ} + (hs : slope c η d = slope c η e) : + slope c η (d+e) = slope c η d := by + by_cases hd : d=0 + · subst d + simpa using hs.symm + · exact slope_add c η hc hd hs + +lemma slope_add_gt (c η : I → ℝ) (hc : ∀ i,0 < c i) {d u : I → ℕ} + (hu : u ≠ 0) {θ : ℝ} (hd : mass η d = θ * mass c d) + (hs : slope c η u > θ) : slope c η (d+u) > θ := by + have hmass := mass_pos c hc u hu + have hu' : mass η u > θ * mass c u := (lt_div_iff₀ hmass).mp hs + apply (lt_div_iff₀ (mass_pos c hc (d+u) (add_ne_zero_right d u hu))).mpr + rw [mass_add,mass_add,hd,mul_add] + linarith + +lemma mass_sum_le {J : Type*} [Fintype J] (c η : I → ℝ) (hc : ∀ i,0 < c i) + (d : J → I → ℕ) (θ : ℝ) (h : ∀ j,d j ≠ 0 → slope c η (d j) ≤ θ) : + (∑ j,mass η (d j)) ≤ θ * ∑ j,mass c (d j) := by + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro j hj + by_cases hd : d j=0 + · simp [hd] + · exact (div_le_iff₀ (mass_pos c hc (d j) hd)).mp (h j hd) + +end ElementaryPositivity.SlopeArithmetic + +namespace ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] + +lemma destabilized_target (c η : I → ℝ) (hc : ∀ i,0 slope c η (d₁+e₁)) : + (d₁≠0 ∧ e₁≠0 ∧ slope c η d₁ > slope c η (d₁+e₁)) ∨ + (d₂≠0 ∧ e₂≠0 ∧ slope c η d₂ > slope c η (d₂+e₂)) := by + have ht : mass η (d₁+d₂) > slope c η (d₁+e₁) * mass c (d₁+d₂) := + (lt_div_iff₀ (mass_pos c hc _ hd)).mp hμ + rw [mass_add,mass_add,mul_add] at ht + have hex : mass η d₁ > slope c η (d₁+e₁) * mass c d₁ ∨ + mass η d₂ > slope c η (d₂+e₂) * mass c d₂ := by + rw [← hs] + by_contra hn + push Not at hn + linarith + rcases hex with h | h + · left + have hdn : d₁≠0 := by intro hh; simp [hh] at h + have hen : e₁≠0 := by + intro hh + rw [hh,add_zero,mass_eq c η hc d₁] at h + exact (lt_irrefl _ h) + exact ⟨hdn,hen,(lt_div_iff₀ (mass_pos c hc _ hdn)).mpr h⟩ + · right + have hdn : d₂≠0 := by intro hh; simp [hh] at h + have hen : e₂≠0 := by + intro hh + rw [hh,add_zero,mass_eq c η hc d₂] at h + exact (lt_irrefl _ h) + exact ⟨hdn,hen,(lt_div_iff₀ (mass_pos c hc _ hdn)).mpr h⟩ +end ElementaryPositivity.SlopeArithmetic + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedAnchors.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedAnchors.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e1b66b3a410100056edb2125d1b22c43839a64b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedAnchors.lean @@ -0,0 +1,168 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationLogCompletion +import OAI.Combinatorics.Chromatic.GradedAlgebra.RealRootCoordinates + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) (pc:I) (e:M →+ E) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) + +omit [FiniteDimensional ℝ E] in +lemma mutated_degree_covector (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) : + ∃J:Module.Dual ℝ E,∀i,J (e (simpleRoot (mutatedRoots Ω C pc) i))=1 := by + classical + obtain ⟨D,hD⟩:=realRootCoordinates_exists C e hC + let w:I → ℝ:=fun i=>if i=pc then -1 else 1+(max 0 (-mutationPairing Ω C pc i):ℤ) + let J:Module.Dual ℝ E:=∑i,w i • (LinearMap.proj i).comp D + have hj (i:I):J (e (simpleRoot C i))=w i:=by + simp only [J,LinearMap.sum_apply,LinearMap.smul_apply,LinearMap.comp_apply, + real_coordinate_simple C e D hD,LinearMap.proj_apply,smul_eq_mul,Pi.single_apply] + rw [Finset.sum_eq_single i] + · simp + · intro j hj hji; simp [hji] + · simp + refine ⟨J,fun i=>?_⟩ + by_cases hi:i=pc + · subst i + rw [mutatedRoot_p,map_neg,map_neg,hj] + simp [w] + · rw [mutatedRoot_off Ω C pc i hi,map_add,map_zsmul,map_add,map_zsmul,hj,hj] + simp [w,hi,zsmul_eq_mul] + +omit [FiniteDimensional ℝ E] in +lemma covector_root_pos (J:Module.Dual ℝ E) + (hJ:∀i,0H i) + rw [ha] at hh + omega + obtain ⟨i,hi⟩:=hp + exact Finset.sum_pos' (fun j _=>mul_nonneg (by exact_mod_cast Nat.zero_le (a j)) (hJ j).le) + ⟨i,Finset.mem_univ i,mul_pos (by exact_mod_cast hi) (hJ i)⟩ + +include hS in +lemma mutated_regular_anchors (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) : + ∃a b:Module.Dual ℝ E,RegularCovector C e a ∧ RegularCovector C e b ∧ + (∀n,0realShearVector e S (simpleRoot C pc) + (e (simpleRoot (mutatedRoots Ω C pc) i))) + let Q:=Finset.univ.image (fun i=>e (simpleRoot (mutatedRoots Ω C pc) i)) + obtain ⟨a,HA,_,Sa⟩:=regular_covector_with_signs C e ∅ (insert (e (simpleRoot C pc)) P) K + obtain ⟨b,HB,_,Sb⟩:=regular_covector_with_signs C e ∅ (insert (e (simpleRoot C pc)) Q) (-J) + have hap:a (e (simpleRoot C pc))<0:=by + apply (Sa _ (Finset.mem_insert_self _ _)).2 + rw [realShearCovectorInverse_at_p e S _ hS J,hJp] + norm_num + have hbp:0covector_root_pos _ e _ ha hn hm,?_⟩ + intro n hn m hm + have H:=covector_root_pos _ e _ hb hn hm + simpa only [LinearMap.neg_apply,neg_pos] using H +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (pc:I) (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) + +lemma onPositiveRay_real_span {r p:M} (H:OnPositiveRay r p) : + e p∈Submodule.span ℝ {e r} := by + obtain ⟨a,b,ha,hb,H⟩:=H + have HH:(a:ℝ) • e p=(b:ℝ) • e r:=by + simpa only [map_nsmul,Nat.cast_smul_eq_nsmul] using congrArg e H + refine Submodule.mem_span_singleton.mpr ⟨(a:ℝ)⁻¹*(b:ℝ),?_⟩ + rw [mul_smul,←HH,inv_smul_smul₀ (by exact_mod_cast (Nat.ne_of_gt ha))] + +include he hS hcomp in +lemma nonpure_preimage_off_line (J:Module.Dual ℝ E) + (hJ:∀i,J (e (simpleRoot (mutatedRoots Ω C pc) i))=1) + (r:M) (d:ℕ) (hd:0covector_root_eval _ e J hJ hm) _ _ d 1 hd (by omega) hr + (simpleRoot_degree _ pc) + rw [hh,mutatedRoot_p,map_neg] + exact Submodule.neg_mem _ H + +include he hS hcomp in +lemma nonpure_preimage_geometry (J:Module.Dual ℝ E) + (hJ:∀i,J (e (simpleRoot (mutatedRoots Ω C pc) i))=1) + (r:M) (d:ℕ) (hd:0HP (onPositiveRay_real_span e H)⟩ + intro H + have hr0:r=0:=he (H.trans (map_zero e).symm) + have hh:mutationIncomingLabel Ω (simpleRoot C pc) r=0:=by simp [hr0,mutationIncomingLabel] + have HJ:=covector_root_eval _ e J hJ hr + rw [hh,map_zero,map_zero] at HJ + have : (d:ℝ)>0:=by exact_mod_cast hd + linarith +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedHalfspaceTransport.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedHalfspaceTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce417aa6b79ffc5816d97dce9d801eb1a04f2c81 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedHalfspaceTransport.lean @@ -0,0 +1,182 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedNoCutTransport +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutatedNoCutCone + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +section Algebra +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] [DecidableEq I] +variable (C : (I → ℤ) →+ M) (pc : I) (e : M →+ E) +omit [Fintype I] in +lemma cutSide_affineSegment (pos : Bool) (a b : Module.Dual ℝ E) + (ha : cutSide pos (a.toAddMonoidHom.comp e) (simpleRoot C pc)) + (hb : cutSide pos (b.toAddMonoidHom.comp e) (simpleRoot C pc)) + (t : ℝ) (ht : 0exact hp + | append s q ih=>exact ⟨hq.1,ih hq.2⟩ + +lemma GenericLinePath.OnCutSide.reindex {a b a' b' : Module.Dual ℝ E} (pos : Bool) + (p : GenericLinePath C e a b) (hp : p.OnCutSide C pc e pos) (ha : a=a') (hb : b=b') : + ∃q : GenericLinePath C e a' b',q.OnCutSide C pc e pos := by + cases ha + cases hb + exact ⟨p,hp⟩ + +lemma segmentBetween_onCutSide (pos : Bool) (a b : Module.Dual ℝ E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (H : ∀N,GenericOffset (realRootsThrough e C N) 0 (b-a) a) + (ha : cutSide pos (a.toAddMonoidHom.comp e) (simpleRoot C pc)) + (hb : cutSide pos (b.toAddMonoidHom.comp e) (simpleRoot C pc)) : + (GenericLinePath.single C e (segmentBetween C e a b HA HB H)).OnCutSide C pc e pos := by + refine ⟨?_,trivial⟩ + intro t ht ht1 + exact cutSide_affineSegment C pc e pos a b ha hb t ht ht1 +end Algebra +section Existence +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (C : (I → ℤ) →+ M) (pc : I) (e : M →+ E) +theorem generic_path_exists_onCutSide (pos : Bool) (a b : Module.Dual ℝ E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (ha : cutSide pos (a.toAddMonoidHom.comp e) (simpleRoot C pc)) + (hb : cutSide pos (b.toAddMonoidHom.comp e) (simpleRoot C pc)) : + ∃p : GenericLinePath C e a b,p.OnCutSide C pc e pos := by + classical + obtain ⟨h,Ha,Hb,HP⟩:=generic_for_two_directions (realRootsThrough e C) a b a {e (simpleRoot C pc)} + have HH : RegularCovector C e h:=by + intro N s hs hn + exact (Ha N).avoid s hs (by simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using hn) + have hs : cutSide pos (h.toAddMonoidHom.comp e) (simpleRoot C pc):=by + have ht:=HP (e (simpleRoot C pc)) (Finset.mem_singleton_self _) + cases pos + · exact ht.2 ha + · exact ht.1 ha + have hx : ∃p : GenericLinePath C e a h,p.OnCutSide C pc e pos := by + let s:=segmentBetween C e a h HA HH (fun N=>(Ha N).join (HA N)) + have hh:=segmentBetween_onCutSide C pc e pos a h HA HH (fun N=>(Ha N).join (HA N)) ha hs + have hp : ∃p : GenericLinePath C e (s.start C e) (s.finish C e),p.OnCutSide C pc e pos:= + ⟨GenericLinePath.single C e s,hh⟩ + obtain ⟨p,hp⟩:=hp + exact GenericLinePath.OnCutSide.reindex C pc e pos p hp + (segmentBetween_start C e _ _ _ _ _) (segmentBetween_finish C e _ _ _ _ _) + have hy : ∃p : GenericLinePath C e h b,p.OnCutSide C pc e pos := by + let s:=segmentBetween C e h b HH HB (fun N=>(Hb N).join_reverse (HB N)) + have hh:=segmentBetween_onCutSide C pc e pos h b HH HB (fun N=>(Hb N).join_reverse (HB N)) hs hb + have hp : ∃p : GenericLinePath C e (s.start C e) (s.finish C e),p.OnCutSide C pc e pos:= + ⟨GenericLinePath.single C e s,hh⟩ + obtain ⟨p,hp⟩:=hp + exact GenericLinePath.OnCutSide.reindex C pc e pos p hp + (segmentBetween_start C e _ _ _ _ _) (segmentBetween_finish C e _ _ _ _ _) + obtain ⟨p,hp⟩:=hx + obtain ⟨q,hq⟩:=hy + exact ⟨p.trans C e q,GenericLinePath.OnCutSide.trans C pc e pos p q hp hq⟩ +end Existence +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry RationalFiber +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance mutatedHalfspaceTransportRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutatedHalfspaceTransportAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutatedHalfspaceTransportAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +def endpointRatioPositive (a b : Module.Dual ℝ E) : CompletedPositive LaurentRay.vUnit Ω C := by + let A:=chartNegative LaurentRay.vUnit Ω C (a.toAddMonoidHom.comp e) (simpleTotalTransport Ω C) + let B:=chartNegative LaurentRay.vUnit Ω C (b.toAddMonoidHom.comp e) (simpleTotalTransport Ω C) + refine ⟨(negativeCovectorUnit Ω C coord hcoord pc e b* + (negativeCovectorUnit Ω C coord hcoord pc e a)⁻¹).val.val,?_,?_⟩ + · change constantCoeff (B.val*(completedInverse LaurentRay.vUnit Ω C A).val)=1 + rw [map_mul,B.property.1,(completedInverse LaurentRay.vUnit Ω C A).property.1,mul_one] + · exact SeriesGraded.mul LaurentRay.vUnit Ω C B.property.2 + (completedInverse LaurentRay.vUnit Ω C A).property.2 + +include hΩ he hS hcomp hdeg in +lemma endpointRatioPositive_nocut_cone {a b : Module.Dual ℝ E} (pos : Bool) + (p : GenericLinePath C e a b) (hs : p.OnCutSide C pc e pos) : + ∀n m,coeff n (endpointRatioPositive Ω C coord hcoord pc e a b).val m≠0 → + m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos) := by + change ∀n m,coeff n (negativeCovectorUnit Ω C coord hcoord pc e b* + (negativeCovectorUnit Ω C coord hcoord pc e a)⁻¹).val.val m≠0 → _ + induction p with + | nil=> + simp only [mul_inv_cancel] + exact series_support_addSubmonoid_one LaurentRay.vUnit Ω _ + | append s p ih=> + obtain ⟨hs,ht⟩:=hs + have hp:=ih ht + have hb:=noncutEndpointRatio_cone Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic pos s.lo s.hi s.ordered s.start_regular s.finish_regular hs + change ∀n m,coeff n (negativeCovectorUnit Ω C coord hcoord pc e (s.finish C e)* + (negativeCovectorUnit Ω C coord hcoord pc e (s.start C e))⁻¹).val.val m≠0 → _ at hb + have htel : (negativeCovectorUnit Ω C coord hcoord pc e (s.finish C e)* + (negativeCovectorUnit Ω C coord hcoord pc e (s.start C e))⁻¹)* + (negativeCovectorUnit Ω C coord hcoord pc e (s.start C e)* + (negativeCovectorUnit Ω C coord hcoord pc e a)⁻¹)= + negativeCovectorUnit Ω C coord hcoord pc e (s.finish C e)* + (negativeCovectorUnit Ω C coord hcoord pc e a)⁻¹ := by simp only [mul_assoc,inv_mul_cancel_left] + simpa only [←Units.val_mul,←Subring.coe_mul,htel] using + series_support_addSubmonoid_mul LaurentRay.vUnit Ω _ _ _ hb hp + +include hS hcomp in +theorem mutatedPathCompletion_rational_nocut {a b : Module.Dual ℝ E} (pos : Bool) + (p : GenericLinePath C e a b) (hs : p.OnCutSide C pc e pos) : + mutationSideAction LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω) pos + (rationalRegrade LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) (nonpDegree coord pc) (mutationSize Ω C pc+1) + (endpointRatioPositive Ω C coord hcoord pc e a b).val)= + rationalRegrade LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) + (nonpDegree (mutatedCoordinates Ω C coord pc) pc) (mutationSize Ω C pc+1) + (mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p) := by + rw [(mutatedPathCompletion_nocut Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg pos p hs).2] + exact mutation_rational_compatibility Ω hΩ C coord hcoord pc pos + (endpointRatioPositive Ω C coord hcoord pc e a b) + (endpointRatioPositive_nocut_cone Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg pos p hs) + +include hcoord hS hcomp in +theorem mutatedPathCompletion_nocut_loop {a : Module.Dual ℝ E} (pos : Bool) + (p : GenericLinePath C e a a) (hs : p.OnCutSide C pc e pos) : + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p=1 := by + rw [(mutatedPathCompletion_nocut Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg pos p hs).2] + simp only [mul_inv_cancel] + exact mutationCompletion_one Ω hΩ C coord pc pos LaurentRay.vUnit +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedIncomingNonpure.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedIncomingNonpure.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd355d44ff30ebd7202dffe8736f7c0d092cf2cc --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedIncomingNonpure.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationIncomingProbes + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +include hnd in +lemma mutatedIncoming_nonpure (r:M) (hr:e r≠0) + (hp:e (simpleRoot C pc)∉Submodule.span ℝ {e r}) + (ho:¬OnPositiveRay r (simpleRoot C pc)) + (hn:¬OnPositiveRay (mutationIncomingLabel Ω (simpleRoot C pc) r) + (simpleRoot (mutatedRoots Ω C pc) pc)) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (hA:∀n,0hA _ (Nat.succ_pos n) m hm) + (fun n _ m hm=>hB _ (Nat.succ_pos n) m hm) + (fun n nh m hm=>(Hreg n nh m hm).1) + (fun n nh m hm=>(Hreg n nh m hm).2) sx sy + (fun n nh m hm=>⟨fun h=>((Ho n nh m hm).1 h).1,fun h=>((Ho n nh m hm).2 h).1⟩) + (fun n nh m hm=>⟨fun h=>((Ho n nh m hm).1 h).2,fun h=>((Ho n nh m hm).2 h).2⟩) + (fun n nh m hm=>⟨fun h=>((Hn n nh m hm).1 h).1,fun h=>((Hn n nh m hm).2 h).1⟩) + (fun n nh m hm=>⟨fun h=>((Hn n nh m hm).1 h).2,fun h=>((Hn n nh m hm).2 h).2⟩) + hxr.le hyr + have HH:=mutation_incoming_log_read Ω hΩ C coord hcoord pc pos r d hs ho hn + rw [hlabel] at H HH + exact H.trans HH.symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedIncomingNonpureRoot.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedIncomingNonpureRoot.lean new file mode 100644 index 0000000000000000000000000000000000000000..db5dcf940ffafcdf5db99d058d304f1161c9654d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedIncomingNonpureRoot.lean @@ -0,0 +1,104 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedIncomingNonpure +import OAI.Combinatorics.Chromatic.Walls.MutatedAnchors + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +include hnd in +lemma mutatedIncoming_nonpure_root + (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + (s:M) (d:ℕ) (hd:0coeff d (FormalLog.log f) s) + (mutatedTransport_pure Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd HA HB ha hb) + change coeff d (FormalLog.log (pureFace Ω C' coord' pc T).val) s=_ at HH + rw [←pureFaceSeries_log Ω C' coord' hc pc,pureFaceSeries_apply,hz,ite_eq_left rfl] at HH + rw [literalIncomingRay_eq Ω _ hs,literalIncoming_simple Ω C' coord' hc pc] + exact HH +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedLineCompletion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedLineCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..6926853ddec150528fabcb0375866113c2d7bfa3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedLineCompletion.lean @@ -0,0 +1,213 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteRefinementImportAll + +namespace OAI + +section +namespace ElementaryPositivity.PowerSeriesAdjoint +open PowerSeries +noncomputable section +variable {A J : Type*} [Ring A] +lemma filter_product_coeff_congr (l : List J) (p : J → Bool) (f : J → PowerSeries A) (D : ℕ) + (h : ∀a∈l,p a=false → ∀n≤D,coeff n (f a)=coeff n 1) : + ∀n≤D,coeff n ((l.filter p).map f).prod=coeff n (l.map f).prod := by + induction l with + | nil=>exact fun _ _=>rfl + | cons a l ih=> + have ih':=ih (fun x hx hp=>h x (List.mem_cons_of_mem a hx) hp) + by_cases hp : p a=true + · simp only [List.filter_cons,hp,↓reduceIte,List.map_cons,List.prod_cons] + intro n hn + exact FormalLog.mul_coeff_congr _ _ _ _ n (fun _ _=>rfl) + (fun j hj=>ih' j (hj.trans hn)) + · have hp' : p a=false:=Bool.eq_false_iff.mpr hp + simp only [List.filter_cons,hp',Bool.false_eq_true,ite_false,List.map_cons,List.prod_cons] + intro n hn + rw [←one_mul (((l.filter p).map f).prod)] + exact FormalLog.mul_coeff_congr _ _ _ _ n + (fun j hj=>(h a (by simp) hp' j (hj.trans hn)).symm) + (fun j hj=>ih' j (hj.trans hn)) +end +end ElementaryPositivity.PowerSeriesAdjoint + +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma mutatedLineProduct_stabilizes (lo hi : ℝ) (D A N : ℕ) (hA : 1≤A) + (hDA : (mutationSize Ω C pc+1)*D≤A) (hAN : A≤N) : + ∀n≤D,coeff n (mutatedLineProduct Ω hΩ C coord pc e he L hdeg v k H lo hi A)= + coeff n (mutatedLineProduct Ω hΩ C coord pc e he L hdeg v k H lo hi N) := by + classical + unfold mutatedLineProduct + rw [←intervalEventList_filter C e v k lo hi hAN] + apply PowerSeriesAdjoint.filter_product_coeff_congr + intro a ha hp + exact mutatedLineFactor_high Ω hΩ C coord pc e he L hdeg v k H D A hA hDA a + (event_not_retained C e v k lo hi a ha (of_decide_eq_false hp)) + +def mutatedLineCompletion (lo hi : ℝ) : PowerSeries (Torus LaurentRay.vUnit Ω) := + PowerSeries.mk (fun d=>coeff d (mutatedLineProduct Ω hΩ C coord pc e he L hdeg v k H lo hi + (max 1 ((mutationSize Ω C pc+1)*d)))) + +lemma mutatedLineCompletion_coeff (lo hi : ℝ) (d N : ℕ) (hN : 1≤N) + (hdN : (mutationSize Ω C pc+1)*d≤N) : + coeff d (mutatedLineCompletion Ω hΩ C coord pc e he L hdeg v k H lo hi)= + coeff d (mutatedLineProduct Ω hΩ C coord pc e he L hdeg v k H lo hi N) := by + simp only [mutatedLineCompletion,PowerSeries.coeff_mk] + exact mutatedLineProduct_stabilizes Ω hΩ C coord pc e he L hdeg v k H lo hi d + (max 1 ((mutationSize Ω C pc+1)*d)) N (le_max_left _ _) (le_max_right _ _) + (max_le hN hdN) d le_rfl +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {A : Type*} [Ring A] +lemma orientPowerSeries_constant (b : Bool) (f : PowerSeries A) (hf : constantCoeff f=1) : + constantCoeff (orientPowerSeries b f)=1 := by + cases b + · simp only [orientPowerSeries,Bool.false_eq_true,ite_false,constantCoeff_invOfUnit, + inv_one,Units.val_one] + · exact hf +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +omit [DecidableEq I] in +lemma orientPowerSeries_graded (b : Bool) (f : PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf : SeriesGraded LaurentRay.vUnit Ω C f) : + SeriesGraded LaurentRay.vUnit Ω C (orientPowerSeries b f) := by + cases b + · exact hf.inverse LaurentRay.vUnit Ω C + · exact hf + +lemma mutationCompletion_inverse (pos : Bool) (f : PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf : RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) + (mutationSize Ω C pc+1) f) (hc : constantCoeff f=1) : + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (invOfUnit f 1)= + invOfUnit (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f) 1 := by + let g:=mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f + let gi:=mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (invOfUnit f 1) + have hleft : gi*g=1:=mutationCompletion_inverse_mul Ω hΩ C coord pc pos LaurentRay.vUnit hf hc + have hright : g*invOfUnit g 1=1:=PowerSeries.mul_invOfUnit g 1 + (mutationCompletion_constant Ω hΩ C coord pc pos LaurentRay.vUnit f hc) + change gi=invOfUnit g 1 + calc gi=gi*1:=(mul_one gi).symm + _=gi*(g*invOfUnit g 1):=by rw [hright] + _=(gi*g)*invOfUnit g 1:=(mul_assoc _ _ _).symm + _=invOfUnit g 1:=by rw [hleft,one_mul] + +include hcoord in +lemma mutationCompletion_orient_graded (pos b : Bool) (f : CompletedPositive LaurentRay.vUnit Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + SeriesGraded LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (orientPowerSeries b f.val)) := by + have hg : SeriesGraded LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f.val):= + mutationCompletion_graded Ω hΩ C coord hcoord pc pos LaurentRay.vUnit f hf + cases b + · simp only [orientPowerSeries,Bool.false_eq_true,ite_false] + rw [mutationCompletion_inverse Ω hΩ C coord pc pos f.val + (mutationCompletion_bound Ω hΩ C coord hcoord pc pos LaurentRay.vUnit f hf) f.property.1] + exact hg.inverse LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + · exact hg + +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) +lemma mutatedLineFactor_constant (a : ℝ) : + constantCoeff (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H a)=1 := by + classical + unfold mutatedLineFactor + split + · split + · exact orientPowerSeries_constant _ _ (normalizedSimple_constant Ω _) + · exact mutationCompletion_constant Ω hΩ C coord pc _ LaurentRay.vUnit _ + (orientPowerSeries_constant _ _ (chartZero _ _ _ _ _).property.1) + · exact constantCoeff_one + +include hcoord hS hcomp in +lemma mutatedLineFactor_graded (a : ℝ) : + SeriesGraded LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H a) := by + classical + unfold mutatedLineFactor + split + · next ha=> + split + · apply orientPowerSeries_graded + rw [←simpleDatum_value Ω (mutatedRoots Ω C pc) pc] + exact WallUnitDatum.graded Ω _ (fun _=>True) _ (simpleDatum_allowed _ pc) + · next hp=> + let data:=lineRayData C e he L hdeg v k H a ha + apply mutationCompletion_orient_graded Ω hΩ C coord hcoord pc + exact simple_fiber_bound Ω C coord hcoord pc e he S hS hcomp L hdeg + data.root data.degree data.degree_pos data.root_degree (k+a • v) data.generic _ + (cutSide_decide ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc) hp) + · exact SeriesGraded.one LaurentRay.vUnit Ω _ + +lemma mutatedLineProduct_constant (lo hi : ℝ) (N : ℕ) : + constantCoeff (mutatedLineProduct Ω hΩ C coord pc e he L hdeg v k H lo hi N)=1 := by + unfold mutatedLineProduct + induction intervalEventList C e v k lo hi N with + | nil=>simp + | cons a l ih=> + simp only [List.map_cons,List.prod_cons,map_mul,mutatedLineFactor_constant,one_mul,ih] + +include hcoord hS hcomp in +lemma mutatedLineProduct_graded (lo hi : ℝ) (N : ℕ) : + SeriesGraded LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (mutatedLineProduct Ω hΩ C coord pc e he L hdeg v k H lo hi N) := by + unfold mutatedLineProduct + induction intervalEventList C e v k lo hi N with + | nil=>exact SeriesGraded.one LaurentRay.vUnit Ω _ + | cons a l ih=> + exact (mutatedLineFactor_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a).mul + LaurentRay.vUnit Ω _ ih + +lemma mutatedLineCompletion_constant (lo hi : ℝ) : + constantCoeff (mutatedLineCompletion Ω hΩ C coord pc e he L hdeg v k H lo hi)=1 := by + rw [←coeff_zero_eq_constantCoeff_apply,mutatedLineCompletion_coeff Ω hΩ C coord pc e he L hdeg v k H lo hi 0 1 le_rfl (by omega), + coeff_zero_eq_constantCoeff_apply,mutatedLineProduct_constant] + +include hcoord hS hcomp in +lemma mutatedLineCompletion_graded (lo hi : ℝ) : + SeriesGraded LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (mutatedLineCompletion Ω hΩ C coord pc e he L hdeg v k H lo hi) := by + intro d + rw [mutatedLineCompletion_coeff Ω hΩ C coord pc e he L hdeg v k H lo hi d + (max 1 ((mutationSize Ω C pc+1)*d)) (le_max_left _ _) (le_max_right _ _)] + exact mutatedLineProduct_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi _ d + +def mutatedLineCompletedPositive (lo hi : ℝ) : CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc) := + ⟨mutatedLineCompletion Ω hΩ C coord pc e he L hdeg v k H lo hi, + mutatedLineCompletion_constant Ω hΩ C coord pc e he L hdeg v k H lo hi, + mutatedLineCompletion_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi⟩ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedNoCutTransport.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedNoCutTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d93463ffb208f761137aa13d3139253fb10e881 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedNoCutTransport.lean @@ -0,0 +1,236 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedPathCompletion + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry RationalFiber +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance mutatedNoCutTransportRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutatedNoCutTransportAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutatedNoCutTransportAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) + +lemma mutatedLineProduct_nocut_eq (pos : Bool) (lo hi : ℝ) (N : ℕ) + (hs : ∀a∈intervalEventList C e v k lo hi N, + cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) : + mutatedLineProduct Ω hΩ C coord pc e he L hdeg v k H lo hi N= + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit + (comparisonWordOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineWord Ω C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N)).val.val := by + classical + let U:=fun a=>comparisonOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a) + have HH : ∀l : List ℝ, (∀a∈l,cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) → + RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) + (l.map U).prod.val.val ∧ + (l.map (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H)).prod= + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (l.map U).prod.val.val := by + intro l + induction l with + | nil=> + intro _ + exact ⟨RegradeBound.one _ _ _ _,(mutationCompletion_one Ω hΩ C coord pc pos LaurentRay.vUnit).symm⟩ + | cons a l ih=> + intro hl + obtain ⟨ht,ih⟩:=ih (fun b hb=>hl b (List.mem_cons_of_mem a hb)) + have ha:=hl a (by simp) + have heq : noncutOldLineFactor Ω C e he L hdeg v k H a=(U a).val.val:= + noncutOldLineFactor_comparison Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H pos a ha + have hb : RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) + (mutationSize Ω C pc+1) (U a).val.val:=by + rw [←heq] + exact noncutOldLineFactor_bound Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H pos a ha + have hf:=mutatedLineFactor_nocut Ω hΩ C coord pc e he L hdeg v k H pos a ha + rw [heq] at hf + change RegradeBound _ _ _ _ ((U a).val.val*(l.map U).prod.val.val) ∧ + mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H a* + (l.map (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H)).prod=_ + refine ⟨hb.mul _ _ _ _ ht,?_⟩ + rw [hf,ih,←mutationCompletion_mul Ω hΩ C coord pc pos LaurentRay.vUnit hb ht] + rfl + simpa only [mutatedLineProduct,comparisonWordOld,actualLineWord,List.map_map,Function.comp_def] + using (HH (intervalEventList C e v k lo hi N) hs).2 + +include hS hcomp in +lemma mutatedLineCompletion_nocut (pos : Bool) (lo hi : ℝ) (horder : lo.mp ha + have hab:=(Finset.mem_filter.mp haF).2 + exact hs a hab.1 hab.2 + rw [mutatedLineProduct_nocut_eq Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H pos lo hi N hsN] + apply mutationCompletion_congr_through Ω hΩ C coord pc pos LaurentRay.vUnit _ _ d N hdN + have ht:=actualLine_old_transport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N + (hlo N) (hhi N) horder + have HH:=oldCoefficientsEqual_mul Ω coord pc N _ _ + (lineNegativeUnit Ω C coord hcoord pc e v k lo)⁻¹ + (lineNegativeUnit Ω C coord hcoord pc e v k lo)⁻¹ ht (fun _ _=>rfl) + simpa only [mul_assoc,mul_inv_cancel,mul_one,oldCoefficientsEqual] using HH +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry RationalFiber +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance mutatedNoCutTransportPathRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutatedNoCutTransportPathAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutatedNoCutTransportPathAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) + +lemma noncutComparisonWord_bound (pos : Bool) (lo hi : ℝ) (N : ℕ) + (hs : ∀a∈intervalEventList C e v k lo hi N, + cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) : + RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) + (comparisonWordOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineWord Ω C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N)).val.val := by + let U:=fun a=>comparisonOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a) + have HH : ∀l : List ℝ, (∀a∈l,cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) → + RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) + (l.map U).prod.val.val := by + intro l + induction l with + | nil=>intro _; exact RegradeBound.one _ _ _ _ + | cons a l ih=> + intro hl + have ha:=hl a (by simp) + have hb:=noncutOldLineFactor_bound Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H pos a ha + rw [noncutOldLineFactor_comparison Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H pos a ha] at hb + exact hb.mul _ _ _ _ (ih (fun b hh=>hl b (List.mem_cons_of_mem a hh))) + simpa only [comparisonWordOld,actualLineWord,List.map_map,Function.comp_def] using + HH (intervalEventList C e v k lo hi N) hs + +include hΩ he hS hcomp hdeg H in +lemma noncutEndpointRatio_bound (pos : Bool) (lo hi : ℝ) (ho : lo.mp hh + have hab:=(Finset.mem_filter.mp hhF).2 + exact hs a hab.1 hab.2 + have hbnd:=noncutComparisonWord_bound Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H pos lo hi n hsN + have ht:=actualLine_old_transport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi n + (ha n) (hb n) ho + have HH:=oldCoefficientsEqual_mul Ω coord pc n _ _ + (lineNegativeUnit Ω C coord hcoord pc e v k lo)⁻¹ + (lineNegativeUnit Ω C coord hcoord pc e v k lo)⁻¹ ht (fun _ _=>rfl) + simp only [mul_assoc,mul_inv_cancel,mul_one] at HH + apply hbnd n m + rw [HH n le_rfl] + exact hm + +def negativeCovectorUnit (a : Module.Dual ℝ E) := completedBiUnit LaurentRay.vUnit Ω C coord hcoord pc + (chartNegative LaurentRay.vUnit Ω C (a.toAddMonoidHom.comp e) (simpleTotalTransport Ω C)) + +def GenericLinePath.OnCutSide (pos : Bool) {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) : Prop := + match p with + | .nil _=>True + | .append s p=>(∀t,s.lo + simp only [mul_inv_cancel] + exact ⟨RegradeBound.one _ _ _ _,(mutationCompletion_one Ω hΩ C coord pc pos LaurentRay.vUnit).symm⟩ + | append s p ih=> + obtain ⟨hs,ht⟩:=hs + obtain ⟨hp,ih⟩:=ih ht + have hb:=noncutEndpointRatio_bound Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic pos s.lo s.hi s.ordered s.start_regular s.finish_regular hs + have heq:=mutatedLineCompletion_nocut Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic pos s.lo s.hi s.ordered s.start_regular s.finish_regular hs + change RegradeBound _ _ _ _ + (negativeCovectorUnit Ω C coord hcoord pc e (s.finish C e)* + (negativeCovectorUnit Ω C coord hcoord pc e (s.start C e))⁻¹).val.val at hb + change mutatedLineCompletion Ω hΩ C coord pc e he L hdeg s.direction s.offset s.generic s.lo s.hi= + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit + (negativeCovectorUnit Ω C coord hcoord pc e (s.finish C e)* + (negativeCovectorUnit Ω C coord hcoord pc e (s.start C e))⁻¹).val.val at heq + have htel : (negativeCovectorUnit Ω C coord hcoord pc e (s.finish C e)* + (negativeCovectorUnit Ω C coord hcoord pc e (s.start C e))⁻¹)* + (negativeCovectorUnit Ω C coord hcoord pc e (s.start C e)* + (negativeCovectorUnit Ω C coord hcoord pc e a)⁻¹)= + negativeCovectorUnit Ω C coord hcoord pc e (s.finish C e)* + (negativeCovectorUnit Ω C coord hcoord pc e a)⁻¹ := by simp only [mul_assoc,inv_mul_cancel_left] + refine ⟨?_,?_⟩ + · simpa only [←Units.val_mul,←Subring.coe_mul,htel] using hb.mul _ _ _ _ hp + · change mutatedLineCompletion Ω hΩ C coord pc e he L hdeg s.direction s.offset s.generic s.lo s.hi* + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p=_ + rw [heq,ih,←mutationCompletion_mul Ω hΩ C coord pc pos LaurentRay.vUnit hb hp] + exact congrArg (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit) + (congrArg (fun u=>u.val.val) htel) + +include hcoord hS hcomp in +theorem mutatedPathCompletion_nocut_independent {a b : Module.Dual ℝ E} (pos : Bool) + (p q : GenericLinePath C e a b) (hp : p.OnCutSide C pc e pos) (hq : q.OnCutSide C pc e pos) : + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p= + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg q := + (mutatedPathCompletion_nocut Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg pos p hp).2.trans + (mutatedPathCompletion_nocut Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg pos q hq).2.symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPathCompletion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPathCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..03171e1f9bf2f1cc4a9f1148052bf8c4d668b595 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPathCompletion.lean @@ -0,0 +1,200 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.GenericLineJoining + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +def mutatedPathProduct {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) (N : ℕ) : + PowerSeries (Torus LaurentRay.vUnit Ω) := + match p with + | .nil _=>1 + | .append s p=>mutatedLineProduct Ω hΩ C coord pc e he L hdeg s.direction s.offset s.generic s.lo s.hi N* + mutatedPathProduct p N + +def mutatedPathCompletion {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) : + PowerSeries (Torus LaurentRay.vUnit Ω) := + match p with + | .nil _=>1 + | .append s p=>mutatedLineCompletion Ω hΩ C coord pc e he L hdeg s.direction s.offset s.generic s.lo s.hi* + mutatedPathCompletion p + +lemma mutatedPathCompletion_coeff {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) + (D N : ℕ) (hN : 1≤N) (hDN : (mutationSize Ω C pc+1)*D≤N) : + ∀d≤D,coeff d (mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p)= + coeff d (mutatedPathProduct Ω hΩ C coord pc e he L hdeg p N) := by + induction p with + | nil=>exact fun _ _=>rfl + | append s p ih=> + intro d hd + apply FormalLog.mul_coeff_congr + · intro j hj + exact mutatedLineCompletion_coeff Ω hΩ C coord pc e he L hdeg s.direction s.offset s.generic + s.lo s.hi j N hN ((Nat.mul_le_mul_left _ (hj.trans hd)).trans hDN) + · intro j hj + exact ih j (hj.trans hd) + +lemma mutatedPathCompletion_trans {a b c : Module.Dual ℝ E} + (p : GenericLinePath C e a b) (q : GenericLinePath C e b c) : + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg (p.trans C e q)= + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg q* + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p := by + induction q with + | nil=>exact (one_mul _).symm + | append s q ih=> + simp only [GenericLinePath.trans,mutatedPathCompletion,ih,mul_assoc] + +lemma mutatedPathCompletion_constant {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) : + constantCoeff (mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p)=1 := by + induction p with + | nil=>exact constantCoeff_one + | append s p ih=> + simp only [mutatedPathCompletion,map_mul,mutatedLineCompletion_constant,ih,one_mul] + +variable (hcoord : ∀d,coord (C d)=d) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +include hcoord hS hcomp in +lemma mutatedPathCompletion_graded {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) : + SeriesGraded LaurentRay.vUnit Ω (mutatedRoots Ω C pc) + (mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p) := by + induction p with + | nil=>exact SeriesGraded.one LaurentRay.vUnit Ω _ + | append s p ih=> + exact (mutatedLineCompletion_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi).mul LaurentRay.vUnit Ω _ ih + +def mutatedPathCompletedPositive {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) : + CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc) := + ⟨mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p, + mutatedPathCompletion_constant Ω hΩ C coord pc e he L hdeg p, + mutatedPathCompletion_graded Ω hΩ C coord pc e he L hdeg hcoord S hS hcomp p⟩ +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry RationalFiber +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +lemma mutationCompletion_list_prod (pos : Bool) (l : List (PowerSeries (Torus LaurentRay.vUnit Ω))) + (h : ∀f∈l,RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) + (mutationSize Ω C pc+1) f) : + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit l.prod= + (l.map (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit)).prod := by + have H : RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) + (mutationSize Ω C pc+1) l.prod ∧ + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit l.prod= + (l.map (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit)).prod := by + induction l with + | nil=>exact ⟨RegradeBound.one _ _ _ _,mutationCompletion_one Ω hΩ C coord pc pos LaurentRay.vUnit⟩ + | cons f l ih=> + obtain ⟨hl,he⟩:=ih (fun x hx=>h x (List.mem_cons_of_mem f hx)) + have hf:=h f (by simp) + refine ⟨hf.mul _ _ _ _ hl,?_⟩ + rw [List.prod_cons,mutationCompletion_mul Ω hΩ C coord pc pos LaurentRay.vUnit hf hl,he] + rfl + exact H.2 + +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) + +def noncutOldLineFactor (a : ℝ) : PowerSeries (Torus LaurentRay.vUnit Ω) := by + classical + exact if ha : ∃N,a∈lineEvents (realRootsThrough e C N) v k then + let data:=lineRayData C e he L hdeg v k H a ha + orientPowerSeries (decide (v (e data.root)<0)) + (chartZero LaurentRay.vUnit Ω C ((k+a • v).toAddMonoidHom.comp e) (simpleTotalTransport Ω C)).val + else 1 + +lemma cutSide_decision (pos : Bool) (h : M →+ ℝ) (p : M) (hs : cutSide pos h p) : + h p≠0 ∧ decide (0simp only; rw [hpos] + · next ha=>exact (mutationCompletion_one Ω hΩ C coord pc pos LaurentRay.vUnit).symm + +include hΩ hcoord hS hcomp in +lemma noncutOldLineFactor_bound (pos : Bool) (a : ℝ) + (hs : cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) : + RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) + (noncutOldLineFactor Ω C e he L hdeg v k H a) := by + classical + unfold noncutOldLineFactor + split + · next ha=> + let data:=lineRayData C e he L hdeg v k H a ha + have hf:=simple_fiber_bound Ω C coord hcoord pc e he S hS hcomp L hdeg + data.root data.degree data.degree_pos data.root_degree (k+a • v) data.generic pos hs + have hb:=mutationCompletion_bound Ω hΩ C coord hcoord pc pos LaurentRay.vUnit _ hf + change RegradeBound _ _ _ _ (orientPowerSeries (decide (v (e data.root)<0)) _) + cases hb' : decide (v (e data.root)<0) + · exact hb.invOfUnit LaurentRay.vUnit Ω _ _ + · exact hb + · exact RegradeBound.one _ _ _ _ + +include hcoord hS hcomp in +lemma noncutOldLineFactor_comparison (pos : Bool) (a : ℝ) + (hs : cutSide pos ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc)) : + noncutOldLineFactor Ω C e he L hdeg v k H a= + (comparisonOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a)).val.val := by + classical + have hp:=(cutSide_decision pos _ _ hs).1 + change (k+a • v) (e (simpleRoot C pc))≠0 at hp + unfold noncutOldLineFactor actualLineLetter + split + · next ha=> + simp only + let data:=lineRayData C e he L hdeg v k H a ha + cases hh : decide (v (e data.root)<0) <;> + simp only [orientPowerSeries,orientedBounded,Bool.false_eq_true,ite_false,ite_true, + comparisonOld,completedBiUnit_val] + all_goals rfl + · next ha=>simp only [comparisonOld]; rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPathIndependent.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPathIndependent.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d97ef3340aac9177e65070caa81f84e66b8a2d9 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPathIndependent.lean @@ -0,0 +1,200 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.LaurentCompletionFaithful + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry RationalFiber +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) +local instance mutatedPathIndependentRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutatedPathIndependentAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutatedPathIndependentAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +include hcoord hS hcomp hnd in +lemma mutatedPathCompletion_independent {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (p q : GenericLinePath C e a b) : + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p= + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg q := by + obtain ⟨r⟩:=generic_path_exists C e b a HB HA + have H1:=mutatedPathCompletion_loop Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd (p.trans C e r) + have H2:=mutatedPathCompletion_loop Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd (r.trans C e q) + rw [mutatedPathCompletion_trans] at H1 H2 + calc + _ = 1*mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p := (one_mul _).symm + _ = (mutatedPathCompletion Ω hΩ C coord pc e he L hdeg q* + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg r)* + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p := by rw [H2] + _ = mutatedPathCompletion Ω hΩ C coord pc e he L hdeg q*1 := by rw [mul_assoc,H1] + _ = _ := mul_one _ + +def mutatedTransport {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) : + CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc) := + mutatedPathCompletedPositive Ω hΩ C coord pc e he L hdeg hcoord S hS hcomp + (Classical.choice (generic_path_exists C e a b HA HB)) + +include hnd in +lemma mutatedTransport_eq_path {a b : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (p : GenericLinePath C e a b) : + (mutatedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HB).val= + mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p := + mutatedPathCompletion_independent Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd HA HB _ p + +include hnd in +lemma mutatedTransport_self {a : Module.Dual ℝ E} (HA : RegularCovector C e a) : + (mutatedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HA).val=1 := + mutatedPathCompletion_loop Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd _ + +include hnd in +lemma mutatedTransport_trans {a b c : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) (HC : RegularCovector C e c) : + (mutatedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HC).val= + (mutatedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HB HC).val* + (mutatedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HB).val := by + let p:=Classical.choice (generic_path_exists C e a b HA HB) + let q:=Classical.choice (generic_path_exists C e b c HB HC) + rw [mutatedTransport_eq_path Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd HA HC (p.trans C e q)] + exact mutatedPathCompletion_trans Ω hΩ C coord pc e he L hdeg p q +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd:∀r≠0,∃m,Ω r m≠0) +local instance mutatedPathIndependentPureRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutatedPathIndependentPureAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutatedPathIndependentPureAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +include hcoord hS hcomp in +omit [FiniteDimensional ℝ E] in +lemma mutatedPathCompletion_pure {a b:Module.Dual ℝ E} (p:GenericLinePath C e a b) : + pureFaceSeries Ω (mutatedCoordinates Ω C coord pc) pc + (mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p)* + pureCutGauge (normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) pc)) + (decide (0rw [mutatedPathCompletion,pureFaceSeries_one,one_mul] + | append s p ih=> + rw [mutatedPathCompletion,pureFaceSeries_mul Ω (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) (mutatedCoordinates_retraction Ω C coord hcoord pc) pc _ _ + (mutatedLineCompletion_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi) + (mutatedPathCompletion_graded Ω hΩ C coord pc e he L hdeg hcoord S hS hcomp p), + mul_assoc,ih] + exact mutatedLineCompletion_pure Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi s.ordered (s.start_regular 1) (s.finish_regular 1) + +include hnd in +lemma mutatedTransport_pure {a b:Module.Dual ℝ E} + (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (ha:a (e (simpleRoot C pc))<0) (hb:0True + | .append s p=>(∀t,s.lo≤t → t ≤ s.hi → s.offset+t • s.direction∈U) ∧ p.InRegion U + +lemma GenericLinePath.InRegion.trans {U : Set (Module.Dual ℝ E)} {a b c : Module.Dual ℝ E} + {p : GenericLinePath C e a b} {q : GenericLinePath C e b c} + (hp : p.InRegion C e U) (hq : q.InRegion C e U) : + (p.trans C e q).InRegion C e U := by + induction q with + | nil=>exact hp + | append s q ih=>exact ⟨hq.1,ih hq.2⟩ + +lemma GenericLinePath.InRegion.castEnds {U : Set (Module.Dual ℝ E)} + {a b a' b' : Module.Dual ℝ E} (h0 : a=a') (h1 : b=b') + {p : GenericLinePath C e a b} (hp : p.InRegion C e U) : + (p.castEnds C e h0 h1).InRegion C e U := by + subst a'; subst b'; exact hp + +lemma segmentBetween_inRegion {U : Set (Module.Dual ℝ E)} (a b : Module.Dual ℝ E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (H : ∀N,GenericOffset (realRootsThrough e C N) 0 (b-a) a) + (hU : ∀t:ℝ,0≤t → t≤1 → (1-t) • a+t • b∈U) : + (GenericLinePath.single C e (segmentBetween C e a b HA HB H)).InRegion C e U := by + refine ⟨?_,trivial⟩ + intro t hlo hhi + change a+t • (b-a)∈U + have heq : a+t • (b-a)=(1-t) • a+t • b := by + module + rw [heq] + exact hU t hlo hhi +end + +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +lemma generic_region_path_via (a b k : Module.Dual ℝ E) (P : Finset E) + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (U : Set (Module.Dual ℝ E)) + (hU : ∀h : Module.Dual ℝ E, + (∀x∈P,(0(Ha N).join (HA N)) + let t:=segmentBetween C e h b HH HB (fun N=>(Hb N).join_reverse (HB N)) + let p:=(GenericLinePath.single C e s).castEnds C e + (segmentBetween_start C e a h HA HH _) (segmentBetween_finish C e a h HA HH _) + let q:=(GenericLinePath.single C e t).castEnds C e + (segmentBetween_start C e h b HH HB _) (segmentBetween_finish C e h b HH HB _) + have hp : p.InRegion C e U := + (segmentBetween_inRegion C e a h HA HH _ (hU h HP).1).castEnds C e _ _ + have hq : q.InRegion C e U := + (segmentBetween_inRegion C e h b HH HB _ (hU h HP).2).castEnds C e _ _ + exact ⟨p.trans C e q,hp.trans C e hq⟩ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPureLine.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPureLine.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b2ee71f23be489a2917e4a1774f1ccbbc676b27 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedPureLine.lean @@ -0,0 +1,216 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutatedPureFace +import OAI.Combinatorics.Chromatic.Walls.InfinityLine + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k:Module.Dual ℝ E) (H:∀N,GenericOffset (realRootsThrough e C N) 0 v k) +local instance mutatedPureLineRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutatedPureLineAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutatedPureLineAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +include hcoord in +lemma pureFaceSeries_product {J:Type*} (l:List J) (f:J → PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf:∀a∈l,SeriesGraded LaurentRay.vUnit Ω C (f a)) : + pureFaceSeries Ω coord pc (l.map f).prod=(l.map (fun a=>pureFaceSeries Ω coord pc (f a))).prod := by + induction l with + | nil=>exact pureFaceSeries_one Ω coord pc + | cons a l ih=> + simp only [List.map_cons,List.prod_cons] + rw [pureFaceSeries_mul Ω C coord hcoord pc _ _ (hf a (by simp)) + (SeriesGraded.list_prod Ω C l f (fun a ha=>hf a (by simp [ha]))), + ih (fun a ha=>hf a (by simp [ha]))] + +include hcoord hS hcomp in +lemma mutatedLineProduct_pure (lo hi:ℝ) (hlohi:lomutatedLineFactor_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a)] + have heq:(fun a=>pureFaceSeries Ω (mutatedCoordinates Ω C coord pc) pc + (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H a))= + (fun a=>if k (e (simpleRoot C pc))+a*v (e (simpleRoot C pc))=0 then + orientPowerSeries (!(decide (v (e (simpleRoot C pc))<0))) + (normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) pc)) else 1):=by + funext a + simpa only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] using + mutatedLineFactor_pure Ω C coord hcoord pc hΩ e he S hS hcomp L hdeg v k H a + rw [heq] + apply pureCut_telescope _ (normalizedSimple_constant Ω _) + (k (e (simpleRoot C pc))) (v (e (simpleRoot C pc))) lo hi hlohi + (Or.inl (RationalFiber.line_cut_offset_ne C pc e L hdeg v k H)) + · exact fun hz=>hlo (RationalFiber.line_cut_event C pc e L hdeg v k H lo hz) + · exact fun hz=>hhi (RationalFiber.line_cut_event C pc e L hdeg v k H hi hz) + · exact fun a ha=>(Finset.mem_filter.mp ha).2 + · intro a hla hah hz + exact Finset.mem_filter.mpr ⟨lineEvents_mono (realRootsThrough_mono C e hN) v k + (RationalFiber.line_cut_event C pc e L hdeg v k H a hz),hla,hah⟩ + +include hcoord hS hcomp in +lemma mutatedLineCompletion_pure (lo hi:ℝ) (hlohi:lorfl +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries RationalFiber +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (v : (LaurentSeries ℚ)ˣ) +local instance mutatedPureLineProductRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance mutatedPureLineProductAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance mutatedPureLineProductAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def completedProduct (l : List (CompletedPositive v Ω C)) : CompletedPositive v Ω C := + l.foldr (completedMul v Ω C) (completedOne v Ω C) + +omit [DecidableEq I] in +lemma completedProduct_val (l : List (CompletedPositive v Ω C)) : + (completedProduct Ω C v l).val=(l.map (fun F=>F.val)).prod := by + induction l with + | nil=>rfl + | cons a l ih=>exact congrArg (fun x=>a.val*x) ih + +lemma infinityCompletedUnit_product (l : List (CompletedPositive v Ω (mutatedRoots Ω C pc))) : + infinityCompletedUnit Ω C coord hcoord pc v (completedProduct Ω (mutatedRoots Ω C pc) v l)= + (l.map (infinityCompletedUnit Ω C coord hcoord pc v)).prod := by + induction l with + | nil=>exact infinityCompletedUnit_one Ω C coord hcoord pc v _ rfl + | cons a l ih=> + rw [List.map_cons,List.prod_cons,←ih] + exact infinityCompletedUnit_mul Ω C coord hcoord pc v _ _ _ rfl +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) +local instance mutatedPureLineFiberRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutatedPureLineFiberAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutatedPureLineFiberAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +def actualInfinityLineProductUnit (lo hi : ℝ) (N : ℕ) : + (PowerSeries (HahnSeries ℤ (Torus LaurentRay.vUnit Ω)))ˣ := + ((intervalEventList C e v k lo hi N).map + (actualInfinityLineUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H)).prod + +def mutatedLineProductPositive (lo hi : ℝ) (N : ℕ) : + CompletedPositive LaurentRay.vUnit Ω (mutatedRoots Ω C pc) := + ⟨mutatedLineProduct Ω hΩ C coord pc e he L hdeg v k H lo hi N, + mutatedLineProduct_constant Ω hΩ C coord pc e he L hdeg v k H lo hi N, + mutatedLineProduct_graded Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N⟩ + +lemma actualInfinityLineProductUnit_eq (lo hi : ℝ) (N : ℕ) : + actualInfinityLineProductUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N= + infinityCompletedUnit Ω C coord hcoord pc LaurentRay.vUnit + (mutatedLineProductPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N) := by + let l:=(intervalEventList C e v k lo hi N).map + (mutatedLineFactorPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H) + have heq : mutatedLineProductPositive Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H lo hi N= + completedProduct Ω (mutatedRoots Ω C pc) LaurentRay.vUnit l := by + apply Subtype.ext + rw [completedProduct_val] + simp only [l,List.map_map,Function.comp_def] + rfl + rw [heq,infinityCompletedUnit_product] + simp only [l,List.map_map,Function.comp_def] + rfl + +lemma actualInfinityLine_product_square (lo hi : ℝ) (hlohi : lohlo (line_cut_event C pc e L hdeg v k H lo hh) + have hh : (k+hi • v) (e (simpleRoot C pc))≠0 := + fun hz=>hhi (line_cut_event C pc e L hdeg v k H hi hz) + have HT:=AffineCut.telescope_sort (k (e (simpleRoot C pc))) (v (e (simpleRoot C pc))) + (Or.inl (line_cut_offset_ne C pc e L hdeg v k H)) + (fun a=>comparisonAction LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a)) + (fun a=>innerHom (actualInfinityLineUnit Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a)) + (fun pos=>infinitySideHom LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) pos) + (intervalLineEvents C e v k lo hi N) lo hi hlohi + (fun a ha=>(Finset.mem_filter.mp ha).2) + (by + intro a hla hah hz + apply Finset.mem_filter.mpr + exact ⟨lineEvents_mono (realRootsThrough_mono C e hN) v k + (line_cut_event C pc e L hdeg v k H a hz),hla,hah⟩) + (fun a _=>actualInfinityLine_square Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a) x + rw [(AffineCut.sides_eq_of_ne _ _ lo hl).2,(AffineCut.sides_eq_of_ne _ _ hi hh).1] at HT + simpa only [actualInfinityLineProductUnit,←innerHom_foldr,List.foldr_map, + comparisonWordAction,actualLineWord,intervalEventList,LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] using HT +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutatedWallKernel.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedWallKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2988477ed37a96653241fe87034d84a178eecb1 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutatedWallKernel.lean @@ -0,0 +1,129 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.GeometricMutationLines +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationOrientedCompatibility + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (u : Rˣ) (Ω : M →+ M →+ ℤ) +local instance : Ring (Torus u Ω) := Torus.instRing u Ω +local instance : AddCommMonoid (Torus u Ω) := (Torus.instRing u Ω).toAddCommMonoid +local instance : AddGroup (Torus u Ω) := (Torus.instRing u Ω).toAddGroup +lemma orientPowerSeries_submonoid (P : AddSubmonoid M) (b : Bool) + (f : PowerSeries (Torus u Ω)) (hf : ∀n m,coeff n f m≠0 → m∈P) : + ∀n m,coeff n (orientPowerSeries b f) m≠0 → m∈P := by + cases b + · exact inverse_support_addSubmonoid u Ω P f hf + · exact hf +lemma one_kernel_support (h : M →+ ℝ) (n : ℕ) (m : M) + (hm : coeff n (1 : PowerSeries (Torus u Ω)) m≠0) : h m=0 := by + by_cases hn : n=0 + · subst n + rw [coeff_zero_eq_constantCoeff_apply,constantCoeff_one] at hm + have hm0 : m=0:=by + by_contra hh + exact hm (Finsupp.single_eq_of_ne hh) + simp [hm0] + · rw [coeff_one,ite_eq_right hn] at hm + exact (hm rfl).elim + +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (C : (I → ℤ) →+ M) +omit [DecidableEq I] in +lemma chartZero_kernel_support (h : M →+ ℝ) (T : CompletedPositive u Ω C) : + ∀n m,coeff n (chartZero u Ω C h T).val m≠0 → h m=0 := by + intro n m hm + cases n with + | zero => + rw [coeff_zero_eq_constantCoeff_apply,(chartZero u Ω C h T).property.1] at hm + have hm0 : m=0:=by + by_contra hh + exact hm (Finsupp.single_eq_of_ne hh) + simp [hm0] + | succ n => exact (chart_three_support u Ω C h T).2.1 n m hm +end + +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma normalizedSimple_kernel_support (h : M →+ ℝ) (r : M) (hr : h r=0) : + ∀n m,coeff n (normalizedSimple Ω r) m≠0 → h m=0 := by + intro n m hm + rw [normalizedSimple,coeff_raySeries] at hm + have heq : m=n • r:=by + by_contra hh + exact hm (Finsupp.single_eq_of_ne hh) + rw [heq,map_nsmul,hr,nsmul_zero] + +include hS hcomp in +lemma mutationCompletion_kernel_support (pos : Bool) (h : Module.Dual ℝ E) + (f : PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf : ∀n m,coeff n f m≠0 → h (e m)=0) : + ∀n m,coeff n (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f) m≠0 → + realSideCovector e S (simpleRoot C pc) pos h (e m)=0 := by + intro n m hm + obtain ⟨a,rfl⟩:=mutationLinearPiece_surjective Ω hΩ C pc pos m + rw [mutationCompletion_coeff_read] at hm + split_ifs at hm with hd + · obtain ⟨j,hj,hja⟩:=Finset.exists_ne_zero_of_sum_ne_zero hm + rw [realSideCovector_mutated_incidence Ω C pc pos e S hS hcomp] + exact hf j a hja + · exact (hm rfl).elim + +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) +include hS hcomp in +lemma mutatedLineFactor_kernel (a : ℝ) : + ∀n m,coeff n (mutatedLineFactor Ω hΩ C coord pc e he L hdeg v k H a) m≠0 → + realMutationCovector e S (simpleRoot C pc) (k+a • v) (e m)=0 := by + classical + unfold mutatedLineFactor + split + · next ha=> + split + · next hp=> + have hcut : realMutationCovector e S (simpleRoot C pc) (k+a • v)=k+a • v:=by + unfold realMutationCovector + rw [ite_eq_left (le_of_eq hp.symm)] + rw [hcut] + apply orientPowerSeries_submonoid LaurentRay.vUnit Ω + (((k+a • v).toAddMonoidHom.comp e).ker.toAddSubmonoid) + apply normalizedSimple_kernel_support + rw [mutatedRoot_p,map_neg] + change -((k+a • v) (e (simpleRoot C pc)))=0 + rw [hp,neg_zero] + · next hp=> + let pos:=decide (0<(k+a • v) (e (simpleRoot C pc))) + have hs : if pos then 0≤(k+a • v) (e (simpleRoot C pc)) else + (k+a • v) (e (simpleRoot C pc))≤0:=by + dsimp [pos] + split_ifs with hh + · exact le_of_lt (of_decide_eq_true hh) + · exact le_of_not_gt (by simpa only [decide_eq_true_eq] using hh) + rw [realMutationCovector_eq_side e S (simpleRoot C pc) pos _ hs] + apply mutationCompletion_kernel_support Ω hΩ C coord pc e S hS hcomp pos + apply orientPowerSeries_submonoid LaurentRay.vUnit Ω + (((k+a • v).toAddMonoidHom.comp e).ker.toAddSubmonoid) + exact chartZero_kernel_support LaurentRay.vUnit Ω C _ _ + · exact one_kernel_support LaurentRay.vUnit Ω + ((realMutationCovector e S (simpleRoot C pc) (k+a • v)).toAddMonoidHom.comp e) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutationChamberPaths.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutationChamberPaths.lean new file mode 100644 index 0000000000000000000000000000000000000000..9760233e39ffdf76780e7375404a8bf6b4d12931 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutationChamberPaths.lean @@ -0,0 +1,242 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutatedPathIndependent +import OAI.Combinatorics.Chromatic.QuantumTorus.MutationConvexSigns + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (p : M) (hS : ∀x,S x x=0) + +def mutationSignRegion (P : Finset E) : Set (Module.Dual ℝ E) := + {h | ∀x∈P,0.mp ha + have hab:=(Finset.mem_filter.mp haF).2 + exact mutatedLineFactor_protected Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + P V D hP v k H a (hregion a hab.1.le hab.2.le) + +include hcoord hS hcomp in +omit [FiniteDimensional ℝ E] in +lemma mutatedPathCompletion_protected (P : Finset E) (V : M → Prop) + (hV : ∀a b,V a → V b → V (a+b)) (D : ℕ) + (hP : ∀n,n+1≤D → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → + ¬V m → e m∈P ∨ -(e m)∈P) + {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) + (hp : p.InRegion C e (mutationSignRegion e S (simpleRoot C pc) P)) : + ∀n,n+1≤D → SupportedOn LaurentRay.vUnit Ω V + (coeff (n+1) (mutatedPathCompletion Ω hΩ C coord pc e he L hdeg p)) := by + induction p with + | nil=> + intro n hn + simp only [mutatedPathCompletion,coeff_one,show n+1≠0 by omega,ite_false] + exact SupportedOn.zero LaurentRay.vUnit Ω V + | append s p ih=> + apply strict_mul_through LaurentRay.vUnit Ω V hV _ _ D + (mutatedLineCompletion_constant Ω hΩ C coord pc e he L hdeg s.direction s.offset s.generic s.lo s.hi) + (mutatedPathCompletion_constant Ω hΩ C coord pc e he L hdeg p) _ (ih hp.2) + intro n hn + rw [mutatedLineCompletion_coeff Ω hΩ C coord pc e he L hdeg s.direction s.offset s.generic s.lo s.hi + (n+1) (max 1 ((mutationSize Ω C pc+1)*D)) (le_max_left _ _) + ((Nat.mul_le_mul_left _ hn).trans (le_max_right _ _))] + exact mutatedLineProduct_protected Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + P V hV D hP s.direction s.offset s.generic s.lo s.hi _ hp.1 n hn +end + +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) +include hnd in +lemma mutatedTransport_protected (P : Finset E) (V : M → Prop) + (hV : ∀a b,V a → V b → V (a+b)) (D : ℕ) + (hP : ∀n,n+1≤D → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → + ¬V m → e m∈P ∨ -(e m)∈P) + {a b : Module.Dual ℝ E} (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (ha : a∈mutationSignRegion e S (simpleRoot C pc) P) + (hb : b∈mutationSignRegion e S (simpleRoot C pc) P) + (hap : a (e (simpleRoot C pc))≠0) (hbp : b (e (simpleRoot C pc))≠0) : + ∀n,n+1≤D → SupportedOn LaurentRay.vUnit Ω V + (coeff (n+1) (mutatedTransport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg HA HB).val) := by + obtain ⟨q,hq⟩:=generic_mutation_region_path C e S (simpleRoot C pc) hS P a b HA HB ha hb hap hbp + rw [mutatedTransport_eq_path Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd HA HB q] + exact mutatedPathCompletion_protected Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg P V hV D hP q hq +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutationEventualIncoming.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutationEventualIncoming.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae4823be04a47cbca697ddffbf09feca94bbdf3b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutationEventualIncoming.lean @@ -0,0 +1,147 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationIncomingFinite +import OAI.Combinatorics.Chromatic.Walls.GeometricMutationLines + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] +variable (Ω : M →+ M →+ ℤ) (e : M →+ E) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (p : M) +variable (hS : ∀x,S x x=0) (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +lemma incoming_side_label (r : M) (pos : Bool) + (hs : if pos then 0≤Ω p r else Ω p r≤0) : + (if pos then r else mutationShear Ω p r)=mutationIncomingLabel Ω p r := by + cases pos + · exact (mutationIncomingLabel_nonpositive Ω p r hs).symm + · exact (mutationIncomingLabel_nonnegative Ω p r hs).symm + +include hcomp in +lemma incoming_line_eventual_side (r : M) (pos : Bool) (k : Module.Dual ℝ E) + (hs : if pos then 0≤Ω p r else Ω p r≤0) + (hz : Ω p r=0 → if pos then 0≤k (e p) else k (e p)≤0) : + ∃T : ℝ,∀t≥T,if pos then 0≤(k+t • S.flip (e r)) (e p) + else (k+t • S.flip (e r)) (e p)≤0 := by + by_cases hh : Ω p r=0 + · refine ⟨0,?_⟩ + intro t ht + simpa only [LinearMap.add_apply,LinearMap.smul_apply,LinearMap.flip_apply, + hcomp,hh,Int.cast_zero,smul_eq_mul,mul_zero,add_zero] using hz hh + · cases pos + · change Ω p r≤0 at hs + have ha : (0:ℝ)< -(Ω p r:ℝ):=by exact_mod_cast (by omega : 0< -Ω p r) + refine ⟨(abs (k (e p))+1)/(-(Ω p r:ℝ)),?_⟩ + intro t ht + have H:=(div_le_iff₀ ha).mp ht + have Hk:=le_abs_self (k (e p)) + change (k+t • S.flip (e r)) (e p)≤0 + simp only [LinearMap.add_apply,LinearMap.smul_apply,LinearMap.flip_apply, + hcomp,smul_eq_mul] + nlinarith + · change 0≤Ω p r at hs + have ha : (0:ℝ)<(Ω p r:ℝ):=by exact_mod_cast (by omega : 0<Ω p r) + refine ⟨(abs (k (e p))+1)/(Ω p r:ℝ),?_⟩ + intro t ht + have H:=(div_le_iff₀ ha).mp ht + have Hk:=neg_abs_le (k (e p)) + change 0≤(k+t • S.flip (e r)) (e p) + simp only [LinearMap.add_apply,LinearMap.smul_apply,LinearMap.flip_apply, + hcomp,smul_eq_mul] + nlinarith + +include hS hcomp in +lemma mutation_incoming_line_eventual (r : M) (pos : Bool) (k : Module.Dual ℝ E) + (hs : if pos then 0≤Ω p r else Ω p r≤0) + (hz : Ω p r=0 → if pos then 0≤k (e p) else k (e p)≤0) : + ∃T : ℝ,∀t≥T,realMutationCovector e S p (k+t • S.flip (e r))= + realSideCovector e S p pos k+t • S.flip (e (mutationIncomingLabel Ω p r)) := by + obtain ⟨T,hT⟩:=incoming_line_eventual_side Ω e S p hcomp r pos k hs hz + refine ⟨T,fun t ht=>?_⟩ + rw [realMutationCovector_incoming_line Ω e S p hS hcomp pos k r t (hT t ht), + incoming_side_label Ω p r pos hs] +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry WallUnits +noncomputable section +variable {M I E : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable [AddCommGroup E] [Module ℝ E] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (pc : I) (pos : Bool) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hS hcomp hdeg in +lemma pushed_nonsimple_incoming_eventually (d dr : ℕ) (r : M) (hdr : 0⟨hA t ((le_max_left A B).trans ht),?_⟩⟩ + have hb : ∀a∈lineEvents (realRootsThrough e C ((mutationSize Ω C pc+1)*d)) (S.flip (e r)) k,a⟨?_,?_⟩⟩ + · rw [hA t ((le_max_left A B).trans ht),mutationIncomingLabel_simple Ω C pc i hi] + · have htne : t∉lineEvents (realRootsThrough e C ((mutationSize Ω C pc+1)*d)) + (S.flip (e (simpleRoot C i))) k:=by + intro htmem + exact (lt_irrefl t) (lt_of_lt_of_le (hbound t htmem) ((le_max_right A B).trans ht)) + have hg:=line_generic e he C L hdeg ((mutationSize Ω C pc+1)*d) 1 (simpleRoot C i) + (by omega) (simpleRoot_degree C i) (S.flip (e (simpleRoot C i))) k + (hS (e (simpleRoot C i))) H t htne + intro n hnd + exact actual_simple_wall_mutation_through Ω hΩ C coord hcoord pc pos i hi hs _ n + (hg.mono C (Nat.mul_le_mul_left _ hnd)) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutationIncomingFinite.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutationIncomingFinite.lean new file mode 100644 index 0000000000000000000000000000000000000000..95232ad615bcc35d4a7e484a20003458d15b9fca --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutationIncomingFinite.lean @@ -0,0 +1,109 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.IncomingEquality +import OAI.Combinatorics.Chromatic.Walls.MutationSimpleIncoming + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +lemma literalIncomingRay_eq_one_of_none (l : List (WallUnitDatum M)) (r : M) + (hn : ∀u∈l,¬OnPositiveRay r u.root) : literalIncomingRay Ω l r=1 := by + classical + unfold literalIncomingRay + have hf : l.filter (fun u=>OnPositiveRay r u.root)=[]:=by + apply List.eq_nil_iff_forall_not_mem.mpr + intro u hu + have H:=List.mem_filter.mp hu + exact hn u H.1 (of_decide_eq_true H.2) + rw [hf,List.map_nil,List.prod_nil] +lemma literalIncoming_simple_nonsimple (r : M) + (hn : ∀i,¬OnPositiveRay r (simpleRoot C i)) : literalIncomingRay Ω (simpleIncomingList C) r=1 := by + apply literalIncomingRay_eq_one_of_none + intro u hu + obtain ⟨i,hi,rfl⟩:=List.mem_map.mp hu + exact hn i + +variable {E : Type*} [AddCommGroup E] [Module ℝ E] +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in +lemma nonsimple_incoming_at_far_through (N d : ℕ) (r : M) (hd : 0 exact hpos.1 + have sy : cutSide pos (y.toAddMonoidHom.comp e) (simpleRoot C pc):=by cases pos <;> exact hpos.2 + have hxside:=realMutationCovector_eq_side e S (simpleRoot C pc) pos x (by cases pos <;> exact le_of_lt hpos.1) + have hyside:=realMutationCovector_eq_side e S (simpleRoot C pc) pos y (by cases pos <;> exact le_of_lt hpos.2) + have evalX (m:M) : realMutationCovector e S (simpleRoot C pc) x (e m)= + x (if pos then e m else realShearVector e S (simpleRoot C pc) (e m)):=by + rw [hxside]; cases pos + · exact realShearCovector_eval e S _ _ _ + · rfl + have evalY (m:M) : realMutationCovector e S (simpleRoot C pc) y (e m)= + y (if pos then e m else realShearVector e S (simpleRoot C pc) (e m)):=by + rw [hyside]; cases pos + · exact realShearCovector_eval e S _ _ _ + · rfl + have memQ (n:ℕ) (hn:n≤N) (m:M) (hm:HasRootDegree (mutatedRoots Ω C pc) n m) : + (if pos then e m else realShearVector e S (simpleRoot C pc) (e m))∈Q:=by + have ha : e m∈A:=realRoot_mem e _ N n hn m hm + cases pos + · exact Finset.mem_union_right _ (Finset.mem_image.mpr ⟨e m,ha,rfl⟩) + · exact Finset.mem_union_left _ ha + have hsign : (if pos then 0≤Ω (simpleRoot C pc) r else Ω (simpleRoot C pc) r≤0):=by + have hs:=HS (e (simpleRoot C pc)) (Finset.mem_insert_self _ _) + have hc : k (e (simpleRoot C pc))=(Ω (simpleRoot C pc) r:ℝ):=hcomp _ _ + cases pos + · have hh : Ω (simpleRoot C pc) r≤0:=by + by_contra hn + have H:=hs.1 (by rw [hc]; exact_mod_cast lt_of_not_ge hn) + exact (not_lt_of_ge hpos.1.le H.1) + exact hh + · have hh : 0≤Ω (simpleRoot C pc) r:=by + by_contra hn + have H:=hs.2 (by rw [hc]; exact_mod_cast lt_of_not_ge hn) + exact (not_lt_of_ge (le_of_lt hpos.1) H.1) + exact hh + refine ⟨pos,x,y,HX,HY,sx,sy,hsign,?_,hxr,hyr,?_,?_,?_⟩ + · cases pos + · exact (mutationIncomingLabel_nonpositive Ω (simpleRoot C pc) r hsign).symm + · exact (mutationIncomingLabel_nonnegative Ω (simpleRoot C pc) r hsign).symm + · intro n hn m hm + have H:=HS (e m) (Finset.mem_insert_of_mem (Finset.mem_union_left _ (realRoot_mem e C K n hn m hm))) + change ((0 < S (e m) (e r) → _) ∧ (S (e m) (e r)<0 → _)) at H + rw [hcomp] at H + exact H + · intro n hn m hm + have H:=HS _ (Finset.mem_insert_of_mem (Finset.mem_union_right _ (memQ n hn m hm))) + rw [evalX,evalY,incoming_side_eval Ω C pc e S hS hcomp pos r m] + exact H + · intro n hn m hm + have hnz : e m≠0:=by + intro H + have hm0 : m=0:=he (H.trans (map_zero e).symm) + exact positive_root_ne_zero (mutatedRoots Ω C pc) + (Function.LeftInverse.injective (mutatedCoordinates_retraction Ω C coord hcoord pc)) + (Nat.succ_pos n) (hm0 ▸ hm) + have hv : (if pos then e m else realShearVector e S (simpleRoot C pc) (e m))≠0:=by + cases pos + · exact realShearVector_ne_zero C pc e S hS hnz + · exact hnz + rw [evalX,evalY] + exact ⟨Hx _ (memQ (n+1) hn m hm) hv,Hy _ (memQ (n+1) hn m hm) hv⟩ +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance mutationIncomingProbesRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance mutationIncomingProbesAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance mutationIncomingProbesAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma normalizedSimple_regradeBound (δ:M →+ ℤ) (B:ℕ) (r:M) (hr:δ r=1) : + RegradeBound LaurentRay.vUnit Ω δ (B+1) (normalizedSimple Ω r) := by + intro n m hm + have H:=normalizedSimple_homogeneous Ω δ r hr n m hm + rw [H,Int.toNat_natCast] + exact ⟨Int.natCast_nonneg _,by nlinarith⟩ + +omit [Fintype I] in +lemma ray_pairing_side (pos:Bool) (r:M) (i:I) (hr:OnPositiveRay r (simpleRoot C i)) + (hs:if pos then 0≤Ω (simpleRoot C pc) r else Ω (simpleRoot C pc) r≤0) : + if pos then 0 ≤ mutationPairing Ω C pc i else mutationPairing Ω C pc i≤0 := by + obtain ⟨a,b,ha,hb,HH⟩:=hr + have H:=congrArg (Ω (simpleRoot C pc)) HH + simp only [map_nsmul,nsmul_eq_mul] at H + have ha' : (0:ℤ).trans (map_mul _ _ _) + +lemma infinityCompletedUnit_one (F : CompletedPositive v Ω (mutatedRoots Ω C pc)) + (h : F.val=1) : infinityCompletedUnit Ω C coord hcoord pc v F=1 := by + apply Units.ext + change laurentRegrade v Ω _ _ _ F.val _=1 + have Hsub : (completedInfinityUnit Ω C coord hcoord pc v F).val=1:=Subtype.ext h + exact congrArg (laurentRegradeHom v Ω _ _ _) Hsub |>.trans (map_one _) + +lemma infinityCompletedUnit_inverse + (F G : CompletedPositive v Ω (mutatedRoots Ω C pc)) + (h : G.val=invOfUnit F.val 1) : + infinityCompletedUnit Ω C coord hcoord pc v G= + (infinityCompletedUnit Ω C coord hcoord pc v F)⁻¹ := by + apply Units.ext + change mutatedLaurent Ω C coord hcoord pc v G= + mutatedLaurent Ω C coord hcoord pc v (completedInverse v Ω (mutatedRoots Ω C pc) F) + exact congrArg _ (Subtype.ext h) + +lemma mutatedLaurent_coeff_congr + (F G : CompletedPositive v Ω (mutatedRoots Ω C pc)) (d : ℕ) (z : ℤ) + (h : ∀n≤(z+(mutationSize Ω C pc+1:ℤ)*(d:ℤ)).toNat,coeff n F.val=coeff n G.val) : + (coeff d (mutatedLaurent Ω C coord hcoord pc v F)).coeff z= + (coeff d (mutatedLaurent Ω C coord hcoord pc v G)).coeff z := by + exact laurentRegrade_coeff_congr v Ω _ _ _ + (mutated_series_laurentBounded Ω C coord hcoord pc v F.property.2) + (mutated_series_laurentBounded Ω C coord hcoord pc v G.property.2) d z h + +lemma infinityCompletedUnit_pure (hΩ : ∀m,Ω m m=0) + (F : CompletedPositive v Ω (mutatedRoots Ω C pc)) + (h : F.val=raySeries v Ω (-simpleRoot C pc) (shiftedElementary v 0)) : + infinityCompletedUnit Ω C coord hcoord pc v F= + completedPureUnit v Ω hΩ (-simpleRoot C pc) := by + have hd : nonpDegree (mutatedCoordinates Ω C coord pc) pc (-simpleRoot C pc)=0 := by + rw [←mutatedRoot_p Ω C pc] + exact nonpDegree_simple_self (mutatedRoots Ω C pc) (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) pc + have hk : (-pureDegree coord pc) (-simpleRoot C pc)=1 := by + simp only [AddMonoidHom.neg_apply,map_neg,neg_neg,pureDegree_simple_self C coord hcoord pc] + apply Units.ext + change laurentRegrade v Ω _ _ _ F.val _=PowerSeries.C _ + have H:=laurentRegrade_pure v Ω + (nonpDegree (mutatedCoordinates Ω C coord pc) pc) (-pureDegree coord pc) + (mutationSize Ω C pc) (-simpleRoot C pc) hd hk (shiftedElementary v 0) + calc + _ = PowerSeries.C (HahnSeries.ofPowerSeries ℤ (Torus v Ω) + (raySeries v Ω (-simpleRoot C pc) (shiftedElementary v 0))) := by + convert H using 1 + congr 1 + _ = _ := by + congr 1 + exact (purePower_eq v Ω hΩ (-simpleRoot C pc) (shiftedElementary v 0)).symm +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries HahnSeries WallUnits +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (k : M →+ ℤ) (p : M) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : NonUnitalSemiring (Torus v Ω) := (Torus.instRing v Ω).toNonUnitalSemiring +local instance : NonUnitalNonAssocSemiring (Torus v Ω) := + (Torus.instRing v Ω).toNonUnitalNonAssocSemiring +lemma completed_expand_opposite + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) + (f : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))) : + PowerSeries.map (expandFiberInfinity v Ω hΩ k p) + ((completedOppositeInverseAction v _ _).symm f)= + innerHom (completedPureUnit v Ω hΩ (-p)) + (PowerSeries.map (expandFiberInfinity v Ω hΩ k p) f) := by + have H:=completed_expand_opposite_inverse v Ω hΩ k p hq + ((completedOppositeInverseAction v _ _).symm f) + rw [RingEquiv.apply_symm_apply] at H + have HH:=congrArg (innerHom (completedPureUnit v Ω hΩ (-p))) H + rw [innerHom_cancel_inv] at HH + exact HH.symm +end +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) (pos : Bool) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +lemma mutation_infinity_oriented_coefficient (b : Bool) (f : CompletedPositive LaurentRay.vUnit Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) + (d : ℕ) (m : M) : + ((coeff d (PowerSeries.map (expandFiberInfinity LaurentRay.vUnit Ω hΩ + (pureDegree coord pc) (simpleRoot C pc)) + (mutationSideAction LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω) pos + (rationalRegrade LaurentRay.vUnit Ω hΩ (pureDegree coord pc) (simpleRoot C pc) + (pureDegree_simple_self C coord hcoord pc) (nonpDegree coord pc) (mutationSize Ω C pc+1) + (orientPowerSeries b f.val))))).coeff (-pureDegree coord pc m)) m= + coeff d (regrade LaurentRay.vUnit Ω (nonpDegree (mutatedCoordinates Ω C coord pc) pc) + (mutationSize Ω C pc+1) (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit + (orientPowerSeries b f.val))) m := by + rw [coeff_map,expandFiberInfinity_read LaurentRay.vUnit Ω hΩ (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc)] + rw [mutation_rational_oriented_compatibility Ω hΩ C coord hcoord pc pos b f hf, + rationalRegrade,coeff_map] + exact readFiberInfinity_embedAdd LaurentRay.vUnit Ω _ _ _ _ _ +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutationLaurentCompletion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutationLaurentCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..120b669625978e966c1ec3c07161567f3bdb75fc --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutationLaurentCompletion.lean @@ -0,0 +1,122 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationRegradeCompatibility +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentDeshear +import OAI.Combinatorics.Chromatic.Walls.RootLaurentCompletion +import OAI.Combinatorics.Chromatic.QuantumTorus.MutationInfinityBound + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +include hcoord in +lemma mutation_infinity_full_bound {n : ℕ} {m : M} + (hm : HasRootDegree (mutatedRoots Ω C pc) n m) : + (n:ℤ) ≤ -pureDegree coord pc m+(mutationSize Ω C pc+1:ℤ)* + nonpDegree (mutatedCoordinates Ω C coord pc) pc m := by + obtain ⟨d,hd,hc,hC⟩:=root_coordinates (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) hm + have hn (i : I) : 0 ≤ mutatedCoordinates Ω C coord pc m i := by + rw [hc] + exact Int.natCast_nonneg _ + have hs : (∑i∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc i)* + mutatedCoordinates Ω C coord pc m i) ≤ + (mutationSize Ω C pc:ℤ)*nonpDegree (mutatedCoordinates Ω C coord pc) pc m := by + change _ ≤ (mutationSize Ω C pc:ℤ)*(∑i∈Finset.univ.erase pc, + mutatedCoordinates Ω C coord pc m i) + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro i hi + apply mul_le_mul_of_nonneg_right _ (hn i) + exact (max_le (abs_nonneg _) (neg_le_abs _)).trans + (mutationSize_bound Ω C pc i (Finset.mem_erase.mp hi).1) + have hk : pureDegree coord pc m = -mutatedCoordinates Ω C coord pc m pc+ + ∑i∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc i)* + mutatedCoordinates Ω C coord pc m i := by + have H:=congrArg (fun f : I → ℤ => f pc) + (mutatedCoefficientMap_involutive pc (mutationPairing Ω C pc) (coord m)) + rw [mutatedCoefficientMap_at] at H + exact H.symm + have he:=nonpDegree_root_eq (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) pc hm + nlinarith + +variable (v : (LaurentSeries ℚ)ˣ) +local instance mutationLaurentCompletionRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance mutationLaurentCompletionAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance mutationLaurentCompletionAddGroup : AddGroup (Torus v Ω) := + (Torus.instRing v Ω).toAddGroup + +include hcoord in +lemma mutated_series_laurentBounded {f : PowerSeries (Torus v Ω)} + (hf : SeriesGraded v Ω (mutatedRoots Ω C pc) f) : + LaurentBounded v Ω (nonpDegree (mutatedCoordinates Ω C coord pc) pc) + (-pureDegree coord pc) (mutationSize Ω C pc) f := by + intro n m hn + have hm : HasRootDegree (mutatedRoots Ω C pc) n m := by + by_contra h + exact hn (hf n m h) + exact ⟨nonpDegree_root_nonneg (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) pc hm, + mutation_infinity_lower_bound Ω C coord hcoord pc hm, + mutation_infinity_full_bound Ω C coord hcoord pc hm⟩ + +def mutatedLaurent (f : CompletedPositive v Ω (mutatedRoots Ω C pc)) : + PowerSeries (HahnSeries ℤ (Torus v Ω)) := + laurentRegrade v Ω (nonpDegree (mutatedCoordinates Ω C coord pc) pc) + (-pureDegree coord pc) (mutationSize Ω C pc) f.val + (mutated_series_laurentBounded Ω C coord hcoord pc v f.property.2) + +include hcoord in +lemma mutatedLaurent_injective : + Function.Injective (mutatedLaurent Ω C coord hcoord pc v) := by + intro f g h + apply Subtype.ext + exact laurentRegrade_injective v Ω _ _ + (rootOrder (mutatedCoordinates Ω C coord pc)) _ + (mutated_series_laurentBounded Ω C coord hcoord pc v f.property.2) + (mutated_series_laurentBounded Ω C coord hcoord pc v g.property.2) + (completed_full_homogeneous v Ω (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) f) + (completed_full_homogeneous v Ω (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) g) h + +def completedInfinityUnit (F : CompletedPositive v Ω (mutatedRoots Ω C pc)) : + (laurentBoundedSubring v Ω (nonpDegree (mutatedCoordinates Ω C coord pc) pc) + (-pureDegree coord pc) (mutationSize Ω C pc))ˣ where + val:=⟨F.val,mutated_series_laurentBounded Ω C coord hcoord pc v F.property.2⟩ + inv:=⟨(completedInverse v Ω (mutatedRoots Ω C pc) F).val, + mutated_series_laurentBounded Ω C coord hcoord pc v + (completedInverse v Ω (mutatedRoots Ω C pc) F).property.2⟩ + val_inv:=Subtype.ext (mul_completedInverse v Ω (mutatedRoots Ω C pc) F) + inv_val:=Subtype.ext (completedInverse_mul v Ω (mutatedRoots Ω C pc) F) + +def infinityCompletedUnit (F : CompletedPositive v Ω (mutatedRoots Ω C pc)) : + (PowerSeries (HahnSeries ℤ (Torus v Ω)))ˣ := + Units.map (laurentRegradeHom v Ω (nonpDegree (mutatedCoordinates Ω C coord pc) pc) + (-pureDegree coord pc) (mutationSize Ω C pc)) + (completedInfinityUnit Ω C coord hcoord pc v F) + +@[simp] lemma infinityCompletedUnit_val (F : CompletedPositive v Ω (mutatedRoots Ω C pc)) : + (infinityCompletedUnit Ω C coord hcoord pc v F).val = + mutatedLaurent Ω C coord hcoord pc v F := rfl + +@[simp] lemma infinityCompletedUnit_inv (F : CompletedPositive v Ω (mutatedRoots Ω C pc)) : + (infinityCompletedUnit Ω C coord hcoord pc v F).inv = + mutatedLaurent Ω C coord hcoord pc v (completedInverse v Ω (mutatedRoots Ω C pc) F) := rfl +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutationLogCompletion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutationLogCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..c1ad91a822f8c7626a564ee40cd842145697830a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutationLogCompletion.lean @@ -0,0 +1,210 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.MutatedNegativeCharts +import OAI.Combinatorics.Chromatic.GradedAlgebra.RegradeLog + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (pc : I) (pos : Bool) (v : Rˣ) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +lemma mutationCompletion_log (F : PowerSeries (Torus v Ω)) + (hf : RegradeBound v Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) F) + (hc : constantCoeff F=1) : + mutationCompletion Ω hΩ C coord pc pos v (FormalLog.log F)= + FormalLog.log (mutationCompletion Ω hΩ C coord pc pos v F) := by + unfold mutationCompletion + rw [regrade_log v Ω _ _ F hf hc] + exact (FormalLog.log_map (mutationTorusPush Ω hΩ C pc pos v).toRatAlgHom _).symm +lemma mutationCompletion_log_read (F : PowerSeries (Torus v Ω)) + (hf : RegradeBound v Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) F) + (hc : constantCoeff F=1) (d : ℕ) (m : M) : + coeff d (FormalLog.log (mutationCompletion Ω hΩ C coord pc pos v F)) + (mutationLinearPiece Ω C pc pos m)= + if d=(mutationNewOrder Ω C coord pc pos m).toNat then + ∑n∈Finset.range ((mutationSize Ω C pc+1)*d+1), coeff n (FormalLog.log F) m else 0 := by + rw [←mutationCompletion_log Ω hΩ C coord pc pos v F hf hc,mutationCompletion_coeff_read] +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd : ∀r≠0,∃m,Ω r m≠0) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +include hnd in +lemma mutatedIncoming_probe (pos : Bool) (d N : ℕ) (hdN : d≤N) (r : M) + {a b x y : Module.Dual ℝ E} + (HA : RegularCovector C e a) (HB : RegularCovector C e b) + (HX : RegularCovector C e x) (HY : RegularCovector C e y) + (hA : ∀n,n+1≤N → ∀m,HasRootDegree (mutatedRoots Ω C pc) (n+1) m → + 0 exact le_of_lt hsx)] + cases pos + · exact realShearCovector_incidence Ω e S (simpleRoot C pc) hS hcomp x r + · rfl + have hyp : yp (mutationLinearPiece Ω C pc pos r)=y (e r):=by + change realMutationCovector e S (simpleRoot C pc) y (e (mutationLinearPiece Ω C pc pos r))=_ + rw [realMutationCovector_eq_side e S _ pos y (by cases pos <;> exact le_of_lt hsy)] + cases pos + · exact realShearCovector_incidence Ω e S (simpleRoot C pc) hS hcomp y r + · rfl + have Hn:=incoming_negative_ratio_log LaurentRay.vUnit Ω (mutatedRoots Ω C pc) hΩ + (mutationLinearPiece Ω C pc pos r) T xp yp N hxn hyn (hxp ▸ hxr) (hyp ▸ hyr) d hdN + have Hratio:=mutatedTransport_negative_ratio Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd + N HA HB HX HY hA hB hx hy + have Hlog:=congrArg (fun f:Torus LaurentRay.vUnit Ω=>f (mutationLinearPiece Ω C pc pos r)) + (FormalLog.log_coeff_congr _ _ d (fun j hj=>Hratio j (hj.trans hdN))) + have Hcut:=mutatedTransport_nocut Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd pos HX HY hsx hsy + have hc : constantCoeff F=1:=by + change constantCoeff ((chartNegative LaurentRay.vUnit Ω C (y.toAddMonoidHom.comp e) + (simpleTotalTransport Ω C)).val * invOfUnit (chartNegative LaurentRay.vUnit Ω C + (x.toAddMonoidHom.comp e) (simpleTotalTransport Ω C)).val 1)=1 + simp only [map_mul,(chartNegative LaurentRay.vUnit Ω C _ (simpleTotalTransport Ω C)).property.1, + constantCoeff_invOfUnit,inv_one,Units.val_one,one_mul] + have Ho:=incoming_negative_ratio_log LaurentRay.vUnit Ω C hΩ r (simpleTotalTransport Ω C) + (x.toAddMonoidHom.comp e) (y.toAddMonoidHom.comp e) ((mutationSize Ω C pc+1)*d) hxo hyo hxr hyr + rw [←Hn,←Hlog,Hcut.2,mutationCompletion_log_read Ω hΩ C coord pc pos LaurentRay.vUnit F Hcut.1 hc] + split_ifs + · apply Finset.sum_congr rfl + intro j hj + exact Ho j (by simpa only [Finset.mem_range,Nat.lt_succ_iff] using hj) + · rfl +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +attribute [local instance] Classical.decEq +variable {M E I : Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) +lemma regular_covector_with_signs (Q P : Finset E) (k : Module.Dual ℝ E) : + ∃h : Module.Dual ℝ E,RegularCovector C e h ∧ (∀q∈Q,q≠0 → h q≠0) ∧ + ∀s∈P,(0(realRootsThrough e C N).countable_toSet)).union Q.countable_toSet).mono + Set.sdiff_subset + have hp : ∀w∈W,w∉Submodule.span ℝ ({0}:Set E):=by + intro w hw + simpa only [W,Set.mem_sdiff,Set.mem_singleton_iff,Submodule.span_zero_singleton,Submodule.mem_bot] + using hw.2 + obtain ⟨h,_,hh,HS⟩:=countable_avoid_with_probes W hW 0 hp + (P.image (fun s=>(0,s))) 0 k (map_zero k) + refine ⟨h,?_,?_,?_⟩ + · intro N s hs hn + exact hh s ⟨Or.inl (Set.mem_iUnion.mpr ⟨N,hs⟩),hn⟩ + · intro q hq hn + exact hh q ⟨Or.inr hq,hn⟩ + · intro s hs + simpa only [zero_smul,add_zero] using HS (0,s) (Finset.mem_image.mpr ⟨s,hs,rfl⟩) + +lemma regular_straddle (Q P : Finset E) (k : Module.Dual ℝ E) (r : E) + (hr : r≠0) (hk : k r=0) : + ∃x y : Module.Dual ℝ E,RegularCovector C e x ∧ RegularCovector C e y ∧ + (∀q∈Q,q≠0 → x q≠0) ∧ (∀q∈Q,q≠0 → y q≠0) ∧ + 0⟨(Sx s (Finset.mem_insert_of_mem hs)).1 (He.1 h), + (Sy s (Finset.mem_insert_of_mem hs)).1 (Hh.1 h)⟩, + fun h=>⟨(Sx s (Finset.mem_insert_of_mem hs)).2 (He.2.1 h), + (Sy s (Finset.mem_insert_of_mem hs)).2 (Hh.2.1 h)⟩⟩ + +lemma regular_straddle_offcut (Q P : Finset E) (k : Module.Dual ℝ E) (r p : E) + (hr : r≠0) (hk : k r=0) (hp : p∉Submodule.span ℝ {r}) : + ∃x y : Module.Dual ℝ E,RegularCovector C e x ∧ RegularCovector C e y ∧ + (∀q∈Q,q≠0 → x q≠0) ∧ (∀q∈Q,q≠0 → y q≠0) ∧ + 0(HS s hs).1 ((Hh s hs).1 h),fun h=>(HS s hs).2 ((Hh s hs).2 h)⟩ +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutationMonomialAction.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutationMonomialAction.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce02d3828664f3dbad38196614b1d7a2f3a653b0 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutationMonomialAction.lean @@ -0,0 +1,149 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationRegradeCompatibility +import OAI.Combinatorics.Chromatic.GradedAlgebra.RootCoefficients +import OAI.Combinatorics.Chromatic.QuantumTorus.NormalizedMonomialAction +import OAI.Combinatorics.Chromatic.Walls.MutatedLineCompletion + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) (pos:Bool) +local instance : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +lemma mutationCompletion_monomialConjugate (b:M) (f:PowerSeries (Torus LaurentRay.vUnit Ω)) : + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (monomialConjugate LaurentRay.vUnit Ω b f)= + monomialConjugate LaurentRay.vUnit Ω (mutationLinearPiece Ω C pc pos b) + (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f) := by + unfold mutationCompletion + rw [regrade_monomialConjugate LaurentRay.vUnit Ω hΩ] + simp only [monomialConjugate,map_mul,PowerSeries.map_C,mutationTorusPush,Torus.push_X,map_neg] + +lemma mutationCompletion_normalizedMonomialAction (f:PowerSeries (Torus LaurentRay.vUnit Ω)) (b:M) + (hf:RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f) + (hc:constantCoeff f=1) : + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (normalizedMonomialAction LaurentRay.vUnit Ω f b)= + normalizedMonomialAction LaurentRay.vUnit Ω (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f) + (mutationLinearPiece Ω C pc pos b) := by + rw [normalizedMonomialAction,mutationCompletion_mul Ω hΩ C coord pc pos LaurentRay.vUnit hf + (monomialConjugate_regradeBound LaurentRay.vUnit Ω hΩ b _ _ (hf.invOfUnit _ _ _ _)), + mutationCompletion_monomialConjugate,mutationCompletion_inverse Ω hΩ C coord pc pos f hf hc] + rfl + +lemma mutationCompletion_actualRootCoefficient (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf:RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f) + (hg:FullHomogeneous LaurentRay.vUnit Ω (rootOrder coord) f) (m:M) : + actualRootCoefficient LaurentRay.vUnit Ω (rootOrder (mutatedCoordinates Ω C coord pc)) + (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f) (mutationLinearPiece Ω C pc pos m)= + actualRootCoefficient LaurentRay.vUnit Ω (rootOrder coord) f m := by + calc + _ = actualRootCoefficient LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) + (regrade LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f) m := by + unfold actualRootCoefficient mutationCompletion + change (if 0 ≤ mutationNewOrder Ω C coord pc pos m then _ else _) = _ + split_ifs + · rw [coeff_map,mutationTorusPush_read] + rfl + · rfl + _ = _ := regrade_actualRootCoefficient LaurentRay.vUnit Ω (rootOrder coord) + (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f hf hg m + +def actualMonomialAdjointCoefficient (τ:M →+ ℤ) (f:PowerSeries (Torus LaurentRay.vUnit Ω)) (b m:M) : + LaurentSeries ℚ := + actualRootCoefficient LaurentRay.vUnit Ω τ (normalizedMonomialAction LaurentRay.vUnit Ω f b) (m-b)* + (↑(LaurentRay.vUnit^(Ω (m-b) b)):LaurentSeries ℚ) + +include hcoord in +lemma mutation_actualMonomialAdjointCoefficient (f:CompletedPositive LaurentRay.vUnit Ω C) + (hf:RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f.val) + (b m:M) : + actualMonomialAdjointCoefficient Ω (rootOrder (mutatedCoordinates Ω C coord pc)) + (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f.val) + (mutationLinearPiece Ω C pc pos b) (mutationLinearPiece Ω C pc pos m)= + actualMonomialAdjointCoefficient Ω (rootOrder coord) f.val b m := by + let N:CompletedPositive LaurentRay.vUnit Ω C:= + ⟨normalizedMonomialAction LaurentRay.vUnit Ω f.val b, + normalizedMonomialAction_constant LaurentRay.vUnit Ω hΩ f.val b f.property.1, + normalizedMonomialAction_graded LaurentRay.vUnit Ω hΩ C f b⟩ + have H:=mutationCompletion_actualRootCoefficient Ω hΩ C coord pc pos N.val + (normalizedMonomialAction_bound LaurentRay.vUnit Ω hΩ _ _ f.val b hf) + (completed_full_homogeneous LaurentRay.vUnit Ω C coord hcoord N) (m-b) + rw [mutationCompletion_normalizedMonomialAction Ω hΩ C coord pc pos f.val b hf f.property.1] at H + unfold actualMonomialAdjointCoefficient + rw [←map_sub,mutationLinearPiece_pairing Ω hΩ C pc pos,H] +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k : Module.Dual ℝ E) +variable (H : ∀N,GenericOffset (realRootsThrough e C N) 0 v k) + +include he hdeg H in +lemma actualLineLetter_old (a : ℝ) + (ha : ∃N,a∈lineEvents (realRootsThrough e C N) v k) : + ∃r d,0Hrp.symm.trans ((data.generic N).2 n hn hnN m hm hm0)⟩ + have HV : v (e (simpleRoot C pc))≠0:=by + intro hz + have hk : k (e (simpleRoot C pc))=0:=by + change k (e (simpleRoot C pc))+a*v (e (simpleRoot C pc))=0 at hp + simpa only [hz,mul_zero,add_zero] using hp + exact section_offset_generic C e L hdeg 1 v k (H 1) 1 one_pos le_rfl + (simpleRoot C pc) (simpleRoot_degree C pc) hk + refine ⟨simpleRoot C pc,1,one_pos,simpleRoot_degree C pc,HV,HG,?_⟩ + have HU:=completedBiUnit_pure Ω hΩ C coord hcoord pc ((k+a • v).toAddMonoidHom.comp e) HG + unfold actualLineLetter + simp only [dite_eq_left ha,dite_eq_left hp] + rw [HU] + by_cases hn : v (e (simpleRoot C pc))<0 + · simp only [hn,decide_true,ite_eq_left,comparisonOld] + · simp only [hn,decide_false,comparisonOld,↓reduceIte] + · refine ⟨data.root,data.degree,data.degree_pos,data.root_degree,data.transverse,data.generic,?_⟩ + unfold actualLineLetter + simp only [dite_eq_left ha,dite_eq_right hp] + change comparisonOld _ _ _ _ _ _ _ _ _ + (orientedBounded _ _ _ _ _ _ _ _ (decide (v (e data.root)<0)))=_ + by_cases hn : v (e data.root)<0 + · simp only [hn,decide_true,orientedBounded,↓reduceIte,comparisonOld] + · simp only [hn,decide_false,orientedBounded,Bool.false_eq_true,↓reduceIte,comparisonOld] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutationRegradeCompatibility.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutationRegradeCompatibility.lean new file mode 100644 index 0000000000000000000000000000000000000000..d01f17b9512c6880444502f0eb5101961b99e751 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutationRegradeCompatibility.lean @@ -0,0 +1,134 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallRegrade + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {R M I : Type*} [CommRing R] [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) +variable (pc : I) (pos : Bool) +local instance mutationRegradeCompatibilityRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance mutationRegradeCompatibilityAddCommMonoid : AddCommMonoid (Torus v Ω) := + (Torus.instRing v Ω).toAddCommMonoid +local instance mutationRegradeCompatibilityAddGroup : AddGroup (Torus v Ω) := + (Torus.instRing v Ω).toAddGroup + +omit [DecidableEq I] in +include hcoord in +lemma completed_full_homogeneous (f : CompletedPositive v Ω C) : + FullHomogeneous v Ω (rootOrder coord) f.val := by + intro n m hm + exact rootOrder_eq C coord hcoord (by by_contra hh; exact hm (f.property.2 n m hh)) + +include hcoord in +lemma fiberCompletion_nonp_bound (f : CompletedPositive v Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + RegradeBound v Ω (nonpDegree coord pc) (mutationSize Ω C pc+1) f.val := by + intro n m hm + have hr : HasRootDegree C n m:=by by_contra hh; exact hm (f.property.2 n m hh) + have hnp:=nonpDegree_root_nonneg C coord hcoord pc hr + have H:=fiber_full_degree_bound Ω C coord hcoord pc pos hr (hf n m hm) + refine ⟨hnp,?_⟩ + rw [←Int.toNat_of_nonneg hnp] at H + exact_mod_cast H + +include hcoord in +lemma mutationCompletion_read_full (f : CompletedPositive v Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) + (n : ℕ) (m : M) (hm : HasRootDegree C n m) : + coeff (mutationNewOrder Ω C coord pc pos m).toNat + (mutationCompletion Ω hΩ C coord pc pos v f.val) + (mutationLinearPiece Ω C pc pos m)=coeff n f.val m := by + rw [mutationCompletion,coeff_map,mutationTorusPush_read] + exact regrade_read v Ω _ _ (rootOrder coord) + (mutationCompletion_bound Ω hΩ C coord hcoord pc pos v f hf) + (completed_full_homogeneous v Ω C coord hcoord f) n m (rootOrder_eq C coord hcoord hm) + +include hcoord in +lemma mutationCompletion_nonp_bound (f : CompletedPositive v Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + RegradeBound v Ω (nonpDegree (mutatedCoordinates Ω C coord pc) pc) (mutationSize Ω C pc+1) + (mutationCompletion Ω hΩ C coord pc pos v f.val) := by + intro d m hm + obtain ⟨a,rfl⟩:=mutationLinearPiece_surjective Ω hΩ C pc pos m + rw [mutationCompletion_coeff_read] at hm + have hd : d=(mutationNewOrder Ω C coord pc pos a).toNat:=by + by_contra hh + exact hm (ite_eq_right hh) + rw [ite_eq_left hd] at hm + obtain ⟨n,hn,hval⟩:=Finset.exists_ne_zero_of_sum_ne_zero hm + have hr : HasRootDegree C n a:=by by_contra hh; exact hval (f.property.2 n a hh) + have hb:=hf n a hval + obtain ⟨d',hr',hde⟩:=mutation_root_image Ω C coord hcoord pc hΩ pos hr hb + have ho:=mutationNewOrder_of_root Ω C coord hcoord pc pos hr' + rw [ho,Int.toNat_natCast] at hd + subst d' + have hu:=fiberUpper_degree_bound Ω C coord hcoord pc pos hr + have hk : 0≤coord a pc:=by + obtain ⟨b,hb,hbc,he⟩:=root_coordinates C coord hcoord hr + rw [hbc] + exact Int.natCast_nonneg _ + have hnp:=nonpDegree_root_nonneg C coord hcoord pc hr + have H : (d:ℤ)≤((mutationSize Ω C pc+1:ℕ):ℤ)*nonpDegree coord pc a:=by + push_cast + nlinarith + rw [mutated_nonpDegree Ω C coord hcoord pc pos a] + refine ⟨hnp,?_⟩ + rw [←Int.toNat_of_nonneg hnp] at H + exact_mod_cast H + +include hcoord in +theorem mutation_regrade_compatibility (f : CompletedPositive v Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + PowerSeries.map (mutationTorusPush Ω hΩ C pc pos v) + (regrade v Ω (nonpDegree coord pc) (mutationSize Ω C pc+1) f.val)= + regrade v Ω (nonpDegree (mutatedCoordinates Ω C coord pc) pc) (mutationSize Ω C pc+1) + (mutationCompletion Ω hΩ C coord pc pos v f.val) := by + classical + apply PowerSeries.ext + intro D + ext m + obtain ⟨a,rfl⟩:=mutationLinearPiece_surjective Ω hΩ C pc pos m + rw [coeff_map,mutationTorusPush_read] + by_cases hD : D=(nonpDegree coord pc a).toNat + · subst D + by_cases ha : ∃n,coeff n f.val a≠0 + · obtain ⟨n,hn⟩:=ha + have hr : HasRootDegree C n a:=by by_contra hh; exact hn (f.property.2 n a hh) + obtain ⟨d,hd,hde⟩:=mutation_root_image Ω C coord hcoord pc hΩ pos hr (hf n a hn) + have ho:=mutationNewOrder_of_root Ω C coord hcoord pc pos hd + rw [regrade_read v Ω _ _ (rootOrder coord) + (fiberCompletion_nonp_bound v Ω C coord hcoord pc pos f hf) + (completed_full_homogeneous v Ω C coord hcoord f) n a (rootOrder_eq C coord hcoord hr)] + rw [←mutated_nonpDegree Ω C coord hcoord pc pos a] + rw [regrade_read v Ω _ _ (rootOrder (mutatedCoordinates Ω C coord pc)) + (mutationCompletion_nonp_bound v Ω hΩ C coord hcoord pc pos f hf) + (completed_full_homogeneous v Ω (mutatedRoots Ω C pc) (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) + (mutationCompletedPositive Ω hΩ C coord hcoord pc pos v f hf)) d _ + (rootOrder_eq (mutatedRoots Ω C pc) (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) hd)] + have H:=mutationCompletion_read_full v Ω hΩ C coord hcoord pc pos f hf n a hr + rw [ho,Int.toNat_natCast] at H + exact H.symm + · push Not at ha + simp only [regrade_coeff_eval,mutated_nonpDegree Ω C coord hcoord pc pos a] + rw [Finset.sum_eq_zero (fun n hn=>ha n)] + symm + apply Finset.sum_eq_zero + intro d hd + rw [mutationCompletion_coeff_read] + split_ifs + · exact Finset.sum_eq_zero (fun n hn=>ha n) + · rfl + · simp only [regrade_coeff_eval,mutated_nonpDegree Ω C coord hcoord pc pos a,ite_eq_right hD] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/MutationSimpleIncoming.lean b/lean/OAI/Combinatorics/Chromatic/Walls/MutationSimpleIncoming.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c1abe1b1ecc0e02cbdb0a50014c5b9e8415d8fa --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/MutationSimpleIncoming.lean @@ -0,0 +1,175 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallRegrade + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) +local instance mutationSimpleIncomingRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance mutationSimpleIncomingAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance mutationSimpleIncomingAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +lemma regrade_homogeneous_identity (δ : M →+ ℤ) (B : ℕ) (f : PowerSeries (Torus v Ω)) + (hf : FullHomogeneous v Ω δ f) : regrade v Ω δ (B+1) f=f := by + classical + apply PowerSeries.ext + intro d + ext m + rw [regrade_coeff_eval] + by_cases hd : d=(δ m).toNat + · rw [ite_eq_left hd] + apply Finset.sum_eq_single d + · intro n hn hnd + by_contra hnz + have H:=hf n m hnz + rw [H,Int.toNat_natCast] at hd + exact hnd hd.symm + · intro hn + have hb : d<(B+1)*d+1:=by nlinarith + exact (hn (Finset.mem_range.mpr hb)).elim + · rw [ite_eq_right hd] + by_contra HH + have H:=hf d m (Ne.symm HH) + rw [H,Int.toNat_natCast] at hd + exact hd rfl + +lemma normalizedSimple_homogeneous (δ : M →+ ℤ) (r : M) (hr : δ r=1) : + FullHomogeneous LaurentRay.vUnit Ω δ (normalizedSimple Ω r) := by + intro n m hm + have he : m=n • r:=by + by_contra hh + apply hm + rw [normalizedSimple,coeff_raySeries] + exact Finsupp.single_eq_of_ne hh + subst m + rw [map_nsmul,hr,nsmul_eq_mul,mul_one] + +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (hΩ : ∀m,Ω m m=0) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +lemma mutation_incoming_simple_image (i : I) (hi : i≠pc) : + mutationLinearPiece Ω C pc (decide (0≤ mutationPairing Ω C pc i)) (simpleRoot C i)= + simpleRoot (mutatedRoots Ω C pc) i := by + rw [mutatedRoot_off Ω C pc i hi] + by_cases ha : 0≤ mutationPairing Ω C pc i + · simp only [ha,decide_true,mutationLinearPiece,ite_true,max_eq_left (by omega : -mutationPairing Ω C pc i≤0),zero_zsmul,add_zero,AddMonoidHom.id_apply] + · have ha' : 0≤ -mutationPairing Ω C pc i:=by omega + simp only [ha,decide_false,mutationLinearPiece,Bool.false_eq_true,ite_false,max_eq_right ha'] + change simpleRoot C i-Ω (simpleRoot C pc) (simpleRoot C i) • simpleRoot C pc= + simpleRoot C i+(-Ω (simpleRoot C pc) (simpleRoot C i)) • simpleRoot C pc + rw [neg_zsmul,sub_eq_add_neg] + +include hcoord in +lemma mutation_incoming_simple_order (i : I) (hi : i≠pc) : + mutationNewOrder Ω C coord pc (decide (0≤ mutationPairing Ω C pc i)) (simpleRoot C i)=1 := by + apply mutationNewOrder_of_root Ω C coord hcoord + rw [mutation_incoming_simple_image Ω C pc i hi] + exact simpleRoot_degree (mutatedRoots Ω C pc) i + +omit [Fintype I] in +lemma mutation_push_normalizedSimple (pos : Bool) (r : M) : + PowerSeries.map (mutationTorusPush Ω hΩ C pc pos LaurentRay.vUnit) (normalizedSimple Ω r)= + normalizedSimple Ω (mutationLinearPiece Ω C pc pos r) := by + apply PowerSeries.ext + intro n + rw [coeff_map,normalizedSimple,coeff_raySeries,normalizedSimple,coeff_raySeries] + change Torus.push LaurentRay.vUnit Ω Ω (mutationLinearPiece Ω C pc pos) _ (Torus.monomial _ _ _ _)=_ + rw [Torus.push_monomial,map_nsmul] + +include hcoord in +theorem mutation_normalized_incoming_simple (i : I) (hi : i≠pc) : + mutationCompletion Ω hΩ C coord pc (decide (0≤ mutationPairing Ω C pc i)) LaurentRay.vUnit + (normalizedSimple Ω (simpleRoot C i))= + normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) i) := by + rw [mutationCompletion,regrade_homogeneous_identity] + · rw [mutation_push_normalizedSimple,mutation_incoming_simple_image Ω C pc i hi] + · exact normalizedSimple_homogeneous Ω _ _ (mutation_incoming_simple_order Ω C coord hcoord pc i hi) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) (pos : Bool) +lemma mutation_side_simple_image (i : I) (hi : i≠pc) + (hside : if pos then 0≤ mutationPairing Ω C pc i else mutationPairing Ω C pc i≤0) : + mutationLinearPiece Ω C pc pos (simpleRoot C i)=simpleRoot (mutatedRoots Ω C pc) i := by + rw [mutatedRoot_off Ω C pc i hi] + cases pos + · change mutationPairing Ω C pc i≤0 at hside + rw [max_eq_right (by omega : 0≤ -mutationPairing Ω C pc i)] + change simpleRoot C i-Ω (simpleRoot C pc) (simpleRoot C i) • simpleRoot C pc= + simpleRoot C i+(-Ω (simpleRoot C pc) (simpleRoot C i)) • simpleRoot C pc + rw [neg_zsmul,sub_eq_add_neg] + · change 0≤ mutationPairing Ω C pc i at hside + rw [max_eq_left (by omega : -mutationPairing Ω C pc i≤0),zero_zsmul,add_zero] + rfl + +include hcoord in +lemma mutation_side_simple_order (i : I) (hi : i≠pc) + (hside : if pos then 0≤ mutationPairing Ω C pc i else mutationPairing Ω C pc i≤0) : + mutationNewOrder Ω C coord pc pos (simpleRoot C i)=1 := by + apply mutationNewOrder_of_root Ω C coord hcoord + rw [mutation_side_simple_image Ω C pc pos i hi hside] + exact simpleRoot_degree (mutatedRoots Ω C pc) i + +include hcoord in +lemma mutation_normalized_simple_side (i : I) (hi : i≠pc) + (hside : if pos then 0≤ mutationPairing Ω C pc i else mutationPairing Ω C pc i≤0) : + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit (normalizedSimple Ω (simpleRoot C i))= + normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) i) := by + rw [mutationCompletion,regrade_homogeneous_identity] + · rw [mutation_push_normalizedSimple,mutation_side_simple_image Ω C pc pos i hi hside] + · exact normalizedSimple_homogeneous Ω _ _ (mutation_side_simple_order Ω C coord hcoord pc pos i hi hside) + +variable {R : Type*} [CommRing R] (v : Rˣ) +local instance mutationSimpleSideRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance mutationSimpleSideAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance mutationSimpleSideAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +lemma mutationCompletion_congr_through (f g : PowerSeries (Torus v Ω)) (d N : ℕ) + (hd : (mutationSize Ω C pc+1)*d≤N) (hfg : ∀n≤N,coeff n f=coeff n g) : + coeff d (mutationCompletion Ω hΩ C coord pc pos v f)= + coeff d (mutationCompletion Ω hΩ C coord pc pos v g) := by + rw [mutationCompletion,mutationCompletion,coeff_map,coeff_map,regrade_coeff,regrade_coeff] + congr 1 + apply Finset.sum_congr rfl + intro n hn + rw [hfg n (by have HH:=Finset.mem_range.mp hn; omega)] + +include hcoord in +lemma actual_simple_wall_mutation_through (i : I) (hi : i≠pc) + (hside : if pos then 0≤ mutationPairing Ω C pc i else mutationPairing Ω C pc i≤0) + (h : M →+ ℝ) (d : ℕ) + (hg : RayGeneric C ((mutationSize Ω C pc+1)*d) (simpleRoot C i) h) : + coeff d (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit + (chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).val)= + coeff d (normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) i)) := by + rw [←mutation_normalized_simple_side Ω hΩ C coord hcoord pc pos i hi hside] + exact mutationCompletion_congr_through Ω hΩ C coord pc pos LaurentRay.vUnit _ _ d _ le_rfl + (pure_simple_wall Ω C coord hcoord i hΩ _ h hg) + +include hcoord in +lemma actual_simple_wall_mutation (i : I) (hi : i≠pc) + (hside : if pos then 0≤ mutationPairing Ω C pc i else mutationPairing Ω C pc i≤0) + (h : M →+ ℝ) (hg : ∀N,RayGeneric C N (simpleRoot C i) h) : + mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit + (chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).val= + normalizedSimple Ω (simpleRoot (mutatedRoots Ω C pc) i) := by + apply PowerSeries.ext + intro d + exact actual_simple_wall_mutation_through Ω hΩ C coord hcoord pc pos i hi hside h d (hg _) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/NamedIndependentRotation.lean b/lean/OAI/Combinatorics/Chromatic/Walls/NamedIndependentRotation.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1a9c16225997a408af87b5855512b0fd693b653 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/NamedIndependentRotation.lean @@ -0,0 +1,62 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.IndependentRotationComparison +import OAI.Combinatorics.Chromatic.QuantumTorus.IndependentElementReindex + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus +open Classical +noncomputable section +variable {K M V : Type*} [Field K] [AddCommGroup M] [Fintype V] [DecidableEq V] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (ell : M →+ ℤ) (p : M) (hp : ell p=1) + +include hΩ in +lemma independentElement_named_rotation (w : V → M) (a b c : V) + (hab : a≠b) (hbc : b≠c) (hac : a≠c) + (hwb : w b=w a+p) (hpa : Ω p (w a)=1) (hpc : Ω p (w c)= -1) + (hac0 : Ω (w a) (w c)=0) (hw : ∀x,x≠a → x≠b → x≠c → Ω p (w x)=0) (k : ℕ) : + pureAction v (complementOmega ell Ω) (complementAlpha ell p Ω) + (embed v Ω hΩ ell p hp (independentElement v Ω (Function.update w b (w c+p)) k)) = + embed v Ω hΩ ell p hp (independentElement v Ω w k) := by + let e : Fin 3 ↪ V := ⟨![a,b,c],by + intro i j hij + fin_cases i <;> fin_cases j <;> simp_all⟩ + let W := {x : V // x∉Set.range e} + let eqv := embeddingSumCompl e + let outside : W → M := fun x=>w x.val + have ho : ∀x:W, x.val≠a ∧ x.val≠b ∧ x.val≠c := by + intro x + refine ⟨?_,?_,?_⟩ + · intro h; exact x.property ⟨0,h.symm⟩ + · intro h; exact x.property ⟨1,h.symm⟩ + · intro h; exact x.property ⟨2,h.symm⟩ + have hold : w ∘ eqv=Sum.elim ![w a,w a+p,w c] outside := by + funext x + cases x with + | inl i => + change w (![a,b,c] i)=![w a,w a+p,w c] i + fin_cases i <;> simp [hwb] + | inr x => rfl + have hnew : (Function.update w b (w c+p)) ∘ eqv= + Sum.elim ![w a,w c+p,w c] outside := by + funext x + cases x with + | inl i => + change Function.update w b (w c+p) (![a,b,c] i)=![w a,w c+p,w c] i + fin_cases i <;> simp [hab,Ne.symm hbc] + | inr x => + change Function.update w b (w c+p) x.val=w x.val + exact Function.update_of_ne (ho x).2.1 _ _ + rw [independentElement_reindex v Ω (Function.update w b (w c+p)) eqv k, + independentElement_reindex v Ω w eqv k,hnew,hold] + exact independentElement_rotation v Ω hΩ ell p hp (w a) (w c) hpa hpc hac0 outside + (fun x=>hw x.val (ho x).1 (ho x).2.1 (ho x).2.2) k +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/NegativeRayCrossing.lean b/lean/OAI/Combinatorics/Chromatic/Walls/NegativeRayCrossing.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a9cf7eef8154e025efe0db32c4e465f7ff46d2c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/NegativeRayCrossing.lean @@ -0,0 +1,188 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallLineInitial +import OAI.Combinatorics.Chromatic.QuantumTorus.SectionCharts + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +lemma negative_ray_positive_side (F : CompletedPositive v Ω C) + (N : ℕ) (p : M) (h k H : M →+ ℝ) + (hg : RayGeneric C N p h) (hkp : 0hm (HD (n+1) (by omega) hn m hr) : OnPositiveRay p m).eval k).1.mpr hkp) + intro n hn + rw [chart_negative_refinement v Ω C h k H F N hs n hn] + have HE:=FormalLog.mul_coeff_congr + (chartNegative v Ω C k (chartZero v Ω C h F)).val (chartNegative v Ω C h F).val + 1 (chartNegative v Ω C h F).val n (fun j hj=>Hneg j (hj.trans hn)) (fun _ _=>rfl) + simpa only [one_mul] using HE + +lemma negative_ray_negative_side (F : CompletedPositive v Ω C) + (N : ℕ) (p : M) (h k H : M →+ ℝ) + (hg : RayGeneric C N p h) (hkp : k p<0) + (hs : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h k H m) : + ∀n≤N,coeff n (chartNegative v Ω C H F).val= + coeff n ((chartZero v Ω C h F).val*(chartNegative v Ω C h F).val) := by + have HD:=RayGeneric.ray_supported v Ω C hg F + have Hneg:=chartNegative_of_negative_through v Ω C k (chartZero v Ω C h F) N (by + intro n hn m hm + exact ((by_contra fun hr=>hm (HD (n+1) (by omega) hn m hr) : OnPositiveRay p m).eval k).2.2.mpr hkp) + intro n hn + rw [chart_negative_refinement v Ω C h k H F N hs n hn] + exact FormalLog.mul_coeff_congr _ _ _ _ n (fun j hj=>Hneg j (hj.trans hn)) (fun _ _=>rfl) + +lemma negative_ray_forward (F : CompletedPositive v Ω C) + (N : ℕ) (p : M) (h k Hplus Hminus : M →+ ℝ) + (hg : RayGeneric C N p h) (hk : k p≠0) + (hsplus : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h k Hplus m) + (hsminus : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h (-k) Hminus m) : + ∀n≤N,coeff n ((if k p<0 then (chartZero v Ω C h F).val else + invOfUnit (chartZero v Ω C h F).val 1)*(chartNegative v Ω C Hminus F).val)= + coeff n (chartNegative v Ω C Hplus F).val := by + intro n hn + split_ifs with hkp + · rw [negative_ray_negative_side v Ω C F N p h k Hplus hg hkp hsplus n hn] + exact FormalLog.mul_coeff_congr _ _ _ _ n (fun _ _=>rfl) + (fun j hj=>negative_ray_positive_side v Ω C F N p h (-k) Hminus hg + (by simpa using neg_pos.mpr hkp) hsminus j (hj.trans hn)) + · have hpos : 0rfl) + (fun j hj=>negative_ray_negative_side v Ω C F N p h (-k) Hminus hg + (by simpa using neg_neg_of_pos hpos) hsminus j (hj.trans hn)) + simpa only [←mul_assoc,invOfUnit_mul (chartZero v Ω C h F).val 1 + (chartZero v Ω C h F).property.1,one_mul] using Hm +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.FiniteEventTraversal +noncomputable section +variable {A : Type*} [Monoid A] + +def intervalWord (S : Finset ℝ) (lo hi : ℝ) (L : ℝ → A) : A := by + classical + exact (((S.filter (fun a=>lo0,∀δ,0<δ → δ<ε → Q (L a*W (a-δ)) (W (a+δ))) + (lo hi : ℝ) (hlo : lo∉S) (hhi : hi∉S) (horder : lolo + intro hi hhi horder hn + let U:=S.filter (fun a=>lolohhi (he ▸ hs)) + have hsU : s∈U:=Finset.mem_filter.mpr ⟨hs,by linarith,hshi⟩ + have hsa:=Finset.le_max' U s hsU + linarith + · intro hlt + linarith + have Hprod : intervalWord S lo hi L=L a*intervalWord S lo (a-δ) L:=by + unfold intervalWord + change ((U.sort (· ≥ ·)).map L).prod=L a*((V.sort (· ≥ ·)).map L).prod + rw [hUV,Finset.sort_insert] + · simp + · intro s hs + exact Finset.le_max' U s (hVU hs) + · exact haV + rw [Hprod,mul_assoc] + exact hQ.trans (hmul _ _ _ _ (hQ.refl _) HI) (hQ.trans (Hε δ hd hδε) HC) + · have hU0 : U=∅:=Finset.not_nonempty_iff_eq_empty.mp hU + have Hz : intervalWord S lo hi L=1:=by + unfold intervalWord + change ((U.sort (· ≥ ·)).map L).prod=1 + rw [hU0] + simp + rw [Hz,one_mul] + apply cell _ _ hlo hhi + intro s hs + constructor + · intro hls + by_contra hh + have hshi : shhi (he ▸ hs)) + have hsU : s∈U:=Finset.mem_filter.mpr ⟨hs,hls,hshi⟩ + rw [hU0] at hsU + exact Finset.notMem_empty _ hsU + · intro hhs + linarith +end +end ElementaryPositivity.FiniteEventTraversal + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/NonpJoint.lean b/lean/OAI/Combinatorics/Chromatic/Walls/NonpJoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e598e9b5e5f8832cd7a2469cd7f60183e1b6db5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/NonpJoint.lean @@ -0,0 +1,83 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteSignCharts + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries RootTruncation +noncomputable section +variable {R M E I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] + [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) + +def nonpSupportFrame (w : M →+ ℤ) (h : M →+ ℝ) (P : AddSubmonoid M) (n : ℤ) : AddSubmonoid M where + carrier:={m | m=0 ∨ (0H a ha i (hi.trans hj)) + +lemma planar_joint_support (e : M →+ E) (he : Function.Injective e) + (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) + (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) + (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + (r s : E) (hr : 0 simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hside + · exact ne_of_lt hside + · exact ne_of_gt hside + have hker : ∀j,coeff j Jc.val∈supportedSubring v Ω kM.ker.toAddSubmonoid:= + completedCut_supported v Ω C N J _ (fun j _=>chartZero_supported_kernel v Ω C kM F j) + have hplane : ∀j,coeff j Jc.val∈supportedSubring v Ω (planeRoots e (e r) s):=by + apply completedCut_supported v Ω C N J _ + intro j hj m hm + by_contra hval + have hmroot:=chart_root_of_ne v Ω C J j m hval + have hmz : kM m=0:=by + by_contra HH; exact hval (chartZero_supported_kernel v Ω C kM F j m HH) + exact hm (hzero j hj m hmroot hmz) + have hcut (a : M →+ ℝ) : ∀j≤N,coeff j (chartZero v Ω C a Jc).val=coeff j (chartZero v Ω C a J).val:=by + apply chartZero_congr_through v Ω C a Jc J N + exact fun j hj=>coeff_cut_of_le J.val hj + have hrootpos (q : M) (j : ℕ) (hj : 0 simp only [cutSide,Bool.false_eq_true,ite_false,ite_true] at hside ⊢ + · exact hsign.2.1 hside + · exact hsign.1 hside + apply HI q d hd hdq _ hgen hside' j hj m ?_ hw + rw [HRef j hj,←hcut _ j hj] + exact hval + · have hmroot:=chart_root_of_ne v Ω C _ j m hval + have hmP : m∈planeRoots e (e r) s:=by + by_contra HH + exact hval ((chartThree_supported v Ω C (incomingCovector Ω q) (planeRoots e (e r) s) Jc hplane).2.1 j m HH) + have hmqr : B (e m) (e q)=0:=by + rw [hcomp] + have HK:=chartZero_supported_kernel v Ω C (incomingCovector Ω q) Jc j + by_contra HH + exact hval (HK m HH) + have hqm : OnPositiveRay q m:=positive_ray_of_pairing_zero e he B hB L (e r) s C hdeg hrs + m q j d hj0 hd hmroot hdq hmP hqP hmqr + have hqr : Ω q r=0:=by + have HH:=(hqm.eval h).2.1.mp hh + change (Ω q r:ℝ)=0 at HH + exact_mod_cast HH + have hhEq:=htargeteq q d hd hdq hqP hqr + rw [hhEq,hcut h j hj] at hval + exact HR j hj m hval hw + have hQ:=planar_joint_support v Ω C e he B hB hcomp L hdeg (e r) s + (by rw [hdeg dr r hrd]; exact_mod_cast hdr) hrs Jc hplane N Q hhIncoming (-h) + intro j hj m hval hw + apply nonpSupportFrame_target (w:=w) (h:=h) (n:=n) (m:=m) (P:=P) ?_ hw ?_ + · by_contra HH + have Hzero:=hQ j hj m HH + rw [hcut (-h) j hj] at Hzero + exact hval Hzero + · have HK:=chartZero_supported_kernel v Ω C (-h) J j + have Hneg : (-h) m=0:=by by_contra HH; exact hval (HK m HH) + simpa only [AddMonoidHom.neg_apply,neg_eq_zero] using Hneg +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/OrderedRootReordering.lean b/lean/OAI/Combinatorics/Chromatic/Walls/OrderedRootReordering.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f352c57924ca28367cfcc5f7e084bcab48320d3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/OrderedRootReordering.lean @@ -0,0 +1,209 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.GeometricRootClosure +import OAI.Combinatorics.Chromatic.Walls.RootClosureFacts + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open RawShuffle SlopeArithmetic WeightedTorusSeries WallUnits UnitSelections PowerSeries +noncomputable section +variable {M J : Type*} [AddCommGroup M] [Fintype J] +variable (Ω : M→+M→+ℤ) (C : (J→ℤ)→+M) (L h : M→+ℝ) (V : AddSubmonoid M) + +def orderedPlaneProducts : Set (PowerSeries (Torus LaurentRay.vUnit Ω)) := + {F | ∃l : List (WallUnitDatum M), + (∀u∈l,u.Allowed C (fun p=>p∈V ∧ 00≤Ω u.root v.root) ∧ F=(l.map (WallUnitDatum.value Ω)).prod} + +lemma indexedUnit_bool (a : ℕ) (k : ℤ) : + indexedUnit (if decide (a=0) then 0 else 1) k=indexedUnit a k := by + by_cases ha : a=0 <;> simp [indexedUnit,ha] + +lemma listLiteral_product (l : List (WallUnitDatum M)) : + ((List.finRange l.length).map (literalAxis (fun i=> (l.get i).parameter) + (fun i=>decide ((l.get i).kind=0)) Ω (rootSum (fun i=> (l.get i).root)) + (fun i=> (l.get i).degree))).prod=(l.map (WallUnitDatum.value Ω)).prod := by + have H : (List.finRange l.length).map (literalAxis (fun i=> (l.get i).parameter) + (fun i=>decide ((l.get i).kind=0)) Ω (rootSum (fun i=> (l.get i).root)) + (fun i=> (l.get i).degree)) = + (List.finRange l.length).map (fun i=>(l.get i).value Ω) := by + apply List.map_congr_left + intro i hi + unfold literalAxis literalAxisScalar elementaryDiagonal WallUnitDatum.value + rw [rootSum_single,one_nsmul,indexedUnit_bool] + rw [H] + change ((List.finRange l.length).map (WallUnitDatum.value Ω ∘ l.get)).prod=_ + rw [←List.map_map,List.map_get_finRange] + +variable (hΩ : ∀p,Ω p p=0) (t : ℝ) +variable (hplane : ∀p∈V,∀q∈V,(Ω p q:ℝ)=t*(h p*L q-L p*h q)) + +include hΩ hplane in +lemma orderedPlane_zero_finite {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : F∈orderedPlaneProducts Ω C L V) : + InPrecisionClosure LaurentRay.vUnit Ω + (literalRootProducts Ω C (fun p=>p∈V ∧ h p=0)) + (PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) F) := by + classical + obtain ⟨l,hl,ho,rfl⟩:=hF + let p : Fin l.length→M := fun i=>(l.get i).root + let w : Fin l.length→ℕ := fun i=>(l.get i).degree + let c : Fin l.length→ℝ := fun i=>L (p i) + let η : Fin l.length→ℝ := fun i=>h (p i) + have hall : ∀i,(l.get i).Allowed C (fun p=>p∈V ∧ 0hl _ (List.get_mem _ _) + let : Fact (∀i,0(hall i).1⟩ + have hc : ∀i,0(hall i).2.2.2 + have hp : ∀i j,(Ω (p i) (p j):ℝ)=t*(η i*c j-c i*η j) := + fun i j=>hplane _ (hall i).2.2.1 _ (hall j).2.2.1 + have hh : ∀d,h (rootSum p d)=slopeValue c η 0 d := rootSum_slope_zero p h c + have hsort : (List.finRange l.length).Pairwise (fun i j=>0≤Ω (p i) (p j)) := by + apply (List.pairwise_map (f:=l.get) + (R:=fun u v : WallUnitDatum M=>0≤Ω u.root v.root)).mp + simpa only [List.map_get_finRange] using ho + have hv : ∀d∈slopeDimensions c η hc 0,rootSum p d∈V ∧ h (rootSum p d)=0 := by + intro d hd + refine ⟨rootSum_mem p V (fun i=>(hall i).2.2.1) d,?_⟩ + rw [hh] + by_cases h0 : d=0 + · subst d; exact slopeValue_zero c η 0 + · exact (slopeValue_eq_zero_iff c η hc 0 d h0).mpr (hd.resolve_left h0) + rw [←listLiteral_product Ω l] + exact geometric_zero_rootClosure Ω hΩ p (fun i=>(l.get i).parameter) + (fun i=>decide ((l.get i).kind=0)) w c η hc t hp (List.finRange l.length) + (List.nodup_finRange _) (List.toFinset_finRange _) hsort C + (rootSum_rootDegree p w C (fun i=>(hall i).2.1)) h 0 hh + (fun p=>p∈V ∧ h p=0) hv + +lemma orderedPlaneProducts_graded {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : F∈orderedPlaneProducts Ω C L V) : SeriesGraded LaurentRay.vUnit Ω C F := by + obtain ⟨l,hl,ho,H⟩:=hF + exact literalRootProducts_graded Ω C (fun p=>p∈V ∧ 0p∈V ∧ h p=0)) + (PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) F) := by + apply hF.zeroFactor Ω C (fun G hG=>orderedPlaneProducts_graded Ω C L V hG) h + exact fun G hG=>orderedPlane_zero_finite Ω C L h V hΩ t hplane hG +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries LaurentPrecision Filter WallUnits +noncomputable section +variable {M J A ι : Type*} [AddCommGroup M] [Fintype J] +variable (Ω : M→+M→+ℤ) (C : (J→ℤ)→+M) + +lemma SeriesGraded.list_prod (s : List A) + (F : A→PowerSeries (Torus LaurentRay.vUnit Ω)) + (hF : ∀a∈s,SeriesGraded LaurentRay.vUnit Ω C (F a)) : + SeriesGraded LaurentRay.vUnit Ω C (s.map F).prod := by + induction s with + | nil=>simpa using SeriesGraded.one LaurentRay.vUnit Ω C + | cons a s ih=> + simpa only [List.map_cons,List.prod_cons] using + (hF a (by simp)).mul LaurentRay.vUnit Ω C (ih (fun x hx=>hF x (by simp [hx]))) + +lemma SeriesConverges.list_prod (l : Filter ι) (s : List A) + (f : A→ι→PowerSeries (Torus LaurentRay.vUnit Ω)) + (F : A→PowerSeries (Torus LaurentRay.vUnit Ω)) + (hf : ∀a∈s,SeriesConverges LaurentRay.vUnit Ω l (f a) (F a)) + (hg : ∀a∈s,∀i,SeriesGraded LaurentRay.vUnit Ω C (f a i)) + (hG : ∀a∈s,SeriesGraded LaurentRay.vUnit Ω C (F a)) : + SeriesConverges LaurentRay.vUnit Ω l (fun i=>(s.map (fun a=>f a i)).prod) (s.map F).prod := by + induction s with + | nil=>simpa using seriesConverges_const LaurentRay.vUnit Ω l 1 + | cons a s ih=> + simpa only [List.map_cons,List.prod_cons] using + (hf a (by simp)).mul LaurentRay.vUnit Ω C l + (ih (fun x hx=>hf x (by simp [hx])) (fun x hx=>hg x (by simp [hx])) + (fun x hx=>hG x (by simp [hx]))) + (hg a (by simp)) + (fun i=>SeriesGraded.list_prod Ω C s (fun x=>f x i) (fun x hx=>hg x (by simp [hx]) i)) + (hG a (by simp)) + (SeriesGraded.list_prod Ω C s F (fun x hx=>hG x (by simp [hx]))) + +lemma literal_lists_ordered_product (L : M→+ℝ) (V : AddSubmonoid M) + (s : List A) (P : A→M→Prop) + (g : A→PowerSeries (Torus LaurentRay.vUnit Ω)) + (hg : ∀a∈s,g a∈literalRootProducts Ω C (P a)) + (hP : ∀a∈s,∀p,P a p→p∈V ∧ 0∀p q,P a p→P b q→0≤Ω p q)) : + (s.map g).prod∈orderedPlaneProducts Ω C L V := by + classical + let ls (a : A) : List (WallUnitDatum M) := + if ha : a∈s then Classical.choose (hg a ha) else [] + have hls : ∀a∈s,(∀u∈ls a,u.Allowed C (P a)) ∧ + g a=((ls a).map (WallUnitDatum.value Ω)).prod:=by + intro a ha + dsimp [ls] + rw [dite_eq_left ha] + exact Classical.choose_spec (hg a ha) + refine ⟨s.flatMap ls,?_,?_,?_⟩ + · intro u hu + obtain ⟨a,ha,hu⟩:=List.mem_flatMap.mp hu + have H:=(hls a ha).1 u hu + exact ⟨H.1,H.2.1,hP a ha u.root H.2.2⟩ + · rw [List.pairwise_flatMap] + constructor + · intro a ha + apply List.pairwise_iff_getElem.mpr + intro i j hi hj hij + exact hself a ha _ _ ((hls a ha).1 _ (List.getElem_mem hi)).2.2 + ((hls a ha).1 _ (List.getElem_mem hj)).2.2 + · apply hpair.imp_of_mem + intro a b ha hb H u hu w hw + exact H u.root w.root ((hls a ha).1 u hu).2.2 ((hls b hb).1 w hw).2.2 + · rw [List.map_flatMap,List.flatMap_def,List.prod_flatten] + simp only [List.map_map] + congr 1 + apply List.map_congr_left + intro a ha + exact (hls a ha).2 + +theorem completed_ordered_ray_product (L : M→+ℝ) (V : AddSubmonoid M) + (s : List A) (P : A→M→Prop) + (F : A→PowerSeries (Torus LaurentRay.vUnit Ω)) + (hF : ∀a∈s,InPrecisionClosure LaurentRay.vUnit Ω (literalRootProducts Ω C (P a)) (F a)) + (hP : ∀a∈s,∀p,P a p→p∈V ∧ 0∀p q,P a p→P b q→0≤Ω p q)) : + InPrecisionClosure LaurentRay.vUnit Ω (orderedPlaneProducts Ω C L V) (s.map F).prod := by + classical + let g (a : A) (T : Finset (PrecisionTest (M:=M))) := + if ha : a∈s then precisionApprox LaurentRay.vUnit Ω (hF a ha) T else 1 + have hg : ∀a∈s,∀T,g a T∈literalRootProducts Ω C (P a):=by + intro a ha T + dsimp [g] + rw [dite_eq_left ha] + exact precisionApprox_mem LaurentRay.vUnit Ω (hF a ha) T + have hconv : ∀a∈s,SeriesConverges LaurentRay.vUnit Ω Filter.atTop (g a) (F a):=by + intro a ha + have he : g a=precisionApprox LaurentRay.vUnit Ω (hF a ha):=by + funext T; dsimp [g]; rw [dite_eq_left ha] + rw [he] + exact precisionApprox_converges LaurentRay.vUnit Ω (hF a ha) + apply InPrecisionClosure.of_converges LaurentRay.vUnit Ω Filter.atTop + (SeriesConverges.list_prod Ω C Filter.atTop s g F hconv + (fun a ha T=>literalRootProducts_graded Ω C (P a) (hg a ha T)) + (fun a ha=>(hF a ha).graded Ω C (fun G hG=>literalRootProducts_graded Ω C (P a) hG))) + apply Eventually.of_forall + intro T + exact inPrecisionClosure_self LaurentRay.vUnit Ω + (literal_lists_ordered_product Ω C L V s P (fun a=>g a T) + (fun a ha=>hg a ha T) hP hself hpair) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/Pack.lean b/lean/OAI/Combinatorics/Chromatic/Walls/Pack.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b939393e4e03f4a43ab6fa2389d747e53696750 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/Pack.lean @@ -0,0 +1,180 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Split + +namespace OAI + +section +namespace ElementaryPositivity.PackConvolution +open ElementaryPositivity.ShuffleConvolution +variable {I : Type*} [Fintype I] {A : I → Type*} +variable [∀ i,DecidableEq (A i)] +variable {R : Type*} [CommSemiring R] + +abbrev Pack := ∀ i, Finset (A i) +abbrev Cut (s : Pack (A := A)) := ∀ i, Split (s i) + +def left {s : Pack (A := A)} (p : Cut s) : Pack (A := A) := fun i => (p i).val.1 +def right {s : Pack (A := A)} (p : Cut s) : Pack (A := A) := fun i => (p i).val.2 + +def kernel (w : (Σi,A i) → (Σi,A i) → R) (s t : Pack (A := A)) : R := + ∏ i, ∏ x ∈ s i, ∏ j, ∏ y ∈ t j, w ⟨i,x⟩ ⟨j,y⟩ + +lemma kernel_union_left (w : (Σi,A i) → (Σi,A i) → R) (s t u : Pack (A := A)) + (h : ∀ i,Disjoint (s i) (t i)) : + kernel w (fun i => s i ∪ t i) u = kernel w s u * kernel w t u := by + simp only [kernel, Finset.prod_union (h _), Finset.prod_mul_distrib] +lemma kernel_union_right (w : (Σi,A i) → (Σi,A i) → R) (s t u : Pack (A := A)) + (h : ∀ i,Disjoint (t i) (u i)) : + kernel w s (fun i => t i ∪ u i) = kernel w s t * kernel w s u := by + simp only [kernel, Finset.prod_union (h _), Finset.prod_mul_distrib] + +variable [DecidableEq I] [∀ i,Fintype (A i)] + +abbrev LeftIndex (s : Pack (A := A)) := Σ p : Cut s, Cut (left p) +abbrev RightIndex (s : Pack (A := A)) := Σ p : Cut s, Cut (right p) + +def distribute {J : Type*} {B : J → Type*} {C : ∀ j, B j → Type*} : + (Σ f : ∀ j,B j, ∀ j,C j (f j)) ≃ (∀ j,Σ b : B j,C j b) where + toFun z j := ⟨z.1 j,z.2 j⟩ + invFun z := ⟨fun j => (z j).1,fun j => (z j).2⟩ + left_inv _ := rfl + right_inv _ := rfl + +def rebracket (s : Pack (A := A)) : LeftIndex s ≃ RightIndex s := + distribute.trans ((Equiv.piCongrRight fun i => ShuffleConvolution.rebracket (s i)).trans + distribute.symm) + +def shuffle (w : (Σi,A i) → (Σi,A i) → R) + (f g : Pack (A := A) → R) (s : Pack (A := A)) : R := + ∑ p : Cut s, f (left p) * g (right p) * kernel w (left p) (right p) + +lemma shuffle_assoc (w : (Σi,A i) → (Σi,A i) → R) + (f g h : Pack (A := A) → R) : + shuffle w (shuffle w f g) h = shuffle w f (shuffle w g h) := by + funext s + have lhs : shuffle w (shuffle w f g) h s = + ∑ z : LeftIndex s, (f (left z.2) * g (right z.2) * kernel w (left z.2) (right z.2)) * + h (right z.1) * kernel w (left z.1) (right z.1) := by + simp only [shuffle, Fintype.sum_sigma, Finset.sum_mul] + have rhs : shuffle w f (shuffle w g h) s = + ∑ z : RightIndex s, f (left z.1) * + (g (left z.2) * h (right z.2) * kernel w (left z.2) (right z.2)) * + kernel w (left z.1) (right z.1) := by + simp only [shuffle, Fintype.sum_sigma, Finset.mul_sum, Finset.sum_mul] + rw [lhs,rhs,← (rebracket s).sum_comp] + apply Finset.sum_congr rfl + intro z hz + change (f (left z.2) * g (right z.2) * kernel w (left z.2) (right z.2)) * + h (right z.1) * kernel w (left z.1) (right z.1) = + f (left z.2) * (g (right z.2) * h (right z.1) * kernel w (right z.2) (right z.1)) * + kernel w (left z.2) (fun i => right z.2 i ∪ right z.1 i) + have hu : left z.1 = fun i => left z.2 i ∪ right z.2 i := by + funext i; exact (z.2 i).property.2.symm + have hk := congrArg (fun t => kernel w t (right z.1)) hu + rw [hk, kernel_union_left w (left z.2) (right z.2) (right z.1) (fun i => (z.2 i).property.1), + kernel_union_right w (left z.2) (right z.2) (right z.1) (fun i => + (z.1 i).property.1.mono_left (z.2 i).right_subset)] + ac_rfl + +end ElementaryPositivity.PackConvolution + +namespace ElementaryPositivity.PackEnumeration +variable {A : Type*} [DecidableEq A] + +abbrev Split (s : Finset A) := + {p : Finset A × Finset A // Disjoint p.1 p.2 ∧ p.1 ∪ p.2 = s} + +def embedding {n : ℕ} {s : Finset A} (r : Fin n ≃ s) : Fin n ↪ A := + r.toEmbedding.trans (Function.Embedding.subtype _) + +omit [DecidableEq A] in +lemma map_univ {n : ℕ} {s : Finset A} (r : Fin n ≃ s) : + Finset.univ.map (embedding r) = s := by + ext x + simp only [Finset.mem_map, Finset.mem_univ, true_and, embedding, + Function.Embedding.trans_apply, Equiv.coe_toEmbedding, Function.Embedding.subtype_apply] + constructor + · rintro ⟨y,rfl⟩; exact (r y).property + · intro hx + exact ⟨r.symm ⟨x,hx⟩,congrArg Subtype.val (r.apply_symm_apply ⟨x,hx⟩)⟩ + +def split {n : ℕ} {s : Finset A} (r : Fin n ≃ s) (t : Finset (Fin n)) : Split s := + ⟨(t.map (embedding r),tᶜ.map (embedding r)), + (Finset.disjoint_map _).mpr (disjoint_compl_right), by + rw [← Finset.map_union, Finset.union_compl, map_univ]⟩ + +lemma split_injective {n : ℕ} {s : Finset A} (r : Fin n ≃ s) : Function.Injective (split r) := by + intro a b hab + apply Finset.map_injective (embedding r) + exact congrArg (fun p => p.val.1) hab + +lemma split_right_unique {s : Finset A} (p q : Split s) (h : p.val.1 = q.val.1) : p = q := by + apply Subtype.ext + apply Prod.ext h + have hp := p.property + have hq := q.property + apply Finset.ext + intro x + have hh : x ∈ p.val.2 ↔ x ∈ s ∧ x ∉ p.val.1 := by + have hu : x ∈ s ↔ x ∈ p.val.1 ∨ x ∈ p.val.2 := by + simpa only [Finset.mem_union] using (congrArg (fun t => x ∈ t) hp.2.symm).to_iff + have hd : ¬(x ∈ p.val.1 ∧ x ∈ p.val.2) := by + intro hmem + exact Finset.disjoint_left.mp hp.1 hmem.1 hmem.2 + tauto + have hh' : x ∈ q.val.2 ↔ x ∈ s ∧ x ∉ q.val.1 := by + have hu : x ∈ s ↔ x ∈ q.val.1 ∨ x ∈ q.val.2 := by + simpa only [Finset.mem_union] using (congrArg (fun t => x ∈ t) hq.2.symm).to_iff + have hd : ¬(x ∈ q.val.1 ∧ x ∈ q.val.2) := by + intro hmem + exact Finset.disjoint_left.mp hq.1 hmem.1 hmem.2 + tauto + rw [hh,hh',h] + +lemma split_surjective {n : ℕ} {s : Finset A} (r : Fin n ≃ s) : Function.Surjective (split r) := by + intro p + let t := Finset.univ.filter fun j => ↑(r j) ∈ p.val.1 + refine ⟨t,split_right_unique _ _ ?_⟩ + change t.map (embedding r) = p.val.1 + ext x + simp only [Finset.mem_map] + constructor + · rintro ⟨j,hj,rfl⟩ + exact (Finset.mem_filter.mp hj).2 + · intro hx + have hs : x ∈ s := p.property.2 ▸ Finset.mem_union_left p.val.2 hx + refine ⟨r.symm ⟨x,hs⟩,?_,?_⟩ + · simp [t,hx] + · exact congrArg Subtype.val (r.apply_symm_apply ⟨x,hs⟩) + +noncomputable def splitEquiv {n : ℕ} {s : Finset A} (r : Fin n ≃ s) : Finset (Fin n) ≃ Split s := + Equiv.ofBijective (split r) ⟨split_injective r,split_surjective r⟩ + +@[simp] lemma splitEquiv_left {n : ℕ} {s : Finset A} (r : Fin n ≃ s) (t : Finset (Fin n)) : + (splitEquiv r t).val.1 = t.map (embedding r) := rfl +@[simp] lemma splitEquiv_right {n : ℕ} {s : Finset A} (r : Fin n ≃ s) (t : Finset (Fin n)) : + (splitEquiv r t).val.2 = tᶜ.map (embedding r) := rfl + +noncomputable def sizedSplitEquiv {n : ℕ} {s : Finset A} (r : Fin n ≃ s) (k : ℕ) : + {t : Finset (Fin n) // t.card = k} ≃ {p : Split s // p.val.1.card = k} := + (splitEquiv r).subtypeEquiv (by intro t; simp) + +noncomputable def mapEquiv {B : Type*} (f : B ↪ A) (t : Finset B) : ↥t ≃ ↥(t.map f) := + Equiv.ofBijective (fun x => ⟨f x.val,Finset.mem_map.mpr ⟨x.val,x.property,rfl⟩⟩) + ⟨by + intro x y h + apply Subtype.ext + exact f.injective (congrArg Subtype.val h), by + intro y + obtain ⟨x,hx,hxy⟩ := Finset.mem_map.mp y.property + exact ⟨⟨x,hx⟩,Subtype.ext hxy⟩⟩ + +omit [DecidableEq A] in +@[simp] lemma mapEquiv_apply {B : Type*} (f : B ↪ A) (t : Finset B) (x : t) : + ↑(mapEquiv f t x) = f x.val := rfl + +end ElementaryPositivity.PackEnumeration + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PathOldTransport.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PathOldTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..42d912106d4b2dc7223960679f9b6d4b7df43b2a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PathOldTransport.lean @@ -0,0 +1,142 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.LineOldTransport + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +def actualPathWord {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) (N : ℕ) : + List (ComparisonCrossing LaurentRay.vUnit Ω (nonpDegree coord pc) (pureDegree coord pc) + (mutationSize Ω C pc+1)) := + match p with + | .nil _=>[] + | .append s p=>actualLineWord Ω C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi N++ + actualPathWord p N + +def covectorNegativeUnit (a : Module.Dual ℝ E) := completedBiUnit LaurentRay.vUnit Ω C coord hcoord pc + (chartNegative LaurentRay.vUnit Ω C (a.toAddMonoidHom.comp e) (simpleTotalTransport Ω C)) + +lemma comparisonWordOld_append {K M : Type*} [Field K] [AddCommGroup M] + (u : Kˣ) (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) + (δ k : M →+ ℤ) (p : M) (hp : k p=1) (hδ : δ p=0) (B : ℕ) + (l l' : List (ComparisonCrossing u Ω δ k B)) : + comparisonWordOld u Ω hΩ δ k p hp hδ B (l++l')= + comparisonWordOld u Ω hΩ δ k p hp hδ B l*comparisonWordOld u Ω hΩ δ k p hp hδ B l' := by + simp only [comparisonWordOld,List.map_append,List.prod_append] + +include he hdeg in +theorem actualPath_old_transport {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) (N : ℕ) : + oldCoefficientsEqual Ω coord pc N + (comparisonWordOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p N)* + covectorNegativeUnit Ω C coord hcoord pc e a) + (covectorNegativeUnit Ω C coord hcoord pc e b) := by + induction p with + | nil=> + simpa only [actualPathWord,comparisonWordOld,List.map_nil,List.prod_nil,one_mul] + using (oldCoefficientsEqual_equivalence Ω coord pc N).refl + _ + | append s p ih=> + rw [actualPathWord,comparisonWordOld_append,mul_assoc] + apply (oldCoefficientsEqual_equivalence Ω coord pc N).trans + (oldCoefficientsEqual_mul Ω coord pc N _ _ _ _ + ((oldCoefficientsEqual_equivalence Ω coord pc N).refl _) ih) + exact actualLine_old_transport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi N (s.start_regular N) (s.finish_regular N) s.ordered + +include he hdeg in +theorem actualPath_old_loop {a : Module.Dual ℝ E} (p : GenericLinePath C e a a) (N : ℕ) : + ∀n≤N,coeff n (comparisonWordOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p N)).val.val=coeff n 1 := by + have HH:=actualPath_old_transport Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p N + have HI:=(oldCoefficientsEqual_equivalence Ω coord pc N).refl + (covectorNegativeUnit Ω C coord hcoord pc e a)⁻¹ + have HX:=oldCoefficientsEqual_mul Ω coord pc N _ _ _ _ HH HI + simpa only [mul_assoc,mul_inv_cancel,mul_one,oldCoefficientsEqual,Units.val_one,OneMemClass.coe_one] using HX +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +lemma WordRefines.append {K M : Type*} [Field K] [AddCommGroup M] + (u : Kˣ) (Ω : M →+ M →+ ℤ) (δ k : M →+ ℤ) (B D : ℕ) + {l l' s s' : List (ComparisonCrossing u Ω δ k B)} + (hl : WordRefines u Ω δ k B D l l') (hs : WordRefines u Ω δ k B D s s') : + WordRefines u Ω δ k B D (l++s) (l'++s') := by + induction hl with + | nil=>exact hs + | cons hc hl ih=>exact .cons hc ih + | insert a hf hi he hl ih=>exact .insert a hf hi he ih + +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] + [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (hΩ : ∀m,Ω m m=0) +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) (pc : I) +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +lemma actualPathWord_refines {a b : Module.Dual ℝ E} (p : GenericLinePath C e a b) + (D A N : ℕ) (hA : 1≤A) (hDA : (mutationSize Ω C pc+1)*D≤A) (hAN : A≤N) : + WordRefines LaurentRay.vUnit Ω (nonpDegree coord pc) (pureDegree coord pc) + (mutationSize Ω C pc+1) D + (actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p A) + (actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p N) := by + induction p with + | nil=>exact .nil + | append s p ih=> + exact WordRefines.append _ _ _ _ _ _ + (actualLineWord_refines Ω C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi D A N hA hDA hAN) ih + +include he hdeg in +theorem actualPath_rational_loop_coefficient {a : Module.Dual ℝ E} + (p : GenericLinePath C e a a) (D : ℕ) + (f : PowerSeries (FiberTorus LaurentRay.vUnit (complementOmega (pureDegree coord pc) Ω) + (complementAlpha (pureDegree coord pc) (simpleRoot C pc) Ω))) : + coeff D (comparisonWordAction LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p + (max 1 ((mutationSize Ω C pc+1)*D))) f)=coeff D f := by + apply finite_refinement_import LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) _ D _ _ f + · intro n + rw [LaurentRay.vUnit_zpow] + exact UnitSelections.laurent_q_not_root n + · intro N + let A:=max 1 ((mutationSize Ω C pc+1)*D) + refine ⟨actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p (max N A),?_,?_⟩ + · exact actualPathWord_refines Ω C coord hcoord pc e he S hS hcomp L hdeg p D A (max N A) + (le_max_left _ _) (le_max_right _ _) (le_max_right _ _) + · intro n hn + exact actualPath_old_loop Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg p (max N A) + n (hn.trans (le_max_left _ _)) +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PathRoot.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PathRoot.lean new file mode 100644 index 0000000000000000000000000000000000000000..46855e3693c453d14a4d04132fcedcc8b003fb27 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PathRoot.lean @@ -0,0 +1,201 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularScheduledRoots + +namespace OAI + +section +namespace ElementaryPositivity.PathLattice +open scoped BigOperators +variable {R : Type*} [CommRing R] {d : ℕ} + +lemma roots_single (i : Fin d) (r : R) : roots (Pi.single i r)=r • gap i := by + rw [roots_apply,Finset.sum_eq_single i] + · simp + · intro j _ hj + simp [Ne.symm hj] + · simp + +lemma roots_coord_single (a : Fin (d+1)) : + roots (coord (Pi.single a (1:R))) = Pi.single a 1 - Pi.single 0 1 := by + induction a using Fin.induction with + | zero => + have hz : coord (Pi.single (0:Fin (d+1)) (1:R))=0 := by + ext i + simp only [coord_single,Fin.val_zero,not_lt_zero,ite_false,Pi.zero_apply] + rw [hz,map_zero,sub_self] + | succ i ih => + have H : roots (coord (Pi.single i.succ (1:R))) - + roots (coord (Pi.single i.castSucc (1:R))) = gap i := by + rw [←map_sub,←map_sub] + change roots (coord (gap i))=gap i + rw [coord_gap,roots_single,one_smul] + rw [ih,gap] at H + exact sub_eq_iff_eq_add.mp H |>.trans (by abel) + +lemma roots_coord (m : Fin (d+1) → R) : + roots (coord m) = m - weight m • Pi.single 0 1 := by + have hm : m=∑ a : Fin (d+1),m a • Pi.single a 1 := by + ext a + simp only [Finset.sum_apply,Pi.smul_apply,Pi.single_apply,smul_eq_mul] + rw [Finset.sum_eq_single a] + · simp + · intro b _ hb + simp [Ne.symm hb] + · simp + calc + roots (coord m) = ∑ a, m a • roots (coord (Pi.single a (1:R))) := by + conv_lhs => rw [hm] + simp only [map_sum,map_smul] + _ = ∑ a, m a • (Pi.single a (1:R)-Pi.single 0 1) := by simp_rw [roots_coord_single] + _ = (∑ a,m a • Pi.single a (1:R)) - (∑ a,m a • Pi.single 0 1) := by + simp only [smul_sub,Finset.sum_sub_distrib] + _ = m-weight m • Pi.single 0 1 := by rw [←hm,←Finset.sum_smul,weight_apply] + +lemma coord_nonneg (m : Fin (d+1) → ℤ) (hm : ∀ a,0 ≤ m a) (i : Fin d) : 0≤coord m i := by + rw [coord_apply] + apply Finset.sum_nonneg + intro a _ + split_ifs <;> first | exact hm a | omega + +lemma vertex_support_rootDegree (m : Fin (d+1) → ℤ) (hm : ∀a,0 ≤ m a) : + ∃ k, QuantumTorus.HasRootDegree (roots (R:=ℤ) (d:=d)).toAddMonoidHom k + (m-weight m • Pi.single 0 1) := by + let c : Fin d → ℕ := fun i => (coord m i).toNat + have hc : (fun i => (c i:ℤ))=coord m := by + ext i + exact Int.toNat_of_nonneg (coord_nonneg m hm i) + refine ⟨∑i,c i,c,rfl,?_⟩ + change roots (fun i => (c i:ℤ))=m-weight m • Pi.single 0 1 + rw [hc,roots_coord] + +lemma gap_prefix_nonpositive (k : Fin (d+1)) (i : Fin d) : + (∑ a : Fin (d+1), if a≤k then gap (R:=ℤ) i a else 0) ≤ 0 := by + have H (b : Fin (d+1)) : (∑a : Fin (d+1),if a≤k then (Pi.single b (1:ℤ)) a else 0)= + if b≤k then 1 else 0 := by + rw [Finset.sum_eq_single b] + · simp + · intro a _ ha + simp [Ne.symm ha] + · simp + have he : (∑ a : Fin (d+1),if a≤k then gap (R:=ℤ) i a else 0)= + (if i.succ≤k then 1 else 0)-(if i.castSucc≤k then 1 else 0) := by + rw [←H i.succ,←H i.castSucc,←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro a _ + simp only [gap,Pi.sub_apply] + split_ifs <;> rfl + rw [he] + simp only [Fin.le_iff_val_le_val,Fin.val_succ,Fin.val_castSucc] + split_ifs <;> omega +end ElementaryPositivity.PathLattice + +end +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators +open Classical +noncomputable section +variable {n : ℕ} +abbrev GapIndex (n : ℕ) := (i : Fin n) × Fin (i.val+2) + +def levelNode (i : Fin n) (j : Fin (i.val+3)) : Vertex n (Cell n) := + if h0 : j.val=0 then .inl i.castSucc + else if he : j.val=i.val+2 then .inl i.succ + else .inr ⟨i,⟨i.val+1-j.val,by omega⟩⟩ + +def afterGap (g : GapIndex n) : Vertex n (Cell n) → Prop + | .inl a => g.1.val < a.val + | .inr b => g.1.val < b.1.val ∨ + (g.1=b.1 ∧ b.2.val+g.2.val < g.1.val+1) + +lemma afterGap_node (g : GapIndex n) (i : Fin n) (j : Fin (i.val+3)) : + afterGap g (levelNode i j) ↔ g.1.val < i.val ∨ (g.1=i ∧ g.2.val < j.val) := by + unfold levelNode + split_ifs with h0 he + · simp only [afterGap,Fin.val_castSucc,h0,not_lt_zero,and_false,or_false] + · simp only [afterGap,Fin.val_succ,he,Fin.ext_iff] + have hg:=g.2.isLt + omega + · simp only [afterGap,Fin.ext_iff] + have hj:=j.isLt + omega + +variable {R : Type*} [CommRing R] +def forwardGap (g : GapIndex n) : Vertex n (Cell n) → R := + Pi.single (levelNode g.1 g.2.succ) 1-Pi.single (levelNode g.1 g.2.castSucc) 1 + +def forwardCoord : (Vertex n (Cell n) → R) →ₗ[R] (GapIndex n → R) := + LinearMap.pi fun g => ∑ a : Vertex n (Cell n), if afterGap g a then LinearMap.proj a else 0 + +lemma forwardCoord_apply (m : Vertex n (Cell n) → R) (g : GapIndex n) : + forwardCoord m g=∑a,if afterGap g a then m a else 0 := by + simp only [forwardCoord,LinearMap.pi_apply,LinearMap.sum_apply] + apply Finset.sum_congr rfl + intro a _ + split_ifs <;> rfl + +lemma forwardCoord_single (a : Vertex n (Cell n)) (r : R) (g : GapIndex n) : + forwardCoord (Pi.single a r) g=if afterGap g a then r else 0 := by + rw [forwardCoord_apply,Finset.sum_eq_single a] + · simp + · intro b _ hb + simp [Ne.symm hb] + · simp + +lemma forwardCoord_gap (g : GapIndex n) : + forwardCoord (forwardGap (R:=R) g)=Pi.single g 1 := by + ext f + rw [forwardGap,map_sub,Pi.sub_apply,forwardCoord_single,forwardCoord_single] + simp only [afterGap_node,Fin.val_succ,Fin.val_castSucc,Pi.single_apply] + by_cases hlev : f.1=g.1 + · simp only [lt_self_iff_false,false_or,hlev,true_and] + have heq : f=g ↔ f.2.val=g.2.val := by + constructor + · intro h; subst f; rfl + · intro h + cases f with | mk i fi => + cases g with | mk j gj => + dsimp only at hlev + subst j + have hh:fi=gj:=Fin.ext h + subst gj + rfl + simp only [heq] + split_ifs <;> simp_all <;> omega + · have heq : f≠g := by intro h; exact hlev (congrArg Sigma.fst h) + simp only [hlev,false_and,or_false,ite_eq_right heq,sub_self] + +def forwardRoots : (GapIndex n → R) →ₗ[R] (Vertex n (Cell n) → R) := + ∑ g, (LinearMap.proj g).smulRight (forwardGap g) +lemma forwardRoots_apply (c : GapIndex n → R) : + forwardRoots c=∑g,c g • forwardGap g := by + simp [forwardRoots,LinearMap.sum_apply,LinearMap.smulRight_apply] + +@[simp] lemma forwardCoord_roots (c : GapIndex n → R) : forwardCoord (forwardRoots c)=c := by + rw [forwardRoots_apply,map_sum] + simp only [map_smul,forwardCoord_gap] + ext g + simp only [Finset.sum_apply,Pi.smul_apply,Pi.single_apply,smul_eq_mul] + rw [Finset.sum_eq_single g] + · simp + · intro f _ hf + simp [Ne.symm hf] + · simp + +lemma forwardRoots_injective : Function.Injective (forwardRoots (R:=R) (n:=n)) := by + intro a b h + have H:=congrArg forwardCoord h + simpa only [forwardCoord_roots] using H + +lemma forwardGap_independent : LinearIndependent R (forwardGap (R:=R) (n:=n)) := by + have H:=Pi.linearIndependent_single_one (GapIndex n) R + have HH:LinearIndependent R (fun g : GapIndex n=>forwardCoord (forwardGap (R:=R) g)) := by + simpa only [forwardCoord_gap] using H + exact HH.of_comp forwardCoord + +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PlanarJointFactorization.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PlanarJointFactorization.lean new file mode 100644 index 0000000000000000000000000000000000000000..675b973e99e12890f90b25db5f3755f9d7e3496e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PlanarJointFactorization.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.FiniteCovectorPerturbation +import OAI.Combinatorics.Chromatic.Walls.IncomingRayElement + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M E I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] + [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (v : Rˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) +variable (e : M→+E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +def planeRoots (r s : E) : AddSubmonoid M := + (Submodule.span ℝ {r,s}).toAddSubmonoid.comap e + +lemma rootsThrough_spec {N : ℕ} {m : M} (H : m∈rootsThrough C N) : + ∃n≤N,HasRootDegree C n m := by + classical + obtain ⟨n,hn,hm⟩:=Finset.mem_biUnion.mp H + refine ⟨n,by have := Finset.mem_range.mp hn; omega,?_⟩ + simpa only [Set.Finite.mem_toFinset,Set.mem_ofPred_eq] using hm + +include he hB hcomp hdeg in + +theorem planar_joint_factorization (r s : E) (hr : 0 0<Ω a b) ∧ + (∀p∈l,∀n,n+1≤N → ∀m, + coeff (n+1) (chartZero v Ω C (incomingCovector Ω p) F).val m≠0 → OnPositiveRay p m) ∧ + ∀n≤N,coeff n F.val=coeff n (completedListProduct v Ω C l + (fun p => chartZero v Ω C (incomingCovector Ω p) F)).val := by + classical + let S:=(rootsThrough C N).filter (fun m => 0 (Finset.mem_filter.mp hm).2 + have hSmem : ∀m∈S,∃d,0 hSmem p (hlS p hp) + have hpair : l.Pairwise (fun a b => 0<Ω a b):=by + apply hlpair.imp + intro a b h + rw [hcomp] at h + exact_mod_cast h + have hcover : ∀n,0 intro hh <;> nlinarith + +lemma pairing_zero_iff (L : Module.Dual ℝ E) (r s m n : E) + (hr : 0 intro hh <;> nlinarith +end +end ElementaryPositivity.PlanarRayOrder + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PlanarRefinement.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PlanarRefinement.lean new file mode 100644 index 0000000000000000000000000000000000000000..0fd9a699142c0a79c59197537ae84b9dd05301fe --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PlanarRefinement.lean @@ -0,0 +1,202 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteRayGeometry + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry RootTruncation +noncomputable section +variable {R M E I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] + [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include hcomp in +lemma real_incoming_covector (p : M) : + (B.flip (e p)).toAddMonoidHom.comp e=incomingCovector Ω p := by + ext m + exact hcomp m p +include hcomp in +lemma real_perturbed_covector (k : Module.Dual ℝ E) (p : M) (δ : ℝ) : + (k+δ • B.flip (e p)).toAddMonoidHom.comp e= + k.toAddMonoidHom.comp e+δ • incomingCovector Ω p := by + ext m + change k (e m)+δ*B (e m) (e p)=k (e m)+δ*(Ω m p:ℝ) + rw [hcomp] +lemma linear_zero_on_plane (k : Module.Dual ℝ E) (r s m : E) + (hr : k r=0) (hs : k s=0) (hm : m∈Submodule.span ℝ {r,s}) : k m=0 := by + obtain ⟨a,b,rfl⟩:=Submodule.mem_span_pair.mp hm + simp only [map_add,map_smul,hr,hs,smul_zero,add_zero] +omit [Algebra ℚ R] in +include he hB hcomp hdeg in +lemma planar_refinement_generic (N : ℕ) (r s : E) (hrs : B r s≠0) + (k : Module.Dual ℝ E) (hkr : k r=0) (hks : k s=0) + (hzero : ∀n,n ≤ N → ∀m,HasRootDegree C n m → k (e m)=0 → e m∈Submodule.span ℝ {r,s}) + (p : M) (d : ℕ) (hd : 0 < d) (hp : HasRootDegree C d p) + (hpP : e p∈Submodule.span ℝ {r,s}) (F : CompletedPositive v Ω C) : + ∃ε > 0,∀δ : ℝ,0 < δ → δ < ε → + RayGeneric C N p ((k+δ • B.flip (e p)).toAddMonoidHom.comp e) ∧ + ∀n ≤ N,coeff n (chartZero v Ω C ((k+δ • B.flip (e p)).toAddMonoidHom.comp e) F).val= + coeff n (chartZero v Ω C (incomingCovector Ω p) + (chartZero v Ω C (k.toAddMonoidHom.comp e) F)).val := by + let kM:=k.toAddMonoidHom.comp e + obtain ⟨ε,heps,Hε⟩:=root_lex_epsilon C N kM (incomingCovector Ω p) + refine ⟨ε,heps,?_⟩ + intro δ hdδ hδε + rw [real_perturbed_covector Ω e B hcomp] + constructor + · constructor + · change k (e p)+δ*(Ω p p:ℝ)=0 + have hpp : (Ω p p:ℝ)=0:=by rw [←hcomp,hB] + rw [hpp,linear_zero_on_plane k r s (e p) hkr hks hpP,mul_zero,add_zero] + · intro n hn hnN m hm hm0 + have Hs:=Hε δ hdδ hδε n hnN m hm + have hz : kM m=0:=by + rcases lt_trichotomy (kM m) 0 with hh|hh|hh + · exact False.elim (ne_of_lt (Hs.2.1 hh) hm0) + · exact hh + · exact False.elim (ne_of_gt (Hs.1 hh) hm0) + have hmp : B (e m) (e p)=0:=by + rw [hcomp] + change kM m+δ*(Ω m p:ℝ)=0 at hm0 + rw [hz,zero_add] at hm0 + exact (mul_eq_zero.mp hm0).resolve_left (ne_of_gt hdδ) + exact positive_ray_of_pairing_zero e he B hB L r s C hdeg hrs m p n d hn hd hm hp + (hzero n hnN m hm hz) hpP hmp + · exact chart_zero_refinement v Ω C kM (incomingCovector Ω p) _ F N (Hε δ hdδ hδε) +lemma joint_roots_plane (N : ℕ) (r : M) (k : Module.Dual ℝ E) + (H : GenericOffset (realRootsThrough e C N) (e r) (B.flip (e r)) k) + (a : ℝ) (s : E) (hs : s∈realRootsThrough e C N) (hv : B s (e r)≠0) + (hsa : (k+a • B.flip (e r)) s=0) : + ∀n,n ≤ N → ∀m,HasRootDegree C n m → (k+a • B.flip (e r)) (e m)=0 → + e m∈Submodule.span ℝ {e r,s} := by + intro n hn m hm hm0 + exact H.joint_plane hs (realRoot_mem e C N n hn m hm) hv a hsa hm0 +omit [Algebra ℚ R] in +lemma joint_cut_supported (N : ℕ) (r : M) (k : Module.Dual ℝ E) + (H : GenericOffset (realRootsThrough e C N) (e r) (B.flip (e r)) k) + (a : ℝ) (s : E) (hs : s∈realRootsThrough e C N) (hv : B s (e r)≠0) + (hsa : (k+a • B.flip (e r)) s=0) (F : CompletedPositive v Ω C) : + ∀n,coeff n (completedCut v Ω C N + (chartZero v Ω C ((k+a • B.flip (e r)).toAddMonoidHom.comp e) F)).val∈ + supportedSubring v Ω (planeRoots e (e r) s) := by + apply completedCut_supported v Ω C N _ _ + intro n hn m hm + by_contra hx + have hroot:=chart_root_of_ne v Ω C _ n m hx + have hz : (k+a • B.flip (e r)) (e m)=0:=by + have Hker:=chartZero_supported_kernel v Ω C ((k+a • B.flip (e r)).toAddMonoidHom.comp e) F n + by_contra hh + exact hx (Hker m hh) + exact hm (joint_roots_plane C e B N r k H a s hs hv hsa n hn m hroot hz) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry RootTruncation WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) (e : M →+ E) +def WallsPositiveThrough (N : ℕ) (F : CompletedPositive LaurentRay.vUnit Ω C) : Prop := + ∀r d,0 < d → HasRootDegree C d r → ∀h : Module.Dual ℝ E, + RayGeneric C N r (h.toAddMonoidHom.comp e) → + RootClosedThrough LaurentRay.vUnit Ω N (literalRootProducts Ω C (OnPositiveRay r)) + (chartZero LaurentRay.vUnit Ω C (h.toAddMonoidHom.comp e) F).val +variable (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include hcomp in +lemma line_plus_covector (k : Module.Dual ℝ E) (r : M) (a δ : ℝ) : + (k+(a+δ) • B.flip (e r)).toAddMonoidHom.comp e= + (k+a • B.flip (e r)).toAddMonoidHom.comp e+δ • incomingCovector Ω r := by + ext m + change k (e m)+(a+δ)*B (e m) (e r)=k (e m)+a*B (e m) (e r)+δ*(Ω m r:ℝ) + rw [hcomp]; ring +include hcomp in +lemma line_minus_covector (k : Module.Dual ℝ E) (r : M) (a δ : ℝ) : + (k+(a-δ) • B.flip (e r)).toAddMonoidHom.comp e= + (k+a • B.flip (e r)).toAddMonoidHom.comp e+δ • (-incomingCovector Ω r) := by + ext m + change k (e m)+(a-δ)*B (e m) (e r)=k (e m)+a*B (e m) (e r)+δ* -(Ω m r:ℝ) + rw [hcomp]; ring +include he hB hcomp hdeg in +theorem wall_joint_induction (n dr : ℕ) (r : M) (hdr : 0 < dr) (hrd : HasRootDegree C dr r) + (F : CompletedPositive LaurentRay.vUnit Ω C) (ih : WallsPositiveThrough Ω C e n F) + (k : Module.Dual ℝ E) + (H : GenericOffset (realRootsThrough e C (n+1)) (e r) (B.flip (e r)) k) + (a : ℝ) (ha : a∈lineEvents (realRootsThrough e C (n+1)) (B.flip (e r)) k) : + ∃ε > 0,∀δ : ℝ,0 < δ → δ < ε → + RootClosedThrough LaurentRay.vUnit Ω (n+1) (literalRootProducts Ω C (OnPositiveRay r)) + (chartZero LaurentRay.vUnit Ω C ((k+(a+δ) • B.flip (e r)).toAddMonoidHom.comp e) F).val → + RootClosedThrough LaurentRay.vUnit Ω (n+1) (literalRootProducts Ω C (OnPositiveRay r)) + (chartZero LaurentRay.vUnit Ω C ((k+(a-δ) • B.flip (e r)).toAddMonoidHom.comp e) F).val := by + obtain ⟨s,hs,hsv,hsa⟩:=(mem_lineEvents_iff _ _ _ _).mp ha + have hrs : B (e r) s≠0:=by + rw [PlanarRayOrder.alternating_swap B hB] + exact neg_ne_zero.mpr hsv + let ka:=k+a • B.flip (e r) + let kaM:=ka.toAddMonoidHom.comp e + let J:=chartZero LaurentRay.vUnit Ω C kaM F + let Jc:=completedCut LaurentRay.vUnit Ω C (n+1) J + have hkr : ka (e r)=0:=by + change k (e r)+a*B (e r) (e r)=0 + rw [H.on_ray,hB,mul_zero,add_zero] + have hks : ka s=0:=hsa + have hzero:=joint_roots_plane C e B (n+1) r k H a s hs hsv hsa + have hJc : ∀i,coeff i Jc.val∈supportedSubring LaurentRay.vUnit Ω (planeRoots e (e r) s):= + joint_cut_supported LaurentRay.vUnit Ω C e B (n+1) r k H a s hs hsv hsa F + have hcut (h : M →+ ℝ) : ∀i ≤ n+1, + coeff i (chartZero LaurentRay.vUnit Ω C h Jc).val=coeff i (chartZero LaurentRay.vUnit Ω C h J).val:=by + apply chartZero_congr_through LaurentRay.vUnit Ω C h Jc J (n+1) + intro i hi + exact coeff_cut_of_le J.val hi + obtain ⟨εp,hεp,Hεp⟩:=root_lex_epsilon C (n+1) kaM (incomingCovector Ω r) + obtain ⟨εm,hεm,Hεm⟩:=root_lex_epsilon C (n+1) kaM (-incomingCovector Ω r) + refine ⟨min εp εm,lt_min hεp hεm,?_⟩ + intro δ hδ hδε hright + have hδp:=lt_of_lt_of_le hδε (min_le_left _ _) + have hδm:=lt_of_lt_of_le hδε (min_le_right _ _) + have hrefp:=chart_zero_refinement LaurentRay.vUnit Ω C kaM (incomingCovector Ω r) + (kaM+δ • incomingCovector Ω r) F (n+1) (Hεp δ hδ hδp) + have hrefm:=chart_zero_refinement LaurentRay.vUnit Ω C kaM (-incomingCovector Ω r) + (kaM+δ • (-incomingCovector Ω r)) F (n+1) (Hεm δ hδ hδm) + have hrpos : RootClosedThrough LaurentRay.vUnit Ω (n+1) (literalRootProducts Ω C (OnPositiveRay r)) + (chartZero LaurentRay.vUnit Ω C (incomingCovector Ω r) Jc).val:=by + apply hright.congr LaurentRay.vUnit Ω + intro i hi + rw [line_plus_covector Ω e B hcomp] + exact (hrefp i hi).trans (hcut _ i hi).symm + have hout:=positive_joint_transport Ω C e he B hB hcomp L hdeg n dr r s hdr hrd hrs Jc hJc (by + intro p d hd hdN hp hpP + by_cases hpr : Ω p r=0 + · rw [ite_eq_left hpr] + have hpp : OnPositiveRay r p:=positive_ray_of_pairing_zero e he B hB L (e r) s C hdeg hrs + p r d dr hd hdr hp hrd hpP (Submodule.subset_span (by simp)) (by rw [hcomp,hpr,Int.cast_zero]) + rw [←hpp.eq_pred,←incoming_same_ray LaurentRay.vUnit Ω C hpp Jc] + exact hrpos + · rw [ite_eq_right hpr] + obtain ⟨η,hη,Hη⟩:=planar_refinement_generic LaurentRay.vUnit Ω C e he B hB hcomp L hdeg + (n+1) (e r) s hrs ka hkr hks hzero p d hd hp hpP F + have hη2 : 0 < η/2:=by positivity + have hηlt : η/2 < η:=by linarith + obtain ⟨hgen,Href⟩:=Hη (η/2) hη2 hηlt + have HI:=ih p d hd hp (ka+(η/2) • B.flip (e p)) (hgen.mono C (by omega)) + apply HI.congr LaurentRay.vUnit Ω + intro i hi + exact (Href i (by omega)).trans (hcut _ i (by omega)).symm) + apply hout.congr LaurentRay.vUnit Ω + intro i hi + rw [line_minus_covector Ω e B hcomp] + exact (hcut _ i hi).trans (hrefm i hi).symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialAdjointCoefficients.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialAdjointCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a4cac9426bc4809949004c9d8bd36190cd2e903 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialAdjointCoefficients.lean @@ -0,0 +1,56 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.MutationMonomialAction + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +local instance polynomialAdjointCoefficientsRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance polynomialAdjointCoefficientsAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance polynomialAdjointCoefficientsAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +def actualPolynomialAdjointCoefficient (τ:M →+ ℤ) (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (F:Torus LaurentRay.vUnit Ω) (m:M) : LaurentSeries ℚ := + F.sum (fun b c=>c*actualMonomialAdjointCoefficient Ω τ f b m) + +lemma actualPolynomialAdjointCoefficient_add (τ:M →+ ℤ) (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (F G:Torus LaurentRay.vUnit Ω) (m:M) : + actualPolynomialAdjointCoefficient Ω τ f (F+G) m= + actualPolynomialAdjointCoefficient Ω τ f F m+actualPolynomialAdjointCoefficient Ω τ f G m := by + exact Finsupp.sum_add_index' (fun _=>zero_mul _) (fun _ _ _=>add_mul _ _ _) + +lemma actualPolynomialAdjointCoefficient_monomial (τ:M →+ ℤ) + (f:PowerSeries (Torus LaurentRay.vUnit Ω)) (b m:M) (c:LaurentSeries ℚ) : + actualPolynomialAdjointCoefficient Ω τ f (Torus.monomial LaurentRay.vUnit Ω b c) m= + c*actualMonomialAdjointCoefficient Ω τ f b m := by + exact Finsupp.sum_single_index (zero_mul _) + +include hcoord in +lemma actualPolynomialAdjointCoefficient_push (pos:Bool) (f:CompletedPositive LaurentRay.vUnit Ω C) + (hf:RegradeBound LaurentRay.vUnit Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f.val) + (F:Torus LaurentRay.vUnit Ω) (m:M) : + actualPolynomialAdjointCoefficient Ω (rootOrder (mutatedCoordinates Ω C coord pc)) + (mutationCompletion Ω hΩ C coord pc pos LaurentRay.vUnit f.val) + (mutationTorusPush Ω hΩ C pc pos LaurentRay.vUnit F) (mutationLinearPiece Ω C pc pos m)= + actualPolynomialAdjointCoefficient Ω (rootOrder coord) f.val F m := by + induction F using Finsupp.induction_linear with + | zero=>simp [actualPolynomialAdjointCoefficient] + | add F G hF hG=>rw [map_add,actualPolynomialAdjointCoefficient_add, + actualPolynomialAdjointCoefficient_add,hF,hG] + | single b c=> + change actualPolynomialAdjointCoefficient Ω _ _ + (mutationTorusPush Ω hΩ C pc pos LaurentRay.vUnit (Torus.monomial LaurentRay.vUnit Ω b c)) _=_ + rw [mutationTorusPush,Torus.push_monomial,actualPolynomialAdjointCoefficient_monomial, + mutation_actualMonomialAdjointCoefficient Ω hΩ C coord hcoord pc pos f hf] + exact (actualPolynomialAdjointCoefficient_monomial Ω _ _ b m c).symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialCoeffLinear.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialCoeffLinear.lean new file mode 100644 index 0000000000000000000000000000000000000000..29ad711efa0c06f4fcc54bb577f95dc0deb5f529 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialCoeffLinear.lean @@ -0,0 +1,219 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.Interaction + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def polynomialCoeffLinear (R : Type*) [CommRing R] [Algebra ℚ R] (s : ℕ) : + Polynomial R →ₗ[ℚ] R where + toFun p := p.coeff s + map_add' p q := Polynomial.coeff_add p q s + map_smul' r p := by simp + +noncomputable def relativeCoeffB (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) (s : ℕ) : + B a μ d ⊗[ℚ] B a μ e →ₗ[ℚ] B a μ d ⊗[ℚ] B a μ e := + (polynomialCoeffLinear (B a μ d ⊗[ℚ] B a μ e) s).comp + (relativeTaylorB a μ d e).toLinearMap + +@[simp] lemma relativeCoeffB_tmul (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (s : ℕ) (f : B a μ d) (g : B a μ e) : + relativeCoeffB a μ d e s (f ⊗ₜ[ℚ] g)=(taylorB a μ d f).coeff s ⊗ₜ[ℚ] g := by + change (relativeTaylorB a μ d e (f ⊗ₜ[ℚ] g)).coeff s=_ + rw [relativeTaylorB_tmul,Polynomial.coeff_mul_C,Polynomial.coeff_map] + change ((taylorB a μ d f).coeff s ⊗ₜ[ℚ] 1) * (1 ⊗ₜ[ℚ] g)=_ + rw [Algebra.TensorProduct.tmul_mul_tmul,mul_one,one_mul] + +theorem relativeCoeffB_graded (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) + (x : B a μ d ⊗[ℚ] B a μ e) (k : ℤ) + (hx : ∀ m n,m+n≠k → TensorProduct.map (componentB a μ d m) (componentB a μ e n) x=0) + (s : ℕ) (p q : ℤ) (h : p+q≠k-s) : + TensorProduct.map (componentB a μ d p) (componentB a μ e q) (relativeCoeffB a μ d e s x)=0 := by + classical + let F := (TensorProduct.map (componentB a μ d p) (componentB a μ e q)).comp (relativeCoeffB a μ d e s) + change F x=0 + obtain ⟨t,ht,he⟩ := SplitTree.componentTensor_finite_decomposition a μ (.node (.leaf d) (.leaf e)) x + change (∑ mn∈t,TensorProduct.map (componentB a μ d mn.1) (componentB a μ e mn.2) x)=x at he + have hterm : ∀ mn∈t,F (TensorProduct.map (componentB a μ d mn.1) (componentB a μ e mn.2) x)=0 := by + intro mn hmn + by_cases hm : mn.1+mn.2=k + · have hsep : p≠mn.1-s ∨ q≠mn.2 := by + by_contra hh + push Not at hh + apply h + rw [hh.1,hh.2,← hm] + ring + generalize x=y + induction y using TensorProduct.inductionOn with + | tmul f g => + change TensorProduct.map (componentB a μ d p) (componentB a μ e q) + (relativeCoeffB a μ d e s (componentB a μ d mn.1 f ⊗ₜ[ℚ] componentB a μ e mn.2 g))=0 + rw [relativeCoeffB_tmul,TensorProduct.map_tmul, + componentB_on_grade a μ d p (mn.1-s) _ + (taylorB_coeff_graded a μ d _ mn.1 ⟨f,rfl⟩ s), + componentB_on_grade a μ e q mn.2 _ ⟨g,rfl⟩] + rcases hsep with hp|hq + · rw [ite_eq_right hp,TensorProduct.zero_tmul] + · rw [ite_eq_right hq,TensorProduct.tmul_zero] + | add y z hy hz => simp only [map_add,hy,hz,add_zero] + · rw [hx mn.1 mn.2 hm,map_zero] + calc + F x=F (∑ mn∈t,TensorProduct.map (componentB a μ d mn.1) (componentB a μ e mn.2) x) := congrArg F he.symm + _=0 := by rw [map_sum]; exact Finset.sum_eq_zero hterm + +theorem relative_restriction_graded (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0restrictionB_graded a c η hc hs A f k hf m n hm) s p q h + +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +open MvPolynomial +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +noncomputable def polynomialMapLinear {R S : Type*} [CommRing R] [CommRing S] + [Algebra ℚ R] [Algebra ℚ S] (l : R →ₗ[ℚ] S) : Polynomial R →ₗ[ℚ] Polynomial S where + toFun p := Polynomial.ofFinsupp (AddMonoidAlgebra.ofCoeff (p.toFinsupp.coeff.mapRange l l.map_zero)) + map_add' p q := by + ext s + exact l.map_add (p.coeff s) (q.coeff s) + map_smul' r p := by + ext s + exact l.map_smul r (p.coeff s) + +@[simp] lemma polynomialMapLinear_coeff {R S : Type*} [CommRing R] [CommRing S] + [Algebra ℚ R] [Algebra ℚ S] (l : R →ₗ[ℚ] S) (p : Polynomial R) (n : ℕ) : + (polynomialMapLinear l p).coeff n=l (p.coeff n) := rfl + +omit [DecidableEq I] in +lemma eulerForm_add_left (a : I → I → ℕ) (d e f : I → ℕ) : + eulerForm a (d+e) f=eulerForm a d f+eulerForm a e f := by + simp only [eulerForm,Pi.add_apply,Nat.cast_add,add_mul,mul_add,Finset.sum_add_distrib] + ring + +omit [DecidableEq I] in +lemma eulerForm_add_right (a : I → I → ℕ) (d e f : I → ℕ) : + eulerForm a d (e+f)=eulerForm a d e+eulerForm a d f := by + simp only [eulerForm,Pi.add_apply,Nat.cast_add,mul_add,Finset.sum_add_distrib] + ring + +lemma coeff_single_toMvPolynomial {R α : Type*} [CommRing R] (i : α) + (p : Polynomial R) (n : ℕ) : + (Polynomial.toMvPolynomial i p).coeff (Finsupp.single i n)=p.coeff n := by + classical + induction p using Polynomial.induction_on' with + | add p q hp hq => simp only [map_add,AddMonoidAlgebra.coeff_add,Finsupp.add_apply,Polynomial.coeff_add,hp,hq] + | monomial m r => + simp [← Polynomial.C_mul_X_pow_eq_monomial,MvPolynomial.coeff_X_pow,(Finsupp.single_injective i).eq_iff,eq_comm] + +lemma restrictionTest_leaf_coeff (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0(rootOrder coord (r-b)).toNat) + +def polynomialSectionIncoming (F:Torus LaurentRay.vUnit Ω) (r:M) : LaurentSeries ℚ := + polynomialSectionCoefficient Ω C coord (incomingCovector Ω r) F r + +include hΩ in +lemma monomialSection_incoming_perturbation (b r:M) (H:M →+ ℝ) + (hs:∀n≤(rootOrder coord (r-b)).toNat,∀m,HasRootDegree C n m → + (0 < incomingCovector Ω r m → 0⟨id,id,id⟩⟩ + · simp only [ite_eq_right ht,zero_mul] + +lemma actualPolynomialAdjointCoefficient_congr (τ:M →+ ℤ) + (f g:PowerSeries (Torus LaurentRay.vUnit Ω)) (F:Torus LaurentRay.vUnit Ω) (r:M) + (hh:∀b∈F.support,actualMonomialAdjointCoefficient Ω τ f b r= + actualMonomialAdjointCoefficient Ω τ g b r) : + actualPolynomialAdjointCoefficient Ω τ f F r=actualPolynomialAdjointCoefficient Ω τ g F r := by + apply Finset.sum_congr rfl + intro b hb + exact congrArg (fun x=>F b*x) (hh b hb) + +include hΩ in +lemma polynomialSection_incoming_perturbation (F:Torus LaurentRay.vUnit Ω) (r:M) (H:M →+ ℝ) + (hs:∀n≤polynomialSectionOrderBound Ω coord F r,∀m,HasRootDegree C n m → + (0 < incomingCovector Ω r m → 0(rootOrder coord (r-b)).toNat) hb + exact hs n (hn.trans hbnd) m hm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialIncomingProbes.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialIncomingProbes.lean new file mode 100644 index 0000000000000000000000000000000000000000..96d84d502f36491eeffc427ebf9f390beaef0c51 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialIncomingProbes.lean @@ -0,0 +1,150 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PolynomialIncomingPerturbation +import OAI.Combinatorics.Chromatic.QuantumTorus.NearCutPolynomialSeeds + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) (pc:I) (e:M →+ E) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +include hS hcomp in +lemma polynomial_incoming_probes (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + (r:M) (K N:ℕ) : + ∃pos:Bool,∃h:Module.Dual ℝ E,RegularCovector C e h ∧ + cutSide pos (h.toAddMonoidHom.comp e) (simpleRoot C pc) ∧ + mutationLinearPiece Ω C pc pos r=mutationIncomingLabel Ω (simpleRoot C pc) r ∧ + (∀n≤K,∀m,HasRootDegree C n m → + (0 < incomingCovector Ω r m → 0realRootsThrough e C d∪ + (realRootsThrough e (mutatedRoots Ω C pc) d∪ + (realRootsThrough e (mutatedRoots Ω C pc) d).image (realShearVector e S (simpleRoot C pc))) + let k:=S.flip (e r) + obtain ⟨h,Ha,_,HP⟩:=generic_for_two_directions_with_probes T 0 0 k (P.image (fun x=>(0,x))) 0 + have HS:∀x∈P,(0 exact le_of_lt hpos)] + cases pos + · exact realShearCovector_eval e S _ _ _ + · rfl + have hsign:(if pos then 0≤Ω (simpleRoot C pc) r else Ω (simpleRoot C pc) r≤0):=by + have hs:=HS _ (Finset.mem_insert_self _ _) + have hc:k (e (simpleRoot C pc))=(Ω (simpleRoot C pc) r:ℝ):=hcomp _ _ + cases pos + · change h (e (simpleRoot C pc))<0 at hpos + by_contra hn + have H:=hs.1 (by rw [hc]; exact_mod_cast lt_of_not_ge hn) + linarith + · change 0by rw [hJ]; norm_num) hn hm + intro hh + rw [hh,map_zero] at H + exact lt_irrefl _ H + have hv:(if pos then e m else realShearVector e S (simpleRoot C pc) (e m))≠0:=by + cases pos + · exact realShearVector_ne_zero C pc e S hS hm0 + · exact hm0 + have HT:(if pos then e m else realShearVector e S (simpleRoot C pc) (e m))∈T n:=by + apply Finset.mem_union_right + have HH:=realRoot_mem e (mutatedRoots Ω C pc) n n le_rfl m hm + cases pos + · exact Finset.mem_union_right _ (Finset.mem_image.mpr ⟨e m,HH,rfl⟩) + · exact Finset.mem_union_left _ HH + rw [heval] + exact (Ha n).avoid _ HT (by simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using hv) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits RationalFiber FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (hnd:∀r≠0,∃m,Ω r m≠0) +include he hdeg hS hcomp hnd in +lemma polynomialSectionIncoming_mutation (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + (F F':Torus LaurentRay.vUnit Ω) (hF:PureInitialRelation Ω hΩ C coord hcoord pc F F') (r:M) : + polynomialSectionIncoming Ω C coord F r= + polynomialSectionIncoming Ω (mutatedRoots Ω C pc) (mutatedCoordinates Ω C coord pc) F' + (mutationIncomingLabel Ω (simpleRoot C pc) r) := by + obtain ⟨pos,h,Hreg,hs,hl,ho,hn,Hnew⟩:=polynomial_incoming_probes Ω C pc e S hS hcomp hC r + (polynomialSectionOrderBound Ω coord F r) + (polynomialSectionOrderBound Ω (mutatedCoordinates Ω C coord pc) F' + (mutationIncomingLabel Ω (simpleRoot C pc) r)) + have Hold:=polynomialSection_incoming_perturbation Ω hΩ C coord F r (h.toAddMonoidHom.comp e) ho + have Hnew':=polynomialSection_incoming_perturbation Ω hΩ (mutatedRoots Ω C pc) + (mutatedCoordinates Ω C coord pc) F' (mutationIncomingLabel Ω (simpleRoot C pc) r) + ((realMutationCovector e S (simpleRoot C pc) h).toAddMonoidHom.comp e) hn + rw [←Hold,←Hnew',←hl] + exact (polynomialSection_mutation Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg hnd hC F F' hF + pos h Hreg hs Hnew r).symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialSection.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialSection.lean new file mode 100644 index 0000000000000000000000000000000000000000..527535bdb734fc6098360c8f273d3008faac2ee7 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PolynomialSection.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PolynomialIncomingPerturbation + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) +local instance polynomialSectionRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance polynomialSectionAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance polynomialSectionAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +omit [DecidableEq I] in +include hΩ in +lemma actualMonomialAdjoint_support (τ:M →+ ℤ) (f:CompletedPositive LaurentRay.vUnit Ω C) + (b m:M) (hm:actualMonomialAdjointCoefficient Ω τ f.val b m≠0) : + ∃d,HasRootDegree C d (m-b) := by + have H:=normalizedMonomialAction_graded LaurentRay.vUnit Ω hΩ C f b + unfold actualMonomialAdjointCoefficient actualRootCoefficient at hm + split_ifs at hm with ht + · refine ⟨(τ (m-b)).toNat,?_⟩ + by_contra hn + exact hm (by rw [H _ _ hn,zero_mul]) + · exact (hm (zero_mul _)).elim + +omit [DecidableEq I] in +include hΩ in +lemma actualPolynomialAdjoint_support (τ:M →+ ℤ) (f:CompletedPositive LaurentRay.vUnit Ω C) + (F:Torus LaurentRay.vUnit Ω) (m:M) + (hm:actualPolynomialAdjointCoefficient Ω τ f.val F m≠0) : + ∃b∈F.support,∃d,HasRootDegree C d (m-b) := by + classical + unfold actualPolynomialAdjointCoefficient Finsupp.sum at hm + obtain ⟨b,hb,hb'⟩:=Finset.exists_ne_zero_of_sum_ne_zero hm + refine ⟨b,hb,actualMonomialAdjoint_support Ω hΩ C τ f b m ?_⟩ + intro hh + exact hb' (show F b * actualMonomialAdjointCoefficient Ω τ f.val b m = 0 from by simp only [hh,mul_zero]) + +include hΩ in +lemma polynomialSection_support (h:M →+ ℝ) (F:Torus LaurentRay.vUnit Ω) (m:M) + (hm:polynomialSectionCoefficient Ω C coord h F m≠0) : + ∃b∈F.support,∃d,HasRootDegree C d (m-b) := + actualPolynomialAdjoint_support Ω hΩ C (rootOrder coord) (rootSectionChart Ω C h) F m hm + +lemma rootDegree_cut_bound (ell:M →+ ℤ) (hc:∀i,ell (simpleRoot C i)≤0) + {d:ℕ} {m:M} (hm:HasRootDegree C d m) : ell m≤0 := by + obtain ⟨a,_,rfl⟩:=hm + have hex:(fun i=>(a i:ℤ))=∑i,Pi.single i (a i:ℤ):=by + ext i + simp + rw [hex,map_sum,map_sum] + apply Finset.sum_nonpos + intro i _ + have H:C (Pi.single i (a i:ℤ))=(a i:ℤ) • simpleRoot C i:=by + rw [simpleRoot,←map_zsmul] + congr 1 + ext j + simp only [Pi.smul_apply,Pi.single_apply,smul_eq_mul] + split_ifs <;> simp + rw [H,map_zsmul,smul_eq_mul] + exact mul_nonpos_of_nonneg_of_nonpos (Int.natCast_nonneg _) (hc i) + +include hΩ in +lemma polynomialSection_cut_bound (h:M →+ ℝ) (F:Torus LaurentRay.vUnit Ω) + (ell:M →+ ℤ) (K:ℤ) (hc:∀i,ell (simpleRoot C i)≤0) + (hF:∀b∈F.support,ell b≤K) (m:M) + (hm:polynomialSectionCoefficient Ω C coord h F m≠0) : ell m≤K := by + obtain ⟨b,hb,d,hd⟩:=polynomialSection_support Ω hΩ C coord h F m hm + have HH:=rootDegree_cut_bound C ell hc hd + rw [map_sub] at HH + have := hF b hb + omega + +include hΩ in +lemma polynomialIncoming_cut_bound (F:Torus LaurentRay.vUnit Ω) + (ell:M →+ ℤ) (K:ℤ) (hc:∀i,ell (simpleRoot C i)≤0) + (hF:∀b∈F.support,ell b≤K) (m:M) + (hm:polynomialSectionIncoming Ω C coord F m≠0) : ell m≤K := + polynomialSection_cut_bound Ω hΩ C coord (incomingCovector Ω m) F ell K hc hF m hm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PowerSeriesThreeFactors.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PowerSeriesThreeFactors.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0f6f93936db02239c7429b2af39e78155151f0e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PowerSeriesThreeFactors.lean @@ -0,0 +1,77 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplit + +namespace OAI + +section +section +namespace ElementaryPositivity.PowerSeriesSplit +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] +variable (P Q : R →+ R) (S : Subring R) +variable (hS : ∀x,x∈S ↔ P x=0) +variable (hP : ∀x,P (P x)=P x) (hQ : ∀x,Q (Q x)=Q x) +variable (hPQ : ∀x,P (Q x)=0) + + def positiveFactor (f : PowerSeries R) := leftFactor P f + def zeroFactor (f : PowerSeries R) := leftFactor Q (rightFactor P f) + def negativeFactor (f : PowerSeries R) := rightFactor Q (rightFactor P f) + +lemma factor_three (f : PowerSeries R) (hf : constantCoeff f=1) : + positiveFactor P f * zeroFactor P Q f * negativeFactor P Q f=f := by + rw [positiveFactor,zeroFactor,negativeFactor,mul_assoc, + factorization Q _ (right_constant P f),factorization P f hf] + +include hS hP hPQ in +lemma zero_negative_nonpositive (f : PowerSeries R) : + (∀n,coeff n (zeroFactor P Q f)∈S) ∧ + (∀n,coeff n (negativeFactor P Q f)∈S) := by + apply factors_mem Q S + · intro x hx + exact (hS _).mpr (hPQ x) + · intro n + cases n with + | zero => rw [coeff_zero_eq_constantCoeff_apply,right_constant]; exact S.one_mem + | succ n => exact (hS _).mpr (right_killed P hP f n) + +lemma three_constant (f : PowerSeries R) : + constantCoeff (positiveFactor P f)=1 ∧ constantCoeff (zeroFactor P Q f)=1 ∧ + constantCoeff (negativeFactor P Q f)=1 := by + exact ⟨left_constant P f,left_constant Q _,right_constant Q _⟩ + +include hS hP hQ hPQ in +lemma three_support (f : PowerSeries R) : + (∀n,P (coeff (n+1) (positiveFactor P f))=coeff (n+1) (positiveFactor P f)) ∧ + (∀n,P (coeff n (zeroFactor P Q f))=0) ∧ + (∀n,Q (coeff (n+1) (zeroFactor P Q f))=coeff (n+1) (zeroFactor P Q f)) ∧ + (∀n,P (coeff n (negativeFactor P Q f))=0) ∧ + (∀n,Q (coeff (n+1) (negativeFactor P Q f))=0) := by + have hs:=zero_negative_nonpositive P Q S hS hP hPQ f + exact ⟨left_fixed P hP f,fun n=>(hS _).mp (hs.1 n),left_fixed Q hQ _, + fun n=>(hS _).mp (hs.2 n),right_killed Q hQ _⟩ + +include hS in +lemma three_uniqueness (f a b c : PowerSeries R) + (ha : constantCoeff a=1) (hb : constantCoeff b=1) (hc : constantCoeff c=1) + (habc : a*b*c=f) + (haP : ∀n,P (coeff (n+1) a)=coeff (n+1) a) + (hbP : ∀n,P (coeff n b)=0) (hcP : ∀n,P (coeff n c)=0) + (hbQ : ∀n,Q (coeff (n+1) b)=coeff (n+1) b) + (hcQ : ∀n,Q (coeff (n+1) c)=0) : + a=positiveFactor P f ∧ b=zeroFactor P Q f ∧ c=negativeFactor P Q f := by + have hbc : ∀n,P (coeff n (b*c))=0 := by + intro n + apply (hS _).mp + exact mul_mem S b c (fun k=>(hS _).mpr (hbP k)) + (fun k=>(hS _).mpr (hcP k)) n + have hfirst:=uniqueness P f a (b*c) ha (by simp [hb,hc]) + (by rwa [←mul_assoc]) haP (fun n=>hbc (n+1)) + have hsecond:=uniqueness Q (rightFactor P f) b c hb hc hfirst.2 hbQ hcQ + exact ⟨hfirst.1,hsecond.1,hsecond.2⟩ +end +end ElementaryPositivity.PowerSeriesSplit +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PrimitiveStrings.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PrimitiveStrings.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a877cf983fcc0f10de07cacf368954ed0f16848 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PrimitiveStrings.lean @@ -0,0 +1,151 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +namespace PrimitiveStrings + +variable {V : Type*} [AddCommGroup V] [Module ℚ V] +variable (D T : Module.End ℚ V) + +abbrev Strings := ℕ →₀ LinearMap.ker D + +noncomputable def evaluate : Strings D →ₗ[ℚ] V := + Finsupp.lsum ℚ fun n => (T ^ n).comp (LinearMap.ker D).subtype + +@[simp] theorem evaluate_single (n : ℕ) (v : LinearMap.ker D) : + evaluate D T (Finsupp.single n v) = (T ^ n) v.val := by + simp [evaluate] + +noncomputable def differentiate : Strings D →ₗ[ℚ] Strings D := + Finsupp.lsum ℚ fun n => + match n with + | 0 => 0 + | k + 1 => (k + 1 : ℚ) • Finsupp.lsingle k + +noncomputable def integrate : Strings D →ₗ[ℚ] Strings D := + Finsupp.lsum ℚ fun n => (n + 1 : ℚ)⁻¹ • Finsupp.lsingle (n + 1) + +@[simp] theorem differentiate_single_zero (v : LinearMap.ker D) : + differentiate D (Finsupp.single 0 v) = 0 := by simp [differentiate] + +@[simp] theorem differentiate_single_succ (n : ℕ) (v : LinearMap.ker D) : + differentiate D (Finsupp.single (n + 1) v) = + Finsupp.single n ((n + 1 : ℚ) • v) := by simp [differentiate] + +@[simp] theorem integrate_single (n : ℕ) (v : LinearMap.ker D) : + integrate D (Finsupp.single n v) = + Finsupp.single (n + 1) ((n + 1 : ℚ)⁻¹ • v) := by simp [integrate] + + theorem differentiate_apply (f : Strings D) (n : ℕ) : + differentiate D f n = (n + 1 : ℚ) • f (n + 1) := by + induction f using Finsupp.induction_linear with + | zero => simp + | add f g hf hg => simp [hf, hg, smul_add] + | single k v => + cases k with + | zero => simp + | succ k => + by_cases h : k = n + · subst k; simp + · simp [Ne.symm h] + +@[simp] theorem differentiate_integrate (f : Strings D) : + differentiate D (integrate D f) = f := by + induction f using Finsupp.induction_linear with + | zero => simp + | add f g hf hg => simp [hf, hg] + | single k v => simp [smul_smul, show (k + 1 : ℚ) ≠ 0 by positivity] + +variable (weyl : ∀ v, D (T v) = T (D v) + v) +include weyl + + theorem derivative_string (v : LinearMap.ker D) (n : ℕ) : + D ((T ^ (n + 1)) v.val) = (n + 1 : ℚ) • (T ^ n) v.val := by + induction n with + | zero => simpa using (weyl v.val).trans (by simp) + | succ n ih => + rw [pow_succ' T (n + 1), Module.End.mul_apply, weyl, ih, map_smul] + rw [← Module.End.mul_apply, ← pow_succ' T n] + simp only [Nat.cast_add, Nat.cast_one] + simp only [add_smul, one_smul] + + theorem evaluate_differentiate (f : Strings D) : + evaluate D T (differentiate D f) = D (evaluate D T f) := by + induction f using Finsupp.induction_linear with + | zero => simp + | add f g hf hg => simp [hf, hg] + | single n v => + cases n with + | zero => simp + | succ n => simp [derivative_string D T weyl, map_smul] + +theorem evaluate_injective_bounded (N : ℕ) (f : Strings D) + (bound : ∀ n, N ≤ n → f n = 0) (hf : evaluate D T f = 0) : f = 0 := by + induction N generalizing f with + | zero => apply Finsupp.ext; intro n; exact bound n (Nat.zero_le n) + | succ N ih => + have hd : differentiate D f = 0 := by + apply ih + · intro n hn + rw [differentiate_apply, bound (n + 1) (Nat.succ_le_succ hn), smul_zero] + · rw [evaluate_differentiate D T weyl, hf, map_zero] + have hpos : ∀ n, f (n + 1) = 0 := by + intro n + have h := congrArg (fun g : Strings D => g n) hd + rw [differentiate_apply] at h + exact (smul_eq_zero.mp h).resolve_left (by positivity) + have heq : f = Finsupp.single 0 (f 0) := by + ext n + cases n with + | zero => simp + | succ n => simp [hpos] + rw [heq, evaluate_single, pow_zero, Module.End.one_apply] at hf + rw [heq] + have hzero : f 0 = 0 := Subtype.ext hf + rw [hzero, Finsupp.single_zero] + + theorem evaluate_injective : Function.Injective (evaluate D T) := by + apply (LinearMap.ker_eq_bot).mp + rw [LinearMap.ker_eq_bot'] + intro f hf + apply evaluate_injective_bounded D T weyl (f.support.sup id + 1) f _ hf + intro n hn + by_contra hne + have hn' : n ≤ f.support.sup id := Finset.le_sup (f := id) (f.mem_support_iff.mpr hne) + omega + +theorem exists_strings_of_pow_eq_zero (N : ℕ) (v : V) (hv : (D ^ N) v = 0) : + ∃ f : Strings D, evaluate D T f = v := by + induction N generalizing v with + | zero => + simp only [pow_zero, Module.End.one_apply] at hv + subst v + exact ⟨0, map_zero _⟩ + | succ N ih => + have hd : (D ^ N) (D v) = 0 := by + rw [← Module.End.mul_apply, ← pow_succ] + exact hv + obtain ⟨f, hf⟩ := ih (D v) hd + let g := integrate D f + have hg : D (v - evaluate D T g) = 0 := by + rw [map_sub, ← evaluate_differentiate D T weyl] + simp only [g, differentiate_integrate, hf, sub_self] + let c : LinearMap.ker D := ⟨v - evaluate D T g, hg⟩ + refine ⟨Finsupp.single 0 c + g, ?_⟩ + simp [c] + +noncomputable def decomposition (nilpotent : ∀ v : V, ∃ N : ℕ, (D ^ N) v = 0) : + Strings D ≃ₗ[ℚ] V := + LinearEquiv.ofBijective (evaluate D T) + ⟨evaluate_injective D T weyl, fun v => by + obtain ⟨N, hv⟩ := nilpotent v + exact exists_strings_of_pow_eq_zero D T weyl N v hv⟩ + +end PrimitiveStrings +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PureActualCoefficients.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PureActualCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..6cfa4dc7b1af9e49399e91cbc552b737860b712d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PureActualCoefficients.lean @@ -0,0 +1,214 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.LatticeHahn +import OAI.Combinatorics.Chromatic.Walls.PolynomialAdjointCoefficients +import OAI.Combinatorics.Chromatic.GradedAlgebra.PureCoefficient + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits RationalFiber +noncomputable section +variable {M:Type*} [AddCommGroup M] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (τ:M →+ ℤ) +local instance pureActualCoefficientsRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance pureActualCoefficientsAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance pureActualCoefficientsAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +include hΩ in +lemma actualMonomialAdjointCoefficient_read (f:PowerSeries (Torus LaurentRay.vUnit Ω)) (b m:M) : + actualMonomialAdjointCoefficient Ω τ f b m= + if 0≤τ (m-b) then + coeff (τ (m-b)).toNat (adjoint f (PowerSeries.C (Torus.X LaurentRay.vUnit Ω b))) m else 0 := by + unfold actualMonomialAdjointCoefficient actualRootCoefficient + split_ifs with h + · simpa only [sub_add_cancel] using + (adjoint_monomial_coeff LaurentRay.vUnit Ω hΩ f b (m-b) (τ (m-b)).toNat).symm + · exact zero_mul _ + +include hΩ in +lemma normalizedSimple_adjoint_coefficient (p b:M) (j:ℕ) : + coeff j (adjoint (normalizedSimple Ω p) (PowerSeries.C (Torus.X LaurentRay.vUnit Ω b)))= + Torus.monomial LaurentRay.vUnit Ω (b+j • p) (coeff j (centeredRatio LaurentRay.vUnit (Ω p b))) := by + rw [adjoint,normalizedSimple_inverse Ω hΩ p] + have H:=old_pure_coeff LaurentRay.vUnit Ω hΩ p b j + simpa only [rayUnit,normalizedSimple,←shiftedElementary_zero,laurent_shiftedElementary_zero] using H + +include hΩ in +lemma actual_pure_monomial (k:M →+ ℤ) (p:M) (hp:k p=1) (hτ:τ p=1) (b m:M) : + actualMonomialAdjointCoefficient Ω τ (normalizedSimple Ω p) b m= + readFiber LaurentRay.vUnit Ω k p hp m + (pureAction LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω) + (embed LaurentRay.vUnit Ω hΩ k p hp (Torus.X LaurentRay.vUnit Ω b))) := by + classical + have hq:∀n:ℕ,1-(↑(LaurentRay.vUnit^(-2:ℤ)):LaurentSeries ℚ)^(n+1)≠0:=by + intro n + rw [LaurentRay.vUnit_zpow] + exact UnitSelections.laurent_q_not_root n + by_cases hm:∃j:ℕ,m=b+j • p + · obtain ⟨j,rfl⟩:=hm + rw [actualMonomialAdjointCoefficient_read Ω hΩ τ] + have ht:τ (b+j • p-b)=(j:ℤ):=by simp only [map_sub,map_add,map_nsmul,hτ,nsmul_eq_mul,mul_one]; omega + rw [ht,ite_eq_left (Int.natCast_nonneg j),Int.toNat_natCast,normalizedSimple_adjoint_coefficient Ω hΩ, + read_pure_monomial_shift LaurentRay.vUnit Ω hΩ k p hp hq] + exact Finsupp.single_eq_same + · rw [actualMonomialAdjointCoefficient_read Ω hΩ τ] + have hr:readFiber LaurentRay.vUnit Ω k p hp m + (pureAction LaurentRay.vUnit (complementOmega k Ω) (complementAlpha k p Ω) + (embed LaurentRay.vUnit Ω hΩ k p hp (Torus.X LaurentRay.vUnit Ω b)))=0:=by + by_contra hh + exact hm (read_pure_monomial_support LaurentRay.vUnit Ω hΩ k p hp hq b m hh) + rw [hr] + split_ifs + · rw [normalizedSimple_adjoint_coefficient Ω hΩ] + exact Finsupp.single_eq_of_ne (fun he=>hm ⟨_,he⟩) + · rfl +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.PowerSeriesAdjoint +open PowerSeries HahnSeries +noncomputable section +variable {A:Type*} [Ring A] +def hahnAction (f:PowerSeries A) (x:HahnSeries ℤ A) : HahnSeries ℤ A := + ofPowerSeries ℤ A f*x*ofPowerSeries ℤ A (invOfUnit f 1) +lemma hahnAction_add (f:PowerSeries A) (x y:HahnSeries ℤ A) : + hahnAction f (x+y)=hahnAction f x+hahnAction f y := by + simp only [hahnAction,mul_add,add_mul] +lemma hahnAction_zero (f:PowerSeries A) : hahnAction f (0:HahnSeries ℤ A)=0 := by + simp only [hahnAction,mul_zero,zero_mul] +lemma hahnAction_one (x:HahnSeries ℤ A) : hahnAction 1 x=x := by + have hi:invOfUnit (1:PowerSeries A) 1=1:=by simpa using mul_invOfUnit (1:PowerSeries A) 1 (by simp) + simp only [hahnAction,hi,map_one,one_mul,mul_one] +lemma hahnAction_mul (f g:PowerSeries A) (x:HahnSeries ℤ A) + (hf:constantCoeff f=1) (hg:constantCoeff g=1) : + hahnAction (f*g) x=hahnAction f (hahnAction g x) := by + simp only [hahnAction,inverse_mul f g hf hg,map_mul,mul_assoc] +lemma hahnAction_inverse_cancel (f:PowerSeries A) (x:HahnSeries ℤ A) + (hf:constantCoeff f=1) : hahnAction (invOfUnit f 1) (hahnAction f x)=x := by + rw [←hahnAction_mul _ _ _ (by simp) hf,invOfUnit_mul f 1 hf,hahnAction_one] +lemma ofPowerSeries_coeff_int (f:PowerSeries A) (j:ℤ) : + (ofPowerSeries ℤ A f).coeff j=if 0≤j then coeff j.toNat f else 0 := by + by_cases hj:0≤j + · rw [ite_eq_left hj,←Int.toNat_of_nonneg hj,HahnSeries.ofPowerSeries_apply_coeff,Int.toNat_natCast] + · rw [ite_eq_right hj,HahnSeries.ofPowerSeries_apply] + apply HahnSeries.embDomain_notin_image_support + rintro ⟨n,_,hn⟩ + have he:(n:ℤ)=j:=hn + omega +end +end ElementaryPositivity.PowerSeriesAdjoint +namespace ElementaryPositivity.QuantumTorus +open PowerSeries HahnSeries PowerSeriesAdjoint WallUnits +noncomputable section +variable {M I:Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) (τ:M →+ ℤ) +local instance pureActualScalarCoefficientsRing : Ring (Torus LaurentRay.vUnit Ω) := Torus.instRing LaurentRay.vUnit Ω +local instance pureActualScalarCoefficientsAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance pureActualScalarCoefficientsAddGroup : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance pureActualScalarCoefficientsNonUnitalSemiring : NonUnitalSemiring (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalSemiring +local instance pureActualScalarCoefficientsNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toNonUnitalNonAssocSemiring + +lemma adjoint_scalar_monomial_coeff (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (b m:M) (c:LaurentSeries ℚ) (n:ℕ) : + coeff n (adjoint f (PowerSeries.C (Torus.monomial LaurentRay.vUnit Ω b c))) m= + c*coeff n (adjoint f (PowerSeries.C (Torus.X LaurentRay.vUnit Ω b))) m := by + rw [adjoint_torus_expansion] + change (Finsupp.single b c).sum (fun d a=>a*coeff n (adjoint f (PowerSeries.C (Torus.X LaurentRay.vUnit Ω d))) m)=_ + exact Finsupp.sum_single_index (zero_mul _) + +lemma hahnAction_monomial_coeff (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (b m:M) (c:LaurentSeries ℚ) (j:ℤ) : + (hahnAction f (latticeHahn LaurentRay.vUnit Ω τ (Torus.monomial LaurentRay.vUnit Ω b c))).coeff j m= + if 0≤j-τ b then c*coeff (j-τ b).toNat (adjoint f (PowerSeries.C (Torus.X LaurentRay.vUnit Ω b))) m else 0 := by + rw [latticeHahn_monomial,hahnAction,hahn_single_shift_adjoint, + HahnSeries.coeff_single_mul,one_mul,ofPowerSeries_coeff_int] + split_ifs + · exact adjoint_scalar_monomial_coeff Ω f b m c _ + · rfl + +include hΩ in +lemma hahnAction_actual_coeff (f:PowerSeries (Torus LaurentRay.vUnit Ω)) + (F:Torus LaurentRay.vUnit Ω) (m:M) : + (hahnAction f (latticeHahn LaurentRay.vUnit Ω τ F)).coeff (τ m) m= + actualPolynomialAdjointCoefficient Ω τ f F m := by + classical + induction F using Finsupp.induction_linear with + | zero=>simp [hahnAction_zero,actualPolynomialAdjointCoefficient] + | add F G hF hG=>rw [map_add,hahnAction_add,HahnSeries.coeff_add, + Finsupp.add_apply,actualPolynomialAdjointCoefficient_add,hF,hG] + | single b c=> + change (hahnAction f (latticeHahn LaurentRay.vUnit Ω τ (Torus.monomial LaurentRay.vUnit Ω b c))).coeff (τ m) m= + actualPolynomialAdjointCoefficient Ω τ f (Torus.monomial LaurentRay.vUnit Ω b c) m + rw [hahnAction_monomial_coeff,actualPolynomialAdjointCoefficient_monomial, + actualMonomialAdjointCoefficient_read Ω hΩ τ,map_sub] + split_ifs <;> simp + +omit [DecidableEq I] in +include hΩ in +lemma adjoint_monomial_degree (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) + (hcoord:∀d,coord (C d)=d) (f:CompletedPositive LaurentRay.vUnit Ω C) + (b m:M) (n:ℕ) + (hm:coeff n (adjoint f.val (PowerSeries.C (Torus.X LaurentRay.vUnit Ω b))) m≠0) : + rootOrder coord (m-b)=(n:ℤ) := by + have H:=normalizedMonomialAction_graded LaurentRay.vUnit Ω hΩ C f b + have he:=adjoint_monomial_coeff LaurentRay.vUnit Ω hΩ f.val b (m-b) n + simp only [sub_add_cancel] at he + rw [he] at hm + apply rootOrder_eq C coord hcoord + by_contra hh + exact hm (by rw [H n (m-b) hh,zero_mul]) + +omit [DecidableEq I] in +include hΩ in +lemma hahnAction_diagonal (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) + (hcoord:∀d,coord (C d)=d) (f:CompletedPositive LaurentRay.vUnit Ω C) + (F:Torus LaurentRay.vUnit Ω) (j:ℤ) (m:M) (hj:j≠rootOrder coord m) : + (hahnAction f.val (latticeHahn LaurentRay.vUnit Ω (rootOrder coord) F)).coeff j m=0 := by + classical + induction F using Finsupp.induction_linear with + | zero=>simp [hahnAction_zero] + | add F G hF hG=>rw [map_add,hahnAction_add,HahnSeries.coeff_add,Finsupp.add_apply,hF,hG,add_zero] + | single b c=> + change (hahnAction f.val (latticeHahn LaurentRay.vUnit Ω (rootOrder coord) (Torus.monomial LaurentRay.vUnit Ω b c))).coeff j m=0 + rw [hahnAction_monomial_coeff] + split_ifs with hn + · have hz:coeff (j-rootOrder coord b).toNat + (adjoint f.val (PowerSeries.C (Torus.X LaurentRay.vUnit Ω b))) m=0:=by + by_contra hh + have H:=adjoint_monomial_degree Ω hΩ C coord hcoord f b m _ hh + rw [map_sub,Int.toNat_of_nonneg hn] at H + exact hj (by omega) + rw [hz,mul_zero] + · rfl + +omit [DecidableEq I] in +include hΩ in +lemma hahnAction_finite_iff (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) + (hcoord:∀d,coord (C d)=d) (f:CompletedPositive LaurentRay.vUnit Ω C) + (F G:Torus LaurentRay.vUnit Ω) : + hahnAction f.val (latticeHahn LaurentRay.vUnit Ω (rootOrder coord) F)= + latticeHahn LaurentRay.vUnit Ω (rootOrder coord) G ↔ + ∀m,actualPolynomialAdjointCoefficient Ω (rootOrder coord) f.val F m=G m := by + constructor + · intro h m + have H:=congrArg (fun x:HahnSeries ℤ (Torus LaurentRay.vUnit Ω)=>x.coeff (rootOrder coord m) m) h + simpa only [hahnAction_actual_coeff Ω hΩ,latticeHahn_coeff,ite_true] using H + · intro h + apply HahnSeries.ext + funext j + apply Finsupp.ext + intro m + by_cases hj:j=rootOrder coord m + · subst j + rw [hahnAction_actual_coeff Ω hΩ,latticeHahn_coeff,ite_eq_left rfl,h] + · rw [hahnAction_diagonal Ω hΩ C coord hcoord f F j m hj,latticeHahn_coeff,ite_eq_right hj] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PureCutFactorization.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PureCutFactorization.lean new file mode 100644 index 0000000000000000000000000000000000000000..0cd76617db1f51a2acadb2057a4d579a2f663839 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PureCutFactorization.lean @@ -0,0 +1,203 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.PureProductSplit + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +include hcoord in +lemma ordered_pure_factor_through (hΩ : ∀m,Ω m m=0) (pos : Bool) (l : List M) + (K : M → CompletedPositive LaurentRay.vUnit Ω C) + (hl : l.Pairwise (fun a b=>0<Ω a b)) + (hroot : ∀q∈l,∃d,0decide (nonpDegree coord pc q≠0))) K + ∀j≤N,coeff j F.val=coeff j (if pos then D.val*A.val else A.val*D.val) := by + classical + let lP:=l.filter (fun q=>decide (nonpDegree coord pc q=0)) + let lA:=l.filter (fun q=>decide (nonpDegree coord pc q≠0)) + let P:=completedListProduct LaurentRay.vUnit Ω C lP K + let A:=completedListProduct LaurentRay.vUnit Ω C lA K + let W:=completedListProduct LaurentRay.vUnit Ω C l K + have hPW : W.val=if pos then P.val*A.val else A.val*P.val:=by + have H:=congrArg (fun L : List M=>(L.map (fun q=>(K q).val)).prod) + (ordered_pure_partition Ω C coord hcoord pc hΩ pos l hl hroot htrend) + cases pos <;> simpa only [W,P,A,lP,lA,completedListProduct,Bool.false_eq_true,ite_false,ite_true,List.map_append,List.prod_append] using H.symm + have hPA : (pureFace Ω C coord pc A).val=1:=by + apply pureFace_list_nonpure Ω C coord hcoord pc lA K + · intro q hq + have H:=List.mem_filter.mp hq + have hn : nonpDegree coord pc q≠0:=of_decide_eq_true H.2 + obtain ⟨d,hd,hr⟩:=hroot q H.1 + have hp:=nonpDegree_root_nonneg C coord hcoord pc hr + omega + · intro q hq + exact hRay q (List.mem_filter.mp hq).1 + have hPP : (pureFace Ω C coord pc P).val=P.val:=by + apply pureFace_list_pure Ω C coord hcoord pc lP K + · intro q hq; exact of_decide_eq_true (List.mem_filter.mp hq).2 + · intro q hq; exact hRay q (List.mem_filter.mp hq).1 + have hWP : (pureFace Ω C coord pc W).val=P.val:=by + change pureFaceSeries Ω coord pc W.val=P.val + rw [hPW] + cases pos <;> simp only [Bool.false_eq_true,ite_false,ite_true] + · rw [pureFaceSeries_mul Ω C coord hcoord pc _ _ A.property.2 P.property.2] + change (pureFace _ _ _ _ A).val*(pureFace _ _ _ _ P).val=P.val + rw [hPA,hPP,one_mul] + · rw [pureFaceSeries_mul Ω C coord hcoord pc _ _ P.property.2 A.property.2] + change (pureFace _ _ _ _ P).val*(pureFace _ _ _ _ A).val=P.val + rw [hPA,hPP,mul_one] + have hPD : ∀j≤N,coeff j P.val=coeff j D.val:=by + intro j hj + rw [←hWP,←hface j hj] + change coeff j (pureFaceSeries Ω coord pc W.val)=coeff j (pureFaceSeries Ω coord pc F.val) + rw [coeff_pureFaceSeries,coeff_pureFaceSeries,hprod j hj] + change ∀j≤N,coeff j F.val=coeff j (if pos then D.val*A.val else A.val*D.val) + intro j hj + rw [hprod j hj] + change coeff j W.val=coeff j (if pos then D.val*A.val else A.val*D.val) + rw [hPW] + cases pos <;> simp only [Bool.false_eq_true,ite_false,ite_true] + · exact FormalLog.mul_coeff_congr A.val P.val A.val D.val j (fun _ _=>rfl) + (fun k hk=>hPD k (hk.trans hj)) + · exact FormalLog.mul_coeff_congr P.val A.val D.val A.val j + (fun k hk=>hPD k (hk.trans hj)) (fun _ _=>rfl) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint RootTruncation WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) + +def boundedNonpFrame (w : M →+ ℤ) (P : AddSubmonoid M) (n : ℤ) : AddSubmonoid M where + carrier:={m | 0≤w m ∧ (w m≤n → m∈P)} + zero_mem':=⟨by simp,fun _=>P.zero_mem⟩ + add_mem':=by + intro a b ha hb + refine ⟨by simpa only [map_add] using add_nonneg ha.1 hb.1,?_⟩ + intro hh + have ha0 : 0≤w a:=ha.1 + have hb0 : 0≤w b:=hb.1 + have hh' : w a+w b≤n:=by simpa only [map_add] using hh + exact P.add_mem (ha.2 (by omega)) (hb.2 (by omega)) + +include hcoord in +def simpleCompleted : CompletedPositive LaurentRay.vUnit Ω C := + ⟨normalizedSimple Ω (simpleRoot C pc),normalizedSimple_constant Ω _,by + rw [←literalIncoming_simple Ω C coord hcoord pc] + exact (literalIncomingCompleted Ω C (simpleIncomingList C) (simpleIncomingList_allowed C) + (simpleRoot C pc)).property.2⟩ + +include hcoord in +lemma simpleCompleted_ray (j : ℕ) (m : M) + (hm : coeff (j+1) (simpleCompleted Ω C coord hcoord pc).val m≠0) : + OnPositiveRay (simpleRoot C pc) m := by + change coeff (j+1) (normalizedSimple Ω (simpleRoot C pc)) m≠0 at hm + rw [normalizedSimple,coeff_raySeries] at hm + have he : m=(j+1) • simpleRoot C pc:=by + by_contra hh; exact hm (Finsupp.single_eq_of_ne hh) + exact ⟨1,j+1,by omega,by omega,by simpa only [one_nsmul] using he⟩ + +include hcoord in +def simpleOrientedCompleted (pos : Bool) : CompletedPositive LaurentRay.vUnit Ω C := + if pos then simpleCompleted Ω C coord hcoord pc else + completedInverse LaurentRay.vUnit Ω C (simpleCompleted Ω C coord hcoord pc) + +include hcoord in +lemma simpleOrientedCompleted_value (pos : Bool) : + (simpleOrientedCompleted Ω C coord hcoord pc pos).val= + simpleOriented Ω pos (simpleRoot C pc) := by cases pos <;> rfl + +include hcoord in +lemma simple_cut_chart_bound (hΩ : ∀m,Ω m m=0) (pos : Bool) + (A F : CompletedPositive LaurentRay.vUnit Ω C) (N : ℕ) (n : ℤ) + (hprod : ∀j≤N,coeff j F.val=coeff j + (if pos then (normalizedSimple Ω (simpleRoot C pc))*A.val + else A.val*(normalizedSimple Ω (simpleRoot C pc)))) + (htrend : ∀j≤N,∀m,coeff j A.val m≠0 → 0≤ sideSign pos*Ω (simpleRoot C pc) m) + (hbound : ∀j≤N,∀m,coeff j A.val m≠0 → nonpDegree coord pc m≤n → + m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) + (h : M →+ ℝ) (hside : cutSide (!pos) h (simpleRoot C pc)) : + ∀j≤N,∀m,coeff j (chartZero LaurentRay.vUnit Ω C h F).val m≠0 → + nonpDegree coord pc m≤n → m∈fiberCone coord pc (mutationPairing Ω C pc) (-sideSign pos) := by + let D:=simpleCompleted Ω C coord hcoord pc + let O:=simpleOrientedCompleted Ω C coord hcoord pc pos + let G:=completedConjugate LaurentRay.vUnit Ω C O A + have hGval : G.val=adjoint (simpleOriented Ω pos (simpleRoot C pc)) A.val:=by + change O.val*A.val*invOfUnit O.val 1=_ + rw [show O.val=simpleOriented Ω pos (simpleRoot C pc) from simpleOrientedCompleted_value Ω C coord hcoord pc pos] + rfl + let P:=fiberCone coord pc (mutationPairing Ω C pc) (-sideSign pos) + let Q:=boundedNonpFrame (nonpDegree coord pc) P n + have hQ : ∀j≤N,coeff j G.val∈supportedSubring LaurentRay.vUnit Ω Q:=by + intro j hj m hmQ + by_contra hm + apply hmQ + refine ⟨nonpDegree_root_nonneg C coord hcoord pc (chart_root_of_ne LaurentRay.vUnit Ω C G j m hm),?_⟩ + intro hn + apply simpleOriented_adjoint_fiber Ω C coord hcoord pc hΩ pos A.val j n + (fun a _=>A.property.2 a) (fun a ha=>htrend a (ha.trans hj)) + (fun a ha=>hbound a (ha.trans hj)) m ?_ hn + rwa [←hGval] + let Gc:=completedCut LaurentRay.vUnit Ω C N G + have hchartQ:= (chartThree_supported LaurentRay.vUnit Ω C h Q Gc + (completedCut_supported LaurentRay.vUnit Ω C N G Q hQ)).2.1 + have hremove : ∀j≤N,coeff j (chartZero LaurentRay.vUnit Ω C h F).val= + coeff j (chartZero LaurentRay.vUnit Ω C h G).val:=by + cases pos + · have Hprod : ∀j≤N,coeff j F.val=coeff j (completedMul LaurentRay.vUnit Ω C D G).val:=by + intro j hj + rw [hprod j hj] + simp only [Bool.false_eq_true,ite_false] + change coeff j (A.val*D.val)=coeff j (D.val*G.val) + rw [hGval] + change coeff j (A.val*D.val)=coeff j (D.val*adjoint (invOfUnit D.val 1) A.val) + rw [adjoint_inverse _ _ D.property.1,←mul_assoc,←mul_assoc,mul_invOfUnit _ 1 D.property.1,one_mul] + intro j hj + rw [chartZero_congr_through LaurentRay.vUnit Ω C h F _ N Hprod j hj] + apply chartZero_left_positive LaurentRay.vUnit Ω C h D G N ?_ j hj + intro k hk m hm + have HR:=simpleCompleted_ray Ω C coord hcoord pc k m hm + exact (HR.eval h).1.mpr hside + · have Hprod : ∀j≤N,coeff j F.val=coeff j (completedMul LaurentRay.vUnit Ω C G D).val:=by + intro j hj + rw [hprod j hj] + simp only [ite_true] + change coeff j (D.val*A.val)=coeff j (G.val*D.val) + rw [hGval] + change coeff j (D.val*A.val)=coeff j (adjoint D.val A.val*D.val) + rw [adjoint,mul_assoc,mul_assoc,invOfUnit_mul _ 1 D.property.1,mul_one] + intro j hj + rw [chartZero_congr_through LaurentRay.vUnit Ω C h F _ N Hprod j hj] + apply chartZero_right_negative LaurentRay.vUnit Ω C h G D N ?_ j hj + intro k hk m hm + have HR:=simpleCompleted_ray Ω C coord hcoord pc k m hm + exact (HR.eval h).2.2.mpr hside + have hcut:=chartZero_congr_through LaurentRay.vUnit Ω C h Gc G N + (fun j hj=>coeff_cut_of_le G.val hj) + intro j hj m hm hn + have hmGc : coeff j (chartZero LaurentRay.vUnit Ω C h Gc).val m≠0:=by + rw [hcut j hj,←hremove j hj]; exact hm + have hmQ : m∈Q:=by by_contra hh; exact hmGc (hchartQ j m hh) + exact hmQ.2 hn +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/PureCutGroup.lean b/lean/OAI/Combinatorics/Chromatic/Walls/PureCutGroup.lean new file mode 100644 index 0000000000000000000000000000000000000000..13c5461d4b504448508cdeac9d84635ac9d61df3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/PureCutGroup.lean @@ -0,0 +1,207 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.NearCutGeometry + +namespace OAI + +section +namespace ElementaryPositivity.AffineCut +noncomputable section +variable {G:Type*} [Group G] +def oldGauge (g:G) (side:Bool) : G := if side then g⁻¹ else 1 +def oldFactor (g:G) (u v t:ℝ) : G := if u+t*v=0 then if v<0 then g else g⁻¹ else 1 +lemma oldFactor_local (g:G) (u v t:ℝ) (hne:u≠0 ∨ v≠0) (x:G) : + oldFactor g u v t*(oldGauge g (beforeSide u v t)*x)=oldGauge g (afterSide u v t)*x := by + by_cases hz:u+t*v=0 + · have hv:v≠0:=by rintro rfl; simp_all + rw [oldFactor,ite_eq_left hz,(sides_at_zero u v t hz).1,(sides_at_zero u v t hz).2] + rcases lt_or_gt_of_ne hv with hn|hp + · simp [oldGauge,hn,show ¬0x) (fun t x=>oldFactor g u v t*x) + (fun side x=>oldGauge g side*x) T lo hi hlohi hmem hcut + (fun t _ x=>oldFactor_local g u v t hne x) 1 + have hid:(T.sort (· ≥ ·)).foldr (fun _ (x:G)=>x) 1=1:=by + generalize T.sort (· ≥ ·)=l + induction l <;> simp_all + have hmul:∀l:List ℝ,∀x:G,l.foldr (fun t x=>oldFactor g u v t*x) x= + (l.map (oldFactor g u v)).prod*x:=by + intro l x + induction l with + | nil=>simp + | cons a l ih=>simp only [List.foldr_cons,List.map_cons,List.prod_cons,ih,mul_assoc] + rw [(sides_eq_of_ne u v lo hlo).2,(sides_eq_of_ne u v hi hhi).1,hid,mul_one,mul_one,hmul] at H + exact H +end +end ElementaryPositivity.AffineCut + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +variable (v k:Module.Dual ℝ E) (H:∀N,GenericOffset (realRootsThrough e C N) 0 v k) + +include he hdeg H in +omit [FiniteDimensional ℝ E] in +lemma nearCut_letter (a:ℝ) (hh:NearCut Ω C pc e (k+a • v)) : + comparisonOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H a)= + AffineCut.oldFactor (oldPureUnit LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc)) + (k (e (simpleRoot C pc))) (v (e (simpleRoot C pc))) a := by + classical + by_cases hp:(k+a • v) (e (simpleRoot C pc))=0 + · have ha:∃N,a∈lineEvents (realRootsThrough e C N) v k:=⟨1,line_cut_event C pc e L hdeg v k H a hp⟩ + unfold actualLineLetter + simp only [dite_eq_left ha,dite_eq_left hp] + have hp':k (e (simpleRoot C pc))+a*v (e (simpleRoot C pc))=0:=hp + rw [AffineCut.oldFactor,ite_eq_left hp'] + by_cases hv:v (e (simpleRoot C pc))<0 <;> simp only [hv,decide_true,decide_false,comparisonOld,↓reduceIte] + · have hp':k (e (simpleRoot C pc))+a*v (e (simpleRoot C pc))≠0:=hp + rw [AffineCut.oldFactor,ite_eq_right hp'] + by_cases ha:∃N,a∈lineEvents (realRootsThrough e C N) v k + · obtain ⟨r,d,hd,hr,hv,hg,HE⟩:=actualLineLetter_old Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a ha + have HC:=nearCut_noncut_wall Ω C coord hcoord pc e he S hS hcomp L hdeg (k+a • v) hh + r d hd hr hg (decide (0<(k+a • v) (e (simpleRoot C pc)))) + (cutSide_decide ((k+a • v).toAddMonoidHom.comp e) (simpleRoot C pc) hp) + have HU:completedBiUnit LaurentRay.vUnit Ω C coord hcoord pc + (chartZero LaurentRay.vUnit Ω C ((k+a • v).toAddMonoidHom.comp e) (simpleTotalTransport Ω C))=1:=by + apply Units.ext + apply Subtype.ext + exact HC + rw [HE,HU] + split_ifs <;> simp + · simp only [actualLineLetter,dite_eq_right ha,comparisonOld] + +include he hdeg H in +omit [FiniteDimensional ℝ E] in +lemma nearCut_line_word (lo hi:ℝ) (hlohi:lohlo (line_cut_event C pc e L hdeg v k H lo hz)) + (fun hz=>hhi (line_cut_event C pc e L hdeg v k H hi hz)) + (intervalLineEvents C e v k lo hi N) (fun a ha=>(Finset.mem_filter.mp ha).2) + (fun a hla hah hz=>Finset.mem_filter.mpr ⟨lineEvents_mono (realRootsThrough_mono C e hN) v k + (line_cut_event C pc e L hdeg v k H a hz),hla,hah⟩) + rw [show (intervalEventList C e v k lo hi N).map + ((comparisonOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1)) ∘ + actualLineLetter Ω C coord hcoord pc e he S hS hcomp L hdeg v k H)=_ from + List.map_congr_left (fun a ha=>nearCut_letter Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg v k H a + (hh a (Finset.mem_filter.mp ((Finset.mem_sort _).mp ha)).2.1.le + (Finset.mem_filter.mp ((Finset.mem_sort _).mp ha)).2.2.le))] + exact HH +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open QuantumTorus PowerSeries WallUnits FiniteRayGeometry +noncomputable section +variable {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (C:(I → ℤ) →+ M) (coord:M →+ (I → ℤ)) (hcoord:∀d,coord (C d)=d) (pc:I) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + +include he hdeg in +omit [FiniteDimensional ℝ E] in +lemma nearCut_path_word {a b:Module.Dual ℝ E} (p:GenericLinePath C e a b) + (hh:p.InRegion C e {h | NearCut Ω C pc e h}) (N:ℕ) (hN:1≤N) : + comparisonWordOld LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc) (mutationSize Ω C pc+1) + (actualPathWord Ω C coord hcoord pc e he S hS hcomp L hdeg p N)* + AffineCut.oldGauge (oldPureUnit LaurentRay.vUnit Ω hΩ (nonpDegree coord pc) (pureDegree coord pc) + (simpleRoot C pc) (pureDegree_simple_self C coord hcoord pc) + (nonpDegree_simple_self C coord hcoord pc)) (decide (0simp only [actualPathWord,comparisonWordOld,List.map_nil,List.prod_nil,one_mul] + | append s p ih=> + rw [actualPathWord,comparisonWordOld_append,mul_assoc,ih hh.2] + exact nearCut_line_word Ω hΩ C coord hcoord pc e he S hS hcomp L hdeg + s.direction s.offset s.generic s.lo s.hi s.ordered (s.start_regular 1) (s.finish_regular 1) hh.1 N hN + +include he hdeg S hS hcomp in +lemma nearCut_chart_ratio (hC:LinearIndependent ℝ (fun i=>e (simpleRoot C i))) + {a b:Module.Dual ℝ E} (HA:RegularCovector C e a) (HB:RegularCovector C e b) + (ha:NearCut Ω C pc e a) (hb:NearCut Ω C pc e b) + (hap:a (e (simpleRoot C pc))<0) (hbp:0(d i:ℤ))=m + +lemma rootDegree_zero : HasRootDegree C 0 0 := by + refine ⟨0,by simp,?_⟩ + change C (0 : I → ℤ)=0 + exact C.map_zero + +lemma rootDegree_add {n k : ℕ} {m p : M} + (hm : HasRootDegree C n m) (hp : HasRootDegree C k p) : + HasRootDegree C (n+k) (m+p) := by + obtain ⟨d,hd,hmd⟩:=hm + obtain ⟨e,he,hpe⟩:=hp + refine ⟨d+e,by simpa only [Pi.add_apply,Finset.sum_add_distrib] using congrArg₂ (·+·) hd he,?_⟩ + have hh : (fun i=>((d+e) i:ℤ))=(fun i=>(d i:ℤ))+(fun i=>(e i:ℤ)) := by + ext i; simp + rw [hh,map_add,hmd,hpe] + +def rootGrade (n : ℕ) : AddSubgroup (Torus v Ω) where + carrier := {f | ∀m,¬HasRootDegree C n m → f m=0} + zero_mem' := by intro m hm; rfl + add_mem' := by intro f g hf hg m hm; change f m+g m=0; rw [hf m hm,hg m hm,add_zero] + neg_mem' := by intro f hf m hm; change -f m=0; rw [hf m hm,neg_zero] + +lemma rootGrade_one : (1 : Torus v Ω)∈rootGrade v Ω C 0 := by + intro m hm + change Finsupp.single 0 (1:R) m=0 + apply Finsupp.single_eq_of_ne + intro he + exact hm (he ▸ rootDegree_zero C) + +lemma rootGrade_mul (n k : ℕ) (f g : Torus v Ω) + (hf : f∈rootGrade v Ω C n) (hg : g∈rootGrade v Ω C k) : + f*g∈rootGrade v Ω C (n+k) := by + classical + intro m hm + change (Torus.multiply v Ω f g) m=0 + simp only [Torus.multiply,Finsupp.sum,Finsupp.finsetSum_apply] + apply Finset.sum_eq_zero + intro x hx + apply Finset.sum_eq_zero + intro y hy + have hxC : HasRootDegree C n x := by + by_contra hn + exact (Finsupp.mem_support_iff.mp hx) (hf x hn) + have hyC : HasRootDegree C k y := by + by_contra hn + exact (Finsupp.mem_support_iff.mp hy) (hg y hn) + apply Finsupp.single_eq_of_ne + intro he + exact hm (he ▸ rootDegree_add C hxC hyC) + +lemma rootGrade_filter (p : M → Prop) [DecidablePred p] (n : ℕ) (f : Torus v Ω) + (hf : f∈rootGrade v Ω C n) : f.filter p∈rootGrade v Ω C n := by + intro m hm + simp only [Finsupp.filter_apply,hf m hm,ite_self] + +def CompletedPositive := {f : PowerSeries (Torus v Ω) // + constantCoeff f=1 ∧ ∀n,coeff n f∈rootGrade v Ω C n} + +variable (h : M →+ ℝ) +open ElementaryPositivity.PowerSeriesSplit + +def chartPositive (f : CompletedPositive v Ω C) : CompletedPositive v Ω C := + ⟨positiveFactor (positiveProject v Ω h) f.val,left_constant _ _, + (factors_graded (positiveProject v Ω h) (rootGrade v Ω C) (rootGrade_one v Ω C) + (rootGrade_mul v Ω C) (fun n x hx=>rootGrade_filter v Ω C _ n x hx) f.val f.property.2).1⟩ +def chartRemainder (f : CompletedPositive v Ω C) : CompletedPositive v Ω C := + ⟨rightFactor (positiveProject v Ω h) f.val,right_constant _ _, + (factors_graded (positiveProject v Ω h) (rootGrade v Ω C) (rootGrade_one v Ω C) + (rootGrade_mul v Ω C) (fun n x hx=>rootGrade_filter v Ω C _ n x hx) f.val f.property.2).2⟩ +def chartZero (f : CompletedPositive v Ω C) : CompletedPositive v Ω C := + ⟨leftFactor (zeroProject v Ω h) (chartRemainder v Ω C h f).val,left_constant _ _, + (factors_graded (zeroProject v Ω h) (rootGrade v Ω C) (rootGrade_one v Ω C) + (rootGrade_mul v Ω C) (fun n x hx=>rootGrade_filter v Ω C _ n x hx) + _ (chartRemainder v Ω C h f).property.2).1⟩ +def chartNegative (f : CompletedPositive v Ω C) : CompletedPositive v Ω C := + ⟨rightFactor (zeroProject v Ω h) (chartRemainder v Ω C h f).val,right_constant _ _, + (factors_graded (zeroProject v Ω h) (rootGrade v Ω C) (rootGrade_one v Ω C) + (rootGrade_mul v Ω C) (fun n x hx=>rootGrade_filter v Ω C _ n x hx) + _ (chartRemainder v Ω C h f).property.2).2⟩ + +lemma chart_three_factorization (f : CompletedPositive v Ω C) : + (chartPositive v Ω C h f).val * (chartZero v Ω C h f).val * + (chartNegative v Ω C h f).val = f.val := + factor_three (positiveProject v Ω h) (zeroProject v Ω h) f.val f.property.1 + +lemma chart_three_support (f : CompletedPositive v Ω C) : + (∀n m,coeff (n+1) (chartPositive v Ω C h f).val m≠0 → 00 rw [coeff_zero_eq_constantCoeff_apply,b.property.1]; exact positiveProject_one v Ω h + | succ n => + apply (Finsupp.filter_eq_zero_iff _ _).mpr + intro m hm + by_contra hn + have hh:=hb n m hn + linarith + have hcP : ∀n,positiveProject v Ω h (coeff n c.val)=0 := by + intro n + cases n with + | zero => rw [coeff_zero_eq_constantCoeff_apply,c.property.1]; exact positiveProject_one v Ω h + | succ n => + apply (Finsupp.filter_eq_zero_iff _ _).mpr + intro m hm + by_contra hn + have hh:=hc n m hn + linarith + have hbQ : ∀n,zeroProject v Ω h (coeff (n+1) b.val)=coeff (n+1) b.val := by + intro n + exact (Finsupp.filter_eq_self_iff _ _).mpr (hb n) + have hcQ : ∀n,zeroProject v Ω h (coeff (n+1) c.val)=0 := by + intro n + apply (Finsupp.filter_eq_zero_iff _ _).mpr + intro m hm + by_contra hn + have hh:=hc n m hn + linarith + have hu:=three_uniqueness (positiveProject v Ω h) (zeroProject v Ω h) + (supportedSubring v Ω (nonpositiveCone h)) (nonpositive_iff v Ω h) + f.val a.val b.val c.val a.property.1 b.property.1 c.property.1 he haP hbP hcP hbQ hcQ + exact ⟨Subtype.ext hu.1,Subtype.ext hu.2.1,Subtype.ext hu.2.2⟩ + +end +end ElementaryPositivity.QuantumTorus +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/QuantumTorusRaySeries.lean b/lean/OAI/Combinatorics/Chromatic/Walls/QuantumTorusRaySeries.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c1446a75c5bcecff63d2389afbfadf9dc4e67ee --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/QuantumTorusRaySeries.lean @@ -0,0 +1,184 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.QuantumTorusTrace +import OAI.Combinatorics.Chromatic.Walls.WallUnits + +namespace OAI + +section +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) +local instance raySeriesAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +noncomputable def raySeries (a : M) (f : PowerSeries R) : PowerSeries (Torus v Ω) := + PowerSeries.mk (fun n=>Torus.monomial v Ω (n • a) (coeff n f)) +@[simp] lemma coeff_raySeries (a : M) (f : PowerSeries R) (n : ℕ) : + coeff n (raySeries v Ω a f)=Torus.monomial v Ω (n • a) (coeff n f) := by + rw [raySeries,coeff_mk] +lemma raySeries_one (a : M) : raySeries v Ω a 1=1 := by + apply PowerSeries.ext + intro n + rw [coeff_raySeries,coeff_one,coeff_one] + split_ifs with hn + · subst n + rw [zero_nsmul] + rfl + · exact Torus.monomial_zero v Ω _ +lemma monomial_sum {α : Type*} (s : Finset α) (m : M) (f : α → R) : + Torus.monomial v Ω m (∑i∈s,f i)=∑i∈s,Torus.monomial v Ω m (f i) := by + change Finsupp.singleAddHom m (∑i∈s,f i)=∑i∈s,Finsupp.singleAddHom m (f i) + exact map_sum (Finsupp.singleAddHom m) f s +lemma raySeries_mul (a : M) (ha : Ω a a=0) (f g : PowerSeries R) : + raySeries v Ω a (f*g)=raySeries v Ω a f*raySeries v Ω a g := by + apply PowerSeries.ext + intro n + rw [coeff_raySeries,coeff_mul,coeff_mul,monomial_sum] + apply Finset.sum_congr rfl + intro p hp + have he:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + rw [coeff_raySeries,coeff_raySeries,Torus.monomial_mul_monomial] + have hz : Ω (p.1 • a) (p.2 • a)=0 := by + simp only [map_nsmul,AddMonoidHom.nsmul_apply,ha,nsmul_zero] + rw [hz,zpow_zero,Units.val_one,mul_one,←add_nsmul,he] + +lemma raySeries_twist (hΩ : ∀m,Ω m m=0) (a m : M) (f : PowerSeries R) : + raySeries v Ω a f*PowerSeries.C (Torus.X v Ω m)= + PowerSeries.C (Torus.X v Ω m)*raySeries v Ω a (PowerSeries.rescale (↑(v^(2*Ω a m)):R) f) := by + apply PowerSeries.ext + intro n + rw [coeff_mul_C,coeff_C_mul,coeff_raySeries,coeff_raySeries,coeff_rescale] + simp only [Torus.X,Torus.monomial_mul_monomial,mul_one,one_mul] + rw [add_comm (n • a) m] + congr 1 + have hn : Ω (n • a) m=(n:ℤ)*Ω a m := by simp [map_nsmul] + have hn' : Ω m (n • a)= -((n:ℤ)*Ω a m) := by + rw [alternating_skew Ω hΩ m (n • a),hn] + rw [hn,hn'] + have he : (↑(v^(2*Ω a m)):R)^n * (↑(v^(-((n:ℤ)*Ω a m))):R)=↑(v^((n:ℤ)*Ω a m)) := by + rw [←Units.val_pow_eq_pow_val,←zpow_natCast,←zpow_mul,←Units.val_mul,←zpow_add] + congr 2 + ring + calc + coeff n f * ↑(v^((n:ℤ)*Ω a m)) = coeff n f * ((↑(v^(2*Ω a m)):R)^n * ↑(v^(-((n:ℤ)*Ω a m)))) := by rw [he] + _ = ((↑(v^(2*Ω a m)):R)^n * coeff n f) * ↑(v^(-((n:ℤ)*Ω a m))) := by ring +end +end ElementaryPositivity.QuantumTorus +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) +local instance rayUnitAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def rayUnit (a : M) (ha : Ω a a=0) (f : PowerSeries K) (hf : constantCoeff f=1) : + (PowerSeries (Torus v Ω))ˣ where + val:=raySeries v Ω a f + inv:=raySeries v Ω a f⁻¹ + val_inv:=by + rw [←raySeries_mul v Ω a ha,PowerSeries.mul_inv_cancel f (by rw [hf]; exact one_ne_zero),raySeries_one] + inv_val:=by + rw [←raySeries_mul v Ω a ha,PowerSeries.inv_mul_cancel f (by rw [hf]; exact one_ne_zero),raySeries_one] + +lemma ray_adjoint (hΩ : ∀m,Ω m m=0) (a m : M) (f : PowerSeries K) (hf : constantCoeff f=1) : + (rayUnit v Ω a (hΩ a) f hf).val * PowerSeries.C (Torus.X v Ω m) * + (rayUnit v Ω a (hΩ a) f hf).inv= + PowerSeries.C (Torus.X v Ω m) * raySeries v Ω a + (PowerSeries.rescale (↑(v^(2*Ω a m)):K) f * f⁻¹) := by + change raySeries v Ω a f * PowerSeries.C (Torus.X v Ω m) * raySeries v Ω a f⁻¹=_ + rw [raySeries_twist v Ω hΩ,mul_assoc,←raySeries_mul v Ω a (hΩ a)] + +lemma ray_inverse_adjoint (hΩ : ∀m,Ω m m=0) (a m : M) (f : PowerSeries K) (hf : constantCoeff f=1) : + (rayUnit v Ω a (hΩ a) f hf).inv * PowerSeries.C (Torus.X v Ω m) * + (rayUnit v Ω a (hΩ a) f hf).val= + PowerSeries.C (Torus.X v Ω m) * raySeries v Ω a + (PowerSeries.rescale (↑(v^(2*Ω a m)):K) f⁻¹ * f) := by + change raySeries v Ω a f⁻¹ * PowerSeries.C (Torus.X v Ω m) * raySeries v Ω a f=_ + rw [raySeries_twist v Ω hΩ,mul_assoc,←raySeries_mul v Ω a (hΩ a)] +end +end ElementaryPositivity.QuantumTorus +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M : Type*} [AddCommGroup M] +variable (Ω : M →+ M →+ ℤ) +local instance positiveCoefficientsAddGroup : AddGroup (Torus PositiveRay.vUnit Ω) := + (Torus.instRing PositiveRay.vUnit Ω).toAddGroup + +def PositiveCoefficients (f : PowerSeries (Torus PositiveRay.vUnit Ω)) : Prop := + ∀n m,∃p : LaurentPolynomial ℕ,PositiveRay.eval p=coeff n f m + +lemma positive_scalar_monomial (m : M) (p : LaurentPolynomial ℕ) (x : M) : + ∃q : LaurentPolynomial ℕ,PositiveRay.eval q=Torus.monomial PositiveRay.vUnit Ω m (PositiveRay.eval p) x := by + classical + by_cases h : m=x + · subst x + exact ⟨p,(Finsupp.single_eq_same).symm⟩ + · refine ⟨0,?_⟩ + rw [map_zero] + exact (Finsupp.single_eq_of_ne (Ne.symm h)).symm + +lemma positive_monomial_ray (a m : M) (F : PowerSeries (RatFunc ℚ)) + (hF : PositiveRay.Positive F) : + PositiveCoefficients Ω (PowerSeries.C (Torus.X PositiveRay.vUnit Ω m) * raySeries PositiveRay.vUnit Ω a F) := by + obtain ⟨A,rfl⟩:=hF + intro n x + rw [coeff_C_mul,coeff_raySeries,Torus.X,Torus.monomial_mul_monomial,one_mul,coeff_map] + have he : (↑(PositiveRay.vUnit ^ Ω m (n • a)):RatFunc ℚ)=PositiveRay.eval (LaurentPolynomial.T (Ω m (n • a))) := by + rw [PositiveRay.eval_T] + simp only [Units.val_zpow_eq_zpow_val,PositiveRay.vUnit,Units.val_mk0] + rw [he,←map_mul] + exact positive_scalar_monomial Ω (m+n • a) _ x + +lemma positive_elementary_adjoint (hΩ : ∀m,Ω m m=0) (a m : M) (k : ℤ) (t : ℕ) + (ht : Ω a m=(t:ℤ)) : + PositiveCoefficients Ω ( + (rayUnit PositiveRay.vUnit Ω a (hΩ a) (elementary RationalRay.q (RationalRay.v^k)) + (constant_elementary _ _)).val * PowerSeries.C (Torus.X PositiveRay.vUnit Ω m) * + (rayUnit PositiveRay.vUnit Ω a (hΩ a) (elementary RationalRay.q (RationalRay.v^k)) + (constant_elementary _ _)).inv) := by + rw [ray_adjoint PositiveRay.vUnit Ω hΩ] + apply positive_monomial_ray + have he : (↑(PositiveRay.vUnit^(2*Ω a m)):RatFunc ℚ)=RationalRay.q⁻¹^t := by + rw [ht,inv_pow,RationalRay.q_pow,←zpow_neg] + change RationalRay.v^(2*(t:ℤ))=RationalRay.v^(-(-2*(t:ℤ))) + congr 1 + ring + rw [he] + exact RationalRay.elementary_ratio_positive k t + +lemma complete_constant (q u : RatFunc ℚ) : constantCoeff (complete q u)=1 := by + simp only [complete,PowerSeries.constantCoeff_inv,constant_elementary,inv_one] + +lemma complete_inverse (q u : RatFunc ℚ) : (complete q u)⁻¹=elementary q (-u) := by + apply (PowerSeries.inv_eq_iff_mul_eq_one (by rw [complete_constant]; exact one_ne_zero)).mpr + exact PowerSeries.mul_inv_cancel _ (by rw [constant_elementary]; exact one_ne_zero) + +lemma positive_complete_adjoint (hΩ : ∀m,Ω m m=0) (a m : M) (k : ℤ) (t : ℕ) + (ht : Ω a m=(t:ℤ)) : + PositiveCoefficients Ω ( + (rayUnit PositiveRay.vUnit Ω a (hΩ a) (complete RationalRay.q (RationalRay.v^k)) + (complete_constant _ _)).val * PowerSeries.C (Torus.X PositiveRay.vUnit Ω m) * + (rayUnit PositiveRay.vUnit Ω a (hΩ a) (complete RationalRay.q (RationalRay.v^k)) + (complete_constant _ _)).inv) := by + rw [ray_adjoint PositiveRay.vUnit Ω hΩ] + apply positive_monomial_ray + have he : (↑(PositiveRay.vUnit^(2*Ω a m)):RatFunc ℚ)=RationalRay.q⁻¹^t := by + rw [ht,inv_pow,RationalRay.q_pow,←zpow_neg] + change RationalRay.v^(2*(t:ℤ))=RationalRay.v^(-(-2*(t:ℤ))) + congr 1 + ring + rw [he,complete_inverse] + exact RationalRay.complete_ratio_positive k t +end +end ElementaryPositivity.QuantumTorus +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/QuantumTorusWallLeading.lean b/lean/OAI/Combinatorics/Chromatic/Walls/QuantumTorusWallLeading.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f2988f637f13e0da799a6b55f3d1b31a327697f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/QuantumTorusWallLeading.lean @@ -0,0 +1,81 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.QuantumTorusChartCompletion +import OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesProductLeading + +namespace OAI + +section +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries ElementaryPositivity.PowerSeriesSplit +noncomputable section +variable {R M I A : Type*} [CommRing R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) (h : M →+ ℝ) +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub + +omit [Fintype I] in +lemma zero_positive_project (x : Torus v Ω) : + zeroProject v Ω h (positiveProject v Ω h x)=0 := by + classical + ext m + change (x.filter (fun m=>0.filter (fun m=>h m=0)) m=0 + simp only [Finsupp.filter_apply] + split_ifs <;> first | rfl | linarith + +lemma chartZero_leading_difference (f g : CompletedPositive v Ω C) (n : ℕ) + (hlow : ∀k≤n,coeff k f.val=coeff k g.val) : + coeff (n+1) (chartZero v Ω C h f).val- + coeff (n+1) (chartZero v Ω C h g).val= + zeroProject v Ω h (coeff (n+1) f.val-coeff (n+1) g.val) := + zero_leading_difference (positiveProject v Ω h) (zeroProject v Ω h) + (zero_positive_project v Ω h) f.val g.val n hlow + +omit [Fintype I] in +lemma joint_middle_leading_difference (f g : A → PowerSeries (Torus v Ω)) + (l : List A) (n : ℕ) + (hf : ∀a∈l,constantCoeff (f a)=1) (hg : ∀a∈l,constantCoeff (g a)=1) + (hlow : ∀a∈l,∀k≤n,coeff k (f a)=coeff k (g a)) : + coeff (n+1) (zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) (l.map f).prod)- + coeff (n+1) (zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) (l.map g).prod)= + zeroProject v Ω h + (l.map (fun a=>coeff (n+1) (f a)-coeff (n+1) (g a))).sum := by + rw [zero_leading_difference (positiveProject v Ω h) (zeroProject v Ω h) + (zero_positive_project v Ω h) _ _ n + (fun k hk=>product_coeff_congr f g l k (fun a ha j hj=>hlow a ha j (hj.trans hk)))] + rw [product_leading_difference f g l n hf hg hlow] + +omit [Fintype I] in +lemma joint_middle_monomial_unaffected (f g : A → PowerSeries (Torus v Ω)) + (l : List A) (n : ℕ) (m : M) + (hf : ∀a∈l,constantCoeff (f a)=1) (hg : ∀a∈l,constantCoeff (g a)=1) + (hlow : ∀a∈l,∀k≤n,coeff k (f a)=coeff k (g a)) + (hlast : ∀a∈l,coeff (n+1) (f a) m=coeff (n+1) (g a) m) : + coeff (n+1) (zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) (l.map f).prod) m= + coeff (n+1) (zeroFactor (positiveProject v Ω h) (zeroProject v Ω h) (l.map g).prod) m := by + classical + have eval_sub (x y : Torus v Ω) : (x-y) m=x m-y m := by + change x m + -y m=x m-y m + exact (sub_eq_add_neg _ _).symm + have he:=congrArg (fun x : Torus v Ω=>x m) + (joint_middle_leading_difference v Ω h f g l n hf hg hlow) + rw [eval_sub] at he + change _-_=((l.map (fun a=>coeff (n+1) (f a)-coeff (n+1) (g a))).sum.filter + (fun x=>h x=0)) m at he + rw [Finsupp.filter_apply] at he + have hz : (l.map (fun a=>coeff (n+1) (f a)-coeff (n+1) (g a))).sum m=0 := by + clear he hf hg hlow + induction l with + | nil => rfl + | cons a l ih => + simp only [List.map_cons,List.sum_cons,Finsupp.add_apply] + rw [eval_sub,hlast a List.mem_cons_self,sub_self,zero_add] + exact ih (fun b hb=>hlast b (List.mem_cons_of_mem a hb)) + rw [hz,ite_self] at he + exact sub_eq_zero.mp he +end +end ElementaryPositivity.QuantumTorus +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RationalCocycleExt.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RationalCocycleExt.lean new file mode 100644 index 0000000000000000000000000000000000000000..54a417011ef3eb5c8ee1c027244cadf92afde4f4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RationalCocycleExt.lean @@ -0,0 +1,33 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RationalPureCocycle + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +variable {K : Type*} [Field K] (v : Kˣ) +def cocycleLift (c : ℤ → (RatFunc K)ˣ) (h0 : c 0=1) + (hc : ∀t u,c (t+u)=c t*scaleAction v (Multiplicative.ofAdd t) (c u)) : + Multiplicative ℤ →* PureExtension v where + toFun t:=⟨c t.toAdd,t⟩ + map_one':=by apply SemidirectProduct.ext; exact h0; rfl + map_mul' t u:=by apply SemidirectProduct.ext; exact hc _ _; rfl +lemma cocycle_eq_zpow (c : ℤ → (RatFunc K)ˣ) (h0 : c 0=1) + (hc : ∀t u,c (t+u)=c t*scaleAction v (Multiplicative.ofAdd t) (c u)) (t : ℤ) : + c t=((⟨c 1,Multiplicative.ofAdd 1⟩ : PureExtension v)^t).left := by + have H:=map_zpow (cocycleLift v c h0 hc) (Multiplicative.ofAdd 1) t + rw [←ofAdd_zsmul,smul_eq_mul,mul_one] at H + exact congrArg SemidirectProduct.left H +lemma cocycle_ext (c d : ℤ → (RatFunc K)ˣ) (hc0 : c 0=1) (hd0 : d 0=1) + (hc : ∀t u,c (t+u)=c t*scaleAction v (Multiplicative.ofAdd t) (c u)) + (hd : ∀t u,d (t+u)=d t*scaleAction v (Multiplicative.ofAdd t) (d u)) + (h1 : c 1=d 1) : c=d := by + funext t + rw [cocycle_eq_zpow v c hc0 hc,cocycle_eq_zpow v d hd0 hd,h1] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RationalCutIdentity.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RationalCutIdentity.lean new file mode 100644 index 0000000000000000000000000000000000000000..32c1ac56459f161be9a785c813a7bd4c8c6d7f04 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RationalCutIdentity.lean @@ -0,0 +1,144 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RationalCocycleExt +import OAI.Combinatorics.Chromatic.GradedAlgebra.RationalShearCocycle +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalPureAction + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) +lemma oppositeInverseRatio_one_val : (oppositeInverseRatio v 1:RatFunc K)= + 1+RatFunc.C (v:K)*(RatFunc.X:RatFunc K)⁻¹ := by + have H:=pureRatio_neg v (-1) + change scaleAction v (Multiplicative.ofAdd (-1)) (pureRatio v 1)=(pureRatio v (-1))⁻¹ at H + rw [pureRatio_one] at H + change reciprocal (↑((pureRatio v (-1))⁻¹):RatFunc K)=_ + rw [←H,scaleAction_val] + change reciprocal (scale (v^(-2*(-1:ℤ))) (1+RatFunc.C (↑(v⁻¹):K)*RatFunc.X))=_ + simp only [map_add,map_one,map_mul,scale_constant,scale_X, + reciprocal_constant,reciprocal_X] + rw [←mul_assoc,←map_mul,←Units.val_mul,←zpow_neg_one,←zpow_add] + norm_num +lemma cutRatio_one : shearRatio v 1*pureRatio v 1=oppositeInverseRatio v 1 := by + apply Units.ext + rw [Units.val_mul,shearRatio_val,pureRatio_one,oppositeInverseRatio_one_val] + change RatFunc.C (↑(v^((1:ℤ)*1)):K)*RatFunc.X^(-(1:ℤ))* + (1+RatFunc.C (↑(v⁻¹):K)*RatFunc.X)=_ + simp only [mul_one,zpow_one,zpow_neg_one,Units.val_inv_eq_inv_val,map_inv₀] + have hx : (RatFunc.X:RatFunc K)≠0:=RatFunc.X_ne_zero + have hv : RatFunc.C (v:K)≠0:=(map_ne_zero RatFunc.C).2 v.ne_zero + field_simp + ring +lemma cutRatio (t : ℤ) : shearRatio v t*pureRatio v t=oppositeInverseRatio v t := by + have H:=cocycle_ext v (fun t=>shearRatio v t*pureRatio v t) (oppositeInverseRatio v) + (by simp) (by simp) (by + intro t u + rw [shearRatio_add,pureRatio_add,map_mul] + simp only [mul_assoc,mul_left_comm,mul_comm]) (oppositeInverseRatio_add v) (cutRatio_one v) + exact congrFun H t + +variable (Ω : M →+ M →+ ℤ) (α : M →+ ℤ) +lemma shearRatio_val_add (t u : ℤ) : (shearRatio v (t+u):RatFunc K)= + (shearRatio v t:RatFunc K)*scale (v^(-2*t)) (shearRatio v u:RatFunc K) := by + rw [shearRatio_add,Units.val_mul,scaleAction_val] + rfl +lemma oppositeInverseRatio_val_add (t u : ℤ) : (oppositeInverseRatio v (t+u):RatFunc K)= + (oppositeInverseRatio v t:RatFunc K)*scale (v^(-2*t)) (oppositeInverseRatio v u:RatFunc K) := by + rw [oppositeInverseRatio_add,Units.val_mul,scaleAction_val] + rfl +def shearActionHom : FiberTorus v Ω α →+* FiberTorus v Ω α := + FiberTorus.gauge v Ω α (fun t=>(shearRatio v t:RatFunc K)) (by simp) (shearRatio_val_add v) +def oppositeInverseActionHom : FiberTorus v Ω α →+* FiberTorus v Ω α := + FiberTorus.gauge v Ω α (fun t=>(oppositeInverseRatio v t:RatFunc K)) + (by simp) (oppositeInverseRatio_val_add v) +lemma rational_cut_identity : + (shearActionHom v Ω α).comp (pureActionHom v Ω α)=oppositeInverseActionHom v Ω α := by + apply RingHom.ext + intro f + change FiberTorus.gaugeAdd v Ω α _ (FiberTorus.gaugeAdd v Ω α _ f)= + FiberTorus.gaugeAdd v Ω α _ f + rw [FiberTorus.gauge_comp] + have HH : (fun t=>(pureRatio v t:RatFunc K)*(shearRatio v t:RatFunc K))= + fun t=>(oppositeInverseRatio v t:RatFunc K) := by + funext t + rw [mul_comm,←Units.val_mul,cutRatio] + rw [HH] +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.WallUnits +open Polynomial +noncomputable section +variable {K : Type*} [Field K] +def centeredExponent (t : ℕ) (i : Fin t) : ℤ := 2*(i:ℕ)+1-(t:ℤ) +def centeredPolynomial (v : Kˣ) (t : ℕ) : K[X] := + ∏i : Fin t,(1+C (↑(v^centeredExponent t i):K)*X) +lemma centeredExponent_rev (t : ℕ) (i : Fin t) : + centeredExponent t i.rev= -centeredExponent t i := by + simp only [centeredExponent,Fin.val_rev] + have h:=i.isLt + omega +lemma centeredExponent_sum (t : ℕ) : ∑i : Fin t,centeredExponent t i=0 := by + have H : (∑i : Fin t,centeredExponent t i)=∑i : Fin t,centeredExponent t i.rev := + (Equiv.sum_comp (Fin.revPerm) (centeredExponent t)).symm + simp only [centeredExponent_rev,Finset.sum_neg_distrib] at H + omega +lemma centeredLetters_product (v : Kˣ) (t : ℕ) : + (∏i : Fin t,(↑(v^centeredExponent t i):K))=1 := by + have H : ∏i : Fin t,v^centeredExponent t i=v^(∑i : Fin t,centeredExponent t i) := by + have HH (s : Finset (Fin t)) : (∏i∈s,v^centeredExponent t i)=v^(∑i∈s,centeredExponent t i) := by + induction s using Finset.induction_on with + | empty=>simp + | @insert i s hi ih=>rw [Finset.prod_insert hi,Finset.sum_insert hi,ih,zpow_add] + exact HH Finset.univ + have H' := congrArg (fun a : Kˣ=>(a:K)) H + simpa only [Units.coe_prod,centeredExponent_sum,zpow_zero,Units.val_one] using H' +lemma reflect_linear (a : Kˣ) : + (1+C (a:K)*X).reflect 1=C (a:K)*(1+C (↑(a⁻¹):K)*X) := by + simp only [reflect_add,reflect_one,pow_one,reflect_C_mul,reflect_one_X,mul_one] + rw [mul_add,mul_one,←mul_assoc,←map_mul,Units.mul_inv,C_1,one_mul] + exact add_comm _ _ +lemma natDegree_linear_le (a : K) : (1+C a*X).natDegree≤1 := by + exact natDegree_add_le_of_degree_le (by simp) ((natDegree_C_mul_le _ _).trans (natDegree_X_le)) +lemma reflect_product_linear {J : Type*} [DecidableEq J] (s : Finset J) (a : J → K) : + (∏i∈s,(1+C (a i)*X)).reflect s.card=∏i∈s,(1+C (a i)*X).reflect 1 := by + induction s using Finset.induction_on with + | empty=>simp + | @insert i s hi ih=> + rw [Finset.prod_insert hi,Finset.card_insert_of_notMem hi,Finset.prod_insert hi] + have hd : (∏j∈s,(1+C (a j)*X)).natDegree≤ s.card := by + have H0 := natDegree_prod_le s (fun j => (1+C (a j)*X)) + have H1 : (∑j∈s,(1+C (a j)*X).natDegree) ≤ ∑j∈s,(1:ℕ) := + Finset.sum_le_sum (fun j _ => natDegree_linear_le (a j)) + exact H0.trans (by simpa using H1) + rw [show s.card+1=1+s.card by omega,reflect_mul _ _ (natDegree_linear_le _) hd,ih] +lemma centeredPolynomial_reflect (v : Kˣ) (t : ℕ) : + (centeredPolynomial v t).reflect t=centeredPolynomial v t := by + unfold centeredPolynomial + have Hcard : t=Finset.univ.card (α:=Fin t):=by simp + conv_lhs => arg 1; rw [Hcard] + rw [reflect_product_linear] + simp_rw [reflect_linear,Finset.prod_mul_distrib,←map_prod,centeredLetters_product,map_one,one_mul] + have H : (∏i : Fin t,(1+C (↑((v^centeredExponent t i)⁻¹):K)*X))= + ∏i : Fin t,(1+C (↑(v^centeredExponent t i.rev):K)*X) := by + apply Finset.prod_congr rfl + intro i hi + rw [centeredExponent_rev,zpow_neg] + rw [H] + exact Equiv.prod_comp (Fin.revPerm) (fun i : Fin t=>(1+C (↑(v^centeredExponent t i):K)*X)) +lemma centeredPolynomial_coeff_symmetry (v : Kˣ) (t j : ℕ) (hj : j≤t) : + (centeredPolynomial v t).coeff j=(centeredPolynomial v t).coeff (t-j) := by + have H:=congrArg (fun f : K[X]=>f.coeff j) (centeredPolynomial_reflect v t) + rw [coeff_reflect,revAt_le hj] at H + exact H.symm +end +end ElementaryPositivity.WallUnits + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RationalFiberReciprocal.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RationalFiberReciprocal.lean new file mode 100644 index 0000000000000000000000000000000000000000..3577b839ea7a8898c961c69655e2bc40c88d3df2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RationalFiberReciprocal.lean @@ -0,0 +1,71 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RationalFiberScale + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +open scoped LaurentSeries RatFunc +variable {K : Type*} [Field K] +lemma ratFunc_hom_ext_C_X {L : Type*} [Field L] (f g : RatFunc K →+* L) + (hc : ∀a : K,f (RatFunc.C a)=g (RatFunc.C a)) (hx : f RatFunc.X=g RatFunc.X) : f=g := by + apply ratFunc_hom_ext + intro p + induction p using Polynomial.induction_on' with + | add p q hp hq=>simp only [map_add,hp,hq] + | monomial n a=> + simp only [←Polynomial.C_mul_X_pow_eq_monomial,map_mul,map_pow,RatFunc.algebraMap_C,RatFunc.algebraMap_X,hc,hx] +lemma reciprocal_transcendental : Transcendental K ((RatFunc.X : RatFunc K)⁻¹) := by + intro h + exact RatFunc.transcendental_X (IsAlgebraic.inv_iff.mp h) +def reciprocalEval : Polynomial K →ₐ[K] RatFunc K := + Polynomial.aeval ((RatFunc.X : RatFunc K)⁻¹) +lemma reciprocalEval_injective : Function.Injective (reciprocalEval (K:=K)) := + transcendental_iff_injective.mp reciprocal_transcendental +lemma reciprocalEval_regular : + (nonZeroDivisors (Polynomial K)) ≤ (nonZeroDivisors (RatFunc K)).comap reciprocalEval := + nonZeroDivisors_le_comap_nonZeroDivisors_of_injective _ reciprocalEval_injective +def reciprocal : RatFunc K →+* RatFunc K := + RatFunc.liftRingHom reciprocalEval.toRingHom reciprocalEval_regular +@[simp] lemma reciprocal_polynomial (f : Polynomial K) : + reciprocal (algebraMap (Polynomial K) (RatFunc K) f)=reciprocalEval f := + RatFunc.liftRingHom_algebraMap _ _ _ +@[simp] lemma reciprocal_X : reciprocal RatFunc.X=(RatFunc.X : RatFunc K)⁻¹ := by + change reciprocal (algebraMap (Polynomial K) (RatFunc K) Polynomial.X)=_ + rw [reciprocal_polynomial] + simp [reciprocalEval] +@[simp] lemma reciprocal_constant (a : K) : reciprocal (RatFunc.C a)=RatFunc.C a := by + rw [←RatFunc.algebraMap_C,reciprocal_polynomial] + simp [reciprocalEval] +lemma reciprocal_involutive : (reciprocal (K:=K)).comp reciprocal=RingHom.id _ := by + apply ratFunc_hom_ext_C_X <;> simp +lemma reciprocal_scale (a : Kˣ) : + (reciprocal (K:=K)).comp (scale a)=(scale a⁻¹).comp reciprocal := by + apply ratFunc_hom_ext_C_X + · intro b; simp + · simp [mul_inv_rev,mul_comm] +def reciprocalEquiv : RatFunc K ≃+* RatFunc K := + RingEquiv.ofRingHom reciprocal reciprocal reciprocal_involutive reciprocal_involutive +def expandInfinity : RatFunc K →+* LaurentSeries K := expandZero.comp reciprocal +lemma expandInfinity_injective : Function.Injective (expandInfinity (K:=K)) := + (expandInfinity (K:=K)).injective +@[simp] lemma expandZero_X : expandZero (RatFunc.X : RatFunc K)=HahnSeries.single (1:ℤ) 1 := + RatFunc.coe_X +@[simp] lemma expandZero_constant (a : K) : expandZero (RatFunc.C a)=HahnSeries.C a := by + change algebraMap (RatFunc K) (LaurentSeries K) (RatFunc.C a)=_ + rw [←RatFunc.algebraMap_C,←IsScalarTower.algebraMap_apply (Polynomial K) (RatFunc K) (LaurentSeries K)] + simp +@[simp] lemma expandZero_X_zpow (n : ℤ) : + expandZero ((RatFunc.X : RatFunc K)^n)=HahnSeries.single n 1 := by + rw [map_zpow₀,expandZero_X,←RatFunc.single_zpow] +@[simp] lemma expandInfinity_X_zpow (n : ℤ) : + expandInfinity ((RatFunc.X : RatFunc K)^n)=HahnSeries.single (-n) 1 := by + change expandZero (reciprocal ((RatFunc.X : RatFunc K)^n))=_ + rw [map_zpow₀,reciprocal_X,inv_zpow,←zpow_neg,expandZero_X_zpow] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RationalFiberScale.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RationalFiberScale.lean new file mode 100644 index 0000000000000000000000000000000000000000..70e1b3e5adb1d1160d3d37125b35af9f65c5340b --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RationalFiberScale.lean @@ -0,0 +1,71 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +open Polynomial +noncomputable section +open scoped LaurentSeries RatFunc +variable {K : Type*} [Field K] +def polynomialScale (a : Kˣ) : K[X] ≃ₐ[K] K[X] := + Polynomial.algEquivOfCompEqX (C (a:K)*X) (C (↑(a⁻¹):K)*X) + (by simp [Polynomial.mul_comp,←mul_assoc,←map_mul]) + (by simp [Polynomial.mul_comp,←mul_assoc,←map_mul]) +@[simp] lemma polynomialScale_apply (a : Kˣ) (f : K[X]) : + polynomialScale a f=f.comp (C (a:K)*X) := by + simp [polynomialScale,Polynomial.comp_eq_aeval] +def scaleEval (a : Kˣ) : K[X] →+* RatFunc K := + (algebraMap K[X] (RatFunc K)).comp (polynomialScale a).toRingHom +lemma scaleEval_injective (a : Kˣ) : Function.Injective (scaleEval a) := + (RatFunc.algebraMap_injective (K:=K)).comp (polynomialScale a).injective +lemma scaleEval_regular (a : Kˣ) : + (nonZeroDivisors K[X]) ≤ (nonZeroDivisors (RatFunc K)).comap (scaleEval a) := + nonZeroDivisors_le_comap_nonZeroDivisors_of_injective _ (scaleEval_injective a) +def scale (a : Kˣ) : RatFunc K →+* RatFunc K := + RatFunc.liftRingHom (scaleEval a) (scaleEval_regular a) +@[simp] lemma scale_polynomial (a : Kˣ) (f : K[X]) : + scale a (algebraMap K[X] (RatFunc K) f)= + algebraMap K[X] (RatFunc K) (f.comp (C (a:K)*X)) := by + rw [scale,RatFunc.liftRingHom_algebraMap] + simp [scaleEval] +lemma ratFunc_hom_ext {L : Type*} [Field L] (f g : RatFunc K →+* L) + (hpoly : ∀p : K[X],f (algebraMap K[X] (RatFunc K) p)=g (algebraMap K[X] (RatFunc K) p)) : f=g := by + apply RingHom.ext + intro x + induction x using RatFunc.induction_on with + | f p q hq=>simp only [map_div₀,hpoly] +@[simp] lemma scale_one : scale (1:Kˣ)=RingHom.id (RatFunc K) := by + apply ratFunc_hom_ext + intro p + simp +lemma scale_mul (a b : Kˣ) : (scale a).comp (scale b)=scale (a*b) := by + apply ratFunc_hom_ext + intro p + simp only [RingHom.comp_apply,scale_polynomial] + congr 1 + rw [Polynomial.comp_assoc] + congr 1 + simp only [Polynomial.mul_comp,Polynomial.C_comp,Polynomial.X_comp,Units.val_mul] + rw [←mul_assoc,←map_mul,mul_comm (b:K) (a:K)] +@[simp] lemma scale_constant (a : Kˣ) (b : K) : + scale a (RatFunc.C b)=RatFunc.C b := by + change scale a (algebraMap K[X] (RatFunc K) (C b))=algebraMap K[X] (RatFunc K) (C b) + rw [scale_polynomial,Polynomial.C_comp] +@[simp] lemma scale_X (a : Kˣ) : scale a RatFunc.X=RatFunc.C (a:K)*RatFunc.X := by + change scale a (algebraMap K[X] (RatFunc K) X)=_ + rw [scale_polynomial,Polynomial.X_comp,map_mul] + rfl +def scaleEquiv (a : Kˣ) : RatFunc K ≃+* RatFunc K := + RingEquiv.ofRingHom (scale a) (scale a⁻¹) + (by rw [scale_mul,mul_inv_cancel,scale_one]) + (by rw [scale_mul,inv_mul_cancel,scale_one]) + +def expandZero : RatFunc K →+* LaurentSeries K := algebraMap _ _ +lemma expandZero_injective : Function.Injective (expandZero (K:=K)) := (expandZero (K:=K)).injective +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RationalIntervalModel.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RationalIntervalModel.lean new file mode 100644 index 0000000000000000000000000000000000000000..372cb9ccfdbcd8d6b37a807514ca65031fcc4f73 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RationalIntervalModel.lean @@ -0,0 +1,95 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +open scoped BigOperators + +lemma rational_finite_between (s t:Finset ℚ) (h:∀a∈s,∀b∈t,a < b) : + ∃x:ℚ,(∀a∈s,a < x) ∧ ∀b∈t,x < b := by + classical + by_cases hs:s.Nonempty + · let a:=s.max' hs + by_cases ht:t.Nonempty + · let b:=t.min' ht + obtain ⟨x,hax,hxb⟩:=exists_between (h a (s.max'_mem hs) b (t.min'_mem ht)) + exact ⟨x,fun c hc=>(s.le_max' c hc).trans_lt hax,fun c hc=>hxb.trans_le (t.min'_le c hc)⟩ + · refine ⟨a+1,fun c hc=>(s.le_max' c hc).trans_lt (lt_add_one a),?_⟩ + simp [Finset.not_nonempty_iff_eq_empty.mp ht] + · by_cases ht:t.Nonempty + · let b:=t.min' ht + refine ⟨b-1,?_,fun c hc=>(sub_one_lt b).trans_le (t.min'_le c hc)⟩ + simp [Finset.not_nonempty_iff_eq_empty.mp hs] + · exact ⟨0,by simp [Finset.not_nonempty_iff_eq_empty.mp hs],by simp [Finset.not_nonempty_iff_eq_empty.mp ht]⟩ + +lemma rational_interval_prefix (h:ℕ → ℕ) (hh:Monotone h) (m:ℕ) : + ∃t:ℕ → ℚ,(∀i < m,0 < t i) ∧ + ∀i j,i < j → j < m → t i < t j ∧ + (j≤h i → t j < t i+1) ∧ (h i < j → t i+1 < t j) := by + classical + induction m with + | zero=>exact ⟨fun _=>1,by simp,by omega⟩ + | succ m ih=> + obtain ⟨t,ht,he⟩:=ih + let lower:Finset ℚ:={0} ∪ (Finset.range m).image t ∪ + ((Finset.range m).filter (fun i=>h i < m)).image (fun i=>t i+1) + let upper:Finset ℚ:=((Finset.range m).filter (fun i=>m≤h i)).image (fun i=>t i+1) + have hcross:∀a∈lower,∀b∈upper,a < b:=by + intro a ha b hb + obtain ⟨j,hj,rfl⟩:=Finset.mem_image.mp hb + obtain ⟨hjm,hjh⟩:=Finset.mem_filter.mp hj + have hjm':j < m:=Finset.mem_range.mp hjm + rcases Finset.mem_union.mp ha with ha|ha + · rcases Finset.mem_union.mp ha with ha|ha + · have ha:a=0:=Finset.mem_singleton.mp ha + rw [ha] + linarith [ht j hjm'] + · obtain ⟨i,hi,rfl⟩:=Finset.mem_image.mp ha + have him:i < m:=Finset.mem_range.mp hi + rcases lt_trichotomy i j with hij|rfl|hji + · linarith [(he i j hij hjm').1] + · exact lt_add_one _ + · exact (he j i hji him).2.1 (le_trans (Nat.le_of_lt him) hjh) + · obtain ⟨i,hi,rfl⟩:=Finset.mem_image.mp ha + obtain ⟨him,hih⟩:=Finset.mem_filter.mp hi + have hij:i < j:=by + by_contra hn + have H:=hh (Nat.le_of_not_gt hn) + omega + linarith [(he i j hij hjm').1] + obtain ⟨x,hxL,hxU⟩:=rational_finite_between lower upper hcross + have hx0:0 < x:=hxL 0 (by simp [lower]) + have hxt:∀i < m,t i < x:=by + intro i hi + apply hxL + simp only [lower,Finset.mem_union] + exact Or.inl (Or.inr (Finset.mem_image.mpr ⟨i,Finset.mem_range.mpr hi,rfl⟩)) + have hxadj:∀i < m,m≤h i → x < t i+1:=by + intro i hi hh + apply hxU + exact Finset.mem_image.mpr ⟨i,Finset.mem_filter.mpr ⟨Finset.mem_range.mpr hi,hh⟩,rfl⟩ + have hxnon:∀i < m,h i < m → t i+1 < x:=by + intro i hi hh + apply hxL + exact Finset.mem_union.mpr (Or.inr (Finset.mem_image.mpr ⟨i,Finset.mem_filter.mpr ⟨Finset.mem_range.mpr hi,hh⟩,rfl⟩)) + refine ⟨Function.update t m x,?_,?_⟩ + · intro i hi + by_cases him:i=m + · simpa [him] using hx0 + · rw [Function.update_of_ne him] + exact ht i (by omega) + · intro i j hij hj + have him:i≠m:=by omega + rw [Function.update_of_ne him] + by_cases hjm:j=m + · subst j + rw [Function.update_self] + exact ⟨hxt i hij,hxadj i hij,hxnon i hij⟩ + · rw [Function.update_of_ne hjm] + exact he i j hij (by omega) +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RationalPureCocycle.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RationalPureCocycle.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f3167accbc77291bdca364c675061b07acaf7dc --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RationalPureCocycle.lean @@ -0,0 +1,159 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.WallUnits +import OAI.Combinatorics.Chromatic.Walls.RationalFiberReciprocal + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +variable {K : Type*} [Field K] + +def scaleAction (v : Kˣ) : Multiplicative ℤ →* MulAut (RatFunc K)ˣ where + toFun t:=Units.mapEquiv (scaleEquiv (v^(-2*t.toAdd))).toMulEquiv + map_one':=by + ext x + change scale (v^(-2*(0:ℤ))) (x:RatFunc K)=(x:RatFunc K) + simp + map_mul' t u:=by + ext x + change scale (v^(-2*(t.toAdd+u.toAdd))) (x:RatFunc K)= + scale (v^(-2*t.toAdd)) (scale (v^(-2*u.toAdd)) (x:RatFunc K)) + rw [show v^(-2*(t.toAdd+u.toAdd))=v^(-2*t.toAdd)*v^(-2*u.toAdd) by rw [mul_add,zpow_add],←scale_mul] + rfl +@[simp] lemma scaleAction_val (v : Kˣ) (t : Multiplicative ℤ) (a : (RatFunc K)ˣ) : + ((scaleAction v t a : (RatFunc K)ˣ):RatFunc K)=scale (v^(-2*t.toAdd)) (a:RatFunc K) := rfl +lemma linearFactor_ne_zero (a : K) : (1+RatFunc.C a*RatFunc.X : RatFunc K)≠0 := by + have he : (1+RatFunc.C a*RatFunc.X : RatFunc K)= + algebraMap (Polynomial K) (RatFunc K) (1+Polynomial.C a*Polynomial.X) := by simp + rw [he] + intro hz + have h : (1+Polynomial.C a*Polynomial.X : Polynomial K)=0 := + (RatFunc.algebraMap_injective (K:=K)) (by simpa using hz) + have H:=congrArg (Polynomial.coeff · 0) h + simp at H + +def pureStep (v : Kˣ) : (RatFunc K)ˣ := Units.mk0 _ (linearFactor_ne_zero (↑(v⁻¹):K)) +abbrev PureExtension (v : Kˣ) := (RatFunc K)ˣ ⋊[scaleAction v] Multiplicative ℤ +def pureGenerator (v : Kˣ) : PureExtension v := ⟨pureStep v,Multiplicative.ofAdd 1⟩ +def pureRatio (v : Kˣ) (t : ℤ) : (RatFunc K)ˣ := (pureGenerator v^t).left +lemma pureRight (v : Kˣ) (t : ℤ) : (pureGenerator v^t).right=Multiplicative.ofAdd t := by + change SemidirectProduct.rightHom (pureGenerator v^t)=_ + rw [map_zpow] + change (Multiplicative.ofAdd 1)^t=Multiplicative.ofAdd t + rw [←ofAdd_zsmul,smul_eq_mul,mul_one] +@[simp] lemma pureRatio_zero (v : Kˣ) : pureRatio v 0=1 := by simp [pureRatio] +@[simp] lemma pureRatio_one (v : Kˣ) : pureRatio v 1=pureStep v := by simp [pureRatio,pureGenerator] +lemma pureRatio_add (v : Kˣ) (t u : ℤ) : + pureRatio v (t+u)=pureRatio v t*scaleAction v (Multiplicative.ofAdd t) (pureRatio v u) := by + simp only [pureRatio,zpow_add,SemidirectProduct.mul_left,pureRight] +lemma pureRatio_nat (v : Kˣ) (n : ℕ) : + pureRatio v (n:ℤ)=∏i∈Finset.range n,scaleAction v (Multiplicative.ofAdd (i:ℤ)) (pureStep v) := by + induction n with + | zero=>simp + | succ n ih=>rw [Nat.cast_add,Nat.cast_one,pureRatio_add,pureRatio_one,ih,Finset.prod_range_succ] +lemma pureRatio_nat_val (v : Kˣ) (n : ℕ) : + (pureRatio v (n:ℤ):RatFunc K)= + ∏i∈Finset.range n,(1+RatFunc.C (↑(v^(-2*(i:ℤ)-1)):K)*RatFunc.X) := by + rw [pureRatio_nat,Units.coe_prod] + apply Finset.prod_congr rfl + intro i hi + rw [scaleAction_val] + change scale (v^(-2*(i:ℤ))) (1+RatFunc.C (↑(v⁻¹):K)*RatFunc.X)=_ + rw [map_add,map_one,map_mul,scale_constant,scale_X,←mul_assoc,←map_mul, + ←Units.val_mul,←zpow_neg_one,←zpow_add] + congr 3 + ring_nf +lemma pureRatio_neg (v : Kˣ) (t : ℤ) : + scaleAction v (Multiplicative.ofAdd t) (pureRatio v (-t))=(pureRatio v t)⁻¹ := by + apply mul_left_cancel (a:=pureRatio v t) + rw [←pureRatio_add,add_neg_cancel,pureRatio_zero,mul_inv_cancel] +end +end ElementaryPositivity.RationalFiber + +end +section +namespace ElementaryPositivity.RationalFiber +open WallUnits PowerSeries +noncomputable section +variable {K : Type*} [Field K] +variable (v : Kˣ) +def shiftedElementary (t : ℤ) : PowerSeries K := + rescale (↑(v^(-2*t)):K) (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K)) +lemma shiftedElementary_zero : shiftedElementary v 0= + elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K) := by + simp [shiftedElementary] +lemma shiftedElementary_constant (t : ℤ) : constantCoeff (shiftedElementary v t)=1 := by + rw [shiftedElementary,←coeff_zero_eq_constantCoeff,coeff_rescale] + simp [elementaryCoeff] +lemma shiftedElementary_step + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) (t : ℤ) : + shiftedElementary v t=(1+C (↑(v^(-2*t-1)):K)*X)*shiftedElementary v (t+1) := by + conv_lhs => rw [shiftedElementary,elementary_tail _ _ hq] + rw [_root_.map_mul,_root_.map_add,_root_.map_one,_root_.map_mul,rescale_C,rescale_X,rescale_rescale] + rw [←mul_assoc,←(PowerSeries.C (R:=K)).map_mul,←Units.val_mul,←zpow_neg_one,←zpow_add] + have H1 : -1+(-2*t)= -2*t-1:=by ring + rw [H1] + unfold shiftedElementary + simp only [zpow_neg_one] + congr 2 + rw [←Units.val_mul,←zpow_add] + congr 2 + ring_nf +lemma expandedPure_step (t : ℤ) : + expandZero (pureRatio v (t+1):RatFunc K)= + expandZero (pureRatio v t:RatFunc K)* + HahnSeries.ofPowerSeries ℤ K (1+C (↑(v^(-2*t-1)):K)*X) := by + rw [pureRatio_add,Units.val_mul,pureRatio_one,scaleAction_val] + change expandZero ((pureRatio v t:RatFunc K)* + scale (v^(-2*t)) (1+RatFunc.C (↑(v⁻¹):K)*RatFunc.X))=_ + rw [_root_.map_add,_root_.map_one,_root_.map_mul,_root_.map_mul,scale_constant,scale_X, + ←mul_assoc,←RatFunc.C.map_mul,←Units.val_mul,←zpow_neg_one,←zpow_add] + rw [show -1+(-2*t)= -2*t-1 by ring] + simp only [_root_.map_mul,_root_.map_add,_root_.map_one,expandZero_constant, + expandZero_X,HahnSeries.ofPowerSeries_C,HahnSeries.ofPowerSeries_X] +lemma expandedPure_times_shift + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) (t : ℤ) : + expandZero (pureRatio v t:RatFunc K)* + HahnSeries.ofPowerSeries ℤ K (shiftedElementary v t)= + HahnSeries.ofPowerSeries ℤ K (shiftedElementary v 0) := by + induction t using Int.induction_on with + | zero=>simp + | succ t ih=> + rw [expandedPure_step,mul_assoc,←_root_.map_mul,←shiftedElementary_step v hq] + exact ih + | pred t ih=> + rw [shiftedElementary_step v hq (-↑t-1)] + have H : (-↑t-1)+(1:ℤ)= -↑t:=by ring + rw [H,_root_.map_mul,←mul_assoc,←expandedPure_step,H] + exact ih +lemma ofPowerSeries_inv_constant_one (f : PowerSeries K) (hf : constantCoeff f=1) : + HahnSeries.ofPowerSeries ℤ K f⁻¹=(HahnSeries.ofPowerSeries ℤ K f)⁻¹ := by + apply eq_inv_of_mul_eq_one_left + rw [←_root_.map_mul,PowerSeries.inv_mul_cancel f (by rw [hf]; exact one_ne_zero),_root_.map_one] +lemma expandedPure_ratio + (hq : ∀n : ℕ,1-(↑(v^(-2:ℤ)):K)^(n+1)≠0) (t : ℤ) : + expandZero (pureRatio v t:RatFunc K)=HahnSeries.ofPowerSeries ℤ K + (elementary (↑(v^(-2:ℤ)):K) (↑(v⁻¹):K)*(shiftedElementary v t)⁻¹) := by + have H:=expandedPure_times_shift v hq t + have H0 : HahnSeries.ofPowerSeries ℤ K (shiftedElementary v t)≠0 := by + intro h + have he:shiftedElementary v t=0:=HahnSeries.ofPowerSeries_injective (Γ:=ℤ) + (by simpa only [_root_.map_zero] using h) + have hc:=congrArg constantCoeff he + rw [shiftedElementary_constant,_root_.map_zero] at hc + exact one_ne_zero hc + rw [shiftedElementary_zero] at H + rw [_root_.map_mul,ofPowerSeries_inv_constant_one _ (shiftedElementary_constant v t)] + calc + _ = (expandZero (pureRatio v t:RatFunc K)* + HahnSeries.ofPowerSeries ℤ K (shiftedElementary v t))* + (HahnSeries.ofPowerSeries ℤ K (shiftedElementary v t))⁻¹ := by + rw [mul_assoc,mul_inv_cancel₀ H0,mul_one] + _ = _ := by rw [H] +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RationalReadExt.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RationalReadExt.lean new file mode 100644 index 0000000000000000000000000000000000000000..9bc27080962b3b40cd65ba60b8f732bc6c04b735 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RationalReadExt.lean @@ -0,0 +1,40 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.RationalTorusFaithful + +namespace OAI + +section +namespace ElementaryPositivity.RationalFiber +noncomputable section +variable {K M : Type*} [Field K] [AddCommGroup M] +variable (v : Kˣ) (Ω : M →+ M →+ ℤ) +variable (k : M →+ ℤ) (p : M) (hp : k p=1) +lemma readFiber_ext {f g : FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω)} + (h : ∀m,readFiber v Ω k p hp m f=readFiber v Ω k p hp m g) : f=g := by + apply Finsupp.ext + intro l + apply expandZero_injective + apply HahnSeries.ext + funext n + have H:=h (n • p+(l:M)) + change (expandZero (f (off k p hp (n • p+(l:M))))).coeff (k (n • p+(l:M)))* + (↑(v^(k (n • p+(l:M))*complementAlpha k p Ω (off k p hp (n • p+(l:M))))):K)= + (expandZero (g (off k p hp (n • p+(l:M))))).coeff (k (n • p+(l:M)))* + (↑(v^(k (n • p+(l:M))*complementAlpha k p Ω (off k p hp (n • p+(l:M))))):K) at H + have hl : k (l:M)=0:=l.property + simp only [map_add,map_zsmul,off_p,smul_zero,off_complement,zero_add,hp, + smul_eq_mul,mul_one,hl,add_zero] at H + exact mul_right_cancel₀ (Units.ne_zero _) H +lemma completed_readFiber_ext + {f g : PowerSeries (FiberTorus v (complementOmega k Ω) (complementAlpha k p Ω))} + (h : ∀d m,readFiber v Ω k p hp m (PowerSeries.coeff d f)= + readFiber v Ω k p hp m (PowerSeries.coeff d g)) : f=g := by + apply PowerSeries.ext + intro d + exact readFiber_ext v Ω k p hp (h d) +end +end ElementaryPositivity.RationalFiber + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RationalTensorDetection.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RationalTensorDetection.lean new file mode 100644 index 0000000000000000000000000000000000000000..c871da26620355d3c8852021a0d58be6c8784802 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RationalTensorDetection.lean @@ -0,0 +1,335 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.LinearDetection +open scoped TensorProduct +universe u v w u' v' i j +variable {K : Type u} [Field K] +variable {M : Type v} {N : Type w} [AddCommGroup M] [AddCommGroup N] +variable [Module K M] [Module K N] + +lemma basisLeft_natural {N' : Type w} [AddCommGroup N'] [Module K N'] + {ι : Type i} [DecidableEq ι] (b : Module.Basis ι K M) (g : N →ₗ[K] N') + (x : M ⊗[K] N) (k : ι) : + TensorProduct.equivFinsuppOfBasisLeft b (TensorProduct.map LinearMap.id g x) k = + g (TensorProduct.equivFinsuppOfBasisLeft b x k) := by + induction x using TensorProduct.inductionOn with + | tmul m n => simp [TensorProduct.equivFinsuppOfBasisLeft_apply_tmul] + | add x y hx hy => simp only [map_add,Finsupp.add_apply,hx,hy] + +lemma basisRight_natural {M' : Type v} [AddCommGroup M'] [Module K M'] + {ι : Type i} [DecidableEq ι] (b : Module.Basis ι K N) (f : M →ₗ[K] M') + (x : M ⊗[K] N) (k : ι) : + TensorProduct.equivFinsuppOfBasisRight b (TensorProduct.map f LinearMap.id x) k = + f (TensorProduct.equivFinsuppOfBasisRight b x k) := by + induction x using TensorProduct.inductionOn with + | tmul m n => simp [TensorProduct.equivFinsuppOfBasisRight_apply_tmul] + | add x y hx hy => simp only [map_add,Finsupp.add_apply,hx,hy] + +theorem tensor_right_detect {ι : Type i} {N' : ι → Type w} + [∀ i, AddCommGroup (N' i)] [∀ i, Module K (N' i)] + (g : ∀ i, N →ₗ[K] N' i) + (hg : ∀ y, (∀ i, g i y=0) → y=0) (x : M ⊗[K] N) + (hx : ∀ i, TensorProduct.map LinearMap.id (g i) x=0) : x=0 := by + classical + let b := Module.Free.chooseBasis K M + apply (TensorProduct.equivFinsuppOfBasisLeft b).injective + rw [map_zero] + ext k + apply hg + intro i + rw [← basisLeft_natural b (g i),hx i,map_zero,Finsupp.zero_apply] + +theorem tensor_left_detect {ι : Type i} {M' : ι → Type v} + [∀ i, AddCommGroup (M' i)] [∀ i, Module K (M' i)] + (f : ∀ i, M →ₗ[K] M' i) + (hf : ∀ x, (∀ i, f i x=0) → x=0) (x : M ⊗[K] N) + (hx : ∀ i, TensorProduct.map (f i) LinearMap.id x=0) : x=0 := by + classical + let b := Module.Free.chooseBasis K N + apply (TensorProduct.equivFinsuppOfBasisRight b).injective + rw [map_zero] + ext k + apply hf + intro i + rw [← basisRight_natural b (f i),hx i,map_zero,Finsupp.zero_apply] + +theorem tensor_detect {ι : Type i} {κ : Type j} {M' : ι → Type v} {N' : κ → Type w} + [∀ i, AddCommGroup (M' i)] [∀ i, Module K (M' i)] + [∀ j, AddCommGroup (N' j)] [∀ j, Module K (N' j)] + (f : ∀ i, M →ₗ[K] M' i) (g : ∀ j, N →ₗ[K] N' j) + (hf : ∀ x, (∀ i, f i x=0) → x=0) + (hg : ∀ y, (∀ j, g j y=0) → y=0) + (x : M ⊗[K] N) (hx : ∀ i j, TensorProduct.map (f i) (g j) x=0) : x=0 := by + apply tensor_left_detect f hf x + intro i + apply tensor_right_detect g hg (TensorProduct.map (f i) LinearMap.id x) + intro j + have hcomp : (TensorProduct.map LinearMap.id (g j)).comp + (TensorProduct.map (f i) (LinearMap.id : N →ₗ[K] N)) = + TensorProduct.map (f i) (g j) := by + ext m n + simp + change ((TensorProduct.map LinearMap.id (g j)).comp + (TensorProduct.map (f i) (LinearMap.id : N →ₗ[K] N))) x=0 + rw [hcomp,hx i j] + +theorem tensor_map_zero_of_test_kernels + {ι : Type i} {κ : Type j} {M' : ι → Type v} {N' : κ → Type w} + [∀ i, AddCommGroup (M' i)] [∀ i, Module K (M' i)] + [∀ j, AddCommGroup (N' j)] [∀ j, Module K (N' j)] + (t : ∀ i, M →ₗ[K] M' i) (s : ∀ j, N →ₗ[K] N' j) + (f : M →ₗ[K] M) (g : N →ₗ[K] N) + (hf : (⨅ i, LinearMap.ker (t i)) ≤ LinearMap.ker f) + (hg : (⨅ j, LinearMap.ker (s j)) ≤ LinearMap.ker g) + (x : M ⊗[K] N) (hx : ∀ i j, TensorProduct.map (t i) (s j) x=0) : + TensorProduct.map f g x=0 := by + let P : Submodule K M := ⨅ i, LinearMap.ker (t i) + let Q : Submodule K N := ⨅ j, LinearMap.ker (s j) + let t' := fun i => P.liftQ (t i) (iInf_le _ i) + let s' := fun j => Q.liftQ (s j) (iInf_le _ j) + have ht : ∀ y, (∀ i, t' i y=0) → y=0 := by + intro y hy + induction y using Submodule.Quotient.induction_on with + | H y => + apply (Submodule.Quotient.mk_eq_zero P).mpr + simpa only [P,t',Submodule.mem_iInf,LinearMap.mem_ker,Submodule.liftQ_apply] using hy + have hs : ∀ y, (∀ j, s' j y=0) → y=0 := by + intro y hy + induction y using Submodule.Quotient.induction_on with + | H y => + apply (Submodule.Quotient.mk_eq_zero Q).mpr + simpa only [Q,s',Submodule.mem_iInf,LinearMap.mem_ker,Submodule.liftQ_apply] using hy + have hquot : TensorProduct.map P.mkQ Q.mkQ x=0 := by + apply tensor_detect t' s' ht hs + intro i j + have hc : (TensorProduct.map (t' i) (s' j)).comp + (TensorProduct.map P.mkQ Q.mkQ) = TensorProduct.map (t i) (s j) := by + ext m n + simp [t',s'] + change ((TensorProduct.map (t' i) (s' j)).comp + (TensorProduct.map P.mkQ Q.mkQ)) x=0 + rw [hc,hx i j] + have hc : (TensorProduct.map (P.liftQ f hf) (Q.liftQ g hg)).comp + (TensorProduct.map P.mkQ Q.mkQ) = TensorProduct.map f g := by + ext m n + simp + rw [← hc,LinearMap.comp_apply,hquot,map_zero] + +end ElementaryPositivity.LinearDetection + +end +section +namespace ElementaryPositivity.LinearDetection +open scoped TensorProduct +universe u v w i j +variable {K : Type u} [Field K] +variable {M : Type v} [AddCommGroup M] [Module K M] +variable {N : Type w} [AddCommGroup N] [Module K N] + +noncomputable def retract (P : Submodule K M) : M →ₗ[K] M := + P.projection (Classical.choose P.exists_isCompl) (Classical.choose_spec P.exists_isCompl) + +lemma retract_mem (P : Submodule K M) (x : M) : retract P x∈P := + P.projection_apply_mem _ x + +lemma retract_eq_self (P : Submodule K M) {x : M} (hx : x∈P) : retract P x=x := + P.projection_apply_of_mem_left _ hx + +lemma retract_top : retract (⊤ : Submodule K M)=LinearMap.id := by + ext x + exact retract_eq_self _ trivial + +noncomputable def filtrationPiece (F : ℕ → Submodule K M) (n : ℕ) (i : Fin (n+1)) : + M →ₗ[K] M := + if i.valretract (F k)-retract (F (k+1))) i.val) = _ + exact (Fin.sum_univ_eq_sum_range (fun k=>retract (F k)-retract (F (k+1))) n).trans + (Finset.sum_range_sub' (fun i=>retract (F i)) n) + rw [hs] + simp only [filtrationPiece,Fin.val_last,lt_self_iff_false,ite_false,sub_add_cancel,hF,retract_top] + +lemma tensor_map_sum_left {α : Type*} (s : Finset α) (f : α → M →ₗ[K] M) + (g : N →ₗ[K] N) : + TensorProduct.map (∑ i∈s,f i) g = ∑ i∈s,TensorProduct.map (f i) g := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi hs => simp [hi,TensorProduct.map_add_left,hs] + +lemma tensor_map_sum_right {α : Type*} (s : Finset α) (f : M →ₗ[K] M) + (g : α → N →ₗ[K] N) : + TensorProduct.map f (∑ i∈s,g i) = ∑ i∈s,TensorProduct.map f (g i) := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert i s hi hs => simp [hi,TensorProduct.map_add_right,hs] + +lemma tensor_sum_pieces (F : ℕ → Submodule K M) (G : ℕ → Submodule K N) + (hF : F 0=⊤) (hG : G 0=⊤) (n : ℕ) (x : M ⊗[K] N) : + ∑ i : Fin (n+1), ∑ j : Fin (n+1), + TensorProduct.map (filtrationPiece F n i) (filtrationPiece G n j) x = x := by + have he : (∑ i : Fin (n+1),∑ j : Fin (n+1), + TensorProduct.map (filtrationPiece F n i) (filtrationPiece G n j))= + TensorProduct.map LinearMap.id LinearMap.id := by + rw [← filtrationPiece_sum F hF n,← filtrationPiece_sum G hG n] + rw [tensor_map_sum_left] + apply Finset.sum_congr rfl + intro i hi + rw [tensor_map_sum_right] + simpa only [LinearMap.sum_apply,TensorProduct.map_id,LinearMap.id_apply] using LinearMap.congr_fun he x + +noncomputable def testFiltration {ι : Type i} {D : ι → Type v} + [∀ i,AddCommGroup (D i)] [∀ i,Module K (D i)] + (t : ∀ i,M →ₗ[K] D i) (wt : ι → ℤ) (W : ℤ) : Submodule K M := + ⨅ i, ⨅ (_ : wt ihx i (lt_of_lt_of_le hi huv) + +noncomputable def additiveTensorFiltration (F : ℤ → Submodule K M) + (G : ℤ → Submodule K N) (W : ℤ) : Submodule K (M ⊗[K] N) := + Submodule.span K {z | ∃ u v x y, W≤u+v ∧ x∈F u ∧ y∈G v ∧ z=x⊗ₜ[K]y} + +lemma tmul_mem_additiveTensorFiltration (F : ℤ → Submodule K M) + (G : ℤ → Submodule K N) {W u v : ℤ} (h : W≤u+v) + {x : M} {y : N} (hx : x∈F u) (hy : y∈G v) : + x⊗ₜ[K]y ∈ additiveTensorFiltration F G W := + Submodule.subset_span ⟨u,v,x,y,h,hx,hy,rfl⟩ + +lemma map_mem_additiveTensorFiltration (F : ℤ → Submodule K M) + (G : ℤ → Submodule K N) {W u v : ℤ} (h : W≤u+v) + (f : M →ₗ[K] M) (g : N →ₗ[K] N) + (hf : ∀ x,f x∈F u) (hg : ∀ y,g y∈G v) (z : M⊗[K]N) : + TensorProduct.map f g z ∈ additiveTensorFiltration F G W := by + induction z using TensorProduct.inductionOn with + | tmul x y => exact tmul_mem_additiveTensorFiltration F G h (hf x) (hg y) + | add x y hx hy => + rw [map_add] + exact (additiveTensorFiltration F G W).add_mem hx hy + +theorem additiveTensorFiltration_iff_tests + {ι : Type i} {κ : Type j} {D : ι → Type v} {E : κ → Type w} + [∀ i,AddCommGroup (D i)] [∀ i,Module K (D i)] + [∀ j,AddCommGroup (E j)] [∀ j,Module K (E j)] + (t : ∀ i,M →ₗ[K] D i) (s : ∀ j,N →ₗ[K] E j) + (wt : ι → ℤ) (ws : κ → ℤ) (L R : ℤ) + (hL : testFiltration t wt L=⊤) (hR : testFiltration s ws R=⊤) + (W : ℤ) (z : M⊗[K]N) : + z∈additiveTensorFiltration (testFiltration t wt) (testFiltration s ws) W ↔ + ∀ i j, wt i+ws jtestFiltration t wt (L+i) + let G : ℕ → Submodule K N := fun j=>testFiltration s ws (R+j) + have hF : Antitone F := by + intro i j hij + exact testFiltration_antitone t wt (by omega) + have hG : Antitone G := by + intro i j hij + exact testFiltration_antitone s ws (by omega) + have hF0 : F 0=⊤ := by simpa only [F,Nat.cast_zero,add_zero] using hL + have hG0 : G 0=⊤ := by simpa only [G,Nat.cast_zero,add_zero] using hR + rw [← tensor_sum_pieces F G hF0 hG0 n z] + apply Submodule.sum_mem + intro i hi + apply Submodule.sum_mem + intro j hj + by_cases hij : i.val+j.valt a.val) + (fun b : {b // ws bs b.val) + _ _ hiKer hjKer + intro a b + apply hz + have ha := a.property + have hb := b.property + omega + rw [he] + exact Submodule.zero_mem _ + · apply map_mem_additiveTensorFiltration (testFiltration t wt) (testFiltration s ws) + (u:=L+i.val) (v:=R+j.val) (by omega) + (filtrationPiece F n i) (filtrationPiece G n j) + · exact filtrationPiece_mem F hF n i + · exact filtrationPiece_mem G hG n j + +end ElementaryPositivity.LinearDetection + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RayIncomingIdentification.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RayIncomingIdentification.lean new file mode 100644 index 0000000000000000000000000000000000000000..f922e0701500902e751d420f6fbd1b8dc3161c4a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RayIncomingIdentification.lean @@ -0,0 +1,154 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.IncomingDisplacement +import OAI.Combinatorics.Chromatic.Walls.PlanarRayOrder + +namespace OAI + +section +namespace ElementaryPositivity.FormalLog +open PowerSeries +noncomputable section +variable {A : Type*} [Ring A] [Module ℚ A] +lemma log_injective_through (F G : PowerSeries A) (N : ℕ) + (hF : constantCoeff F=1) (hG : constantCoeff G=1) + (h : ∀n≤N,coeff n (log F)=coeff n (log G)) : + ∀n≤N,coeff n F=coeff n G := by + intro n hn + induction n using Nat.strong_induction_on with + | h n ih => + cases n with + | zero => simp only [coeff_zero_eq_constantCoeff,hF,hG] + | succ n => + have H:=log_leading_difference F G n hF hG + (fun j hj=>ih j (by omega) (by omega)) + rw [h (n+1) hn,sub_self] at H + exact sub_eq_zero.mp H.symm +lemma log_injective (F G : PowerSeries A) (hF : constantCoeff F=1) + (hG : constantCoeff G=1) (h : log F=log G) : F=G := by + ext n + exact log_injective_through F G n hF hG (fun j _=>congrArg (coeff j) h) n le_rfl +end +end ElementaryPositivity.FormalLog + +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M I : Type*} [CommRing R] [Algebra ℚ R] [AddCommGroup M] [Fintype I] +variable (v : Rˣ) (Ω : M→+M→+ℤ) (C : (I→ℤ)→+M) + +def OnPositiveRay (r m : M) : Prop := ∃a b : ℕ,0 intro h <;> nlinarith + constructor <;> constructor <;> intro h <;> nlinarith + +lemma OnPositiveRay.incomingSigns {r m : M} (hm : OnPositiveRay r m) (x : M) : + (0 < incomingCovector Ω r x↔0 < incomingCovector Ω m x) ∧ + (incomingCovector Ω r x=0↔incomingCovector Ω m x=0) ∧ + (incomingCovector Ω r x<0↔incomingCovector Ω m x<0) := by + let h : M→+ℝ := (Int.castAddHom ℝ).comp (Ω x) + have H:=hm.eval h + exact ⟨H.1.symm,H.2.1.symm,H.2.2.symm⟩ + +omit [Algebra ℚ R] in +lemma chart_sign_congr (h k : M→+ℝ) (F : CompletedPositive v Ω C) + (H : ∀m,(0(H m).1.mp (hs.1 n m hm)) + (fun n m hm=>(H m).2.1.mp (hs.2.1 n m hm)) + (fun n m hm=>(H m).2.2.mp (hs.2.2 n m hm)) + +omit [Algebra ℚ R] in +lemma incoming_same_ray {r m : M} (hm : OnPositiveRay r m) (F : CompletedPositive v Ω C) : + chartZero v Ω C (incomingCovector Ω r) F=chartZero v Ω C (incomingCovector Ω m) F := + (chart_sign_congr v Ω C _ _ F (hm.incomingSigns Ω)).2.1 + +theorem incoming_ray_log (hΩ : ∀m,Ω m m=0) (r : M) (k : M→+ℝ) (hk : k r=0) + (F : CompletedPositive v Ω C) (m : M) (hm : OnPositiveRay r m) (n : ℕ) : + coeff n (FormalLog.log (chartZero v Ω C k + (chartZero v Ω C (incomingCovector Ω r) F)).val) m= + coeff n (FormalLog.log (chartZero v Ω C (incomingCovector Ω m) F).val) m := by + rw [incoming_same_ray v Ω C hm F] + exact incoming_displacement_log v Ω C hΩ m k ((hm.eval k).2.1.mpr hk) F n + +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (e : M→+E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (L : Module.Dual ℝ E) (r s : E) + +include he hB in +lemma positive_ray_of_pairing_zero (C : (I→ℤ)→+M) + (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) + (hrs : B r s≠0) (m p : M) (n d : ℕ) (hn : 0 0 PlanarRayOrder.slope B L r (e m) + let T:=S.image slope + have hchoose (a : ℝ) (ha : a∈T) : ∃m∈S,slope m=a:=Finset.mem_image.mp ha + let c (a : ℝ) : M:=if ha : a∈T then Classical.choose (hchoose a ha) else 0 + have hc : ∀a∈T,c a∈S ∧ slope (c a)=a:=by + intro a ha + dsimp [c] + rw [dite_eq_left ha] + exact Classical.choose_spec (hchoose a ha) + let ts:=T.sort (· ≥ ·) + have hts : ts.Pairwise (fun a b => b (Finset.mem_sort _).mp ha + refine ⟨ts.map c,?_,?_,?_⟩ + · intro p hp + obtain ⟨a,ha,rfl⟩:=List.mem_map.mp hp + exact (hc a (hmem a ha)).1 + · rw [List.pairwise_map] + apply hts.imp_of_mem + intro a b ha hb hab + have hca:=hc a (hmem a ha) + have hcb:=hc b (hmem b hb) + apply (PlanarRayOrder.pairing_pos_iff B hB L r s (e (c a)) (e (c b)) hr + (hS _ hca.1).1 (hS _ hcb.1).1 (hS _ hca.1).2 (hS _ hcb.1).2).mpr + change slope (c b) exact map_one φ + | succ n ih => simp only [elementaryCoeff,map_mul,map_div₀,map_sub,map_one,map_pow,ih] + +lemma map_elementary {K L : Type*} [Field K] [Field L] (φ : K →+* L) (q u : K) : + PowerSeries.map φ (elementary q u)=elementary (φ q) (φ u) := by + ext n + rw [coeff_map,coeff_elementary,coeff_elementary,map_elementaryCoeff] + +lemma elementary_atInfinity (k : ℤ) : + PowerSeries.map atInfinity (elementary RationalRay.q (RationalRay.v^k))= + elementary (HahnSeries.single (2:ℤ) (1:ℚ)) (HahnSeries.single (-k) (1:ℚ)) := by + rw [map_elementary] + change elementary (atInfinity RationalRay.q) (atInfinity (RationalRay.v^k))=_ + rw [atInfinity_q,atInfinity_v_pow] +lemma map_complete {K L : Type*} [Field K] [Field L] (φ : K →+* L) (q u : K) : + PowerSeries.map φ (complete q u)=complete (φ q) (φ u) := by + unfold complete + have hm : PowerSeries.map φ (elementary q (-u))=elementary (φ q) (-φ u) := by + rw [map_elementary,map_neg] + apply (PowerSeries.eq_inv_iff_mul_eq_one (by rw [constant_elementary]; exact one_ne_zero)).mpr + rw [←hm,←map_mul,PowerSeries.inv_mul_cancel _ (by rw [constant_elementary]; exact one_ne_zero),map_one] + +lemma complete_atInfinity (k : ℤ) : + PowerSeries.map atInfinity (complete RationalRay.q (RationalRay.v^k))= + complete (HahnSeries.single (2:ℤ) (1:ℚ)) (HahnSeries.single (-k) (1:ℚ)) := by + rw [map_complete,atInfinity_q,atInfinity_v_pow] + +lemma atInfinity_eval_monomial (a : ℕ) (k : ℤ) : + atInfinity (PositiveRay.eval (LaurentPolynomial.C a * LaurentPolynomial.T k))= + HahnSeries.single (-k) (a:ℚ) := by + rw [map_mul,PositiveRay.eval_T,map_mul,atInfinity_v_pow] + have hc : PositiveRay.eval (LaurentPolynomial.C a)=(a:RatFunc ℚ) := by + simp [PositiveRay.eval] + rw [hc,map_natCast,←HahnSeries.single_zero_natCast,HahnSeries.single_mul_single, + zero_add,mul_one] + +lemma atInfinity_eval_coeff (p : LaurentPolynomial ℕ) (j : ℤ) : + (atInfinity (PositiveRay.eval p)).coeff j=(p.coeff (-j):ℚ) := by + induction p using LaurentPolynomial.induction_on' with + | add p q hp hq => + simp only [map_add,HahnSeries.coeff_add,AddMonoidAlgebra.coeff_add,Finsupp.add_apply, + Nat.cast_add,hp,hq] + | C_mul_T k a => + rw [atInfinity_eval_monomial,HahnSeries.coeff_single,←LaurentPolynomial.single_eq_C_mul_T] + simp only [AddMonoidAlgebra.coeff_single,Finsupp.single_apply] + by_cases h : j= -k + · subst j; simp + · have h' : k≠ -j := by omega + simp [h,h'] + +lemma positive_coeff_atInfinity {F : PowerSeries (RatFunc ℚ)} (hF : PositiveRay.Positive F) + (n : ℕ) (j : ℤ) : ∃a : ℕ,(atInfinity (coeff n F)).coeff j=(a:ℚ) := by + obtain ⟨A,rfl⟩:=hF + rw [coeff_map,atInfinity_eval_coeff] + exact ⟨(coeff n A).coeff (-j),rfl⟩ + +end LaurentRay +end +end ElementaryPositivity.WallUnits +end +end +section +section +namespace ElementaryPositivity.FiniteFunctionValues +noncomputable section +variable {α β : Type*} [Fintype α] +def values (f : α → β) : Multiset β := Finset.univ.val.map f + +lemma count_values [DecidableEq β] (f : α → β) (b : β) : + (values f).count b=Fintype.card {x : α // f x=b} := by + classical + simp only [values,Multiset.count_map,Fintype.card_subtype,Finset.filter_val,Finset.card,eq_comm] + +lemma values_comp (e : Equiv.Perm α) (f : α → β) : values (f ∘ e)=values f := by + rw [values,←Multiset.map_map,Multiset.map_univ_val_equiv] + rfl + +lemma values_eq_iff [DecidableEq β] (f g : α → β) : + values f=values g ↔ ∃e : Equiv.Perm α,∀x,g (e x)=f x := by + classical + constructor + · intro h + have hc (b : β) : Fintype.card {x : α // f x=b}=Fintype.card {x : α // g x=b} := by + rw [←count_values,←count_values,h] + let ee (b : β) : {x : α // f x=b} ≃ {x : α // g x=b}:=Fintype.equivOfCardEq (hc b) + exact ⟨Equiv.ofFiberEquiv ee,Equiv.ofFiberEquiv_map ee⟩ + · rintro ⟨e,he⟩ + have hf : f=g ∘ e := funext (fun x=>(he x).symm) + rw [hf,values_comp] + +lemma values_fin {n : ℕ} (f : Fin n → β) : values f=(List.ofFn f:Multiset β) := by + rw [values,Finset.val_univ_fin,List.ofFn_eq_map] + rfl + +lemma values_card (f : α → β) : (values f).card=Fintype.card α := by + simp [values] + +lemma values_fin_surjective {n : ℕ} (s : Sym β n) : ∃f : Fin n → β,values f=s.val := by + classical + obtain ⟨l,hl⟩:=Quotient.exists_rep s.val + have hl' : (l:Multiset β)=s.val:=hl + have hn : l.length=n := by simpa only [←Multiset.coe_card,hl'] using s.property + subst n + refine ⟨l.get,?_⟩ + rw [values_fin,List.ofFn_get] + exact hl' +end +end ElementaryPositivity.FiniteFunctionValues +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RealLatticeRealization.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RealLatticeRealization.lean new file mode 100644 index 0000000000000000000000000000000000000000..204249807ffa1742791126a46c2dc61c39678583 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RealLatticeRealization.lean @@ -0,0 +1,197 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.ForwardChartMutation + +namespace OAI + +section +namespace ElementaryPositivity.LatticeRealization +open scoped BigOperators +open TriangularDynamics +variable {V : Type*} [Fintype V] [DecidableEq V] + +noncomputable def cast : (V → ℤ) →+ (V → ℝ) where + toFun x i := x i + map_zero' := by ext i; simp + map_add' x y := by ext i; simp + +omit [Fintype V] [DecidableEq V] in +@[simp] lemma cast_apply (x : V → ℤ) (i : V) : cast x i=(x i:ℝ) := rfl +omit [Fintype V] [DecidableEq V] in +lemma cast_injective : Function.Injective (cast (V:=V)) := by + intro a b h + ext i + have H := congrFun h i + change (a i : ℝ)=(b i : ℝ) at H + exact_mod_cast H + +variable (A : Matrix V V ℤ) +noncomputable def realPairing : (V → ℝ) →ₗ[ℝ] (V → ℝ) →ₗ[ℝ] ℝ := + Matrix.toBilin' (fun i j => (A i j:ℝ)) + +lemma realPairing_apply (x y : V → ℝ) : + realPairing A x y=∑i,∑j,x i*(A i j:ℝ)*y j := Matrix.toBilin'_apply _ _ _ + +lemma realPairing_cast (x y : V → ℤ) : + realPairing A (cast x) (cast y)=(matrixPairing A x y:ℝ) := by + simp only [realPairing_apply,matrixPairing_apply,cast_apply,Int.cast_sum,Int.cast_mul] + +lemma realPairing_skew (hA : ∀i j,A i j= -A j i) (x y : V → ℝ) : + realPairing A x y= -realPairing A y x := by + rw [realPairing_apply,realPairing_apply,Finset.sum_comm] + simp only [←Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + rw [hA j i,Int.cast_neg] + ring + +lemma realPairing_self (hA : ∀i j,A i j= -A j i) (x : V → ℝ) : + realPairing A x x=0 := by + have H:=realPairing_skew A hA x x + linarith + +noncomputable def realDot : (V → ℝ) →ₗ[ℝ] (V → ℝ) →ₗ[ℝ] ℝ := Matrix.toBilin' (1 : Matrix V V ℝ) + +lemma realDot_apply (x y : V → ℝ) : realDot x y=∑i,x i*y i := by + simp [realDot,Matrix.toBilin'_apply,Matrix.one_apply] +lemma realDot_comm (x y : V → ℝ) : realDot x y=realDot y x := by + simp only [realDot_apply] + apply Finset.sum_congr rfl + intro i _ + ring +lemma realDot_cast (x y : V → ℤ) : + realDot (cast x) (cast y)=(LatticeExtension.dot x y:ℝ) := by + simp only [realDot_apply,LatticeExtension.dot_apply,cast_apply,Int.cast_sum,Int.cast_mul] + +noncomputable def extendedCast : LatticeExtension.Extended V →+ ((V → ℝ) × (V → ℝ)) := + (cast.comp (AddMonoidHom.fst _ _)).prod (cast.comp (AddMonoidHom.snd _ _)) +omit [Fintype V] [DecidableEq V] in +lemma extendedCast_apply (x : LatticeExtension.Extended V) : + extendedCast x=(cast x.1,cast x.2) := rfl +omit [Fintype V] [DecidableEq V] in +lemma extendedCast_injective : Function.Injective (extendedCast (V:=V)) := by + intro a b h + apply Prod.ext + · exact cast_injective (congrArg Prod.fst h) + · exact cast_injective (congrArg Prod.snd h) + +noncomputable def extendedRealForm : ((V → ℝ) × (V → ℝ)) →ₗ[ℝ] + ((V → ℝ) × (V → ℝ)) →ₗ[ℝ] ℝ := + ((realPairing A).compl₁₂ (LinearMap.fst ℝ _ _) (LinearMap.fst ℝ _ _)) + + (realDot.compl₁₂ (LinearMap.snd ℝ _ _) (LinearMap.fst ℝ _ _)) - + (realDot.compl₁₂ (LinearMap.fst ℝ _ _) (LinearMap.snd ℝ _ _)) + +lemma extendedRealForm_apply (x y : (V → ℝ) × (V → ℝ)) : + extendedRealForm A x y=realPairing A x.1 y.1+realDot x.2 y.1-realDot x.1 y.2 := rfl + +lemma extendedRealForm_self (hA : ∀i j,A i j= -A j i) (x : (V → ℝ) × (V → ℝ)) : + extendedRealForm A x x=0 := by + rw [extendedRealForm_apply,realPairing_self A hA,zero_add,realDot_comm x.2 x.1,sub_self] + +lemma extendedRealForm_cast (x y : LatticeExtension.Extended V) : + extendedRealForm A (extendedCast x) (extendedCast y)= + (LatticeExtension.form (matrixPairing A) x y:ℝ) := by + simp only [extendedRealForm_apply,extendedCast_apply,realPairing_cast,realDot_cast, + LatticeExtension.form_apply,Int.cast_sub,Int.cast_add] + +end ElementaryPositivity.LatticeRealization + +end +section +namespace ElementaryPositivity.ForwardChain +variable {M M':Type*} [AddCommGroup M] [AddCommGroup M'] +lemma gaps_map (a:M →+ M') (x y:M) (bs:List M) : + gaps (a x) (bs.map a) (a y)=(gaps x bs y).map a := by + induction bs generalizing x with + | nil => simp [gaps,map_sub] + | cons b bs ih => simp only [gaps,List.map_cons,map_sub,ih] +end ElementaryPositivity.ForwardChain + +namespace ElementaryPositivity.TriangularDynamics +variable {n:ℕ} {M M':Type*} [AddCommGroup M] [AddCommGroup M'] +lemma forwardInventory_map (a:M →+ M') (d:Fin (n+1) → M) (w:Cell n → M) (q:List (Cell n)) : + forwardInventory (a ∘ d) (a ∘ w) q=(forwardInventory d w q).map a := by + unfold forwardInventory + rw [List.map_flatMap] + congr 1 + funext i + simp only [levelGaps,Function.comp_apply,←List.map_map,ForwardChain.gaps_map] +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus LatticeExtension LatticeRealization +open Classical +noncomputable section +variable {n:ℕ} + +lemma cast_single {V:Type*} [Fintype V] [DecidableEq V] (i:V) (z:ℤ) : + LatticeRealization.cast (Pi.single i z)=Pi.single i (z:ℝ) := by + ext j + simp only [LatticeRealization.cast_apply,Pi.single_apply] + split_ifs <;> simp +lemma cast_forwardGap (g:GapIndex n) : + LatticeRealization.cast (forwardGap (R:=ℤ) g)=forwardGap (R:=ℝ) g := by + simp only [forwardGap,map_sub,cast_single,Int.cast_one] + +def extendedRoots (n:ℕ) : (GapIndex n → ℤ) →+ Extended (Vertex n (Cell n)) := + includeVertices.comp (forwardRoots (R:=ℤ)).toAddMonoidHom + +def extendedCoord (n:ℕ) : Extended (Vertex n (Cell n)) →+ (GapIndex n → ℤ) := + (forwardCoord (R:=ℤ)).toAddMonoidHom.comp (AddMonoidHom.fst _ _) + +lemma extendedCoord_roots (c:GapIndex n → ℤ) : extendedCoord n (extendedRoots n c)=c := by + exact forwardCoord_roots c +lemma extendedRoot_eq (g:GapIndex n) : simpleRoot (extendedRoots n) g=includeVertices (forwardGap g) := by + change includeVertices (simpleRoot (forwardRoots (R:=ℤ)).toAddMonoidHom g)=_ + rw [simpleRoot_forwardRoots] +lemma extendedRoots_realIndependent : + LinearIndependent ℝ (fun i:GapIndex n=>extendedCast (simpleRoot (extendedRoots n) i)) := by + let incl : (Vertex n (Cell n) → ℝ) →ₗ[ℝ] + ((Vertex n (Cell n) → ℝ) × (Vertex n (Cell n) → ℝ)) := LinearMap.inl ℝ _ _ + have hincl : Function.Injective incl := by + intro x y h + exact congrArg Prod.fst h + have hk : LinearMap.ker incl = ⊥ := LinearMap.ker_eq_bot.mpr hincl + have Hi : LinearIndependent ℝ (incl ∘ (forwardGap (R:=ℝ) (n:=n))) := + (forwardGap_independent (R:=ℝ) (n:=n)).map' incl hk + convert Hi using 1 + funext i + rw [extendedRoot_eq] + change (LatticeRealization.cast (forwardGap (R:=ℤ) i),LatticeRealization.cast 0)=(forwardGap i,0) + rw [cast_forwardGap,map_zero] + +def initialFreeChart (n:ℕ) : FreeChart (I:=GapIndex n) (extendedCast (V:=Vertex n (Cell n))) where + roots := extendedRoots n + coord := extendedCoord n + retract := extendedCoord_roots + independent := extendedRoots_realIndependent + +lemma initialFreeChart_inventory : + ((gapIndices n).map (simpleRoot (initialFreeChart n).roots)).Perm + (forwardInventory (includeVertices ∘ anchor) (includeVertices ∘ bridge) (phaseCycle n)) := by + apply List.Perm.of_eq + rw [forwardInventory_map,initial_forwardInventory,List.map_map] + apply List.map_congr_left + intro g _ + exact extendedRoot_eq g + +def extendedOmega (n:ℕ) := LatticeExtension.form (triangularOmega n) +lemma extendedOmega_self : ∀m,extendedOmega n m m=0 := form_self _ triangularOmega_self +lemma extendedOmega_nondegenerate : ∀r≠0,∃m,extendedOmega n r m≠0 := form_nondegenerate _ +lemma extendedOmega_original (m m':Lattice n (Cell n)) : + extendedOmega n (includeVertices m) (includeVertices m')=triangularOmega n m m' := form_original _ _ _ +def triangularRealForm (n:ℕ) := extendedRealForm (chartMatrix (@cellLevel n) (@triangularBB n)) +lemma triangularRealForm_self : ∀m, triangularRealForm n m m=0 := + extendedRealForm_self _ (chartMatrix_skew cellLevel triangularBB triangularBB_skew) +lemma triangularRealForm_compatible (m m':Extended (Vertex n (Cell n))) : + triangularRealForm n (extendedCast m) (extendedCast m')=(extendedOmega n m m':ℝ) := + extendedRealForm_cast _ _ _ +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RefinedLaurent.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RefinedLaurent.lean new file mode 100644 index 0000000000000000000000000000000000000000..a813e67a5651e7a90d3ce590700dff27b7af0c54 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RefinedLaurent.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.SeparationCoefficients +import OAI.Combinatorics.Chromatic.Walls.CenterLineSpecialization +import OAI.Combinatorics.Chromatic.Shuffle.LaurentLeading +import OAI.Combinatorics.Chromatic.Walls.LaurentLinearNaturality +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentProductNaturality + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open ElementaryPositivity.CenterCalculus +open ElementaryPositivity.LaurentAtInfinity +open SeparationInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma refined_inverseKernel_degreeZero (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,01) (fun _=>0)) + (totalLeadingPolynomial a c η hc θ (.node L R) ⟨hL,hR⟩ W f)) := by + have hm := mapRing_mul_polynomial + (refinedAtB a c η hc θ L R hL hR v w).toRingHom + (quotientInverseKernelUnit a (SlopeArithmetic.slope c η) L.dim R.dim).val + (restrictionRelativeB a c η hc + ((slope_dim c η hc hL).trans (slope_dim c η hc hR).symm) (firstCut L.dim R.dim) f) + change mapRing (refinedAtB a c η hc θ L R hL hR v w).toRingHom + (separationSeries a c η hc ((slope_dim c η hc hL).trans (slope_dim c η hc hR).symm) f)=_ at hm + rw [hm] + rw [weightComponent_laurent_mul a (SlopeArithmetic.slope c η) (.node L R) W _ _ + (scalarCrossKernel a L R v w).val + (refined_relative_laurent_degreeCut a c η hc θ L R hL hR v w W f hf) + (refined_inverseKernel_degreeZero a c η hc θ L R hL hR v w)] + rw [refinedAtB_relative_polynomial,LaurentAtInfinity.polynomial_mapLinear, + ←lineSpecialization_mapLinear] + rfl + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RefinedTensorDetection.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RefinedTensorDetection.lean new file mode 100644 index 0000000000000000000000000000000000000000..b41b185ba82543be6f72422d0451df076685c1d3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RefinedTensorDetection.lean @@ -0,0 +1,139 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RefinedLaurent +import OAI.Combinatorics.Chromatic.Shuffle.CrossCancellation + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial +open scoped TensorProduct +open ElementaryPositivity.CenterCalculus +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +noncomputable def refinedCenterPolynomial (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 rfl + have ht:=centerTranslation_evalRat a (SlopeArithmetic.slope c η) (.node L R) + (Algebra.TensorProduct.map (restrictionB a c η hc θ L hL) (restrictionB a c η hc θ R hR) x) v + change _=translationAtAlgB a (SlopeArithmetic.slope c η) (.node L R) _ _ + rw [translationAtAlgB_apply,he] + exact ht + +lemma refinedCenterPolynomial_coeff_test (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 rfl + | add x y hx hy => simp only [map_add,hx,hy] + +lemma refinedAtB_weight_zero_test (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0componentTensor a (SlopeArithmetic.slope c η) (.node L R) (k,l) + (AddMonoidAlgebra.coeff p (z.sumElim w))) hp + rw [coeff_mapLinear,componentTensor_weightComponent,ite_eq_left hw,AddMonoidAlgebra.coeff_zero, + Finsupp.zero_apply,map_zero,refinedCenterPolynomial_coeff_test] at h + exact h +end ElementaryPositivity.RawShuffle.SplitTree + +end +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.LaurentAtInfinity +open SplitTree SeparationInfinity +universe u +variable {I : Type u} [Fintype I] [DecidableEq I] + +lemma refined_negative_separation_weight_zero (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0x.coeff (-j)) h + rw [mapLinear_coeff,mapRing_coeff,polynomial_coeff_positive p (-j) (by omega)] at hh + exact hh + +theorem separationCoefficient_negative_filtration (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0refined_negative_separation_weight_zero a c η hc θ hχ L R hL hR v w W j hj f hf) + change (2*L.totalDegree k+L.doubleShift a)+(2*R.totalDegree l+R.doubleShift a)=W at hw + change 2*(L.totalDegree k+R.totalDegree l)+(L.doubleShift a+R.doubleShift a)=W + omega + +end ElementaryPositivity.RawShuffle + +end +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +variable {A σ : Type*} [CommRing A] [Algebra ℚ A] +lemma lineSpecialization_coeff_zero (v h : σ → ℚ) (p : MvPolynomial σ A) : + (lineSpecialization v h p).coeff 0=evalRat v p := by + rw [Polynomial.coeff_zero_eq_eval_zero] + have he:=lineSpecialization_eval v h p 0 + simpa only [map_zero,mul_zero,add_zero] using he +lemma evalRat_map_algebra_eq (v : σ → ℚ) (p : MvPolynomial σ ℚ) : + evalRat (A:=A) v (map (algebraMap ℚ A) p)=algebraMap ℚ A (evalRat v p) := by + rw [← lineSpecialization_coeff_zero v (fun _=>0),lineSpecialization_map_algebra, + Polynomial.coeff_map,lineSpecialization_coeff_zero] +end ElementaryPositivity.CenterCalculus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RootClosureFacts.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RootClosureFacts.lean new file mode 100644 index 0000000000000000000000000000000000000000..526a640a7faaf3130aa835b59c496eecf07beff2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RootClosureFacts.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.SeriesApproximation +import OAI.Combinatorics.Chromatic.Walls.RootProducts + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries LaurentPrecision Filter +open WallUnits +noncomputable section +variable {M J : Type*} [AddCommGroup M] [Fintype J] +variable (Ω : M→+M→+ℤ) (C : (J→ℤ)→+M) +variable {A : Set (PowerSeries (Torus LaurentRay.vUnit Ω))} +variable {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + +lemma InPrecisionClosure.graded + (hF : InPrecisionClosure LaurentRay.vUnit Ω A F) + (hA : ∀G∈A,SeriesGraded LaurentRay.vUnit Ω C G) : + SeriesGraded LaurentRay.vUnit Ω C F := by + classical + intro n m hm + ext j + obtain ⟨G,hG,H⟩:=hF {(n,m,j+1)} + have HH:=H (n,m,j+1) (by simp) j (by dsimp; omega) + dsimp only at HH + rw [hA G hG n m hm] at HH + exact HH.symm + +lemma InPrecisionClosure.constant + (hF : InPrecisionClosure LaurentRay.vUnit Ω A F) + (hA : ∀G∈A,constantCoeff G=1) : constantCoeff F=1 := by + classical + apply Finsupp.ext + intro m + ext j + obtain ⟨G,hG,H⟩:=hF {(0,m,j+1)} + have HH:=H (0,m,j+1) (by simp) j (by dsimp; omega) + dsimp only at HH + rw [coeff_zero_eq_constantCoeff] at HH + rw [hA G hG] at HH + exact HH.symm + +variable (V : M→Prop) +def rootClosureCompleted (hF : InPrecisionClosure LaurentRay.vUnit Ω + (literalRootProducts Ω C V) F) : CompletedPositive LaurentRay.vUnit Ω C := + ⟨F,hF.constant Ω (fun _ h=>literalRootProducts_constant Ω C V h), + hF.graded Ω C (fun _ h=>literalRootProducts_graded Ω C V h)⟩ + +lemma InPrecisionClosure.zeroFactor + (hF : InPrecisionClosure LaurentRay.vUnit Ω A F) + (hA : ∀G∈A,SeriesGraded LaurentRay.vUnit Ω C G) + (h : M→+ℝ) (B : Set (PowerSeries (Torus LaurentRay.vUnit Ω))) + (hB : ∀G∈A,InPrecisionClosure LaurentRay.vUnit Ω B + (PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) G)) : + InPrecisionClosure LaurentRay.vUnit Ω B + (PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) F) := by + let g:=precisionApprox LaurentRay.vUnit Ω hF + have hg:=precisionApprox_converges LaurentRay.vUnit Ω hF + have hgg : ∀T,SeriesGraded LaurentRay.vUnit Ω C (g T) := + fun T=>hA _ (precisionApprox_mem LaurentRay.vUnit Ω hF T) + have hFG:=hF.graded Ω C hA + have H:=filter_factors_converge LaurentRay.vUnit Ω C Filter.atTop (fun m=>0h m=0) H.2 + (fun T n=>by + simpa only [PowerSeriesSplit.rightFactor,coeff_mk] using + (filter_pair_graded LaurentRay.vUnit Ω C (fun m=>0by + simpa only [PowerSeriesSplit.rightFactor,coeff_mk] using + (filter_pair_graded LaurentRay.vUnit Ω C (fun m=>0hB _ (precisionApprox_mem LaurentRay.vUnit Ω hF T)) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RootLaurentCompletion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RootLaurentCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..72af04b9d87aac1c8428b1c4f494b41af47f1728 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RootLaurentCompletion.lean @@ -0,0 +1,75 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegradeFaithful +import OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentRegrade + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (δ κ η : M →+ ℤ) (B : ℕ) +local instance rootLaurentCompletionRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance rootLaurentCompletionAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance rootLaurentCompletionAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +lemma laurentRegrade_read {f : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (hhom : FullHomogeneous v Ω η f) + (n d : ℕ) (z : ℤ) (m : M) (hn : η m=(n:ℤ)) + (hd : δ m=(d:ℤ)) (hz : κ m=z) : + (coeff d (laurentRegrade v Ω δ κ B f hf)).coeff z m=coeff n f m := by + rw [laurentRegrade_coeff,nonp_torus_eval_sum] + have H (j : ℕ) : (coeff d (laurentHomogenize v Ω δ κ (coeff j f))).coeff z m=coeff j f m := by + rw [laurentHomogenize_coeff,hd,hz] + simp + simp_rw [H] + apply Finset.sum_eq_single n + · intro j hj hjn + by_contra h + have HH:=hhom j m h + rw [hn] at HH + exact hjn (by omega) + · intro hn' + by_contra h + have HH:=(hf n m h).2.2 + rw [hd,hz] at HH + simp only [Finset.mem_range,not_lt] at hn' + omega + +lemma laurentRegrade_injective {f g : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (hg : LaurentBounded v Ω δ κ B g) + (hfh : FullHomogeneous v Ω η f) (hgh : FullHomogeneous v Ω η g) + (heq : laurentRegrade v Ω δ κ B f hf=laurentRegrade v Ω δ κ B g hg) : f=g := by + apply PowerSeries.ext + intro n + ext m + by_cases H : η m=(n:ℤ) ∧ 0≤δ m + · rw [←laurentRegrade_read v Ω δ κ η B hf hfh n (δ m).toNat (κ m) m H.1 + (Int.toNat_of_nonneg H.2).symm rfl,heq, + laurentRegrade_read v Ω δ κ η B hg hgh n (δ m).toNat (κ m) m H.1 + (Int.toNat_of_nonneg H.2).symm rfl] + · have hF : coeff n f m=0 := by + by_contra h + exact H ⟨hfh n m h,(hf n m h).1⟩ + have hG : coeff n g m=0 := by + by_contra h + exact H ⟨hgh n m h,(hg n m h).1⟩ + rw [hF,hG] + +lemma laurentRegrade_coeff_congr {f g : PowerSeries (Torus v Ω)} + (hf : LaurentBounded v Ω δ κ B f) (hg : LaurentBounded v Ω δ κ B g) + (d : ℕ) (z : ℤ) + (H : ∀n≤(z+(B+1:ℤ)*(d:ℤ)).toNat,coeff n f=coeff n g) : + (coeff d (laurentRegrade v Ω δ κ B f hf)).coeff z= + (coeff d (laurentRegrade v Ω δ κ B g hg)).coeff z := by + rw [laurentRegrade_coeff,laurentRegrade_coeff] + apply Finset.sum_congr rfl + intro n hn + rw [H n (by simpa only [Finset.mem_range,Nat.lt_succ_iff] using hn)] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/RootProducts.lean b/lean/OAI/Combinatorics/Chromatic/Walls/RootProducts.lean new file mode 100644 index 0000000000000000000000000000000000000000..d962fd22a31b87a4eff938a4ab43c6fd2d943767 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/RootProducts.lean @@ -0,0 +1,165 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CompletedInverse +import OAI.Combinatorics.Chromatic.Walls.WeightedRay +import OAI.Combinatorics.Chromatic.Walls.HNTorusFactor + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits UnitSelections LaurentPrecision +noncomputable section +variable {M J : Type*} [AddCommGroup M] [Fintype J] + +structure WallUnitDatum (M : Type*) where + degree : ℕ + root : M + kind : ℕ + parameter : ℤ + +variable (Ω : M→+M→+ℤ) (C : (J→ℤ)→+M) + +def WallUnitDatum.value (u : WallUnitDatum M) : PowerSeries (Torus LaurentRay.vUnit Ω) := + weightedRay LaurentRay.vUnit Ω u.degree u.root + (PowerSeries.map LaurentRay.atInfinity (indexedUnit u.kind u.parameter)) + +def WallUnitDatum.Allowed (V : M→Prop) (u : WallUnitDatum M) : Prop := + 0simpa using rootDegree_zero C + | succ k ih=>simpa only [Nat.succ_mul,succ_nsmul] using rootDegree_add C ih hp + +lemma weightedRay_graded (n : ℕ) (p : M) (hp : HasRootDegree C n p) + (F : PowerSeries (LaurentSeries ℚ)) : + SeriesGraded LaurentRay.vUnit Ω C (weightedRay LaurentRay.vUnit Ω n p F) := by + intro k m hm + rw [coeff_weightedRay] + split_ifs with h + · change (Finsupp.single ((k/n) • p) (coeff (k/n) F)) m=0 + apply Finsupp.single_eq_of_ne + intro H + apply hm + simpa only [Nat.div_mul_cancel h,H] using rootDegree_nsmul C hp (k/n) + · rfl + +lemma indexedUnit_constant (a : ℕ) (k : ℤ) : constantCoeff (indexedUnit a k)=1 := by + unfold indexedUnit + split_ifs + · exact constant_elementary _ _ + · simp only [complete,constantCoeff_inv,constant_elementary,inv_one] + +lemma WallUnitDatum.constant (u : WallUnitDatum M) : constantCoeff (u.value Ω)=1 := by + rw [←coeff_zero_eq_constantCoeff,WallUnitDatum.value,coeff_weightedRay] + simp only [dvd_zero,ite_eq_left,Nat.zero_div,zero_nsmul,coeff_map,coeff_zero_eq_constantCoeff, + indexedUnit_constant,map_one] + rfl + +lemma WallUnitDatum.graded (V : M→Prop) (u : WallUnitDatum M) (hu : u.Allowed C V) : + SeriesGraded LaurentRay.vUnit Ω C (u.value Ω) := + weightedRay_graded Ω C u.degree u.root hu.2.1 _ + +def literalRootProducts (V : M→Prop) : Set (PowerSeries (Torus LaurentRay.vUnit Ω)) := + {F | ∃l : List (WallUnitDatum M),(∀u∈l,u.Allowed C V) ∧ F=(l.map (WallUnitDatum.value Ω)).prod} + +lemma literalRootProducts_graded (V : M→Prop) {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : F∈literalRootProducts Ω C V) : SeriesGraded LaurentRay.vUnit Ω C F := by + obtain ⟨l,hl,rfl⟩:=hF + induction l with + | nil=>simpa using SeriesGraded.one LaurentRay.vUnit Ω C + | cons u l ih=> + simp only [List.map_cons,List.prod_cons] + exact (u.graded Ω C V (hl u (by simp))).mul LaurentRay.vUnit Ω C + (ih (fun v hv=>hl v (by simp [hv]))) + +lemma literalRootProducts_constant (V : M→Prop) {F : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : F∈literalRootProducts Ω C V) : constantCoeff F=1 := by + obtain ⟨l,hl,rfl⟩:=hF + simp only [map_list_prod,List.map_map] + have H : l.map (constantCoeff ∘ WallUnitDatum.value Ω)=l.map (fun _=>1) := by + apply List.map_congr_left + intro u hu + exact u.constant Ω + rw [H] + simp +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.LaurentPositive +open LaurentPrecision +noncomputable section + +def NatCoeff (r : ℚ) : Prop := ∃n : ℕ,r=n + +def Positive (f : LaurentSeries ℚ) : Prop := ∀j,NatCoeff (f.coeff j) + +lemma natCoeff_zero : NatCoeff 0 := ⟨0,rfl⟩ +lemma natCoeff_one : NatCoeff 1 := ⟨1,rfl⟩ +lemma NatCoeff.add {r s : ℚ} (hr : NatCoeff r) (hs : NatCoeff s) : NatCoeff (r+s) := by + obtain ⟨n,rfl⟩:=hr + obtain ⟨m,rfl⟩:=hs + exact ⟨n+m,(Nat.cast_add n m).symm⟩ +lemma NatCoeff.mul {r s : ℚ} (hr : NatCoeff r) (hs : NatCoeff s) : NatCoeff (r*s) := by + obtain ⟨n,rfl⟩:=hr + obtain ⟨m,rfl⟩:=hs + exact ⟨n*m,(Nat.cast_mul n m).symm⟩ +lemma NatCoeff.sum {A : Type*} (s : Finset A) (f : A → ℚ) + (h : ∀a∈s,NatCoeff (f a)) : NatCoeff (∑a∈s,f a) := by + classical + induction s using Finset.induction_on with + | empty => exact natCoeff_zero + | @insert a s ha ih => + rw [Finset.sum_insert ha] + exact (h a (Finset.mem_insert_self _ _)).add (ih (fun b hb=>h b (Finset.mem_insert_of_mem hb))) + +lemma positive_zero : Positive 0 := fun _=>natCoeff_zero +lemma positive_one : Positive 1 := by + intro j + rw [HahnSeries.coeff_one] + split <;> first | exact natCoeff_one | exact natCoeff_zero +lemma Positive.add {f g : LaurentSeries ℚ} (hf : Positive f) (hg : Positive g) : Positive (f+g) := + fun j=>(hf j).add (hg j) +lemma Positive.mul {f g : LaurentSeries ℚ} (hf : Positive f) (hg : Positive g) : Positive (f*g) := by + intro j + rw [HahnSeries.coeff_mul] + apply NatCoeff.sum + intro p hp + exact (hf p.1).mul (hg p.2) +lemma Positive.sum {A : Type*} (s : Finset A) (f : A → LaurentSeries ℚ) + (h : ∀a∈s,Positive (f a)) : Positive (∑a∈s,f a) := by + classical + induction s using Finset.induction_on with + | empty => exact positive_zero + | @insert a s ha ih => + rw [Finset.sum_insert ha] + exact (h a (Finset.mem_insert_self _ _)).add (ih (fun b hb=>h b (Finset.mem_insert_of_mem hb))) + +lemma single (k : ℤ) (r : ℚ) (hr : NatCoeff r) : Positive (HahnSeries.single k r) := by + intro j + rw [HahnSeries.coeff_single] + split <;> first | exact hr | exact natCoeff_zero + +lemma series {A : Type*} (e : A → ℤ) (he : EnergyLaurent.Admissible e) : + Positive (EnergyLaurent.series e he) := by + intro j + rw [EnergyLaurent.series_coeff] + exact ⟨_,rfl⟩ + +lemma of_converges {A : Type*} (l : Filter A) [l.NeBot] + {f : A → LaurentSeries ℚ} {F : LaurentSeries ℚ} + (h : Converges l f F) (hp : ∀ᶠi in l,Positive (f i)) : Positive F := by + intro j + obtain ⟨i,hi,hpi⟩:=Filter.Eventually.exists ((h (j+1)).and hp) + rw [←hi j (by omega)] + exact hpi j + +end +end ElementaryPositivity.LaurentPositive + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/SectionGenericPerturbation.lean b/lean/OAI/Combinatorics/Chromatic/Walls/SectionGenericPerturbation.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f1fd3419a836794656ef307f46418342cf87b52 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/SectionGenericPerturbation.lean @@ -0,0 +1,222 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SectionRayTransition +import OAI.Combinatorics.Chromatic.Walls.FiniteWallCrossing + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (e : M →+ E) (L : Module.Dual ℝ E) +variable (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include hdeg in +lemma section_positive_perturbation (F : CompletedPositive v Ω C) + (X : PowerSeries (Torus v Ω)) (N : ℕ) (h : Module.Dual ℝ E) : + ∃k : Module.Dual ℝ E,ChamberGeneric C N (k.toAddMonoidHom.comp e) ∧ + ∀n≤N,coeff n (sectionValue v Ω C F (k.toAddMonoidHom.comp e) X)= + coeff n (sectionValue v Ω C F (h.toAddMonoidHom.comp e) X) := by + let hM:=h.toAddMonoidHom.comp e + let lM:=L.toAddMonoidHom.comp e + obtain ⟨ε,hε,Hε⟩:=root_lex_epsilon C N hM lM + let δ:=ε/2 + have hd : 0<δ:=by dsimp [δ]; linarith + have hdε : δ<ε:=by dsimp [δ]; linarith + have hk : (h+δ • L).toAddMonoidHom.comp e=hM+δ • lM:=by ext m; rfl + refine ⟨h+δ • L,?_,?_⟩ + · rw [hk] + intro n hn hnN m hm + have HH:=Hε δ hd hdε n hnN m hm + have hlpos : 0Hneg j (hj.trans hn)) (fun _ _=>rfl) + rw [HH,adjoint_one] +include hdeg in +lemma section_generic_offset (F : CompletedPositive v Ω C) + (X : PowerSeries (Torus v Ω)) (N : ℕ) (h dir : Module.Dual ℝ E) : + ∃k : Module.Dual ℝ E,GenericOffset (realRootsThrough e C N) 0 dir k ∧ + ∀n≤N,coeff n (sectionValue v Ω C F (k.toAddMonoidHom.comp e) X)= + coeff n (sectionValue v Ω C F (h.toAddMonoidHom.comp e) X) := by + obtain ⟨h',hgen,heq⟩:=section_positive_perturbation v Ω C e L hdeg F X N h + obtain ⟨k,Hk,Hsign⟩:=exists_generic_offset (realRootsThrough e C N) 0 dir h' (map_zero h') + refine ⟨k,Hk,?_⟩ + have HH:=section_sign_congr_through v Ω C (h'.toAddMonoidHom.comp e) + (k.toAddMonoidHom.comp e) F X N (by + intro n hn hnN m hm + have HS:=Hsign (e m) (realRoot_mem e C N n hnN m hm) + exact ⟨HS.1,fun hh=>False.elim (hgen n hn hnN m hm hh),HS.2⟩) + exact fun n hn=>(HH n hn).symm.trans (heq n hn) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit FiniteRayGeometry +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (e : M →+ E) (L : Module.Dual ℝ E) +variable (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include hdeg in +lemma uniform_section_positive_perturbation (N : ℕ) (h : Module.Dual ℝ E) : + ∃k : Module.Dual ℝ E,ChamberGeneric C N (k.toAddMonoidHom.comp e) ∧ + ∀(F : CompletedPositive v Ω C) (X : PowerSeries (Torus v Ω)),∀n≤N, + coeff n (sectionValue v Ω C F (k.toAddMonoidHom.comp e) X)= + coeff n (sectionValue v Ω C F (h.toAddMonoidHom.comp e) X) := by + let hM:=h.toAddMonoidHom.comp e + let lM:=L.toAddMonoidHom.comp e + obtain ⟨ε,hε,Hε⟩:=root_lex_epsilon C N hM lM + let δ:=ε/2 + have hd : 0<δ:=by dsimp [δ]; linarith + have hdε : δ<ε:=by dsimp [δ]; linarith + have hk : (h+δ • L).toAddMonoidHom.comp e=hM+δ • lM:=by ext m; rfl + refine ⟨h+δ • L,?_,?_⟩ + · rw [hk] + intro n hn hnN m hm + have HH:=Hε δ hd hdε n hnN m hm + have hlpos : 0Hneg j (hj.trans hn)) (fun _ _=>rfl) + rw [HH,adjoint_one] +include hdeg in +lemma uniform_section_generic_offset (N : ℕ) (h dir : Module.Dual ℝ E) : + ∃k : Module.Dual ℝ E,GenericOffset (realRootsThrough e C N) 0 dir k ∧ + ∀(F : CompletedPositive v Ω C) (X : PowerSeries (Torus v Ω)),∀n≤N, + coeff n (sectionValue v Ω C F (k.toAddMonoidHom.comp e) X)= + coeff n (sectionValue v Ω C F (h.toAddMonoidHom.comp e) X) := by + obtain ⟨h',hgen,heq⟩:=uniform_section_positive_perturbation v Ω C e L hdeg N h + obtain ⟨k,Hk,Hsign⟩:=exists_generic_offset (realRootsThrough e C N) 0 dir h' (map_zero h') + refine ⟨k,Hk,?_⟩ + intro F X n hn + have HH:=section_sign_congr_through v Ω C (h'.toAddMonoidHom.comp e) + (k.toAddMonoidHom.comp e) F X N (by + intro n hn hnN m hm + have HS:=Hsign (e m) (realRoot_mem e C N n hnN m hm) + exact ⟨HS.1,fun hh=>False.elim (hgen n hn hnN m hm hh),HS.2⟩) + exact (HH n hn).symm.trans (heq F X n hn) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit FiniteRayGeometry LaurentPositive WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] + +structure LineTransfer (E:Type*) [AddCommGroup E] [Module ℝ E] where + wall : Module.Dual ℝ E + source : Module.Dual ℝ E + reverse : Bool + +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) (e:M →+ E) +def LineTransfer.operator (F:CompletedPositive LaurentRay.vUnit Ω C) (t:LineTransfer E) : + PowerSeries (Torus LaurentRay.vUnit Ω) := + if t.reverse then invOfUnit (chartZero LaurentRay.vUnit Ω C (t.wall.toAddMonoidHom.comp e) F).val 1 + else (chartZero LaurentRay.vUnit Ω C (t.wall.toAddMonoidHom.comp e) F).val +lemma LineTransfer.constantCoeff_operator (F:CompletedPositive LaurentRay.vUnit Ω C) (t:LineTransfer E) : + constantCoeff (t.operator Ω C e F)=1 := by + unfold LineTransfer.operator + split + · simp + · exact (chartZero LaurentRay.vUnit Ω C _ F).property.1 + +def LineTransfer.delta (F:CompletedPositive LaurentRay.vUnit Ω C) (b:M) + (X:PowerSeries (Torus LaurentRay.vUnit Ω)) (N:ℕ) (r:M) (t:LineTransfer E) : LaurentSeries ℚ := + ∑j∈Finset.range N,∑m∈gradePoints C b j, + coeff j (sectionValue LaurentRay.vUnit Ω C F (t.source.toAddMonoidHom.comp e) X) m* + monomialJump Ω (t.operator Ω C e F) (N-j) m r + +def LineTransfer.PositiveThrough (F:CompletedPositive LaurentRay.vUnit Ω C) (N:ℕ) (r:M) (t:LineTransfer E) : Prop := + ∀d≤N,∀m,Positive (monomialJump Ω (t.operator Ω C e F) d m r) + +variable (he:Function.Injective e) (B:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB:∀x,B x x=0) +variable (hcomp:∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in +lemma section_line_transfer (N:ℕ) (r:M) (F:CompletedPositive LaurentRay.vUnit Ω C) + (walls:WallsPositiveThrough Ω C e N F) (k:Module.Dual ℝ E) + (H:GenericOffset (realRootsThrough e C N) 0 (B.flip (e r)) k) + (a:ℝ) (ha:a∈lineEvents (realRootsThrough e C N) (B.flip (e r)) k) : + ∃ε>0,∀δ:ℝ,0<δ → δ<ε → ∃t:LineTransfer E, + t.PositiveThrough Ω C e F N r ∧ + ∀b (X:PowerSeries (Torus LaurentRay.vUnit Ω)),ShiftGraded LaurentRay.vUnit Ω C b X → + coeff N (sectionValue LaurentRay.vUnit Ω C F ((k+(a-δ) • B.flip (e r)).toAddMonoidHom.comp e) X) r = + coeff N (sectionValue LaurentRay.vUnit Ω C F ((k+(a+δ) • B.flip (e r)).toAddMonoidHom.comp e) X) r + + t.delta Ω C e F b X N r := by + have hΩ:∀m,Ω m m=0:=by + intro m; have HH:=hB (e m); rw [hcomp] at HH; exact_mod_cast HH + obtain ⟨p,d,hd,hdN,hp,hv,hgen⟩:=section_event_ray C e he L hdeg N (B.flip (e r)) k H a ha + let h:=(k+a • B.flip (e r)).toAddMonoidHom.comp e + let dir:=(B.flip (e r)).toAddMonoidHom.comp e + obtain ⟨εp,hεp,Hεp⟩:=root_lex_epsilon C N h dir + obtain ⟨εm,hεm,Hεm⟩:=root_lex_epsilon C N h (-dir) + refine ⟨min εp εm,lt_min hεp hεm,?_⟩ + intro δ hδ hδε + have hδp:=lt_of_lt_of_le hδε (min_le_left _ _) + have hδm:=lt_of_lt_of_le hδε (min_le_right _ _) + let hpM:=(k+(a+δ) • B.flip (e r)).toAddMonoidHom.comp e + let hmM:=(k+(a-δ) • B.flip (e r)).toAddMonoidHom.comp e + have HC (X:PowerSeries (Torus LaurentRay.vUnit Ω)):=section_ray_crossing LaurentRay.vUnit Ω C F X N p h dir hpM hmM hgen + (by simpa only [hpM,line_covector_add] using Hεp δ hδ hδp) + (by simpa only [hmM,line_covector_sub] using Hεm δ hδ hδm) + have HS:∀n,0 if HasRootDegree C n (m-b) then + (coeff n (sectionValue v Ω C F (incomingCovector Ω m) X)) m else 0) + (by intro m hm; rw [Set.Finite.mem_toFinset]; by_contra hn; exact hm (ite_eq_right hn)) +lemma sectionIncoming_apply (n : ℕ) (X : PowerSeries (Torus v Ω)) (m : M) : + sectionIncoming v Ω C F b n X m=if HasRootDegree C n (m-b) then + (coeff n (sectionValue v Ω C F (incomingCovector Ω m) X)) m else 0 := rfl +lemma sectionIncoming_graded (n : ℕ) (X : PowerSeries (Torus v Ω)) : + sectionIncoming v Ω C F b n X∈shiftRootGrade v Ω C b n := by + intro m hm + rw [sectionIncoming_apply,ite_eq_right hm] +lemma sectionIncoming_congr (n : ℕ) (X Y : PowerSeries (Torus v Ω)) + (h : ∀k≤n,coeff k X=coeff k Y) : + sectionIncoming v Ω C F b n X=sectionIncoming v Ω C F b n Y := by + apply Finsupp.ext + intro m + rw [sectionIncoming_apply,sectionIncoming_apply] + split_ifs + · exact congrArg (fun t : Torus v Ω=>t m) + (adjoint_coeff_congr (chartNegative v Ω C (incomingCovector Ω m) F).val _ X Y n (fun _ _=>rfl) h) + · rfl +lemma sectionIncoming_leading (n : ℕ) (X Y : PowerSeries (Torus v Ω)) + (h : ∀kt m) H + · rw [ite_eq_right hm,ite_eq_right hm,hX m hm,hY m hm] +lemma sectionIncoming_zero (X : PowerSeries (Torus v Ω)) + (hX : coeff 0 X∈shiftRootGrade v Ω C b 0) : + sectionIncoming v Ω C F b 0 X=coeff 0 X := by + apply Finsupp.ext + intro m + rw [sectionIncoming_apply] + by_cases hm : HasRootDegree C 0 (m-b) + · rw [ite_eq_left hm] + unfold sectionValue + rw [coeff_zero_eq_constantCoeff,constant_adjoint _ _ (chartNegative v Ω C _ F).property.1] + · rw [ite_eq_right hm,hX m hm] + +def sectionSolutionCoefficients (l : ℕ → Torus v Ω) : ℕ → Torus v Ω + | 0 => l 0 + | n+1 => l (n+1)-sectionIncoming v Ω C F b (n+1) + (PowerSeries.mk (fun k=>if _ : k≤n then sectionSolutionCoefficients l k else 0)) +termination_by n=>n + +def sectionSolution (l : ℕ → Torus v Ω) : PowerSeries (Torus v Ω) := + PowerSeries.mk (sectionSolutionCoefficients v Ω C F b l) +def sectionTruncation (l : ℕ → Torus v Ω) (n : ℕ) : PowerSeries (Torus v Ω) := + PowerSeries.mk (fun k=>if k≤n then sectionSolutionCoefficients v Ω C F b l k else 0) +lemma sectionSolution_graded (l : ℕ → Torus v Ω) + (hl : ∀n,l n∈shiftRootGrade v Ω C b n) : + ShiftGraded v Ω C b (sectionSolution v Ω C F b l) := by + intro n + cases n with + | zero => simpa only [sectionSolution,coeff_mk,sectionSolutionCoefficients] using hl 0 + | succ n => + simp only [sectionSolution,coeff_mk,sectionSolutionCoefficients] + exact (shiftRootGrade v Ω C b (n+1)).sub_mem (hl _) (sectionIncoming_graded v Ω C F b _ _) +lemma sectionTruncation_lower (l : ℕ → Torus v Ω) (n k : ℕ) (hk : k≤n) : + coeff k (sectionSolution v Ω C F b l)=coeff k (sectionTruncation v Ω C F b l n) := by + simp only [sectionSolution,sectionTruncation,coeff_mk,ite_eq_left hk] +lemma sectionTruncation_top (l : ℕ → Torus v Ω) (n : ℕ) : + coeff (n+1) (sectionTruncation v Ω C F b l n)=0 := by + simp only [sectionTruncation,coeff_mk,show ¬n+1≤n by omega,ite_false] +lemma sectionSolution_step (l : ℕ → Torus v Ω) (n : ℕ) : + coeff (n+1) (sectionSolution v Ω C F b l)=l (n+1)- + sectionIncoming v Ω C F b (n+1) (sectionTruncation v Ω C F b l n) := by + simp only [sectionSolution,coeff_mk,sectionSolutionCoefficients,sectionTruncation,dite_eq_ite] +lemma sectionSolution_prescription (l : ℕ → Torus v Ω) + (hl : ∀n,l n∈shiftRootGrade v Ω C b n) (n : ℕ) : + sectionIncoming v Ω C F b n (sectionSolution v Ω C F b l)=l n := by + cases n with + | zero => + rw [sectionIncoming_zero v Ω C F b _ (sectionSolution_graded v Ω C F b l hl 0)] + simp only [sectionSolution,coeff_mk,sectionSolutionCoefficients] + | succ n => + have ht : coeff (n+1) (sectionTruncation v Ω C F b l n)∈shiftRootGrade v Ω C b (n+1):=by + rw [sectionTruncation_top]; exact (shiftRootGrade v Ω C b (n+1)).zero_mem + have H:=sectionIncoming_leading v Ω C F b (n+1) + (sectionSolution v Ω C F b l) (sectionTruncation v Ω C F b l n) + (fun k hk=>sectionTruncation_lower v Ω C F b l n k (by omega)) + (sectionSolution_graded v Ω C F b l hl _) ht + rw [sectionTruncation_top,sub_zero,sectionSolution_step] at H + exact sub_left_inj.mp H + +theorem existsUnique_section (l : ℕ → Torus v Ω) + (hl : ∀n,l n∈shiftRootGrade v Ω C b n) : + ∃! X : {X : PowerSeries (Torus v Ω) // ShiftGraded v Ω C b X}, + ∀n,sectionIncoming v Ω C F b n X.val=l n := by + refine ⟨⟨sectionSolution v Ω C F b l,sectionSolution_graded v Ω C F b l hl⟩, + sectionSolution_prescription v Ω C F b l hl,?_⟩ + intro X hX + apply Subtype.ext + apply PowerSeries.ext + intro n + induction n using Nat.strong_induction_on with + | h n ih => + have H:=sectionIncoming_leading v Ω C F b n X.val (sectionSolution v Ω C F b l) + ih (X.property n) (sectionSolution_graded v Ω C F b l hl n) + rw [hX n,sectionSolution_prescription v Ω C F b l hl n,sub_self] at H + exact sub_eq_zero.mp H.symm + +def thetaInitial : PowerSeries (Torus v Ω) := + sectionSolution v Ω C F b (fun n=>coeff n (PowerSeries.C (Torus.X v Ω b))) +def thetaValue (h : M →+ ℝ) : PowerSeries (Torus v Ω) := + sectionValue v Ω C F h (thetaInitial v Ω C F b) +lemma thetaInitial_graded : ShiftGraded v Ω C b (thetaInitial v Ω C F b) := + sectionSolution_graded v Ω C F b _ (ShiftGraded.monomial v Ω C b) +lemma thetaValue_graded (h : M →+ ℝ) : ShiftGraded v Ω C b (thetaValue v Ω C F b h) := + (thetaInitial_graded v Ω C F b).sectionValue v Ω C F h +lemma thetaInitial_prescription (n : ℕ) : + sectionIncoming v Ω C F b n (thetaInitial v Ω C F b)= + coeff n (PowerSeries.C (Torus.X v Ω b)) := + sectionSolution_prescription v Ω C F b _ (ShiftGraded.monomial v Ω C b) n +lemma thetaValue_leading (h : M →+ ℝ) : + constantCoeff (thetaValue v Ω C F b h)=Torus.X v Ω b := by + rw [thetaValue,sectionValue,constant_adjoint _ _ (chartNegative v Ω C h F).property.1] + simp only [thetaInitial,sectionSolution,←coeff_zero_eq_constantCoeff_apply,coeff_mk,sectionSolutionCoefficients,coeff_C,ite_true] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/SectionLineProgram.lean b/lean/OAI/Combinatorics/Chromatic/Walls/SectionLineProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c860476c5b1ce5c5a9a586f4ab379518931ca24a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/SectionLineProgram.lean @@ -0,0 +1,90 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SectionGenericPerturbation + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit FiniteRayGeometry FiniteEventTraversal LaurentPositive WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (Ω:M →+ M →+ ℤ) (C:(I → ℤ) →+ M) +variable (e:M →+ E) (he:Function.Injective e) +variable (B:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB:∀x,B x x=0) +variable (hcomp:∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L:Module.Dual ℝ E) (hdeg:∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in + +lemma section_line_program (F:CompletedPositive LaurentRay.vUnit Ω C) + (N:ℕ) (walls:WallsPositiveThrough Ω C e N F) (h:Module.Dual ℝ E) (r:M) : + ∃ts:List (LineTransfer E), + (∀t∈ts,t.PositiveThrough Ω C e F N r) ∧ + ∀b (X:PowerSeries (Torus LaurentRay.vUnit Ω)),ShiftGraded LaurentRay.vUnit Ω C b X → + coeff N (sectionValue LaurentRay.vUnit Ω C F (h.toAddMonoidHom.comp e) X) r = + coeff N (sectionValue LaurentRay.vUnit Ω C F (incomingCovector Ω r) X) r + + (ts.map (fun t=>t.delta Ω C e F b X N r)).sum := by + have hΩ:∀m,Ω m m=0:=by + intro m; have HH:=hB (e m); rw [hcomp] at HH; exact_mod_cast HH + obtain ⟨k,Hk,Heq⟩:=uniform_section_generic_offset LaurentRay.vUnit Ω C e L hdeg N h (B.flip (e r)) + let dir:=B.flip (e r) + let S:=realRootsThrough e C N + let events:=lineEvents S dir k + let P (a:ℝ):Prop:=∃ts:List (LineTransfer E), + (∀t∈ts,t.PositiveThrough Ω C e F N r) ∧ + ∀b (X:PowerSeries (Torus LaurentRay.vUnit Ω)),ShiftGraded LaurentRay.vUnit Ω C b X → + coeff N (sectionValue LaurentRay.vUnit Ω C F ((k+a • dir).toAddMonoidHom.comp e) X) r = + coeff N (sectionValue LaurentRay.vUnit Ω C F (incomingCovector Ω r) X) r+ + (ts.map (fun t=>t.delta Ω C e F b X N r)).sum + have h0:(0:ℝ)∉events:=section_line_zero_not_event C e N dir k Hk + have hstart:∃a,0≤a ∧ (∀z∈events,z0,∀δ:ℝ,0<δ → δ<ε → P (a+δ) → P (a-δ):=by + intro a ha ha0 + obtain ⟨ε,he,Hε⟩:=section_line_transfer Ω C e he B hB hcomp L hdeg N r F walls k Hk a ha + refine ⟨ε,he,?_⟩ + intro δ hd hδε HP + obtain ⟨t,ht,Ht⟩:=Hε δ hd hδε + obtain ⟨ts,hpos,hid⟩:=HP + refine ⟨t::ts,?_,?_⟩ + · intro t' ht' + rcases List.mem_cons.mp ht' with rfl|ht' + · exact ht + · exact hpos t' ht' + · intro b X hX + rw [Ht b X hX,hid b X hX] + simp only [List.map_cons,List.sum_cons] + ac_rfl + obtain ⟨ts,hpos,hid⟩:=descend events P hstart hcell hstep 0 (le_refl 0) h0 + refine ⟨ts,hpos,?_⟩ + intro b X hX + rw [←Heq F X N le_rfl] + simpa only [zero_smul,add_zero] using hid b X hX +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/SectionRayTransition.lean b/lean/OAI/Combinatorics/Chromatic/Walls/SectionRayTransition.lean new file mode 100644 index 0000000000000000000000000000000000000000..a61eb1d72a06790f92f7278830bd2879bcfb679c --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/SectionRayTransition.lean @@ -0,0 +1,148 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteRayGeometry +import OAI.Combinatorics.Chromatic.Walls.FiniteElementaryAdjoint +import OAI.Combinatorics.Chromatic.QuantumTorus.SectionCharts + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +lemma section_ray_positive_side (F : CompletedPositive v Ω C) + (X : PowerSeries (Torus v Ω)) (N : ℕ) (p : M) (h k H : M →+ ℝ) + (hg : RayGeneric C N p h) (hkp : 0hm (HD (n+1) (by omega) hn m hr) : OnPositiveRay p m).eval k).1.mpr hkp) + intro n hn + rw [section_refinement_through v Ω C h k H F X N hs n hn] + have HE:=adjoint_coeff_congr (chartNegative v Ω C k (chartZero v Ω C h F)).val 1 + (sectionValue v Ω C F h X) (sectionValue v Ω C F h X) n + (fun j hj=>Hneg j (hj.trans hn)) (fun _ _=>rfl) + rw [HE,adjoint_one] +lemma section_ray_negative_side (F : CompletedPositive v Ω C) + (X : PowerSeries (Torus v Ω)) (N : ℕ) (p : M) (h k H : M →+ ℝ) + (hg : RayGeneric C N p h) (hkp : k p<0) + (hs : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h k H m) : + ∀n≤N,coeff n (sectionValue v Ω C F H X)= + coeff n (adjoint (chartZero v Ω C h F).val (sectionValue v Ω C F h X)) := by + have HD:=RayGeneric.ray_supported v Ω C hg F + have Hneg:=chartNegative_of_negative_through v Ω C k (chartZero v Ω C h F) N (by + intro n hn m hm + exact ((by_contra fun hr=>hm (HD (n+1) (by omega) hn m hr) : OnPositiveRay p m).eval k).2.2.mpr hkp) + intro n hn + rw [section_refinement_through v Ω C h k H F X N hs n hn] + exact adjoint_coeff_congr _ _ _ _ n (fun j hj=>Hneg j (hj.trans hn)) (fun _ _=>rfl) +lemma section_ray_crossing (F : CompletedPositive v Ω C) + (X : PowerSeries (Torus v Ω)) (N : ℕ) (p : M) (h k Hplus Hminus : M →+ ℝ) + (hg : RayGeneric C N p h) + (hsplus : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h k Hplus m) + (hsminus : ∀n≤N,∀m,HasRootDegree C n m → LexSigns h (-k) Hminus m) : + (0rfl) + (fun j hj=>(section_ray_positive_side v Ω C F X N p h k Hplus hg hp hsplus j (hj.trans hn)).symm) + · intro hp n hn + rw [section_ray_positive_side v Ω C F X N p h (-k) Hminus hg (by simpa using neg_pos.mpr hp) hsminus n hn] + exact (adjoint_inverse_coeff _ _ _ (chartZero v Ω C h F).property.1 n + (fun j hj=>section_ray_negative_side v Ω C F X N p h k Hplus hg hp hsplus j (hj.trans hn))).symm +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries FiniteRayGeometry PowerSeriesSplit PowerSeriesAdjoint +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (C : (I → ℤ) →+ M) (e : M →+ E) (he : Function.Injective e) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +def ChamberGeneric (N : ℕ) (h : M →+ ℝ) : Prop := + ∀n,0Finset.sum_eq_zero_iff.mp hc i (Finset.mem_univ i)) + subst c + change C (0 : I → ℤ)=p at hcp + rw [map_zero] at hcp + exact hcp.symm + exact hv (by rw [hp0,map_zero,map_zero]) + refine ⟨p,d,hd0,hd,hp,hv,hsa,?_⟩ + intro n hn hnN m hm hm0 + have HH:=H.joint_plane hs (realRoot_mem e C N n hnN m hm) hv a hsa hm0 + apply positive_ray_of_mem_span e he C L hdeg p m d n hd0 hn hp hm + obtain ⟨x,y,hxy⟩:=Submodule.mem_span_pair.mp HH + apply Submodule.mem_span_singleton.mpr + exact ⟨y,by simpa only [smul_zero,zero_add] using hxy⟩ +include hdeg in +lemma section_offset_generic (N : ℕ) (v k : Module.Dual ℝ E) + (H : GenericOffset (realRootsThrough e C N) 0 v k) : + ChamberGeneric C N (k.toAddMonoidHom.comp e) := by + intro n hn hnN m hm + apply H.avoid _ (realRoot_mem e C N n hnN m hm) + simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using realRoot_ne_zero C e L hdeg n hn m hm +lemma section_line_zero_not_event (N : ℕ) (v k : Module.Dual ℝ E) + (H : GenericOffset (realRootsThrough e C N) 0 v k) : + (0:ℝ)∉lineEvents (realRootsThrough e C N) v k := by + intro hh + obtain ⟨s,hs,hv,hs0⟩:=(mem_lineEvents_iff _ _ _ _).mp hh + apply H.avoid s hs _ + · simpa only [zero_smul,add_zero] using hs0 + · simpa only [Submodule.span_zero_singleton,Submodule.mem_bot] using + (show s≠0 from fun h=>hv (by rw [h,map_zero])) +lemma line_covector_add (v k : Module.Dual ℝ E) (a δ : ℝ) : + ((k+(a+δ) • v).toAddMonoidHom.comp e)= + (k+a • v).toAddMonoidHom.comp e+δ • (v.toAddMonoidHom.comp e) := by + ext m + change k (e m)+((a+δ)*v (e m))=(k (e m)+a*v (e m))+δ*v (e m) + ring +lemma line_covector_sub (v k : Module.Dual ℝ E) (a δ : ℝ) : + ((k+(a-δ) • v).toAddMonoidHom.comp e)= + (k+a • v).toAddMonoidHom.comp e+δ • (-(v.toAddMonoidHom.comp e)) := by + ext m + change k (e m)+((a-δ)*v (e m))=(k (e m)+a*v (e m))+δ*(-v (e m)) + ring +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/ShuffleFiltration.lean b/lean/OAI/Combinatorics/Chromatic/Walls/ShuffleFiltration.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f1d55e1fe28cb37e451d6660dedf152a52dccc3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/ShuffleFiltration.lean @@ -0,0 +1,88 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Histories.ShuffleLeafFiltration +import OAI.Combinatorics.Chromatic.QuantumTorus.ProductUnitFiltration +import OAI.Combinatorics.Chromatic.Shuffle.GridShapeFiltration + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic +open SplitTree +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [DecidableEq I] in +private lemma size_positive (d : I → ℕ) (hd : d≠0) : 0<∑ i,d i := by + classical + obtain ⟨i,hi⟩ : ∃ i,d i≠0 := by + by_contra h + push Not at h + exact hd (funext h) + exact Finset.sum_pos' (fun _ _=>Nat.zero_le _) ⟨i,Finset.mem_univ _,Nat.pos_of_ne_zero hi⟩ + +theorem shuffleBUnit_filtered (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + intro d e hN hdθ heθ U V f g hf hg + by_cases hd : d=0 + · subst d + exact shuffleBUnit_filtered_zero_left a c η hc θ e _ U V f g hf hg + by_cases he : e=0 + · subst e + exact shuffleBUnit_filtered_zero_right a c η hc θ d _ U V f g hf hg + have hdθ' : slope c η d=θ := hdθ.resolve_left hd + have heθ' : slope c η e=θ := heθ.resolve_left he + have hde := SlopeArithmetic.add_ne_zero_left d e hd + rw [unitalSourceFiltration_nonzero a c η hc θ (d+e) hde] + apply sourceFiltration_of_binary + · intro t + rw [show hdθ.compatible heθ=Or.inr (Or.inr (hdθ'.trans heθ'.symm)) from rfl, + shuffleBUnit_eq_shuffleB] + exact shuffleB_translation_leaf_degreeCut a c η hc θ d e hd he hdθ' heθ' + (hχ d e hd he hdθ' heθ') U V f g + (by rwa [unitalSourceFiltration_nonzero a c η hc θ d hd] at hf) + (by rwa [unitalSourceFiltration_nonzero a c η hc θ e he] at hg) t + · intro α β hα hβ hsα hsβ h + apply restriction_shuffleBUnit_filtered a c η hc θ d e α β hα hβ hdθ' hsα hsβ _ h + · intro d' e' h' + apply ih (∑ i,α i) _ d' e' (by simp only [h']) + have hp:=size_positive β hβ + have hh : (∑ i,α i)+(∑ i,β i)=N := by + rw [←Finset.sum_add_distrib] + simpa only [Pi.add_apply] using (congrArg (fun x : I → ℕ=>∑ i,x i) h).trans hN + omega + · intro d' e' h' + apply ih (∑ i,β i) _ d' e' (by simp only [h']) + have hp:=size_positive α hα + have hh : (∑ i,α i)+(∑ i,β i)=N := by + rw [←Finset.sum_add_distrib] + simpa only [Pi.add_apply] using (congrArg (fun x : I → ℕ=>∑ i,x i) h).trans hN + omega + · exact hf + · exact hg + +theorem shuffleB_filtered (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + rw [tensorValue_tmul,tensorShuffle_decomposable,shuffleTensorLinear_tmul] + exact (shufflePolynomial_eq a f g).symm + | add f g hf hg => simp only [map_add,hf,hg] + +lemma invariant_transfer_eq (a : I → I → ℕ) (d e : I → ℕ) + (p : MvPolynomial ((Σi,Fin (d i)) ⊕ (Σi,Fin (e i))) ℚ) + (hp : ∀ σ,rename (sumAction (packAction (fun i=>Fin (d i))) + (packAction (fun i=>Fin (e i))) σ) p = p) : + tensorShuffle a p = localizeS (d+e) (shuffleTensorLinear a d e (separateTensor d e p)) := by + rw [← tensorShuffle_tensorValue,tensorValue_separateTensor d e p hp] + +lemma shuffleTensorLinear_mem (a : I → I → ℕ) (d e : I → ℕ) (f : S d ⊗[ℚ] S e) : + shuffleTensorLinear a d e f ∈ shuffleImage a d e := by + induction f using TensorProduct.inductionOn with + | tmul f g => exact Submodule.subset_span ⟨f,g,rfl⟩ + | add f g hf hg => simpa only [map_add] using (shuffleImage a d e).add_mem hf hg + +noncomputable def twoTargetTransfer (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) : + (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂) →ₗ[ℚ] + S (d₁+e₁) ⊗[ℚ] S (d₂+e₂) := + TensorProduct.map (shuffleTensorLinear a d₁ e₁) (shuffleTensorLinear a d₂ e₂) + +@[simp] lemma twoTargetTransfer_tmul (a : I → I → ℕ) (d₁ e₁ d₂ e₂ : I → ℕ) + (f₁ : S d₁) (g₁ : S e₁) (f₂ : S d₂) (g₂ : S e₂) : + twoTargetTransfer a d₁ e₁ d₂ e₂ ((f₁ ⊗ₜ[ℚ] g₁) ⊗ₜ[ℚ] (f₂ ⊗ₜ[ℚ] g₂)) = + shufflePolynomial a f₁ g₁ ⊗ₜ[ℚ] shufflePolynomial a f₂ g₂ := by + simp [twoTargetTransfer] + +lemma shuffleImage_le_destabilizing (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d e : I → ℕ) (hd : d≠0) (he : e≠0) (hμ : μ d > μ (d+e)) : + shuffleImage a d e ≤ destabilizingSpace a μ (d+e) := by + apply Submodule.span_le.mpr + rintro p ⟨f,g,rfl⟩ + exact Submodule.subset_span ⟨d,e,rfl,f,g,hd,he,hμ,rfl⟩ + +lemma quotient_shuffleTensorLinear_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d e : I → ℕ) (hd : d≠0) (he : e≠0) (hμ : μ d > μ (d+e)) + (f : S d ⊗[ℚ] S e) : quotientAlg a μ (d+e) (shuffleTensorLinear a d e f) = 0 := by + exact Ideal.Quotient.eq_zero_iff_mem.mpr + ((shuffleImage_le_destabilizing a μ d e hd he hμ) (shuffleTensorLinear_mem a d e f)) + +lemma quotient_twoTargetTransfer_zero (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + (d₁ e₁ d₂ e₂ : I → ℕ) + (h : (d₁≠0 ∧ e₁≠0 ∧ μ d₁ > μ (d₁+e₁)) ∨ + (d₂≠0 ∧ e₂≠0 ∧ μ d₂ > μ (d₂+e₂))) + (f : (S d₁ ⊗[ℚ] S e₁) ⊗[ℚ] (S d₂ ⊗[ℚ] S e₂)) : + quotientTensor a μ (d₁+e₁) (d₂+e₂) (twoTargetTransfer a d₁ e₁ d₂ e₂ f) = 0 := by + induction f using TensorProduct.inductionOn with + | tmul f g => + simp only [twoTargetTransfer, TensorProduct.map_tmul, quotientTensor, + Algebra.TensorProduct.map_tmul] + rcases h with ⟨hd,he,hμ⟩ | ⟨hd,he,hμ⟩ + · rw [quotient_shuffleTensorLinear_zero a μ d₁ e₁ hd he hμ,TensorProduct.zero_tmul] + · rw [quotient_shuffleTensorLinear_zero a μ d₂ e₂ hd he hμ,TensorProduct.tmul_zero] + | add f g hf hg => + change (quotientTensor a μ (d₁+e₁) (d₂+e₂)).toLinearMap (twoTargetTransfer a d₁ e₁ d₂ e₂ (f+g)) = 0 + rw [(twoTargetTransfer a d₁ e₁ d₂ e₂).map_add, (quotientTensor a μ (d₁+e₁) (d₂+e₂)).toLinearMap.map_add] + exact (congrArg₂ (· + ·) hf hg).trans (add_zero 0) + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/SignedMultiplicity.lean b/lean/OAI/Combinatorics/Chromatic/Walls/SignedMultiplicity.lean new file mode 100644 index 0000000000000000000000000000000000000000..d964999e776e0a37bd8b1e5b46eb8379d2f9cff3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/SignedMultiplicity.lean @@ -0,0 +1,123 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.UnitIndexEnergy + +namespace OAI + +section +section +namespace ElementaryPositivity.SignedMultiplicity +variable {α : Type*} [DecidableEq α] + +lemma pairwise_iff_count (even : α → Prop) (w : List α) : + w.Pairwise (fun x y=>x=y → even x) ↔ ∀a,¬even a → w.count a≤1 := by + induction w with + | nil => simp + | cons x w ih => + rw [List.pairwise_cons,ih] + constructor + · rintro ⟨hh,ht⟩ a ha + by_cases hx : x=a + · subst a + have hn : x∉w := fun he=>ha (hh x he rfl) + simp only [List.count_cons_self, List.count_eq_zero_of_not_mem hn] + omega + · simpa [List.count_cons,hx,eq_comm] using ht a ha + · intro h + constructor + · intro y hy hxy + subst y + by_contra hn + have hb:=h x hn + have hp : 0x=y → even x)} +abbrev Selection (even : α → Prop) := {m : Multiset α // ∀a,¬even a → m.count a≤1} + +def wordSelectionEquiv (even : α → Prop) : Word even ≃ Selection even where + toFun w:=⟨(w.val:Multiset α),by + simpa only [Multiset.coe_count] using (pairwise_iff_count even w.val).mp w.property.2⟩ + invFun m:=⟨m.val.sort (·≤·),Multiset.pairwise_sort _ _,by + apply (pairwise_iff_count even _).mpr + intro a ha + have hh:=m.property a ha + simpa only [←Multiset.coe_count,Multiset.sort_eq] using hh⟩ + left_inv w:=by + apply Subtype.ext + change (w.val:Multiset α).sort (·≤·)=w.val + exact List.Perm.eq_of_pairwise' (Multiset.pairwise_sort (w.val:Multiset α) (·≤·)) w.property.1 + (Quotient.exact (Multiset.sort_eq (w.val:Multiset α) (·≤·))) + right_inv m:=Subtype.ext (Multiset.sort_eq m.val (·≤·)) + +lemma selection_sum {β : Type*} [AddCommMonoid β] (even : α → Prop) (f : α → β) (w : Word even) : + (((wordSelectionEquiv even w).val).map f).sum=(w.val.map f).sum := rfl + +abbrev CountSelection (even : α → Prop) := {f : α →₀ ℕ // ∀a,¬even a → f a≤1} + +noncomputable def selectionCountEquiv (even : α → Prop) : Selection even ≃ CountSelection even := + Multiset.toFinsupp.toEquiv.subtypeEquiv (fun m=>by + rfl) + +noncomputable def wordCountEquiv (even : α → Prop) : Word even ≃ CountSelection even := + (wordSelectionEquiv even).trans (selectionCountEquiv even) +end Ordered +end ElementaryPositivity.SignedMultiplicity +end +namespace ElementaryPositivity.UnitSelections +noncomputable section +def unitEnergy (a n : ℕ) (k : ℤ) (f : UnitIndex a n) : ℤ := + (n:ℤ)*k-2*unitWeight a n f +end +end ElementaryPositivity.UnitSelections + +section +namespace ElementaryPositivity.SignedMultiplicity +variable {A B : Type*} + +lemma multiset_count_sum [DecidableEq A] {T : Type*} [AddCommMonoid T] + (m : Multiset A) (e : A → T) : + m.toFinsupp.sum (fun x n=>n • e x)=(m.map e).sum := by + induction m using Multiset.induction_on with + | empty => simp + | cons x m ih => + change (({x}:Multiset A)+m).toFinsupp.sum _=((({x}:Multiset A)+m).map e).sum + rw [Multiset.toFinsupp_add] + rw [Finsupp.sum_add_index' (h:=fun x n=>n • e x) (by simp) + (by intro a b c; exact add_nsmul (e a) b c)] + simp only [Multiset.toFinsupp_singleton,Multiset.map_add,Multiset.sum_add, + Multiset.map_singleton,Multiset.sum_singleton,ih] + rw [Finsupp.sum_single_index (h:=fun x n=>n • e x) (by simp),one_nsmul] + +def countReindex (e : A ≃ B) (evenA : A → Prop) (evenB : B → Prop) + (he : ∀a,evenA a ↔ evenB (e a)) : CountSelection evenA ≃ CountSelection evenB := + (Finsupp.equivCongrLeft e).subtypeEquiv (fun f=>by + constructor + · intro h b hb + have ha : ¬evenA (e.symm b) := by simpa only [he,Equiv.apply_symm_apply] using hb + exact h (e.symm b) ha + · intro h a ha + have hb : ¬evenB (e a):=by simpa only [he] using ha + have hh:=h (e a) hb + simpa only [Finsupp.equivCongrLeft_apply,Finsupp.equivMapDomain_apply, + Equiv.symm_apply_apply] using hh) + +lemma countReindex_sum (e : A ≃ B) (evenA : A → Prop) (evenB : B → Prop) + (he : ∀a,evenA a ↔ evenB (e a)) (f : CountSelection evenA) + {T : Type*} [AddCommMonoid T] (energy : B → T) : + (countReindex e evenA evenB he f).val.sum (fun b n=>n • energy b)= + f.val.sum (fun a n=>n • energy (e a)) := + Finsupp.sum_equivMapDomain e f.val (fun b n=>n • energy b) +end ElementaryPositivity.SignedMultiplicity +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/SimpleAdjointFiber.lean b/lean/OAI/Combinatorics/Chromatic/Walls/SimpleAdjointFiber.lean new file mode 100644 index 0000000000000000000000000000000000000000..821c577d5af565fb7be1048b16a397881d210736 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/SimpleAdjointFiber.lean @@ -0,0 +1,206 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TorusAdjointExpansion +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationRootMap +import OAI.Combinatorics.Chromatic.GradedAlgebra.SimpleBinomial + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddCommGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommGroup +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance : Sub (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toSub + +def simpleOriented (pos : Bool) (p : M) : PowerSeries (Torus LaurentRay.vUnit Ω) := + if pos then normalizedSimple Ω p else invOfUnit (normalizedSimple Ω p) 1 + +def sideSign (pos : Bool) : ℤ := if pos then 1 else -1 +lemma sideSign_neg (pos : Bool) : sideSign (!pos)= -sideSign pos := by cases pos <;> rfl +lemma simpleOriented_support (hΩ : ∀m,Ω m m=0) (pos : Bool) (p m x : M) + (N : ℕ) (htrend : 0≤ sideSign pos*Ω p m) + (hx : coeff N (adjoint (simpleOriented Ω pos p) + (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m))) x≠0) : + (N:ℤ)≤ sideSign pos*Ω p m ∧ x=m+N • p := by + let t:=(sideSign pos*Ω p m).toNat + have ht : (t:ℤ)=sideSign pos*Ω p m:=Int.toNat_of_nonneg htrend + have HG : N≤t ∧ x=m+N • p:=by + cases pos + · apply normalizedSimple_inverse_adjoint_support Ω hΩ p m x t N ?_ hx + simpa only [sideSign,Bool.false_eq_true,ite_false,neg_one_mul,Int.neg_neg] using congrArg Neg.neg ht.symm + · apply normalizedSimple_adjoint_support Ω hΩ p m x t N ?_ hx + simpa only [sideSign,ite_true,one_mul] using ht.symm + exact ⟨by rw [←ht]; exact_mod_cast HG.1,HG.2⟩ + +include hcoord in +lemma simpleOriented_adjoint_fiber (hΩ : ∀m,Ω m m=0) (pos : Bool) + (A : PowerSeries (Torus LaurentRay.vUnit Ω)) (N : ℕ) (n : ℤ) + (hA : ∀j≤N,coeff j A∈rootGrade LaurentRay.vUnit Ω C j) + (htrend : ∀j≤N,∀m,coeff j A m≠0 → 0≤ sideSign pos*Ω (simpleRoot C pc) m) + (hbound : ∀j≤N,∀m,coeff j A m≠0 → nonpDegree coord pc m≤n → + m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + ∀x,coeff N (adjoint (simpleOriented Ω pos (simpleRoot C pc)) A) x≠0 → + nonpDegree coord pc x≤n → + x∈fiberCone coord pc (mutationPairing Ω C pc) (-sideSign pos) := by + classical + intro x hx hxn + rw [coeff_adjoint_expansion,torus_ring_eval_sum] at hx + obtain ⟨j,hj,hterm⟩:=Finset.exists_ne_zero_of_sum_ne_zero hx + have hjN : j≤N:=by have H:=Finset.mem_range.mp hj; omega + rw [adjoint_torus_expansion] at hterm + obtain ⟨m,hm,hterm⟩:=Finset.exists_ne_zero_of_sum_ne_zero hterm + have hmA : coeff j A m≠0:=(mul_ne_zero_iff.mp hterm).1 + have hmAd:=(mul_ne_zero_iff.mp hterm).2 + have HS:=simpleOriented_support Ω hΩ pos (simpleRoot C pc) m x (N-j) + (htrend j hjN m hmA) hmAd + have hroot : HasRootDegree C j m:=by + by_contra hh + exact hmA (hA j hjN m hh) + have hw : nonpDegree coord pc x=nonpDegree coord pc m:=by + rw [HS.2,map_add,map_nsmul,nonpDegree_simple_self C coord hcoord,nsmul_zero,add_zero] + rw [hw] at hxn + rw [HS.2] + exact fiber_shift_bound Ω C coord hcoord pc hΩ hroot (sideSign pos) (N-j) HS.1 + (hbound j hjN m hmA hxn) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) + +def mutationLinearPiece (pos : Bool) : M →+ M := + if pos then AddMonoidHom.id M else mutationShear Ω (simpleRoot C pc) + +omit [Fintype I] in +include hcoord in +lemma mutationLinearPiece_coordinates (pos : Bool) (m : M) : + coord (mutationLinearPiece Ω C pc pos m)= + if pos then coord m else coord m-Ω (simpleRoot C pc) m • Pi.single pc 1 := by + cases pos + · simp only [mutationLinearPiece,Bool.false_eq_true,ite_false,mutationShear, + AddMonoidHom.coe_mk,ZeroHom.coe_mk,map_sub,map_zsmul] + congr 1 + change _ • coord (C (Pi.single pc 1))=_ + rw [hcoord] + · rfl + +include hcoord in +lemma mutatedCoordinate_off (pos : Bool) (m : M) (i : I) (hi : i≠pc) : + mutatedCoordinates Ω C coord pc (mutationLinearPiece Ω C pc pos m) i=coord m i := by + change mutatedCoefficientMap pc (mutationPairing Ω C pc) + (coord (mutationLinearPiece Ω C pc pos m)) i=_ + rw [mutatedCoefficientMap_off pc _ _ i hi,mutationLinearPiece_coordinates Ω C coord hcoord] + cases pos <;> simp [hi] + +include hcoord in +lemma mutatedCoordinate_at (hΩ : ∀m,Ω m m=0) (pos : Bool) {n : ℕ} {m : M} + (hm : HasRootDegree C n m) : + mutatedCoordinates Ω C coord pc (mutationLinearPiece Ω C pc pos m) pc= + fiberUpper coord pc (mutationPairing Ω C pc) (sideSign pos) m-coord m pc := by + change mutatedCoefficientMap pc (mutationPairing Ω C pc) + (coord (mutationLinearPiece Ω C pc pos m)) pc=_ + rw [mutatedCoefficientMap_at] + have HH : (∑j∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc j)* + coord (mutationLinearPiece Ω C pc pos m) j)= + ∑j∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc j)*coord m j:=by + apply Finset.sum_congr rfl + intro j hj + rw [mutationLinearPiece_coordinates Ω C coord hcoord] + cases pos <;> simp [(Finset.mem_erase.mp hj).1] + rw [HH,mutationLinearPiece_coordinates Ω C coord hcoord] + cases pos + · simp only [Bool.false_eq_true,ite_false,Pi.sub_apply,Pi.smul_apply,Pi.single_eq_same, + smul_eq_mul,mul_one,sideSign] + have Hflip:=fiberUpper_flip coord pc (mutationPairing Ω C pc) 1 m + rw [←root_pairing_coordinates Ω C coord hcoord pc hΩ hm] at Hflip + change fiberUpper coord pc (mutationPairing Ω C pc) (-1) m= + fiberUpper coord pc (mutationPairing Ω C pc) 1 m+1*Ω (simpleRoot C pc) m at Hflip + rw [Hflip] + change -(coord m pc-Ω (simpleRoot C pc) m)+ + (∑j∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc j)*coord m j)=_ + simp only [fiberUpper,AddMonoidHom.coe_mk,ZeroHom.coe_mk,neg_mul,one_mul] + ring + · simp only [ite_true,sideSign] + change -coord m pc+(∑j∈Finset.univ.erase pc,max 0 (-mutationPairing Ω C pc j)*coord m j)=_ + simp only [fiberUpper,AddMonoidHom.coe_mk,ZeroHom.coe_mk,neg_mul,one_mul] + ring + +include hcoord in +lemma mutated_nonpDegree (pos : Bool) (m : M) : + nonpDegree (mutatedCoordinates Ω C coord pc) pc (mutationLinearPiece Ω C pc pos m)= + nonpDegree coord pc m := by + change (∑i∈Finset.univ.erase pc,mutatedCoordinates Ω C coord pc (mutationLinearPiece Ω C pc pos m) i)=_ + apply Finset.sum_congr rfl + intro i hi + exact mutatedCoordinate_off Ω C coord hcoord pc pos m i (Finset.mem_erase.mp hi).1 + +include hcoord in +lemma mutationLinearPiece_span {n : ℕ} {m : M} (hm : HasRootDegree C n m) (pos : Bool) : + C (coord (mutationLinearPiece Ω C pc pos m))=mutationLinearPiece Ω C pc pos m := by + have hc : C (coord m)=m:=by + obtain ⟨d,hd,hcd,hem⟩:=root_coordinates C coord hcoord hm + rw [←hem,hcoord] + rw [mutationLinearPiece_coordinates Ω C coord hcoord] + cases pos + · simp only [Bool.false_eq_true,ite_false,map_sub,map_zsmul,hc,mutationLinearPiece,mutationShear, + AddMonoidHom.coe_mk,ZeroHom.coe_mk,simpleRoot] + · exact hc + +include hcoord in +lemma mutated_span {n : ℕ} {m : M} (hm : HasRootDegree C n m) (pos : Bool) : + mutatedRoots Ω C pc (mutatedCoordinates Ω C coord pc (mutationLinearPiece Ω C pc pos m))= + mutationLinearPiece Ω C pc pos m := by + change C (mutatedCoefficientMap pc (mutationPairing Ω C pc) + (mutatedCoefficientMap pc (mutationPairing Ω C pc) (coord (mutationLinearPiece Ω C pc pos m))))=_ + rw [mutatedCoefficientMap_involutive] + exact mutationLinearPiece_span Ω C coord hcoord pc hm pos + +include hcoord in +lemma mutation_root_image (hΩ : ∀m,Ω m m=0) (pos : Bool) {n : ℕ} {m : M} + (hm : HasRootDegree C n m) + (hb : m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + ∃d : ℕ,HasRootDegree (mutatedRoots Ω C pc) d (mutationLinearPiece Ω C pc pos m) ∧ + (d:ℤ)=nonpDegree coord pc m+ + fiberUpper coord pc (mutationPairing Ω C pc) (sideSign pos) m-coord m pc := by + let q:=mutatedCoordinates Ω C coord pc (mutationLinearPiece Ω C pc pos m) + have hq : ∀i,0≤q i:=by + intro i + by_cases hi : i=pc + · subst i + change 0 ≤ mutatedCoordinates Ω C coord pc (mutationLinearPiece Ω C pc pos m) pc + rw [mutatedCoordinate_at Ω C coord hcoord pc hΩ pos hm] + exact sub_nonneg.mpr hb.2 + · change 0 ≤ mutatedCoordinates Ω C coord pc (mutationLinearPiece Ω C pc pos m) i + rw [mutatedCoordinate_off Ω C coord hcoord pc pos m i hi] + obtain ⟨a,ha,hac,he⟩:=root_coordinates C coord hcoord hm + rw [hac] + exact Int.natCast_nonneg _ + refine ⟨∑i,(q i).toNat,⟨fun i=>(q i).toNat,rfl,?_⟩,?_⟩ + · have he : (fun i=>((q i).toNat:ℤ))=q:=funext (fun i=>Int.toNat_of_nonneg (hq i)) + rw [he] + exact mutated_span Ω C coord hcoord pc hm pos + · rw [Nat.cast_sum] + simp only [Int.toNat_of_nonneg (hq _)] + rw [←Finset.sum_erase_add _ _ (Finset.mem_univ pc)] + have ha : q pc=fiberUpper coord pc (mutationPairing Ω C pc) (sideSign pos) m-coord m pc:= + mutatedCoordinate_at Ω C coord hcoord pc hΩ pos hm + have ho : (∑i∈Finset.univ.erase pc,q i)=nonpDegree coord pc m:= + mutated_nonpDegree Ω C coord hcoord pc pos m + rw [ha,ho] + ring +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/SimpleIncomingData.lean b/lean/OAI/Combinatorics/Chromatic/Walls/SimpleIncomingData.lean new file mode 100644 index 0000000000000000000000000000000000000000..a640464d06300277e98897041d731bf01a108045 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/SimpleIncomingData.lean @@ -0,0 +1,119 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.GlobalWallPositive +import OAI.Combinatorics.Chromatic.Walls.OffCutJoint + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) + +def simpleDatum (i : I) : WallUnitDatum M := ⟨1,simpleRoot C i,0,-1⟩ +def simpleIncomingList : List (WallUnitDatum M) := (Finset.univ.toList).map (simpleDatum C) +lemma simpleDatum_allowed (i : I) : (simpleDatum C i).Allowed C (fun _=>True) := + ⟨Nat.zero_lt_one,simpleRoot_degree C i,True.intro⟩ +lemma simpleIncomingList_allowed : ∀u∈simpleIncomingList C,u.Allowed C (fun _=>True) := by + intro u hu + obtain ⟨i,hi,rfl⟩:=List.mem_map.mp hu + exact simpleDatum_allowed C i + +def simpleTotalTransport : CompletedPositive LaurentRay.vUnit Ω C := literalTotalTransport Ω C (simpleIncomingList C) +lemma simpleTotalTransport_positive_prescription (hΩ : ∀m,Ω m m=0) : + PositiveIncomingPrescription Ω C (simpleTotalTransport Ω C) := + literalTotalTransport_prescription Ω C hΩ _ (simpleIncomingList_allowed C) + +omit [Fintype I] in +include hcoord in +lemma simpleRoot_coordinates (i j : I) : coord (simpleRoot C i) j= (Pi.single i 1 : I → ℤ) j := by + exact congrFun (hcoord _) j +include hcoord in +lemma nonpDegree_simple_self (pc : I) : nonpDegree coord pc (simpleRoot C pc)=0 := by + change (∑i∈Finset.univ.erase pc,coord (simpleRoot C pc) i)=0 + apply Finset.sum_eq_zero + intro i hi + rw [simpleRoot_coordinates C coord hcoord] + simp [(Finset.mem_erase.mp hi).1] +include hcoord in +lemma simple_off_fiber (pc i : I) (hi : i≠pc) (α : I → ℤ) (σ : ℤ) : + simpleRoot C i∈fiberCone coord pc α σ := by + have hc : coord (simpleRoot C i) pc=0:=by rw [simpleRoot_coordinates C coord hcoord]; simp [hi.symm] + constructor + · rw [hc] + · rw [hc] + change 0≤∑j∈Finset.univ.erase pc,max 0 (-σ*α j)*coord (simpleRoot C i) j + apply Finset.sum_nonneg + intro j hj + apply mul_nonneg (le_max_left _ _) + rw [simpleRoot_coordinates C coord hcoord] + by_cases hji : j=i + · subst j; simp + · simp [hji] +include hcoord in +lemma positive_nonp_not_simple_ray (pc : I) (r : M) (hr : 0m∈fiberCone coord pc α σ) := by + classical + refine ⟨(simpleIncomingList C).filter (fun u=>OnPositiveRay r u.root),?_,rfl⟩ + intro u hu + have hu':=List.mem_filter.mp hu + obtain ⟨i,hi,rfl⟩:=List.mem_map.mp hu'.1 + have hri : OnPositiveRay r (simpleRoot C i):=by exact of_decide_eq_true hu'.2 + have hip : i≠pc:=by intro hh; subst i; exact positive_nonp_not_simple_ray C coord hcoord pc r hr hri + exact ⟨Nat.zero_lt_one,simpleRoot_degree C i,simple_off_fiber C coord hcoord pc i hip α σ⟩ +include hcoord in +lemma simpleIncomingCompleted_fiber (pc : I) (r : M) (hr : 0 + rw [coeff_zero_eq_constantCoeff,(literalIncomingCompleted Ω C _ _ r).property.1] + exact (supportedSubring LaurentRay.vUnit Ω _).one_mem + | succ j=> + exact literalRootProducts_strictSupport Ω C (fun m=>m∈fiberCone coord pc α σ) + (fun a b ha hb=>(fiberCone coord pc α σ).add_mem ha hb) + (simpleIncomingRay_fiber Ω C coord hcoord pc r hr α σ) j + +omit [DecidableEq I] in +lemma literalTotalTransport_ray_prescription (hΩ : ∀m,Ω m m=0) + (l : List (WallUnitDatum M)) (hl : ∀u∈l,u.Allowed C (fun _=>True)) (r : M) : + ∀n m,OnPositiveRay r m → + coeff n (FormalLog.log (chartZero LaurentRay.vUnit Ω C (incomingCovector Ω m) + (literalTotalTransport Ω C l)).val) m= + coeff n (FormalLog.log (literalIncomingCompleted Ω C l hl r).val) m := by + classical + intro n m hm + cases n with + | zero=>simp only [coeff_zero_eq_constantCoeff,FormalLog.log_constant,Finsupp.zero_apply] + | succ n=> + by_cases hroot : HasRootDegree C (n+1) m + · have H:=congrArg (fun x : Torus LaurentRay.vUnit Ω=>x m) + (incomingSolution_prescription LaurentRay.vUnit Ω C hΩ _ (literalIncomingLog_graded Ω C l) n) + rw [incomingCoefficient_apply,ite_eq_left hroot,literalIncomingLog_apply,ite_eq_left hroot] at H + change coeff (n+1) (FormalLog.log (chartZero LaurentRay.vUnit Ω C (incomingCovector Ω m) + (literalTotalTransport Ω C l)).val) m=coeff (n+1) (FormalLog.log (literalIncomingRay Ω l r)) m + rw [literalIncomingRay_eq Ω l hm] + exact H + · rw [root_graded_log LaurentRay.vUnit Ω C _ (n+1) m hroot, + root_graded_log LaurentRay.vUnit Ω C (literalIncomingCompleted Ω C l hl r) (n+1) m hroot] +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/SimpleIncomingElement.lean b/lean/OAI/Combinatorics/Chromatic/Walls/SimpleIncomingElement.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef64602cd7b6ac8ce0ec3891510adfb1d2524fd2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/SimpleIncomingElement.lean @@ -0,0 +1,195 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.SimpleBinomial +import OAI.Combinatorics.Chromatic.GradedAlgebra.PureFaceLog + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +omit [Fintype I] in +include hcoord in +lemma simpleRoot_ray_iff (i : I) : OnPositiveRay (simpleRoot C pc) (simpleRoot C i) ↔ i=pc := by + constructor + · rintro ⟨a,b,ha,hb,he⟩ + by_contra hi + have HH:=congrArg (fun m=>coord m pc) he + simp only [map_nsmul,Pi.smul_apply,simpleRoot_coordinates C coord hcoord] at HH + simp only [Pi.single_eq_of_ne (Ne.symm hi),Pi.single_eq_same,nsmul_eq_mul,mul_one] at HH + omega + · rintro rfl + exact ⟨1,1,by omega,by omega,rfl⟩ +include hcoord in +lemma literalIncoming_simple : + literalIncomingRay Ω (simpleIncomingList C) (simpleRoot C pc)=normalizedSimple Ω (simpleRoot C pc) := by + classical + unfold literalIncomingRay simpleIncomingList + rw [List.filter_map] + have hf : (Finset.univ.toList : List I).filter + ((fun u : WallUnitDatum M=>decide (OnPositiveRay (simpleRoot C pc) u.root)) ∘ simpleDatum C)=[pc] := by + apply List.perm_singleton.mp + apply (List.perm_ext_iff_of_nodup ((Finset.nodup_toList _).filter _) (by simp)).mpr + intro i + simp only [List.mem_filter,Finset.mem_toList,Finset.mem_univ,true_and,Function.comp_apply, + simpleDatum,List.mem_singleton] + constructor + · intro hh; exact (simpleRoot_ray_iff C coord hcoord pc i).mp (of_decide_eq_true hh) + · intro hh; exact decide_eq_true ((simpleRoot_ray_iff C coord hcoord pc i).mpr hh) + rw [hf,List.map_singleton,List.map_singleton,List.prod_singleton,simpleDatum_value] +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries RootTruncation WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (coord : M →+ (I → ℤ)) (hcoord : ∀d,coord (C d)=d) (pc : I) +include hcoord in +lemma nonp_zero_of_simple_ray {m : M} (hm : OnPositiveRay (simpleRoot C pc) m) : + nonpDegree coord pc m=0 := by + obtain ⟨a,b,ha,hb,he⟩:=hm + have HH:=congrArg (nonpDegree coord pc) he + rw [map_nsmul,map_nsmul,nonpDegree_simple_self C coord hcoord,nsmul_zero,nsmul_eq_mul] at HH + exact (mul_eq_zero.mp HH).resolve_left (by exact_mod_cast Nat.ne_of_gt ha) + +lemma pureFaceSeries_eq_through (F : PowerSeries (Torus LaurentRay.vUnit Ω)) (N : ℕ) + (hF : ∀j≤N,∀m,coeff j F m≠0 → nonpDegree coord pc m=0) : + ∀j≤N,coeff j (pureFaceSeries Ω coord pc F)=coeff j F := by + intro j hj + apply Finsupp.ext + intro m + rw [pureFaceSeries_apply] + split_ifs with hh + · rfl + · exact (not_ne_iff.mp (fun he=>hh (hF j hj m he))).symm + +include hcoord in +lemma pureFace_simpleTransport_value (hΩ : ∀m,Ω m m=0) : + (pureFace Ω C coord pc (simpleTotalTransport Ω C)).val=normalizedSimple Ω (simpleRoot C pc) := by + rw [pureFace_simpleTransport Ω C coord hcoord pc hΩ] + exact literalIncoming_simple Ω C coord hcoord pc + +include hcoord in +lemma pure_simple_wall (hΩ : ∀m,Ω m m=0) (N : ℕ) (h : M →+ ℝ) + (hg : RayGeneric C N (simpleRoot C pc) h) : + ∀j≤N,coeff j (chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C)).val= + coeff j (normalizedSimple Ω (simpleRoot C pc)) := by + let F:=chartZero LaurentRay.vUnit Ω C h (simpleTotalTransport Ω C) + have HF:=pureFace_chartZero Ω C coord hcoord pc h hg.1 (simpleTotalTransport Ω C) + have HR : ∀j≤N,∀m,coeff j F.val m≠0 → nonpDegree coord pc m=0:=by + intro j hj m hm + cases j with + | zero => + rw [coeff_zero_eq_constantCoeff_apply,F.property.1] at hm + have hm0 : m=0:=by + by_contra hh + exact hm (Finsupp.single_eq_of_ne hh) + rw [hm0,map_zero] + | succ j=> + have hmroot : HasRootDegree C (j+1) m:=by by_contra hh; exact hm (F.property.2 _ m hh) + have hmzero : h m=0:=(chart_three_support LaurentRay.vUnit Ω C h _).2.1 j m hm + exact nonp_zero_of_simple_ray C coord hcoord pc (hg.2 (j+1) (by omega) hj m hmroot hmzero) + intro j hj + rw [←pureFaceSeries_eq_through Ω coord pc F.val N HR j hj] + change coeff j (pureFace Ω C coord pc F).val=_ + rw [HF,pureFace_simpleTransport_value Ω C coord hcoord pc hΩ] + +include hcoord in +lemma pure_joint_factor (hΩ : ∀m,Ω m m=0) (N : ℕ) (k h : M →+ ℝ) + (hk : k (simpleRoot C pc)=0) (hh : h (simpleRoot C pc)=0) + (hRay : ∀j,j+1≤N → ∀m, + coeff (j+1) (chartZero LaurentRay.vUnit Ω C h + (chartZero LaurentRay.vUnit Ω C k (simpleTotalTransport Ω C))).val m≠0 → + OnPositiveRay (simpleRoot C pc) m) : + ∀j≤N,coeff j (chartZero LaurentRay.vUnit Ω C h + (chartZero LaurentRay.vUnit Ω C k (simpleTotalTransport Ω C))).val= + coeff j (normalizedSimple Ω (simpleRoot C pc)) := by + let F:=chartZero LaurentRay.vUnit Ω C h + (chartZero LaurentRay.vUnit Ω C k (simpleTotalTransport Ω C)) + have HR : ∀j≤N,∀m,coeff j F.val m≠0 → nonpDegree coord pc m=0:=by + intro j hj m hm + cases j with + | zero=> + rw [coeff_zero_eq_constantCoeff_apply,F.property.1] at hm + have hm0 : m=0:=by by_contra hh; exact hm (Finsupp.single_eq_of_ne hh) + rw [hm0,map_zero] + | succ j=>exact nonp_zero_of_simple_ray C coord hcoord pc (hRay j hj m hm) + intro j hj + rw [←pureFaceSeries_eq_through Ω coord pc F.val N HR j hj] + change coeff j (pureFace Ω C coord pc F).val=_ + rw [pureFace_chartZero Ω C coord hcoord pc h hh,pureFace_chartZero Ω C coord hcoord pc k hk, + pureFace_simpleTransport_value Ω C coord hcoord pc hΩ] +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +def completedOne : CompletedPositive v Ω C := + ⟨1,by simp,FormalLog.graded_one _ (rootGrade_one v Ω C)⟩ +def completedMul (F G : CompletedPositive v Ω C) : CompletedPositive v Ω C := + ⟨F.val*G.val,by simp only [map_mul,F.property.1,G.property.1,mul_one], + FormalLog.graded_multiply _ (rootGrade_mul v Ω C) _ _ F.property.2 G.property.2⟩ +def completedConjugate (F G : CompletedPositive v Ω C) : CompletedPositive v Ω C := + completedMul v Ω C (completedMul v Ω C F G) (completedInverse v Ω C F) +lemma chartZero_right_negative (h : M →+ ℝ) (G H : CompletedPositive v Ω C) (N : ℕ) + (hH : ∀j,j+1≤N → ∀m,coeff (j+1) H.val m≠0 → h m<0) : + ∀j≤N,coeff j (chartZero v Ω C h (completedMul v Ω C G H)).val= + coeff j (chartZero v Ω C h G).val := by + have HG:=chart_three_support v Ω C h G + have HU:=chart_three_truncated_unique v Ω C h (completedMul v Ω C G H) + (chartPositive v Ω C h G).val (chartZero v Ω C h G).val + ((chartNegative v Ω C h G).val*H.val) N + (chartPositive v Ω C h G).property.1 (chartZero v Ω C h G).property.1 + (by simp only [map_mul,(chartNegative v Ω C h G).property.1,H.property.1,mul_one]) + (by change _*(_*H.val)=G.val*H.val; rw [←mul_assoc,chart_three_factorization]) + (fun j _=>HG.1 j) (fun j _=>HG.2.1 j) (by + intro j hj m hm + by_contra hh + exact hm (strict_mul_through v Ω (fun m=>h m<0) + (fun a b ha hb=>by simpa only [map_add] using add_neg ha hb) + (chartNegative v Ω C h G).val H.val N + (chartNegative v Ω C h G).property.1 H.property.1 + (fun j hj m hm=>by by_contra hv; exact hm (HG.2.2 j m hv)) + (fun j hj m hm=>by by_contra hv; exact hm (hH j hj m hv)) j hj m hh)) + exact fun j hj=>(HU j hj).2.1.symm +lemma chartZero_left_positive (h : M →+ ℝ) (H G : CompletedPositive v Ω C) (N : ℕ) + (hH : ∀j,j+1≤N → ∀m,coeff (j+1) H.val m≠0 → 00by simpa only [map_add] using add_pos ha hb) + H.val (chartPositive v Ω C h G).val N + H.property.1 (chartPositive v Ω C h G).property.1 + (fun j hj m hm=>by by_contra hv; exact hm (hH j hj m hv)) + (fun j hj m hm=>by by_contra hv; exact hm (HG.1 j m hv)) j hj m hh)) + (fun j _=>HG.2.1 j) (fun j _=>HG.2.2 j) + exact fun j hj=>(HU j hj).2.1.symm +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/SquarefreeBlocks.lean b/lean/OAI/Combinatorics/Chromatic/Walls/SquarefreeBlocks.lean new file mode 100644 index 0000000000000000000000000000000000000000..e1ed249eef8e6b2e20b0543eb0964c2352a62dcc --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/SquarefreeBlocks.lean @@ -0,0 +1,110 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.SquarefreeBlocks +open scoped BigOperators +open Classical +noncomputable section +variable {V:Type*} [DecidableEq V] +variable {n r:ℕ} (b:Fin n ↪ V) + +def target : V → ℤ:=∑j:Fin n,Pi.single (b j) 1 + +def vector (s:Fin r → Finset V) : V → ℤ:=∑i:Fin r,∑x∈s i,Pi.single x 1 + +lemma target_apply (x:V) : target b x=if x∈Set.range b then 1 else 0 := by + unfold target + simp only [Finset.sum_apply,Pi.single_apply] + by_cases h:x∈Set.range b + · obtain ⟨j,rfl⟩:=h + rw [ite_eq_left (Set.mem_range_self j)] + rw [Finset.sum_eq_single j] + · simp + · intro k hk hkj + rw [ite_eq_right (fun h=>hkj (b.injective h.symm))] + · simp + · rw [ite_eq_right h] + apply Finset.sum_eq_zero + intro j hj + exact ite_eq_right (fun hj=>h ⟨j,hj.symm⟩) + +lemma vector_apply (s:Fin r → Finset V) (x:V) : + vector s x=((Finset.univ.filter (fun i=>x∈s i)).card:ℤ) := by + unfold vector + simp only [Finset.sum_apply,Pi.single_apply] + simp only [Finset.sum_ite_eq,Finset.sum_boole] + +lemma membership_unique (s:Fin r → Finset V) (hs:vector s=target b) (j:Fin n) : + ∃!i:Fin r,b j∈s i := by + have H:=congrFun hs (b j) + rw [vector_apply,target_apply,ite_eq_left (Set.mem_range_self j)] at H + have hc:(Finset.univ.filter (fun i=>b j∈s i)).card=1:=by exact_mod_cast H + obtain ⟨i,hi⟩:=Finset.card_eq_one.mp hc + refine ⟨i,?_,?_⟩ + · have h:i∈Finset.univ.filter (fun i=>b j∈s i):=by rw [hi]; simp + exact (Finset.mem_filter.mp h).2 + · intro k hk + have h:k∈Finset.univ.filter (fun i=>b j∈s i):=Finset.mem_filter.mpr ⟨Finset.mem_univ _,hk⟩ + rw [hi,Finset.mem_singleton] at h + exact h + +lemma membership_range (s:Fin r → Finset V) (hs:vector s=target b) (i:Fin r) (x:V) (hx:x∈s i) : + x∈Set.range b := by + by_contra hn + have H:=congrFun hs x + rw [vector_apply,target_apply,ite_eq_right hn] at H + have hc:(Finset.univ.filter (fun i=>x∈s i)).card=0:=by exact_mod_cast H + have hh:=Finset.card_eq_zero.mp hc + have hm:i∈Finset.univ.filter (fun i=>x∈s i):=Finset.mem_filter.mpr ⟨Finset.mem_univ _,hx⟩ + rw [hh] at hm + exact Finset.notMem_empty _ hm + +def coloring (s:{s:Fin r → Finset V // vector s=target b}) : Fin n → Fin r:= + fun j=>(membership_unique b s.val s.property j).choose +lemma coloring_mem (s:{s:Fin r → Finset V // vector s=target b}) (j:Fin n) : + b j∈s.val (coloring b s j):=(membership_unique b s.val s.property j).choose_spec.1 +lemma coloring_eq (s:{s:Fin r → Finset V // vector s=target b}) (j:Fin n) (i:Fin r) (h:b j∈s.val i) : + coloring b s j=i:=((membership_unique b s.val s.property j).choose_spec.2 i h).symm + +def blocks (κ:Fin n → Fin r) (i:Fin r) : Finset V:= + (Finset.univ.filter (fun j=>κ j=i)).map b +omit [DecidableEq V] in +lemma mem_blocks (κ:Fin n → Fin r) (i:Fin r) (x:V) : + x∈blocks b κ i ↔ ∃j,κ j=i ∧ b j=x := by simp [blocks] +lemma blocks_vector (κ:Fin n → Fin r) : vector (blocks b κ)=target b := by + ext x + simp only [vector,blocks,Finset.sum_apply,Finset.sum_map,Finset.sum_filter] + rw [Finset.sum_comm] + simp only [ite_apply,Pi.zero_apply] + change (∑j:Fin n,∑i:Fin r,if κ j=i then (Pi.single (b j) (1:ℤ) : V → ℤ) x else 0)=_ + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true] + simp only [target,Finset.sum_apply] + +def equiv : {s:Fin r → Finset V // vector s=target b} ≃ (Fin n → Fin r) where + toFun:=coloring b + invFun κ:=⟨blocks b κ,blocks_vector b κ⟩ + left_inv s:=by + apply Subtype.ext + funext i + apply Finset.ext + intro x + rw [mem_blocks] + constructor + · rintro ⟨j,hj,rfl⟩ + rw [←hj] + exact coloring_mem b s j + · intro hx + obtain ⟨j,rfl⟩:=membership_range b s.val s.property i x hx + exact ⟨j,coloring_eq b s j i hx,rfl⟩ + right_inv κ:=by + funext j + apply coloring_eq + exact (mem_blocks b κ (κ j) (b j)).mpr ⟨j,rfl,rfl⟩ +end +end ElementaryPositivity.SquarefreeBlocks + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/StationaryIntegerSequences.lean b/lean/OAI/Combinatorics/Chromatic/Walls/StationaryIntegerSequences.lean new file mode 100644 index 0000000000000000000000000000000000000000..a43255bbd51fde09a321f0a5de783d7149b05e53 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/StationaryIntegerSequences.lean @@ -0,0 +1,298 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.IncomingEquality + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics + +lemma period_total_nonpos (B K : ℕ → ℤ) (hB : ∀ n, 0 ≤ B n) + (hK : Monotone K) (step : ∀ n, B (n+1) = B n - K (n+1)) (n : ℕ) : + K n ≤ 0 := by + by_contra hn + have hk : 1 ≤ K n := by omega + have hb : ∀ t : ℕ, B (n+t) ≤ B n - (t:ℤ) := by + intro t + induction t with + | zero => simp + | succ t ih => + have hm := hK (show n ≤ n+t+1 by omega) + have hs := step (n+t) + simp only [Nat.add_succ, Nat.add_zero, Nat.cast_succ] at * + omega + have H := hb ((B n).toNat+1) + have H0 := hB (n+((B n).toNat+1)) + have Hn := Int.toNat_of_nonneg (hB n) + omega + +lemma monotone_int_stabilizes (a : ℕ → ℤ) (ha : Monotone a) + (hb : ∃ b, ∀ n, a n ≤ b) : ∃ N, ∀ n, N ≤ n → a n = a N := by + obtain ⟨v,⟨N,hN⟩,hv⟩ := Int.exists_greatest_of_bdd + (P := fun z => ∃ n, a n = z) + (by obtain ⟨b,hb⟩ := hb; exact ⟨b,fun z ⟨n,hn⟩ => hn ▸ hb n⟩) + ⟨a 0,0,rfl⟩ + refine ⟨N,fun n hn => le_antisymm ?_ (ha hn)⟩ + rw [hN] + exact hv (a n) ⟨n,rfl⟩ + +lemma finite_coordinates_stabilize {ι : Type*} [Fintype ι] + (a : ℕ → ι → ℤ) (ha : ∀ i, Monotone (fun n => a n i)) + (hs : ∀ n, ∑ i, a n i ≤ 0) : + ∃ N, ∀ n, N ≤ n → ∀ i, a n i = a N i := by + classical + have hb : ∀ i, ∃ b, ∀ n, a n i ≤ b := by + intro i + refine ⟨-∑ j ∈ Finset.univ.erase i, a 0 j,fun n => ?_⟩ + have H := Finset.sum_le_sum (s := Finset.univ.erase i) + (fun j _ => ha j (show 0 ≤ n by omega)) + have he := Finset.sum_erase_add (Finset.univ : Finset ι) (a n) (Finset.mem_univ i) + have Hn := hs n + dsimp only at H he + omega + choose N hN using fun i => monotone_int_stabilizes (fun n => a n i) (ha i) (hb i) + refine ⟨Finset.univ.sup N,fun n hn i => ?_⟩ + have hi : N i ≤ Finset.univ.sup N := Finset.le_sup (f := N) (Finset.mem_univ i) + rw [hN i n (hi.trans hn),hN i _ hi] + +lemma nonnegative_affine_slope (a b : ℤ) (h : ∃ N : ℕ, ∀ L, N ≤ L → + 0 ≤ a + (L:ℤ)*b) : 0 ≤ b := by + obtain ⟨N,hN⟩ := h + by_contra hb + have hb' : b ≤ -1 := by omega + let L := max N (a.toNat+1) + have hL := hN L (le_max_left _ _) + have hLa : a < (L:ℤ) := by + have hh : a.toNat+1 ≤ L := le_max_right _ _ + have ha : a ≤ (a.toNat:ℤ) := by omega + omega + have hL0 : (0:ℤ) ≤ L := Int.natCast_nonneg L + nlinarith + +lemma concave_nonpositive_zero (D : ℕ) (K : ℕ → ℤ) + (h0 : K 0 = 0) (hD : K D = 0) + (hn : ∀ i, i ≤ D → K i ≤ 0) + (hc : ∀ i, 0 < i → i < D → 0 ≤ 2*K i-K (i-1)-K (i+1)) : + ∀ i, i ≤ D → K i = 0 := by + obtain ⟨j,hj,hmin⟩ := Finset.exists_min_image (Finset.range (D+1)) K + (by exact ⟨0,by simp⟩) + have hjD : j ≤ D := by + have h := Finset.mem_range.mp hj + omega + have hm : ∀ i, i ≤ D → K j ≤ K i := by + intro i hi + exact hmin i (Finset.mem_range.mpr (by omega)) + have propagate : ∀ i, i ≤ D → K i = K j → K j = 0 := by + intro i + induction i using Nat.strong_induction_on with + | h i ih => + intro hi he + by_cases hz : i = 0 + · simpa [hz,h0] using he.symm + by_cases hd : i = D + · simpa [hd,hD] using he.symm + have H := hc i (by omega) (by omega) + have Hl := hm (i-1) (by omega) + have Hr := hm (i+1) (by omega) + have he' : K (i-1) = K j := by omega + exact ih (i-1) (by omega) (by omega) he' + have hj0 := propagate j hjD rfl + intro i hi + have hh := hm i hi + have hh' := hn i hi + omega +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open ElementaryPositivity.QuantumTorus +variable {n : ℕ} {B : Type*} [Fintype B] [DecidableEq B] +abbrev Vertex (n : ℕ) (B : Type*) := Sum (Fin (n+1)) B +abbrev Lattice (n : ℕ) (B : Type*) := Vertex n B → ℤ + +def anchor (i : Fin (n+1)) : Lattice n B := Pi.single (Sum.inl i) 1 +def bridge (b : B) : Lattice n B := Pi.single (Sum.inr b) 1 + +def delta (level : B → Fin n) (b : B) : Lattice n B := + anchor (level b).succ - anchor (level b).castSucc + +def eventRoot (level : B → Fin n) (L : ℕ) (b : B) : Lattice n B := + bridge b - anchor (level b).castSucc + (L:ℤ) • delta level b + +def levelTotal (level : B → Fin n) (i : Fin n) : Lattice n B →+ ℤ where + toFun m := ∑ b, if level b = i then m (Sum.inr b) else 0 + map_zero' := by simp + map_add' m m' := by + change (∑ b, if level b = i then m (Sum.inr b)+m' (Sum.inr b) else 0) = _ + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro b _ + split_ifs <;> simp + +def cutContains (level : B → Fin n) (i : Fin n) : Vertex n B → Prop + | Sum.inl a => a.val ≤ i.val + | Sum.inr b => (level b).val ≤ i.val + +instance cutContains_decidable (level : B → Fin n) (i : Fin n) : + DecidablePred (cutContains level i) := fun a => by + cases a <;> unfold cutContains <;> infer_instance + +def cutPrefix (level : B → Fin n) (i : Fin n) : Lattice n B →+ ℤ where + toFun m := ∑ a, if cutContains level i a then m a else 0 + map_zero' := by simp + map_add' m m' := by + change (∑ a, if cutContains level i a then m a+m' a else 0) = _ + rw [←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro b _ + split_ifs <;> simp + +@[simp] lemma cutPrefix_single (level : B → Fin n) (i : Fin n) (a : Vertex n B) (z : ℤ) : + cutPrefix level i (Pi.single a z) = if cutContains level i a then z else 0 := by + classical + change (∑ v, if cutContains level i v then Pi.single a z v else 0) = _ + rw [Finset.sum_eq_single a] + · simp + · intro b _ hb + simp [hb] + · simp + +@[simp] lemma levelTotal_anchor (level : B → Fin n) (i : Fin n) (a : Fin (n+1)) : + levelTotal level i (anchor a) = 0 := by + simp [levelTotal,anchor] +@[simp] lemma levelTotal_bridge (level : B → Fin n) (i : Fin n) (b : B) : + levelTotal level i (bridge b) = if level b = i then 1 else 0 := by + change (∑ c, if level c = i then bridge b (Sum.inr c) else 0) = _ + rw [Finset.sum_eq_single b] + · simp [bridge] + · intro c _ hc + simp [bridge,hc] + · simp + +omit [DecidableEq B] in +lemma total_levels (level : B → Fin n) (m : Lattice n B) : + ∑ i, levelTotal level i m = ∑ b, m (Sum.inr b) := by + simp only [levelTotal,AddMonoidHom.coe_mk,ZeroHom.coe_mk] + rw [Finset.sum_comm] + simp + +omit [Fintype B] in +@[simp] lemma eventRoot_bridge (level : B → Fin n) (L : ℕ) (b c : B) : + eventRoot level L b (Sum.inr c) = if c = b then 1 else 0 := by + simp [eventRoot,bridge,anchor,delta,Pi.single_apply] + +@[simp] lemma cutPrefix_eventRoot (level : B → Fin n) (i : Fin n) (L : ℕ) (b : B) : + cutPrefix level i (eventRoot level L b) = if level b = i then -(L:ℤ) else 0 := by + simp only [eventRoot,delta,map_add,map_sub,map_zsmul,anchor,bridge,cutPrefix_single, + cutContains,Fin.val_succ,Fin.val_castSucc,smul_eq_mul] + by_cases h : level b = i + · simp [h] + · have hne : (level b).val ≠ i.val := fun hh => h (Fin.ext hh) + split_ifs <;> simp_all <;> omega + +@[simp] lemma levelTotal_eventRoot (level : B → Fin n) (i : Fin n) (L : ℕ) (b : B) : + levelTotal level i (eventRoot level L b) = if level b = i then 1 else 0 := by + simp only [eventRoot,delta,map_add,map_sub,map_zsmul,levelTotal_bridge,levelTotal_anchor, + sub_self,smul_zero,add_zero,sub_zero] + +def periodFunctional (level : B → Fin n) (i : Fin n) (L : ℕ) : Lattice n B →+ ℤ := + cutPrefix level i + (L:ℤ) • levelTotal level i + +@[simp] lemma periodFunctional_eventRoot (level : B → Fin n) (i : Fin n) (L : ℕ) (b : B) : + periodFunctional level i L (eventRoot level L b) = 0 := by + simp only [periodFunctional,AddMonoidHom.add_apply,AddMonoidHom.zsmul_apply, + cutPrefix_eventRoot,levelTotal_eventRoot,smul_eq_mul] + split_ifs <;> ring + +variable (Ω : Lattice n B →+ Lattice n B →+ ℤ) + +def rotate (level : B → Fin n) (L : ℕ) (m : Lattice n B) (b : B) : Lattice n B := + mutationIncomingLabel Ω (eventRoot level L b) m + +def period (level : B → Fin n) (cycle : List B) (L : ℕ) (m : Lattice n B) : Lattice n B := + cycle.foldl (rotate Ω level L) m + +def history (level : B → Fin n) (cycle : List B) (m : Lattice n B) : ℕ → Lattice n B + | 0 => m + | L+1 => period Ω level cycle L (history level cycle m L) + +omit [Fintype B] in +lemma rotate_bridge_mono (level : B → Fin n) (L : ℕ) (m : Lattice n B) (b c : B) : + m (Sum.inr c) ≤ rotate Ω level L m b (Sum.inr c) := by + simp only [rotate,mutationIncomingLabel,Pi.add_apply,Pi.smul_apply,eventRoot_bridge, + smul_eq_mul] + split_ifs <;> simp + +omit [Fintype B] in +lemma period_bridge_mono (level : B → Fin n) (cycle : List B) (L : ℕ) (m : Lattice n B) (c : B) : + m (Sum.inr c) ≤ period Ω level cycle L m (Sum.inr c) := by + induction cycle generalizing m with + | nil => exact le_rfl + | cons b bs ih => + exact (rotate_bridge_mono Ω level L m b c).trans (ih (rotate Ω level L m b)) + +lemma periodFunctional_rotate (level : B → Fin n) (i : Fin n) (L : ℕ) (m : Lattice n B) (b : B) : + periodFunctional level i L (rotate Ω level L m b) = periodFunctional level i L m := by + simp only [rotate,mutationIncomingLabel,map_add,map_zsmul,periodFunctional_eventRoot, + smul_zero,add_zero] + +lemma periodFunctional_period (level : B → Fin n) (i : Fin n) (cycle : List B) + (L : ℕ) (m : Lattice n B) : + periodFunctional level i L (period Ω level cycle L m) = periodFunctional level i L m := by + induction cycle generalizing m with + | nil => rfl + | cons b bs ih => + change periodFunctional level i L (period Ω level bs L (rotate Ω level L m b)) = _ + rw [ih,periodFunctional_rotate] + +omit [Fintype B] in +lemma history_bridge_mono (level : B → Fin n) (cycle : List B) (m : Lattice n B) (b : B) : + Monotone (fun L => history Ω level cycle m L (Sum.inr b)) := by + apply monotone_nat_of_le_succ + intro L + exact period_bridge_mono Ω level cycle L _ b + +lemma history_total_mono (level : B → Fin n) (cycle : List B) (m : Lattice n B) (i : Fin n) : + Monotone (fun L => levelTotal level i (history Ω level cycle m L)) := by + intro L L' h + apply Finset.sum_le_sum + intro b _ + split_ifs + · exact history_bridge_mono Ω level cycle m b h + · rfl + +def cutDeficit (level : B → Fin n) (i : Fin n) (N L : ℕ) (m : Lattice n B) : ℤ := + (N:ℤ)-periodFunctional level i L m + +lemma history_deficit_step (level : B → Fin n) (cycle : List B) (m : Lattice n B) + (i : Fin n) (N L : ℕ) : + cutDeficit level i N (L+1) (history Ω level cycle m (L+1)) = + cutDeficit level i N L (history Ω level cycle m L) - + levelTotal level i (history Ω level cycle m (L+1)) := by + have h := periodFunctional_period Ω level i cycle L (history Ω level cycle m L) + change periodFunctional level i L (history Ω level cycle m (L+1)) = _ at h + simp only [cutDeficit,periodFunctional,AddMonoidHom.add_apply,AddMonoidHom.zsmul_apply, + smul_eq_mul,Nat.cast_add,Nat.cast_one] at * + linear_combination -h + +lemma history_total_nonpos (level : B → Fin n) (cycle : List B) (m : Lattice n B) + (N : ℕ) (hs : ∀ L i, 0 ≤ cutDeficit level i N L (history Ω level cycle m L)) + (L : ℕ) (i : Fin n) : levelTotal level i (history Ω level cycle m L) ≤ 0 := + period_total_nonpos (fun L => cutDeficit level i N L (history Ω level cycle m L)) + (fun L => levelTotal level i (history Ω level cycle m L)) (fun L => hs L i) + (history_total_mono Ω level cycle m i) (history_deficit_step Ω level cycle m i N) L + +lemma history_bridge_stabilizes (level : B → Fin n) (cycle : List B) (m : Lattice n B) + (N : ℕ) (hs : ∀ L i, 0 ≤ cutDeficit level i N L (history Ω level cycle m L)) : + ∃ T, ∀ L, T ≤ L → ∀ b, history Ω level cycle m L (Sum.inr b) = + history Ω level cycle m T (Sum.inr b) := by + apply finite_coordinates_stabilize (fun L b => history Ω level cycle m L (Sum.inr b)) + (history_bridge_mono Ω level cycle m) + intro L + rw [←total_levels level] + exact Finset.sum_nonpos (fun i _ => history_total_nonpos Ω level cycle m N hs L i) +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/StringPositiveFactor.lean b/lean/OAI/Combinatorics/Chromatic/Walls/StringPositiveFactor.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd96b48da33c2a9decf5d8a6a02ecd7a4b4ff2b6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/StringPositiveFactor.lean @@ -0,0 +1,87 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TorusPositive +import OAI.Combinatorics.Chromatic.GradedAlgebra.StringStripSeries +import OAI.Combinatorics.Chromatic.GradedAlgebra.WeightedPushTwist + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity RawShuffle EnergyLaurent QuantumTorus WallUnits WeightedTorusSeries +open PowerSeries +noncomputable section +variable {S I : Type*} [Fintype I] [DecidableEq I] +variable (a : S → ℕ) (t : S → ℕ) (dim : S → (I→ℕ)) (k : S → ℤ) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) +variable (D : AddSubmonoid (I→ℕ)) (hdim : ∀s,dim s∈D) + +def stringSeries (d : I→ℕ) : LaurentSeries ℚ := series _ (he d) + +omit [Fintype I] [DecidableEq I] in +include hdim in +lemma stringSeries_support (d : I→ℕ) (hd : stringSeries a dim k he d≠0) : d∈D := by + classical + by_contra H + let : IsEmpty (StringCounts a dim d) := ⟨fun x=>H (x.property ▸ + countDimension_mem _ _ D (fun s=>hdim s.1) x.val)⟩ + apply hd + ext j + rw [stringSeries,series_coeff] + simp + +variable (τ : (I→ℕ) →+ ℤ) (hτ : ∀s,(t s:ℤ)=τ (dim s)) +omit [Fintype I] [DecidableEq I] in +include hdim in +lemma stripSeries_support (d : I→ℕ) (hd : stripSeries a t dim k τ hτ he d≠0) : d∈D := by + classical + by_contra H + let : IsEmpty (StripCounts a t dim d) := ⟨fun x=>H (x.property ▸ + countDimension_mem _ _ D (fun s=>hdim s.1) x.val)⟩ + apply hd + ext j + rw [stripSeries,series_coeff] + simp + +variable {M : Type*} [AddCommGroup M] +variable (Ω : M →+ M →+ ℤ) (P : (I→ℕ) →+ M) +variable (hiso : ∀d∈D,∀e∈D,Ω (P d) (P e)=0) +variable (m : M) (htwist : ∀d,τ d=Ω (P d) m) + +include hiso hdim htwist hτ in +lemma stringSeries_twist_convolution : + (fun d=>stringSeries a dim k he d*↑(LaurentRay.vUnit^(2*Ω (P d) m)))= + convolution LaurentRay.vUnit Ω P (stripSeries a t dim k τ hτ he) + (stringSeries a dim k he) := by + funext d + rw [LaurentRay.vUnit_zpow,←htwist] + rw [convolution_of_isotropic_support LaurentRay.vUnit Ω P _ _ + (fun x y hx hy=>hiso x (stripSeries_support a t dim k he D hdim τ hτ x hx) + y (stringSeries_support a dim k he D hdim y hy))] + exact stringStrip_scaled a t dim k τ hτ he d + +variable (w : I → ℕ) [Fact (∀i,0LaurentPositive.series _ (stripEnergy_admissible a t dim k τ hτ he d))) + +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/StringRay.lean b/lean/OAI/Combinatorics/Chromatic/Walls/StringRay.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d840bac24a14f2cf66b92385885ebc6773778d3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/StringRay.lean @@ -0,0 +1,114 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.StringPositiveFactor + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity EnergyLaurent RawShuffle WeightedTorusSeries QuantumTorus WallUnits PowerSeries +noncomputable section +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : ℕ) (δ : I→ℕ) (k : ℤ) + +def oneStringEquiv : (Σn,UnitIndex a n) ≃ CountSelection (fun _ : PUnit×ℕ=>a≠0) := + (unitRowCount a).trans (countReindex (Equiv.punitProd ℕ).symm _ _ (fun _=>Iff.rfl)) + +omit [Fintype I] [DecidableEq I] in +lemma oneString_dimension (q : Σn,UnitIndex a n) : + countDimension (fun _ : PUnit×ℕ=>a≠0) (fun _=>δ) (oneStringEquiv a q)=q.1 • δ := by + dsimp only [countDimension,oneStringEquiv,Equiv.trans_apply] + rw [countReindex_sum] + change (unitRowCount a q).val.sum (fun _ n=>n • δ)=_ + rw [Finsupp.sum,←Finset.sum_smul] + change ((unitRowCount a q).val.sum (fun _ n=>n)) • δ=_ + rw [unitRowCount_sum] + +lemma oneString_energy (q : Σn,UnitIndex a n) : + countEnergy (fun _ : PUnit×ℕ=>a≠0) (fun x=>k-2*(x.2:ℤ)) (oneStringEquiv a q)= + unitEnergy a q.1 k q.2 := by + dsimp only [countEnergy,oneStringEquiv,Equiv.trans_apply] + rw [countReindex_sum] + exact unitRowCount_energy a q.1 k q.2 + +omit [Fintype I] [DecidableEq I] in +lemma nsmul_dimension_injective (hδ : δ≠0) : Function.Injective (fun n:ℕ=>n • δ) := by + obtain ⟨i,hi⟩:=Function.ne_iff.mp hδ + intro n m H + have HE:=congrArg (fun d:I→ℕ=>d i) H + change n*δ i=m*δ i at HE + exact Nat.eq_of_mul_eq_mul_right (Nat.pos_of_ne_zero hi) HE + +variable (hδ : δ≠0) + +def unitSigmaFibre (n : ℕ) : UnitIndex a n ≃ {q : Σm,UnitIndex a m // q.1=n} where + toFun f:=⟨⟨n,f⟩,rfl⟩ + invFun q:=q.property ▸ q.val.2 + left_inv f:=rfl + right_inv q:=by + rcases q with ⟨⟨m,f⟩,h⟩ + cases h + rfl + +def oneStringDimensionEquiv (n : ℕ) : UnitIndex a n ≃ + StringCounts (fun _:PUnit=>a) (fun _=>δ) (n • δ) := + (unitSigmaFibre a n).trans ((oneStringEquiv a).subtypeEquiv (fun q=>by + change q.1=n ↔ countDimension _ _ (oneStringEquiv a q)=n • δ + rw [oneString_dimension] + exact (nsmul_dimension_injective δ hδ).eq_iff.symm)) + +variable (he : ∀d,Admissible (stringEnergy (fun _:PUnit=>a) (fun _=>δ) (fun _=>k) d)) + +omit [Fintype I] [DecidableEq I] in +include hδ in +lemma oneStringSeries_nsmul (n : ℕ) : + stringSeries (fun _:PUnit=>a) (fun _=>δ) (fun _=>k) he (n • δ)=indexedUnitSeries a n k := by + symm + apply series_equiv _ _ (oneStringDimensionEquiv a δ hδ n) + intro f + exact oneString_energy a k ⟨n,f⟩ + +omit [Fintype I] [DecidableEq I] in +lemma oneStringSeries_off (d : I→ℕ) (hd : ∀n:ℕ,n • δ≠d) : + stringSeries (fun _:PUnit=>a) (fun _=>δ) (fun _=>k) he d=0 := by + let : IsEmpty (StringCounts (fun _:PUnit=>a) (fun _=>δ) d) := ⟨fun f=>by + let q:=(oneStringEquiv a).symm f.val + apply hd q.1 + rw [←oneString_dimension a δ q] + dsimp only [q] + rw [Equiv.apply_symm_apply] + exact f.property⟩ + ext j + rw [stringSeries,series_coeff] + simp only [HahnSeries.coeff_zero,Nat.cast_eq_zero] + exact Nat.card_eq_zero.mpr (Or.inl (inferInstance : IsEmpty _)) +end +end ElementaryPositivity.UnitSelections + +end +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity RawShuffle EnergyLaurent QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : ℕ) (δ : I→ℕ) (k : ℤ) (hδ : δ≠0) +variable (he : ∀d,Admissible (stringEnergy (fun _:PUnit=>a) (fun _=>δ) (fun _=>k) d)) +variable (w : I→ℕ) [Fact (∀i,0a) (fun _=>δ) (fun _=>k) he)= + weightedRay LaurentRay.vUnit Ω (WeightedTorusSeries.weight w δ) (P δ) + (PowerSeries.map LaurentRay.atInfinity (indexedUnit a k)) := by + apply push_on_ray + · intro n + rw [oneStringSeries_nsmul a δ k hδ he,coeff_map,indexedUnit_literal_expansion] + · exact oneStringSeries_off a δ k he +end +end ElementaryPositivity.UnitSelections + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/StringReorderingEnergy.lean b/lean/OAI/Combinatorics/Chromatic/Walls/StringReorderingEnergy.lean new file mode 100644 index 0000000000000000000000000000000000000000..c40e13c3cdedbeaba53790a523a81a316e86e666 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/StringReorderingEnergy.lean @@ -0,0 +1,92 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteStringReordering + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic +attribute [local instance] Classical.propDecidable +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) + +def inputShift (d : I → ℕ) : ℤ := ∑ i,(d i:ℤ)*(κ i+1-a i i) +omit [DecidableEq I] in +@[simp] lemma inputShift_zero : inputShift a κ (0 : I → ℕ)=0 := by simp [inputShift] +omit [DecidableEq I] in +lemma inputShift_add (d e : I → ℕ) : inputShift a κ (d+e)=inputShift a κ d+inputShift a κ e := by + simp [inputShift,add_mul,Finset.sum_add_distrib] + +def normalizedEnergy (d : I → ℕ) (k : ℤ) : ℤ := inputShift a κ d-eulerForm a d d-2*k + +omit [DecidableEq I] in +lemma normalizedEnergy_product (d e : I → ℕ) (k m : ℤ) : + normalizedEnergy a κ (d+e) (k+m-eulerForm a d e)= + normalizedEnergy a κ d k+normalizedEnergy a κ e m+(eulerForm a d e-eulerForm a e d) := by + simp only [normalizedEnergy,inputShift_add,eulerForm_add_left,eulerForm_add_right] + ring + +variable (c η : I → ℝ) (hc : ∀ i,0inputShift a κ (w i).1.val)).sum := by + induction l with + | nil => simp [wordWeight] + | cons i l ih => + change inputShift a κ ((w i).1.val+(wordWeight c η hc θ w l).1.val)=_ + rw [inputShift_add,ih] + rfl + +lemma stringWordEnergy (l : StringPBWIndex a c η hc θ) : + normalizedEnergy a κ (stringPBWGrade a c η hc θ l).1.1.val + (stringPBWGrade a c η hc θ l).2= + (l.val.map (fun i=>stringStartParameter a κ c η hc θ i-2*i.2.1)).sum := by + have H:=wordPolynomialDegree_shift a c η hc θ + (fun i : GlobalStringIndex a c η hc θ=>i.1.val) (globalStringPolynomialDegree a c η hc θ) l.val + change inputShift a κ (wordWeight c η hc θ _ l.val).1.val- + eulerForm a (wordWeight c η hc θ _ l.val).1.val (wordWeight c η hc θ _ l.val).1.val- + 2*wordPolynomialDegree a c η hc θ _ (globalStringPolynomialDegree a c η hc θ) l.val=_ + rw [sub_sub,add_comm (eulerForm a _ _),H,inputShift_word] + have E : ∀ j : List (GlobalStringIndex a c η hc θ), + (j.map (fun i=>inputShift a κ i.1.val.1.val)).sum - + (j.map (fun i=>2*globalStringPolynomialDegree a c η hc θ i+ + eulerForm a i.1.val.1.val i.1.val.1.val)).sum = + (j.map (fun i=>stringStartParameter a κ c η hc θ i-2*i.2.1)).sum := by + intro j + induction j with + | nil => simp + | cons i j ih => + simp only [List.map_cons,List.sum_cons] + have H := stringLetterEnergy a κ c η hc θ i + dsimp only [normalizedEnergy] at H + linear_combination ih + H + exact E l.val + +noncomputable def stringSelectionEquiv : + StringPBWIndex a c η hc θ ≃ + ElementaryPositivity.SignedSelection (fun i : GlobalStringIndex a c η hc θ=> + globalColorSign a c η hc θ i.1.val i.1.val=1) := + ElementaryPositivity.signedWordSelectionEquiv _ +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/StringRootClosure.lean b/lean/OAI/Combinatorics/Chromatic/Walls/StringRootClosure.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c9db182689bde43209bfc7e06b7c33d3e5ff538 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/StringRootClosure.lean @@ -0,0 +1,46 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.StringLiteralClosure + +namespace OAI + +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity RawShuffle EnergyLaurent QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {S I J M : Type*} [Fintype I] [DecidableEq I] [Fintype J] [AddCommGroup M] +variable (a : S→ℕ) (dim : S→(I→ℕ)) (k : S→ℤ) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) +variable (D : AddSubmonoid (I→ℕ)) (hdim : ∀s,dim s∈D) (h0 : ∀s,dim s≠0) +variable (w : I→ℕ) [Fact (∀i,0f.property (.inl a) ha⟩, + ⟨(Finsupp.sumFinsuppEquivProdFinsupp f.val).2,fun b hb=>f.property (.inr b) hb⟩⟩ + invFun fg:=⟨fg.1.val.sumElim fg.2.val,by + intro x hx + cases x with + | inl a=>exact fg.1.property a hx + | inr b=>exact fg.2.property b hx⟩ + left_inv f:=by + apply Subtype.ext + exact Finsupp.sumFinsuppEquivProdFinsupp.symm_apply_apply f.val + right_inv fg:=by + apply Prod.ext + · apply Subtype.ext + exact congrArg Prod.fst (Finsupp.sumFinsuppEquivProdFinsupp.apply_symm_apply (fg.1.val,fg.2.val)) + · apply Subtype.ext + exact congrArg Prod.snd (Finsupp.sumFinsuppEquivProdFinsupp.apply_symm_apply (fg.1.val,fg.2.val)) + +lemma countSum_sum {T : Type*} [AddCommMonoid T] + (f : CountSelection (Sum.elim evenA evenB)) (e : A ⊕ B → T) : + f.val.sum (fun x n=>n • e x)= + ((countSumEquiv evenA evenB f).1).val.sum (fun a n=>n • e (.inl a))+ + ((countSumEquiv evenA evenB f).2).val.sum (fun b n=>n • e (.inr b)) := by + have H:=Finsupp.sumFinsuppEquivProdFinsupp.symm_apply_apply f.val + change ((Finsupp.sumFinsuppEquivProdFinsupp f.val).1.sumElim + (Finsupp.sumFinsuppEquivProdFinsupp f.val).2)=f.val at H + conv_lhs=>rw [←H] + exact Finsupp.sum_sumElim _ _ _ +end +end ElementaryPositivity.SignedMultiplicity + +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity +noncomputable section +variable {S : Type*} (a : S → ℕ) (t : S → ℕ) + +abbrev HeadLevel := Σs,Fin (t s) + +def levelCutEquiv : S×ℕ ≃ HeadLevel t ⊕ (S×ℕ) where + toFun x:=if h:x.2(x.1,x.2.val)) + (fun x : S×ℕ=>(x.1,x.2+t x.1)) x + left_inv x:=by + dsimp only + split_ifs with h + · rfl + · change (x.1,x.2-t x.1+t x.1)=x + exact Prod.ext rfl (Nat.sub_add_cancel (Nat.le_of_not_gt h)) + right_inv x:=by + cases x with + | inl x=> + dsimp only [Sum.elim_inl] + rw [dite_eq_left x.2.isLt] + | inr x=> + dsimp only [Sum.elim_inr] + rw [dite_eq_right (show ¬x.2+t x.1a x.1≠0) + (fun x : S×ℕ=>a x.1≠0) (levelCutEquiv t x) := by + dsimp only [levelCutEquiv,Equiv.coe_fn_mk] + split_ifs <;> rfl + +def stringStripEquiv : CountSelection (fun x : S×ℕ=>a x.1≠0) ≃ + CountSelection (fun x : HeadLevel t=>a x.1≠0) × + CountSelection (fun x : S×ℕ=>a x.1≠0) := + (countReindex (levelCutEquiv t) _ _ (levelCut_even a t)).trans + (countSumEquiv _ _) + +lemma stringStrip_sum {T : Type*} [AddCommMonoid T] + (f : CountSelection (fun x : S×ℕ=>a x.1≠0)) (e : S×ℕ → T) : + f.val.sum (fun x n=>n • e x)= + (stringStripEquiv a t f).1.val.sum (fun x n=>n • e (x.1,x.2.val))+ + (stringStripEquiv a t f).2.val.sum (fun x n=>n • e (x.1,x.2+t x.1)) := by + have H:=countReindex_sum (levelCutEquiv t) _ _ (levelCut_even a t) f + (fun x=>e ((levelCutEquiv t).symm x)) + simp only [Equiv.symm_apply_apply] at H + rw [←H,countSum_sum] + rfl + +lemma stringStrip_dimension {T : Type*} [AddCommMonoid T] (dim : S → T) + (f : CountSelection (fun x : S×ℕ=>a x.1≠0)) : + f.val.sum (fun x n=>n • dim x.1)= + (stringStripEquiv a t f).1.val.sum (fun x n=>n • dim x.1)+ + (stringStripEquiv a t f).2.val.sum (fun x n=>n • dim x.1) := + stringStrip_sum a t f (fun x=>dim x.1) + +lemma stringStrip_energy (k : S → ℤ) + (f : CountSelection (fun x : S×ℕ=>a x.1≠0)) : + f.val.sum (fun x n=>n • (k x.1+2*(t x.1:ℤ)-2*(x.2:ℤ)))= + (stringStripEquiv a t f).1.val.sum (fun x n=>n • (k x.1+2*(t x.1:ℤ)-2*(x.2.val:ℤ)))+ + (stringStripEquiv a t f).2.val.sum (fun x n=>n • (k x.1-2*(x.2:ℤ))) := by + rw [stringStrip_sum] + congr 1 + apply Finsupp.sum_congr + intro x hx + congr 1 + simp only [Nat.cast_add] + ring +end +end ElementaryPositivity.UnitSelections + +end +section +namespace ElementaryPositivity.SignedMultiplicity +noncomputable section +variable {S I : Type*} (even : S → Prop) (dim : S → (I → ℕ)) + +def countDimension (f : CountSelection even) : I → ℕ := + f.val.sum (fun s n=>n • dim s) + +def zeroCount : CountSelection even := ⟨0,by simp⟩ + +@[simp] lemma countDimension_zero : countDimension even dim (zeroCount even)=0 := by + simp [countDimension,zeroCount] + +lemma countDimension_apply (f : CountSelection even) (i : I) : + countDimension even dim f i=∑s∈f.val.support,f.val s*dim s i := by + simp [countDimension,Finsupp.sum,Finset.sum_apply] + +lemma count_eq_zero_of_dimension (hdim : ∀s,dim s≠0) (f : CountSelection even) + (h : countDimension even dim f=0) : f=zeroCount even := by + classical + apply Subtype.ext + ext s + by_contra H + have hs : s∈f.val.support := Finsupp.mem_support_iff.mpr (by simpa [zeroCount] using H) + obtain ⟨i,hi⟩:=Function.ne_iff.mp (hdim s) + have HE:=congrArg (fun d : I→ℕ=>d i) h + rw [countDimension_apply] at HE + have HB : f.val s*dim s i≤0 := + (Finset.single_le_sum (fun _ _=>Nat.zero_le _) hs).trans_eq HE + have hf : 0n • e s) + +@[simp] lemma countEnergy_zero (e : S → ℤ) : countEnergy even e (zeroCount even)=0 := by + simp [countEnergy,zeroCount] + +lemma dimensionCounts_zero_energy (hdim : ∀s,dim s≠0) (e : S → ℤ) + (f : DimensionCounts even dim 0) : countEnergy even e f.val=0 := by + rw [count_eq_zero_of_dimension even dim hdim f.val f.property,countEnergy_zero] + +lemma countDimension_mem (D : AddSubmonoid (I → ℕ)) (hd : ∀s,dim s∈D) (f : CountSelection even) : + countDimension even dim f∈D := by + unfold countDimension Finsupp.sum + exact D.sum_mem (fun s hs=>D.nsmul_mem (hd s) _) + +lemma countEnergy_shift (τ : (I→ℕ) →+ ℤ) (e : S → ℤ) (f : CountSelection even) : + countEnergy even (fun s=>e s+τ (dim s)) f= + countEnergy even e f+τ (countDimension even dim f) := by + simp only [countEnergy,countDimension,Finsupp.sum,map_sum,map_nsmul,smul_add,Finset.sum_add_distrib] +end +end ElementaryPositivity.SignedMultiplicity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/Taylor.lean b/lean/OAI/Combinatorics/Chromatic/Walls/Taylor.lean new file mode 100644 index 0000000000000000000000000000000000000000..368e39b03bb522499872240156bc6f3856a1f130 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/Taylor.lean @@ -0,0 +1,136 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.CommonTranslation + +open scoped BigOperators + +variable {V : Type*} [AddCommGroup V] [Module ℚ V] + +theorem coefficients_mem {N : ℕ} (U : Submodule ℚ V) (v : Fin N → V) + (h : ∀ t : ℚ, ∑ n : Fin N, t^(n:ℕ) • v n ∈ U) (n : Fin N) : v n ∈ U := by + apply (Subspace.forall_mem_dualAnnihilator_apply_eq_zero_iff U (v n)).mp + intro φ hφ + let p : Polynomial ℚ := ∑ k : Fin N, Polynomial.monomial (k:ℕ) (φ (v k)) + have hp : p = 0 := by + apply Polynomial.zero_of_eval_zero + intro t + have hz : φ (∑ k : Fin N, t^(k:ℕ) • v k) = 0 := ((Submodule.mem_dualAnnihilator φ).mp hφ) _ (h t) + simpa [p, Polynomial.eval_finsetSum, Polynomial.eval_monomial, + map_sum, map_smul, mul_comm] using hz + have hc := congrArg (fun p : Polynomial ℚ => p.coeff (n:ℕ)) hp + simpa [p, Polynomial.coeff_sum, Polynomial.coeff_monomial, + ← Fin.ext_iff] using hc + +variable {A : Type*} [CommRing A] [Algebra ℚ A] + +theorem polynomial_coeff_mem (U : Submodule ℚ A) (p : Polynomial A) + (h : ∀ t : ℚ, p.eval (algebraMap ℚ A t) ∈ U) (n : ℕ) : p.coeff n ∈ U := by + by_cases hn : n < p.natDegree+1 + · apply coefficients_mem U (fun k : Fin (p.natDegree+1) => p.coeff k.val) ?_ ⟨n,hn⟩ + intro t + convert h t using 1 + rw [Polynomial.eval_eq_sum_range] + simp only [Algebra.smul_def, map_pow] + rw [Fin.sum_univ_eq_sum_range (fun i => (algebraMap ℚ A t)^i * p.coeff i)] + apply Finset.sum_congr rfl + intro i hi + exact mul_comm _ _ + · rw [Polynomial.coeff_eq_zero_of_natDegree_lt (by omega)] + exact U.zero_mem + +section Polynomials +open MvPolynomial +variable {α β : Type*} + +noncomputable def taylor : MvPolynomial α ℚ →ₐ[ℚ] Polynomial (MvPolynomial α ℚ) := + aeval fun i => Polynomial.C (X i) + Polynomial.X + +@[simp] lemma taylor_X (i : α) : + taylor (X i) = Polynomial.C (X i) + Polynomial.X := by simp [taylor] + +@[simp] lemma taylor_C (r : ℚ) : + taylor (C r : MvPolynomial α ℚ) = Polynomial.C (C r) := by + simp [taylor, Polynomial.algebraMap_apply] + +lemma taylor_eval (p : MvPolynomial α ℚ) (t : ℚ) : + (taylor p).eval (C t) = aeval (fun i => X i + C t) p := by + induction p using MvPolynomial.induction_on with + | C r => simp + | add p q hp hq => simp [hp,hq] + | mul_X p i hp => simp [hp] + +@[simp] lemma taylor_coeff_zero (p : MvPolynomial α ℚ) : (taylor p).coeff 0 = p := by + rw [Polynomial.coeff_zero_eq_eval_zero] + have h := taylor_eval p 0 + simpa [show (aeval fun i : α => X i + C (0:ℚ)) = AlgHom.id ℚ _ by ext; simp] using h + +noncomputable def D : Derivation ℚ (MvPolynomial α ℚ) (MvPolynomial α ℚ) := + mkDerivation ℚ fun _ => 1 + +@[simp] lemma D_X (i : α) : D (X i) = 1 := mkDerivation_X ℚ _ i +@[simp] lemma D_C (r : ℚ) : D (C r : MvPolynomial α ℚ) = 0 := derivation_C _ _ +lemma D_mul (p q : MvPolynomial α ℚ) : D (p*q) = D p*q + p*D q := by + simp [smul_eq_mul, mul_comm, add_comm] + +lemma D_eq_sum [Fintype α] : D (α := α) = ∑ i : α, pderiv i := by + classical + apply MvPolynomial.derivation_ext + intro i + rw [show (∑ j : α, pderiv j) (X i) = ∑ j : α, pderiv j (X i) from by + simpa only [Derivation.coeFnAddMonoidHom_apply, Finset.sum_apply] using + congrFun (map_sum Derivation.coeFnAddMonoidHom (fun j : α => pderiv j) Finset.univ) (X i)] + simp [pderiv_X, Pi.single_apply] + +lemma taylor_derivative (p : MvPolynomial α ℚ) : + Polynomial.derivative (taylor p) = taylor (D p) := by + induction p using MvPolynomial.induction_on with + | C r => simp + | add p q hp hq => simp [hp,hq] + | mul_X p i hp => + simp only [map_mul, Polynomial.derivative_mul, taylor_X, + Polynomial.derivative_C, Polynomial.derivative_X, zero_add, mul_one, hp, + D_mul, D_X, map_add] + +@[simp] lemma taylor_coeff_one (p : MvPolynomial α ℚ) : (taylor p).coeff 1 = D p := by + have h := congrArg (fun q : Polynomial (MvPolynomial α ℚ) => q.coeff 0) (taylor_derivative p) + simpa [Polynomial.coeff_derivative] using h + +lemma D_rename (f : α → β) (p : MvPolynomial α ℚ) : + D (rename f p) = rename f (D p) := by + induction p using MvPolynomial.induction_on with + | C r => simp + | add p q hp hq => simp [hp,hq] + | mul_X p i hp => simp [hp] + +theorem D_mem_of_translation_mem (U : Submodule ℚ (MvPolynomial α ℚ)) + (p : MvPolynomial α ℚ) + (h : ∀ t : ℚ, aeval (fun i => X i + C t) p ∈ U) : D p ∈ U := by + have hc := polynomial_coeff_mem U (taylor p) (fun t => by simpa [taylor_eval] using h t) 1 + simpa using hc + +lemma taylor_iterate_D (n : ℕ) (p : MvPolynomial α ℚ) : + taylor ((D.toLinearMap ^ n) p) = (Polynomial.derivative^[n]) (taylor p) := by + induction n with + | zero => rfl + | succ n ih => + rw [pow_succ', Module.End.mul_apply] + change taylor (D ((D.toLinearMap^n) p)) = _ + rw [← taylor_derivative, ih, Function.iterate_succ_apply'] + +theorem locally_nilpotent_D (p : MvPolynomial α ℚ) : + (D.toLinearMap ^ ((taylor p).natDegree+1)) p = 0 := by + have h := taylor_iterate_D ((taylor p).natDegree+1) p + rw [Polynomial.iterate_derivative_eq_zero (Nat.lt_succ_self _)] at h + have h0 := congrArg (fun q : Polynomial (MvPolynomial α ℚ) => q.coeff 0) h + simpa using h0 + +end Polynomials + +end ElementaryPositivity.CommonTranslation + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TensorAssociatedGrade.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TensorAssociatedGrade.lean new file mode 100644 index 0000000000000000000000000000000000000000..8958bee9afcf8e038001daea507ebd670f5b100f --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TensorAssociatedGrade.lean @@ -0,0 +1,219 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.LinearFiltrationBilinear + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +open LinearDetection +open scoped TensorProduct DirectSum +variable {M N : Type*} [AddCommGroup M] [Module ℚ M] [AddCommGroup N] [Module ℚ N] + +noncomputable def gradeProjection (F : ℤ → Submodule ℚ M) (u : ℤ) : + M →ₗ[ℚ] Grade (F u) (F (u+1)) := + (mk _ _).comp ((retract (F u)).codRestrict _ (retract_mem _)) + +lemma gradeProjection_mem (F : ℤ → Submodule ℚ M) (u : ℤ) (x : F u) : + gradeProjection F u x.val=mk (F u) (F (u+1)) x := by + apply congrArg (mk _ _) + apply Subtype.ext + exact retract_eq_self _ x.property + +lemma gradeProjection_zero (F : ℤ → Submodule ℚ M) (hF : Antitone F) (u v : ℤ) + (huv : utmul_mem_additiveTensorFiltration F G (le_refl _) hx hy) + (fun _ hx _ hy=>tmul_mem_additiveTensorFiltration F G (by omega) hx hy) + (fun _ hx _ hy=>tmul_mem_additiveTensorFiltration F G (by omega) hx hy)) + +lemma tensorGradeInclusion_mk (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (u v : ℤ) (x : F u) (y : G v) : + tensorGradeInclusion F G u v (mk _ _ x⊗ₜ[ℚ]mk _ _ y)= + mk _ _ ⟨x.val⊗ₜ[ℚ]y.val,tmul_mem_additiveTensorFiltration F G (le_refl _) x.property y.property⟩ := rfl + +lemma tensorProjection_kills (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) (u v : ℤ) : + additiveTensorFiltration F G (u+v+1)≤ + LinearMap.ker (TensorProduct.map (gradeProjection F u) (gradeProjection G v)) := by + apply Submodule.span_le.mpr + rintro _ ⟨a,b,x,y,hab,hx,hy,rfl⟩ + change TensorProduct.map _ _ (x⊗ₜ[ℚ]y)=0 + rw [TensorProduct.map_tmul] + by_cases ha : u + induction y using Submodule.Quotient.induction_on with + | H y => + change tensorGradeProjection F G hF hG u v + (tensorGradeInclusion F G u v (mk _ _ x⊗ₜ[ℚ]mk _ _ y))=mk _ _ x⊗ₜ[ℚ]mk _ _ y + rw [tensorGradeInclusion_mk,tensorGradeProjection_mk,TensorProduct.map_tmul, + gradeProjection_mem,gradeProjection_mem] + +abbrev TensorGradePart (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) (W u : ℤ) := + Grade (F u) (F (u+1)) ⊗[ℚ] Grade (G (W-u)) (G (W-u+1)) + +noncomputable def tensorGradeInclusionW (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (W u : ℤ) : TensorGradePart F G W u →ₗ[ℚ] TensorGrade F G W := + TensorProduct.lift (bilinear (F u) (F (u+1)) (G (W-u)) (G (W-u+1)) + (additiveTensorFiltration F G W) (additiveTensorFiltration F G (W+1)) + (TensorProduct.mk ℚ M N) + (fun _ hx _ hy=>tmul_mem_additiveTensorFiltration F G (by omega) hx hy) + (fun _ hx _ hy=>tmul_mem_additiveTensorFiltration F G (by omega) hx hy) + (fun _ hx _ hy=>tmul_mem_additiveTensorFiltration F G (by omega) hx hy)) + +lemma tensorGradeInclusionW_mk (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (W u : ℤ) (x : F u) (y : G (W-u)) : + tensorGradeInclusionW F G W u (mk _ _ x⊗ₜ[ℚ]mk _ _ y)= + mk _ _ ⟨x.val⊗ₜ[ℚ]y.val,tmul_mem_additiveTensorFiltration F G (by omega) x.property y.property⟩ := rfl + +noncomputable def tensorGradeProjectionW (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) (W u : ℤ) : + TensorGrade F G W →ₗ[ℚ] TensorGradePart F G W u := + (next _ _).liftQ ((TensorProduct.map (gradeProjection F u) (gradeProjection G (W-u))).comp + (additiveTensorFiltration F G W).subtype) (by + intro x hx + apply tensorProjection_kills F G hF hG u (W-u) + change x.val∈additiveTensorFiltration F G (W+1) at hx + change x.val∈additiveTensorFiltration F G (u+(W-u)+1) + simpa only [add_sub_cancel] using hx) + +lemma tensorGradeProjectionW_mk (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) (W u : ℤ) (x : additiveTensorFiltration F G W) : + tensorGradeProjectionW F G hF hG W u (mk _ _ x)= + TensorProduct.map (gradeProjection F u) (gradeProjection G (W-u)) x.val := rfl + +lemma tensorGradeProjectionW_inclusion_self (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) (W u : ℤ) : + (tensorGradeProjectionW F G hF hG W u).comp (tensorGradeInclusionW F G W u)=LinearMap.id := by + ext x y + induction x using Submodule.Quotient.induction_on with + | H x => + induction y using Submodule.Quotient.induction_on with + | H y => + change tensorGradeProjectionW F G hF hG W u + (tensorGradeInclusionW F G W u (mk _ _ x⊗ₜ[ℚ]mk _ _ y))=mk _ _ x⊗ₜ[ℚ]mk _ _ y + rw [tensorGradeInclusionW_mk,tensorGradeProjectionW_mk,TensorProduct.map_tmul, + gradeProjection_mem,gradeProjection_mem] + +lemma tensorGradeProjectionW_inclusion_ne (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) (W u j : ℤ) (huj : u≠j) : + (tensorGradeProjectionW F G hF hG W u).comp (tensorGradeInclusionW F G W j)=0 := by + ext x y + induction x using Submodule.Quotient.induction_on with + | H x => + induction y using Submodule.Quotient.induction_on with + | H y => + change tensorGradeProjectionW F G hF hG W u + (tensorGradeInclusionW F G W j (mk _ _ x⊗ₜ[ℚ]mk _ _ y))=0 + rw [tensorGradeInclusionW_mk,tensorGradeProjectionW_mk,TensorProduct.map_tmul] + by_cases h : u + change mk _ _ x∈LinearMap.range (tensorGradeSum F G W) + have h : ∀ (z : M⊗[ℚ]N) (hz : z∈additiveTensorFiltration F G W), + mk _ _ ⟨z,hz⟩∈LinearMap.range (tensorGradeSum F G W) := by + intro z hz + induction hz using Submodule.span_induction with + | mem z hz => + rcases hz with ⟨u,v,x,y,hw,hx,hy,rfl⟩ + by_cases he : W=u+v + · have hv : v=W-u:=by omega + subst v + refine ⟨DirectSum.lof ℚ ℤ _ u (mk _ _ ⟨x,hx⟩⊗ₜ[ℚ]mk _ _ ⟨y,hy⟩),?_⟩ + rw [tensorGradeSum,DirectSum.toModule_lof,tensorGradeInclusionW_mk] + · have hz' : x⊗ₜ[ℚ]y∈additiveTensorFiltration F G (W+1):= + tmul_mem_additiveTensorFiltration F G (by omega) hx hy + have he : (mk _ _ ⟨x⊗ₜ[ℚ]y,tmul_mem_additiveTensorFiltration F G hw hx hy⟩ : TensorGrade F G W)=0 := + (Submodule.Quotient.mk_eq_zero _).mpr hz' + rw [he] + exact Submodule.zero_mem _ + | zero => exact Submodule.zero_mem _ + | add x y hx hy hix hiy => + exact (LinearMap.range (tensorGradeSum F G W)).add_mem hix hiy + | smul r x hx hix => exact (LinearMap.range (tensorGradeSum F G W)).smul_mem r hix + exact h x.val x.property + +noncomputable def tensorGradeEquiv (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) (W : ℤ) : + (⨁ u : ℤ,TensorGradePart F G W u) ≃ₗ[ℚ] TensorGrade F G W := + LinearEquiv.ofBijective (tensorGradeSum F G W) + ⟨tensorGradeSum_injective F G hF hG W,tensorGradeSum_surjective F G W⟩ + +end ElementaryPositivity.LinearFiltration + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TensorFiltrationIdeals.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TensorFiltrationIdeals.lean new file mode 100644 index 0000000000000000000000000000000000000000..6dbd2b99966f14eab817c62910e2c012401a204e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TensorFiltrationIdeals.lean @@ -0,0 +1,48 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RationalTensorDetection + +namespace OAI + +section +namespace ElementaryPositivity.LinearDetection +open scoped TensorProduct +variable {K A B : Type*} [Field K] [CommRing A] [CommRing B] [Algebra K A] [Algebra K B] + +lemma additiveTensorFiltration_mul_mem (F : ℤ → Submodule K A) (G : ℤ → Submodule K B) + (hF : ∀ w x y,x∈F w → x*y∈F w) (hG : ∀ w x y,x∈G w → x*y∈G w) + (W : ℤ) (x y : A⊗[K]B) (hx : x∈additiveTensorFiltration F G W) : + x*y∈additiveTensorFiltration F G W := by + have hgen {u v : ℤ} {a : A} {b : B} (hw : W≤u+v) (ha : a∈F u) (hb : b∈G v) + (z : A⊗[K]B) : (a⊗ₜ[K]b)*z ∈ additiveTensorFiltration F G W := by + induction z using TensorProduct.inductionOn with + | tmul c d => + rw [Algebra.TensorProduct.tmul_mul_tmul] + exact tmul_mem_additiveTensorFiltration F G hw (hF u a c ha) (hG v b d hb) + | add z t hz ht => + rw [mul_add] + exact (additiveTensorFiltration F G W).add_mem hz ht + induction hx using Submodule.span_induction with + | mem z hz => + obtain ⟨u,v,a,b,hw,ha,hb,rfl⟩:=hz + exact hgen hw ha hb y + | zero => simp only [zero_mul]; exact (additiveTensorFiltration F G W).zero_mem + | add z t _ _ hz ht => + rw [add_mul] + exact (additiveTensorFiltration F G W).add_mem hz ht + | smul c z _ hz => + rw [smul_mul_assoc] + exact (additiveTensorFiltration F G W).smul_mem c hz + +noncomputable def additiveTensorFiltrationIdeal (F : ℤ → Submodule K A) (G : ℤ → Submodule K B) + (hF : ∀ w x y,x∈F w → x*y∈F w) (hG : ∀ w x y,x∈G w → x*y∈G w) + (W : ℤ) : Ideal (A⊗[K]B) where + __ := (additiveTensorFiltration F G W).toAddSubmonoid + smul_mem' c x hx := by + change c*x∈additiveTensorFiltration F G W + rw [mul_comm] + exact additiveTensorFiltration_mul_mem F G hF hG W x c hx +end ElementaryPositivity.LinearDetection + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TensorFiltrationInterchange.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TensorFiltrationInterchange.lean new file mode 100644 index 0000000000000000000000000000000000000000..75bf0d5bcbab156c1f207f4e4a1129bd4aa4e743 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TensorFiltrationInterchange.lean @@ -0,0 +1,172 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RationalTensorDetection + +namespace OAI + +section +namespace ElementaryPositivity.LinearDetection +open scoped TensorProduct +variable {K A B C D E F : Type*} [Field K] + [AddCommGroup A] [Module K A] [AddCommGroup B] [Module K B] + [AddCommGroup C] [Module K C] [AddCommGroup D] [Module K D] + [AddCommGroup E] [Module K E] [AddCommGroup F] [Module K F] + +lemma additiveTensorFiltration_antitone (P : ℤ → Submodule K A) (Q : ℤ → Submodule K B) : + Antitone (additiveTensorFiltration P Q) := by + intro u v h + apply Submodule.span_mono + rintro x ⟨a,b,f,g,hab,hf,hg,rfl⟩ + exact ⟨a,b,f,g,le_trans h hab,hf,hg,rfl⟩ + +lemma tensor_map_mem_filtration (P : ℤ → Submodule K A) (Q : ℤ → Submodule K B) + (R : ℤ → Submodule K C) (S : ℤ → Submodule K D) + (f : A →ₗ[K] C) (g : B →ₗ[K] D) + (hf : ∀ w x,x∈P w → f x∈R w) (hg : ∀ w y,y∈Q w → g y∈S w) + (W : ℤ) (x : A⊗[K]B) (hx : x∈additiveTensorFiltration P Q W) : + TensorProduct.map f g x∈additiveTensorFiltration R S W := by + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨u,v,a,b,hw,ha,hb,rfl⟩:=hx + rw [TensorProduct.map_tmul] + exact tmul_mem_additiveTensorFiltration R S hw (hf u a ha) (hg v b hb) + | zero => rw [map_zero]; exact (additiveTensorFiltration R S W).zero_mem + | add x y _ _ hx hy => rw [map_add]; exact (additiveTensorFiltration R S W).add_mem hx hy + | smul r x _ hx => rw [map_smul]; exact (additiveTensorFiltration R S W).smul_mem r hx + +lemma interchange_mem_filtration + (P : ℤ → Submodule K A) (Q : ℤ → Submodule K B) + (R : ℤ → Submodule K C) (S : ℤ → Submodule K D) + (U V : ℤ) (x : A⊗[K]B) (y : C⊗[K]D) + (hx : x∈additiveTensorFiltration P Q U) (hy : y∈additiveTensorFiltration R S V) : + TensorProduct.tensorTensorTensorComm K A B C D (x⊗ₜ[K]y)∈ + additiveTensorFiltration (additiveTensorFiltration P R) (additiveTensorFiltration Q S) (U+V) := by + let J:=additiveTensorFiltration (additiveTensorFiltration P R) + (additiveTensorFiltration Q S) (U+V) + let τ:=TensorProduct.tensorTensorTensorComm K A B C D + change τ (x⊗ₜ[K]y)∈J + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨u,v,a,b,hu,ha,hb,rfl⟩:=hx + induction hy using Submodule.span_induction with + | mem y hy => + obtain ⟨w,z,c,d,hv,hc,hd,rfl⟩:=hy + change (a⊗ₜ[K]c)⊗ₜ[K](b⊗ₜ[K]d)∈J + exact tmul_mem_additiveTensorFiltration _ _ (show U+V≤(u+w)+(v+z) by omega) + (tmul_mem_additiveTensorFiltration P R (le_refl _) ha hc) + (tmul_mem_additiveTensorFiltration Q S (le_refl _) hb hd) + | zero => rw [TensorProduct.tmul_zero,τ.map_zero]; exact J.zero_mem + | add y z _ _ hy hz => rw [TensorProduct.tmul_add,τ.map_add]; exact J.add_mem hy hz + | smul r y _ hy => rw [TensorProduct.tmul_smul,τ.map_smul]; exact J.smul_mem r hy + | zero => rw [TensorProduct.zero_tmul,τ.map_zero]; exact J.zero_mem + | add x z _ _ hx hz => rw [TensorProduct.add_tmul,τ.map_add]; exact J.add_mem hx hz + | smul r x _ hx => rw [←TensorProduct.smul_tmul',τ.map_smul]; exact J.smul_mem r hx + +lemma lift_mem_filtration (P : ℤ → Submodule K A) (Q : ℤ → Submodule K B) + (R : ℤ → Submodule K C) (hR : Antitone R) (f : A →ₗ[K] B →ₗ[K] C) + (hf : ∀ u v x y,x∈P u → y∈Q v → f x y∈R (u+v)) + (W : ℤ) (x : A⊗[K]B) (hx : x∈additiveTensorFiltration P Q W) : + TensorProduct.lift f x∈R W := by + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨u,v,a,b,hw,ha,hb,rfl⟩:=hx + rw [TensorProduct.lift.tmul] + exact hR hw (hf u v a b ha hb) + | zero => rw [map_zero]; exact (R W).zero_mem + | add x y _ _ hx hy => rw [map_add]; exact (R W).add_mem hx hy + | smul r x _ hx => rw [map_smul]; exact (R W).smul_mem r hx +end ElementaryPositivity.LinearDetection + +end +section +namespace ElementaryPositivity.LinearFiltration +variable {M N : Type*} [AddCommGroup M] [Module ℚ M] [AddCommGroup N] [Module ℚ N] +noncomputable def next (F G : Submodule ℚ M) : Submodule ℚ F := G.comap F.subtype +def Grade (F G : Submodule ℚ M) := F ⧸ next F G +noncomputable instance (F G : Submodule ℚ M) : AddCommGroup (Grade F G) := + inferInstanceAs (AddCommGroup (F ⧸ next F G)) +noncomputable instance (F G : Submodule ℚ M) : Module ℚ (Grade F G) := + inferInstanceAs (Module ℚ (F ⧸ next F G)) +noncomputable def mk (F G : Submodule ℚ M) : F →ₗ[ℚ] Grade F G := (next F G).mkQ +noncomputable def restrict (F : Submodule ℚ M) (G : Submodule ℚ N) + (f : M →ₗ[ℚ] N) (h : ∀ x∈F,f x∈G) : F →ₗ[ℚ] G := + (f.comp F.subtype).codRestrict G (fun x=>h x.val x.property) +noncomputable def map (F F' : Submodule ℚ M) (G G' : Submodule ℚ N) + (f : M →ₗ[ℚ] N) (h : ∀ x∈F,f x∈G) (h' : ∀ x∈F',f x∈G') : + Grade F F' →ₗ[ℚ] Grade G G' := + (next F F').liftQ ((next G G').mkQ.comp (restrict F G f h)) (by + intro x hx + exact (Submodule.Quotient.mk_eq_zero _).mpr (h' x.val hx)) +lemma map_mk (F F' : Submodule ℚ M) (G G' : Submodule ℚ N) + (f : M →ₗ[ℚ] N) (h : ∀ x∈F,f x∈G) (h' : ∀ x∈F',f x∈G') (x : F) : + map F F' G G' f h h' (Submodule.Quotient.mk x)= + Submodule.Quotient.mk (restrict F G f h x) := rfl +lemma map_eq_zero (F F' : Submodule ℚ M) (G G' : Submodule ℚ N) + (f : M →ₗ[ℚ] N) (h : ∀ x∈F,f x∈G) (h' : ∀ x∈F',f x∈G') + (hz : ∀ x∈F,f x∈G') : map F F' G G' f h h'=0 := by + apply LinearMap.ext + intro x + induction x using Submodule.Quotient.induction_on with + | H x => + change Submodule.Quotient.mk (restrict F G f h x) = (0 : G ⧸ next G G') + exact (Submodule.Quotient.mk_eq_zero _).mpr (hz x.val x.property) +end ElementaryPositivity.LinearFiltration + +end +section +namespace ElementaryPositivity.LinearDetection +open scoped TensorProduct +variable {K A B C : Type*} [Field K] + [AddCommGroup A] [Module K A] [AddCommGroup B] [Module K B] + [AddCommGroup C] [Module K C] + +lemma assoc_mem_tensorFiltration (F : ℤ → Submodule K A) (G : ℤ → Submodule K B) + (H : ℤ → Submodule K C) (W : ℤ) (x : (A⊗[K]B)⊗[K]C) + (hx : x∈additiveTensorFiltration (additiveTensorFiltration F G) H W) : + TensorProduct.assoc K A B C x∈additiveTensorFiltration F (additiveTensorFiltration G H) W := by + let J:=additiveTensorFiltration F (additiveTensorFiltration G H) W + let τ:=TensorProduct.assoc K A B C + change τ x∈J + induction hx using Submodule.span_induction with + | mem x hx => + rcases hx with ⟨u,v,x,z,huv,hx,hz,rfl⟩ + induction hx using Submodule.span_induction with + | mem x hx => + rcases hx with ⟨r,s,x,y,hrs,hx,hy,rfl⟩ + change x⊗ₜ[K](y⊗ₜ[K]z)∈J + exact tmul_mem_additiveTensorFiltration _ _ (show W≤r+(s+v) by omega) hx + (tmul_mem_additiveTensorFiltration _ _ (le_refl _) hy hz) + | zero => rw [TensorProduct.zero_tmul,τ.map_zero]; exact J.zero_mem + | add x y _ _ hx hy => rw [TensorProduct.add_tmul,τ.map_add]; exact J.add_mem hx hy + | smul r x _ hx => rw [←TensorProduct.smul_tmul',τ.map_smul]; exact J.smul_mem r hx + | zero => rw [map_zero]; exact J.zero_mem + | add x y _ _ hx hy => rw [map_add]; exact J.add_mem hx hy + | smul r x _ hx => rw [map_smul]; exact J.smul_mem r hx + +lemma unassoc_mem_tensorFiltration (F : ℤ → Submodule K A) (G : ℤ → Submodule K B) + (H : ℤ → Submodule K C) (W : ℤ) (x : A⊗[K](B⊗[K]C)) + (hx : x∈additiveTensorFiltration F (additiveTensorFiltration G H) W) : + (TensorProduct.assoc K A B C).symm x∈additiveTensorFiltration (additiveTensorFiltration F G) H W := by + let J:=additiveTensorFiltration (additiveTensorFiltration F G) H W + let τ:=(TensorProduct.assoc K A B C).symm + change τ x∈J + induction hx using Submodule.span_induction with + | mem x hx => + rcases hx with ⟨u,v,x,z,huv,hx,hz,rfl⟩ + induction hz using Submodule.span_induction with + | mem z hz => + rcases hz with ⟨r,s,y,z,hrs,hy,hz,rfl⟩ + change (x⊗ₜ[K]y)⊗ₜ[K]z∈J + exact tmul_mem_additiveTensorFiltration _ _ (show W≤(u+r)+s by omega) + (tmul_mem_additiveTensorFiltration _ _ (le_refl _) hx hy) hz + | zero => rw [TensorProduct.tmul_zero,τ.map_zero]; exact J.zero_mem + | add y z _ _ hy hz => rw [TensorProduct.tmul_add,τ.map_add]; exact J.add_mem hy hz + | smul r z _ hz => rw [TensorProduct.tmul_smul,τ.map_smul]; exact J.smul_mem r hz + | zero => rw [map_zero]; exact J.zero_mem + | add x y _ _ hx hy => rw [map_add]; exact J.add_mem hx hy + | smul r x _ hx => rw [map_smul]; exact J.smul_mem r hx + +end ElementaryPositivity.LinearDetection + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TensorGradeFiniteSum.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TensorGradeFiniteSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..323eb2808c4cbb2d74d289daad5942397ebd3899 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TensorGradeFiniteSum.lean @@ -0,0 +1,38 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TensorGradeFunctor + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +open scoped TensorProduct +variable {M N X Y D : Type*} [AddCommGroup M] [Module ℚ M] + [AddCommGroup N] [Module ℚ N] [AddCommGroup X] [Module ℚ X] + [AddCommGroup Y] [Module ℚ Y] [Fintype D] + +lemma tensorGradeLift_sum_left (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) + (f : D → ∀ u,FGrade F u →ₗ[ℚ] X) (g : ∀ v,FGrade G v →ₗ[ℚ] Y) + (W : ℤ) (x : TensorGrade F G W) : + tensorGradeLift F G hF hG (fun u=>∑ d,f d u) g W x= + ∑ d,tensorGradeLift F G hF hG (f d) g W x := by + induction x using tensorGrade_induction F G hF hG W with + | hz => simp only [map_zero,Finset.sum_const_zero] + | ha x y hx hy => simp only [map_add,hx,hy,Finset.sum_add_distrib] + | ht u x y => simp only [tensorGradeLift_part,LinearMap.sum_apply,TensorProduct.sum_tmul] + +lemma tensorGradeLift_sum_right (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) + (f : ∀ u,FGrade F u →ₗ[ℚ] X) (g : D → ∀ v,FGrade G v →ₗ[ℚ] Y) + (W : ℤ) (x : TensorGrade F G W) : + tensorGradeLift F G hF hG f (fun v=>∑ d,g d v) W x= + ∑ d,tensorGradeLift F G hF hG f (g d) W x := by + induction x using tensorGrade_induction F G hF hG W with + | hz => simp only [map_zero,Finset.sum_const_zero] + | ha x y hx hy => simp only [map_add,hx,hy,Finset.sum_add_distrib] + | ht u x y => simp only [tensorGradeLift_part,LinearMap.sum_apply,TensorProduct.tmul_sum] +end ElementaryPositivity.LinearFiltration + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TensorGradeFunctor.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TensorGradeFunctor.lean new file mode 100644 index 0000000000000000000000000000000000000000..c62494cc4ca839607ae7ab4a9cc2b676b044b0ff --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TensorGradeFunctor.lean @@ -0,0 +1,174 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalTensorGradeInclusion + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +open ElementaryPositivity.LinearDetection +open scoped TensorProduct DirectSum +variable {M N M' N' X Y X' Y' : Type*} + [AddCommGroup M] [Module ℚ M] [AddCommGroup N] [Module ℚ N] + [AddCommGroup M'] [Module ℚ M'] [AddCommGroup N'] [Module ℚ N'] + [AddCommGroup X] [Module ℚ X] [AddCommGroup Y] [Module ℚ Y] + [AddCommGroup X'] [Module ℚ X'] [AddCommGroup Y'] [Module ℚ Y'] + +abbrev FGrade (F : ℤ → Submodule ℚ M) (u : ℤ) := Grade (F u) (F (u+1)) + +noncomputable def gradeMap (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (f : M →ₗ[ℚ] N) (hf : ∀ w x,x∈F w → f x∈G w) (W : ℤ) : + FGrade F W →ₗ[ℚ] FGrade G W := + map (F W) (F (W+1)) (G W) (G (W+1)) f (hf W) (hf (W+1)) + +lemma gradeMap_mk (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (f : M →ₗ[ℚ] N) (hf : ∀ w x,x∈F w → f x∈G w) (W : ℤ) (x : F W) : + gradeMap F G f hf W (mk _ _ x)=mk _ _ ⟨f x.val,hf W x.val x.property⟩ := rfl + +lemma gradeMap_id (F : ℤ → Submodule ℚ M) + (hf : ∀ w x,x∈F w → LinearMap.id (R:=ℚ) (M:=M) x∈F w) (W : ℤ) : + gradeMap F F LinearMap.id hf W=LinearMap.id := by + apply LinearMap.ext + intro x + induction x using Submodule.Quotient.induction_on with + | H x => rfl + +noncomputable def tensorGradeMap (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (F' : ℤ → Submodule ℚ M') (G' : ℤ → Submodule ℚ N') + (f : M →ₗ[ℚ] M') (g : N →ₗ[ℚ] N') + (hf : ∀ w x,x∈F w → f x∈F' w) (hg : ∀ w y,y∈G w → g y∈G' w) (W : ℤ) : + TensorGrade F G W →ₗ[ℚ] TensorGrade F' G' W := + gradeMap (additiveTensorFiltration F G) (additiveTensorFiltration F' G') + (TensorProduct.map f g) (tensor_map_mem_filtration F G F' G' f g hf hg) W + +lemma tensorGradeMap_part (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (F' : ℤ → Submodule ℚ M') (G' : ℤ → Submodule ℚ N') + (f : M →ₗ[ℚ] M') (g : N →ₗ[ℚ] N') + (hf : ∀ w x,x∈F w → f x∈F' w) (hg : ∀ w y,y∈G w → g y∈G' w) (W u : ℤ) + (x : FGrade F u) (y : FGrade G (W-u)) : + tensorGradeMap F G F' G' f g hf hg W (tensorGradeInclusionW F G W u (x⊗ₜ[ℚ]y))= + tensorGradeInclusionW F' G' W u + (gradeMap F F' f hf u x⊗ₜ[ℚ]gradeMap G G' g hg (W-u) y) := by + induction x using Submodule.Quotient.induction_on with + | H x => + induction y using Submodule.Quotient.induction_on with + | H y => rfl + +noncomputable def tensorGradeLift (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) + (f : ∀ u,FGrade F u →ₗ[ℚ] X) (g : ∀ v,FGrade G v →ₗ[ℚ] Y) (W : ℤ) : + TensorGrade F G W →ₗ[ℚ] X⊗[ℚ]Y := + (DirectSum.toModule ℚ ℤ (X⊗[ℚ]Y) (fun u=>TensorProduct.map (f u) (g (W-u)))).comp + (tensorGradeEquiv F G hF hG W).symm.toLinearMap + +lemma tensorGradeLift_part (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) + (f : ∀ u,FGrade F u →ₗ[ℚ] X) (g : ∀ v,FGrade G v →ₗ[ℚ] Y) (W u : ℤ) + (x : FGrade F u) (y : FGrade G (W-u)) : + tensorGradeLift F G hF hG f g W (tensorGradeInclusionW F G W u (x⊗ₜ[ℚ]y))= + f u x⊗ₜ[ℚ]g (W-u) y := by + change DirectSum.toModule ℚ ℤ _ _ ((tensorGradeEquiv F G hF hG W).symm _) = _ + rw [tensorGradeEquiv_symm_inclusion,DirectSum.toModule_lof,TensorProduct.map_tmul] + +lemma tensorGradeLift_map_natural (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (F' : ℤ → Submodule ℚ M') (G' : ℤ → Submodule ℚ N') + (hF : Antitone F) (hG : Antitone G) (hF' : Antitone F') (hG' : Antitone G') + (f : M →ₗ[ℚ] M') (g : N →ₗ[ℚ] N') + (hf : ∀ w x,x∈F w → f x∈F' w) (hg : ∀ w y,y∈G w → g y∈G' w) + (l : ∀ u,FGrade F' u →ₗ[ℚ] X) (r : ∀ v,FGrade G' v →ₗ[ℚ] Y) + (W : ℤ) (x : TensorGrade F G W) : + tensorGradeLift F' G' hF' hG' l r W (tensorGradeMap F G F' G' f g hf hg W x)= + tensorGradeLift F G hF hG (fun u=>(l u).comp (gradeMap F F' f hf u)) + (fun v=>(r v).comp (gradeMap G G' g hg v)) W x := by + induction x using tensorGrade_induction F G hF hG W with + | hz => simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy] + | ht u x y => rw [tensorGradeMap_part,tensorGradeLift_part,tensorGradeLift_part]; rfl + +lemma tensorGradeLift_comp (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) + (f : ∀ u,FGrade F u →ₗ[ℚ] X) (g : ∀ v,FGrade G v →ₗ[ℚ] Y) + (l : X →ₗ[ℚ] X') (r : Y →ₗ[ℚ] Y') (W : ℤ) (x : TensorGrade F G W) : + TensorProduct.map l r (tensorGradeLift F G hF hG f g W x)= + tensorGradeLift F G hF hG (fun u=>l.comp (f u)) (fun v=>r.comp (g v)) W x := by + induction x using tensorGrade_induction F G hF hG W with + | hz => simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy] + | ht u x y => rw [tensorGradeLift_part,tensorGradeLift_part,TensorProduct.map_tmul]; rfl + +end ElementaryPositivity.LinearFiltration + +end +section +namespace ElementaryPositivity.LinearFiltration +open ElementaryPositivity.LinearDetection +open scoped TensorProduct DirectSum +variable {M N P X Y Z : Type*} + [AddCommGroup M] [Module ℚ M] [AddCommGroup N] [Module ℚ N] + [AddCommGroup P] [Module ℚ P] [AddCommGroup X] [Module ℚ X] + [AddCommGroup Y] [Module ℚ Y] [AddCommGroup Z] [Module ℚ Z] + +lemma tensorGradeLift_mk_tmul (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (hF : Antitone F) (hG : Antitone G) + (f : ∀ u,FGrade F u →ₗ[ℚ] X) (g : ∀ v,FGrade G v →ₗ[ℚ] Y) + (W u v : ℤ) (h : u+v=W) (x : F u) (y : G v) : + tensorGradeLift F G hF hG f g W + (mk _ _ ⟨x.val⊗ₜ[ℚ]y.val,tmul_mem_additiveTensorFiltration F G (by omega) x.property y.property⟩)= + f u (mk _ _ x)⊗ₜ[ℚ]g v (mk _ _ y) := by + have hv : v=W-u := by omega + subst v + exact tensorGradeLift_part F G hF hG f g W u (mk _ _ x) (mk _ _ y) + +noncomputable def tensorGradeAssoc (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (H : ℤ → Submodule ℚ P) (W : ℤ) : + TensorGrade (additiveTensorFiltration F G) H W →ₗ[ℚ] + TensorGrade F (additiveTensorFiltration G H) W := + gradeMap (additiveTensorFiltration (additiveTensorFiltration F G) H) + (additiveTensorFiltration F (additiveTensorFiltration G H)) + (TensorProduct.assoc ℚ M N P).toLinearMap (assoc_mem_tensorFiltration F G H) W + +lemma tensorGradeAssoc_mk (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (H : ℤ → Submodule ℚ P) (W : ℤ) + (x : additiveTensorFiltration (additiveTensorFiltration F G) H W) : + tensorGradeAssoc F G H W (mk _ _ x)= + mk _ _ ⟨TensorProduct.assoc ℚ M N P x.val,assoc_mem_tensorFiltration F G H W x.val x.property⟩ := rfl + +lemma tensorGradeLift_assoc (F : ℤ → Submodule ℚ M) (G : ℤ → Submodule ℚ N) + (H : ℤ → Submodule ℚ P) (hF : Antitone F) (hG : Antitone G) (hH : Antitone H) + (f : ∀ u,FGrade F u →ₗ[ℚ] X) (g : ∀ v,FGrade G v →ₗ[ℚ] Y) + (h : ∀ w,FGrade H w →ₗ[ℚ] Z) (W : ℤ) + (x : TensorGrade (additiveTensorFiltration F G) H W) : + tensorGradeLift F (additiveTensorFiltration G H) hF (additiveTensorFiltration_antitone G H) + f (tensorGradeLift G H hG hH g h) W (tensorGradeAssoc F G H W x)= + TensorProduct.assoc ℚ X Y Z + (tensorGradeLift (additiveTensorFiltration F G) H (additiveTensorFiltration_antitone F G) hH + (tensorGradeLift F G hF hG f g) h W x) := by + induction x using tensorGrade_induction (additiveTensorFiltration F G) H + (additiveTensorFiltration_antitone F G) hH W with + | hz => simp only [map_zero] + | ha x y hx hy => simp only [map_add,hx,hy] + | ht u x z => + induction x using tensorGrade_induction F G hF hG u with + | hz => simp only [TensorProduct.zero_tmul,map_zero] + | ha x y hx hy => simp only [TensorProduct.add_tmul,map_add,hx,hy] + | ht r x y => + rw [tensorGradeLift_part,tensorGradeLift_part,TensorProduct.assoc_tmul] + induction x using Submodule.Quotient.induction_on with + | H x => + induction y using Submodule.Quotient.induction_on with + | H y => + induction z using Submodule.Quotient.induction_on with + | H z => + let yz : additiveTensorFiltration G H (W-r) := + ⟨y.val⊗ₜ[ℚ]z.val,tmul_mem_additiveTensorFiltration G H (by omega) y.property z.property⟩ + have houter := tensorGradeLift_mk_tmul F (additiveTensorFiltration G H) + hF (additiveTensorFiltration_antitone G H) f (tensorGradeLift G H hG hH g h) + W r (W-r) (by omega) x yz + refine houter.trans ?_ + exact congrArg (fun t=>f r (mk _ _ x)⊗ₜ[ℚ]t) + (tensorGradeLift_mk_tmul G H hG hH g h (W-r) (u-r) (W-u) (by omega) y z) + +end ElementaryPositivity.LinearFiltration + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TensorMiddleFiltration.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TensorMiddleFiltration.lean new file mode 100644 index 0000000000000000000000000000000000000000..613fc1ba8dc259753e3c84ab9743f3e3a94d6ffc --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TensorMiddleFiltration.lean @@ -0,0 +1,106 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TensorFiltrationInterchange + +namespace OAI + +section +namespace ElementaryPositivity.LinearDetection +open scoped TensorProduct +variable {K A B C D : Type*} [Field K] + [AddCommGroup A] [Module K A] [AddCommGroup B] [Module K B] + [AddCommGroup C] [Module K C] [AddCommGroup D] [Module K D] + +noncomputable def middleInsert (a : A) (d : D) : + C⊗[K]B →ₗ[K] (A⊗[K]C)⊗[K](B⊗[K]D) := + TensorProduct.map (TensorProduct.mk K A C a) ((TensorProduct.mk K B D).flip d) + +lemma middleInsert_tmul (a : A) (d : D) (c : C) (b : B) : + middleInsert a d (c⊗ₜ[K]b)=(a⊗ₜ[K]c)⊗ₜ[K](b⊗ₜ[K]d) := rfl + +lemma middleInsert_mem_filtration + (P : ℤ → Submodule K A) (Q : ℤ → Submodule K B) + (R : ℤ → Submodule K C) (S : ℤ → Submodule K D) + (u z W : ℤ) (a : A) (d : D) (ha : a∈P u) (hd : d∈S z) + (x : C⊗[K]B) (hx : x∈additiveTensorFiltration R Q W) : + middleInsert a d x∈ + additiveTensorFiltration (additiveTensorFiltration P R) + (additiveTensorFiltration Q S) (u+W+z) := by + let J:=additiveTensorFiltration (additiveTensorFiltration P R) + (additiveTensorFiltration Q S) (u+W+z) + change middleInsert a d x∈J + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨v,w,c,b,hw,hc,hb,rfl⟩:=hx + rw [middleInsert_tmul] + exact tmul_mem_additiveTensorFiltration _ _ (show u+W+z≤(u+v)+(w+z) by omega) + (tmul_mem_additiveTensorFiltration P R (le_refl _) ha hc) + (tmul_mem_additiveTensorFiltration Q S (le_refl _) hb hd) + | zero => rw [map_zero]; exact J.zero_mem + | add x y _ _ hx hy => rw [map_add]; exact J.add_mem hx hy + | smul r x _ hx => rw [map_smul]; exact J.smul_mem r hx + +end ElementaryPositivity.LinearDetection + +end +section +namespace ElementaryPositivity.LinearDetection +open scoped TensorProduct +variable {K A B C D : Type*} [Field K] + [CommRing A] [Algebra K A] [CommRing B] [Algebra K B] + [CommRing C] [Algebra K C] [CommRing D] [Algebra K D] + +noncomputable def middleEmbedding : C⊗[K]B →ₐ[K] (A⊗[K]C)⊗[K](B⊗[K]D) := + Algebra.TensorProduct.map Algebra.TensorProduct.includeRight Algebra.TensorProduct.includeLeft + +lemma middleEmbedding_mul (r : C⊗[K]B) (a : A) (c : C) (b : B) (d : D) : + middleEmbedding r*((a⊗ₜ[K]c)⊗ₜ[K](b⊗ₜ[K]d))= + middleInsert a d (r*(c⊗ₜ[K]b)) := by + induction r using TensorProduct.inductionOn with + | add r s hr hs => rw [map_add,add_mul,add_mul,map_add,hr,hs] + | tmul x y => + change ((1⊗ₜ[K]x)⊗ₜ[K](y⊗ₜ[K]1))*((a⊗ₜ[K]c)⊗ₜ[K](b⊗ₜ[K]d))=_ + simp only [Algebra.TensorProduct.tmul_mul_tmul,one_mul,middleInsert_tmul] + +lemma middleAction_mem_filtration + (P : ℤ → Submodule K A) (Q : ℤ → Submodule K B) + (R : ℤ → Submodule K C) (S : ℤ → Submodule K D) + (δ : ℤ) (r : C⊗[K]B) + (hr : ∀ v w c b,c∈R v → b∈Q w → r*(c⊗ₜ[K]b)∈additiveTensorFiltration R Q (v+w+δ)) + (W : ℤ) (x : (A⊗[K]C)⊗[K](B⊗[K]D)) + (hx : x∈additiveTensorFiltration (additiveTensorFiltration P R) + (additiveTensorFiltration Q S) W) : + middleEmbedding r*x∈additiveTensorFiltration (additiveTensorFiltration P R) + (additiveTensorFiltration Q S) (W+δ) := by + let J:=additiveTensorFiltration (additiveTensorFiltration P R) + (additiveTensorFiltration Q S) (W+δ) + let L : (A⊗[K]C)⊗[K](B⊗[K]D) →ₗ[K] (A⊗[K]C)⊗[K](B⊗[K]D) := + LinearMap.mulLeft K (middleEmbedding r) + change L x∈J + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨u,z,f,g,hw,hf,hg,rfl⟩:=hx + induction hf using Submodule.span_induction with + | mem f hf => + obtain ⟨p,v,a,c,hpv,ha,hc,rfl⟩:=hf + induction hg using Submodule.span_induction with + | mem g hg => + obtain ⟨w,t,b,d,hwt,hb,hd,rfl⟩:=hg + change middleEmbedding r*((a⊗ₜ[K]c)⊗ₜ[K](b⊗ₜ[K]d))∈J + rw [middleEmbedding_mul] + exact additiveTensorFiltration_antitone _ _ (show W+δ≤p+(v+w+δ)+t by omega) + (middleInsert_mem_filtration P Q R S p t (v+w+δ) a d ha hd _ (hr v w c b hc hb)) + | zero => rw [TensorProduct.tmul_zero,L.map_zero]; exact J.zero_mem + | add x y _ _ hx hy => rw [TensorProduct.tmul_add,L.map_add]; exact J.add_mem hx hy + | smul s x _ hx => rw [TensorProduct.tmul_smul,L.map_smul]; exact J.smul_mem s hx + | zero => rw [TensorProduct.zero_tmul,L.map_zero]; exact J.zero_mem + | add x y _ _ hx hy => rw [TensorProduct.add_tmul,L.map_add]; exact J.add_mem hx hy + | smul s x _ hx => rw [←TensorProduct.smul_tmul',L.map_smul]; exact J.smul_mem s hx + | zero => rw [L.map_zero]; exact J.zero_mem + | add x y _ _ hx hy => rw [L.map_add]; exact J.add_mem hx hy + | smul s x _ hx => rw [L.map_smul]; exact J.smul_mem s hx + +end ElementaryPositivity.LinearDetection + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TensorPolynomialLinear.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TensorPolynomialLinear.lean new file mode 100644 index 0000000000000000000000000000000000000000..d44149987bc303e11658ad61338519e97e298125 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TensorPolynomialLinear.lean @@ -0,0 +1,36 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.TensorPolynomialBox + +namespace OAI + +section +namespace ElementaryPositivity.CenterCalculus +open MvPolynomial +open scoped TensorProduct +variable {A B α β : Type*} [CommRing A] [CommRing B] [Algebra ℚ A] [Algebra ℚ B] + +noncomputable def boxRightLinear (p : MvPolynomial α A) : + MvPolynomial β B →ₗ[ℚ] MvPolynomial (α⊕β) (A⊗[ℚ]B) := + { toFun := box p + map_add' := by intro q r; simp only [box,map_add,mul_add] + map_smul' := by + intro r q + ext z + rw [←Finsupp.comapDomain_sumElim_comapDomain z,coeff_box,coeff_smul,coeff_smul,coeff_box] + exact (TensorProduct.mk ℚ A B _).map_smul r _ } + +noncomputable def boxLeftLinear (q : MvPolynomial β B) : + MvPolynomial α A →ₗ[ℚ] MvPolynomial (α⊕β) (A⊗[ℚ]B) := + { toFun := fun p=>box p q + map_add' := by intro p r; simp only [box,map_add,add_mul] + map_smul' := by + intro r p + ext z + rw [←Finsupp.comapDomain_sumElim_comapDomain z,coeff_box,coeff_smul,coeff_smul,coeff_box] + rw [←TensorProduct.smul_tmul',RingHom.id_apply] } + +end ElementaryPositivity.CenterCalculus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/ThresholdWords.lean b/lean/OAI/Combinatorics/Chromatic/Walls/ThresholdWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..878200705990d66139eb11af03ea678b73e8ce3d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/ThresholdWords.lean @@ -0,0 +1,98 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.ThresholdWords +noncomputable section +attribute [local instance] Classical.propDecidable +variable {A : Type*} (P : A → Prop) (μ : A → ℝ) + +abbrev Word := {l : List A // (∀x∈l,P x) ∧ l.Pairwise (fun x y=>μ y<μ x)} +abbrev High (θ : ℝ) := {l : Word P μ // ∀x∈l.val,θ<μ x} +abbrev Low (θ : ℝ) := {l : Word P μ // ∀x∈l.val,μ x≤θ} + +lemma ordered_filter_partition (θ : ℝ) (l : List A) + (hl : l.Pairwise (fun x y=>μ y<μ x)) : + l.filter (fun x=>decide (θ<μ x)) ++ l.filter (fun x=>decide (μ x≤θ))=l := by + induction l with + | nil=>rfl + | cons x l ih=> + have hp:=List.pairwise_cons.mp hl + by_cases hx : θ<μ x + · simpa only [List.filter_cons,decide_eq_true hx,decide_eq_false (not_le.mpr hx), + Bool.false_eq_true,ite_true,ite_false,List.cons_append] using congrArg (List.cons x) (ih hp.2) + · have hx' : μ x≤θ := le_of_not_gt hx + have hall : ∀y∈l,μ y≤θ := fun y hy=>(hp.1 y hy).le.trans hx' + have H : l.filter (fun x=>decide (θ<μ x))=[] := by + simp only [List.filter_eq_nil_iff,decide_eq_true_eq] + exact fun y hy=>not_lt.mpr (hall y hy) + have L : l.filter (fun x=>decide (μ x≤θ))=l := by + apply List.filter_eq_self.mpr + simpa only [decide_eq_true_eq] using hall + simp only [List.filter_cons,decide_eq_false hx,decide_eq_true hx',Bool.false_eq_true,ite_true,ite_false,H,L,List.nil_append] + +def high (θ : ℝ) (l : Word P μ) : High P μ θ := + ⟨⟨l.val.filter (fun x=>decide (θ<μ x)), + ⟨fun x hx=>l.property.1 x (List.mem_of_mem_filter hx), + l.property.2.sublist List.filter_sublist⟩⟩, + fun _ hx=>of_decide_eq_true (List.mem_filter.mp hx).2⟩ + +def low (θ : ℝ) (l : Word P μ) : Low P μ θ := + ⟨⟨l.val.filter (fun x=>decide (μ x≤θ)), + ⟨fun x hx=>l.property.1 x (List.mem_of_mem_filter hx), + l.property.2.sublist List.filter_sublist⟩⟩, + fun _ hx=>of_decide_eq_true (List.mem_filter.mp hx).2⟩ + +def merge (θ : ℝ) (l : High P μ θ) (r : Low P μ θ) : Word P μ := + ⟨l.val.val++r.val.val,⟨fun x hx=>by + rcases List.mem_append.mp hx with hx|hx + · exact l.val.property.1 x hx + · exact r.val.property.1 x hx, + List.pairwise_append.mpr ⟨l.val.property.2,r.val.property.2, + fun x hx y hy=>(r.property y hy).trans_lt (l.property x hx)⟩⟩⟩ + +@[simp] lemma merge_high_low (θ : ℝ) (l : Word P μ) : + merge P μ θ (high P μ θ l) (low P μ θ l)=l := + Subtype.ext (ordered_filter_partition μ θ l.val l.property.2) + +@[simp] lemma high_merge (θ : ℝ) (l : High P μ θ) (r : Low P μ θ) : + high P μ θ (merge P μ θ l r)=l := by + apply Subtype.ext + apply Subtype.ext + change (l.val.val++r.val.val).filter (fun x=>decide (θ<μ x))=l.val.val + rw [List.filter_append] + have H : l.val.val.filter (fun x=>decide (θ<μ x))=l.val.val := by + apply List.filter_eq_self.mpr + simpa only [decide_eq_true_eq] using l.property + have L : r.val.val.filter (fun x=>decide (θ<μ x))=[] := by + simp only [List.filter_eq_nil_iff,decide_eq_true_eq] + exact fun x hx=>not_lt.mpr (r.property x hx) + rw [H,L,List.append_nil] + +@[simp] lemma low_merge (θ : ℝ) (l : High P μ θ) (r : Low P μ θ) : + low P μ θ (merge P μ θ l r)=r := by + apply Subtype.ext + apply Subtype.ext + change (l.val.val++r.val.val).filter (fun x=>decide (μ x≤θ))=r.val.val + rw [List.filter_append] + have H : l.val.val.filter (fun x=>decide (μ x≤θ))=[] := by + simp only [List.filter_eq_nil_iff,decide_eq_true_eq] + exact fun x hx=>not_le.mpr (l.property x hx) + have L : r.val.val.filter (fun x=>decide (μ x≤θ))=r.val.val := by + apply List.filter_eq_self.mpr + simpa only [decide_eq_true_eq] using r.property + rw [H,L,List.nil_append] + +def splitEquiv (θ : ℝ) : Word P μ ≃ High P μ θ × Low P μ θ where + toFun l:=(high P μ θ l,low P μ θ l) + invFun p:=merge P μ θ p.1 p.2 + left_inv l:=merge_high_low P μ θ l + right_inv p:=by simp + +end +end ElementaryPositivity.ThresholdWords + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TorusAdjointExpansion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TorusAdjointExpansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..49abbb4e1545d8cbb292275d890a7a71cc8fd63a --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TorusAdjointExpansion.lean @@ -0,0 +1,88 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.QuantumTorusAlgebra +import OAI.Combinatorics.Chromatic.Walls.AdjointExpansion +import OAI.Combinatorics.Chromatic.Walls.TorusPositive +import OAI.Combinatorics.Chromatic.Walls.TranslatedCompletion + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint LaurentPositive WallUnits +noncomputable section +variable {M : Type*} [AddCommGroup M] +variable (Ω : M →+ M →+ ℤ) +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddCommGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommGroup +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup +local instance : Sub (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toSub +lemma torus_ring_eval_sum {J : Type*} (s : Finset J) (f : J → Torus LaurentRay.vUnit Ω) (r : M) : + (∑j∈s,f j) r=∑j∈s,f j r := by + classical + induction s using Finset.induction_on with + | empty=>rfl + | @insert j s hj ih=> + rw [Finset.sum_insert hj,Finset.sum_insert hj] + change f j r+(∑j∈s,f j) r=_ + rw [ih] +lemma torus_eq_sum_X (f : Torus LaurentRay.vUnit Ω) : + f=∑m∈f.support,f m • Torus.X LaurentRay.vUnit Ω m := by + classical + change f=∑m∈f.support,f m • Finsupp.single m 1 + simpa only [Finsupp.smul_single,smul_eq_mul,mul_one,Finsupp.sum] using (Finsupp.sum_single f).symm +lemma adjoint_torus_expansion (F : PowerSeries (Torus LaurentRay.vUnit Ω)) + (f : Torus LaurentRay.vUnit Ω) (N : ℕ) (r : M) : + coeff N (adjoint F (PowerSeries.C f)) r= + ∑m∈f.support,f m*(coeff N (adjoint F (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m)))) r := by + classical + conv_lhs => rw [torus_eq_sum_X Ω f] + rw [map_sum] + change (coeff N (adjoint F (∑m∈f.support,(PowerSeries.C (f m • Torus.X LaurentRay.vUnit Ω m) : PowerSeries (Torus LaurentRay.vUnit Ω))))) r=_ + simp only [adjoint,Finset.mul_sum,Finset.sum_mul,map_sum] + change (∑m∈f.support,(coeff N (F*PowerSeries.C (f m • Torus.X LaurentRay.vUnit Ω m)*invOfUnit F 1) : Torus LaurentRay.vUnit Ω)) r=_ + rw [torus_ring_eval_sum] + apply Finset.sum_congr rfl + intro m hm + have HC : PowerSeries.C (f m • Torus.X LaurentRay.vUnit Ω m)= + f m • (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m) : PowerSeries (Torus LaurentRay.vUnit Ω)) := by + ext n + rw [coeff_C,coeff_smul,coeff_C] + split_ifs <;> simp + rw [HC,mul_smul_comm,smul_mul_assoc,coeff_smul] + rfl + +lemma adjoint_target_positive (F : PowerSeries (Torus LaurentRay.vUnit Ω)) + (f : Torus LaurentRay.vUnit Ω) (q : M →+ ℤ) (N : ℕ) (r : M) + (hF : ∀n≤N,coeff n F∈chargeGrade LaurentRay.vUnit Ω q 0) + (hf : TorusPositive Ω f) + (hp : ∀m,q m=q r → Positive (coeff N (adjoint F (PowerSeries.C (Torus.X LaurentRay.vUnit Ω m))) r)) : + Positive (coeff N (adjoint F (PowerSeries.C f)) r) := by + classical + rw [adjoint_torus_expansion] + apply Positive.sum + intro m hm + by_cases hq : q m=q r + · exact (hf m).mul (hp m hq) + · have H:=adjoint_charge LaurentRay.vUnit Ω q F N hF m r (Ne.symm hq) + rw [H,mul_zero] + exact positive_zero +lemma adjoint_increment_positive (F X : PowerSeries (Torus LaurentRay.vUnit Ω)) + (q : M →+ ℤ) (N : ℕ) (r : M) (hF0 : constantCoeff F=1) + (hF : ∀n≤N,coeff n F∈chargeGrade LaurentRay.vUnit Ω q 0) + (hX : ∀jhF n (hn.trans (Nat.sub_le _ _))) (hX j (Finset.mem_range.mp hj)) + (fun m hm=>hp m hm _ (Nat.sub_le _ _)) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TorusPositive.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TorusPositive.lean new file mode 100644 index 0000000000000000000000000000000000000000..afab369bb930b8fa74bb0c10039415be65c75967 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TorusPositive.lean @@ -0,0 +1,165 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.RootProducts + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open LaurentPositive WallUnits PowerSeries +noncomputable section +variable {M : Type*} [AddCommGroup M] +variable (Ω : M →+ M →+ ℤ) +local instance : AddCommMonoid (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddCommMonoid +local instance : AddGroup (Torus LaurentRay.vUnit Ω) := (Torus.instRing LaurentRay.vUnit Ω).toAddGroup + +def TorusPositive (f : Torus LaurentRay.vUnit Ω) : Prop := ∀m,Positive (f m) +def IntegralPositive (F : PowerSeries (Torus LaurentRay.vUnit Ω)) : Prop := ∀n,TorusPositive Ω (coeff n F) + +lemma torusPositive_zero : TorusPositive Ω 0 := fun _=>positive_zero +lemma TorusPositive.add {f g : Torus LaurentRay.vUnit Ω} + (hf : TorusPositive Ω f) (hg : TorusPositive Ω g) : TorusPositive Ω (f+g) := + fun m=>(hf m).add (hg m) +lemma TorusPositive.sum {A : Type*} (s : Finset A) (f : A → Torus LaurentRay.vUnit Ω) + (h : ∀a∈s,TorusPositive Ω (f a)) : TorusPositive Ω (∑a∈s,f a) := by + classical + induction s using Finset.induction_on with + | empty => exact torusPositive_zero Ω + | @insert a s ha ih => + rw [Finset.sum_insert ha] + exact (h a (Finset.mem_insert_self _ _)).add Ω (ih (fun b hb=>h b (Finset.mem_insert_of_mem hb))) +lemma torusPositive_monomial (m : M) (r : LaurentSeries ℚ) (hr : Positive r) : + TorusPositive Ω (Torus.monomial LaurentRay.vUnit Ω m r) := by + classical + intro x + change Positive ((Finsupp.single m r) x) + by_cases h : m=x + · subst x + simpa only [Finsupp.single_eq_same] using hr + · simpa only [Finsupp.single_eq_of_ne (Ne.symm h)] using positive_zero + +lemma TorusPositive.mul {f g : Torus LaurentRay.vUnit Ω} + (hf : TorusPositive Ω f) (hg : TorusPositive Ω g) : TorusPositive Ω (f*g) := by + change TorusPositive Ω (Torus.multiply LaurentRay.vUnit Ω f g) + unfold Torus.multiply Finsupp.sum + apply TorusPositive.sum + intro x hx + apply TorusPositive.sum + intro y hy + apply torusPositive_monomial + rw [LaurentRay.vUnit_zpow] + exact ((hf x).mul (hg y)).mul (LaurentPositive.single _ _ natCoeff_one) + +lemma completedPositive_C_X (m : M) : IntegralPositive Ω (C (Torus.X LaurentRay.vUnit Ω m)) := by + intro n + rw [coeff_C] + split + · exact torusPositive_monomial Ω _ _ positive_one + · exact torusPositive_zero Ω + +lemma IntegralPositive.mul {F G : PowerSeries (Torus LaurentRay.vUnit Ω)} + (hF : IntegralPositive Ω F) (hG : IntegralPositive Ω G) : IntegralPositive Ω (F*G) := by + intro n + rw [coeff_mul] + exact TorusPositive.sum Ω _ _ (fun p hp=>(hF p.1).mul Ω (hG p.2)) + +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (w : I → ℕ) [Fact (∀i,0torusPositive_monomial Ω _ _ (hf d.val)) + +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries LaurentPrecision +noncomputable section +variable {M I ι : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) +variable (C : (I→ℤ) →+ M) (l : Filter ι) +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub +attribute [local instance] Classical.propDecidable + +def sumSupport (S T : Finset M) : Finset M := (S×ˢT).image (fun p=>p.1+p.2) + +lemma torus_mul_support (S T : Finset M) (f g : Torus v Ω) + (hf : f.support⊆S) (hg : g.support⊆T) : (f*g).support⊆sumSupport S T := by + intro m hm + by_contra H + apply Finsupp.mem_support_iff.mp hm + rw [torus_mul_finite v Ω S T f g hf hg m] + apply Finset.sum_eq_zero + intro x hx + apply Finset.sum_eq_zero + intro y hy + apply Finsupp.single_eq_of_ne + intro Hxy + apply H + exact Finset.mem_image.mpr ⟨(x,y),Finset.mem_product.mpr ⟨hx,hy⟩,Hxy.symm⟩ + +lemma SeriesConverges.mul_of_support {f g : ι → PowerSeries (Torus v Ω)} + {F G : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) (hg : SeriesConverges v Ω l g G) + (S T : ℕ → Finset M) (hs : ∀i n,(coeff n (f i)).support⊆S n) + (ht : ∀i n,(coeff n (g i)).support⊆T n) + (hS : ∀n,(coeff n F).support⊆S n) (hT : ∀n,(coeff n G).support⊆T n) : + SeriesConverges v Ω l (fun i=>f i*g i) (F*G) := by + intro n + simp only [coeff_mul] + apply TorusConverges.sum + intro p hp + exact (hf p.1).mul_of_support v Ω l (hg p.2) (S p.1) (T p.2) + (fun i=>hs i p.1) (fun i=>ht i p.2) (hS p.1) (hT p.2) + +lemma SeriesConverges.mul_C {f : ι → PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) (hfg : ∀i,SeriesGraded v Ω C (f i)) + (hF : SeriesGraded v Ω C F) (x : Torus v Ω) : + SeriesConverges v Ω l (fun i=>f i*PowerSeries.C x) (F*PowerSeries.C x) := by + intro n + simp only [coeff_mul_C] + exact (hf n).mul_of_support v Ω l (torusConverges_const v Ω l x) + (rootDegree_finite C n).toFinset x.support + (fun i=>rootGrade_support v Ω C n _ (hfg i n)) (fun _=>Finset.Subset.refl _) + (rootGrade_support v Ω C n _ (hF n)) (Finset.Subset.refl _) + +lemma SeriesGraded.mul_C_support {F : PowerSeries (Torus v Ω)} + (hF : SeriesGraded v Ω C F) (x : Torus v Ω) (n : ℕ) : + (coeff n (F*PowerSeries.C x)).support⊆sumSupport (rootDegree_finite C n).toFinset x.support := by + rw [coeff_mul_C] + exact torus_mul_support v Ω _ _ _ _ (rootGrade_support v Ω C n _ (hF n)) (Finset.Subset.refl _) + +theorem SeriesConverges.adjoint {f : ι → PowerSeries (Torus v Ω)} {F : PowerSeries (Torus v Ω)} + (hf : SeriesConverges v Ω l f F) + (hfg : ∀i,SeriesGraded v Ω C (f i)) (hF : SeriesGraded v Ω C F) (x : Torus v Ω) : + SeriesConverges v Ω l (fun i=>f i*PowerSeries.C x*invOfUnit (f i) 1) + (F*PowerSeries.C x*invOfUnit F 1) := by + exact (hf.mul_C v Ω C l hfg hF x).mul_of_support v Ω l + (hf.inverse v Ω C l hfg hF) + (fun n=>sumSupport (rootDegree_finite C n).toFinset x.support) + (fun n=>(rootDegree_finite C n).toFinset) + (fun i n=>(hfg i).mul_C_support v Ω C x n) + (fun i n=>rootGrade_support v Ω C n _ ((hfg i).inverse v Ω C n)) + (fun n=>hF.mul_C_support v Ω C x n) + (fun n=>rootGrade_support v Ω C n _ (hF.inverse v Ω C n)) + +variable [l.NeBot] +lemma IntegralPositive.of_converges {f : ι → PowerSeries (Torus WallUnits.LaurentRay.vUnit Ω)} + {F : PowerSeries (Torus WallUnits.LaurentRay.vUnit Ω)} + (hf : SeriesConverges WallUnits.LaurentRay.vUnit Ω l f F) + (hp : ∀ᶠi in l,IntegralPositive Ω (f i)) : IntegralPositive Ω F := by + intro n m + exact LaurentPositive.of_converges l (hf n m) (hp.mono (fun i hi=>hi n m)) + +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TranslatedCompletion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TranslatedCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb82c0e76f26258af6cd8bc6da9178a8d379eb49 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TranslatedCompletion.lean @@ -0,0 +1,184 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.CompletedInverse + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +local instance shiftRootGradeAddCommGroup : AddCommGroup (Torus v Ω) := (Torus.instRing v Ω).toAddCommGroup +local instance shiftRootGradeSub : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub +local instance shiftRootGradeAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def shiftRootGrade (b : M) (n : ℕ) : AddSubgroup (Torus v Ω) where + carrier:={f | ∀m,¬HasRootDegree C n (m-b) → f m=0} + zero_mem':=by intro m hm; rfl + add_mem':=by intro f g hf hg m hm; change f m+g m=0; rw [hf m hm,hg m hm,add_zero] + neg_mem':=by intro f hf m hm; change -f m=0; rw [hf m hm,neg_zero] +def ShiftGraded (b : M) (X : PowerSeries (Torus v Ω)) : Prop := + ∀n,coeff n X∈shiftRootGrade v Ω C b n +lemma shiftRootGrade_finite (b : M) (n : ℕ) : {m | HasRootDegree C n (m-b)}.Finite := by + apply ((rootDegree_finite C n).image (fun r=>r+b)).subset + intro m hm + exact ⟨m-b,hm,sub_add_cancel m b⟩ +lemma shiftRootGrade_mul (b c : M) (n k : ℕ) (f g : Torus v Ω) + (hf : f∈shiftRootGrade v Ω C b n) (hg : g∈shiftRootGrade v Ω C c k) : + f*g∈shiftRootGrade v Ω C (b+c) (n+k) := by + classical + intro m hm + change (Torus.multiply v Ω f g) m=0 + simp only [Torus.multiply,Finsupp.sum,Finsupp.finsetSum_apply] + apply Finset.sum_eq_zero + intro x hx + apply Finset.sum_eq_zero + intro y hy + have hxC : HasRootDegree C n (x-b):=by by_contra hn; exact (Finsupp.mem_support_iff.mp hx) (hf x hn) + have hyC : HasRootDegree C k (y-c):=by by_contra hn; exact (Finsupp.mem_support_iff.mp hy) (hg y hn) + apply Finsupp.single_eq_of_ne + intro he + apply hm + rw [he] + convert rootDegree_add C hxC hyC using 1; abel +lemma ShiftGraded.mul {b c : M} {X Y : PowerSeries (Torus v Ω)} + (hX : ShiftGraded v Ω C b X) (hY : ShiftGraded v Ω C c Y) : + ShiftGraded v Ω C (b+c) (X*Y) := by + intro n + rw [coeff_mul] + apply (shiftRootGrade v Ω C (b+c) n).sum_mem + intro p hp + rw [←Finset.HasAntidiagonal.mem_antidiagonal.mp hp] + exact shiftRootGrade_mul v Ω C b c p.1 p.2 _ _ (hX p.1) (hY p.2) +lemma shiftGraded_zero_iff (F : PowerSeries (Torus v Ω)) : + ShiftGraded v Ω C 0 F↔SeriesGraded v Ω C F := by + simp only [ShiftGraded,SeriesGraded,shiftRootGrade,rootGrade,AddSubgroup.mem_mk,sub_zero] +lemma ShiftGraded.adjoint {b : M} {X : PowerSeries (Torus v Ω)} + (hX : ShiftGraded v Ω C b X) (F : CompletedPositive v Ω C) : + ShiftGraded v Ω C b (adjoint F.val X) := by + have hF:=(shiftGraded_zero_iff v Ω C F.val).mpr F.property.2 + have hI:=(shiftGraded_zero_iff v Ω C (completedInverse v Ω C F).val).mpr + (completedInverse v Ω C F).property.2 + simpa only [zero_add,add_zero,PowerSeriesAdjoint.adjoint,completedInverse] using (hF.mul v Ω C hX).mul v Ω C hI +lemma ShiftGraded.sub {b : M} {X Y : PowerSeries (Torus v Ω)} + (hX : ShiftGraded v Ω C b X) (hY : ShiftGraded v Ω C b Y) : + ShiftGraded v Ω C b (X-Y) := by + intro n + exact (shiftRootGrade v Ω C b n).sub_mem (hX n) (hY n) +lemma ShiftGraded.monomial (b : M) : + ShiftGraded v Ω C b (PowerSeries.C (Torus.X v Ω b)) := by + intro n + rw [coeff_C] + split_ifs with hn + · subst n + intro m hm + change (Finsupp.single b (1:LaurentSeries ℚ)) m=0 + apply Finsupp.single_eq_of_ne + intro he + apply hm + rw [←he,sub_self] + exact rootDegree_zero C + · exact (shiftRootGrade v Ω C b n).zero_mem + +def sectionValue (F : CompletedPositive v Ω C) (h : M →+ ℝ) + (X : PowerSeries (Torus v Ω)) : PowerSeries (Torus v Ω) := + adjoint (chartNegative v Ω C h F).val X +lemma ShiftGraded.sectionValue {b : M} {X : PowerSeries (Torus v Ω)} + (hX : ShiftGraded v Ω C b X) (F : CompletedPositive v Ω C) (h : M →+ ℝ) : + ShiftGraded v Ω C b (sectionValue v Ω C F h X) := + hX.adjoint v Ω C (chartNegative v Ω C h F) +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint +noncomputable section +variable {M : Type*} [AddCommGroup M] +variable (v : (LaurentSeries ℚ)ˣ) (Ω : M →+ M →+ ℤ) (q : M →+ ℤ) +local instance chargeGradeAddCommGroup : AddCommGroup (Torus v Ω) := (Torus.instRing v Ω).toAddCommGroup +local instance chargeGradeAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup +local instance chargeGradeSub : Sub (Torus v Ω) := (Torus.instRing v Ω).toSub + +def chargeGrade (z : ℤ) : AddSubgroup (Torus v Ω) where + carrier:={f | ∀m,q m≠z → f m=0} + zero_mem':=by intro m hm; rfl + add_mem':=by intro f g hf hg m hm; change f m+g m=0; rw [hf m hm,hg m hm,add_zero] + neg_mem':=by intro f hf m hm; change -f m=0; rw [hf m hm,neg_zero] +lemma chargeGrade_one : (1:Torus v Ω)∈chargeGrade v Ω q 0 := by + intro m hm + change (Finsupp.single 0 (1:LaurentSeries ℚ)) m=0 + apply Finsupp.single_eq_of_ne + intro he + exact hm (by rw [he,map_zero]) +lemma chargeGrade_X (m : M) : Torus.X v Ω m∈chargeGrade v Ω q (q m) := by + intro r hr + change (Finsupp.single m (1:LaurentSeries ℚ)) r=0 + apply Finsupp.single_eq_of_ne + exact fun he=>hr (congrArg q he) +lemma chargeGrade_mul (a b : ℤ) (f g : Torus v Ω) + (hf : f∈chargeGrade v Ω q a) (hg : g∈chargeGrade v Ω q b) : + f*g∈chargeGrade v Ω q (a+b) := by + classical + intro m hm + change (Torus.multiply v Ω f g) m=0 + simp only [Torus.multiply,Finsupp.sum,Finsupp.finsetSum_apply] + apply Finset.sum_eq_zero + intro x hx + apply Finset.sum_eq_zero + intro y hy + have hxq : q x=a:=by by_contra hn; exact (Finsupp.mem_support_iff.mp hx) (hf x hn) + have hyq : q y=b:=by by_contra hn; exact (Finsupp.mem_support_iff.mp hy) (hg y hn) + apply Finsupp.single_eq_of_ne + intro he + apply hm + rw [he,map_add,hxq,hyq] +lemma chargeGrade_series_mul (a b : ℤ) (F G : PowerSeries (Torus v Ω)) (N : ℕ) + (hF : ∀n≤N,coeff n F∈chargeGrade v Ω q a) + (hG : ∀n≤N,coeff n G∈chargeGrade v Ω q b) : + coeff N (F*G)∈chargeGrade v Ω q (a+b) := by + rw [coeff_mul] + apply (chargeGrade v Ω q (a+b)).sum_mem + intro p hp + have H:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + exact chargeGrade_mul v Ω q a b _ _ (hF p.1 (by omega)) (hG p.2 (by omega)) +lemma chargeGrade_inverse (F : PowerSeries (Torus v Ω)) (N : ℕ) + (hF : ∀n≤N,coeff n F∈chargeGrade v Ω q 0) : + ∀n≤N,coeff n (invOfUnit F 1)∈chargeGrade v Ω q 0 := by + intro n hn + induction n using Nat.strong_induction_on with + | h n ih => + rw [coeff_inverse_one] + split_ifs with h0 + · exact chargeGrade_one v Ω q + · apply (chargeGrade v Ω q 0).neg_mem + apply (chargeGrade v Ω q 0).sum_mem + intro p hp + split_ifs with hp2 + · have H:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + simpa only [add_zero] using chargeGrade_mul v Ω q 0 0 _ _ + (hF p.1 (by omega)) (ih p.2 hp2 (by omega)) + · exact (chargeGrade v Ω q 0).zero_mem +lemma adjoint_charge (F : PowerSeries (Torus v Ω)) (N : ℕ) + (hF : ∀n≤N,coeff n F∈chargeGrade v Ω q 0) (m : M) : + coeff N (adjoint F (PowerSeries.C (Torus.X v Ω m)))∈chargeGrade v Ω q (q m) := by + have hm : ∀n≤N,coeff n (PowerSeries.C (Torus.X v Ω m))∈chargeGrade v Ω q (q m):=by + intro n hn + rw [coeff_C] + split_ifs + · exact chargeGrade_X v Ω q m + · exact (chargeGrade v Ω q (q m)).zero_mem + have hFI : ∀n≤N,coeff n (F*PowerSeries.C (Torus.X v Ω m))∈chargeGrade v Ω q (q m):=by + intro n hn + simpa only [zero_add] using chargeGrade_series_mul v Ω q 0 (q m) _ _ n + (fun j hj=>hF j (hj.trans hn)) (fun j hj=>hm j (hj.trans hn)) + simpa only [add_zero,adjoint] using chargeGrade_series_mul v Ω q (q m) 0 _ _ N hFI + (chargeGrade_inverse v Ω q F N hF) +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularAnchorProjection.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularAnchorProjection.lean new file mode 100644 index 0000000000000000000000000000000000000000..8017475c0d9974e5f3f4427b7ab2dd7b4d2f9d83 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularAnchorProjection.lean @@ -0,0 +1,148 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularMonomialCriterion +import OAI.Combinatorics.Chromatic.QuantumTorus.OrdinaryElementaryExpressions + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} +local instance triangularAnchorProjectionRing : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := + Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance triangularAnchorProjectionAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit (extendedOmega n)) := + (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommMonoid +local instance triangularAnchorProjectionAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := + (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup +local instance triangularAnchorProjectionAddGroup : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := + (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup +local instance triangularAnchorProjectionSub : Sub (Torus LaurentRay.vUnit (extendedOmega n)) := + (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toSub + +def bridgeCut : Extended (Vertex n (Cell n)) →+ ℝ where + toFun m:= -∑b:Cell n,(m.1 (.inr b):ℝ) + map_zero':=by simp + map_add' m r:=by simp [Finset.sum_add_distrib,add_comm] + +lemma bridgeCut_anchor (a:Fin (n+1)) : bridgeCut (includeVertices (anchor a))=0 := by + simp [bridgeCut,anchor] +lemma bridgeCut_bridge (b:Cell n) : bridgeCut (includeVertices (bridge b))= -1 := by + simp [bridgeCut,bridge,Pi.single_apply] +lemma bridgeCut_pure (μ:Fin (n+1) → ℤ) : bridgeCut (includeVertices (pureAnchor μ))=0 := by + simp only [pureAnchor,map_sum,map_zsmul,bridgeCut_anchor,zsmul_zero,Finset.sum_const_zero] + +lemma triangularSeed_bridgeCut {N:ℕ} (f:ElementaryExpr N) : + triangularExpression f∈supportedSubring LaurentRay.vUnit (extendedOmega n) (nonpositiveCone bridgeCut) := by + intro m hm + by_contra hn + apply hm + change -(∑b:Cell n,(m.1 (.inr b):ℝ)) ≤ 0 + apply neg_nonpos.mpr + apply Finset.sum_nonneg + intro b _ + exact_mod_cast triangularSeed_nonneg f m (Finsupp.mem_support_iff.mpr hn) (.inr b) + +lemma anchorExponent_single (a:Fin (n+1)) : + anchorExponent (Finsupp.single a 1)=includeVertices (anchor a) := by + apply Prod.ext + · ext b + cases b with + | inl b=>simp [anchorExponent,pureAnchor_apply_anchor,anchor,Pi.single_apply,Finsupp.single_apply,eq_comm] + | inr b=>simp [anchorExponent,pureAnchor_apply_bridge,anchor] + · rfl + +lemma anchorPolynomial_esymm (k:ℕ) : + anchorPolynomial (MvPolynomial.esymm (Fin (n+1)) (LaurentSeries ℚ) k)= + ∑s:Finset (Fin (n+1)),if s.card=k then + Torus.X LaurentRay.vUnit (extendedOmega n) (∑a∈s,includeVertices (anchor a)) else 0 := by + rw [MvPolynomial.esymm_eq_sum_monomial,map_sum] + have he:Finset.powersetCard k (Finset.univ:Finset (Fin (n+1)))= + (Finset.univ:Finset (Finset (Fin (n+1)))).filter (fun s=>s.card=k):=by ext s; simp + rw [he,Finset.sum_filter] + apply Finset.sum_congr rfl + intro s _ + split_ifs + · change anchorPolynomialAdd (MvPolynomial.monomial _ 1)=_ + rw [anchorPolynomial_monomial,map_sum] + simp only [anchorExponent_single,Torus.X] + · rfl + +lemma independent_projection_pair (k:ℕ) (s:Finset (Fin (n+1))) (t:Finset (Cell n)) : + zeroProject LaurentRay.vUnit (extendedOmega n) bridgeCut + (independentTerm LaurentRay.vUnit (extendedOmega n) + (vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge)) k (s.disjSum t))= + if t=∅ then (if s.card=k then + Torus.X LaurentRay.vUnit (extendedOmega n) (∑a∈s,includeVertices (anchor a)) else 0) else 0 := by + have hsum:(∑x∈s.disjSum t,vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge) x)= + (∑a∈s,includeVertices (anchor a))+(∑b∈t,includeVertices (bridge b)):=by + exact sum_labels_disjSum _ _ s t + have hcut:bridgeCut (∑x∈s.disjSum t,vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge) x)= -(t.card:ℝ):=by + rw [hsum,map_add,map_sum,map_sum] + simp only [bridgeCut_anchor,bridgeCut_bridge,Finset.sum_const_zero,zero_add,Finset.sum_const,nsmul_eq_mul,mul_neg,mul_one] + by_cases ht:t=∅ + · subst t + have hind:IsIndependent (extendedOmega n) + (vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge)) (s.disjSum ∅):=by + intro x hx y hy + obtain ⟨a,ha,rfl⟩:=Finset.mem_disjSum.mp hx |>.resolve_right (by simp) + obtain ⟨b,hb,rfl⟩:=Finset.mem_disjSum.mp hy |>.resolve_right (by simp) + change extendedOmega n (includeVertices (anchor a)) (includeVertices (anchor b))=0 + rw [extendedOmega_original] + exact omega_anchors a b + simp only [independentTerm,hind,true_and,Finset.card_disjSum,Finset.card_empty,add_zero,ite_true] + split_ifs with hc + · rw [setMonomial,Torus.X,zeroProject_monomial,show bridgeCut (∑x∈s.disjSum ∅,vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge) x)=0 by simpa using hcut,ite_eq_left rfl,hsum] + simp only [Finset.sum_empty,add_zero,Torus.X] + · exact map_zero _ + · rw [ite_eq_right ht,independentTerm] + split_ifs + · rw [setMonomial,Torus.X,zeroProject_monomial,ite_eq_right] + rw [hcut] + simpa only [neg_eq_zero,Nat.cast_eq_zero,Finset.card_eq_zero] using ht + · exact map_zero _ + +lemma triangularAtom_projection (k:ℕ) : + zeroProject LaurentRay.vUnit (extendedOmega n) bridgeCut (triangularExpression (.atom k))= + anchorPolynomial (MvPolynomial.esymm (Fin (n+1)) (LaurentSeries ℚ) k) := by + change zeroProject _ _ _ (independentElement _ _ (Sum.elim _ _) k)=_ + rw [independent_sum_decomposition] + change zeroProject _ _ _ (∑t:Finset (Cell n),∑s:Finset (Fin (n+1)), + independentTerm LaurentRay.vUnit (extendedOmega n) + (vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge)) k (s.disjSum t))=_ + rw [map_sum,anchorPolynomial_esymm] + simp only [map_sum,independent_projection_pair] + rw [Finset.sum_eq_single (∅:Finset (Cell n))] + · simp only [ite_true] + · intro t _ ht + simp only [ite_eq_right ht,Finset.sum_const_zero] + · simp + +lemma triangularExpression_projection {N:ℕ} (f:ElementaryExpr N) : + zeroProject LaurentRay.vUnit (extendedOmega n) bridgeCut (triangularExpression f)= + anchorPolynomial (f.ordinary (σ:=Fin (n+1)) (R:=LaurentSeries ℚ)) := by + induction f with + | zero k=>exact (map_zero _).trans (map_zero _).symm + | one=>exact (zeroProject_one _ _ _).trans (map_one _).symm + | atom k=>exact triangularAtom_projection k + | add f g hf hg=>simpa only [triangularExpression,ElementaryExpr.eval,ElementaryExpr.ordinary,map_add] using congrArg₂ (fun a b=>a+b) hf hg + | neg f hf=>simpa only [triangularExpression,ElementaryExpr.eval,ElementaryExpr.ordinary,map_neg] using congrArg Neg.neg hf + | mul f g hf hg=> + change zeroProject _ _ _ (triangularExpression f*triangularExpression g)=anchorPolynomial (f.ordinary*g.ordinary) + rw [zeroProject_mul_nonpositive _ _ _ _ _ (triangularSeed_bridgeCut f) (triangularSeed_bridgeCut g),hf,hg,map_mul] + +lemma triangularExpression_anchorCoeff {N:ℕ} (f:ElementaryExpr N) (d:Fin (n+1) →₀ ℕ) : + triangularExpression f (anchorExponent d)=(f.ordinary (σ:=Fin (n+1)) (R:=LaurentSeries ℚ)).coeff d := by + have H:=congrArg (fun t:Torus LaurentRay.vUnit (extendedOmega n)=>t (anchorExponent d)) (triangularExpression_projection (n:=n) f) + rw [show (anchorPolynomial (f.ordinary (σ:=Fin (n+1)) (R:=LaurentSeries ℚ))) (anchorExponent d)= + (f.ordinary (σ:=Fin (n+1)) (R:=LaurentSeries ℚ)).coeff d from anchorPolynomial_coeff _ d] at H + change ((triangularExpression f).filter (fun m=>bridgeCut m=0)) (anchorExponent d)=_ at H + simpa only [Finsupp.filter_apply,show bridgeCut (anchorExponent d)=0 from bridgeCut_pure _,ite_true] using H +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularAnchored.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularAnchored.lean new file mode 100644 index 0000000000000000000000000000000000000000..02daed89fce1c2fe5dbd35d688780defe812da77 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularAnchored.lean @@ -0,0 +1,136 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularMonomialProducer +import OAI.Combinatorics.Chromatic.QuantumTorus.ExpressionAdditiveOperations + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization PowerSeries PowerSeriesAdjoint +open scoped BigOperators +open Classical +noncomputable section +variable {n : ℕ} + +lemma triangularIncoming_zero (N : ℕ) (m : Lattice n (Cell n)) : + triangularIncoming (.zero N) m = 0 := by + simp [triangularIncoming,triangularExpression,ElementaryExpr.eval,polynomialSectionIncoming, + polynomialSectionCoefficient,actualPolynomialAdjointCoefficient] +lemma triangularIncoming_add {N : ℕ} (f g : ElementaryExpr N) (m : Lattice n (Cell n)) : + triangularIncoming (.add f g) m = triangularIncoming f m + triangularIncoming g m := + actualPolynomialAdjointCoefficient_add _ _ _ _ _ _ +lemma triangularIncoming_neg {N : ℕ} (f : ElementaryExpr N) (m : Lattice n (Cell n)) : + triangularIncoming (.neg f) m = -triangularIncoming f m := by + have H := triangularIncoming_add f (.neg f) m + have hz : triangularIncoming (.add f (.neg f)) m = 0 := by + change actualPolynomialAdjointCoefficient _ _ _ (triangularExpression f + -triangularExpression f) _ = 0 + rw [add_neg_cancel] + simp [actualPolynomialAdjointCoefficient] + rw [hz] at H + exact eq_neg_of_add_eq_zero_right H.symm + +def AnchorSupported {N:ℕ} (f : ElementaryExpr N) : Prop := + ∀ m : Lattice n (Cell n), triangularIncoming f m ≠ 0 → + ∃ μ : Fin (n+1) →₀ ℕ, μ.degree = N ∧ + (∀ i : Fin n, μ i.succ ≤ μ i.castSucc) ∧ m = natAnchor (fun a => μ a) + +lemma AnchorSupported.zero (N:ℕ) : AnchorSupported (n:=n) (.zero N) := by + intro m h; exact (h (triangularIncoming_zero N m)).elim +lemma AnchorSupported.add {N:ℕ} {f g:ElementaryExpr N} + (hf:AnchorSupported (n:=n) f) (hg:AnchorSupported (n:=n) g) : + AnchorSupported (n:=n) (.add f g) := by + intro m hm + rw [triangularIncoming_add] at hm + by_cases h:triangularIncoming f m=0 + · rw [h,zero_add] at hm; exact hg m hm + · exact hf m h +lemma AnchorSupported.neg {N:ℕ} {f:ElementaryExpr N} (hf:AnchorSupported (n:=n) f) : + AnchorSupported (n:=n) (.neg f) := by + intro m hm + rw [triangularIncoming_neg] at hm + exact hf m (fun h=>hm (by rw [h,neg_zero])) +lemma AnchorSupported.nscale {N:ℕ} {f:ElementaryExpr N} (hf:AnchorSupported (n:=n) f) (k:ℕ) : + AnchorSupported (n:=n) (f.nscale k) := by + induction k with + | zero=>exact AnchorSupported.zero N + | succ k ih=>exact ih.add hf +lemma AnchorSupported.zscale {N:ℕ} {f:ElementaryExpr N} (hf:AnchorSupported (n:=n) f) (z:ℤ) : + AnchorSupported (n:=n) (f.zscale z) := by + cases z with + | ofNat k=>exact hf.nscale k + | negSucc k=>exact (hf.nscale (k+1)).neg + +lemma monomial_producer_supported (μ : Fin (n+1) →₀ ℕ) + (hμ:∀i:Fin n, μ i.succ ≤ μ i.castSucc) : + ∃ f:ElementaryExpr μ.degree, + f.ordinary=(OrbitMonomial.polynomial μ : MvPolynomial (Fin (n+1)) ℤ) ∧ + AnchorSupported (n:=n) f := by + obtain ⟨f,hf,d,hd,he⟩:=triangularMonomial_producer μ hμ + refine ⟨f,hf,?_⟩ + intro m hm + obtain ⟨c,hc⟩:=triangularIncoming_in_rootCone f m hm + let k:=∑i,c i + have hk:HasRootDegree (extendedRoots n) k (includeVertices m-triangularBase μ.degree):=by + refine ⟨c,rfl,?_⟩ + change includeVertices (forwardRoots (fun i=>(c i:ℤ)))=includeVertices m-includeVertices ((μ.degree:ℤ) • anchor 0) + rw [hc,map_add,add_sub_cancel_left] + have H := polynomialInitial_incoming (extendedOmega n) extendedOmega_self (extendedRoots n) + (extendedCoord n) extendedCoord_roots (triangularBase μ.degree) (triangularBase_order μ.degree) + (triangularExpression f) (by intro a ha; exact triangularSeed_in_rootCone f a (Finsupp.mem_support_iff.mpr ha)) k _ hk + rw [he,coneThetaInitial_prescription _ _ _ _ _ _ hd] at H + have hlabel:includeVertices m=anchorExponent μ:=by + by_contra hh + have hz:coneDelta (extendedOmega n) d (anchorExponent μ) k (includeVertices m)=0:=by + unfold coneDelta + split_ifs + · exact Finsupp.single_eq_of_ne hh + · rfl + exact hm (H.symm.trans hz) + exact ⟨μ,rfl,hμ,congrArg Prod.fst hlabel⟩ + +lemma triangularExpression_anchorSupported {N:ℕ} (f:ElementaryExpr N) : AnchorSupported (n:=n) f := by + let p:MvPolynomial (Fin (n+1)) ℤ:=f.ordinary + let s:=p.support.filter (fun μ=>∀i:Fin n,μ i.succ ≤ μ i.castSucc) + have ht:∀μ∈s,∃g:ElementaryExpr N, + g.ordinary=MvPolynomial.C (p.coeff μ)*OrbitMonomial.polynomial μ ∧ AnchorSupported (n:=n) g:=by + intro μ hμ + obtain ⟨hmem,hdom⟩:=Finset.mem_filter.mp hμ + have hdeg:μ.degree=N:=by + by_contra h + exact (MvPolynomial.mem_support_iff.mp hmem) (f.ordinary_homogeneous.coeff_eq_zero h) + obtain ⟨g,hg,hs⟩:=monomial_producer_supported μ hdom + let g':ElementaryExpr N:=hdeg ▸ g + have ho:g'.ordinary=(OrbitMonomial.polynomial μ:MvPolynomial (Fin (n+1)) ℤ):=by + rw [ElementaryExpr.ordinary_cast]; exact hg + have hs':AnchorSupported (n:=n) g':=by + subst N; exact hs + refine ⟨g'.zscale (p.coeff μ),?_,hs'.zscale _⟩ + rw [ElementaryExpr.ordinary_zscale,ho,zsmul_eq_mul] + congr 1 + have hw:∀t:Finset (Fin (n+1) →₀ ℕ),t⊆s → ∃g:ElementaryExpr N, + g.ordinary=∑μ∈t,MvPolynomial.C (p.coeff μ)*OrbitMonomial.polynomial μ ∧ AnchorSupported (n:=n) g:=by + intro t + induction t using Finset.induction with + | empty=>intro _; exact ⟨.zero N,by simp [ElementaryExpr.ordinary],AnchorSupported.zero N⟩ + | @insert μ t hμ ih=> + intro h + obtain ⟨g,hg,hs⟩:=ht μ (h (Finset.mem_insert_self _ _)) + obtain ⟨g',hg',hs'⟩:=ih (fun a ha=>h (Finset.mem_insert_of_mem ha)) + refine ⟨.add g g',?_,hs.add hs'⟩ + change g.ordinary+g'.ordinary=_ + rw [hg,hg',Finset.sum_insert hμ] + obtain ⟨g,hg,hs⟩:=hw s (fun _=>id) + have hp:p=∑μ∈s,MvPolynomial.C (p.coeff μ)*OrbitMonomial.polynomial μ:= + OrbitMonomial.symmetric_orbit_decomposition p f.ordinary_symmetric + have he:triangularExpression (n:=n) f=triangularExpression g:= + triangularExpression_ordinary_equal f g (hp.trans hg.symm) + intro m hm + have hi:triangularIncoming f m=triangularIncoming g m:=by unfold triangularIncoming; rw [he] + rw [hi] at hm + exact hs m hm +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularCommutativity.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularCommutativity.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd599aee3c8a0ab3bb812e04f5fa0f1f63c53649 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularCommutativity.lean @@ -0,0 +1,204 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.SectionGenericPerturbation +import OAI.Combinatorics.Chromatic.Walls.TriangularLinearSection + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension +open Classical +noncomputable section +variable {n:ℕ} +local instance triangularCommutativityRing : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance triangularCommutativityAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup +local instance triangularCommutativityAddGroup : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup +local instance triangularCommutativitySub : Sub (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toSub + +lemma pureAnchor_pair (μ ν:Fin (n+1) → ℤ) : triangularOmega n (pureAnchor μ) (pureAnchor ν)=0 := by + rw [pureAnchor,map_sum,AddMonoidHom.finsetSum_apply] + simp only [map_zsmul,AddMonoidHom.zsmul_apply,anchor_pair_pure,zsmul_zero,Finset.sum_const_zero] + +lemma pure_product_cyclic {k l:ℕ} (f:ElementaryExpr k) (g:ElementaryExpr l) (μ:Fin (n+1) → ℤ) : + (triangularExpression (n:=n) f*triangularExpression (n:=n) g) (includeVertices (pureAnchor μ))= + (triangularExpression (n:=n) g*triangularExpression (n:=n) f) (includeVertices (pureAnchor μ)) := by + apply torus_target_cyclic LaurentRay.vUnit (extendedOmega n) extendedOmega_self + intro r hr s hs he + have hbridge:∀b,r.1 (.inr b)=0:=by + intro b + have H:=congrArg (fun x:Extended (Vertex n (Cell n))=>x.1 (.inr b)) he + change r.1 (.inr b)+s.1 (.inr b)=pureAnchor μ (.inr b) at H + rw [pureAnchor_apply_bridge] at H + have h1:=triangularSeed_nonneg f r hr (.inr b) + have h2:=triangularSeed_nonneg g s hs (.inr b) + omega + have hdual:=triangularSeed_dual_zero f r hr + have hr':r=includeVertices (pureAnchor (fun a=>r.1 (.inl a))):=by + apply Prod.ext + · exact pureAnchor_of_bridges_zero r.1 hbridge + · exact hdual + rw [hr',extendedOmega_original,pureAnchor_pair] + +lemma triangularPure_equal {N:ℕ} (f g:ElementaryExpr N) + (hp:∀μ:Fin (n+1) → ℤ,triangularExpression f (includeVertices (pureAnchor μ))= + triangularExpression g (includeVertices (pureAnchor μ))) : + triangularExpression (n:=n) f=triangularExpression g := by + have H:=triangularPure_detect (.add f (.neg g)) (by + intro μ + change triangularExpression f (includeVertices (pureAnchor μ))+ + -(triangularExpression g (includeVertices (pureAnchor μ)))=0 + rw [hp,add_neg_cancel]) + change triangularExpression f+ -(triangularExpression g)=0 at H + exact sub_eq_zero.mp H + +lemma triangularExpression_cast {k l:ℕ} (h:k=l) (f:ElementaryExpr k) : + triangularExpression (n:=n) (h ▸ f)=triangularExpression f := by subst l; rfl + +theorem triangularExpression_commute {k l:ℕ} (f:ElementaryExpr k) (g:ElementaryExpr l) : + Commute (triangularExpression (n:=n) f) (triangularExpression g) := by + let h:ElementaryExpr (k+l):=Nat.add_comm l k ▸ (.mul g f) + have hh:triangularExpression (n:=n) h=triangularExpression g*triangularExpression f:=by + exact triangularExpression_cast (Nat.add_comm l k) (.mul g f) + have H:=triangularPure_equal (.mul f g) h (by intro μ; rw [hh]; exact pure_product_cyclic f g μ) + exact H.trans hh +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit FiniteRayGeometry LaurentPositive WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in +lemma section_line_step (N : ℕ) (r : M) (F : CompletedPositive LaurentRay.vUnit Ω C) + (walls : WallsPositiveThrough Ω C e N F) (X : PowerSeries (Torus LaurentRay.vUnit Ω)) + (ih : ∀j0,∀δ : ℝ,0<δ → δ<ε → + Positive (coeff N (sectionValue LaurentRay.vUnit Ω C F ((k+(a+δ) • B.flip (e r)).toAddMonoidHom.comp e) X) r) → + Positive (coeff N (sectionValue LaurentRay.vUnit Ω C F ((k+(a-δ) • B.flip (e r)).toAddMonoidHom.comp e) X) r) := by + have hΩ : ∀m,Ω m m=0:=by + intro m; have HH:=hB (e m); rw [hcomp] at HH; exact_mod_cast HH + obtain ⟨p,d,hd,hdN,hp,hv,hgen⟩:=section_event_ray C e he L hdeg N (B.flip (e r)) k H a ha + let h:=(k+a • B.flip (e r)).toAddMonoidHom.comp e + let dir:=(B.flip (e r)).toAddMonoidHom.comp e + obtain ⟨εp,hεp,Hεp⟩:=root_lex_epsilon C N h dir + obtain ⟨εm,hεm,Hεm⟩:=root_lex_epsilon C N h (-dir) + refine ⟨min εp εm,lt_min hεp hεm,?_⟩ + intro δ hδ hδε hplus + have hδp:=lt_of_lt_of_le hδε (min_le_left _ _) + have hδm:=lt_of_lt_of_le hδε (min_le_right _ _) + let hpM:=(k+(a+δ) • B.flip (e r)).toAddMonoidHom.comp e + let hmM:=(k+(a-δ) • B.flip (e r)).toAddMonoidHom.comp e + have HC:=section_ray_crossing LaurentRay.vUnit Ω C F X N p h dir hpM hmM hgen + (by simpa only [hpM,line_covector_add] using Hεp δ hδ hδp) + (by simpa only [hmM,line_covector_sub] using Hεm δ hδ hδm) + have HS : ∀n,0ih j hj (k+(a+δ) • B.flip (e r))) + have Hpair : dir p=(Ω p r:ℝ):=hcomp p r + have Hne : dir p≠0:=hv + rcases lt_or_gt_of_ne Hne with hneg|hpos + · have Hinc:=HI.2 (by exact_mod_cast (le_of_lt (Hpair ▸ hneg))) + rw [←HC.2 hneg N le_rfl] at Hinc + have HA:=Hinc.add hplus + simpa only [hpM,hmM,sub_add_cancel] using HA + · have Hinc:=HI.1 (by exact_mod_cast (le_of_lt (Hpair ▸ hpos))) + rw [←HC.1 hpos N le_rfl] at Hinc + have HA:=Hinc.add hplus + simpa only [hpM,hmM,sub_add_cancel] using HA +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesAdjoint PowerSeriesSplit FiniteRayGeometry FiniteEventTraversal LaurentPositive WallUnits +noncomputable section +variable {M E I : Type*} [AddCommGroup M] [AddCommGroup E] [Module ℝ E] [Fintype I] +variable (Ω : M →+ M →+ ℤ) (C : (I → ℤ) →+ M) +variable (e : M →+ E) (he : Function.Injective e) +variable (B : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hB : ∀x,B x x=0) +variable (hcomp : ∀a b,B (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀n m,HasRootDegree C n m → L (e m)=(n:ℝ)) +include he hB hcomp hdeg in + +theorem positive_sections (F : CompletedPositive LaurentRay.vUnit Ω C) + (incoming : PositiveIncomingPrescription Ω C F) (b : M) + (X : PowerSeries (Torus LaurentRay.vUnit Ω)) (hX : ShiftGraded LaurentRay.vUnit Ω C b X) + (hinc : ∀n,TorusPositive Ω (sectionIncoming LaurentRay.vUnit Ω C F b n X)) : + ∀N,∀h : Module.Dual ℝ E,TorusPositive Ω (coeff N (sectionValue LaurentRay.vUnit Ω C F (h.toAddMonoidHom.comp e) X)) := by + have hΩ : ∀m,Ω m m=0:=by + intro m; have HH:=hB (e m); rw [hcomp] at HH; exact_mod_cast HH + have walls:=positive_walls_through Ω C e he B hB hcomp L hdeg F incoming + intro N + induction N using Nat.strong_induction_on with + | h N ih => + intro h r + obtain ⟨k,Hk,Heq⟩:=section_generic_offset LaurentRay.vUnit Ω C e L hdeg F X N h (B.flip (e r)) + rw [←Heq N le_rfl] + let dir:=B.flip (e r) + let S:=realRootsThrough e C N + let events:=lineEvents S dir k + let P (a : ℝ):=Positive (coeff N (sectionValue LaurentRay.vUnit Ω C F ((k+a • dir).toAddMonoidHom.comp e) X) r) + have h0 : (0:ℝ)∉events:=section_line_zero_not_event C e N dir k Hk + have hstart : ∃a,0≤a ∧ (∀z∈events,z0,∀δ : ℝ,0<δ → δ<ε → P (a+δ) → P (a-δ):=by + intro a ha ha0 + exact section_line_step Ω C e he B hB hcomp L hdeg N r F (walls N) X ih k Hk a ha + have HH:=descend events P hstart hcell hstep 0 (le_refl 0) h0 + simpa only [P,zero_smul,add_zero] using HH +include he hB hcomp hdeg in + +theorem thetaValue_positive (F : CompletedPositive LaurentRay.vUnit Ω C) + (incoming : PositiveIncomingPrescription Ω C F) (b : M) (h : Module.Dual ℝ E) : + IntegralPositive Ω (thetaValue LaurentRay.vUnit Ω C F b (h.toAddMonoidHom.comp e)) := by + intro N + exact positive_sections Ω C e he B hB hcomp L hdeg F incoming b + (thetaInitial LaurentRay.vUnit Ω C F b) (thetaInitial_graded LaurentRay.vUnit Ω C F b) + (fun n=>by rw [thetaInitial_prescription]; exact completedPositive_C_X Ω b n) N h +end +end ElementaryPositivity.QuantumTorus + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularDirectSum.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularDirectSum.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee9627fec6a275097a73e7c5dd1a941fdf0ae1ae --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularDirectSum.lean @@ -0,0 +1,48 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +open scoped DirectSum +universe u v w + +theorem triangular_directSum_injective {J : Type u} [DecidableEq J] {M : J → Type v} {N : Type w} + [∀ j,AddCommGroup (M j)] [∀ j,Module ℚ (M j)] [AddCommGroup N] [Module ℚ N] + (r : J → J → Prop) [IsStrictOrder J r] + (F : ∀ j,M j →ₗ[ℚ] N) (D : ∀ j,N →ₗ[ℚ] M j) + (hdiag : ∀ j x,D j (F j x)=x) + (hoff : ∀ i j,j≠i → ¬r j i → ∀ x,D i (F j x)=0) : + Function.Injective (DirectSum.toModule ℚ J N F) := by + classical + apply (LinearMap.ker_eq_bot).mp + apply LinearMap.ker_eq_bot'.mpr + intro x hx + by_contra hn + have hs : (x.support : Set J).Nonempty := + Finset.nonempty_iff_ne_empty.mpr (fun h=>hn (DFinsupp.support_eq_empty.mp h)) + have hwf : WellFounded (fun i j=>r i j ∧ i∈x.support ∧ j∈x.support) := + Set.wellFoundedOn_iff.mp x.support.finite_toSet.wellFoundedOn + obtain ⟨i,hi,hm⟩:=hwf.has_min (x.support : Set J) hs + have H : D i (DirectSum.toModule ℚ J N F x)=x i := by + calc + _ = D i (DirectSum.toModule ℚ J N F (∑ j∈x.support,DirectSum.of M j (x j))) := + congrArg (fun y=>D i (DirectSum.toModule ℚ J N F y)) (DirectSum.sum_support_of x).symm + _ = ∑ j∈x.support,D i (F j (x j)) := by + simp only [map_sum] + apply Finset.sum_congr rfl + intro j hj + exact congrArg (D i) (DirectSum.toModule_lof (R:=ℚ) (φ:=F) j (x j)) + _ = x i := by + rw [Finset.sum_eq_single i] + · exact hdiag i (x i) + · intro j hj hji + exact hoff i j hji (fun h=>hm j hj ⟨h,hj,hi⟩) (x j) + · intro h; exact (h hi).elim + rw [hx,map_zero] at H + exact (DFinsupp.mem_support_iff.mp hi) H.symm +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapOrthogonality.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapOrthogonality.lean new file mode 100644 index 0000000000000000000000000000000000000000..a792b4db9f21fbc787a0cb33165505bc60940596 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapOrthogonality.lean @@ -0,0 +1,157 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularGapTotals + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +lemma stationary_anchor_pair_zero (m:Lattice n (Cell n)) (hK:∀i,levelTotal cellLevel i m=0) + (a:Fin (n+1)) : triangularOmega n (anchor a) m=0 := by + have HT:∀i,extendedTotal cellLevel m i=0 := by + intro i + unfold extendedTotal + split_ifs <;> first | exact hK _ | rfl + change chartPairing cellLevel triangularBB (anchor a) m=0 + rw [chartPairing_anchor,HT,HT,sub_self] + +lemma gapXi_cell (m:Lattice n (Cell n)) (b:Cell n) : + gapXi m (b.2.val+1) (b.1.val+1)=triangularOmega n (eventRoot cellLevel 0 b) m := by + have hb:=b.2.isLt + rw [gapXi,dite_eq_left (by have hn:=b.1.isLt; omega)] + congr 2 + +lemma gap_positive_u (c:GapIndex n → ℤ) (m:Lattice n (Cell n)) + (hm:m=anchor 0+forwardRoots c) (hK:∀i,levelTotal cellLevel i m=0) + (g:GapIndex n) (hg:0 < c g) : + ∃j,1 ≤ j ∧ j ≤ g.1.val+1 ∧ 0 < gapU c j (g.1.val+1) := by + have ht:=g.2.isLt + by_cases hz:g.2.val=0 + · refine ⟨1,by omega,by omega,?_⟩ + rw [gapU_first,←gapValue_end_eq c m hm hK,←hz,gapValue_read] + exact hg + · let j:=g.1.val+2-g.2.val + have hj:1 ≤ j ∧ j ≤ g.1.val+1 ∧ g.1.val+1 ≤ n := by + have hn:=g.1.isLt + dsimp [j] + omega + refine ⟨j,hj.1,hj.2.1,?_⟩ + rw [gapU,ite_eq_left hj] + have he:g.1.val+1+1-j=g.2.val:=by dsimp [j]; omega + rw [he,gapValue_read] + exact hg + +lemma positive_level_event_zero (c:GapIndex n → ℤ) (m:Lattice n (Cell n)) + (hc:∀g,0 ≤ c g) (hm:m=anchor 0+forwardRoots c) (hK:∀i,levelTotal cellLevel i m=0) + (hxi:∀b,0 ≤ triangularOmega n (eventRoot cellLevel 0 b) m) + (g:GapIndex n) (hg:0 < c g) (b:Cell n) (hbg:b.1=g.1) : + triangularOmega n (eventRoot cellLevel 0 b) m=0 := by + obtain ⟨j,hj,hji,hu⟩:=gap_positive_u c m hm hK g hg + let A:=actualIntegerGaps c m hc hm hK hxi + have H:=A.positive_gap_zero_pairings j (g.1.val+1) hj hji (by have := g.1.isLt; omega) hu + (b.2.val+1) (by omega) (by have hb:=b.2.isLt; have he:=congrArg Fin.val hbg; omega) + change gapXi m (b.2.val+1) (g.1.val+1)=0 at H + rw [←hbg,gapXi_cell] at H + exact H + +lemma positive_gap_target_zero (c:GapIndex n → ℤ) (m:Lattice n (Cell n)) + (hc:∀g,0 ≤ c g) (hm:m=anchor 0+forwardRoots c) (hK:∀i,levelTotal cellLevel i m=0) + (hxi:∀b,0 ≤ triangularOmega n (eventRoot cellLevel 0 b) m) + (g:GapIndex n) (hg:0 < c g) : triangularOmega n (forwardGap g) m=0 := by + have HB:∀b:Cell n,b.1=g.1 → triangularOmega n (bridge b) m=0 := by + intro b hb + have H:=positive_level_event_zero c m hc hm hK hxi g hg b hb + simp only [eventRoot,Nat.cast_zero,zero_smul,add_zero,map_sub,AddMonoidHom.sub_apply, + stationary_anchor_pair_zero m hK,sub_zero] at H + exact H + have HN:∀t:Fin (g.1.val+3),triangularOmega n (Pi.single (levelNode g.1 t) 1) m=0 := by + intro t + unfold levelNode + split_ifs + · exact stationary_anchor_pair_zero m hK _ + · exact stationary_anchor_pair_zero m hK _ + · exact HB _ rfl + rw [forwardGap,map_sub,AddMonoidHom.sub_apply,HN,HN,sub_self] +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open Classical +noncomputable section +variable {n : ℕ} + +lemma phaseEarlier_trans {a b c : Cell n} (hab : phaseEarlier a b) (hbc : phaseEarlier b c) : + phaseEarlier a c := by + unfold phaseEarlier at * + rcases hab with hab|⟨hab,hab'⟩ <;> rcases hbc with hbc|⟨hbc,hbc'⟩ + · left; omega + · left; omega + · left; omega + · right; exact ⟨hab.trans hbc,lt_trans hab' hbc'⟩ + +def phaseLE (a b : Cell n) : Prop := phaseEarlier a b ∨ a=b +instance : DecidableRel (@phaseLE n) := fun _ _=>inferInstanceAs (Decidable (_ ∨ _)) +instance : IsTrans (Cell n) phaseLE where + trans a b c hab hbc := by + rcases hab with hab|rfl + · rcases hbc with hbc|rfl + · exact Or.inl (phaseEarlier_trans hab hbc) + · exact Or.inl hab + · exact hbc +instance : Std.Antisymm (@phaseLE n) where + antisymm a b hab hba := by + rcases hab with hab|h + · rcases hba with hba|h + · exact (phaseEarlier_asymm hab hba).elim + · exact h.symm + · exact h +instance : Std.Total (@phaseLE n) where + total a b := by + rcases phaseEarlier_trichotomy a b with h|h|h + · exact Or.inl (Or.inl h) + · exact Or.inl (Or.inr h) + · exact Or.inr (Or.inl h) + +def phaseCycle (n : ℕ) : List (Cell n) := Finset.univ.sort phaseLE +@[simp] lemma mem_phaseCycle (b : Cell n) : b∈phaseCycle n := by simp [phaseCycle] +lemma phaseCycle_nodup : (phaseCycle n).Nodup := Finset.sort_nodup _ _ +lemma phaseCycle_pairwise : (phaseCycle n).Pairwise phaseLE := by + exact Finset.pairwise_sort _ _ + +lemma prefix_before {pre post : List (Cell n)} {b c : Cell n} + (hcycle : phaseCycle n=pre++b::post) : c∈pre ↔ phaseEarlier c b := by + have hp:=phaseCycle_pairwise (n:=n) + rw [hcycle] at hp + have hnd:=phaseCycle_nodup (n:=n) + rw [hcycle] at hnd + have hneq : b∉pre := by + have H:=(List.nodup_append.mp hnd).2.2 + exact fun hb=>H b hb b (by simp) rfl + constructor + · intro hc + have hh:phaseLE c b:=(List.pairwise_append.mp hp).2.2 c hc b (by simp) + rcases hh with hh|hh + · exact hh + · subst c; exact (hneq hc).elim + · intro hcb + have hc:=mem_phaseCycle c + rw [hcycle,List.mem_append,List.mem_cons] at hc + rcases hc with hc|hc|hc + · exact hc + · subst c; exact (phaseEarlier_irrefl b hcb).elim + · have hh:phaseLE b c:=(List.pairwise_cons.mp (List.pairwise_append.mp hp).2.1).1 c hc + rcases hh with hh|hh + · exact (phaseEarlier_asymm hcb hh).elim + · subst c; exact (phaseEarlier_irrefl b hcb).elim +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapPairing.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapPairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a0780a223f644ed02ce78081412118e064a019d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapPairing.lean @@ -0,0 +1,217 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PathRoot + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +def ownNodeWeight (a r j:ℕ) : ℤ := + if j=0 then 1 else if j=a+2 then -1 else + if j+r < a+1 then 2 else if j+r=a+1 then 1 else 0 +def lowerNodeWeight (a r j:ℕ) : ℤ := + if j=0 then 0 else if j=a+2 then 1 else if j+r ≤ a+1 then -1 else 0 +def upperNodeWeight (a r j:ℕ) : ℤ := + if j=0 then -1 else if j=a+2 then 0 else if j+r < a+1 then -1 else 0 + +def eventNodeWeight (b:Cell n) (i:Fin n) (j:ℕ) : ℤ := + if i=b.1 then ownNodeWeight i.val b.2.val j + else if i.val+1=b.1.val then lowerNodeWeight i.val b.2.val j + else if b.1.val+1=i.val then upperNodeWeight i.val b.2.val j + else 0 + +lemma eventRoot_levelNode (b:Cell n) (i:Fin n) (j:Fin (i.val+3)) : + triangularOmega n (eventRoot cellLevel 0 b) (Pi.single (levelNode i j) 1)=eventNodeWeight b i j.val := by + have hb := b.2.isLt + have hj := j.isLt + unfold levelNode + split_ifs with h0 he + · change triangularOmega n (eventRoot cellLevel 0 b) (anchor i.castSucc)=_ + rw [eventRoot_anchor] + simp only [eventNodeWeight,ownNodeWeight,lowerNodeWeight,upperNodeWeight,h0,Fin.ext_iff,Fin.val_castSucc,Fin.val_succ] + split_ifs <;> first | contradiction | omega + · change triangularOmega n (eventRoot cellLevel 0 b) (anchor i.succ)=_ + rw [eventRoot_anchor] + simp only [eventNodeWeight,ownNodeWeight,lowerNodeWeight,upperNodeWeight,he,Fin.ext_iff,Fin.val_castSucc,Fin.val_succ] + split_ifs <;> first | contradiction | omega + · change triangularOmega n (eventRoot cellLevel 0 b) (bridge ⟨i,⟨i.val+1-j.val,_⟩⟩)=_ + rw [eventRoot_bridge_value] + have hcell : (⟨i,⟨i.val+1-j.val,by omega⟩⟩ : Cell n)=b ↔ + i.val=b.1.val ∧ i.val+1-j.val=b.2.val := by + constructor + · intro h; exact ⟨congrArg (fun x:Cell n=>x.1.val) h,congrArg (fun x:Cell n=>x.2.val) h⟩ + · intro h; exact cell_ext (Fin.ext h.1) h.2 + simp only [hcell,eventNodeWeight,ownNodeWeight,lowerNodeWeight,upperNodeWeight,phaseEarlier,cellRow,Fin.ext_iff,Fin.lt_def] + by_cases hlev:i.val=b.1.val + · simp only [hlev,ite_true,true_and,lt_self_iff_false,and_false,or_false] + split_ifs <;> first | contradiction | omega + · simp only [hlev,ite_false] + by_cases hlo:i.val+1=b.1.val + · simp only [hlo,true_or,ite_true] + split_ifs <;> first | contradiction | omega + · simp only [hlo,false_or,ite_false] + by_cases hup:b.1.val+1=i.val + · simp only [hup,ite_true] + split_ifs <;> first | contradiction | omega + · simp only [hup,ite_false] + +lemma ownNodeWeight_step (a r j:ℕ) (hr:r ≤ a) (hj:j ≤ a+1) : + ownNodeWeight a r (j+1)-ownNodeWeight a r j= + (if j=0 then 1 else 0)-(if j=a-r then 1 else 0)- + (if j=a+1-r then 1 else 0)-(if j=a+1 then 1 else 0) := by + have h1 : j=a-r ↔ j+r=a := by omega + have h2 : j=a+1-r ↔ j+r=a+1 := by omega + simp only [ownNodeWeight,h1,h2] + by_cases hz:j=0 + · simp only [hz,zero_add] + split_ifs <;> first | contradiction | omega + · simp only [hz,ite_false] + by_cases he:j=a+1 + · simp only [he] + split_ifs <;> first | contradiction | omega + · split_ifs <;> first | contradiction | omega + +lemma lowerNodeWeight_step (a r j:ℕ) (hr:r ≤ a+1) (hj:j ≤ a+1) : + lowerNodeWeight a r (j+1)-lowerNodeWeight a r j= + -(if j=0 then 1 else 0)+(if j=a+1-r then 1 else 0)+ + (if j=a+1 then 1 else 0) := by + have h1:j=a+1-r ↔ j+r=a+1 := by omega + simp only [lowerNodeWeight,h1] + by_cases hz:j=0 + · simp only [hz,zero_add] + split_ifs <;> first | contradiction | omega + · simp only [hz,ite_false] + by_cases he:j=a+1 + · simp only [he] + split_ifs <;> first | contradiction | omega + · split_ifs <;> first | contradiction | omega + +lemma upperNodeWeight_step (a r j:ℕ) (hr:r < a) (hj:j ≤ a+1) : + upperNodeWeight a r (j+1)-upperNodeWeight a r j= + (if j=a-r then 1 else 0) := by + have h1:j=a-r ↔ j+r=a := by omega + simp only [upperNodeWeight,h1] + split_ifs <;> first | contradiction | omega + +def eventGapWeight (b:Cell n) (g:GapIndex n) : ℤ := + if g.1=b.1 then + (if g.2.val=0 then 1 else 0) - + (if g.2.val=b.1.val-b.2.val then 1 else 0) - + (if g.2.val=b.1.val+1-b.2.val then 1 else 0) - + (if g.2.val=b.1.val+1 then 1 else 0) + else if g.1.val+1=b.1.val then + -(if g.2.val=0 then 1 else 0) + + (if g.2.val=b.1.val-b.2.val then 1 else 0) + + (if g.2.val=b.1.val then 1 else 0) + else if b.1.val+1=g.1.val then + (if g.2.val=b.1.val+1-b.2.val then 1 else 0) + else 0 + +lemma eventRoot_forwardGap (b:Cell n) (g:GapIndex n) : + triangularOmega n (eventRoot cellLevel 0 b) (forwardGap g)=eventGapWeight b g := by + rw [forwardGap,map_sub,eventRoot_levelNode,eventRoot_levelNode] + simp only [Fin.val_succ,Fin.val_castSucc,eventNodeWeight,eventGapWeight,Fin.ext_iff] + have hb:=b.2.isLt + have hg:=g.2.isLt + by_cases hlev:g.1.val=b.1.val + · simp only [hlev,ite_true] + exact ownNodeWeight_step _ _ _ (by omega) (by omega) + · simp only [hlev,ite_false] + by_cases hlo:g.1.val+1=b.1.val + · simp only [hlo,ite_true] + convert lowerNodeWeight_step g.1.val b.2.val g.2.val (by omega) (by omega) using 1 + rw [hlo] + · simp only [hlo,ite_false] + by_cases hup:b.1.val+1=g.1.val + · simp only [hup,ite_true] + convert upperNodeWeight_step g.1.val b.2.val g.2.val (by omega) (by omega) using 1 + · simp only [hup,ite_false,sub_self] +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +def gapValue (c:GapIndex n → ℤ) (i t:ℕ) : ℤ := + ∑g,if g.1.val+1=i ∧ g.2.val=t then c g else 0 + +lemma gapValue_nonneg (c:GapIndex n → ℤ) (hc:∀g,0 ≤ c g) (i t:ℕ) : 0 ≤ gapValue c i t := by + apply Finset.sum_nonneg + intro g _ + split_ifs <;> first | exact hc g | omega + +lemma gapValue_out (c:GapIndex n → ℤ) (i t:ℕ) + (h:¬(1 ≤ i ∧ i ≤ n ∧ t ≤ i)) : gapValue c i t=0 := by + apply Finset.sum_eq_zero + intro g _ + split_ifs with hg + · have h1:=g.1.isLt + have h2:=g.2.isLt + exact (h (by omega)).elim + · rfl + +lemma gap_ext (g f:GapIndex n) (h1:g.1.val=f.1.val) (h2:g.2.val=f.2.val) : g=f := by + cases g with | mk i g => + cases f with | mk j f => + have hij:i=j:=Fin.ext h1 + subst j + have hgf:g=f:=Fin.ext h2 + subst f + rfl + +lemma gapValue_read (c:GapIndex n → ℤ) (g:GapIndex n) : gapValue c (g.1.val+1) g.2.val=c g := by + rw [gapValue,Finset.sum_eq_single g] + · simp + · intro f _ hfg + have hf:¬(f.1.val+1=g.1.val+1 ∧ f.2.val=g.2.val) := by + intro h + exact hfg (gap_ext f g (by omega) h.2) + simp only [hf,ite_false] + · simp + +lemma sum_eventGapWeight (c:GapIndex n → ℤ) (b:Cell n) : + (∑g,c g*eventGapWeight b g)= + gapValue c (b.1.val+1) 0-gapValue c (b.1.val+1) (b.1.val-b.2.val)- + gapValue c (b.1.val+1) (b.1.val+1-b.2.val)-gapValue c (b.1.val+1) (b.1.val+1)- + gapValue c b.1.val 0+gapValue c b.1.val (b.1.val-b.2.val)+gapValue c b.1.val b.1.val+ + gapValue c (b.1.val+2) (b.1.val+1-b.2.val) := by + simp only [gapValue,←Finset.sum_sub_distrib,←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro g _ + have h1:g.1.val+1=b.1.val+1 ↔ g.1.val=b.1.val := by omega + have h2:g.1.val+1=b.1.val+2 ↔ b.1.val+1=g.1.val := by omega + simp only [eventGapWeight,Fin.ext_iff,h1,h2] + by_cases he:g.1.val=b.1.val + · have hlo:g.1.val+1≠b.1.val:=by omega + have hup:b.1.val+1≠g.1.val:=by omega + have hself:b.1.val+1≠b.1.val:=by omega + simp only [he,hself,true_and,false_and,ite_true,ite_false,mul_sub,mul_ite,mul_one,mul_zero] + ring + · by_cases hlo:g.1.val+1=b.1.val + · have hup:b.1.val+1≠g.1.val:=by omega + simp only [he,hlo,hup,true_and,false_and,ite_true,ite_false,mul_add,mul_neg,mul_ite,mul_one,mul_zero] + ring + · by_cases hup:b.1.val+1=g.1.val + · simp only [he,hlo,hup,true_and,false_and,ite_true,ite_false,mul_ite,mul_one,mul_zero] + ring + · simp only [he,hlo,hup,false_and,ite_false,mul_zero,sub_zero,add_zero] + +lemma eventRoot_roots (b:Cell n) (c:GapIndex n → ℤ) : + triangularOmega n (eventRoot cellLevel 0 b) (forwardRoots c)=∑g,c g*eventGapWeight b g := by + rw [forwardRoots_apply,map_sum] + simp only [map_zsmul,smul_eq_mul,eventRoot_forwardGap] +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapTotals.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapTotals.lean new file mode 100644 index 0000000000000000000000000000000000000000..6bb4431acd7f0492a332eb21e8a890a80af88aa4 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGapTotals.lean @@ -0,0 +1,164 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularGaps +import OAI.Combinatorics.Chromatic.Walls.TriangularGapPairing + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +lemma levelTotal_node (i j:Fin n) (t:Fin (j.val+3)) : + levelTotal cellLevel i (Pi.single (levelNode j t) (1:ℤ))= + if j=i ∧ 0 omega + · simp only [hi,false_and,ite_false,sub_self] + +lemma levelTotal_roots (i:Fin n) (c:GapIndex n → ℤ) : + levelTotal cellLevel i (forwardRoots c)=gapValue c (i.val+1) 0-gapValue c (i.val+1) (i.val+1) := by + rw [forwardRoots_apply,map_sum] + simp only [map_zsmul,smul_eq_mul,levelTotal_gap,gapValue,←Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro g _ + have h1:g.1.val+1=i.val+1 ↔ g.1=i := by simp [Fin.ext_iff] + by_cases he:g.1=i + · simp only [he,true_and,mul_sub,mul_ite,mul_one,mul_zero] + · simp only [h1,he,false_and,ite_false,sub_self,mul_zero] + +lemma gapValue_end_eq (c:GapIndex n → ℤ) (m:Lattice n (Cell n)) + (hm:m=anchor 0+forwardRoots c) (hK:∀i,levelTotal cellLevel i m=0) (i:ℕ) : + gapValue c i 0=gapValue c i i := by + by_cases hi:1 ≤ i ∧ i ≤ n + · let a:Fin n:=⟨i-1,by omega⟩ + have H:=hK a + rw [hm,map_add,levelTotal_anchor,zero_add,levelTotal_roots] at H + have ha:a.val+1=i:=by dsimp [a]; omega + rw [ha] at H + omega + · rw [gapValue_out c i 0 (by omega),gapValue_out c i i (by omega)] +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +def gapU (c:GapIndex n → ℤ) (j i:ℕ) : ℤ := + if 1 ≤ j ∧ j ≤ i ∧ i ≤ n then gapValue c i (i+1-j) else 0 + +def indexedCell (j i:ℕ) (h:1 ≤ j ∧ j ≤ i ∧ i ≤ n) : Cell n := + ⟨⟨i-1,by omega⟩,⟨j-1,by change j-1 < i-1+1; omega⟩⟩ + +def gapXi (m:Lattice n (Cell n)) (j i:ℕ) : ℤ := + if h:1 ≤ j ∧ j ≤ i ∧ i ≤ n then triangularOmega n (eventRoot cellLevel 0 (indexedCell j i h)) m else 0 + +lemma gapU_first (c:GapIndex n → ℤ) (i:ℕ) : gapU c 1 i=gapValue c i i := by + unfold gapU + by_cases h:1 ≤ 1 ∧ 1 ≤ i ∧ i ≤ n + · rw [ite_eq_left h,Nat.add_sub_cancel] + · rw [ite_eq_right h,gapValue_out c i i (by omega)] + +lemma gapU_upper (c:GapIndex n → ℤ) (j i:ℕ) (hj:1 ≤ j) (hji:j ≤ i) : + gapU c (j+1) (i+1)=gapValue c (i+1) (i+1-j) := by + unfold gapU + by_cases h:1 ≤ j+1 ∧ j+1 ≤ i+1 ∧ i+1 ≤ n + · rw [ite_eq_left h] + congr 1 + omega + · rw [ite_eq_right h,gapValue_out c (i+1) (i+1-j) (by omega)] + +lemma gapXi_formula (c:GapIndex n → ℤ) (m:Lattice n (Cell n)) + (hm:m=anchor 0+forwardRoots c) (hK:∀i,levelTotal cellLevel i m=0) + (j i:ℕ) (hj:1 ≤ j) (hji:j ≤ i) (hi:i ≤ n) : + gapXi m j i=(if i=1 then 1 else 0)-gapValue c i (i+1-j)-gapValue c i (i-j)+ + gapValue c (i-1) (i-j)+gapValue c (i+1) (i+1-j) := by + have hh:1 ≤ j ∧ j ≤ i ∧ i ≤ n:=⟨hj,hji,hi⟩ + rw [gapXi,dite_eq_left hh,hm,map_add,eventRoot_anchor,eventRoot_roots,sum_eventGapWeight] + simp only [indexedCell,Fin.ext_iff,Fin.val_zero,Fin.val_castSucc,Fin.val_succ] + have h1:i-1+1=i:=by omega + have h2:i-1-(j-1)=i-j:=by omega + have h3:i-1+1-(j-1)=i+1-j:=by omega + have h4:i-1+2=i+1:=by omega + have hz:¬0=i-1+1:=by omega + have hzi:0=i-1 ↔ i=1:=by omega + rw [h2,h3,h4] + have hze:¬0=i:=by omega + simp only [hzi,h1,hze,ite_false,sub_zero] + rw [gapValue_end_eq c m hm hK i,gapValue_end_eq c m hm hK (i-1)] + ring + +lemma gapXi_pairing (c:GapIndex n → ℤ) (m:Lattice n (Cell n)) + (hm:m=anchor 0+forwardRoots c) (hK:∀i,levelTotal cellLevel i m=0) + (j i:ℕ) (hj:1 ≤ j) (hji:j ≤ i) (hi:i ≤ n) : + gapXi m j i=(if i=1 then 1 else 0)-gapU c j i- + (if j < i then gapU c (j+1) i else gapU c 1 i)+ + (if j < i then gapU c j (i-1) else gapU c 1 (j-1))+gapU c (j+1) (i+1) := by + rw [gapXi_formula c m hm hK j i hj hji hi,gapU_upper c j i hj hji] + have hu:gapU c j i=gapValue c i (i+1-j):=by rw [gapU,ite_eq_left ⟨hj,hji,hi⟩] + rw [hu] + by_cases hji':j < i + · have hU1:gapU c (j+1) i=gapValue c i (i-j):=by + rw [gapU,ite_eq_left (show 1 ≤ j+1 ∧ j+1 ≤ i ∧ i ≤ n by omega)] + congr 1 + omega + have hU2:gapU c j (i-1)=gapValue c (i-1) (i-j):=by + rw [gapU,ite_eq_left (show 1 ≤ j ∧ j ≤ i-1 ∧ i-1 ≤ n by omega)] + congr 1 + omega + rw [ite_eq_left hji',ite_eq_left hji',hU1,hU2] + · have hjj:j=i:=by omega + subst j + rw [ite_eq_right (lt_irrefl i),ite_eq_right (lt_irrefl i),gapU_first,gapU_first,Nat.sub_self, + gapValue_end_eq c m hm hK i,gapValue_end_eq c m hm hK (i-1)] + +def actualIntegerGaps (c:GapIndex n → ℤ) (m:Lattice n (Cell n)) + (hc:∀g,0 ≤ c g) (hm:m=anchor 0+forwardRoots c) (hK:∀i,levelTotal cellLevel i m=0) + (hxi:∀b,0 ≤ triangularOmega n (eventRoot cellLevel 0 b) m) : TriangularGaps.IntegerGaps n where + u:=gapU c + xi:=gapXi m + u_out j i h:=by rw [gapU,ite_eq_right h] + u_nonneg j i:=by unfold gapU; split_ifs; exact gapValue_nonneg c hc _ _; omega + xi_nonneg j i hj hji hi:=by rw [gapXi,dite_eq_left ⟨hj,hji,hi⟩]; exact hxi _ + pairing:=gapXi_pairing c m hm hK +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGaps.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGaps.lean new file mode 100644 index 0000000000000000000000000000000000000000..6029cebfb27c1907805c057663db9a01f53812b2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularGaps.lean @@ -0,0 +1,298 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity.TriangularGaps + +structure Recurrence (n : ℕ) where + u : ℕ → ℕ → ℕ + T : ℕ → ℕ → ℕ + xi : ℕ → ℕ → ℕ + u_out : ∀ j i, ¬(1 ≤ j ∧ j ≤ i ∧ i ≤ n) → u j i = 0 + T_out : ∀ j i, ¬(1 ≤ j ∧ j ≤ i ∧ i ≤ n) → T j i = 0 + diagonal : ∀ j i, 1 ≤ j → j ≤ i → i ≤ n → + u j i = T j i + u (j + 1) (i + 1) + row : ∀ j i, 1 ≤ j → j ≤ i → i < n → + T j (i + 1) + xi j (i + 1) = T j i + start : ∀ j, 1 ≤ j → j ≤ n → + T j j + xi j j + u 1 j = (if j = 1 then 1 else 0) + u 1 (j - 1) + +namespace Recurrence + +variable {n : ℕ} (R : Recurrence n) + +lemma diagonal_all (j i : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) : + R.u j i = R.T j i + R.u (j + 1) (i + 1) := by + by_cases hi : i ≤ n + · exact R.diagonal j i hj hji hi + · rw [R.u_out j i (by omega), R.T_out j i (by omega), + R.u_out (j + 1) (i + 1) (by omega)] + +lemma row_mono_add (j i k : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) (hik : i + k ≤ n) : + R.T j (i + k) ≤ R.T j i := by + induction k with + | zero => simp + | succ k ih => + have h := R.row j (i + k) hj (by omega) (by omega) + have h' := ih (by omega) + have he : i + (k + 1) = i + k + 1 := by omega + rw [he] + omega + +lemma row_le_start (j i : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) (hi : i ≤ n) : + R.T j i ≤ R.T j j := by + simpa [Nat.add_sub_of_le hji] using + R.row_mono_add j j (i - j) hj le_rfl (by omega) + +lemma partial_total (i : ℕ) (hi : i ≤ n) : + (∑ k ∈ Finset.range i, (R.T (k+1) (k+1) + R.xi (k+1) (k+1))) + R.u 1 i = + if i = 0 then 0 else 1 := by + induction i with + | zero => simp [R.u_out 1 0 (by omega)] + | succ i ih => + have hp := ih (by omega) + have hs := R.start (i+1) (by omega) hi + rw [Finset.sum_range_succ] + simp only [Nat.add_sub_cancel] at hs + by_cases hiz : i = 0 + · subst i + simpa [R.u_out 1 0 (by omega)] using hs + · simp only [ite_eq_right hiz] at hp + simp only [ite_eq_right (show i + 1 ≠ 1 by omega), zero_add] at hs + simp only [Nat.add_eq_zero_iff, Nat.one_ne_zero, and_false, ite_false] + omega + +lemma total_le_one : + (∑ k ∈ Finset.range n, (R.T (k+1) (k+1) + R.xi (k+1) (k+1))) ≤ 1 := by + have h := R.partial_total n le_rfl + split_ifs at h <;> omega + +lemma unique_start (s : ℕ) (hs : 1 ≤ s) (hsn : s ≤ n) (hpos : 0 < R.T s s) : + R.T s s = 1 ∧ + (∀ j, 1 ≤ j → j ≤ n → R.T j j = if j = s then 1 else 0) ∧ + (∀ j, 1 ≤ j → j ≤ n → R.xi j j = 0) := by + have h := Finset.sum_le_one_iff.mp R.total_le_one + have hsi : s - 1 ∈ Finset.range n := by simp; omega + have hs1 : s - 1 + 1 = s := by omega + have hsp : R.T (s-1+1) (s-1+1) + R.xi (s-1+1) (s-1+1) ≠ 0 := by + rw [hs1]; omega + have hone := (h (s-1) (s-1) hsi hsi hsp hsp).2 + rw [hs1] at hone + have honeT : R.T s s = 1 := by omega + have others : ∀ j, 1 ≤ j → j ≤ n → j ≠ s → R.T j j + R.xi j j = 0 := by + intro j hj hjn hjs + by_contra hn + have hji : j - 1 ∈ Finset.range n := by simp; omega + have hj1 : j - 1 + 1 = j := by omega + have ho := (h (s-1) (j-1) hsi hji hsp (by simpa [hj1] using hn)).1 + omega + refine ⟨honeT, ?_, ?_⟩ + · intro j hj hjn + by_cases hjs : j = s + · simpa [hjs] using honeT + · have ho := others j hj hjn hjs + simp only [ite_eq_right hjs] + omega + · intro j hj hjn + by_cases hjs : j = s + · subst j; omega + · have ho := others j hj hjn hjs + omega + +lemma anchor_run (s : ℕ) (hs : 1 ≤ s) (hsn : s ≤ n) (hpos : 0 < R.T s s) + (i : ℕ) (hi : i ≤ n) : R.u 1 i = if 0 < i ∧ i < s then 1 else 0 := by + obtain ⟨_, ht, hx⟩ := R.unique_start s hs hsn hpos + induction i with + | zero => simp [R.u_out 1 0 (by omega)] + | succ i ih => + have hp := ih (by omega) + have hst := R.start (i+1) (by omega) hi + rw [ht (i+1) (by omega) hi, hx (i+1) (by omega) hi] at hst + simp only [Nat.add_sub_cancel, add_zero] at hst + split_ifs at hp hst ⊢ <;> omega + +lemma other_rows_zero (s : ℕ) (hs : 1 ≤ s) (hsn : s ≤ n) + (hpos : 0 < R.T s s) (j i : ℕ) (hjs : j ≠ s) : R.T j i = 0 := by + by_cases hv : 1 ≤ j ∧ j ≤ i ∧ i ≤ n + · have h := R.row_le_start j i hv.1 hv.2.1 hv.2.2 + have h0 := (R.unique_start s hs hsn hpos).2.1 j hv.1 (by omega) + rw [ite_eq_right hjs] at h0 + omega + · exact R.T_out j i hv + +lemma diagonal_sum (j i t : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) : + R.u j i = (∑ k ∈ Finset.range t, R.T (j+k) (i+k)) + R.u (j+t) (i+t) := by + induction t with + | zero => simp + | succ t ih => + rw [Finset.sum_range_succ] + have hd := R.diagonal_all (j+t) (i+t) (by omega) (by omega) + rw [hd] at ih + simpa only [Nat.add_assoc] using ih + +lemma u_one_row (s : ℕ) (hs : 1 ≤ s) (hsn : s ≤ n) (hpos : 0 < R.T s s) + (j i : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) : + R.u j i = if j ≤ s then R.T s (i+s-j) else 0 := by + have hsum := R.diagonal_sum j i (n+1) hj hji + rw [R.u_out (j+(n+1)) (i+(n+1)) (by omega), add_zero] at hsum + rw [hsum] + by_cases hjs : j ≤ s + · rw [ite_eq_left hjs] + rw [Finset.sum_eq_single (s-j)] + · congr 1 <;> omega + · intro k hk hks + exact R.other_rows_zero s hs hsn hpos (j+k) (i+k) (by omega) + · intro hk + simp only [Finset.mem_range] at hk + omega + · rw [ite_eq_right hjs] + apply Finset.sum_eq_zero + intro k hk + exact R.other_rows_zero s hs hsn hpos (j+k) (i+k) (by omega) + +lemma row_formula (s : ℕ) (hs : 1 ≤ s) (hsn : s ≤ n) (hpos : 0 < R.T s s) + (i : ℕ) (hsi : s ≤ i) (hi : i ≤ n) : + R.T s i = if i + 1 < 2*s then 1 else 0 := by + have hd := R.u_one_row s hs hsn hpos 1 (i+1-s) (by omega) (by omega) + rw [ite_eq_left hs] at hd + have he : i+1-s+s-1 = i := by omega + rw [he] at hd + rw [← hd, R.anchor_run s hs hsn hpos (i+1-s) (by omega)] + split_ifs <;> omega + +lemma xi_zero_before (s : ℕ) (hs : 1 ≤ s) (hsn : s ≤ n) (hpos : 0 < R.T s s) + (j i : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) (hi : i ≤ n) (hbefore : i+1 < 2*s) : + R.xi j i = 0 := by + by_cases hji' : j = i + · subst i + exact (R.unique_start s hs hsn hpos).2.2 j hj hi + · have hr := R.row j (i-1) hj (by omega) (by omega) + have he : i-1+1 = i := by omega + rw [he] at hr + by_cases hjs : j = s + · subst j + rw [R.row_formula s hs hsn hpos i hji hi, + R.row_formula s hs hsn hpos (i-1) (by omega) (by omega), + ite_eq_left hbefore, ite_eq_left (by omega)] at hr + omega + · rw [R.other_rows_zero s hs hsn hpos j i hjs, + R.other_rows_zero s hs hsn hpos j (i-1) hjs] at hr + omega + +theorem positive_gap_zero_pairings (j i : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) + (hi : i ≤ n) (hu : 0 < R.u j i) : + ∀ k, 1 ≤ k → k ≤ i → R.xi k i = 0 := by + have hsum := R.diagonal_sum j i (n+1) hj hji + rw [R.u_out (j+(n+1)) (i+(n+1)) (by omega), add_zero] at hsum + have hp : 0 < ∑ k ∈ Finset.range (n+1), R.T (j+k) (i+k) := by omega + obtain ⟨k, hk, htk⟩ := (Finset.sum_pos_iff_of_nonneg (fun _ _ => Nat.zero_le _)).mp hp + have hv : 1 ≤ j+k ∧ j+k ≤ i+k ∧ i+k ≤ n := by + by_contra hn + rw [R.T_out (j+k) (i+k) hn] at htk + omega + let s := j+k + have hs : 1 ≤ s := hv.1 + have hsn : s ≤ n := by dsimp [s]; omega + have hpos : 0 < R.T s s := by + have hl := R.row_le_start (j+k) (i+k) hv.1 hv.2.1 hv.2.2 + dsimp [s]; omega + have hur := R.u_one_row s hs hsn hpos j i hj hji + have hjs : j ≤ s := by dsimp [s]; omega + rw [ite_eq_left hjs] at hur + have htarget : i+s-j ≤ n := by + by_contra hn + rw [R.T_out s (i+s-j) (by omega)] at hur + omega + have hf := R.row_formula s hs hsn hpos (i+s-j) (by omega) htarget + have hbefore : i+1 < 2*s := by + rw [hur] at hu + split_ifs at hf <;> omega + intro k hk hki + exact R.xi_zero_before s hs hsn hpos k i hk hki hi hbefore + +end Recurrence + +structure IntegerGaps (n : ℕ) where + u : ℕ → ℕ → ℤ + xi : ℕ → ℕ → ℤ + u_out : ∀ j i, ¬(1 ≤ j ∧ j ≤ i ∧ i ≤ n) → u j i = 0 + u_nonneg : ∀ j i, 0 ≤ u j i + xi_nonneg : ∀ j i, 1 ≤ j → j ≤ i → i ≤ n → 0 ≤ xi j i + pairing : ∀ j i, 1 ≤ j → j ≤ i → i ≤ n → + xi j i = (if i = 1 then 1 else 0) - u j i - + (if j < i then u (j+1) i else u 1 i) + + (if j < i then u j (i-1) else u 1 (j-1)) + u (j+1) (i+1) + +namespace IntegerGaps +variable {n : ℕ} (A : IntegerGaps n) + +def t (j i : ℕ) : ℤ := A.u j i - A.u (j+1) (i+1) + +lemma t_row (j i : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) (hi : i < n) : + A.t j (i+1) + A.xi j (i+1) = A.t j i := by + have h := A.pairing j (i+1) hj (by omega) (by omega) + rw [ite_eq_right (show i+1 ≠ 1 by omega), ite_eq_left (by omega), ite_eq_left (by omega)] at h + simp only [Nat.add_sub_cancel] at h + dsimp [t] + linarith + +lemma t_start (j : ℕ) (hj : 1 ≤ j) (hjn : j ≤ n) : + A.t j j + A.xi j j + A.u 1 j = (if j = 1 then 1 else 0) + A.u 1 (j-1) := by + have h := A.pairing j j hj le_rfl hjn + simp only [lt_self_iff_false, ite_false] at h + dsimp [t] + linarith + +lemma t_nonneg (j i : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) (hi : i ≤ n) : + 0 ≤ A.t j i := by + apply Nat.decreasingInduction' (m := i) (n := n) (P := fun k => 0 ≤ A.t j k) _ hi + · dsimp [t] + rw [A.u_out (j+1) (n+1) (by omega), sub_zero] + exact A.u_nonneg j n + · intro k hk hik hnext + have hr := A.t_row j k hj (by omega) hk + have hx := A.xi_nonneg j (k+1) hj (by omega) (by omega) + linarith + +def recurrence : Recurrence n where + u j i := (A.u j i).toNat + T j i := if 1 ≤ j ∧ j ≤ i ∧ i ≤ n then (A.t j i).toNat else 0 + xi j i := (A.xi j i).toNat + u_out j i h := by simp only [A.u_out j i h, Int.toNat_zero] + T_out j i h := by simp only [ite_eq_right h] + diagonal j i hj hji hi := by + rw [ite_eq_left ⟨hj, hji, hi⟩, ← Int.toNat_add (A.t_nonneg j i hj hji hi) (A.u_nonneg _ _)] + congr 1 + dsimp [t] + ring + row j i hj hji hi := by + rw [ite_eq_left ⟨hj, by omega, by omega⟩, ite_eq_left ⟨hj, hji, by omega⟩, + ← Int.toNat_add (A.t_nonneg j (i+1) hj (by omega) (by omega)) + (A.xi_nonneg j (i+1) hj (by omega) (by omega)), A.t_row j i hj hji hi] + start j hj hjn := by + rw [ite_eq_left ⟨hj, le_rfl, hjn⟩, + ← Int.toNat_add (A.t_nonneg j j hj le_rfl hjn) (A.xi_nonneg j j hj le_rfl hjn), + ← Int.toNat_add (add_nonneg (A.t_nonneg j j hj le_rfl hjn) + (A.xi_nonneg j j hj le_rfl hjn)) (A.u_nonneg 1 j), A.t_start j hj hjn] + split_ifs <;> simp [Int.toNat_add, A.u_nonneg] + + theorem positive_gap_zero_pairings (j i : ℕ) (hj : 1 ≤ j) (hji : j ≤ i) + (hi : i ≤ n) (hu : 0 < A.u j i) : + ∀ k, 1 ≤ k → k ≤ i → A.xi k i = 0 := by + have hpos : 0 < A.recurrence.u j i := by + change 0 < (A.u j i).toNat + omega + have h := A.recurrence.positive_gap_zero_pairings j i hj hji hi hpos + intro k hk hki + have hz := h k hk hki + change (A.xi k i).toNat = 0 at hz + have hn := A.xi_nonneg k i hk hki hi + omega + +end IntegerGaps +end ElementaryPositivity.TriangularGaps + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularIncoming.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularIncoming.lean new file mode 100644 index 0000000000000000000000000000000000000000..7cbe3eb5f34b1790a5eec0e69a81f57624f7fd37 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularIncoming.lean @@ -0,0 +1,89 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularPolynomialStationarity +import OAI.Combinatorics.Chromatic.GradedAlgebra.ElementaryExpressionBounds + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +lemma initial_vertexDisplay (a:Vertex n (Cell n)) : + vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge) a= + includeVertices (Pi.single a (1:ℤ)) := by cases a <;> rfl + +lemma triangularSeed_nonneg {N:ℕ} (f:ElementaryExpr N) + (m:Extended (Vertex n (Cell n))) (hm:m∈(triangularExpression f).support) + (a:Vertex n (Cell n)) : 0 ≤ m.1 a := by + let ell : Extended (Vertex n (Cell n)) →+ ℤ := + -((Pi.evalAddMonoidHom (fun _=>ℤ) a).comp (AddMonoidHom.fst _ _)) + have H:=f.cutSupported_scaled LaurentRay.vUnit (extendedOmega n) ell 0 + (vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge)) (fun x=>by + rw [initial_vertexDisplay] + change -((Pi.single x (1:ℤ) : Lattice n (Cell n)) a) ≤ 0 + simp only [Pi.single_apply] + split_ifs <;> omega) m hm + change -(m.1 a) ≤ (N:ℤ)*0 at H + omega + +lemma triangularSeed_dual_zero {N:ℕ} (f:ElementaryExpr N) + (m:Extended (Vertex n (Cell n))) (hm:m∈(triangularExpression f).support) : m.2=0 := by + ext a + let ell : Extended (Vertex n (Cell n)) →+ ℤ := + (Pi.evalAddMonoidHom (fun _=>ℤ) a).comp (AddMonoidHom.snd _ _) + have H:=f.weight LaurentRay.vUnit (extendedOmega n) ell 0 + (vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge)) (fun x=>by + rw [initial_vertexDisplay]; rfl) m hm + change m.2 a=(N:ℤ)*0 at H + change m.2 a=0 + simpa only [mul_zero] using H + +lemma triangularSeed_weight {N:ℕ} (f:ElementaryExpr N) + (m:Extended (Vertex n (Cell n))) (hm:m∈(triangularExpression f).support) : vertexWeight m.1=(N:ℤ) := by + let ell: Extended (Vertex n (Cell n)) →+ ℤ := + (vertexWeight (R:=ℤ)).toAddMonoidHom.comp (AddMonoidHom.fst _ _) + have H:=f.weight LaurentRay.vUnit (extendedOmega n) ell 1 + (vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge)) (fun x=>by + rw [initial_vertexDisplay] + change vertexWeight (Pi.single x (1:ℤ))=1 + simp [vertexWeight_apply,Pi.single_apply]) m hm + change vertexWeight m.1=(N:ℤ)*1 at H + simpa only [mul_one] using H + +lemma triangularSeed_in_rootCone {N:ℕ} (f:ElementaryExpr N) + (m:Extended (Vertex n (Cell n))) (hm:m∈(triangularExpression f).support) : + ∃k,HasRootDegree (extendedRoots n) k (m-includeVertices ((N:ℤ) • anchor 0)) := by + obtain ⟨k,c,hc,he⟩:=triangularVertex_rootDegree m.1 (triangularSeed_nonneg f m hm) + refine ⟨k,c,hc,?_⟩ + change includeVertices (forwardRoots (fun i=>(c i:ℤ)))=m-includeVertices ((N:ℤ) • anchor 0) + rw [triangularSeed_weight f m hm] at he + change forwardRoots (fun i=>(c i:ℤ))=m.1-(N:ℤ) • anchor 0 at he + rw [he,map_sub] + congr 1 + exact Prod.ext rfl (triangularSeed_dual_zero f m hm).symm + +lemma triangularIncoming_in_rootCone {N:ℕ} (f:ElementaryExpr N) (m:Lattice n (Cell n)) + (hm:triangularIncoming f m≠0) : + ∃c:GapIndex n → ℕ, m=(N:ℤ) • anchor 0+forwardRoots (fun g=>(c g:ℤ)) := by + obtain ⟨b,hb,d,hd⟩:=polynomialSection_support (extendedOmega n) extendedOmega_self + (extendedRoots n) (extendedCoord n) (incomingCovector (extendedOmega n) (includeVertices m)) + (triangularExpression f) (includeVertices m) hm + obtain ⟨k,hk⟩:=triangularSeed_in_rootCone f b hb + have H:=rootDegree_add (extendedRoots n) hd hk + rw [sub_add_sub_cancel] at H + obtain ⟨c,_,he⟩:=H + refine ⟨c,?_⟩ + have hh:forwardRoots (fun g=>(c g:ℤ))=m-(N:ℤ) • anchor 0 := + congrArg Prod.fst he + rw [hh] + abel +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLateStationarity.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLateStationarity.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8992f368236678909a141680feddda5f9f197bd --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLateStationarity.lean @@ -0,0 +1,218 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.StationaryIntegerSequences + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open ElementaryPositivity.QuantumTorus +variable {n : ℕ} {B : Type*} [Fintype B] [DecidableEq B] +variable (Ω : Lattice n B →+ Lattice n B →+ ℤ) + +omit [Fintype B] in +lemma period_of_bridge_eq (level : B → Fin n) (cycle : List B) (L : ℕ) (m : Lattice n B) + (h : ∀ b, period Ω level cycle L m (Sum.inr b) = m (Sum.inr b)) : + period Ω level cycle L m = m ∧ ∀ b ∈ cycle, 0 ≤ Ω (eventRoot level L b) m := by + induction cycle generalizing m with + | nil => exact ⟨rfl,by simp⟩ + | cons b bs ih => + have hle := period_bridge_mono Ω level bs L (rotate Ω level L m b) b + change rotate Ω level L m b (Sum.inr b) ≤ period Ω level (b::bs) L m (Sum.inr b) at hle + rw [h b] at hle + have ht : max 0 (-Ω (eventRoot level L b) m) = 0 := by + simp only [rotate,mutationIncomingLabel,Pi.add_apply,Pi.smul_apply,eventRoot_bridge, + ite_true,smul_eq_mul,mul_one] at hle + omega + have hfix : rotate Ω level L m b = m := by + simp only [rotate,mutationIncomingLabel,ht,zero_zsmul,add_zero] + have hp : period Ω level (b::bs) L m = period Ω level bs L m := by + change period Ω level bs L (rotate Ω level L m b) = _ + rw [hfix] + have H := ih m (by intro c; simpa only [hp] using h c) + refine ⟨hp.trans H.1,fun c hc => ?_⟩ + rcases List.mem_cons.mp hc with rfl | hc + · omega + · exact H.2 c hc + +lemma history_late_fixed (level : B → Fin n) (cycle : List B) (m : Lattice n B) + (N : ℕ) (hs : ∀ L i, 0 ≤ cutDeficit level i N L (history Ω level cycle m L)) : + ∃ T, (∀ L, T ≤ L → history Ω level cycle m L = history Ω level cycle m T) ∧ + ∀ L, T ≤ L → ∀ b ∈ cycle, 0 ≤ Ω (eventRoot level L b) (history Ω level cycle m T) := by + obtain ⟨T,hT⟩ := history_bridge_stabilizes Ω level cycle m N hs + have he : ∀ L, T ≤ L → period Ω level cycle L (history Ω level cycle m L) = + history Ω level cycle m L ∧ + ∀ b ∈ cycle, 0 ≤ Ω (eventRoot level L b) (history Ω level cycle m L) := by + intro L hL + apply period_of_bridge_eq + intro b + change history Ω level cycle m (L+1) (Sum.inr b) = history Ω level cycle m L (Sum.inr b) + rw [hT (L+1) (by omega) b,hT L hL b] + have hconst : ∀ k, history Ω level cycle m (T+k) = history Ω level cycle m T := by + intro k + induction k with + | zero => simp + | succ k ih => + rw [Nat.add_succ,history] + exact ((he (T+k) (by omega)).1).trans ih + refine ⟨T,?_,?_⟩ + · intro L hL + simpa only [Nat.add_sub_of_le hL] using hconst (L-T) + · intro L hL b hb + have HH := (he L hL).2 b hb + have H := hconst (L-T) + rw [Nat.add_sub_of_le hL] at H + simpa only [H] using HH + +omit [Fintype B] in +lemma eventRoot_pairing (level : B → Fin n) (L : ℕ) (b : B) (m : Lattice n B) : + Ω (eventRoot level L b) m = Ω (eventRoot level 0 b) m + (L:ℤ)*Ω (delta level b) m := by + simp only [eventRoot,Nat.cast_zero,zero_zsmul,add_zero,map_add,map_zsmul, + AddMonoidHom.add_apply,AddMonoidHom.zsmul_apply,smul_eq_mul] + +omit [Fintype B] in +lemma period_fixed (level : B → Fin n) (cycle : List B) (L : ℕ) (m : Lattice n B) + (hp : ∀ b ∈ cycle, 0 ≤ Ω (eventRoot level L b) m) : period Ω level cycle L m = m := by + induction cycle with + | nil => rfl + | cons b bs ih => + change period Ω level bs L (mutationIncomingLabel Ω (eventRoot level L b) m) = m + rw [mutationIncomingLabel_nonnegative Ω _ m (hp b (by simp))] + exact ih (by intro c hc; exact hp c (by simp [hc])) + +omit [Fintype B] in +lemma period_injective (hΩ : ∀ m, Ω m m = 0) (level : B → Fin n) (cycle : List B) (L : ℕ) : + Function.Injective (period Ω level cycle L) := by + induction cycle with + | nil => exact Function.injective_id + | cons b bs ih => + intro m m' h + apply (mutationIncomingLabelEquiv Ω (eventRoot level L b) (hΩ _)).injective + apply ih + exact h + +omit [Fintype B] in +lemma history_injective (hΩ : ∀ m, Ω m m = 0) (level : B → Fin n) (cycle : List B) (L : ℕ) : + Function.Injective (fun m => history Ω level cycle m L) := by + induction L with + | zero => exact Function.injective_id + | succ L ih => + intro m m' h + apply ih + exact period_injective Ω hΩ level cycle L h + +omit [Fintype B] in +lemma history_fixed (level : B → Fin n) (cycle : List B) (m : Lattice n B) + (hp : ∀ L b, b ∈ cycle → 0 ≤ Ω (eventRoot level L b) m) (L : ℕ) : + history Ω level cycle m L = m := by + induction L with + | zero => rfl + | succ L ih => + rw [history,ih] + exact period_fixed Ω level cycle L m (hp L) +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open ElementaryPositivity.QuantumTorus +variable {n : ℕ} {B : Type*} [Fintype B] [DecidableEq B] + +def extendedTotal (level : B → Fin n) (m : Lattice n B) (k : ℕ) : ℤ := + if h : 0 < k ∧ k ≤ n then levelTotal level ⟨k-1,by omega⟩ m else 0 + +omit [DecidableEq B] in +@[simp] lemma extendedTotal_zero (level : B → Fin n) (m : Lattice n B) : + extendedTotal level m 0 = 0 := by simp [extendedTotal] +omit [DecidableEq B] in +@[simp] lemma extendedTotal_last (level : B → Fin n) (m : Lattice n B) : + extendedTotal level m (n+1) = 0 := by simp [extendedTotal] +omit [DecidableEq B] in +@[simp] lemma extendedTotal_succ (level : B → Fin n) (m : Lattice n B) (i : Fin n) : + extendedTotal level m (i.val+1) = levelTotal level i m := by + unfold extendedTotal + rw [dite_eq_left (by constructor <;> omega)] + congr 2 + +omit [DecidableEq B] in +lemma extendedTotal_nonpos (level : B → Fin n) (m : Lattice n B) + (h : ∀ i, levelTotal level i m ≤ 0) (k : ℕ) : extendedTotal level m k ≤ 0 := by + unfold extendedTotal + split_ifs with hk + · exact h _ + · rfl + +omit [DecidableEq B] in +lemma extendedTotal_all_zero (level : B → Fin n) (m : Lattice n B) + (h : ∀ k, k ≤ n+1 → extendedTotal level m k = 0) (k : ℕ) : + extendedTotal level m k = 0 := by + by_cases hk : k ≤ n+1 + · exact h k hk + · simp [extendedTotal,show ¬(0 ?_⟩ + rw [←eventRoot_pairing] + exact hp L hL b (hcycle b) + have ht : ∀ k, k ≤ n+1 → extendedTotal level star k = 0 := by + apply concave_nonpositive_zero (n+1) (extendedTotal level star) + (extendedTotal_zero _ _) (extendedTotal_last _ _) + · intro k _ + exact extendedTotal_nonpos level star (fun i => history_total_nonpos Ω level cycle m N hs T i) k + · intro k hk hkn + let i : Fin n := ⟨k-1,by omega⟩ + obtain ⟨b,hb⟩ := hl i + have HH := hslope b + rw [hdelta,hb] at HH + have hi : i.val+1=k := by dsimp [i]; omega + have hi' : i.val+2=k+1 := by omega + rw [hi,hi'] at HH + exact HH + have hall := extendedTotal_all_zero level star ht + have hd0 : ∀ b, Ω (delta level b) star = 0 := by + intro b + rw [hdelta,hall,hall,hall] + ring + have hp0 : ∀ b, 0 ≤ Ω (eventRoot level 0 b) star := by + intro b + have HH := hp T le_rfl b (hcycle b) + change 0 ≤ Ω (eventRoot level T b) star at HH + rw [eventRoot_pairing,hd0,mul_zero,add_zero] at HH + exact HH + have hpl : ∀ L b, b ∈ cycle → 0 ≤ Ω (eventRoot level L b) star := by + intro L b _ + rw [eventRoot_pairing,hd0,mul_zero,add_zero] + exact hp0 b + have hm : m = star := by + apply history_injective Ω hΩ level cycle T + change history Ω level cycle m T = history Ω level cycle star T + rw [history_fixed Ω level cycle star hpl T] + refine ⟨?_,?_,?_⟩ + · intro i + rw [hm,←extendedTotal_succ] + exact hall _ + · simpa only [hm] using hp0 + · intro L + rw [hm] + exact history_fixed Ω level cycle star hpl L +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLevelQueues.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLevelQueues.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd660f3c4020427e40b384f8668bbb6807b5a3e6 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLevelQueues.lean @@ -0,0 +1,163 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularGapOrthogonality + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open Classical +noncomputable section +variable {n : ℕ} + +def levelQueue (q : List (Cell n)) (i : Fin n) : List (Cell n) := q.filter (fun b=>decide (b.1=i)) +def initialLevelQueue (i : Fin n) : List (Cell n) := List.ofFn (fun j:Fin (i.val+1)=>⟨i,j.rev⟩) + +lemma mem_levelQueue (q : List (Cell n)) (i : Fin n) (b : Cell n) : + b∈levelQueue q i ↔ b∈q ∧ b.1=i := by simp [levelQueue] +lemma initialLevelQueue_mem (i : Fin n) (b : Cell n) : + b∈initialLevelQueue i ↔ b.1=i := by + rw [initialLevelQueue,List.mem_ofFn] + constructor + · rintro ⟨j,rfl⟩; rfl + · intro hb + cases b with | mk l r => + dsimp only at hb + subst l + exact ⟨r.rev,by simp⟩ + +lemma initialLevelQueue_nodup (i : Fin n) : (initialLevelQueue i).Nodup := by + rw [initialLevelQueue,List.nodup_ofFn] + intro j k h + have hh:=congrArg cellRow h + apply Fin.rev_injective + exact Fin.ext hh + +lemma initialLevelQueue_pairwise (i : Fin n) : (initialLevelQueue i).Pairwise phaseLE := by + rw [initialLevelQueue,List.pairwise_ofFn] + intro j k hjk + apply Or.inl + apply Or.inl + change k.rev.val < j.rev.val + simp only [Fin.val_rev] + have := k.isLt + omega + +lemma phaseCycle_levelQueue (i : Fin n) : levelQueue (phaseCycle n) i=initialLevelQueue i := by + apply List.Perm.eq_of_pairwise (fun a b _ _ hab hba=>Std.Antisymm.antisymm (r:=phaseLE) a b hab hba) + · exact List.Pairwise.filter _ phaseCycle_pairwise + · exact initialLevelQueue_pairwise i + · apply (List.perm_ext_iff_of_nodup (List.Nodup.filter _ phaseCycle_nodup) + (initialLevelQueue_nodup i)).mpr + intro b + simp only [List.mem_filter,decide_eq_true_eq,mem_phaseCycle,true_and,initialLevelQueue_mem] + +lemma levelQueue_cons (b : Cell n) (q : List (Cell n)) (i : Fin n) : + levelQueue (b::q) i=if b.1=i then b::levelQueue q i else levelQueue q i := by + by_cases h:b.1=i <;> simp [levelQueue,h] +lemma levelQueue_append (q r : List (Cell n)) (i : Fin n) : + levelQueue (q++r) i=levelQueue q i++levelQueue r i := by simp [levelQueue] +lemma levelQueue_rotate (b : Cell n) (q : List (Cell n)) (i : Fin n) : + levelQueue (q++[b]) i=levelQueue q i++(if b.1=i then [b] else []) := by + by_cases h:b.1=i <;> simp [levelQueue,h] + +lemma queue_update_off {M : Type*} (w : Cell n → M) (b : Cell n) (w' : M) + (q : List (Cell n)) (hb : b∉q) : q.map (Function.update w b w')=q.map w := by + apply List.map_congr_left + intro c hc + have hcb:c≠b:=by intro h; subst c; exact hb hc + exact Function.update_of_ne hcb _ _ + +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.ForwardChain +open ElementaryPositivity.QuantumTorus +variable {M : Type*} [AddCommGroup M] + +def gaps (a : M) : List M → M → List M + | [],c => [c-a] + | b::bs,c => (b-a)::gaps b bs c + +lemma gaps_append (a c d : M) (bs : List M) : + gaps a (bs++[c]) d=gaps a bs c++[d-c] := by + induction bs generalizing a with + | nil => rfl + | cons b bs ih => simp only [List.cons_append,gaps,ih] + +variable (Ω : M →+ M →+ ℤ) (p : M) +def positiveMutate (r : M) : M := r + max (-Ω p r) 0 • p + +lemma positiveMutate_nonneg (r : M) (h : 0 ≤ Ω p r) : positiveMutate Ω p r=r := by + simp only [positiveMutate,max_eq_right (by omega : -Ω p r≤0),zero_smul,add_zero] + +lemma positiveMutate_minus_one (r : M) (h : Ω p r= -1) : positiveMutate Ω p r=r+p := by + simp [positiveMutate,h] +lemma positiveMutate_minus_two (r : M) (h : Ω p r= -2) : positiveMutate Ω p r=r+p+p := by + simp only [positiveMutate,h,neg_neg,show max (2:ℤ) 0=2 by decide] + rw [show (2:ℤ) • p=p+p by simp [two_smul]] + abel + +lemma gaps_mutate_last (a c : M) (bs : List M) + (ha : Ω p a=0) (hc : Ω p c= -1) + (hb : ∀b∈bs,Ω p b=0) : + (gaps a bs c).map (positiveMutate Ω p)=gaps a bs (c+p) := by + induction bs generalizing a with + | nil => + simp only [gaps,List.map_cons,List.map_nil,List.cons.injEq,and_true] + rw [positiveMutate_minus_one Ω p (c-a) (by rw [map_sub,hc,ha,sub_zero])] + abel + | cons b bs ih => + have hb0:=hb b (by simp) + have hr:Ω p (b-a)=0 := by rw [map_sub,hb0,ha,sub_self] + simp only [gaps,List.map_cons] + rw [positiveMutate_nonneg Ω p (b-a) (by omega),ih b hb0 (fun x hx=>hb x (by simp [hx]))] + +lemma gaps_mutate_rotation (a b c : M) (bs : List M) (hp : p=b-a) + (_ha : Ω p a=1) (hb : Ω p b=1) (hc : Ω p c= -1) + (hs : ∀x∈bs,Ω p x=0) : + (gaps b bs c).map (positiveMutate Ω p)=gaps a bs (c+p) := by + cases bs with + | nil => + simp only [gaps,List.map_cons,List.map_nil,List.cons.injEq,and_true] + rw [positiveMutate_minus_two Ω p (c-b) (by rw [map_sub,hc,hb]; norm_num)] + rw [hp] + abel + | cons x xs => + have hx:=hs x (by simp) + simp only [gaps,List.map_cons] + rw [positiveMutate_minus_one Ω p (x-b) (by rw [map_sub,hx,hb]; norm_num), + gaps_mutate_last Ω p x c xs hx hc (fun z hz=>hs z (by simp [hz]))] + congr 1 + rw [hp] + abel + +lemma gaps_rotation_perm (a b c : M) (bs : List M) (hp : p=b-a) + (ha : Ω p a=1) (hb : Ω p b=1) (hc : Ω p c= -1) + (hs : ∀x∈bs,Ω p x=0) : + ((-p)::(gaps b bs c).map (positiveMutate Ω p)).Perm + (gaps a (bs++[c+p]) c) := by + rw [gaps_mutate_rotation Ω p a b c bs hp ha hb hc hs,gaps_append] + have H:c-(c+p)= -p := by abel + rw [H] + simpa only [List.singleton_append] using (List.perm_append_comm (l₁ := [-p]) (l₂ := gaps a bs (c+p))) + +lemma gaps_mutate_fixed (a c : M) (bs : List M) + (ha : Ω p a≤0) (hc : 0≤Ω p c) + (hb : ∀b∈bs,Ω p b=0) : + (gaps a bs c).map (positiveMutate Ω p)=gaps a bs c := by + induction bs generalizing a with + | nil => + simp only [gaps,List.map_cons,List.map_nil] + rw [positiveMutate_nonneg Ω p (c-a) (by rw [map_sub]; omega)] + | cons b bs ih => + have hb0:=hb b (by simp) + simp only [gaps,List.map_cons] + rw [positiveMutate_nonneg Ω p (b-a) (by rw [map_sub,hb0]; omega), + ih b (by omega) (fun x hx=>hb x (by simp [hx]))] +end ElementaryPositivity.ForwardChain + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLinearIncoming.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLinearIncoming.lean new file mode 100644 index 0000000000000000000000000000000000000000..4794b728031b62a561015fce90ac6b9f38ee65e8 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLinearIncoming.lean @@ -0,0 +1,163 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.RootCoefficientLocality +import OAI.Combinatorics.Chromatic.Walls.TriangularIncoming +import OAI.Combinatorics.Chromatic.QuantumTorus.IndependentElement + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +lemma triangularLinear_sum : triangularExpression (n:=n) (.atom 1)= + ∑a:Vertex n (Cell n),Torus.X LaurentRay.vUnit (extendedOmega n) + (includeVertices (Pi.single a (1:ℤ))) := by + unfold triangularExpression ElementaryExpr.eval + rw [independentElement_one _ _ extendedOmega_self] + apply Finset.sum_congr rfl + intro a _ + rw [initial_vertexDisplay] + +lemma triangularLinear_support (m:Extended (Vertex n (Cell n))) + (hm:(triangularExpression (.atom 1)) m≠0) : + ∃a:Vertex n (Cell n),m=includeVertices (Pi.single a (1:ℤ)) := by + rw [triangularLinear_sum,Finsupp.finsetSum_apply] at hm + obtain ⟨a,_,ha⟩:=Finset.exists_ne_zero_of_sum_ne_zero hm + refine ⟨a,?_⟩ + by_contra hh + exact ha (Finsupp.single_eq_of_ne hh) + +lemma vertex_single_injective : Function.Injective (fun a:Vertex n (Cell n)=> + includeVertices (Pi.single a (1:ℤ))) := by + intro a b hab + by_contra h + have H:=congrArg (fun m:Extended (Vertex n (Cell n))=>m.1 a) hab + change (Pi.single a (1:ℤ):Lattice n (Cell n)) a=(Pi.single b (1:ℤ):Lattice n (Cell n)) a at H + simp only [Pi.single_eq_same,Pi.single_eq_of_ne h] at H + omega + +lemma triangularLinear_vertex (a:Vertex n (Cell n)) : + triangularExpression (.atom 1) (includeVertices (Pi.single a (1:ℤ)))=1 := by + rw [triangularLinear_sum,Finsupp.finsetSum_apply,Finset.sum_eq_single a] + · simp [Torus.X,Torus.monomial] + · intro b _ hba + apply Finsupp.single_eq_of_ne + intro hh + exact hba (vertex_single_injective hh.symm) + · simp + +lemma triangularLinear_locality (m:Lattice n (Cell n)) (hm:triangularIncoming (.atom 1) m≠0) : + triangularIncoming (.atom 1) m=triangularExpression (.atom 1) (includeVertices m) := by + obtain ⟨c,hc⟩:=triangularIncoming_in_rootCone (.atom 1) m hm + simp only [Nat.cast_one,one_smul] at hc + obtain ⟨hK,hxi,_⟩:=triangularExpression_stationary (.atom 1) m hm + exact actualPolynomialAdjoint_locality (extendedOmega n) extendedOmega_self + (extendedRoots n) (extendedCoord n) extendedCoord_roots + (rootSectionChart (extendedOmega n) (extendedRoots n) (incomingCovector (extendedOmega n) (includeVertices m))) + (includeVertices (anchor 0)) (includeVertices m) c (by rw [hc,map_add]; rfl) + (triangularExpression (.atom 1)) (by + intro b hb + simpa only [Nat.cast_one,one_smul] using triangularSeed_in_rootCone (.atom 1) b hb) + (by intro g hg + rw [extendedRoot_eq,extendedOmega_original] + exact positive_gap_target_zero (fun i=>(c i:ℤ)) m (fun _=>Int.natCast_nonneg _) hc hK hxi g + (by exact_mod_cast hg)) + +lemma stationary_vertex_initial (a:Vertex n (Cell n)) + (hK:∀i,levelTotal cellLevel i (Pi.single a (1:ℤ))=0) + (hxi:∀b,0 ≤ triangularOmega n (eventRoot cellLevel 0 b) (Pi.single a (1:ℤ))) : + a=Sum.inl (0:Fin (n+1)) := by + cases a with + | inr b => + have H:=hK b.1 + change levelTotal cellLevel b.1 (bridge b)=0 at H + simp only [levelTotal_bridge,cellLevel,ite_true] at H + contradiction + | inl a => + congr 1 + by_contra ha + have ha0:0 < a.val:=by + have hh:a.val≠0:=by intro H; exact ha (Fin.ext H) + omega + let i:Fin n:=⟨a.val-1,by have := a.isLt; omega⟩ + let b:Cell n:=⟨i,⟨0,by omega⟩⟩ + have H:=hxi b + change 0 ≤ triangularOmega n (eventRoot cellLevel 0 b) (anchor a) at H + rw [eventRoot_anchor] at H + have he:a=b.1.succ:=by apply Fin.ext; dsimp [b,i]; omega + have hn:a≠b.1.castSucc:=by intro hh; have := congrArg Fin.val hh; dsimp [b,i] at this; omega + rw [ite_eq_left he,ite_eq_right hn] at H + omega + +lemma triangularLinear_onlyIncoming (m:Lattice n (Cell n)) (hm:triangularIncoming (.atom 1) m≠0) : + m=anchor 0 := by + have H:=triangularLinear_locality m hm + rw [H] at hm + obtain ⟨a,ha⟩:=triangularLinear_support (includeVertices m) hm + have he:m=Pi.single a (1:ℤ):=congrArg Prod.fst ha + obtain ⟨hK,hxi,_⟩:=triangularExpression_stationary (.atom 1) m (by rw [H]; exact hm) + rw [he] at hK hxi + rw [he,stationary_vertex_initial a hK hxi] + rfl +lemma triangularLinear_anchorIncoming : triangularIncoming (n:=n) (.atom 1) (anchor 0)=1 := by + have H:=actualPolynomialAdjoint_locality (extendedOmega n) extendedOmega_self + (extendedRoots n) (extendedCoord n) extendedCoord_roots + (rootSectionChart (extendedOmega n) (extendedRoots n) (incomingCovector (extendedOmega n) (includeVertices (anchor 0)))) + (includeVertices (anchor 0)) (includeVertices (anchor 0)) (fun _=>0) (by + change _ = _ + extendedRoots n 0 + rw [map_zero,add_zero]) + (triangularExpression (.atom 1)) (by + intro b hb + simpa only [Nat.cast_one,one_smul] using triangularSeed_in_rootCone (.atom 1) b hb) + (by intro g hg; omega) + change triangularIncoming (.atom 1) (anchor 0)=_ at H + rw [H] + exact triangularLinear_vertex (.inl 0) + +lemma triangularLinear_incoming (m:Lattice n (Cell n)) : + triangularIncoming (.atom 1) m=if m=anchor 0 then 1 else 0 := by + by_cases hm:m=anchor 0 + · rw [hm,ite_eq_left rfl,triangularLinear_anchorIncoming] + · rw [ite_eq_right hm] + by_contra hn + exact hm (triangularLinear_onlyIncoming m hn) + +lemma triangularIncoming_dual_zero {N:ℕ} (f:ElementaryExpr N) (m:Extended (Vertex n (Cell n))) + (hm:polynomialSectionIncoming (extendedOmega n) (extendedRoots n) (extendedCoord n) + (triangularExpression f) m≠0) : m.2=0 := by + obtain ⟨b,hb,d,c,_,he⟩:=polynomialSection_support (extendedOmega n) extendedOmega_self + (extendedRoots n) (extendedCoord n) (incomingCovector (extendedOmega n) m) + (triangularExpression f) m hm + have H:=congrArg Prod.snd he + change 0=m.2-b.2 at H + rw [triangularSeed_dual_zero f b hb,sub_zero] at H + exact H.symm + +lemma triangularLinear_fullIncoming (m:Extended (Vertex n (Cell n))) : + polynomialSectionIncoming (extendedOmega n) (extendedRoots n) (extendedCoord n) + (triangularExpression (.atom 1)) m=if m=includeVertices (anchor 0) then 1 else 0 := by + by_cases hd:m.2=0 + · have he:m=includeVertices m.1:=Prod.ext rfl hd + rw [he] + change triangularIncoming (.atom 1) m.1=_ + rw [triangularLinear_incoming] + congr 1 + apply propext + constructor + · intro hh; rw [hh] + · exact fun hh=>congrArg Prod.fst hh + · have hn:m≠includeVertices (anchor 0):=by intro hh; exact hd (congrArg Prod.snd hh) + rw [ite_eq_right hn] + by_contra hz + exact hd (triangularIncoming_dual_zero (.atom 1) m hz) + +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLinearSection.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLinearSection.lean new file mode 100644 index 0000000000000000000000000000000000000000..6434b16564ae37dc5d5b527206ca419c884aa960 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularLinearSection.lean @@ -0,0 +1,222 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.IncomingExtremalLocality +import OAI.Combinatorics.Chromatic.QuantumTorus.PolynomialThetaIdentification +import OAI.Combinatorics.Chromatic.Walls.TriangularLinearIncoming + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension PowerSeries PowerSeriesAdjoint +open Classical +noncomputable section +variable {n:ℕ} + +lemma extendedCoord_anchor_zero : extendedCoord n (includeVertices (anchor 0))=0 := by + ext g + change forwardCoord (Pi.single (Sum.inl (0:Fin (n+1))) (1:ℤ)) g=0 + rw [forwardCoord_single] + simp [afterGap] +lemma rootOrder_anchor_zero : rootOrder (extendedCoord n) (includeVertices (anchor 0))=0 := by + change (∑g,extendedCoord n (includeVertices (anchor 0)) g)=0 + rw [extendedCoord_anchor_zero] + simp +lemma triangularLinear_initial : + polynomialInitial (extendedOmega n) (extendedRoots n) (extendedCoord n) (triangularExpression (.atom 1))= + thetaInitial LaurentRay.vUnit (extendedOmega n) (extendedRoots n) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) (includeVertices (anchor 0)) := by + apply polynomialInitial_eq_theta (extendedOmega n) extendedOmega_self (extendedRoots n) + (extendedCoord n) extendedCoord_roots (includeVertices (anchor 0)) (rootOrder_anchor_zero (n:=n)) + · intro m hm + simpa only [Nat.cast_one,one_smul] using triangularSeed_in_rootCone (.atom 1) m (Finsupp.mem_support_iff.mpr hm) + · intro m + by_cases he:m=includeVertices (anchor 0) + · simpa only [ite_eq_left he] using triangularLinear_fullIncoming m + · simpa only [ite_eq_right he] using triangularLinear_fullIncoming m + +lemma triangularLinear_theta (h:Extended (Vertex n (Cell n)) →+ ℝ) : + adjoint (rootSectionChart (extendedOmega n) (extendedRoots n) h).val + (homogenize LaurentRay.vUnit (extendedOmega n) (rootOrder (extendedCoord n)) (triangularExpression (.atom 1)))= + thetaValue LaurentRay.vUnit (extendedOmega n) (extendedRoots n) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) (includeVertices (anchor 0)) h := by + rw [rootSectionChart_action] + change sectionValue _ _ _ _ _ (polynomialInitial _ _ _ _)=_ + rw [triangularLinear_initial] + rfl + +lemma triangularLinear_negative_theta (h:Extended (Vertex n (Cell n)) →+ ℝ) + (hh:∀k,0 change -(triangularOmega n (anchor a) (pureAnchor μ)) ≤ 0; rw [anchor_pair_pure]; omega + | inr b=> change -(triangularOmega n (bridge b) (pureAnchor μ)) ≤ 0; rw [bridge_pair_pure]; have := hμ b.1; omega) m hm + change -(extendedOmega n m (includeVertices (pureAnchor μ))) ≤ (N:ℤ)*0 at H + omega + +lemma triangularPure_incoming {N:ℕ} (f:ElementaryExpr N) (μ:Fin (n+1) → ℤ) + (hμ:∀i:Fin n,μ i.succ ≤ μ i.castSucc) : + triangularIncoming f (pureAnchor μ)=triangularExpression f (includeVertices (pureAnchor μ)) := by + apply polynomialSectionIncoming_extremal (extendedOmega n) extendedOmega_self (extendedRoots n) (extendedCoord n) + intro m hm + exact triangularSeed_dominant_nonnegative f μ hμ m hm +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension PowerSeries PowerSeriesAdjoint +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} +local instance triangularLinearSectionRing : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance triangularLinearSectionAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup + +local instance triangularLinearSectionAddGroup : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup +local instance triangularLinearSectionSub : Sub (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toSub + +local instance triangularLinearSectionNonUnitalSemiring : NonUnitalSemiring (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toNonUnitalSemiring +local instance triangularLinearSectionNonUnitalNonAssocSemiring : NonUnitalNonAssocSemiring (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toNonUnitalNonAssocSemiring + +lemma pureAnchor_of_bridges_zero (m:Lattice n (Cell n)) (hm:∀b,m (.inr b)=0) : + m=pureAnchor (fun a=>m (.inl a)) := by + ext a + cases a with + | inl a=>rw [pureAnchor_apply_anchor] + | inr b=>rw [pureAnchor_apply_bridge,hm] + +lemma bridges_zero_of_level_zero (m:Lattice n (Cell n)) + (hm:∀b,0 ≤ m (.inr b)) (hK:∀i,levelTotal cellLevel i m=0) : ∀b,m (.inr b)=0 := by + intro b + have H:=hK b.1 + change (∑c:Cell n,if cellLevel c=b.1 then m (.inr c) else 0)=0 at H + have Hp:∀c:Cell n,0 ≤ if cellLevel c=b.1 then m (.inr c) else 0:=by + intro c; split_ifs <;> first | exact hm c | omega + have hh: (if cellLevel b=b.1 then m (.inr b) else 0) ≤ + ∑c:Cell n,if cellLevel c=b.1 then m (.inr c) else 0 := + Finset.single_le_sum (fun c _=>Hp c) (Finset.mem_univ b) + rw [H] at hh + simp only [cellLevel,ite_true] at hh + exact le_antisymm hh (hm b) + +lemma triangularSeed_order_nonnegative {N:ℕ} (f:ElementaryExpr N) : + ∀m,triangularExpression (n:=n) f m≠0 → 0 ≤ rootOrder (extendedCoord n) m := by + apply conePolynomial_nonnegativeOrder (extendedOmega n) (extendedRoots n) (extendedCoord n) + extendedCoord_roots (includeVertices ((N:ℤ) • anchor 0)) + · rw [map_zsmul,map_zsmul,rootOrder_anchor_zero,zsmul_zero] + · intro m hm + exact triangularSeed_in_rootCone f m (Finsupp.mem_support_iff.mpr hm) + +theorem triangularPure_detect {N:ℕ} (f:ElementaryExpr N) + (hpure:∀μ:Fin (n+1) → ℤ,triangularExpression f (includeVertices (pureAnchor μ))=0) : + triangularExpression (n:=n) f=0 := by + let Y:=homogenize LaurentRay.vUnit (extendedOmega n) (rootOrder (extendedCoord n)) (triangularExpression f) + have hY:∀k,coeff k Y=0:=by + intro k + induction k using Nat.strong_induction_on with + | h k ih=> + apply Finsupp.ext + intro m + by_contra hm + have hs:triangularExpression f m≠0:=by + intro hz + exact hm (by simp [Y,homogenize_coeff,hz]) + have hd:k=(rootOrder (extendedCoord n) m).toNat:=by + by_contra hd + exact hm (by simp [Y,homogenize_coeff,hd]) + have hz:0 ≤ rootOrder (extendedCoord n) m:=triangularSeed_order_nonnegative f m hs + have hdual:m.2=0:=triangularSeed_dual_zero f m (Finsupp.mem_support_iff.mpr hs) + have hinc:polynomialSectionIncoming (extendedOmega n) (extendedRoots n) (extendedCoord n) + (triangularExpression f) m=coeff k Y m:=by + have H:=adjoint_leading + (rootSectionChart (extendedOmega n) (extendedRoots n) (incomingCovector (extendedOmega n) m)).val + Y 0 (rootSectionChart (extendedOmega n) (extendedRoots n) _).property.1 k + (by intro j hj; rw [ih j hj]; rfl) + simp only [adjoint,mul_zero,zero_mul] at H + have H := sub_left_inj.mp H + have hh:=congrArg (fun t:Torus LaurentRay.vUnit (extendedOmega n)=>t m) H + change coeff k (adjoint _ Y) m=coeff k Y m at hh + rw [hd,homogenize_adjoint_actual (extendedOmega n) extendedOmega_self + (rootOrder (extendedCoord n)) _ (triangularExpression f) (triangularSeed_order_nonnegative f) m hz] at hh + simpa only [polynomialSectionIncoming,polynomialSectionCoefficient,hd] using hh + have he:m=includeVertices m.1:=Prod.ext rfl hdual + have hi:triangularIncoming f m.1≠0:=by + change polynomialSectionIncoming (extendedOmega n) (extendedRoots n) (extendedCoord n) + (triangularExpression f) (includeVertices m.1)≠0 + rw [←he,hinc] + exact hm + have hK:∀i,levelTotal cellLevel i m.1=0:=(triangularExpression_stationary f m.1 hi).1 + have hb:=bridges_zero_of_level_zero m.1 + (fun b=>triangularSeed_nonneg f m (Finsupp.mem_support_iff.mpr hs) (.inr b)) hK + have hp:=pureAnchor_of_bridges_zero m.1 hb + apply hs + rw [he,hp] + exact hpure _ + apply Finsupp.ext + intro m + have H:=congrArg (fun t:Torus LaurentRay.vUnit (extendedOmega n)=>t m) (hY (rootOrder (extendedCoord n) m).toNat) + simpa only [Y,homogenize_coeff,ite_true,Finsupp.zero_apply] using H +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularMonomialCriterion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularMonomialCriterion.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6331491c997088039f0fcc8863cd2eee77a1ff5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularMonomialCriterion.lean @@ -0,0 +1,210 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.LaurentPositiveDomination + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization PowerSeries PowerSeriesAdjoint LaurentPositive +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} +local instance : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance : AddCommMonoid (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommMonoid +local instance : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup +local instance : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup +local instance : Sub (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toSub + +lemma triangularConeDelta_apply (N d k:ℕ) (μ:Fin (n+1) → ℕ) + (hm:HasRootDegree (extendedRoots n) d (includeVertices (natAnchor μ)-triangularBase N)) + (m:Extended (Vertex n (Cell n))) (hk:HasRootDegree (extendedRoots n) k (m-triangularBase N)) : + coneDelta (extendedOmega n) d (includeVertices (natAnchor μ)) k m= + if m=includeVertices (natAnchor μ) then 1 else 0 := by + by_cases he:m=includeVertices (natAnchor μ) + · subst m + have H1:=rootOrder_eq (extendedRoots n) (extendedCoord n) extendedCoord_roots hm + have H2:=rootOrder_eq (extendedRoots n) (extendedCoord n) extendedCoord_roots hk + have hkd:k=d:=by omega + subst k + simp [coneDelta,Torus.X,Torus.monomial] + · rw [ite_eq_right he,coneDelta] + split_ifs + · exact Finsupp.single_eq_of_ne he + · rfl + +lemma triangularMonomial_initial {N:ℕ} (f:ElementaryExpr N) + (d:ℕ) (μ:Fin (n+1) → ℕ) (hμ:∑a,μ a=N) (hdom:∀i:Fin n,μ i.succ ≤ μ i.castSucc) + (hm:HasRootDegree (extendedRoots n) d (includeVertices (natAnchor μ)-triangularBase N)) + (hp:∀ν:Fin (n+1) → ℤ,(∀i:Fin n,ν i.succ ≤ ν i.castSucc) → + triangularExpression f (includeVertices (pureAnchor ν))=if ν=(fun a=>(μ a:ℤ)) then 1 else 0) : + polynomialInitial (extendedOmega n) (extendedRoots n) (extendedCoord n) (triangularExpression f)= + coneThetaInitial (extendedOmega n) (extendedRoots n) (simpleTotalTransport (extendedOmega n) (extendedRoots n)) + (triangularBase N) d (includeVertices (natAnchor μ)) := by + let X:=polynomialInitial (extendedOmega n) (extendedRoots n) (extendedCoord n) (triangularExpression f) + let T:=coneThetaInitial (extendedOmega n) (extendedRoots n) (simpleTotalTransport (extendedOmega n) (extendedRoots n)) + (triangularBase N) d (includeVertices (natAnchor μ)) + have hX:=triangularExpression_initial_graded (n:=n) f + have hT:=coneThetaInitial_graded (extendedOmega n) (extendedRoots n) (simpleTotalTransport (extendedOmega n) (extendedRoots n)) (triangularBase N) d _ hm + obtain ⟨L,hL⟩:=real_covector_prescribe (extendedRoots n) extendedCast extendedRoots_realIndependent (fun _=>1) + let h:Module.Dual ℝ ((Vertex n (Cell n) → ℝ) × (Vertex n (Cell n) → ℝ)) := -L + have hneg:∀k,0 + apply Finsupp.ext + intro m + by_contra hne + have hkm:HasRootDegree (extendedRoots n) k (m-triangularBase N):=by + by_contra hh + exact hne ((hX k m hh).trans (hT k m hh).symm) + have H:=sectionIncoming_leading LaurentRay.vUnit (extendedOmega n) (extendedRoots n) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) (triangularBase N) k X T + ih (hX k) (hT k) + have HI:(sectionIncoming LaurentRay.vUnit (extendedOmega n) (extendedRoots n) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) (triangularBase N) k X) m - + coneDelta (extendedOmega n) d (includeVertices (natAnchor μ)) k m ≠ 0 := by + intro hz + rw [←coneThetaInitial_prescription (extendedOmega n) (extendedRoots n) _ (triangularBase N) d _ hm k] at hz + have HH:=congrArg (fun z:Torus LaurentRay.vUnit (extendedOmega n)=>z m) H + rw [torus_sub_apply,torus_sub_apply] at HH + exact hne (sub_eq_zero.mp (HH.symm.trans hz)) + rw [polynomialInitial_incoming (extendedOmega n) extendedOmega_self (extendedRoots n) + (extendedCoord n) extendedCoord_roots (triangularBase N) (triangularBase_order N) _ + (by intro a ha; exact triangularSeed_in_rootCone f a (Finsupp.mem_support_iff.mpr ha)) k m hkm, + triangularConeDelta_apply N d k μ hm m hkm] at HI + have Hneg:=adjoint_leading + (chartNegative LaurentRay.vUnit (extendedOmega n) (extendedRoots n) (h.toAddMonoidHom.comp extendedCast) + (simpleTotalTransport (extendedOmega n) (extendedRoots n))).val X T + (chartNegative _ _ _ _ _).property.1 k ih + change coeff k (sectionValue _ _ _ _ _ X)-coeff k (sectionValue _ _ _ _ _ T)=_ at Hneg + rw [hval] at Hneg + have Hord:coeff k (homogenize LaurentRay.vUnit (extendedOmega n) (rootOrder (extendedCoord n)) + (triangularExpression f)) m - coeff k (triangularConeTheta N d μ (h.toAddMonoidHom.comp extendedCast)) m ≠0:=by + intro hz + have HH:=congrArg (fun z:Torus LaurentRay.vUnit (extendedOmega n)=>z m) Hneg + rw [torus_sub_apply,torus_sub_apply] at HH + exact hne (sub_eq_zero.mp (HH.symm.trans hz)) + have hs:triangularExpression f m≠0 ∨ triangularExpression (linearPower N) m≠0:=by + by_cases hf:triangularExpression f m=0 + · right + apply triangularTheta_support N d μ hμ hdom hm h hneg k m + intro ht + exact Hord (by simp [homogenize_coeff,hf,ht]) + · exact Or.inl hf + have hdual:m.2=0:=hs.elim + (fun hf=>triangularSeed_dual_zero f m (Finsupp.mem_support_iff.mpr hf)) + (fun hf=>triangularSeed_dual_zero (linearPower N) m (Finsupp.mem_support_iff.mpr hf)) + have hnon:∀b,0 ≤ m.1 (.inr b):=fun b=>hs.elim + (fun hf=>triangularSeed_nonneg f m (Finsupp.mem_support_iff.mpr hf) (.inr b)) + (fun hf=>triangularSeed_nonneg (linearPower N) m (Finsupp.mem_support_iff.mpr hf) (.inr b)) + have he:m=includeVertices m.1:=Prod.ext rfl hdual + have hpure:∃ν:Fin (n+1) → ℤ,m=includeVertices (pureAnchor ν):=by + by_cases htarget:m=includeVertices (natAnchor μ) + · exact ⟨fun a=>(μ a:ℤ),htarget⟩ + · rw [ite_eq_right htarget,sub_zero,he] at HI + have hK:∀i,levelTotal cellLevel i m.1=0:=(triangularExpression_stationary f m.1 HI).1 + exact ⟨fun a=>m.1 (.inl a),he.trans (congrArg includeVertices (pureAnchor_of_bridges_zero m.1 + (bridges_zero_of_level_zero m.1 hnon hK)))⟩ + obtain ⟨ν,rfl⟩:=hpure + change triangularIncoming f (pureAnchor ν)-(if includeVertices (pureAnchor ν)=includeVertices (natAnchor μ) then 1 else 0)≠0 at HI + rw [triangularPureIncoming_delta f (fun a=>(μ a:ℤ)) (fun i=>Int.ofNat_le.mpr (hdom i)) hp] at HI + have hh:includeVertices (pureAnchor ν)=includeVertices (natAnchor μ) ↔ ν=(fun a=>(μ a:ℤ)):=by + constructor + · exact fun H=>pureAnchor_injective (congrArg Prod.fst H) + · intro H; rw [H]; rfl + exact HI (by simp only [hh,sub_self]) +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} +local instance : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance : AddCommMonoid (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommMonoid +local instance : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup +local instance : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup +local instance : Sub (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toSub + +def anchorExponent : (Fin (n+1) →₀ ℕ) →+ Extended (Vertex n (Cell n)) where + toFun d:=includeVertices (pureAnchor (fun a=>(d a:ℤ))) + map_zero':=by apply Prod.ext; ext a; cases a <;> simp [pureAnchor_apply_anchor,pureAnchor_apply_bridge]; rfl + map_add' d e:=by + apply Prod.ext + · ext a + cases a <;> simp [pureAnchor_apply_anchor,pureAnchor_apply_bridge] + · rfl +lemma anchorExponent_injective : Function.Injective (anchorExponent (n:=n)) := by + intro d e he + ext a + have H:=congrArg (fun m:Extended (Vertex n (Cell n))=>m.1 (.inl a)) he + change pureAnchor (fun a=>(d a:ℤ)) (.inl a)=pureAnchor (fun a=>(e a:ℤ)) (.inl a) at H + rw [pureAnchor_apply_anchor,pureAnchor_apply_anchor] at H + exact Int.ofNat_inj.mp H +lemma anchorExponent_pair (d e:Fin (n+1) →₀ ℕ) : + extendedOmega n (anchorExponent d) (anchorExponent e)=0 := by + change extendedOmega n (includeVertices _) (includeVertices _)=0 + rw [extendedOmega_original,pureAnchor_pair] + +def anchorPolynomialAdd : MvPolynomial (Fin (n+1)) (LaurentSeries ℚ) →+ + Torus LaurentRay.vUnit (extendedOmega n) where + toFun p:=Finsupp.mapDomain (anchorExponent (n:=n)) (AddMonoidAlgebra.coeff p) + map_zero':=Finsupp.mapDomain_zero + map_add' _ _:=Finsupp.mapDomain_add +lemma anchorPolynomial_monomial (d:Fin (n+1) →₀ ℕ) (r:LaurentSeries ℚ) : + anchorPolynomialAdd (MvPolynomial.monomial d r)=Torus.monomial LaurentRay.vUnit (extendedOmega n) (anchorExponent d) r := + Finsupp.mapDomain_single +lemma anchorPolynomial_coeff (p:MvPolynomial (Fin (n+1)) (LaurentSeries ℚ)) (d:Fin (n+1) →₀ ℕ) : + anchorPolynomialAdd p (anchorExponent d)=p.coeff d := + Finsupp.mapDomain_apply_of_injective anchorExponent_injective (AddMonoidAlgebra.coeff p) d +lemma anchorPolynomial_mul (p q:MvPolynomial (Fin (n+1)) (LaurentSeries ℚ)) : + anchorPolynomialAdd (p*q)=anchorPolynomialAdd p*anchorPolynomialAdd q := by + induction p using MvPolynomial.induction_on' with + | add p p' hp hp'=>simp only [add_mul,map_add,hp,hp'] + | monomial d r=> + induction q using MvPolynomial.induction_on' with + | add q q' hq hq'=>simp only [mul_add,map_add,hq,hq'] + | monomial e s=> + rw [MvPolynomial.monomial_mul_monomial,anchorPolynomial_monomial,anchorPolynomial_monomial,anchorPolynomial_monomial, + Torus.monomial_mul_monomial,anchorExponent_pair,zpow_zero,Units.val_one,mul_one,map_add] + +def anchorPolynomial : MvPolynomial (Fin (n+1)) (LaurentSeries ℚ) →+* + Torus LaurentRay.vUnit (extendedOmega n) where + __:=anchorPolynomialAdd + map_one':=by + change anchorPolynomialAdd (MvPolynomial.monomial 0 1)=_ + rw [anchorPolynomial_monomial,map_zero] + rfl + map_mul':=anchorPolynomial_mul +lemma anchorPolynomial_X (a:Fin (n+1)) : + anchorPolynomial (MvPolynomial.X a)=Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (anchor a)) := by + change anchorPolynomialAdd (MvPolynomial.monomial (Finsupp.single a 1) 1)=_ + rw [anchorPolynomial_monomial] + congr 1 + apply Prod.ext + · ext b + cases b with + | inl b=>simp [anchorExponent,pureAnchor_apply_anchor,anchor,Pi.single_apply,Finsupp.single_apply,eq_comm] + | inr b=>simp [anchorExponent,pureAnchor_apply_bridge,anchor] + · rfl +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularMonomialProducer.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularMonomialProducer.lean new file mode 100644 index 0000000000000000000000000000000000000000..51aea0a234778f0287f2f0063bc583c0d1be7f4e --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularMonomialProducer.lean @@ -0,0 +1,80 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularAnchorProjection +import OAI.Combinatorics.Chromatic.QuantumTorus.OrdinaryExpressionNaturality + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization PowerSeries PowerSeriesAdjoint LaurentPositive +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} + +lemma orbitExpression_pureCoeff {N:ℕ} (f:ElementaryExpr N) (μ:Fin (n+1) →₀ ℕ) + (hμ:∀i:Fin n,μ i.succ ≤ μ i.castSucc) + (hf:f.ordinary= (OrbitMonomial.polynomial μ:MvPolynomial (Fin (n+1)) ℤ)) + (ν:Fin (n+1) → ℤ) (hν:∀i:Fin n,ν i.succ ≤ ν i.castSucc) : + triangularExpression f (includeVertices (pureAnchor ν))=if ν=(fun a=>(μ a:ℤ)) then 1 else 0 := by + have hmap:f.ordinary=(OrbitMonomial.polynomial μ:MvPolynomial (Fin (n+1)) (LaurentSeries ℚ)):=by + rw [←ElementaryExpr.ordinary_map f (Int.castRingHom (LaurentSeries ℚ)),hf,OrbitMonomial.polynomial_map] + by_cases hnon:∀a,0 ≤ ν a + · let d:Fin (n+1) →₀ ℕ:=Finsupp.equivFunOnFinite.symm (fun a=>(ν a).toNat) + have hd:∀a,(d a:ℤ)=ν a:=fun a=>Int.toNat_of_nonneg (hnon a) + have hdd:∀i:Fin n,d i.succ ≤ d i.castSucc:=by + intro i + exact Int.ofNat_le.mp (by simpa only [hd] using hν i) + have he:includeVertices (pureAnchor ν)=anchorExponent d:=by + change includeVertices (pureAnchor ν)=includeVertices (pureAnchor (fun a=>(d a:ℤ))) + rw [show (fun a=>(d a:ℤ))=ν from funext hd] + rw [he,triangularExpression_anchorCoeff,hmap,OrbitMonomial.dominant_coeff μ d hμ hdd] + have hh:d=μ ↔ ν=(fun a=>(μ a:ℤ)):=by + constructor + · intro h; funext a; rw [←hd a,h] + · intro h; ext a; apply Int.ofNat_inj.mp; rw [hd,h] + simp only [hh] + · obtain ⟨a,ha⟩:=not_forall.mp hnon + have he:ν≠(fun a=>(μ a:ℤ)):=by intro h; apply ha; rw [h]; exact Int.natCast_nonneg _ + rw [ite_eq_right he] + by_contra hh + have H:=triangularSeed_nonneg f _ (Finsupp.mem_support_iff.mpr hh) (.inl a) + have H':0 ≤ pureAnchor ν (.inl a):=H + exact ha (by simpa only [pureAnchor_apply_anchor] using H') + +lemma natAnchor_rootDegree (μ:Fin (n+1) →₀ ℕ) : + ∃d,HasRootDegree (extendedRoots n) d (anchorExponent μ-triangularBase μ.degree) := by + have hpos:∀a,0 ≤ natAnchor (fun a=>μ a) a:=by + intro a + cases a <;> simp [natAnchor,pureAnchor_apply_anchor,pureAnchor_apply_bridge] + obtain ⟨d,c,hc,he⟩:=triangularVertex_rootDegree (natAnchor (fun a=>μ a)) hpos + have hw:vertexWeight (natAnchor (fun a=>μ a))=(μ.degree:ℤ):=by + rw [vertexWeight_apply,Fintype.sum_sum_type] + simp only [natAnchor,pureAnchor_apply_anchor,pureAnchor_apply_bridge,Finset.sum_const_zero,add_zero] + rw [Finsupp.degree_eq_sum,Nat.cast_sum] + refine ⟨d,c,hc,?_⟩ + change includeVertices (forwardRoots (fun i=>(c i:ℤ)))=anchorExponent μ-triangularBase μ.degree + change forwardRoots (fun i=>(c i:ℤ))=natAnchor (fun a=>μ a)-vertexWeight (natAnchor (fun a=>μ a)) • anchor 0 at he + rw [hw] at he + rw [he,map_sub] + rfl + +lemma triangularMonomial_producer (μ:Fin (n+1) →₀ ℕ) + (hμ:∀i:Fin n,μ i.succ ≤ μ i.castSucc) : + ∃f:ElementaryExpr μ.degree, f.ordinary=(OrbitMonomial.polynomial μ:MvPolynomial (Fin (n+1)) ℤ) ∧ + ∃d,HasRootDegree (extendedRoots n) d (anchorExponent μ-triangularBase μ.degree) ∧ + polynomialInitial (extendedOmega n) (extendedRoots n) (extendedCoord n) (triangularExpression f)= + coneThetaInitial (extendedOmega n) (extendedRoots n) (simpleTotalTransport (extendedOmega n) (extendedRoots n)) + (triangularBase μ.degree) d (anchorExponent μ) := by + obtain ⟨f,hf⟩:=homogeneousExpression_representation (OrbitMonomial.polynomial μ:MvPolynomial (Fin (n+1)) ℤ) + (OrbitMonomial.polynomial_symmetric μ) (OrbitMonomial.polynomial_homogeneous μ) + obtain ⟨d,hd⟩:=natAnchor_rootDegree μ + refine ⟨f,hf,d,hd,?_⟩ + exact triangularMonomial_initial f d (fun a=>μ a) (Finsupp.degree_eq_sum μ).symm hμ hd + (orbitExpression_pureCoeff f μ hμ hf) +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPeriodTransport.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPeriodTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb0a15ba3ce204ab4db4b83e6beafe99acf60fc8 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPeriodTransport.lean @@ -0,0 +1,205 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PolynomialSection +import OAI.Combinatorics.Chromatic.Walls.RealLatticeRealization +import OAI.Combinatorics.Chromatic.Walls.ForwardPolynomialMutation + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits +open Classical +noncomputable section +variable {n:ℕ} {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (hnd:∀r≠0,∃m,Ω r m≠0) +variable (h:Lattice n (Cell n) →+ M) (hform:∀x y,Ω (h x) (h y)=triangularOmega n x y) + +include hform in +lemma mutationIncomingLabel_map (p m:Lattice n (Cell n)) : + mutationIncomingLabel Ω (h p) (h m)=h (mutationIncomingLabel (triangularOmega n) p m) := by + simp only [mutationIncomingLabel,hform,map_add,map_zsmul] + +include hΩ he hS hcomp hnd hform in +lemma partial_period_transport (is:List I) (his:is.Nodup) (hall:∀i,i∈is) + (L:ℕ) (rest:List (Cell n)) (pre:List (Cell n)) + (hcycle:phaseCycle n=pre++rest) (ch:FreeChart (I:=I) e) + (hinv:(is.map (simpleRoot ch.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ partialBridge L pre) (rest++pre))) + {N:ℕ} (f:ElementaryExpr N) : + ∃ch':FreeChart (I:=I) e, + (is.map (simpleRoot ch'.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ periodBridge (L+1)) (phaseCycle n)) ∧ + ∀m,polynomialSectionIncoming Ω ch.roots ch.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ partialBridge L pre))) (h m)= + polynomialSectionIncoming Ω ch'.roots ch'.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ periodBridge (L+1)))) + (h (rest.foldl (rotate (triangularOmega n) cellLevel L) m)) := by + induction rest generalizing pre ch with + | nil => + have hpre:pre=phaseCycle n:=by simpa using hcycle.symm + subst pre + refine ⟨ch,?_,?_⟩ + · simpa only [List.nil_append,partialBridge_cycle] using hinv + · intro m + simp only [partialBridge_cycle,List.foldl_nil] + | cons b post ih => + have hb:=cycle_head_not_mem hcycle + have hbp:b∉pre:=fun hh=>hb (List.mem_append.mpr (Or.inr hh)) + have hp:h (eventRoot cellLevel L b)= (h ∘ partialBridge L pre) b - (h ∘ anchor) b.1.castSucc:=by + rw [eventRoot_partial L hcycle,map_sub] + rfl + have hd:∀j,Ω (h (eventRoot cellLevel L b)) ((h ∘ anchor) j)= + (if j=b.1.castSucc then 1 else 0)-(if j=b.1.succ then 1 else 0):=by + intro j + exact (hform _ _).trans (scheduledRoot_anchor L b j) + have hw:∀c,Ω (h (eventRoot cellLevel L b)) ((h ∘ partialBridge L pre) c)=if c=b then 1 else 0:=by + intro c + change Ω (h (eventRoot cellLevel L b)) (h (partialBridge L pre c))=_ + rw [hform,partialBridge_scheduled L hcycle] + exact scheduledRoot_bridge L b c + have hdd:Ω ((h ∘ anchor) b.1.castSucc) ((h ∘ anchor) b.1.succ)=0:=by + simp only [Function.comp_apply,hform,omega_anchors] + have hiv:(is.map (simpleRoot ch.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ partialBridge L pre) (b::(post++pre))):=by + simpa only [List.cons_append] using hinv + obtain ⟨pc,hpc,hpi,hF⟩:=freeChart_polynomial_step Ω hΩ e he S hS hcomp hnd ch is his hall + (h ∘ anchor) (h ∘ partialBridge L pre) b (post++pre) hb hiv + (h (eventRoot cellLevel L b)) hp hd hw hdd f + have hnew:Function.update (h ∘ partialBridge L pre) b + ((h ∘ anchor) b.1.succ+h (eventRoot cellLevel L b))=h ∘ partialBridge L (pre++[b]):=by + rw [partialBridge_step L pre b hbp,Function.comp_update,map_add] + rfl + rw [hnew] at hpi hF + have hc':phaseCycle n=(pre++[b])++post:=by rw [hcycle]; simp only [List.append_assoc,List.singleton_append] + have hi':(is.map (simpleRoot (ch.mutate Ω pc).roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ partialBridge L (pre++[b])) (post++(pre++[b]))):=by + simpa only [List.append_assoc] using hpi + obtain ⟨ch',hfin,heq⟩:=ih (pre++[b]) hc' (ch.mutate Ω pc) hi' + refine ⟨ch',hfin,?_⟩ + intro m + rw [hF,mutationIncomingLabel_map Ω h hform] + exact heq (rotate (triangularOmega n) cellLevel L m b) + +include hΩ he hS hcomp hnd hform in +lemma full_period_transport (is:List I) (his:is.Nodup) (hall:∀i,i∈is) + (L:ℕ) (ch:FreeChart (I:=I) e) + (hinv:(is.map (simpleRoot ch.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ periodBridge L) (phaseCycle n))) + {N:ℕ} (f:ElementaryExpr N) : + ∃ch':FreeChart (I:=I) e, + (is.map (simpleRoot ch'.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ periodBridge (L+1)) (phaseCycle n)) ∧ + ∀m,polynomialSectionIncoming Ω ch.roots ch.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ periodBridge L))) (h m)= + polynomialSectionIncoming Ω ch'.roots ch'.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ periodBridge (L+1)))) + (h (period (triangularOmega n) cellLevel (phaseCycle n) L m)) := by + have hi:(is.map (simpleRoot ch.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ partialBridge L []) (phaseCycle n++[])):=by + simpa only [partialBridge_nil,List.append_nil] using hinv + simpa only [partialBridge_nil,period] using partial_period_transport Ω hΩ e he S hS hcomp hnd h hform + is his hall L (phaseCycle n) [] rfl ch hi f +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits +open Classical +noncomputable section +variable {n:ℕ} {M E I:Type*} [AddCommGroup M] [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E] [Fintype I] [DecidableEq I] +variable (Ω:M →+ M →+ ℤ) (hΩ:∀m,Ω m m=0) +variable (e:M →+ E) (he:Function.Injective e) +variable (S:E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS:∀x,S x x=0) +variable (hcomp:∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (hnd:∀r≠0,∃m,Ω r m≠0) +variable (h:Lattice n (Cell n) →+ M) (hform:∀x y,Ω (h x) (h y)=triangularOmega n x y) +variable (retract:M →+ Lattice n (Cell n)) (hret:∀m,retract (h m)=m) + +omit [FiniteDimensional ℝ E] in +include hΩ hret in +lemma periodIncoming_cut [FiniteDimensional ℝ E] (is:List I) (hall:∀i,i∈is) + (L:ℕ) (ch:FreeChart (I:=I) e) + (hinv:(is.map (simpleRoot ch.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ periodBridge L) (phaseCycle n))) + {N:ℕ} (f:ElementaryExpr N) (m:Lattice n (Cell n)) + (hm:polynomialSectionIncoming Ω ch.roots ch.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ periodBridge L))) (h m)≠0) (i:Fin n) : + periodFunctional cellLevel i L m≤(N:ℤ) := by + let ell:M →+ ℤ:=(periodFunctional cellLevel i L).comp retract + have hell (x:Lattice n (Cell n)):ell (h x)=periodFunctional cellLevel i L x:=by + change periodFunctional cellLevel i L (retract (h x))=_ + rw [hret] + have hc:∀j,ell (simpleRoot ch.roots j)≤0:=by + intro j + have H:=hinv.mem_iff.mp (List.mem_map.mpr ⟨j,hall j,rfl⟩) + rw [forwardInventory_map] at H + obtain ⟨r,hr,heq⟩:=List.mem_map.mp H + rw [←heq,hell] + exact periodInventory_cut_nonpos i L (phaseCycle n) r hr + have hv:∀x,ell (vertexDisplay (h ∘ anchor) (h ∘ periodBridge L) x)≤1:=by + intro x + cases x with + | inl a => + change ell (h (anchor a))≤1 + rw [hell,periodFunctional_anchor] + split_ifs <;> omega + | inr b => + change ell (h (periodBridge L b))≤1 + rw [hell,periodFunctional_bridge] + split_ifs <;> omega + have hf:=f.cutSupported LaurentRay.vUnit Ω ell (vertexDisplay (h ∘ anchor) (h ∘ periodBridge L)) hv + have H:=polynomialIncoming_cut_bound Ω hΩ ch.roots ch.coord _ ell N hc hf (h m) hm + rwa [hell] at H + +include hΩ he hS hcomp hnd hform in +lemma complete_history_transport (is:List I) (his:is.Nodup) (hall:∀i,i∈is) + (ch:FreeChart (I:=I) e) + (hinv:(is.map (simpleRoot ch.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ periodBridge 0) (phaseCycle n))) + {N:ℕ} (f:ElementaryExpr N) (m:Lattice n (Cell n)) (L:ℕ) : + ∃ch':FreeChart (I:=I) e, + (is.map (simpleRoot ch'.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ periodBridge L) (phaseCycle n)) ∧ + polynomialSectionIncoming Ω ch.roots ch.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ periodBridge 0))) (h m)= + polynomialSectionIncoming Ω ch'.roots ch'.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ periodBridge L))) + (h (history (triangularOmega n) cellLevel (phaseCycle n) m L)) := by + induction L with + | zero => exact ⟨ch,hinv,rfl⟩ + | succ L ih => + obtain ⟨ch',hi,heq⟩:=ih + obtain ⟨ch'',hi',heq'⟩:=full_period_transport Ω hΩ e he S hS hcomp hnd h hform is his hall L ch' hi f + exact ⟨ch'',hi',heq.trans (heq' _)⟩ + +include hΩ he hS hcomp hnd hform hret in +lemma genuine_history_cut_deficit (is:List I) (his:is.Nodup) (hall:∀i,i∈is) + (ch:FreeChart (I:=I) e) + (hinv:(is.map (simpleRoot ch.roots)).Perm + (forwardInventory (h ∘ anchor) (h ∘ periodBridge 0) (phaseCycle n))) + {N:ℕ} (f:ElementaryExpr N) (m:Lattice n (Cell n)) + (hm:polynomialSectionIncoming Ω ch.roots ch.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ periodBridge 0))) (h m)≠0) + (L:ℕ) (i:Fin n) : + 0≤cutDeficit cellLevel i N L (history (triangularOmega n) cellLevel (phaseCycle n) m L) := by + obtain ⟨ch',hi,heq⟩:=complete_history_transport Ω hΩ e he S hS hcomp hnd h hform is his hall ch hinv f m L + have hm':polynomialSectionIncoming Ω ch'.roots ch'.coord + (f.eval LaurentRay.vUnit Ω (vertexDisplay (h ∘ anchor) (h ∘ periodBridge L))) + (h (history (triangularOmega n) cellLevel (phaseCycle n) m L))≠0:=by rwa [←heq] + have H:=periodIncoming_cut Ω hΩ e h retract hret is hall L ch' hi f _ hm' i + unfold cutDeficit + omega +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPolynomialStationarity.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPolynomialStationarity.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c4091c5ceef95f0500ea568fff9dc2faae74289 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPolynomialStationarity.lean @@ -0,0 +1,159 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularPeriodTransport + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization +open Classical +noncomputable section +variable {n:ℕ} + +def triangularExpression {N:ℕ} (f:ElementaryExpr N) : Torus LaurentRay.vUnit (extendedOmega n) := + f.eval LaurentRay.vUnit (extendedOmega n) (vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ bridge)) + +def triangularIncoming {N:ℕ} (f:ElementaryExpr N) (m:Lattice n (Cell n)) : LaurentSeries ℚ := + polynomialSectionIncoming (extendedOmega n) (extendedRoots n) (extendedCoord n) + (triangularExpression f) (includeVertices m) + +lemma cellLevel_surjective : Function.Surjective (@cellLevel n) := by + intro i + exact ⟨⟨i,⟨0,by omega⟩⟩,rfl⟩ + +lemma triangularExpression_stationary {N:ℕ} (f:ElementaryExpr N) (m:Lattice n (Cell n)) + (hm:triangularIncoming f m≠0) : + (∀i,levelTotal cellLevel i m=0) ∧ + (∀b,0≤triangularOmega n (eventRoot cellLevel 0 b) m) ∧ + (∀L,history (triangularOmega n) cellLevel (phaseCycle n) m L=m) := by + apply chart_tropical_stationary cellLevel cellLevel_surjective triangularBB triangularBB_skew + (phaseCycle n) (mem_phaseCycle (n:=n)) m N + intro L i + have hzero : periodBridge (n:=n) 0 = bridge := by + funext c + simp [periodBridge] + have hinv : ((gapIndices n).map (simpleRoot (initialFreeChart n).roots)).Perm + (forwardInventory (includeVertices ∘ anchor) (includeVertices ∘ periodBridge 0) (phaseCycle n)) := by + simpa only [hzero] using initialFreeChart_inventory (n:=n) + have hm' : polynomialSectionIncoming (extendedOmega n) (initialFreeChart n).roots (initialFreeChart n).coord + (f.eval LaurentRay.vUnit (extendedOmega n) + (vertexDisplay (includeVertices ∘ anchor) (includeVertices ∘ periodBridge 0))) + (includeVertices m)≠0 := by + simpa only [triangularIncoming,triangularExpression,initialFreeChart,hzero] using hm + exact genuine_history_cut_deficit (extendedOmega n) extendedOmega_self extendedCast extendedCast_injective + (triangularRealForm n) triangularRealForm_self triangularRealForm_compatible extendedOmega_nondegenerate + includeVertices extendedOmega_original (AddMonoidHom.fst _ _) (fun _=>rfl) + (gapIndices n) (gapIndices_nodup (n:=n)) (mem_gapIndices (n:=n)) (initialFreeChart n) hinv f m hm' L i +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators +open QuantumTorus +open Classical +noncomputable section +variable {n:ℕ} {R:Type*} [CommRing R] + +lemma forwardRoots_single (g:GapIndex n) (r:R) : + forwardRoots (Pi.single g r)=r • forwardGap g := by + rw [forwardRoots_apply,Finset.sum_eq_single g] + · simp + · intro h _ hh + simp [Ne.symm hh] + · simp + +lemma forwardRoots_coord_gap (g:GapIndex n) : + forwardRoots (forwardCoord (forwardGap (R:=R) g))=forwardGap g := by + rw [forwardCoord_gap,forwardRoots_single,one_smul] + +lemma forwardRoots_coord_level (i:Fin n) + (h:forwardRoots (forwardCoord (Pi.single (.inl i.castSucc) (1:R)))= + Pi.single (.inl i.castSucc) 1-Pi.single (.inl (0:Fin (n+1))) 1) + (j:Fin (i.val+3)) : + forwardRoots (forwardCoord (Pi.single (levelNode i j) (1:R)))= + Pi.single (levelNode i j) 1-Pi.single (.inl (0:Fin (n+1))) 1 := by + induction j using Fin.induction with + | zero => simpa only [levelNode_zero] using h + | succ j ih => + have H:=forwardRoots_coord_gap (R:=R) (⟨i,j⟩:GapIndex n) + simp only [forwardGap,map_sub] at H + rw [ih] at H + exact sub_eq_iff_eq_add.mp H |>.trans (by abel) + +lemma forwardRoots_coord_anchor (a:Fin (n+1)) : + forwardRoots (forwardCoord (Pi.single (.inl a) (1:R)))= + Pi.single (.inl a) 1-Pi.single (.inl (0:Fin (n+1))) 1 := by + induction a using Fin.induction with + | zero => + have hz:forwardCoord (Pi.single (.inl (0:Fin (n+1))) (1:R))=0 := by + ext g + simp [forwardCoord_single,afterGap] + rw [hz,map_zero,sub_self] + | succ i ih => + simpa only [levelNode_last] using forwardRoots_coord_level i ih (Fin.last (i.val+2)) + +lemma forwardRoots_coord_vertex (a:Vertex n (Cell n)) : + forwardRoots (forwardCoord (Pi.single a (1:R)))=Pi.single a 1-Pi.single (.inl (0:Fin (n+1))) 1 := by + cases a with + | inl a => exact forwardRoots_coord_anchor a + | inr b => + let j:Fin (b.1.val+3):=⟨b.1.val+1-b.2.val,by have := b.2.isLt; omega⟩ + have hj:levelNode b.1 j=.inr b:=by + have haq:=b.2.isLt + simp only [levelNode,j] + rw [dite_eq_right (by omega),dite_eq_right (by omega)] + congr 1 + apply cell_ext + · rfl + change b.1.val+1-(b.1.val+1-b.2.val)=b.2.val + omega + simpa only [hj] using forwardRoots_coord_level b.1 (forwardRoots_coord_anchor b.1.castSucc) j + +def vertexWeight : (Vertex n (Cell n) → R) →ₗ[R] R := ∑a,LinearMap.proj a +lemma vertexWeight_apply (m:Vertex n (Cell n) → R) : vertexWeight m=∑a,m a := by + simp [vertexWeight,LinearMap.sum_apply] + +lemma forwardRoots_coord (m:Vertex n (Cell n) → R) : + forwardRoots (forwardCoord m)=m-vertexWeight m • Pi.single (.inl (0:Fin (n+1))) 1 := by + have hm:m=∑a,m a • Pi.single a (1:R) := by + ext a + simp only [Finset.sum_apply,Pi.smul_apply,Pi.single_apply,smul_eq_mul] + rw [Finset.sum_eq_single a] + · simp + · intro b _ hb; simp [Ne.symm hb] + · simp + calc + _ = ∑a,m a • forwardRoots (forwardCoord (Pi.single a (1:R))) := by + conv_lhs => rw [hm] + simp only [map_sum,map_smul] + _ = ∑a,m a • (Pi.single a (1:R)-Pi.single (.inl (0:Fin (n+1))) 1) := by + simp_rw [forwardRoots_coord_vertex] + _ = (∑a,m a • Pi.single a (1:R))-(∑a,m a • Pi.single (.inl (0:Fin (n+1))) 1) := by + simp only [smul_sub,Finset.sum_sub_distrib] + _ = _ := by rw [←hm,←Finset.sum_smul,vertexWeight_apply] + +lemma forwardCoord_nonneg (m:Lattice n (Cell n)) (hm:∀a,0 ≤ m a) (g:GapIndex n) : + 0 ≤ forwardCoord m g := by + rw [forwardCoord_apply] + apply Finset.sum_nonneg + intro a _ + split_ifs <;> first | exact hm a | omega + +lemma triangularVertex_rootDegree (m:Lattice n (Cell n)) (hm:∀a,0 ≤ m a) : + ∃k,HasRootDegree (forwardRoots (R:=ℤ) (n:=n)).toAddMonoidHom k (m-vertexWeight m • anchor 0) := by + let c:GapIndex n → ℕ:=fun g=>(forwardCoord m g).toNat + have hc:(fun g=>(c g:ℤ))=forwardCoord m := by + ext g + exact Int.toNat_of_nonneg (forwardCoord_nonneg m hm g) + refine ⟨∑g,c g,c,rfl,?_⟩ + change forwardRoots (fun g=>(c g:ℤ))=m-vertexWeight m • anchor 0 + rw [hc,forwardRoots_coord] + rfl +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPositivePowers.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPositivePowers.lean new file mode 100644 index 0000000000000000000000000000000000000000..be604baf0872d25388d328d8c562e63778d6a7e3 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularPositivePowers.lean @@ -0,0 +1,214 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.TriangularCommutativity + +namespace OAI + +section +namespace ElementaryPositivity.PowerSeriesAdjoint +open PowerSeries +noncomputable section +variable {A:Type*} [Ring A] +lemma adjoint_product (F X Y:PowerSeries A) (hF:constantCoeff F=1) : + adjoint F (X*Y)=adjoint F X*adjoint F Y := by + unfold adjoint + calc + _ = F*X*(invOfUnit F 1*F)*Y*invOfUnit F 1 := by rw [invOfUnit_mul F 1 hF]; simp only [mul_one,mul_assoc] + _ = _ := by simp only [mul_assoc] +end +end ElementaryPositivity.PowerSeriesAdjoint + +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization PowerSeries PowerSeriesAdjoint LaurentPositive +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} +local instance triangularPositivePowersRing : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance triangularPositivePowersAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommMonoid +local instance triangularPositivePowersAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup +local instance triangularPositivePowersAddGroup : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup + +def linearPower : (N:ℕ) → ElementaryExpr N + | 0 => .one + | N+1 => .mul (linearPower N) (.atom 1) + +lemma linearPower_eval (N:ℕ) : + triangularExpression (n:=n) (linearPower N)=(triangularExpression (.atom 1))^N := by + induction N with + | zero=>rfl + | succ N ih=>change triangularExpression (linearPower N)*triangularExpression (.atom 1)=_; rw [ih,pow_succ] + +lemma homogenize_one_triangular : + homogenize LaurentRay.vUnit (extendedOmega n) (rootOrder (extendedCoord n)) 1=1 := by + change homogenize _ _ _ (Torus.monomial LaurentRay.vUnit (extendedOmega n) 0 1)=_ + rw [homogenize_monomial,map_zero,Int.toNat_zero,monomial_zero_eq_C_apply] + exact map_one PowerSeries.C + +lemma triangularLinear_positive (h:Module.Dual ℝ ((Vertex n (Cell n) → ℝ) × (Vertex n (Cell n) → ℝ))) : + IntegralPositive (extendedOmega n) + (adjoint (rootSectionChart (extendedOmega n) (extendedRoots n) (h.toAddMonoidHom.comp extendedCast)).val + (homogenize LaurentRay.vUnit (extendedOmega n) (rootOrder (extendedCoord n)) (triangularExpression (.atom 1)))) := by + obtain ⟨L,hL⟩:=real_covector_prescribe (extendedRoots n) extendedCast extendedRoots_realIndependent (fun _=>1) + rw [triangularLinear_theta] + exact thetaValue_positive (extendedOmega n) (extendedRoots n) extendedCast extendedCast_injective + (triangularRealForm n) triangularRealForm_self triangularRealForm_compatible L + (fun _ _ hm=>covector_root_eval (extendedRoots n) extendedCast L hL hm) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) + (simpleTotalTransport_positive_prescription _ _ extendedOmega_self) _ h + +lemma triangularPower_positive (N:ℕ) + (h:Module.Dual ℝ ((Vertex n (Cell n) → ℝ) × (Vertex n (Cell n) → ℝ))) : + IntegralPositive (extendedOmega n) + (adjoint (rootSectionChart (extendedOmega n) (extendedRoots n) (h.toAddMonoidHom.comp extendedCast)).val + (homogenize LaurentRay.vUnit (extendedOmega n) (rootOrder (extendedCoord n)) (triangularExpression (linearPower N)))) := by + induction N with + | zero=> + change IntegralPositive _ (adjoint _ (homogenize _ _ _ 1)) + rw [homogenize_one_triangular] + have H:adjoint (rootSectionChart (extendedOmega n) (extendedRoots n) (h.toAddMonoidHom.comp extendedCast)).val 1=1:=by + simp only [adjoint,mul_one] + exact mul_invOfUnit _ 1 (rootSectionChart _ _ _).property.1 + rw [H] + simpa only [Torus.X_zero,map_one] using completedPositive_C_X (extendedOmega n) 0 + | succ N ih=> + change IntegralPositive _ (adjoint _ (homogenize _ _ _ + (triangularExpression (linearPower N)*triangularExpression (.atom 1)))) + rw [homogenize_mul _ _ _ _ _ (triangularSeed_order_nonnegative _) (triangularSeed_order_nonnegative _), + adjoint_product _ _ _ (rootSectionChart _ _ _).property.1] + exact ih.mul _ (triangularLinear_positive h) + +lemma triangularPower_incoming_positive (N k:ℕ) : + TorusPositive (extendedOmega n) + (sectionIncoming LaurentRay.vUnit (extendedOmega n) (extendedRoots n) + (simpleTotalTransport (extendedOmega n) (extendedRoots n)) + (includeVertices ((N:ℤ) • anchor 0)) k + (polynomialInitial (extendedOmega n) (extendedRoots n) (extendedCoord n) + (triangularExpression (linearPower N)))) := by + intro m + rw [sectionIncoming_apply] + split_ifs + · have hcov:(((triangularRealForm n).flip (extendedCast m)).toAddMonoidHom.comp extendedCast) = incomingCovector (extendedOmega n) m := by + ext a + exact triangularRealForm_compatible a m + have H:=triangularPower_positive (n:=n) N ((triangularRealForm n).flip (extendedCast m)) k m + rw [hcov,rootSectionChart_action] at H + exact H + · exact positive_zero +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension PowerSeries PowerSeriesAdjoint LaurentPositive +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} +local instance triangularOrdinaryPowersRing : Ring (Torus LaurentRay.vUnit (extendedOmega n)) := Torus.instRing LaurentRay.vUnit (extendedOmega n) +local instance triangularOrdinaryPowersAddCommMonoid : AddCommMonoid (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommMonoid +local instance triangularOrdinaryPowersAddCommGroup : AddCommGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddCommGroup +local instance triangularOrdinaryPowersAddGroup : AddGroup (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toAddGroup +local instance triangularOrdinaryPowersSub : Sub (Torus LaurentRay.vUnit (extendedOmega n)) := (Torus.instRing LaurentRay.vUnit (extendedOmega n)).toSub + +lemma triangularLinear_ordinary_positive : TorusPositive (extendedOmega n) (triangularExpression (.atom 1)) := by + rw [triangularLinear_sum] + exact TorusPositive.sum _ _ _ (fun a _=>torusPositive_monomial _ _ _ positive_one) + +lemma triangularLinear_retain (a:Fin (n+1)) : + TorusPositive (extendedOmega n) + (triangularExpression (.atom 1)-Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (anchor a))) := by + have H:(∑b∈(Finset.univ:Finset (Vertex n (Cell n))).erase (.inl a), + Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (Pi.single b (1:ℤ))))= + triangularExpression (.atom 1)-Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (anchor a)) := by + apply Finsupp.ext + intro m + rw [torus_sub_apply,triangularLinear_sum] + simp only [Finsupp.finsetSum_apply] + have H:=Finset.sum_erase_add + (s:=(Finset.univ:Finset (Vertex n (Cell n)))) + (fun b=>(Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (Pi.single b (1:ℤ)))) m) + (Finset.mem_univ (.inl a)) + change _ = _ - (Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (Pi.single (.inl a) (1:ℤ)))) m + rw [←H,add_sub_cancel_right] + let ev:Torus LaurentRay.vUnit (extendedOmega n) →+ LaurentSeries ℚ := + {toFun:=fun f=>f m,map_zero':=rfl,map_add':=fun _ _=>rfl} + exact map_sum ev _ _ + rw [←H] + exact TorusPositive.sum _ _ _ (fun b _=>torusPositive_monomial _ _ _ positive_one) + +def natAnchor (μ:Fin (n+1) → ℕ) : Lattice n (Cell n) := pureAnchor (fun a=>(μ a:ℤ)) +lemma natAnchor_zero : natAnchor (n:=n) 0=0 := by + ext a + cases a <;> simp [natAnchor,pureAnchor_apply_anchor,pureAnchor_apply_bridge] + +lemma natAnchor_step (μ:Fin (n+1) → ℕ) (a:Fin (n+1)) (ha:0<μ a) : + natAnchor μ=natAnchor (Function.update μ a (μ a-1))+anchor a := by + ext b + cases b with + | inl b=> + simp only [natAnchor,pureAnchor_apply_anchor,Pi.add_apply,anchor,Pi.single_apply,Sum.inl.injEq] + by_cases hb:b=a + · subst b; simp only [Function.update_self,ite_true]; omega + · rw [Function.update_of_ne hb,ite_eq_right hb] + simp + | inr b=>simp [natAnchor,pureAnchor_apply_bridge,anchor] + +lemma natural_sum_step (μ:Fin (n+1) → ℕ) (a:Fin (n+1)) (ha:0<μ a) : + (∑b,Function.update μ a (μ a-1) b)+1=∑b,μ b := by + symm + calc + _ = ∑b,(Function.update μ a (μ a-1) b+(if b=a then 1 else 0)) := by + apply Finset.sum_congr rfl + intro b _ + by_cases hb:b=a + · subst b; simp only [Function.update_self,ite_true]; omega + · rw [Function.update_of_ne hb,ite_eq_right hb]; omega + _ = _ := by rw [Finset.sum_add_distrib]; simp + +lemma triangularPower_ordinary_retain (N:ℕ) (μ:Fin (n+1) → ℕ) (hμ:∑a,μ a=N) : + TorusPositive (extendedOmega n) + (triangularExpression (linearPower N)-Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (natAnchor μ))) := by + induction N generalizing μ with + | zero=> + have hz:μ=0:=by + ext a + have H:μ a ≤ ∑b,μ b:=Finset.single_le_sum (fun _ _=>Nat.zero_le _) (Finset.mem_univ a) + have H':μ a=0:=by omega + exact H' + subst μ + rw [natAnchor_zero,map_zero,Torus.X_zero,linearPower_eval,pow_zero,sub_self] + exact torusPositive_zero _ + | succ N ih=> + obtain ⟨a,_,ha⟩:=Finset.exists_ne_zero_of_sum_ne_zero (show (∑a,μ a)≠0 by omega) + have ha':0<μ a:=Nat.pos_of_ne_zero ha + let ν:=Function.update μ a (μ a-1) + have hν:∑b,ν b=N:=by + change (∑b,Function.update μ a (μ a-1) b)=N + have :=natural_sum_step μ a ha' + omega + have hp:(triangularExpression (linearPower N)-Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (natAnchor ν)))* + triangularExpression (.atom 1)+Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (natAnchor ν))* + (triangularExpression (.atom 1)-Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (anchor a)))= + triangularExpression (linearPower (N+1))-Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (natAnchor μ)):=by + have hpair:extendedOmega n (includeVertices (natAnchor ν)) (includeVertices (anchor a))=0:=by + rw [extendedOmega_original,triangularOmega_skew,natAnchor,anchor_pair_pure,neg_zero] + have hm:Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (natAnchor ν))* + Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (anchor a))= + Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (natAnchor μ)):=by + rw [Torus.X_mul_X_of_pairing_zero _ _ _ _ hpair,←map_add,←natAnchor_step μ a ha'] + change (_-_)*_+_*(_-_)=triangularExpression (linearPower N)*triangularExpression (.atom 1)-_ + calc + _ = triangularExpression (linearPower N)*triangularExpression (.atom 1)- + Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (natAnchor ν))* + Torus.X LaurentRay.vUnit (extendedOmega n) (includeVertices (anchor a)) := by noncomm_ring + _ = _ := by rw [hm] + rw [←hp] + exact ((ih ν hν).mul _ triangularLinear_ordinary_positive).add _ + ((torusPositive_monomial _ _ _ positive_one).mul _ (triangularLinear_retain a)) +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TriangularScheduledRoots.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularScheduledRoots.lean new file mode 100644 index 0000000000000000000000000000000000000000..c9353895b3ced72dbf6158dcdfa7b9545c3fe4f2 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TriangularScheduledRoots.lean @@ -0,0 +1,178 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.FiniteLatticePairing + +namespace OAI + +section +namespace ElementaryPositivity.TriangularDynamics +open scoped BigOperators + +variable {n : ℕ} + +lemma triangularOmega_skew (m m' : Lattice n (Cell n)) : + triangularOmega n m m' = -triangularOmega n m' m := + matrixPairing_skew _ (chartMatrix_skew cellLevel triangularBB triangularBB_skew) _ _ + +@[simp] lemma omega_anchors (i j : Fin (n+1)) : + triangularOmega n (anchor i) (anchor j)=0 := by + change matrixPairing (chartMatrix (@cellLevel n) (@triangularBB n)) + (Pi.single (.inl i) 1) (Pi.single (.inl j) 1)=0 + exact matrixPairing_single (chartMatrix cellLevel triangularBB) (.inl i) (.inl j) + +@[simp] lemma omega_delta_anchor (b : Cell n) (i : Fin (n+1)) : + triangularOmega n (delta cellLevel b) (anchor i)=0 := by + simp only [delta,map_sub,AddMonoidHom.sub_apply,omega_anchors,sub_self] + +@[simp] lemma omega_anchor_delta (i : Fin (n+1)) (b : Cell n) : + triangularOmega n (anchor i) (delta cellLevel b)=0 := by + simp only [delta,map_sub,omega_anchors,sub_self] + +@[simp] lemma omega_delta_delta (b c : Cell n) : + triangularOmega n (delta cellLevel b) (delta cellLevel c)=0 := by + simp only [delta,map_sub,AddMonoidHom.sub_apply,omega_anchors,sub_self] + +def levelCartan (i j : Fin n) : ℤ := + if i=j then 2 else if i.val+1=j.val ∨ j.val+1=i.val then -1 else 0 + +lemma levelCartan_comm (i j : Fin n) : levelCartan i j=levelCartan j i := by + simp only [levelCartan,eq_comm,or_comm] + +lemma omega_delta_bridge (b c : Cell n) : + triangularOmega n (delta cellLevel b) (bridge c)=levelCartan b.1 c.1 := by + simp only [delta,map_sub,AddMonoidHom.sub_apply] + change matrixPairing _ (anchor b.1.succ) (bridge c)- + matrixPairing _ (anchor b.1.castSucc) (bridge c)=_ + simp only [anchor,bridge,matrixPairing_single,chartMatrix] + dsimp only [cellLevel] + simp only [Fin.ext_iff,Fin.val_succ,Fin.val_castSucc,levelCartan] + split_ifs <;> omega + +lemma omega_event_delta (b c : Cell n) : + triangularOmega n (eventRoot cellLevel 0 b) (delta cellLevel c)= -levelCartan b.1 c.1 := by + rw [triangularOmega_skew] + simp only [eventRoot,Nat.cast_zero,zero_smul,add_zero,map_sub,omega_delta_anchor, + sub_zero,omega_delta_bridge,levelCartan_comm c.1 b.1] + +def scheduledBridge (L : ℕ) (b c : Cell n) : Lattice n (Cell n) := + bridge c + ((L:ℤ)+(if phaseEarlier c b then 1 else 0)) • delta cellLevel c + +@[simp] lemma scheduledBridge_self (L : ℕ) (b : Cell n) : + scheduledBridge L b b=bridge b+(L:ℤ) • delta cellLevel b := by + simp [scheduledBridge] + +lemma scheduledRoot_anchor (L : ℕ) (b : Cell n) (a : Fin (n+1)) : + triangularOmega n (eventRoot cellLevel L b) (anchor a)= + (if a=b.1.castSucc then 1 else 0)-(if a=b.1.succ then 1 else 0) := by + have he : eventRoot cellLevel L b=eventRoot cellLevel 0 b+(L:ℤ) • delta cellLevel b := by + simp [eventRoot] + rw [he,map_add,AddMonoidHom.add_apply,map_zsmul,AddMonoidHom.zsmul_apply, + omega_delta_anchor,smul_zero,add_zero,eventRoot_anchor] + +lemma scheduledRoot_bridge (L : ℕ) (b c : Cell n) : + triangularOmega n (eventRoot cellLevel L b) (scheduledBridge L b c)=if c=b then 1 else 0 := by + have he : eventRoot cellLevel L b=eventRoot cellLevel 0 b+(L:ℤ) • delta cellLevel b := by + simp [eventRoot] + rw [he,scheduledBridge] + simp only [map_add,map_zsmul,AddMonoidHom.add_apply,AddMonoidHom.zsmul_apply, + omega_delta_delta,omega_delta_bridge,omega_event_delta, + eventRoot_bridge_value,smul_eq_mul] + by_cases heq : c=b + · subst c + simp [levelCartan] + · by_cases hl : c.1=b.1 + · have hl' := hl.symm + by_cases hh : phaseEarlier c b + · simp only [levelCartan,ite_eq_left hl,ite_eq_left hl',ite_eq_right heq] + simp only [hh,ite_true] + ring + · simp only [levelCartan,ite_eq_left hl,ite_eq_left hl',ite_eq_right heq] + simp only [hh,ite_false] + ring + · have hl' : b.1≠c.1 := Ne.symm hl + by_cases ha : c.1.val+1=b.1.val ∨ b.1.val+1=c.1.val + · have ha' : b.1.val+1=c.1.val ∨ c.1.val+1=b.1.val := ha.symm + by_cases hh : phaseEarlier c b + · simp only [levelCartan,ite_eq_right hl,ite_eq_right hl',ite_eq_right heq,ha,ha',hh,ite_true] + ring + · simp only [levelCartan,ite_eq_right hl,ite_eq_right hl',ite_eq_right heq,ha,ha',hh,ite_true,ite_false] + ring + · have ha' : ¬(b.1.val+1=c.1.val ∨ c.1.val+1=b.1.val) := by tauto + simp only [levelCartan,ite_eq_right hl,ite_eq_right hl',ite_eq_right heq,ha,ha',ite_false] + ring + +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.PathLattice +open scoped BigOperators +variable {R : Type*} [CommRing R] {d : ℕ} + +def gap (i : Fin d) : Fin (d+1) → R := Pi.single i.succ 1 - Pi.single i.castSucc 1 + +def roots : (Fin d → R) →ₗ[R] (Fin (d+1) → R) := + ∑ i, (LinearMap.proj i).smulRight (gap i) + +lemma roots_apply (c : Fin d → R) : roots c = ∑ i, c i • gap i := by + simp [roots,LinearMap.sum_apply,LinearMap.smulRight_apply] + +def coord : (Fin (d+1) → R) →ₗ[R] (Fin d → R) := + LinearMap.pi fun i => ∑ j : Fin (d+1), if i.val < j.val then LinearMap.proj j else 0 + +lemma coord_apply (m : Fin (d+1) → R) (i : Fin d) : + coord m i = ∑ j : Fin (d+1), if i.val < j.val then m j else 0 := by + simp only [coord,LinearMap.pi_apply,LinearMap.sum_apply] + apply Finset.sum_congr rfl + intro j _ + split_ifs <;> rfl + +lemma coord_single (a : Fin (d+1)) (r : R) (i : Fin d) : + coord (Pi.single a r) i = if i.val < a.val then r else 0 := by + rw [coord_apply,Finset.sum_eq_single a] + · simp + · intro b _ hb + simp [Ne.symm hb] + · simp + +lemma coord_gap (i : Fin d) : coord (gap (R:=R) i) = Pi.single i 1 := by + ext j + rw [gap,map_sub,Pi.sub_apply,coord_single,coord_single] + simp only [Pi.single_apply,Fin.val_succ,Fin.val_castSucc] + split_ifs with h h' he he <;> simp_all only [sub_self,sub_zero,zero_sub,Fin.ext_iff] <;> omega + +@[simp] lemma coord_roots (c : Fin d → R) : coord (roots c) = c := by + rw [roots_apply,map_sum] + simp only [map_smul,coord_gap] + ext j + simp only [Finset.sum_apply,Pi.smul_apply,Pi.single_apply,smul_eq_mul] + rw [Finset.sum_eq_single j] + · simp + · intro i _ hi + simp [Ne.symm hi] + · simp + +lemma roots_injective : Function.Injective (roots (R:=R) (d:=d)) := by + intro x y h + have := congrArg coord h + simpa only [coord_roots] using this + +lemma gaps_linearIndependent : LinearIndependent R (gap (R:=R) (d:=d)) := by + have H := Pi.linearIndependent_single_one (Fin d) R + have HH : LinearIndependent R (fun i : Fin d => coord (gap (R:=R) i)) := by + simpa only [coord_gap] using H + exact HH.of_comp coord + +def weight : (Fin (d+1) → R) →ₗ[R] R := ∑ j, LinearMap.proj j +lemma weight_apply (m : Fin (d+1) → R) : weight m = ∑ j, m j := by simp [weight] +lemma weight_single (a : Fin (d+1)) (r : R) : weight (Pi.single a r)=r := by + simp [weight_apply,Pi.single_apply] +@[simp] lemma weight_gap (i : Fin d) : weight (gap (R:=R) i)=0 := by + rw [gap,map_sub,weight_single,weight_single,sub_self] +@[simp] lemma weight_roots (c : Fin d → R) : weight (roots c)=0 := by + simp only [roots_apply,map_sum,map_smul,weight_gap,smul_zero,Finset.sum_const_zero] + +end ElementaryPositivity.PathLattice + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TripleSymbols.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TripleSymbols.lean new file mode 100644 index 0000000000000000000000000000000000000000..b295790f5a5be9444c6362320d9fe9a655729059 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TripleSymbols.lean @@ -0,0 +1,170 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.NormalizedTensorSymbol +import OAI.Combinatorics.Chromatic.Shuffle.TripleFiltration + +namespace OAI + +section +namespace ElementaryPositivity.RawShuffle.SplitTree +open MvPolynomial ElementaryPositivity.CenterCalculus +open ElementaryPositivity.ShufflePolynomiality +open scoped TensorProduct +variable {I : Type*} [Fintype I] [DecidableEq I] + +lemma refinedCenterPolynomial_coeff_degreeCut (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + obtain ⟨U,V,x,y,hUV,hx,hy,rfl⟩:=hx + rw [refinedCenterPolynomial_tmul,←Finsupp.comapDomain_sumElim_comapDomain z,coeff_box] + rintro ⟨k,l⟩ hkl + change componentTensor a (SlopeArithmetic.slope c η) L k _⊗ₜ[ℚ] + componentTensor a (SlopeArithmetic.slope c η) R l _=0 + change 2*(L.totalDegree k+R.totalDegree l)+(L.doubleShift a+R.doubleShift a) + simp only [refinedCenterPolynomial,map_zero,AddMonoidAlgebra.coeff_zero,Finsupp.zero_apply] + exact (degreeCutSubmodule a (SlopeArithmetic.slope c η) (.node L R) W).zero_mem + | add x y hx hy ihx ihy => + simp only [refinedCenterPolynomial,map_add,AddMonoidAlgebra.coeff_add,Finsupp.add_apply] at ihx ihy ⊢ + exact (degreeCutSubmodule a (SlopeArithmetic.slope c η) (.node L R) W).add_mem ihx ihy + | smul r x hx ih => + simp only [refinedCenterPolynomial,map_smul,coeff_smul] at ih ⊢ + exact (degreeCutSubmodule a (SlopeArithmetic.slope c η) (.node L R) W).smul_mem r ih + +noncomputable def refinedTripleCenterPolynomial (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + rw [refinedTripleCenterPolynomial_tmul,coeff_box,TensorProduct.map_tmul] + change componentTensor a (SlopeArithmetic.slope c η) (.node L M) (k,l) _⊗ₜ[ℚ] + componentTensor a (SlopeArithmetic.slope c η) N m _=_ + rw [refinedCenterPolynomial_coeff_test] + rfl + | add x y hx hy => + rw [(refinedTripleCenterPolynomial a c η hc θ L M N hL hM hN).map_add, + AddMonoidAlgebra.coeff_add,Finsupp.add_apply] + simp only [LinearMap.map_add,hx,hy] + +noncomputable def tripleInternalDenominator (a : I → I → ℕ) (L M N : SplitTree I) : + MvPolynomial ((L.node M).node N).Centers ℚ := + rename Sum.inl (internalDenominator a L M)*rename Sum.inr (centerDenominator a N N.centerPairs) + +noncomputable def tripleInternalNumerator (a : I → I → ℕ) (L M N : SplitTree I) : + MvPolynomial ((L.node M).node N).Centers ℚ := + rename Sum.inl (internalNumerator a L M)*rename Sum.inr (centerNumerator a N N.centerPairs) + +omit [DecidableEq I] in +lemma tripleInternalDenominator_ne_zero (a : I → I → ℕ) (L M N : SplitTree I) : + tripleInternalDenominator a L M N≠0 := by + apply mul_ne_zero + · exact fun h=>internalDenominator_ne_zero a L M ((rename_eq_zero_iff_of_injective _ Sum.inl_injective).mp h) + · exact fun h=>centerDenominator_ne_zero a N ((rename_eq_zero_iff_of_injective _ Sum.inr_injective).mp h) + +omit [DecidableEq I] in +lemma tripleInternalNumerator_ne_zero (a : I → I → ℕ) (L M N : SplitTree I) : + tripleInternalNumerator a L M N≠0 := by + apply mul_ne_zero + · exact fun h=>internalNumerator_ne_zero a L M ((rename_eq_zero_iff_of_injective _ Sum.inl_injective).mp h) + · exact fun h=>centerNumerator_ne_zero a N ((rename_eq_zero_iff_of_injective _ Sum.inr_injective).mp h) + +lemma refinedTripleLeadingPolynomial_tmul (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0 + obtain ⟨U,V,x,y,hw,hx,hy,rfl⟩:=hz + have hy' := sourceFiltration_antitone a c η hc θ N.dim (show W-U≤V by omega) hy + have he : W=U+(W-U) := by omega + rw [he,refinedTripleLeadingPolynomial_tmul a c η hc θ L M N hL hM hN U (W-U) x y hx hy'] + obtain ⟨p,hp⟩:=refinedLeadingPolynomial_denominator_divisible a c η hc θ L M hL hM hχL hχM U x hx + obtain ⟨q,hq⟩:=totalLeadingPolynomial_denominator_divisible a c η hc θ N hN (W-U) y hy' + N.centerPairs N.centerPairs_ne N.centerPairs_norev hχN + refine ⟨box p q,?_⟩ + rw [hp,hq,box_scalar_left] + rfl + | zero => + rw [(refinedTripleCenterPolynomial a c η hc θ L M N hL hM hN).map_zero,LinearMap.map_zero] + exact dvd_zero _ + | add x y hx hy ihx ihy => + rw [(refinedTripleCenterPolynomial a c η hc θ L M N hL hM hN).map_add,LinearMap.map_add] + exact dvd_add ihx ihy + | smul r x hx ih => + obtain ⟨q,hq⟩:=ih + refine ⟨r • q,?_⟩ + rw [(refinedTripleCenterPolynomial a c η hc θ L M N hL hM hN).map_smul r x, + LinearMap.map_smul,hq,mul_smul_comm] + +end ElementaryPositivity.RawShuffle.SplitTree + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/TruncatedFactorization.lean b/lean/OAI/Combinatorics/Chromatic/Walls/TruncatedFactorization.lean new file mode 100644 index 0000000000000000000000000000000000000000..fbadb852dd1c4bb19ce62ed760ec18f721810265 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/TruncatedFactorization.lean @@ -0,0 +1,78 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Walls.PowerSeriesThreeFactors + +namespace OAI + +section +namespace ElementaryPositivity.PowerSeriesSplit +open PowerSeries +noncomputable section +variable {R : Type*} [Ring R] + +lemma pair_truncated_unique (P : R→+R) (f a b : PowerSeries R) (N : ℕ) + (ha : constantCoeff a=1) (hb : constantCoeff b=1) + (hab : ∀n≤N,coeff n (a*b)=coeff n f) + (hleft : ∀n,n+1≤N→P (coeff (n+1) a)=coeff (n+1) a) + (hright : ∀n,n+1≤N→P (coeff (n+1) b)=0) : + ∀n≤N,coeff n a=coeff n (leftFactor P f) ∧ coeff n b=coeff n (rightFactor P f) := by + have h : ∀n≤N,(coeff n a,coeff n b)=pairCoefficients P f n := by + intro n + induction n using Nat.strong_induction_on with + | h n ih=> + intro hn + cases n with + | zero=>simp only [coeff_zero_eq_constantCoeff_apply,ha,hb,pairCoefficients] + | succ n=> + have hs : (∑i : Fin n,coeff (i.val+1) a*coeff (n-i.val) b)= + ∑i : Fin n,(pairCoefficients P f (i.val+1)).1*(pairCoefficients P f (n-i.val)).2 := by + apply Finset.sum_congr rfl + intro i hi + rw [←ih (i.val+1) (by omega) (by omega),←ih (n-i.val) (by omega) (by omega)] + have hc:=coeff_mul_succ a b n ha hb + rw [hab (n+1) hn,hs] at hc + have hr : coeff (n+1) f-∑i : Fin n, + (pairCoefficients P f (i.val+1)).1*(pairCoefficients P f (n-i.val)).2= + coeff (n+1) a+coeff (n+1) b :=by rw [hc]; abel + rw [pairCoefficients,hr] + simp only [map_add,hleft n hn,hright n hn,add_zero] + congr 1 + abel + intro n hn + constructor + · simpa only [leftFactor,coeff_mk] using congrArg Prod.fst (h n hn) + · simpa only [rightFactor,coeff_mk] using congrArg Prod.snd (h n hn) + +lemma mul_mem_through (S : Subring R) (a b : PowerSeries R) (N : ℕ) + (ha : ∀n≤N,coeff n a∈S) (hb : ∀n≤N,coeff n b∈S) : + ∀n≤N,coeff n (a*b)∈S :=by + intro n hn + rw [coeff_mul] + apply S.sum_mem + intro p hp + have hh:=Finset.HasAntidiagonal.mem_antidiagonal.mp hp + exact S.mul_mem (ha p.1 (by omega)) (hb p.2 (by omega)) + +lemma three_truncated_unique (P Q : R→+R) (S : Subring R) (hS : ∀x,x∈S↔P x=0) + (f a b c : PowerSeries R) (N : ℕ) + (ha : constantCoeff a=1) (hb : constantCoeff b=1) (hc : constantCoeff c=1) + (habc : ∀n≤N,coeff n (a*b*c)=coeff n f) + (haP : ∀n,n+1≤N→P (coeff (n+1) a)=coeff (n+1) a) + (hbP : ∀n≤N,P (coeff n b)=0) (hcP : ∀n≤N,P (coeff n c)=0) + (hbQ : ∀n,n+1≤N→Q (coeff (n+1) b)=coeff (n+1) b) + (hcQ : ∀n,n+1≤N→Q (coeff (n+1) c)=0) : + ∀n≤N,coeff n a=coeff n (positiveFactor P f) ∧ + coeff n b=coeff n (zeroFactor P Q f) ∧ coeff n c=coeff n (negativeFactor P Q f) :=by + have hbc : ∀n≤N,P (coeff n (b*c))=0:=fun n hn=>(hS _).mp + (mul_mem_through S b c N (fun k hk=>(hS _).mpr (hbP k hk)) + (fun k hk=>(hS _).mpr (hcP k hk)) n hn) + have H:=pair_truncated_unique P f a (b*c) N ha (by simp [hb,hc]) + (fun n hn=>by simpa only [mul_assoc] using habc n hn) haP (fun n hn=>hbc (n+1) hn) + have H0:=pair_truncated_unique Q (rightFactor P f) b c N hb hc + (fun n hn=>(H n hn).2) hbQ hcQ + exact fun n hn=>⟨(H n hn).1,(H0 n hn).1,(H0 n hn).2⟩ +end +end ElementaryPositivity.PowerSeriesSplit + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/UnitalCoproductNaturality.lean b/lean/OAI/Combinatorics/Chromatic/Walls/UnitalCoproductNaturality.lean new file mode 100644 index 0000000000000000000000000000000000000000..99227efd7b309b27b4caf6176774450a3afd7655 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/UnitalCoproductNaturality.lean @@ -0,0 +1,198 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalCoproductUnits + +namespace OAI + +section +namespace ElementaryPositivity.TensorTransport +open scoped TensorProduct +variable {M N P X : Type*} [AddCommGroup M] [Module ℚ M] + [AddCommGroup N] [Module ℚ N] [AddCommGroup P] [Module ℚ P] + [AddCommGroup X] [Module ℚ X] +lemma map_left_insert (f : X →ₗ[ℚ] M⊗[ℚ]N) (g : X →ₗ[ℚ] N) + (u : M) (hf : ∀ x,f x=u⊗ₜ[ℚ]g x) (x : X⊗[ℚ]P) : + TensorProduct.assoc ℚ M N P (TensorProduct.map f LinearMap.id x)= + u⊗ₜ[ℚ]TensorProduct.map g LinearMap.id x := by + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,TensorProduct.tmul_add,hx,hy] + | tmul x y => simp only [TensorProduct.map_tmul,LinearMap.id_apply,hf,TensorProduct.assoc_tmul] +lemma map_right_insert (f : X →ₗ[ℚ] N⊗[ℚ]P) (g : X →ₗ[ℚ] N) + (u : P) (hf : ∀ x,f x=g x⊗ₜ[ℚ]u) (x : M⊗[ℚ]X) : + TensorProduct.map LinearMap.id f x= + TensorProduct.assoc ℚ M N P (TensorProduct.map LinearMap.id g x⊗ₜ[ℚ]u) := by + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,TensorProduct.add_tmul,hx,hy] + | tmul x y => simp only [TensorProduct.map_tmul,LinearMap.id_apply,hf,TensorProduct.assoc_tmul] +lemma map_middle_left (f : X →ₗ[ℚ] M⊗[ℚ]N) (g : X →ₗ[ℚ] M) + (u : N) (hf : ∀ x,f x=g x⊗ₜ[ℚ]u) (x : X⊗[ℚ]P) : + TensorProduct.assoc ℚ M N P (TensorProduct.map f LinearMap.id x)= + TensorProduct.map LinearMap.id (TensorProduct.mk ℚ N P u) + (TensorProduct.map g LinearMap.id x) := by + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => simp only [TensorProduct.map_tmul,LinearMap.id_apply,hf, + TensorProduct.assoc_tmul,TensorProduct.mk_apply] +lemma map_middle_right (f : X →ₗ[ℚ] N⊗[ℚ]P) (g : X →ₗ[ℚ] P) + (u : N) (hf : ∀ x,f x=u⊗ₜ[ℚ]g x) (x : M⊗[ℚ]X) : + TensorProduct.map LinearMap.id f x= + TensorProduct.map LinearMap.id (TensorProduct.mk ℚ N P u) + (TensorProduct.map LinearMap.id g x) := by + induction x using TensorProduct.inductionOn with + | add x y hx hy => simp only [map_add,hx,hy] + | tmul x y => simp only [TensorProduct.map_tmul,LinearMap.id_apply,hf,TensorProduct.mk_apply] +end ElementaryPositivity.TensorTransport + +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +attribute [local instance] unitalSepTensor unitalSepTensorA +noncomputable local instance naturalTensorAdd (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + AddCommGroup (B a μ d⊗[ℚ]B a μ e) := TensorProduct.addCommGroup +noncomputable local instance naturalTensorModule (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d e : I → ℕ) : + Module ℚ (B a μ d⊗[ℚ]B a μ e) := TensorProduct.leftModule + +noncomputable def castBLinear (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (h : d=e) : B a μ d →ₗ[ℚ] B a μ e := by + subst e + exact LinearMap.id + +lemma castBLinear_apply (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) + {d e : I → ℕ} (h : d=e) (x : B a μ d) : + castBLinear a μ h x=castB a μ h x := by subst e; rfl + +lemma castBLinear_rfl (a : I → I → ℕ) (μ : (I → ℕ) → ℝ) (d : I → ℕ) : + castBLinear a μ (rfl : d=d)=LinearMap.id := rfl + +lemma unitalSeparationConstant_cast (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0.compatible hf) x))= + TensorProduct.map LinearMap.id + (unitalSeparationConstant a c η hc e f (he.compatible hf)) + (unitalSeparationConstant a c η hc 0 (e+f) (Or.inl rfl) + (castB a (slope c η) (add_assoc 0 e f) x)) := by + rw [unitalSeparationConstant_map_zero_left] + have h := unitalSeparationConstant_cast a c η hc (zero_add e) (rfl : f=f) + ((show OnSlopeOrZero c η θ 0 from Or.inl rfl).add hc he |>.compatible hf) (he.compatible hf) x + simp only [castBLinear_rfl] at h ⊢ + rw [←h] + rw [unitalSeparationConstant_zero_left_any,TensorProduct.map_tmul,LinearMap.id_apply, + castB_trans] + +lemma unitalCoproduct_coassoc_zero_right (a : I → I → ℕ) (c η : I → ℝ) + (hc : ∀ i,0by rw [castBLinear_apply]; exact unitalSeparationConstant_zero_right_any a c η hc d y) + (unitalSeparationConstant a c η hc (d+0) f ((hd.add hc (Or.inl rfl)).compatible hf) x) + have hR := TensorTransport.map_middle_right + (unitalSeparationConstant a c η hc 0 f (Or.inl rfl)) + (castBLinear a (slope c η) (zero_add f)) (1:B a (slope c η) 0) + (fun y=>by rw [castBLinear_apply]; exact unitalSeparationConstant_zero_left_any a c η hc f y) + (unitalSeparationConstant a c η hc d (0+f) + (hd.compatible ((show OnSlopeOrZero c η θ 0 from Or.inl rfl).add hc hf)) + (castB a (slope c η) (add_assoc d 0 f) x)) + rw [hL,hR] + have hL' := unitalSeparationConstant_cast a c η hc (add_zero d) (rfl : f=f) + ((hd.add hc (Or.inl rfl)).compatible hf) (hd.compatible hf) x + have hR' := unitalSeparationConstant_cast a c η hc (rfl : d=d) (zero_add f) + (hd.compatible ((show OnSlopeOrZero c η θ 0 from Or.inl rfl).add hc hf)) + (hd.compatible hf) (castB a (slope c η) (add_assoc d 0 f) x) + simp only [castBLinear_rfl] at hL' hR' ⊢ + rw [←hL',←hR',castB_trans] + +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/UnitalGradeComparison.lean b/lean/OAI/Combinatorics/Chromatic/Walls/UnitalGradeComparison.lean new file mode 100644 index 0000000000000000000000000000000000000000..2f0b2ae42795650bb735e2b47fb44d286cf2faad --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/UnitalGradeComparison.lean @@ -0,0 +1,72 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.UnitalCoproductComparison +import OAI.Combinatorics.Chromatic.Shuffle.UnitalGradeAlgebra + +namespace OAI + +section +namespace ElementaryPositivity.LinearFiltration +variable {M : Type*} [AddCommGroup M] [Module ℚ M] +noncomputable def congr {F F' G G' : Submodule ℚ M} (h : F=G) (h' : F'=G') : + Grade F F' ≃ₗ[ℚ] Grade G G' := by + subst G; subst G' + exact LinearEquiv.refl ℚ _ +lemma congr_mk {F F' G G' : Submodule ℚ M} (h : F=G) (h' : F'=G') (x : F) : + congr h h' (Submodule.Quotient.mk x)=Submodule.Quotient.mk ⟨x.val,h ▸ x.property⟩ := by + subst G; subst G'; rfl +end ElementaryPositivity.LinearFiltration + +namespace ElementaryPositivity.RawShuffle +open scoped TensorProduct +open ElementaryPositivity.LinearFiltration ElementaryPositivity.SlopeArithmetic +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 + rw [unitalGradeCoproduct_mk,unitalTensorGradeNonzeroEquiv_mk,unitalGradeNonzeroEquiv_mk,separationCoproduct_mk] + apply congrArg (LinearFiltration.mk (sourceTensorFiltration a c η hc θ d e W) + (sourceTensorFiltration a c η hc θ d e (W+1))) + apply Subtype.ext + exact unitalSeparationConstant_eq a c η hc d e hs hde x.val +end ElementaryPositivity.RawShuffle + +namespace ElementaryPositivity.RawShuffle +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (c η : I → ℝ) (hc : ∀ i,0 exact ⟨1,one_pos,by simp⟩ + | @insert a S ha ih => + obtain ⟨b,hb,H⟩:=ih + refine ⟨max b (a+1),lt_of_lt_of_le hb (le_max_left _ _),?_⟩ + intro z hz + rcases Finset.mem_insert.mp hz with rfl|hz + · exact lt_of_lt_of_le (by linarith : z < z+1) (le_max_right _ _) + · exact lt_of_lt_of_le (H z hz) (le_max_left _ _) +lemma far_line_lex (S : Finset E) (v h : Module.Dual ℝ E) (b : ℝ) + (hb : ∀a∈lineEvents S v h,a < b) (s : E) (hs : s∈S) : + (0 < v s → 0 < (h+b • v) s) ∧ (v s < 0 → (h+b • v) s < 0) ∧ + (v s=0 → (0 < h s → 0 < (h+b • v) s) ∧ (h s=0 → (h+b • v) s=0) ∧ + (h s < 0 → (h+b • v) s < 0)) := by + classical + simp only [LinearMap.add_apply,LinearMap.smul_apply,smul_eq_mul] + have HB : v s≠0 → -h s/v s < b:=fun hv => hb _ + (Finset.mem_image.mpr ⟨s,Finset.mem_filter.mpr ⟨hs,hv⟩,rfl⟩) + constructor + · intro hh + have H:=HB (ne_of_gt hh) + have hz : h s+(-h s/v s)*v s=0:=by field_simp [ne_of_gt hh]; ring + nlinarith + constructor + · intro hh + have H:=HB (ne_of_lt hh) + have hz : h s+(-h s/v s)*v s=0:=by field_simp [ne_of_lt hh]; ring + nlinarith + · intro hz + simp only [hz,mul_zero,add_zero] + exact ⟨id,id,id⟩ +include he hdeg in +lemma offset_ray_generic (N d : ℕ) (r : M) (hd : 0 < d) (hr : HasRootDegree C d r) + (v h : Module.Dual ℝ E) + (H : GenericOffset (realRootsThrough e C N) (e r) v h) : + RayGeneric C N r (h.toAddMonoidHom.comp e) := by + refine ⟨H.on_ray,?_⟩ + intro n hn hnN m hm hm0 + apply positive_ray_of_mem_span e he C L hdeg r m d n hd hn hr hm + by_contra hP + exact H.avoid _ (realRoot_mem e C N n hnN m hm) hP hm0 +include he hB hcomp hdeg in +theorem incoming_positive_at_far (N d : ℕ) (r : M) (hd : 0 < d) (hr : HasRootDegree C d r) + (k : Module.Dual ℝ E) + (H : GenericOffset (realRootsThrough e C N) (e r) (B.flip (e r)) k) + (F D : CompletedPositive LaurentRay.vUnit Ω C) + (hD : ∀n m,coeff (n+1) D.val m≠0 → OnPositiveRay r m) + (hpos : RootClosedThrough LaurentRay.vUnit Ω N (literalRootProducts Ω C (OnPositiveRay r)) D.val) + (hprescribed : ∀n ≤ N,∀m,OnPositiveRay r m → + coeff n (FormalLog.log (chartZero LaurentRay.vUnit Ω C (incomingCovector Ω m) F).val) m= + coeff n (FormalLog.log D.val) m) : + ∃b,0 < b ∧ (∀a∈lineEvents (realRootsThrough e C N) (B.flip (e r)) k,a < b) ∧ + RootClosedThrough LaurentRay.vUnit Ω N (literalRootProducts Ω C (OnPositiveRay r)) + (chartZero LaurentRay.vUnit Ω C ((k+b • B.flip (e r)).toAddMonoidHom.comp e) F).val := by + have hΩ : ∀m,Ω m m=0:=by + intro m; have HH:=hB (e m); rw [hcomp] at HH; exact_mod_cast HH + obtain ⟨b,hb,hbound⟩:=finite_upper_bound (lineEvents (realRootsThrough e C N) (B.flip (e r)) k) + refine ⟨b,hb,hbound,?_⟩ + have Hgen:=offset_ray_generic C e he L hdeg N d r hd hr (B.flip (e r)) k H + have Hinc:=incoming_ray_element_through LaurentRay.vUnit Ω C hΩ r (k.toAddMonoidHom.comp e) + H.on_ray F D N (fun n hn hnN m hm hΩm hkm => Hgen.2 n hn hnN m hm hkm) hD hprescribed + have Href:=chart_zero_refinement LaurentRay.vUnit Ω C (incomingCovector Ω r) + (k.toAddMonoidHom.comp e) ((k+b • B.flip (e r)).toAddMonoidHom.comp e) F N (by + intro n hn m hm + have HH:=far_line_lex (realRootsThrough e C N) (B.flip (e r)) k b hbound + (e m) (realRoot_mem e C N n hn m hm) + simp only [LinearMap.flip_apply,hcomp] at HH + exact HH) + apply hpos.congr LaurentRay.vUnit Ω + intro n hn + exact (Href n hn |>.trans (Hinc n hn)).symm +end +end ElementaryPositivity.QuantumTorus + +end +section +namespace ElementaryPositivity.FiniteEventTraversal +noncomputable section +lemma finite_gap (S : Finset ℝ) (a : ℝ) : + ∃ε > 0,∀s∈S,s≠a → ε < |s-a| := by + classical + induction S using Finset.induction_on with + | empty=>exact ⟨1,one_pos,by simp⟩ + | @insert s S hs ih=> + obtain ⟨ε,he,H⟩:=ih + by_cases hsa : s=a + · refine ⟨ε,he,?_⟩ + intro x hx hn + rcases Finset.mem_insert.mp hx with rfl|hx + · exact False.elim (hn hsa) + · exact H x hx hn + · refine ⟨min ε (|s-a|/2),lt_min he (by have := abs_pos.mpr (sub_ne_zero.mpr hsa); positivity),?_⟩ + intro x hx hn + rcases Finset.mem_insert.mp hx with rfl|hx + · exact lt_of_le_of_lt (min_le_right _ _) (by have := abs_pos.mpr (sub_ne_zero.mpr hsa); linarith) + · exact lt_of_le_of_lt (min_le_left _ _) (H x hx hn) +lemma near_not_mem (S : Finset ℝ) (a δ ε : ℝ) (hd : 0 < δ) (hde : δ < ε) + (H : ∀s∈S,s≠a → ε < |s-a|) : a+δ∉S ∧ a-δ∉S := by + constructor + · intro hs + have hx:=H (a+δ) hs (by linarith) + rw [add_sub_cancel_left,abs_of_pos hd] at hx + linarith + · intro hs + have hx:=H (a-δ) hs (by linarith) + have he : a-δ-a= -δ:=by ring + rw [he,abs_neg,abs_of_pos hd] at hx + linarith + +theorem descend (S : Finset ℝ) (P : ℝ → Prop) + (initial : ∃b,0 ≤ b ∧ (∀s∈S,s < b) ∧ P b) + (cell : ∀a b,0 ≤ a → 0 ≤ b → a∉S → b∉S → + (∀s∈S,a < s↔b < s) → P a → P b) + (step : ∀a∈S,0 < a → ∃ε > 0,∀δ,0 < δ → δ < ε → P (a+δ) → P (a-δ)) + (t : ℝ) (ht : 0 ≤ t) (htS : t∉S) : P t := by + classical + suffices ∀k,∀t:ℝ,0 ≤ t → t∉S → (S.filter (fun s=>t < s)).card=k → P t from + this _ t ht htS rfl + intro k + induction k using Nat.strong_induction_on with + | h k ih=> + intro t ht htS hk + let U:=S.filter (fun s=>t < s) + by_cases hU : U.Nonempty + · let a:=U.min' hU + have haU : a∈U:=Finset.min'_mem _ _ + have haS : a∈S:=(Finset.mem_filter.mp haU).1 + have hta : t < a:=(Finset.mem_filter.mp haU).2 + obtain ⟨ε,he,Hε⟩:=step a haS (lt_of_le_of_lt ht hta) + obtain ⟨η,hh,Hη⟩:=finite_gap S a + let δ:=min (min ε η) (a-t)/2 + have hd : 0 < δ:=by dsimp [δ]; exact div_pos (lt_min (lt_min he hh) (sub_pos.mpr hta)) (by norm_num) + have hδsmall : δ < min (min ε η) (a-t):=by + have hp : 0 < min (min ε η) (a-t):=lt_min (lt_min he hh) (sub_pos.mpr hta) + dsimp [δ]; linarith + have hδε : δ < ε:=lt_of_lt_of_le hδsmall ((min_le_left _ _).trans (min_le_left _ _)) + have hδη : δ < η:=lt_of_lt_of_le hδsmall ((min_le_left _ _).trans (min_le_right _ _)) + have hδt : δ < a-t:=lt_of_lt_of_le hδsmall (min_le_right _ _) + have hnS:=near_not_mem S a δ η hd hδη Hη + have hsub : S.filter (fun s=>a+δ < s) ⊂ U:=by + apply Finset.ssubset_iff_subset_ne.mpr + constructor + · intro x hx + obtain ⟨hx,hxx⟩:=Finset.mem_filter.mp hx + exact Finset.mem_filter.mpr ⟨hx,by linarith⟩ + · intro heq + have hx : a∈S.filter (fun s=>a+δ < s):=heq.symm ▸ haU + have := (Finset.mem_filter.mp hx).2 + linarith + have hcard : (S.filter (fun s=>a+δ < s)).card < k:=by + rw [←hk]; exact Finset.card_lt_card hsub + have hb : P (a+δ):=ih _ hcard (a+δ) (by linarith) hnS.1 rfl + have hc : P (a-δ):=Hε δ hd hδε hb + apply cell (a-δ) t (by linarith) ht hnS.2 htS _ hc + intro s hs + constructor + · intro hcs + by_contra hts + linarith + · intro hts + have hsu : s∈U:=Finset.mem_filter.mpr ⟨hs,hts⟩ + have has : a ≤ s:=Finset.min'_le _ _ hsu + linarith + · obtain ⟨b,hb,hbS,hPb⟩:=initial + have hbN : b∉S:=fun hbmem=>lt_irrefl b (hbS b hbmem) + apply cell b t hb ht hbN htS _ hPb + intro s hs + have hts : ¬t < s:=fun h=>hU ⟨s,Finset.mem_filter.mpr ⟨hs,h⟩⟩ + exact iff_of_false (not_lt_of_ge (hbS s hs).le) hts +end +end ElementaryPositivity.FiniteEventTraversal + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/WallRegrade.lean b/lean/OAI/Combinatorics/Chromatic/Walls/WallRegrade.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae51f0ec76058f4e57a39d63ad60122df9dfe100 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/WallRegrade.lean @@ -0,0 +1,218 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegradeFaithful +import OAI.Combinatorics.Chromatic.GradedAlgebra.MutationDegreeBound + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries WallUnits +noncomputable section +variable {M I : Type*} [AddCommGroup M] [Fintype I] [DecidableEq I] +variable (C : (I → ℤ) →+ M) (coord : M →+ (I → ℤ)) +variable (hcoord : ∀d,coord (C d)=d) +def rootOrder : M →+ ℤ where + toFun m:=∑i,coord m i + map_zero':=by simp + map_add':=by intro a b; simp [Finset.sum_add_distrib] +omit [DecidableEq I] in +include hcoord in +lemma rootOrder_eq {n : ℕ} {m : M} (hm : HasRootDegree C n m) : rootOrder coord m=(n:ℤ) := by + obtain ⟨d,hd,hc,he⟩:=root_coordinates C coord hcoord hm + change (∑i,coord m i)=(n:ℤ) + simp only [hc,←Nat.cast_sum,hd] + +variable {R : Type*} [CommRing R] [Algebra ℚ R] (v : Rˣ) (Ω : M →+ M →+ ℤ) +omit [Algebra ℚ R] [DecidableEq I] in +include hcoord in +lemma chart_full_homogeneous (h : M →+ ℝ) (f : CompletedPositive v Ω C) : + FullHomogeneous v Ω (rootOrder coord) (chartZero v Ω C h f).val := by + intro j m hm + exact rootOrder_eq C coord hcoord (chart_root_of_ne v Ω C (chartZero v Ω C h f) j m hm) + +variable {E : Type*} [AddCommGroup E] [Module ℝ E] +variable (pc : I) (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) +include hcoord he hS hcomp hdeg in +lemma simple_regrade_bound (r : M) (dr : ℕ) (hdr : 0 rfl +include hΩ in +lemma mutationLinearPiece_pairing (a b : M) : + Ω (mutationLinearPiece Ω C pc pos a) (mutationLinearPiece Ω C pc pos b)=Ω a b := by + cases pos + · exact mutationShear_pairing Ω hΩ _ a b + · rfl +include hΩ in +lemma mutationLinearPiece_injective : Function.Injective (mutationLinearPiece Ω C pc pos) := by + intro a b hab + apply (mutationPieceEquiv Ω hΩ C pc pos).injective + simpa only [mutationPieceEquiv_apply] using hab +include hΩ in +lemma mutationLinearPiece_surjective : Function.Surjective (mutationLinearPiece Ω C pc pos) := by + intro m + refine ⟨(mutationPieceEquiv Ω hΩ C pc pos).symm m,?_⟩ + rw [←mutationPieceEquiv_apply Ω hΩ C pc pos,AddEquiv.apply_symm_apply] + +variable [Fintype I] + +def mutationNewOrder : M →+ ℤ := + (rootOrder (mutatedCoordinates Ω C coord pc)).comp (mutationLinearPiece Ω C pc pos) + +include hcoord in +lemma mutationNewOrder_of_root {n : ℕ} {m : M} + (hm : HasRootDegree (mutatedRoots Ω C pc) n (mutationLinearPiece Ω C pc pos m)) : + mutationNewOrder Ω C coord pc pos m=(n:ℤ) := + rootOrder_eq (mutatedRoots Ω C pc) (mutatedCoordinates Ω C coord pc) + (mutatedCoordinates_retraction Ω C coord hcoord pc) hm + +variable {R : Type*} [CommRing R] (v : Rˣ) +local instance wallRegradeRing : Ring (Torus v Ω) := Torus.instRing v Ω +local instance wallRegradeAddCommMonoid : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance wallRegradeAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def mutationTorusPush : Torus v Ω →+* Torus v Ω := + Torus.push v Ω Ω (mutationLinearPiece Ω C pc pos) (mutationLinearPiece_pairing Ω hΩ C pc pos) +omit [Fintype I] in +lemma mutationTorusPush_read (f : Torus v Ω) (m : M) : + mutationTorusPush Ω hΩ C pc pos v f (mutationLinearPiece Ω C pc pos m)=f m := + Finsupp.mapDomain_apply_of_injective (mutationLinearPiece_injective Ω hΩ C pc pos) f m + +def mutationCompletion (f : PowerSeries (Torus v Ω)) : PowerSeries (Torus v Ω) := + PowerSeries.map (mutationTorusPush Ω hΩ C pc pos v) + (regrade v Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f) + +lemma mutationCompletion_coeff_read (f : PowerSeries (Torus v Ω)) (d : ℕ) (m : M) : + coeff d (mutationCompletion Ω hΩ C coord pc pos v f) (mutationLinearPiece Ω C pc pos m)= + if d=(mutationNewOrder Ω C coord pc pos m).toNat then + ∑n∈Finset.range ((mutationSize Ω C pc+1)*d+1),coeff n f m else 0 := by + rw [mutationCompletion,coeff_map,mutationTorusPush_read,regrade_coeff_eval] + +include hcoord hΩ in +lemma mutationCompletion_bound (f : CompletedPositive v Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + RegradeBound v Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f.val := by + intro n m hm + obtain ⟨d,hd,hnp,hn⟩:=mutation_root_image_bound Ω C coord hcoord pc hΩ pos + (by by_contra hh; exact hm (f.property.2 n m hh)) (hf n m hm) + rw [mutationNewOrder_of_root Ω C coord hcoord pc pos hd] + exact ⟨Int.natCast_nonneg _,by simpa using hn⟩ + +include hcoord in +lemma mutationCompletion_graded (f : CompletedPositive v Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + ∀d,coeff d (mutationCompletion Ω hΩ C coord pc pos v f.val)∈ + rootGrade v Ω (mutatedRoots Ω C pc) d := by + classical + intro d m hm + obtain ⟨a,rfl⟩:=mutationLinearPiece_surjective Ω hΩ C pc pos m + rw [mutationCompletion_coeff_read] + split_ifs with ha + · by_contra hz + obtain ⟨n,hn,hz⟩:=Finset.exists_ne_zero_of_sum_ne_zero hz + obtain ⟨d',hd',he⟩:=mutation_root_image Ω C coord hcoord pc hΩ pos + (by by_contra hh; exact hz (f.property.2 n a hh)) (hf n a hz) + have he':=mutationNewOrder_of_root Ω C coord hcoord pc pos hd' + rw [he',Int.toNat_natCast] at ha + exact hm (ha ▸ hd') + · rfl + +lemma mutationCompletion_constant (f : PowerSeries (Torus v Ω)) (hf : constantCoeff f=1) : + constantCoeff (mutationCompletion Ω hΩ C coord pc pos v f)=1 := by + rw [←coeff_zero_eq_constantCoeff_apply] + rw [mutationCompletion,coeff_map,regrade_coeff] + simp only [mul_zero,zero_add,Finset.sum_range_one,coeff_zero_eq_constantCoeff,hf, + homogenize_one,map_one] + +def mutationCompletedPositive (f : CompletedPositive v Ω C) + (hf : ∀n m,coeff n f.val m≠0 → m∈fiberCone coord pc (mutationPairing Ω C pc) (sideSign pos)) : + CompletedPositive v Ω (mutatedRoots Ω C pc) := + ⟨mutationCompletion Ω hΩ C coord pc pos v f.val, + mutationCompletion_constant Ω hΩ C coord pc pos v f.val f.property.1, + mutationCompletion_graded Ω hΩ C coord hcoord pc pos v f hf⟩ + +lemma mutationCompletion_mul {f g : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f) + (hg : RegradeBound v Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) g) : + mutationCompletion Ω hΩ C coord pc pos v (f*g)= + mutationCompletion Ω hΩ C coord pc pos v f*mutationCompletion Ω hΩ C coord pc pos v g := by + unfold mutationCompletion + rw [regrade_mul v Ω _ _ hf hg,map_mul] +lemma mutationCompletion_one : mutationCompletion Ω hΩ C coord pc pos v 1=1 := by + rw [mutationCompletion,regrade_one,map_one] +lemma mutationCompletion_inverse_mul {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f) + (hc : constantCoeff f=1) : + mutationCompletion Ω hΩ C coord pc pos v (PowerSeries.invOfUnit f 1)* + mutationCompletion Ω hΩ C coord pc pos v f=1 := by + rw [←mutationCompletion_mul Ω hΩ C coord pc pos v (hf.invOfUnit v Ω _ _) hf, + PowerSeries.invOfUnit_mul f 1 hc,mutationCompletion_one] +lemma mutationCompletion_mul_inverse {f : PowerSeries (Torus v Ω)} + (hf : RegradeBound v Ω (mutationNewOrder Ω C coord pc pos) (mutationSize Ω C pc+1) f) + (hc : constantCoeff f=1) : + mutationCompletion Ω hΩ C coord pc pos v f* + mutationCompletion Ω hΩ C coord pc pos v (PowerSeries.invOfUnit f 1)=1 := by + rw [←mutationCompletion_mul Ω hΩ C coord pc pos v hf (hf.invOfUnit v Ω _ _), + PowerSeries.mul_invOfUnit f 1 hc,mutationCompletion_one] + +variable {E : Type*} [AddCommGroup E] [Module ℝ E] +variable (e : M →+ E) (he : Function.Injective e) +variable (S : E →ₗ[ℝ] E →ₗ[ℝ] ℝ) (hS : ∀x,S x x=0) +variable (hcomp : ∀a b,S (e a) (e b)=(Ω a b:ℝ)) +variable (L : Module.Dual ℝ E) (hdeg : ∀d m,HasRootDegree C d m → L (e m)=(d:ℝ)) + +def actualMutatedWall (r : M) (dr : ℕ) (hdr : 0 1 + | n + 1 => u * q ^ n * elementaryCoeff q u n / (1 - q ^ (n + 1)) + +noncomputable def elementary (q u : K) : PowerSeries K := + PowerSeries.mk (elementaryCoeff q u) + +@[simp] theorem coeff_elementary (q u : K) (n : ℕ) : + PowerSeries.coeff n (elementary q u) = elementaryCoeff q u n := by + simp [elementary] + +@[simp] theorem constant_elementary (q u : K) : + PowerSeries.constantCoeff (elementary q u) = 1 := rfl + +theorem elementaryCoeff_product (q u : K) (n : ℕ) : + elementaryCoeff q u n = + (u ^ n * q ^ (∑ i ∈ Finset.range n, i)) / + ∏ i ∈ Finset.range n, (1 - q ^ (i + 1)) := by + induction n with + | zero => simp [elementaryCoeff] + | succ n ih => + rw [elementaryCoeff, ih, Finset.sum_range_succ, Finset.prod_range_succ, + pow_succ, pow_add] + simp only [div_eq_mul_inv, mul_inv_rev] + ring + +theorem elementary_tail (q u : K) (hq : ∀ n : ℕ, 1 - q ^ (n + 1) ≠ 0) : + elementary q u = (1 + PowerSeries.C u * PowerSeries.X) * + PowerSeries.rescale q (elementary q u) := by + ext n + cases n with + | zero => + simp only [coeff_zero_eq_constantCoeff, map_mul, map_add, constantCoeff_one, + constantCoeff_C, constantCoeff_X, mul_zero, add_zero, one_mul] + rw [constant_elementary, ← coeff_zero_eq_constantCoeff, coeff_rescale] + simp [elementaryCoeff] + | succ n => + rw [add_mul, one_mul, map_add] + simp only [coeff_elementary, coeff_rescale] + rw [mul_assoc, PowerSeries.coeff_C_mul, PowerSeries.coeff_succ_X_mul, + PowerSeries.coeff_rescale, coeff_elementary, elementaryCoeff] + field_simp [hq n] + ring + +@[simp] theorem rescale_C (a u : K) : + PowerSeries.rescale a (PowerSeries.C u) = PowerSeries.C u := by + ext n + cases n <;> simp + +theorem elementary_head (q u : K) (hq0 : q ≠ 0) + (hq : ∀ n : ℕ, 1 - q ^ (n + 1) ≠ 0) : + PowerSeries.rescale q⁻¹ (elementary q u) = + (1 + PowerSeries.C (u * q⁻¹) * PowerSeries.X) * elementary q u := by + have h := congrArg (PowerSeries.rescale q⁻¹) (elementary_tail q u hq) + simp only [map_mul, map_add, map_one, rescale_C, PowerSeries.rescale_X, + PowerSeries.rescale_rescale, mul_inv_cancel₀ hq0, PowerSeries.rescale_one, + RingHom.id_apply] at h + rw [← mul_assoc (PowerSeries.C u), ← map_mul] at h + exact h + +theorem elementary_shift (q u : K) (hq0 : q ≠ 0) + (hq : ∀ n : ℕ, 1 - q ^ (n + 1) ≠ 0) (t : ℕ) : + PowerSeries.rescale (q⁻¹ ^ t) (elementary q u) = + (∏ i ∈ Finset.range t, + (1 + PowerSeries.C (u * q⁻¹ ^ (i + 1)) * PowerSeries.X)) * + elementary q u := by + induction t with + | zero => simp + | succ t ih => + rw [pow_succ', ← PowerSeries.rescale_rescale, elementary_head q u hq0 hq] + simp only [map_mul, map_add, map_one, rescale_C, PowerSeries.rescale_X] + rw [ih] + rw [Finset.prod_range_succ] + simp only [pow_succ', map_mul] + ring + +theorem rescale_inv_of_const_one (a : K) (F : PowerSeries K) + (hF : PowerSeries.constantCoeff F = 1) : + PowerSeries.rescale a F⁻¹ = (PowerSeries.rescale a F)⁻¹ := by + have hR : PowerSeries.constantCoeff (PowerSeries.rescale a F) ≠ 0 := by + rw [← PowerSeries.coeff_zero_eq_constantCoeff, PowerSeries.coeff_rescale, + pow_zero, one_mul, PowerSeries.coeff_zero_eq_constantCoeff, hF] + exact one_ne_zero + apply (PowerSeries.eq_inv_iff_mul_eq_one hR).2 + rw [← map_mul, PowerSeries.inv_mul_cancel F (by simp [hF]), map_one] + +noncomputable def complete (q u : K) : PowerSeries K := (elementary q (-u))⁻¹ + +theorem complete_shift (q u : K) (hq0 : q ≠ 0) + (hq : ∀ n : ℕ, 1 - q ^ (n + 1) ≠ 0) (t : ℕ) : + PowerSeries.rescale (q⁻¹ ^ t) (complete q u) = + (elementary q (-u))⁻¹ * + (∏ i ∈ Finset.range t, + (1 + PowerSeries.C (-u * q⁻¹ ^ (i + 1)) * PowerSeries.X))⁻¹ := by + rw [complete, rescale_inv_of_const_one _ _ (constant_elementary _ _), + elementary_shift q (-u) hq0 hq t, PowerSeries.mul_inv_rev] + +theorem elementary_ratio (q u : K) (hq0 : q ≠ 0) + (hq : ∀ n : ℕ, 1 - q ^ (n + 1) ≠ 0) (t : ℕ) : + PowerSeries.rescale (q⁻¹ ^ t) (elementary q u) * (elementary q u)⁻¹ = + ∏ i ∈ Finset.range t, + (1 + PowerSeries.C (u * q⁻¹ ^ (i + 1)) * PowerSeries.X) := by + rw [elementary_shift q u hq0 hq t, mul_assoc, + PowerSeries.mul_inv_cancel _ (by simp), mul_one] + +theorem complete_ratio (q u : K) (hq0 : q ≠ 0) + (hq : ∀ n : ℕ, 1 - q ^ (n + 1) ≠ 0) (t : ℕ) : + PowerSeries.rescale (q⁻¹ ^ t) (complete q u) * elementary q (-u) = + (∏ i ∈ Finset.range t, + (1 + PowerSeries.C (-u * q⁻¹ ^ (i + 1)) * PowerSeries.X))⁻¹ := by + rw [complete_shift q u hq0 hq t] + rw [mul_right_comm, PowerSeries.inv_mul_cancel _ (by simp), one_mul] + +end Field + +namespace RationalRay +noncomputable def v : RatFunc ℚ := RatFunc.X +noncomputable def q : RatFunc ℚ := v ^ (-2 : ℤ) +theorem v_nonzero : v ≠ 0 := RatFunc.X_ne_zero + +theorem degree_pow (x : RatFunc ℚ) (hx : x ≠ 0) (n : ℕ) : + (x ^ n).intDegree = n * x.intDegree := by + induction n with + | zero => simp + | succ n ih => + rw [pow_succ, RatFunc.intDegree_mul (pow_ne_zero _ hx) hx, ih] + push_cast + ring + +theorem q_nonzero : q ≠ 0 := zpow_ne_zero _ v_nonzero + +theorem q_degree : q.intDegree = -2 := by + change (v ^ (-(2 : ℕ) : ℤ)).intDegree = -2 + rw [zpow_neg, zpow_natCast, RatFunc.intDegree_inv, degree_pow v v_nonzero] + simp [v] + +theorem q_not_root_unity (n : ℕ) : 1 - q ^ (n + 1) ≠ 0 := by + intro h + have heq := congrArg RatFunc.intDegree (sub_eq_zero.mp h) + rw [RatFunc.intDegree_one, degree_pow q q_nonzero, q_degree] at heq + omega + +theorem q_pow (n : ℕ) : q ^ n = v ^ (-2 * (n : ℤ)) := by + rw [q, ← zpow_natCast, ← zpow_mul] + +noncomputable def normalized : PowerSeries (RatFunc ℚ) := elementary q v⁻¹ + +theorem normalized_coefficient (n : ℕ) : + PowerSeries.coeff n normalized = + v ^ (-(n : ℤ) ^ 2) / + ∏ i ∈ Finset.range n, (1 - v ^ (-2 * ((i + 1 : ℕ) : ℤ))) := by + rw [normalized, coeff_elementary] + induction n with + | zero => simp [elementaryCoeff] + | succ n ih => + rw [elementaryCoeff, ih, Finset.prod_range_succ] + have hn : v⁻¹ * q ^ n * v ^ (-(n : ℤ) ^ 2) = + v ^ (-((n + 1 : ℕ) : ℤ) ^ 2) := by + rw [q_pow, ← zpow_neg_one, ← zpow_add₀ v_nonzero, ← zpow_add₀ v_nonzero] + congr 1 + push_cast + ring + rw [q_pow (n + 1)] + calc + _ = (v⁻¹ * q ^ n * v ^ (-(n : ℤ) ^ 2)) / + ((∏ i ∈ Finset.range n, (1 - v ^ (-2 * ((i + 1 : ℕ) : ℤ)))) * + (1 - v ^ (-2 * ((n + 1 : ℕ) : ℤ)))) := by + simp only [div_eq_mul_inv, mul_inv_rev] + ring + _ = _ := by rw [hn] + +theorem normalized_ratio (t : ℕ) : + PowerSeries.rescale (q⁻¹ ^ t) normalized * normalized⁻¹ = + ∏ i ∈ Finset.range t, + (1 + PowerSeries.C (v⁻¹ * q⁻¹ ^ (i + 1)) * PowerSeries.X) := + elementary_ratio q v⁻¹ q_nonzero q_not_root_unity t + +end RationalRay + +namespace PositiveRay +open PowerSeries +noncomputable def vUnit : (RatFunc ℚ)ˣ := Units.mk0 RationalRay.v RationalRay.v_nonzero +noncomputable def eval : LaurentPolynomial ℕ →+* RatFunc ℚ := + LaurentPolynomial.eval₂ (Nat.castRingHom _) vUnit + +@[simp] theorem eval_T (b : ℤ) : eval (LaurentPolynomial.T b) = RationalRay.v ^ b := by + simp [eval, vUnit] + +def Positive (F : PowerSeries (RatFunc ℚ)) : Prop := + ∃ A : PowerSeries (LaurentPolynomial ℕ), PowerSeries.map eval A = F + +theorem positive_mul {F G : PowerSeries (RatFunc ℚ)} + (hF : Positive F) (hG : Positive G) : Positive (F * G) := by + obtain ⟨A, rfl⟩ := hF + obtain ⟨B, rfl⟩ := hG + exact ⟨A * B, map_mul _ _ _⟩ + +theorem positive_one : Positive 1 := ⟨1, map_one _⟩ + +theorem positive_E (b : ℤ) : + Positive (1 + PowerSeries.C (RationalRay.v ^ b) * PowerSeries.X) := by + refine ⟨1 + PowerSeries.C (LaurentPolynomial.T b) * PowerSeries.X, ?_⟩ + simp + +theorem geometric (a : RatFunc ℚ) : + PowerSeries.rescale a (PowerSeries.mk 1) * (1 - PowerSeries.C a * PowerSeries.X) = 1 := by + have h := congrArg (PowerSeries.rescale a) + (PowerSeries.mk_one_mul_one_sub_eq_one (RatFunc ℚ)) + simpa only [map_mul, map_sub, map_one, PowerSeries.rescale_X] using h + +theorem positive_H (b : ℤ) : + Positive (1 - PowerSeries.C (RationalRay.v ^ b) * PowerSeries.X)⁻¹ := by + refine ⟨PowerSeries.rescale (LaurentPolynomial.T b) (PowerSeries.mk 1), ?_⟩ + have he : PowerSeries.map eval + (PowerSeries.rescale (LaurentPolynomial.T b) (PowerSeries.mk 1)) = + PowerSeries.rescale (RationalRay.v ^ b) (PowerSeries.mk 1) := by + ext n + simp only [PowerSeries.coeff_map, PowerSeries.coeff_rescale, PowerSeries.coeff_mk, + Pi.one_apply, mul_one, map_pow, eval_T] + rw [he] + exact (PowerSeries.eq_inv_iff_mul_eq_one (by simp)).2 (geometric _) + +theorem positive_E_string (t : ℕ) (b : ℕ → ℤ) : + Positive (∏ i ∈ Finset.range t, + (1 + PowerSeries.C (RationalRay.v ^ b i) * PowerSeries.X)) := by + induction t with + | zero => simpa using positive_one + | succ t ih => + rw [Finset.prod_range_succ] + exact positive_mul ih (positive_E _) + +theorem positive_H_string (t : ℕ) (b : ℕ → ℤ) : + Positive (∏ i ∈ Finset.range t, + (1 - PowerSeries.C (RationalRay.v ^ b i) * PowerSeries.X))⁻¹ := by + induction t with + | zero => simpa using positive_one + | succ t ih => + rw [Finset.prod_range_succ, PowerSeries.mul_inv_rev] + exact positive_mul (positive_H _) ih +end PositiveRay + +namespace RationalRay + +theorem shift_weight (k : ℤ) (j : ℕ) : + v ^ k * q⁻¹ ^ (j + 1) = v ^ (k + 2 * ((j + 1 : ℕ) : ℤ)) := by + have h : q⁻¹ ^ (j + 1) = v ^ (2 * ((j + 1 : ℕ) : ℤ)) := by + rw [inv_pow, q_pow, ← zpow_neg] + congr 1 + rw [h, ← zpow_add₀ v_nonzero] + +theorem elementary_ratio_positive (k : ℤ) (t : ℕ) : + PositiveRay.Positive (PowerSeries.rescale (q⁻¹ ^ t) (elementary q (v ^ k)) * + (elementary q (v ^ k))⁻¹) := by + rw [elementary_ratio q _ q_nonzero q_not_root_unity t] + simp_rw [shift_weight] + exact PositiveRay.positive_E_string t _ + +theorem complete_ratio_positive (k : ℤ) (t : ℕ) : + PositiveRay.Positive (PowerSeries.rescale (q⁻¹ ^ t) (complete q (v ^ k)) * + elementary q (-(v ^ k))) := by + rw [complete_ratio q _ q_nonzero q_not_root_unity t] + simp_rw [neg_mul, shift_weight, map_neg, neg_mul, ← sub_eq_add_neg] + exact PositiveRay.positive_H_string t _ + +end RationalRay + +end ElementaryPositivity.WallUnits +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/WeightedCompletion.lean b/lean/OAI/Combinatorics/Chromatic/Walls/WeightedCompletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..e88a1d60dd2203d7d7dec4b68e776bc3fbc466f5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/WeightedCompletion.lean @@ -0,0 +1,69 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.SplitContinuity +import OAI.Combinatorics.Chromatic.GradedAlgebra.HNSeries + +namespace OAI + +section +namespace ElementaryPositivity.WeightedTorusSeries +open QuantumTorus PowerSeries LaurentPrecision +noncomputable section +variable {I J M ι : Type*} [Fintype I] [DecidableEq I] [Fintype J] [AddCommGroup M] +variable (w : I→ℕ) [Fact (∀i,0rfl + | @insert a s ha ih=> + rw [Finset.sum_insert ha,Finset.sum_insert ha] + change (f a) m+(∑i∈s,f i) m=_ + rw [ih] + +omit [DecidableEq I] in +include hroot in +lemma push_graded (f : (I→ℕ)→LaurentSeries ℚ) : SeriesGraded v Ω C (push w v Ω P f) := by + classical + intro n m hm + simp only [push,coeff_mk,pushCoeff,torus_sum_apply] + apply Finset.sum_eq_zero + intro d hd + change (Finsupp.single (P d.val) (f d.val)) m=0 + apply Finsupp.single_eq_of_ne + intro H + apply hm + simpa only [d.property,H] using hroot d.val + +def completedPush (f : (I→ℕ)→LaurentSeries ℚ) (hf : f 0=1) : CompletedPositive v Ω C := + ⟨push w v Ω P f,push_constant w v Ω P f hf,push_graded w v Ω P C hroot f⟩ + +variable (l : Filter ι) +omit [DecidableEq I] in +lemma push_converges {f : ι→(I→ℕ)→LaurentSeries ℚ} {F : (I→ℕ)→LaurentSeries ℚ} + (hf : ∀d,Converges l (fun i=>f i d) (F d)) : + SeriesConverges v Ω l (fun i=>push w v Ω P (f i)) (push w v Ω P F) := by + classical + intro n m + simp only [push,coeff_mk,pushCoeff,torus_sum_apply] + apply LaurentPrecision.Converges.sum + intro d hd + change Converges l (fun i=>(Finsupp.single (P d.val) (f i d.val)) m) + ((Finsupp.single (P d.val) (F d.val)) m) + by_cases H : m=P d.val + · subst m + simpa only [Finsupp.single_eq_same] using hf d.val + · simp only [Finsupp.single_eq_of_ne H] + exact converges_const l 0 +end +end ElementaryPositivity.WeightedTorusSeries + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/WeightedInverseAdjoint.lean b/lean/OAI/Combinatorics/Chromatic/Walls/WeightedInverseAdjoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a2ea85c13f6cf1df5c52218fdaf630ccef8a96d --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/WeightedInverseAdjoint.lean @@ -0,0 +1,193 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Shuffle.HNZeroFactor +import OAI.Combinatorics.Chromatic.GradedAlgebra.StringBackshift + +namespace OAI + +section +namespace ElementaryPositivity.WeightedTorusSeries +open QuantumTorus RawShuffle PowerSeries +noncomputable section +variable {I : Type*} [Fintype I] [DecidableEq I] +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) (P : (I→ℕ) →+ M) +local instance : Ring (Torus v Ω) := Torus.instRing v Ω +local instance : AddCommMonoid (Torus v Ω) := (Torus.instRing v Ω).toAddCommMonoid +local instance : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +lemma convolution_comm_isotropic (f g : (I→ℕ) → R) + (h : ∀d e,f d≠0 → g e≠0 → Ω (P d) (P e)=0) + (h' : ∀d e,g d≠0 → f e≠0 → Ω (P d) (P e)=0) : + convolution v Ω P f g=convolution v Ω P g f := by + classical + funext d + rw [convolution_of_isotropic_support v Ω P f g h, + convolution_of_isotropic_support v Ω P g f h'] + let E : DimensionSplit d ≃ DimensionSplit d := { + toFun:=fun s=>DimensionSplit.ofPair s.right s.left (by rw [add_comm,DimensionSplit.left_add_right]) + invFun:=fun s=>DimensionSplit.ofPair s.right s.left (by rw [add_comm,DimensionSplit.left_add_right]) + left_inv:=by + intro s + funext i + apply Fin.ext + change d i-(d i-(s i).val)=(s i).val + have H:=(s i).isLt + omega + right_inv:=by + intro s + funext i + apply Fin.ext + change d i-(d i-(s i).val)=(s i).val + have H:=(s i).isLt + omega } + apply Fintype.sum_equiv E + intro s + dsimp only [E,Equiv.coe_fn_mk] + rw [DimensionSplit.left_ofPair,DimensionSplit.right_ofPair,mul_comm] + +variable (w : I → ℕ) [Fact (∀i,0f d*↑(v^(2*Ω (P d) m))) q) : + PowerSeries.invOfUnit (push w v Ω P f) 1*C (Torus.X v Ω m)*push w v Ω P f= + C (Torus.X v Ω m)*push w v Ω P q := by + let F:=push w v Ω P f + let X:=C (Torus.X v Ω m) + let Q:=push w v Ω P q + have H : F*(X*Q)=X*F := by + dsimp only [F,X,Q] + rw [←mul_assoc,push_twist w v Ω P hΩ,mul_assoc,←push_convolution,←hq] + have Hi : invOfUnit F 1*F=1 := + PowerSeries.invOfUnit_mul _ 1 (push_constant w v Ω P f hf) + change invOfUnit F 1*X*F=X*Q + calc + _ = invOfUnit F 1*(X*F) := mul_assoc _ _ _ + _ = invOfUnit F 1*(F*(X*Q)) := by rw [H] + _ = _ := by rw [←mul_assoc,Hi,one_mul] +end +end ElementaryPositivity.WeightedTorusSeries + +end +section +namespace ElementaryPositivity.UnitSelections +open SignedMultiplicity RawShuffle EnergyLaurent QuantumTorus WallUnits WeightedTorusSeries +open PowerSeries +noncomputable section +variable {S I : Type*} [Fintype I] [DecidableEq I] +variable (a : S → ℕ) (t : S → ℕ) (dim : S → (I→ℕ)) (k : S → ℤ) +variable (he : ∀d,Admissible (stringEnergy a dim k d)) +variable (D : AddSubmonoid (I→ℕ)) (hdim : ∀s,dim s∈D) +variable (τ : (I→ℕ) →+ ℤ) (hτ : ∀s,(t s:ℤ)=τ (dim s)) +variable {M : Type*} [AddCommGroup M] +variable (Ω : M →+ M →+ ℤ) (P : (I→ℕ) →+ M) +variable (hiso : ∀d∈D,∀e∈D,Ω (P d) (P e)=0) +variable (m : M) (htwist : ∀d,τ d= -Ω (P d) m) + +include hdim hτ hiso htwist in +lemma stringSeries_inverse_convolution : + stringSeries a dim k he= + convolution LaurentRay.vUnit Ω P + (fun d=>stringSeries a dim k he d*↑(LaurentRay.vUnit^(2*Ω (P d) m))) + (stripSeries a t dim (fun s=>k s-2*(t s:ℤ)) τ hτ + (backshiftString_admissible a t dim k τ hτ he)) := by + let hg:=backshiftString_admissible a t dim k τ hτ he + let g:=stringSeries a dim (fun s=>k s-2*(t s:ℤ)) hg + let q:=stripSeries a t dim (fun s=>k s-2*(t s:ℤ)) τ hτ hg + have H : (fun d=>stringSeries a dim k he d*↑(LaurentRay.vUnit^(2*Ω (P d) m)))=g := by + funext d + rw [LaurentRay.vUnit_zpow] + dsimp only [g] + rw [backshiftString_series a t dim k τ hτ he d] + rw [htwist,mul_neg] + rw [H] + change stringSeries a dim k he=convolution LaurentRay.vUnit Ω P g q + have hgs : ∀d,g d≠0 → d∈D := fun d h=>stringSeries_support a dim _ hg D hdim d h + have hqs : ∀d,q d≠0 → d∈D := fun d h=>stripSeries_support a t dim _ hg D hdim τ hτ d h + rw [convolution_comm_isotropic LaurentRay.vUnit Ω P g q + (fun d e hd he=>hiso d (hgs d hd) e (hqs e he)) + (fun d e hd he=>hiso d (hqs d hd) e (hgs e he))] + funext d + rw [convolution_of_isotropic_support LaurentRay.vUnit Ω P q g + (fun d e hd he=>hiso d (hqs d hd) e (hgs e he))] + exact backstripString_series a t dim k τ hτ he d + +variable (w : I → ℕ) [Fact (∀i,0k s-2*(t s:ℤ)) τ hτ + (backshiftString_admissible a t dim k τ hτ he)) := by + exact push_inverse_adjoint_of_convolution LaurentRay.vUnit Ω P w hΩ m _ _ hzero + (stringSeries_inverse_convolution a t dim k he D hdim τ hτ Ω P hiso m htwist) + +include hdim hτ hiso htwist in + +theorem stringSeries_inverse_adjoint_positive (hΩ : ∀x,Ω x x=0) + (hzero : stringSeries a dim k he 0=1) : + IntegralPositive Ω + (invOfUnit (push w LaurentRay.vUnit Ω P (stringSeries a dim k he)) 1* + C (Torus.X LaurentRay.vUnit Ω m)*push w LaurentRay.vUnit Ω P (stringSeries a dim k he)) := by + rw [stringSeries_inverse_adjoint a t dim k he D hdim τ hτ Ω P hiso m htwist w hΩ hzero] + exact (completedPositive_C_X Ω m).mul Ω (push_positive Ω w P _ + (fun d=>LaurentPositive.series _ (stripEnergy_admissible a t dim _ τ hτ + (backshiftString_admissible a t dim k τ hτ he) d))) +end +end ElementaryPositivity.UnitSelections + +end +section +namespace ElementaryPositivity.RawShuffle +open SlopeArithmetic SignedMultiplicity UnitSelections EnergyLaurent +open QuantumTorus WeightedTorusSeries WallUnits PowerSeries +noncomputable section +variable {I : Type*} [Fintype I] [DecidableEq I] +variable (a : I → I → ℕ) (κ : I → ℤ) (c η : I → ℝ) (hc : ∀i,0s.1.val.1.val + let τ : (I→ℕ) →+ ℤ := -((Ω.flip m).comp P) + let t : SlopeStringStart a c η hc θ → ℕ := fun s=>(τ (dim s)).toNat + have hdim : ∀s,dim s∈slopeDimensions c η hc θ := fun s=>s.1.val.1.property + have ht : ∀s,(t s:ℤ)=τ (dim s) := fun s=>Int.toNat_of_nonneg (neg_nonneg.mpr (hm _ (hdim s))) + have hi : ∀d∈slopeDimensions c η hc θ,∀e∈slopeDimensions c η hc θ,Ω (P d) (P e)=0 := by + intro d hd e he + rw [hgeom,eulerForm_slopeDimensions_symm a c η hc θ ⟨d,hd⟩ ⟨e,he⟩,sub_self] + exact stringSeries_inverse_adjoint_positive (slopeStartRowType a c η hc θ) t dim + (slopeStartParameter a κ c η hc θ) (primitiveCountsEnergy_admissible a κ c η hc θ) + (slopeDimensions c η hc θ) hdim τ ht Ω P hi m (fun _=>rfl) w hΩ + (primitiveCountsSeries_zero a κ c η hc θ) + +variable (h : M →+ ℝ) (hh : ∀d,h (P d)=slopeValue c η θ d) +include hΩ hgeom hm hh in + +theorem finiteInput_zero_inverse_adjoint_positive (ε : I → Bool) + (ha : ∀i,a i i=elementaryDiagonal ε i) : + let F := PowerSeriesSplit.zeroFactor (positiveProject LaurentRay.vUnit Ω h) + (zeroProject LaurentRay.vUnit Ω h) (push w LaurentRay.vUnit Ω P (literalInputCoefficient a κ ε)) + IntegralPositive Ω (invOfUnit F 1*C (Torus.X LaurentRay.vUnit Ω m)*F) := by + dsimp only + rw [←literalInput_primitiveFactor a κ c η hc w Ω P hgeom h θ hh ε ha] + exact primitiveFactor_inverse_adjoint_positive a κ c η hc w Ω P hΩ hgeom θ m hm + +end +end ElementaryPositivity.RawShuffle + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Walls/WeightedRay.lean b/lean/OAI/Combinatorics/Chromatic/Walls/WeightedRay.lean new file mode 100644 index 0000000000000000000000000000000000000000..5805df1a00a51f725f1fb85e54e904896f5586bf --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Walls/WeightedRay.lean @@ -0,0 +1,111 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.GradedAlgebra.WeightedTorusSeries +import OAI.Combinatorics.Chromatic.Walls.QuantumTorusRaySeries +import OAI.Combinatorics.Chromatic.GradedAlgebra.NoncommExpand + +namespace OAI + +section +namespace ElementaryPositivity.QuantumTorus +open PowerSeries PowerSeriesDilate +noncomputable section +variable {R M : Type*} [CommRing R] [AddCommGroup M] +variable (v : Rˣ) (Ω : M →+ M →+ ℤ) +local instance weightedRayAddGroup : AddGroup (Torus v Ω) := (Torus.instRing v Ω).toAddGroup + +def weightedRay (w : ℕ) (a : M) (f : PowerSeries R) : PowerSeries (Torus v Ω) := + dilate w (raySeries v Ω a f) + +@[simp] lemma coeff_weightedRay (w : ℕ) (a : M) (f : PowerSeries R) (n : ℕ) : + coeff n (weightedRay v Ω w a f)= + if w∣n then Torus.monomial v Ω ((n/w) • a) (coeff (n/w) f) else 0 := by + rw [weightedRay,coeff_dilate,coeff_raySeries] + +lemma weightedRay_one (w : ℕ) (a : M) : weightedRay v Ω w a 1=1 := by + rw [weightedRay,raySeries_one] + simpa only [map_one] using dilate_C w (R:=Torus v Ω) 1 + +lemma weightedRay_mul (w : ℕ) (hw : 0⟨l,hl.trans h,hx⟩) + +lemma wordLengthFiltration_letter (b : J → A) (i : J) : b i ∈ wordLengthFiltration b 1 := by + simpa only [wordProduct_cons,wordProduct_nil,mul_one] using wordLengthFiltration_word b [i] 1 le_rfl + +lemma wordLengthFiltration_one (b : J → A) (n : ℕ) : (1:A) ∈ wordLengthFiltration b n := + wordLengthFiltration_word b [] n (Nat.zero_le n) + +lemma wordLengthFiltration_mul (b : J → A) {m n : ℕ} {x y : A} + (hx : x ∈ wordLengthFiltration b m) (hy : y ∈ wordLengthFiltration b n) : + x*y ∈ wordLengthFiltration b (m+n) := by + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨l,hl,rfl⟩ := hx + induction hy using Submodule.span_induction with + | mem y hy => + obtain ⟨k,hk,rfl⟩ := hy + rw [← wordProduct_append] + exact wordLengthFiltration_word b (l++k) (m+n) (by simpa using Nat.add_le_add hl hk) + | zero => simpa only [mul_zero] using (wordLengthFiltration b (m+n)).zero_mem + | add x y hx hy hxi hyi => simpa only [mul_add] using (wordLengthFiltration b (m+n)).add_mem hxi hyi + | smul r x hx hxi => simpa only [Algebra.mul_smul_comm] using (wordLengthFiltration b (m+n)).smul_mem r hxi + | zero => simpa only [zero_mul] using (wordLengthFiltration b (m+n)).zero_mem + | add x z hx hz hxi hzi => simpa only [add_mul] using (wordLengthFiltration b (m+n)).add_mem hxi hzi + | smul r x hx hxi => simpa only [Algebra.smul_mul_assoc] using (wordLengthFiltration b (m+n)).smul_mem r hxi + +lemma wordLengthFiltration_span_range (b : J → A) : + Submodule.span ℚ (Set.range b) ≤ wordLengthFiltration b 1 := by + apply Submodule.span_le.mpr + rintro x ⟨i,rfl⟩ + exact wordLengthFiltration_letter b i + +lemma adjoin_le_span_words (b : J → A) : + (Algebra.adjoin ℚ (Set.range b)).toSubmodule ≤ + Submodule.span ℚ (Set.range (wordProduct b)) := by + let S := Submodule.span ℚ (Set.range (wordProduct b)) + have hm : ∀ x∈S,∀ y∈S,x*y∈S := by + intro x hx y hy + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨l,rfl⟩ := hx + induction hy using Submodule.span_induction with + | mem y hy => + obtain ⟨k,rfl⟩ := hy + rw [←wordProduct_append] + exact Submodule.subset_span ⟨l++k,rfl⟩ + | zero => simpa only [mul_zero] using S.zero_mem + | add x y hx hy hxi hyi => simpa only [mul_add] using S.add_mem hxi hyi + | smul r x hx hxi => simpa only [Algebra.mul_smul_comm] using S.smul_mem r hxi + | zero => simpa only [zero_mul] using S.zero_mem + | add x z hx hz hxi hzi => simpa only [add_mul] using S.add_mem hxi hzi + | smul r x hx hxi => simpa only [Algebra.smul_mul_assoc] using S.smul_mem r hxi + let T : Subalgebra ℚ A := + { S with + one_mem' := Submodule.subset_span ⟨[],rfl⟩ + mul_mem' := fun hx hy=>hm _ hx _ hy + algebraMap_mem' := fun r=>by + rw [Algebra.algebraMap_eq_smul_one] + exact S.smul_mem r (Submodule.subset_span ⟨[],rfl⟩) } + have h : Algebra.adjoin ℚ (Set.range b) ≤ T := by + apply Algebra.adjoin_le + rintro x ⟨i,rfl⟩ + change b i∈S + have hi : wordProduct b [i]∈S := Submodule.subset_span ⟨[i],rfl⟩ + simpa only [wordProduct_cons,wordProduct_nil,mul_one] using hi + exact h + +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Witness/ElementaryAlphabetRigidity.lean b/lean/OAI/Combinatorics/Chromatic/Witness/ElementaryAlphabetRigidity.lean new file mode 100644 index 0000000000000000000000000000000000000000..34423afdca4c9fae2b5883fdfff136ef4ca70a91 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Witness/ElementaryAlphabetRigidity.lean @@ -0,0 +1,159 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Witness.HistoryMainWitness + +namespace OAI + +section +namespace ElementaryPositivity.ElementaryRigidity +open scoped BigOperators +open Classical +noncomputable section +variable {n r:ℕ} {R S:Type*} [CommSemiring R] [CommSemiring S] + +def eval (n r:ℕ) (R:Type*) [CommSemiring R] : + MvPolynomial (Fin n) R →+* MvPolynomial (Fin r) R := + MvPolynomial.eval₂Hom MvPolynomial.C (fun i=>MvPolynomial.esymm (Fin r) R (i.val+1)) + +def partitionPolynomial (lam:Nat.Partition n) : MvPolynomial (Fin n) R := + (lam.parts.attach.map (fun k=>MvPolynomial.X (⟨k.val-1,by + have hp:=lam.parts_pos k.property + have hb:=lam.le_of_mem_parts k.property + omega⟩:Fin n))).prod + +lemma eval_partition (lam:Nat.Partition n) (r:ℕ) : + eval n r R (partitionPolynomial (R:=R) lam)=MvPolynomial.esymmPart (Fin r) R lam := by + unfold partitionPolynomial MvPolynomial.esymmPart + rw [map_multiset_prod,Multiset.map_map] + have he:∀k:{k // k∈lam.parts}, + eval n r R (MvPolynomial.X (⟨k.val-1,by + have hp:=lam.parts_pos k.property + have hb:=lam.le_of_mem_parts k.property + omega⟩:Fin n))=MvPolynomial.esymm (Fin r) R k.val:=by + intro k + simp only [eval,MvPolynomial.eval₂Hom_X'] + rw [Nat.sub_add_cancel (lam.parts_pos k.property)] + simp_rw [Function.comp_def,he] + have H:=congrArg (fun l:Multiset ℕ=>(l.map (MvPolynomial.esymm (Fin r) R)).prod) + (Multiset.attach_map_val lam.parts) + simpa only [Multiset.map_map,Function.comp_def] using H + +lemma map_eval (f:R →+* S) (p:MvPolynomial (Fin n) R) : + MvPolynomial.map f (eval n r R p)=eval n r S (MvPolynomial.map f p) := by + unfold eval + rw [MvPolynomial.map_eval₂Hom,MvPolynomial.eval₂Hom_map_hom] + simp only [MvPolynomial.map_esymm] + congr 2 + ext x + simp + +lemma eval_injective_ring (R:Type*) [CommRing R] (n:ℕ) : Function.Injective (eval n n R) := by + intro p q h + apply MvPolynomial.esymmAlgHom_fin_injective R le_rfl + apply Subtype.ext + rw [MvPolynomial.esymmAlgHom_apply,MvPolynomial.esymmAlgHom_apply] + exact h + +lemma eval_injective_natPolynomial (n:ℕ) : Function.Injective (eval n n (Polynomial ℕ)) := by + let f:Polynomial ℕ →+* Polynomial ℤ:=Polynomial.mapRingHom (Nat.castRingHom ℤ) + have hf:Function.Injective f:=Polynomial.map_injective (Nat.castRingHom ℤ) (by intro a b h; change (a:ℤ)=(b:ℤ) at h; exact Int.ofNat_inj.mp h) + intro p q h + apply MvPolynomial.map_injective f hf + apply eval_injective_ring (Polynomial ℤ) n + rw [←map_eval,←map_eval,h] + +lemma eval_C (x:R) : eval n r R (MvPolynomial.C x)=MvPolynomial.C x := + MvPolynomial.eval₂Hom_C _ _ _ + +lemma uniform_of_at_n {A:Type*} [Fintype A] (E:A → ℕ) + (lam μ:A → Nat.Partition n) + (h:(∑a,MvPolynomial.C (Polynomial.X^E a)*MvPolynomial.esymmPart (Fin n) (Polynomial ℕ) (lam a))= + ∑a,MvPolynomial.C (Polynomial.X^E a)*MvPolynomial.esymmPart (Fin n) (Polynomial ℕ) (μ a)) + (r:ℕ) : + (∑a,MvPolynomial.C (Polynomial.X^E a)*MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (lam a))= + ∑a,MvPolynomial.C (Polynomial.X^E a)*MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (μ a) := by + have he:(∑a,MvPolynomial.C (Polynomial.X^E a)*partitionPolynomial (R:=Polynomial ℕ) (lam a))= + ∑a,MvPolynomial.C (Polynomial.X^E a)*partitionPolynomial (R:=Polynomial ℕ) (μ a):=by + apply eval_injective_natPolynomial n + simpa only [map_sum,map_mul,eval_partition,eval_C] using h + have H:=congrArg (eval n r (Polynomial ℕ)) he + simpa only [map_sum,map_mul,eval_partition,eval_C] using H +end +end ElementaryPositivity.ElementaryRigidity + +end +section +namespace ElementaryPositivity.FiniteSearch +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) + +lemma test_of_expansion (t:Table n) + (h:G.chromatic n=∑σ:{σ:Equiv.Perm (Fin n) // G.Nondescent σ}, + MvPolynomial.C (Polynomial.X^G.graphInversions σ.val)* + MvPolynomial.esymmPart (Fin n) (Polynomial ℕ) (rowPartition (t σ.val))) : Test G t := by + intro a k + let af:Fin n →₀ ℕ:=Finsupp.equivFunOnFinite.symm (fun c=>(a c).val) + have H:=congrArg (fun p:MvPolynomial (Fin n) (Polynomial ℕ)=>(p.coeff af).coeff k.val) h + rw [chromatic_coefficient,witness_coefficient] at H + exact H + +lemma expansion_of_test (t:Table n) (ht:Test G t) : + G.chromatic n=∑σ:{σ:Equiv.Perm (Fin n) // G.Nondescent σ}, + MvPolynomial.C (Polynomial.X^G.graphInversions σ.val)* + MvPolynomial.esymmPart (Fin n) (Polynomial ℕ) (rowPartition (t σ.val)) := by + apply MvPolynomial.ext + intro a + by_cases ha:a.degree=n + · apply Polynomial.ext + intro k + rw [chromatic_coefficient,witness_coefficient] + by_cases hk:k≤G.edgeCount + · let af:Fin n → Fin (n+1):=fun c=>⟨a c,by have H:=Finsupp.le_degree c a; omega⟩ + exact ht af ⟨k,Nat.lt_succ_of_le hk⟩ + · rw [colorCount_zero_high G a k (by omega),witnessCount_zero_high G t a k (by omega)] + · rw [chromatic_degree_zero G a ha,MvPolynomial.coeff_sum] + symm + apply Finset.sum_eq_zero + intro σ hσ + rw [MvPolynomial.coeff_C_mul,row_degree_zero _ _ ha,mul_zero] + +lemma uniform_expansion_of_test (W:G.PermutationWitness) (t:Table n) (ht:Test G t) (r:ℕ) : + G.chromatic r=∑σ:{σ:Equiv.Perm (Fin n) // G.Nondescent σ}, + MvPolynomial.C (Polynomial.X^G.graphInversions σ.val)* + MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (rowPartition (t σ.val)) := by + trans ∑σ:{σ:Equiv.Perm (Fin n) // G.Nondescent σ}, + MvPolynomial.C (Polynomial.X^G.graphInversions σ.val)* + MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (W.theta σ) + · exact W.expansion r + · apply ElementaryRigidity.uniform_of_at_n + (fun σ:{σ:Equiv.Perm (Fin n) // G.Nondescent σ}=>G.graphInversions σ.val) + W.theta (fun σ=>rowPartition (t σ.val)) + trans G.chromatic n + · exact (W.expansion n).symm + · exact expansion_of_test G t ht + +lemma exists_test (W:G.PermutationWitness) : ∃t:Table n,Test G t := by + let p0:Nat.Partition n:=Nat.Partition.ofSums n {n} (by simp) + let p:(Fin n → Fin n) → Nat.Partition n:=fun w=> + if hw:WordOK G w then W.theta ⟨Equiv.ofBijective w hw.1,hw.2⟩ else p0 + let t:Table n:=fun w=>Classical.choose (rowPartition_surjective n (p w)) + have he:∀σ:{σ:Equiv.Perm (Fin n) // G.Nondescent σ},rowPartition (t σ.val)=W.theta σ:=by + intro σ + have H:rowPartition (t σ.val)=p σ.val:=Classical.choose_spec (rowPartition_surjective n (p σ.val)) + rw [H] + have hp:WordOK G σ.val:=⟨σ.val.bijective,σ.property⟩ + dsimp only [p] + rw [dite_eq_left hp] + congr 1 + apply Subtype.ext + exact Equiv.ext (fun _=>rfl) + refine ⟨t,test_of_expansion G t ?_⟩ + simp_rw [he] + exact W.expansion n +end +end ElementaryPositivity.FiniteSearch + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Witness/ElementaryProductDegree.lean b/lean/OAI/Combinatorics/Chromatic/Witness/ElementaryProductDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..c77152876febb726b3c20d67ba2eb11241f964d7 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Witness/ElementaryProductDegree.lean @@ -0,0 +1,144 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Witness.ProfilePartition +import OAI.Combinatorics.Chromatic.Walls.LaurentPolynomialEnergy + +namespace OAI + +section +namespace ElementaryPositivity.ElementaryMatrix +open scoped BigOperators +open Classical +noncomputable section +variable {A B:Type*} [Fintype A] [Fintype B] [DecidableEq A] [DecidableEq B] +omit [Fintype A] [DecidableEq A] [DecidableEq B] in +lemma colCount_degree (s:B → Finset A) : (colCount s).degree=(rowCount s).degree := by + simp only [colCount,map_sum,Finsupp.degree_single,Finset.sum_const,smul_eq_mul,mul_one] + rw [Finsupp.degree_eq_sum] + rfl + +lemma elementary_product_coeff_zero {R:Type*} [CommSemiring R] + (μ:A →₀ ℕ) (a:B →₀ ℕ) (h:a.degree≠μ.degree) : + (∏i:A,MvPolynomial.esymm B R (μ i)).coeff a=0 := by + rw [elementary_product_coeff] + apply Finset.sum_eq_zero + intro s hs + rw [ite_eq_right] + rintro ⟨hr,hc⟩ + exact h (by rw [←hc,colCount_degree,hr]) +end +end ElementaryPositivity.ElementaryMatrix + +end +section +namespace ElementaryPositivity.Packets +open scoped BigOperators +variable {n:ℕ} {A R:Type*} [Fintype A] [LinearOrder A] [CommSemiring R] +omit [Fintype A] [LinearOrder A] in +lemma coloring_monomial (κ:Fin n → A) : + (∏i:Fin n,MvPolynomial.X (κ i):MvPolynomial A R)=MvPolynomial.monomial (wordCount κ) 1 := by + rw [wordCount,MvPolynomial.monomial_sum_one] + rfl +end ElementaryPositivity.Packets +namespace ElementaryPositivity.NaturalUnitIntervalGraph +open Packets +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) +lemma inversion_coefficient (r:ℕ) (a:Fin r →₀ ℕ) : + (G.inversionChromatic r).coeff a= + ∑κ:Fin n → Fin r,if G.Proper κ ∧ wordCount κ=a then + (Polynomial.X^G.coloringInversions κ:Polynomial ℕ) else 0 := by + unfold inversionChromatic + rw [MvPolynomial.coeff_sum,Finset.sum_filter] + apply Finset.sum_congr rfl + intro κ hκ + by_cases hp:G.Proper κ + · simp only [hp,ite_true,true_and,coloring_monomial,MvPolynomial.coeff_C_mul,MvPolynomial.coeff_monomial] + split_ifs <;> simp + · simp [hp] +lemma inversion_coefficient_zero (r:ℕ) (a:Fin r →₀ ℕ) (ha:a.degree≠n) : + (G.inversionChromatic r).coeff a=0 := by + rw [inversion_coefficient] + apply Finset.sum_eq_zero + intro κ hκ + rw [ite_eq_right] + rintro ⟨_,he⟩ + exact ha (he ▸ wordCount_degree κ) +end +end ElementaryPositivity.NaturalUnitIntervalGraph + +end +section +namespace ElementaryPositivity.TriangularDynamics +open Packets WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) + +lemma decorated_polynomial_expansion (r:ℕ) : G.inversionChromatic r= + ∑d:DecoratedLeaf G,MvPolynomial.C (Polynomial.X^leafEnergy G d)* + MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (leafPartition G d) := by + apply MvPolynomial.ext + intro a + simp only [MvPolynomial.coeff_sum,MvPolynomial.coeff_C_mul,leafPartition,esymmPart_profile] + by_cases ha:a.degree=n + · apply LaurentPositive.centered_injective G.edgeCount + rw [G.inversion_coefficient,LaurentPositive.centered_sum,LaurentPositive.centered_sum] + simp only [LaurentPositive.centered_mul,LaurentPositive.map_elementary_coeff, + LaurentPositive.centered_X_pow] + have he:∀κ:Fin n → Fin r, wordCount κ=a ↔ ∀c,(Finset.univ.filter (fun j=>κ j=c)).card=a c:=by + intro κ + constructor + · intro h c; rw [←h,wordCount_apply] + · intro h; ext c; rw [wordCount_apply]; exact h c + simp only [apply_ite,LaurentPositive.centered_X_pow,LaurentPositive.centered_zero,he] + exact decorated_coefficient G r a ha + · rw [G.inversion_coefficient_zero r a ha] + symm + apply Finset.sum_eq_zero + intro d hd + rw [ElementaryMatrix.elementary_product_coeff_zero _ _ (by simpa only [historyProfile_degree] using ha),mul_zero] + +lemma admissible_polynomial_expansion (r:ℕ) : G.inversionChromatic r= + ∑w:{w:Equiv.Perm (Fin n) // G.Admissible w}, + MvPolynomial.C (Polynomial.X^G.graphInversions w.val)* + MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (admissiblePartition G w) := by + rw [decorated_polynomial_expansion,←Equiv.sum_comp (admissibleHistoryEquiv G)] + apply Finset.sum_congr rfl + intro w hw + rw [admissibleHistoryEquiv_energy] + rfl +end +end ElementaryPositivity.TriangularDynamics + +end +section +namespace ElementaryPositivity.NaturalUnitIntervalGraph +open scoped BigOperators +variable {n:ℕ} (G:ElementaryPositivity.NaturalUnitIntervalGraph n) + +def ofAdmissibleWitness + (lam:{w:Equiv.Perm (Fin n) // G.Admissible w} → Nat.Partition n) + (hexp:∀r:ℕ,G.inversionChromatic r= + ∑w:{w:Equiv.Perm (Fin n) // G.Admissible w}, + MvPolynomial.C (Polynomial.X^G.graphInversions w.val)* + MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (lam w)) : G.PermutationWitness where + theta σ:=lam (G.reversalEquiv σ) + expansion r:=by + rw [←G.reflect_inversionChromatic r,hexp r,map_sum] + rw [←Equiv.sum_comp G.reversalEquiv] + apply Finset.sum_congr rfl + intro σ hσ + rw [CoefficientReflection.reflect_C_X_pow_mul_esymmPart _ _ _ (G.graphInversions_le_edges _)] + congr 2 + congr 1 + change G.edgeCount-G.graphInversions (reversePerm σ.val)=G.graphInversions σ.val + have H:=G.graphInversions_add_reverse σ.val + omega +end ElementaryPositivity.NaturalUnitIntervalGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Witness/ElementarySingletonCoefficient.lean b/lean/OAI/Combinatorics/Chromatic/Witness/ElementarySingletonCoefficient.lean new file mode 100644 index 0000000000000000000000000000000000000000..c135958bcfe18318d28ab8651166ba28eb06b708 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Witness/ElementarySingletonCoefficient.lean @@ -0,0 +1,116 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Histories.GraphCommonHistory +import OAI.Combinatorics.Chromatic.Walls.LaurentFiniteDecorations + +namespace OAI + +section +namespace ElementaryPositivity.ElementaryMatrix +open scoped BigOperators +open Classical +noncomputable section +variable {A:Type*} [Fintype A] [DecidableEq A] +variable {R:Type*} [CommSemiring R] + +def allOnes (n:ℕ) : Fin n →₀ ℕ:=Finsupp.equivFunOnFinite.symm (fun _=>1) +lemma allOnes_apply (n:ℕ) (i:Fin n) : allOnes n i=1:=rfl +lemma allOnes_degree (n:ℕ) : (allOnes n).degree=n := by + change (allOnes n).sum (fun _ k=>k)=n + rw [Finsupp.sum_fintype _ _ (fun _=>rfl)] + simp [allOnes_apply] + +lemma singleton_coefficient {n:ℕ} (μ:A →₀ ℕ) (hμ:μ.degree=n) : + (∏i:A,MvPolynomial.esymm (Fin n) R (μ i)).coeff (allOnes n)=(μ.multinomial:R) := by + rw [duality] + simp only [allOnes_apply,MvPolynomial.esymm_one,Finset.prod_const,Finset.card_univ,Fintype.card_fin] + change μ.sum (fun _ k=>k)=n at hμ + rw [MvPolynomial.coeff_sum_X_pow_of_fintype,ite_eq_left hμ] + +omit [Fintype A] [DecidableEq A] in +lemma profile_multinomial_pos (μ:A →₀ ℕ) : 0<μ.multinomial := Nat.multinomial_pos _ _ +end +end ElementaryPositivity.ElementaryMatrix + +end +section +namespace ElementaryPositivity.TriangularDynamics +open QuantumTorus WallUnits LatticeExtension LatticeRealization +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) + +def historyDimension : ℕ:=(graph_common_history G).choose + +def historySyntax : LocalHistoryFormula (Extended (Vertex (historyDimension G) (Cell (historyDimension G)))) + ((Vertex (historyDimension G) (Cell (historyDimension G)) → ℝ) × + (Vertex (historyDimension G) (Cell (historyDimension G)) → ℝ)) := + (graph_common_history G).choose_spec.choose + +lemma historySyntax_positive : (historySyntax G).Positive + (extendedOmega (historyDimension G)) (extendedRoots (historyDimension G)) extendedCast + (simpleTotalTransport (extendedOmega (historyDimension G)) (extendedRoots (historyDimension G))) := + (graph_common_history G).choose_spec.choose_spec.1 + +abbrev HistoryLeaf := {l:(historySyntax G).Leaf // AnchoredLeaf n (historySyntax G) l} +def historyProfile (l:HistoryLeaf G) := leafProfile n (historySyntax G) l +lemma historyProfile_degree (l:HistoryLeaf G) : (historyProfile G l).degree=n := + leafProfile_degree n (historySyntax G) l +lemma historyProfile_dominant (l:HistoryLeaf G) : + ∀i:Fin (historyDimension G),historyProfile G l i.succ≤historyProfile G l i.castSucc := + leafProfile_dominant n (historySyntax G) l + +def historyWeight (l:HistoryLeaf G) : LaurentSeries ℚ:= + (historySyntax G).leafWeight (extendedOmega (historyDimension G)) (extendedRoots (historyDimension G)) + extendedCast (simpleTotalTransport (extendedOmega (historyDimension G)) + (extendedRoots (historyDimension G))) l.val +lemma historyWeight_positive (l:HistoryLeaf G) : LaurentPositive.Positive (historyWeight G l):= + (historySyntax G).leafWeight_positive _ _ _ _ (historySyntax_positive G) l.val + +lemma history_coefficient (r:ℕ) (a:Fin r →₀ ℕ) (ha:a.degree=n) : + (∑κ:Fin n → Fin r, + if G.Proper κ ∧ (∀i,(Finset.univ.filter (fun j=>κ j=i)).card=a i) then + (↑(LaurentRay.vUnit^(2*(G.coloringInversions κ:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ) else 0)= + ∑l:HistoryLeaf G,historyWeight G l * + (∏i:Fin (historyDimension G+1),MvPolynomial.esymm (Fin r) (LaurentSeries ℚ) + (historyProfile G l i)).coeff a := + (graph_common_history G).choose_spec.choose_spec.2 r a ha + +lemma history_singleton : + (∑κ:Fin n → Fin n, + if G.Proper κ ∧ (∀i,(Finset.univ.filter (fun j=>κ j=i)).card=1) then + (↑(LaurentRay.vUnit^(2*(G.coloringInversions κ:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ) else 0)= + ∑l:HistoryLeaf G,historyWeight G l*(historyProfile G l).multinomial := by + have he:=history_coefficient G n (ElementaryMatrix.allOnes n) (ElementaryMatrix.allOnes_degree n) + simp only [ElementaryMatrix.allOnes_apply] at he + apply he.trans + apply Finset.sum_congr rfl + intro l hl + rw [ElementaryMatrix.singleton_coefficient _ (historyProfile_degree G l)] + +lemma historyWeight_support (l:HistoryLeaf G) (j:ℤ) (hj:(historyWeight G l).coeff j≠0) : + ∃k:Fin (G.edgeCount+1),j=(G.edgeCount:ℤ)-2*(k.val:ℤ) := by + apply LaurentPositive.support_of_positive_sum (historyWeight G) (historyWeight_positive G) + (fun l=>(historyProfile G l).multinomial) + (fun l=>ElementaryMatrix.profile_multinomial_pos _) _ _ l j hj + intro j hn + rw [←history_singleton G,HahnSeries.coeff_sum] + apply Finset.sum_eq_zero + intro κ hκ + split_ifs + · rw [LaurentRay.vUnit_zpow] + apply HahnSeries.coeff_single_of_ne + intro he + apply hn + refine ⟨⟨G.coloringInversions κ,by + have H:G.coloringInversions κ≤G.edgeCount:=Finset.card_le_card (Finset.filter_subset _ _) + omega⟩,?_⟩ + change j=(G.edgeCount:ℤ)-2*(G.coloringInversions κ:ℤ) + omega + · rfl +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Witness/GraphDecoratedHistories.lean b/lean/OAI/Combinatorics/Chromatic/Witness/GraphDecoratedHistories.lean new file mode 100644 index 0000000000000000000000000000000000000000..14720bc9b455b94deb5220716bd3b9d9d32f7441 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Witness/GraphDecoratedHistories.lean @@ -0,0 +1,101 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Witness.ElementarySingletonCoefficient +import OAI.Combinatorics.Chromatic.Witness.GraphRequiredPackets +import OAI.Combinatorics.Chromatic.Histories.PacketSortedWords + +namespace OAI + +section +namespace ElementaryPositivity +open WallUnits +open scoped BigOperators +open Classical +noncomputable section +lemma sum_subtype_ite {A R:Type*} [Fintype A] [AddCommMonoid R] (P:A → Prop) [DecidablePred P] (f:A → R) : + (∑a:{a // P a},f a.val)=∑a,if P a then f a else 0 := by + rw [←Finset.sum_filter] + exact (Finset.sum_subtype _ (by simp) f).symm +end +namespace TriangularDynamics +open Packets +open WallUnits +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) + +abbrev DecoratedLeaf:=Σl:HistoryLeaf G, + LaurentPositive.Decoration (historyWeight G l) (historyWeight_positive G l) G.edgeCount + +def leafEnergy (d:DecoratedLeaf G):ℕ:=d.2.1.val +abbrev DecoratedWord:=Σd:DecoratedLeaf G,AnchorWord (n:=n) (historyProfile G d.1) +def decoratedMask (w:DecoratedWord G):Finset (Fin (n-1)):=ascentMask (·<·) w.2.val +def decoratedEnergy (w:DecoratedWord G):ℕ:=leafEnergy G w.1 +abbrev RequiredDecorated (J:Finset (Fin (n-1))):={w:DecoratedWord G // J⊆decoratedMask G w} + +def requiredDecoratedEquiv (J:Finset (Fin (n-1))) : RequiredDecorated G J ≃ + Σd:DecoratedLeaf G,RequiredAnchor (n:=n) (historyProfile G d.1) J where + toFun w:=⟨w.val.1,⟨w.val.2.val,w.val.2.property,w.property⟩⟩ + invFun w:=⟨⟨w.1,⟨w.2.val,w.2.property.1⟩⟩,w.2.property.2⟩ + left_inv _:=rfl + right_inv _:=rfl + +lemma decorated_coefficient (r:ℕ) (a:Fin r →₀ ℕ) (ha:a.degree=n) : + (∑κ:Fin n → Fin r, + if G.Proper κ ∧ (∀i,(Finset.univ.filter (fun j=>κ j=i)).card=a i) then + (↑(LaurentRay.vUnit^(2*(G.coloringInversions κ:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ) else 0)= + ∑d:DecoratedLeaf G,(↑(LaurentRay.vUnit^(2*(leafEnergy G d:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ) * + (∏i:Fin (historyDimension G+1),MvPolynomial.esymm (Fin r) (LaurentSeries ℚ) + (historyProfile G d.1 i)).coeff a := by + rw [history_coefficient G r a ha] + symm + rw [Fintype.sum_sigma] + apply Finset.sum_congr rfl + intro l hl + change (∑d:LaurentPositive.Decoration (historyWeight G l) (historyWeight_positive G l) G.edgeCount, + (↑(LaurentRay.vUnit^(2*(d.1.val:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ)* + (∏i:Fin (historyDimension G+1),MvPolynomial.esymm (Fin r) (LaurentSeries ℚ) + (historyProfile G l i)).coeff a)=_ + rw [←Finset.sum_mul,←LaurentPositive.decoration_expansion _ _ _ (historyWeight_support G l)] + +lemma required_energy_sum (J:Finset (Fin (n-1))) : + (∑w:G.RequiredWord J, + (↑(LaurentRay.vUnit^(2*(G.graphInversions w.val:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ))= + ∑w:RequiredDecorated G J, + (↑(LaurentRay.vUnit^(2*(decoratedEnergy G w.val:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ) := by + have hc:(∑w:G.RequiredWord J, + (↑(LaurentRay.vUnit^(2*(G.graphInversions w.val:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ))= + ∑κ:G.PacketColor J, + (↑(LaurentRay.vUnit^(2*(G.coloringInversions κ.val:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ):=by + rw [←Equiv.sum_comp (G.requiredColorEquiv J)] + apply Finset.sum_congr rfl + intro w hw + rw [G.requiredColorEquiv_energy] + rw [hc] + change (∑κ:{κ:Fin n → Fin (n+1) // G.Proper κ ∧ ∀c,card κ c=card (index J) c}, + (↑(LaurentRay.vUnit^(2*(G.coloringInversions κ.val:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ))=_ + rw [sum_subtype_ite (fun κ:Fin n → Fin (n+1)=>G.Proper κ ∧ ∀c,card κ c=card (index J) c) + (fun κ=>(↑(LaurentRay.vUnit^(2*(G.coloringInversions κ:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ))] + have hd:=decorated_coefficient G (n+1) (packetProfile J) (packetProfile_degree J) + simp only [packetProfile_apply] at hd + change (∑κ:Fin n → Fin (n+1),if G.Proper κ ∧ (∀i,card κ i=card (index J) i) then + (↑(LaurentRay.vUnit^(2*(G.coloringInversions κ:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ) else 0)=_ at hd + apply hd.trans + rw [←Equiv.sum_comp (requiredDecoratedEquiv G J).symm] + conv_rhs => rw [Fintype.sum_sigma] + apply Finset.sum_congr rfl + intro d hd + rw [requiredAnchor_card] + change (↑(LaurentRay.vUnit^(2*(leafEnergy G d:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ)* + (Fintype.card (RequiredAnchor (historyProfile G d.1) J):LaurentSeries ℚ)= + ∑y:RequiredAnchor (historyProfile G d.1) J, + (↑(LaurentRay.vUnit^(2*(leafEnergy G d:ℤ)-(G.edgeCount:ℤ))):LaurentSeries ℚ) + simp [mul_comm] + +end +end TriangularDynamics +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Witness/GraphRequiredPackets.lean b/lean/OAI/Combinatorics/Chromatic/Witness/GraphRequiredPackets.lean new file mode 100644 index 0000000000000000000000000000000000000000..f5267d4d942ea99ac6d67f6644ccd38e628078c5 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Witness/GraphRequiredPackets.lean @@ -0,0 +1,120 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.QuantumTorus.Admissible +import OAI.Combinatorics.Chromatic.Histories.SortedFiberPerm + +namespace OAI + +section +namespace ElementaryPositivity.NaturalUnitIntervalGraph +open Packets +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) + +def nonedgeLT (a b:Fin n):Prop:=aindex J (w.symm a)):=by + intro a b hab he + rcases lt_trichotomy (w.symm a) (w.symm b) with h|h|h + · have H:=inside_of_required G.nonedgeLT G.nonedgeLT_trans J w hw _ _ h he + exact H.2 (by simpa only [w.apply_symm_apply] using hab) + · have hh:a=b:=w.symm.injective h + subst b + exact G.edge_irrefl a hab + · have H:=inside_of_required G.nonedgeLT G.nonedgeLT_trans J w hw _ _ h he.symm + exact H.2 (by simpa only [w.apply_symm_apply] using (G.edge_comm a b).mp hab) + +lemma required_of_sorted (J:Finset (Fin (n-1))) (κ:Fin n → Fin (n+1)) + (hκ:G.Proper κ) (w:Equiv.Perm (Fin n)) (hw:∀i,κ (w i)=index J i) + (hs:Sorted (index J) w) : J⊆G.wordMask w := by + intro t ht + apply (mem_ascentMask _ _ _).mpr + have he:index J (left t)=index J (right t):=(index_left_right J t).mpr ht + refine ⟨hs _ _ he (by change t.valindex J (w.val.symm a),G.required_proper J w.val w.property, + fun c=>(card_of_perm (index J) (fun a=>index J (w.val.symm a)) w.val (by intro i; simp) c).symm⟩ + invFun κ:=⟨sortedPerm (index J) κ.val (fun c=>(κ.property.2 c).symm), + G.required_of_sorted J κ.val κ.property.1 _ (sortedPerm_map _ _ _) (sortedPerm_sorted _ _ _)⟩ + left_inv w:=by + apply Subtype.ext + change sortedPerm (index J) (fun a=>index J (w.val.symm a)) _=w.val + apply sorted_unique (index J) (fun a=>index J (w.val.symm a)) + · exact sortedPerm_map (index J) (fun a=>index J (w.val.symm a)) _ + · intro i; simp + · exact sortedPerm_sorted (index J) (fun a=>index J (w.val.symm a)) _ + · exact G.required_sorted _ _ w.property + right_inv κ:=by + apply Subtype.ext + funext a + have H:=sortedPerm_map (index J) κ.val (fun c=>(κ.property.2 c).symm) + ((sortedPerm (index J) κ.val (fun c=>(κ.property.2 c).symm)).symm a) + simpa only [Equiv.apply_symm_apply] using H.symm + +lemma packet_energy (J:Finset (Fin (n-1))) (κ:Fin n → Fin (n+1)) + (hκ:G.Proper κ) (w:Equiv.Perm (Fin n)) (hw:∀i,κ (w i)=index J i) : + G.coloringInversions κ=G.graphInversions w := by + rw [G.graphInversions_eq_card_invertedEdges,coloringInversions,invertedEdges] + congr 1 + apply Finset.filter_congr + intro ab hab + have hedge:G.Edge ab.1 ab.2:=(Finset.mem_filter.mp hab).2.2 + have hne:κ ab.1≠κ ab.2:=hκ _ _ hedge + have hcolor:∀a,κ a=index J (w.symm a):=fun a=>by simpa using hw (w.symm a) + rw [hcolor ab.1,hcolor ab.2] at hne ⊢ + constructor + · intro h + by_contra hn + exact (not_lt_of_ge (index_mono J (le_of_not_gt hn))) h + · intro h + exact lt_of_le_of_ne (index_mono J h.le) hne.symm + +lemma requiredColorEquiv_energy (J:Finset (Fin (n-1))) (w:G.RequiredWord J) : + G.coloringInversions (G.requiredColorEquiv J w).val=G.graphInversions w.val:=by + apply G.packet_energy J _ (G.required_proper J w.val w.property) w.val + intro i + simp +end +end ElementaryPositivity.NaturalUnitIntervalGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Witness/HistoryMainWitness.lean b/lean/OAI/Combinatorics/Chromatic/Witness/HistoryMainWitness.lean new file mode 100644 index 0000000000000000000000000000000000000000..8821ea02ab4f7b80dda62c9bbad26f02859c0519 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Witness/HistoryMainWitness.lean @@ -0,0 +1,211 @@ +import Mathlib +import OAI.Combinatorics.Chromatic.Witness.ElementaryProductDegree + +namespace OAI + +section +namespace ElementaryPositivity.NaturalUnitIntervalGraph + +noncomputable def historyWitness {n:ℕ} (G:ElementaryPositivity.NaturalUnitIntervalGraph n) : G.PermutationWitness:= + G.ofAdmissibleWitness (TriangularDynamics.admissiblePartition G) + (TriangularDynamics.admissible_polynomial_expansion G) +end ElementaryPositivity.NaturalUnitIntervalGraph + +end +section +namespace ElementaryPositivity.FiniteSearch +open scoped BigOperators + +abbrev Row (n:ℕ):={v:Fin n → Fin (n+1) // ∑i,(v i).val=n} + +def rowPartition {n:ℕ} (v:Row n):Nat.Partition n:= + Nat.Partition.ofSums n (Finset.univ.val.map (fun i=>(v.val i).val)) v.property + +lemma rowPartition_surjective (n:ℕ) : Function.Surjective (@rowPartition n) := by + intro p + obtain ⟨l,hl⟩:=Quotient.exists_rep p.parts + have hl':(l:Multiset ℕ)=p.parts:=hl + have hsum:l.sum=n:=by simpa only [←hl',Multiset.sum_coe] using p.parts_sum + have hpos:∀i∈l,0 < i:=by intro i hi; exact p.parts_pos (by simpa only [←hl',Multiset.mem_coe] using hi) + have hlen:l.length≤n:=hsum ▸ List.length_le_sum_of_one_le l hpos + let L:=l++List.replicate (n-l.length) 0 + have hL:L.length=n:=by simp [L]; omega + have hbL:∀x∈L,x≤n:=by + intro x hx + simp only [L,List.mem_append,List.mem_replicate] at hx + rcases hx with hx|⟨_,hx⟩ + · exact p.le_of_mem_parts (by simpa only [←hl',Multiset.mem_coe] using hx) + · omega + let v:Fin n → Fin (n+1):=fun i=>⟨L[i.val]'(by omega), + Nat.lt_succ_of_le (hbL _ (List.getElem_mem (by omega)))⟩ + have hv:List.ofFn (fun i:Fin n=>(v i).val)=L:=by + apply List.ext_getElem + · simp [hL] + · intro i hi hj + simp only [List.getElem_ofFn] + rfl + have hm:(Finset.univ.val.map (fun i:Fin n=>(v i).val):Multiset ℕ)=L:=by + rw [Finset.val_univ_fin] + change (List.map (fun i:Fin n=>(v i).val) (List.finRange n):Multiset ℕ)=_ + rw [←List.ofFn_eq_map,hv] + have hvsum:(∑i:Fin n,(v i).val)=n:=by + change (Finset.univ.val.map (fun i:Fin n=>(v i).val)).sum=n + rw [hm,Multiset.sum_coe] + simp [L,hsum] + refine ⟨⟨v,hvsum⟩,?_⟩ + apply Nat.Partition.ext + change (Finset.univ.val.map (fun i:Fin n=>(v i).val)).filter (·≠0)=p.parts + rw [hm,←hl'] + have hf:(l:Multiset ℕ).filter (·≠0)=(l:Multiset ℕ):= + Multiset.filter_eq_self.mpr (by intro i hi; exact (hpos i hi).ne') + simpa [L] using hf + +end ElementaryPositivity.FiniteSearch + +end +section +namespace ElementaryPositivity.FiniteSearch +open scoped BigOperators +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) + +abbrev Table (n:ℕ):=(Fin n → Fin n) → Row n + +def WordOK (w:Fin n → Fin n):Prop:=Function.Bijective w ∧ + ∀i j:Fin n,i.val+1=j.val → w j + ij.1 < ij.2 ∧ w ij.2 < w ij.1 ∧ G.Edge (w ij.1) (w ij.2)).card + +def colorCount (a:Fin n → ℕ) (k:ℕ):ℕ:=∑κ:Fin n → Fin n, + if G.Proper κ ∧ (∀c,(Finset.univ.filter (fun j=>κ j=c)).card=a c) ∧ G.coloringAscents κ=k then 1 else 0 + +def matrixCount (v:Row n) (a:Fin n → ℕ):ℕ:=∑s:Fin n → Finset (Fin n), + if (∀i,(s i).card=(v.val i).val) ∧ + (∀c,(Finset.univ.filter (fun i=>c∈s i)).card=a c) then 1 else 0 + +def witnessCount (t:Table n) (a:Fin n → ℕ) (k:ℕ):ℕ:=∑w:Fin n → Fin n, + if WordOK G w ∧ wordEnergy G w=k then matrixCount (t w) a else 0 + +def Test (t:Table n):Prop:=∀a:Fin n → Fin (n+1),∀k:Fin (G.edgeCount+1), + colorCount G (fun c=>(a c).val) k.val=witnessCount G t (fun c=>(a c).val) k.val +instance (t:Table n):Decidable (Test G t):=inferInstanceAs (Decidable (∀a:Fin n → Fin (n+1), + ∀k:Fin (G.edgeCount+1),colorCount G (fun c=>(a c).val) k.val=witnessCount G t (fun c=>(a c).val) k.val)) + +end ElementaryPositivity.FiniteSearch + +end +section +namespace ElementaryPositivity.FiniteSearch +open scoped BigOperators +open Packets +open Classical +noncomputable section +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) + +def rowProfile (v:Row n):Fin n →₀ ℕ:=Finsupp.equivFunOnFinite.symm (fun i=>(v.val i).val) +lemma rowProfile_degree (v:Row n):(rowProfile v).degree=n:=by + rw [Finsupp.degree_eq_sum] + exact v.property +lemma rowPartition_eq_profile (v:Row n):rowPartition v=profilePartition (rowProfile v) (rowProfile_degree v):=rfl + +lemma matrix_coefficient {R:Type*} [CommSemiring R] (v:Row n) (a:Fin n →₀ ℕ) : + (MvPolynomial.esymmPart (Fin n) R (rowPartition v)).coeff a=(matrixCount v a:R) := by + rw [rowPartition_eq_profile,esymmPart_profile,ElementaryMatrix.elementary_product_coeff] + simp only [matrixCount,Nat.cast_sum,Nat.cast_ite,Nat.cast_one,Nat.cast_zero] + apply Finset.sum_congr rfl + intro s hs + have hr:ElementaryMatrix.rowCount s=rowProfile v ↔ ∀i,(s i).card=(v.val i).val:= + ElementaryMatrix.rowCount_eq s _ + have hc:ElementaryMatrix.colCount s=a ↔ ∀c,(Finset.univ.filter (fun i=>c∈s i)).card=a c:=by + rw [Finsupp.ext_iff] + simp only [ElementaryMatrix.colCount_apply,ElementaryMatrix.transpose] + simp only [hr,hc] + +lemma chromatic_coefficient (a:Fin n →₀ ℕ) (k:ℕ) : + ((G.chromatic n).coeff a).coeff k=colorCount G a k := by + have he:∀κ:Fin n → Fin n,wordCount κ=a ↔ ∀c,(Finset.univ.filter (fun j=>κ j=c)).card=a c:=by + intro κ + rw [Finsupp.ext_iff] + simp only [wordCount_apply] + unfold NaturalUnitIntervalGraph.chromatic colorCount + rw [MvPolynomial.coeff_sum,Polynomial.finsetSum_coeff,Finset.sum_filter] + apply Finset.sum_congr rfl + intro κ hκ + by_cases hp:G.Proper κ + · simp only [hp,ite_true,true_and,coloring_monomial,MvPolynomial.coeff_C_mul,MvPolynomial.coeff_monomial] + by_cases ha:wordCount κ=a + · simp only [ha,ite_true,mul_one,Polynomial.coeff_X_pow,(he κ).mp ha] + simp [eq_comm] + · simp only [ha,ite_false,mul_zero,Polynomial.coeff_zero,(he κ).not.mp ha,false_and] + · simp [hp] + +lemma chromatic_degree_zero (a:Fin n →₀ ℕ) (ha:a.degree≠n): + (G.chromatic n).coeff a=0 := by + ext k + rw [chromatic_coefficient,Polynomial.coeff_zero,colorCount] + apply Finset.sum_eq_zero + intro κ hκ + rw [ite_eq_right] + rintro ⟨_,hc,_⟩ + have hca:wordCount κ=a:=by ext c; rw [wordCount_apply]; exact hc c + exact ha (hca ▸ wordCount_degree κ) + +def wordEquiv : {σ:Equiv.Perm (Fin n) // G.Nondescent σ} ≃ {w:Fin n → Fin n // WordOK G w} where + toFun σ:=⟨σ.val,σ.val.bijective,σ.property⟩ + invFun w:=⟨Equiv.ofBijective w.val w.property.1,w.property.2⟩ + left_inv σ:=by apply Subtype.ext; exact Equiv.ext (fun _=>rfl) + right_inv _:=rfl + +lemma witness_coefficient (t:Table n) (a:Fin n →₀ ℕ) (k:ℕ) : + ((∑σ:{σ:Equiv.Perm (Fin n) // G.Nondescent σ},MvPolynomial.C (Polynomial.X^G.graphInversions σ.val)* + MvPolynomial.esymmPart (Fin n) (Polynomial ℕ) (rowPartition (t σ.val))).coeff a).coeff k= + witnessCount G t a k := by + rw [←Equiv.sum_comp (wordEquiv G).symm] + rw [MvPolynomial.coeff_sum,Polynomial.finsetSum_coeff] + change (∑w:{w:Fin n → Fin n // WordOK G w}, + ((MvPolynomial.C (Polynomial.X^wordEnergy G w.val)* + MvPolynomial.esymmPart (Fin n) (Polynomial ℕ) (rowPartition (t w.val))).coeff a).coeff k)=_ + simp only [MvPolynomial.coeff_C_mul,matrix_coefficient,Polynomial.coeff_mul_natCast,Polynomial.coeff_X_pow,Nat.cast_id] + rw [sum_subtype_ite (WordOK G) (fun w => (if k = wordEnergy G w then 1 else 0) * (matrixCount (t w) a : ℕ))] + unfold witnessCount + apply Finset.sum_congr rfl + intro w hw + by_cases hp:WordOK G w + · by_cases hk:wordEnergy G w=k + · simp [hp,hk] + · have hk':k≠wordEnergy G w:=Ne.symm hk + simp [hp,hk,hk'] + · simp [hp] + +lemma row_degree_zero (v:Row n) (a:Fin n →₀ ℕ) (ha:a.degree≠n) : + (MvPolynomial.esymmPart (Fin n) (Polynomial ℕ) (rowPartition v)).coeff a=0 := by + rw [rowPartition_eq_profile,esymmPart_profile] + exact ElementaryMatrix.elementary_product_coeff_zero _ _ (by simpa only [rowProfile_degree] using ha) + +lemma colorCount_zero_high (a:Fin n → ℕ) (k:ℕ) (hk:G.edgeCountsimp + | cons k l ih=> + by_cases hk:k=0 + · subst k; simp [MvPolynomial.esymm_zero,ih] + · simp [hk,ih] + unfold MvPolynomial.esymmPart profilePartition + rw [Nat.Partition.ofSums_parts,H,Multiset.map_map] + rfl +end +end ElementaryPositivity + +end +section +namespace ElementaryPositivity.ExactMasks +open Classical +noncomputable section +instance requiredFintype {A I:Type*} [Fintype A] [DecidableEq I] (mask:A → Finset I) (J:Finset I) : + Fintype (Required mask J):=inferInstanceAs (Fintype {a:A // J⊆mask a}) +instance exactFintype {A I:Type*} [Fintype A] [DecidableEq I] (mask:A → Finset I) (J:Finset I) : + Fintype (Exact mask J):=inferInstanceAs (Fintype {a:A // mask a=J}) +end +end ElementaryPositivity.ExactMasks +namespace ElementaryPositivity.TriangularDynamics +open Packets +open scoped BigOperators +open Classical +noncomputable section +variable {n:ℕ} (G:NaturalUnitIntervalGraph n) + +def requiredHistoryMatching (J:Finset (Fin (n-1))) : + ExactMasks.GradedEquiv + (fun w:ExactMasks.Required G.wordMask J=>G.graphInversions w.val) + (fun w:ExactMasks.Required (decoratedMask G) J=>decoratedEnergy G w.val) := + LaurentPositive.gradedEquivOfEnergySum G.edgeCount _ _ (required_energy_sum G J) + +def exactHistoryMatching (J:Finset (Fin (n-1))) : + ExactMasks.GradedEquiv + (fun w:ExactMasks.Exact G.wordMask J=>G.graphInversions w.val) + (fun w:ExactMasks.Exact (decoratedMask G) J=>decoratedEnergy G w.val) := by + letI:Encodable (Equiv.Perm (Fin n)):=Fintype.toEncodable _ + exact ExactMasks.refine G.wordMask (decoratedMask G) G.graphInversions (decoratedEnergy G) + (requiredHistoryMatching G) J + +def admissibleExactEquiv : {w:Equiv.Perm (Fin n) // G.Admissible w} ≃ ExactMasks.Exact G.wordMask ∅ where + toFun w:=⟨w.val,(G.wordMask_empty w.val).mpr w.property⟩ + invFun w:=⟨w.val,(G.wordMask_empty w.val).mp w.property⟩ + left_inv _:=rfl + right_inv _:=rfl + +def emptyDecoratedEquiv : ExactMasks.Exact (decoratedMask G) ∅ ≃ DecoratedLeaf G where + toFun w:=w.val.1 + invFun d:=⟨⟨d,((emptyAnchorEquiv.{0,1} (historyProfile G d.1) (historyProfile_degree G d.1)).symm PUnit.unit.{1}).val⟩, + ((emptyAnchorEquiv.{0,1} (historyProfile G d.1) (historyProfile_degree G d.1)).symm PUnit.unit.{1}).property⟩ + left_inv w:=by + rcases w with ⟨⟨d,w⟩,hw⟩ + have H: (emptyAnchorEquiv.{0,1} (historyProfile G d.1) (historyProfile_degree G d.1)).symm PUnit.unit.{1}= + (⟨w,hw⟩:EmptyAnchor (n:=n) (historyProfile G d.1)):= + (emptyAnchorEquiv.{0,1} (historyProfile G d.1) (historyProfile_degree G d.1)).symm_apply_apply ⟨w,hw⟩ + apply Subtype.ext + exact congrArg (fun z:EmptyAnchor (n:=n) (historyProfile G d.1)=> (⟨d,z.val⟩:DecoratedWord G)) H + right_inv _:=rfl + +def admissibleHistoryEquiv : {w:Equiv.Perm (Fin n) // G.Admissible w} ≃ DecoratedLeaf G:= + (admissibleExactEquiv G).trans ((exactHistoryMatching G ∅).val.trans (emptyDecoratedEquiv G)) + +lemma admissibleHistoryEquiv_energy (w:{w:Equiv.Perm (Fin n) // G.Admissible w}) : + leafEnergy G (admissibleHistoryEquiv G w)=G.graphInversions w.val:= + (exactHistoryMatching G ∅).property (admissibleExactEquiv G w) + +def leafPartition (d:DecoratedLeaf G):Nat.Partition n:= + profilePartition (historyProfile G d.1) (historyProfile_degree G d.1) + +def admissiblePartition (w:{w:Equiv.Perm (Fin n) // G.Admissible w}):Nat.Partition n:= + leafPartition G (admissibleHistoryEquiv G w) +end +end ElementaryPositivity.TriangularDynamics + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Chromatic/Witness/WitnessTransport.lean b/lean/OAI/Combinatorics/Chromatic/Witness/WitnessTransport.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a3b41dfdcc5284aab14908b75d1e99f99b0f346 --- /dev/null +++ b/lean/OAI/Combinatorics/Chromatic/Witness/WitnessTransport.lean @@ -0,0 +1,232 @@ +import Mathlib + +namespace OAI + +section +namespace ElementaryPositivity +namespace FiniteMatching + +variable {A B : Type*} [DecidableEq B] +variable {P : A → Prop} {Q : B → Prop} + +def align (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) (a : {a // P a}) : A ≃ B := + e.trans (Equiv.swap (e a.val) (f a).val) + +@[simp] theorem align_at (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (a : {a // P a}) : align e f a a.val = (f a).val := by + simp [align] + +theorem align_preserves (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (a b : {a // P a}) (hb : e b.val = (f b).val) : + align e f a b.val = (f b).val := by + by_cases hab : a = b + · subst b + exact align_at _ _ _ + · have habval : a.val ≠ b.val := fun h => hab (Subtype.ext h) + have he : (f b).val ≠ e a.val := by + rw [← hb] + exact fun h => habval (e.injective h.symm) + have hf : (f b).val ≠ (f a).val := + fun h => hab (f.injective (Subtype.ext h.symm)) + simp [align, hb, Equiv.swap_apply_of_ne_of_ne he hf] + +def compress (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) : + List {a // P a} → A ≃ B + | [] => e + | a :: as => compress (align e f a) f as + + theorem compress_preserves (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (as : List {a // P a}) (b : {a // P a}) (hb : e b.val = (f b).val) : + compress e f as b.val = (f b).val := by + induction as generalizing e with + | nil => exact hb + | cons a as ih => + exact ih _ (align_preserves e f a b hb) + + theorem compress_at (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (as : List {a // P a}) (b : {a // P a}) (hb : b ∈ as) : + compress e f as b.val = (f b).val := by + induction as generalizing e with + | nil => simp at hb + | cons a as ih => + rcases List.mem_cons.mp hb with h | h + · subst b + exact compress_preserves (align e f a) f as a (align_at e f a) + · exact ih (align e f a) h + +omit [DecidableEq B] in + theorem membership_iff (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (he : ∀ a : {a // P a}, e a.val = (f a).val) (a : A) : + P a ↔ Q (e a) := by + constructor + · intro ha + rw [he ⟨a, ha⟩] + exact (f ⟨a, ha⟩).property + · intro hq + let a' := f.symm ⟨e a, hq⟩ + have haa : a'.val = a := by + apply e.injective + rw [he a'] + exact congrArg Subtype.val (f.apply_symm_apply ⟨e a, hq⟩) + exact haa ▸ a'.property + +def cancel (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (as : List {a // P a}) (complete : ∀ a, a ∈ as) : + {a // ¬P a} ≃ {b // ¬Q b} := + (compress e f as).subtypeEquiv fun a => + not_congr (membership_iff (compress e f as) f + (fun b => compress_at e f as b (complete b)) a) + +variable {W : Type*} + + theorem swap_preserves (energy : B → W) (x y : B) (h : energy x = energy y) + (b : B) : energy (Equiv.swap x y b) = energy b := by + by_cases hx : b = x + · subst b + simpa using h.symm + · by_cases hy : b = y + · subst b + simpa using h + · rw [Equiv.swap_apply_of_ne_of_ne hx hy] + + theorem align_energy (energyA : A → W) (energyB : B → W) + (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (he : ∀ a, energyB (e a) = energyA a) + (hf : ∀ a, energyB (f a).val = energyA a.val) + (a : {a // P a}) (x : A) : energyB (align e f a x) = energyA x := by + change energyB (Equiv.swap (e a.val) (f a).val (e x)) = _ + rw [swap_preserves energyB _ _ ((he a.val).trans (hf a).symm)] + exact he x + + theorem compress_energy (energyA : A → W) (energyB : B → W) + (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (he : ∀ a, energyB (e a) = energyA a) + (hf : ∀ a, energyB (f a).val = energyA a.val) + (as : List {a // P a}) (x : A) : energyB (compress e f as x) = energyA x := by + induction as generalizing e with + | nil => exact he x + | cons a as ih => exact ih _ (align_energy energyA energyB e f he hf a) + + theorem cancel_energy (energyA : A → W) (energyB : B → W) + (e : A ≃ B) (f : {a // P a} ≃ {b // Q b}) + (he : ∀ a, energyB (e a) = energyA a) + (hf : ∀ a, energyB (f a).val = energyA a.val) + (as : List {a // P a}) (complete : ∀ a, a ∈ as) (x : {a // ¬P a}) : + energyB (cancel e f as complete x).val = energyA x.val := + compress_energy energyA energyB e f he hf as x.val + +end FiniteMatching +end ElementaryPositivity + +namespace ElementaryPositivity +namespace ExactMasks + +variable {A B I W : Type*} [DecidableEq I] + +def Exact (mask : A → Finset I) (J : Finset I) := {a // mask a = J} +def Required (mask : A → Finset I) (J : Finset I) := {a // J ⊆ mask a} +def Strict (mask : A → Finset I) (J : Finset I) := {a // J ⊂ mask a} + +def GradedEquiv (energyA : A → W) (energyB : B → W) := + {e : A ≃ B // ∀ a, energyB (e a) = energyA a} + +def strictFibers (mask : A → Finset I) (J : Finset I) : + Strict mask J ≃ Σ K : {K : Finset I // J ⊂ K}, Exact mask K.val where + toFun a := ⟨⟨mask a.val, a.property⟩, ⟨a.val, rfl⟩⟩ + invFun a := ⟨a.2.val, by simpa only [a.2.property] using a.1.property⟩ + left_inv _ := rfl + right_inv a := by + rcases a with ⟨⟨K, hk⟩, ⟨a, ha⟩⟩ + dsimp only at ha + subst K + rfl + +def internalStrict (mask : A → Finset I) (J : Finset I) : + {a : Required mask J // mask a.val ≠ J} ≃ Strict mask J where + toFun a := ⟨a.val.val, Finset.ssubset_iff_subset_ne.mpr + ⟨a.val.property, Ne.symm a.property⟩⟩ + invFun a := ⟨⟨a.val, (Finset.ssubset_iff_subset_ne.mp a.property).1⟩, + Ne.symm ((Finset.ssubset_iff_subset_ne.mp a.property).2)⟩ + left_inv _ := rfl + right_inv _ := rfl + +def exactCompl (mask : A → Finset I) (J : Finset I) : + Exact mask J ≃ {a : Required mask J // ¬mask a.val ≠ J} where + toFun a := ⟨⟨a.val, by rw [a.property]⟩, not_not.mpr a.property⟩ + invFun a := ⟨a.val.val, not_not.mp a.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +def strictEquiv (maskA : A → Finset I) (maskB : B → Finset I) (J : Finset I) + (ih : ∀ K, J ⊂ K → Exact maskA K ≃ Exact maskB K) : + Strict maskA J ≃ Strict maskB J := + (strictFibers maskA J).trans + ((Equiv.sigmaCongrRight fun K : {K : Finset I // J ⊂ K} => ih K.val K.property).trans + (strictFibers maskB J).symm) + +omit [DecidableEq I] in + theorem strictEquiv_energy (maskA : A → Finset I) (maskB : B → Finset I) + (energyA : A → W) (energyB : B → W) (J : Finset I) + (ih : ∀ K, J ⊂ K → Exact maskA K ≃ Exact maskB K) + (hh : ∀ K h a, energyB (ih K h a).val = energyA a.val) + (a : Strict maskA J) : + energyB (strictEquiv maskA maskB J ih a).val = energyA a.val := by + exact hh (maskA a.val) a.property ⟨a.val, rfl⟩ + +variable [Fintype A] [Encodable A] [DecidableEq B] + +def step (maskA : A → Finset I) (maskB : B → Finset I) + (energyA : A → W) (energyB : B → W) (J : Finset I) + (required : GradedEquiv + (fun a : Required maskA J => energyA a.val) + (fun b : Required maskB J => energyB b.val)) + (ih : ∀ K, J ⊂ K → GradedEquiv + (fun a : Exact maskA K => energyA a.val) + (fun b : Exact maskB K => energyB b.val)) : + GradedEquiv (fun a : Exact maskA J => energyA a.val) + (fun b : Exact maskB J => energyB b.val) := by + letI : DecidableEq (Required maskB J) := + inferInstanceAs (DecidableEq {b : B // J ⊆ maskB b}) + letI : Fintype (Required maskA J) := + inferInstanceAs (Fintype {a : A // J ⊆ maskA a}) + letI : Encodable (Required maskA J) := + inferInstanceAs (Encodable {a : A // J ⊆ maskA a}) + let ilarge := strictEquiv maskA maskB J (fun K h => (ih K h).val) + let internal := (internalStrict maskA J).trans + (ilarge.trans (internalStrict maskB J).symm) + let enumeration := Encodable.sortedUniv {a : Required maskA J // maskA a.val ≠ J} + have complete : ∀ a, a ∈ enumeration := fun a => Encodable.mem_sortedUniv a + let cancelled := FiniteMatching.cancel required.val internal enumeration complete + refine ⟨(exactCompl maskA J).trans (cancelled.trans (exactCompl maskB J).symm), ?_⟩ + intro a + apply FiniteMatching.cancel_energy + (fun a : Required maskA J => energyA a.val) + (fun b : Required maskB J => energyB b.val) + required.val internal required.property + intro x + exact strictEquiv_energy maskA maskB energyA energyB J + (fun K h => (ih K h).val) (fun K h => (ih K h).property) + (internalStrict maskA J x) + +def refine [Fintype I] (maskA : A → Finset I) (maskB : B → Finset I) + (energyA : A → W) (energyB : B → W) + (required : ∀ J, GradedEquiv + (fun a : Required maskA J => energyA a.val) + (fun b : Required maskB J => energyB b.val)) (J : Finset I) : + GradedEquiv (fun a : Exact maskA J => energyA a.val) + (fun b : Exact maskB J => energyB b.val) := + step maskA maskB energyA energyB J (required J) + (fun K _ => refine maskA maskB energyA energyB required K) +termination_by Fintype.card I - J.card +decreasing_by + rename_i strictSubset + have hjk := Finset.card_lt_card strictSubset + have hk := Finset.card_le_univ K + omega + +end ExactMasks +end ElementaryPositivity + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/CrossBound.lean b/lean/OAI/Combinatorics/CliqueFree/CrossBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..e0de77db84bdb26b40006773167b95f102bb00a3 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/CrossBound.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.CliqueFree.DisjointCross + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph +attribute [local instance] Classical.decEq +universe u +variable {V : Type u} [Fintype V] + +section ColoringCount +variable [DecidableEq V] + +lemma bool_point_count (u : V) (b : Bool) : + (∑ f : V → Bool, if f u = b then (1:ℝ) else 0) = + (Fintype.card (V → Bool) : ℝ)/2 := by + let e := Equiv.funSplitAt u Bool + have hc : (Fintype.card (V → Bool) : ℝ) = + 2*(Fintype.card ({j : V // j ≠ u} → Bool) : ℝ) := by + have h := Fintype.card_congr e + simpa only [Fintype.card_prod,Fintype.card_bool,Nat.cast_mul,Nat.cast_ofNat] using congrArg (fun n : ℕ ↦ (n:ℝ)) h + calc + _ = (Fintype.card ({j : V // j ≠ u} → Bool) : ℝ) := by + rw [← e.symm.sum_comp (fun f : V → Bool ↦ if f u = b then (1:ℝ) else 0)] + rw [Fintype.sum_prod_type,Fintype.sum_bool] + cases b <;> simp [e,Equiv.funSplitAt_symm_apply] + _ = _ := by linarith + +lemma bool_pair_count (u v : V) (huv : u ≠ v) : + (∑ f : V → Bool, if f u = false ∧ f v = true then (1:ℝ) else 0) = + (Fintype.card (V → Bool) : ℝ)/4 := by + let e := Equiv.funSplitAt u Bool + have hc : (Fintype.card (V → Bool) : ℝ) = + 2*(Fintype.card ({j : V // j ≠ u} → Bool) : ℝ) := by + have h := Fintype.card_congr e + simpa only [Fintype.card_prod,Fintype.card_bool,Nat.cast_mul,Nat.cast_ofNat] using congrArg (fun n : ℕ ↦ (n:ℝ)) h + have hsum := e.symm.sum_comp (fun f : V → Bool ↦ + if f u = false ∧ f v = true then (1:ℝ) else 0) + rw [Fintype.sum_prod_type,Fintype.sum_bool] at hsum + simp only [e,Equiv.funSplitAt_symm_apply,eq_self,dite_true,dite_eq_right huv.symm, + Bool.true_eq_false,false_and,ite_false,true_and,sum_const_zero,zero_add] at hsum + rw [← hsum, bool_point_count (⟨v,huv.symm⟩ : {j : V // j ≠ u}) true] + linarith only [hc] + +end ColoringCount + +omit [Fintype V] in +lemma crossMass_colored (G : SimpleGraph V) (w : V → ℝ) (S D : Finset V) (f : V → Bool) : + crossMass G w (S.filter fun u ↦ f u = false) (D.filter fun v ↦ f v = true) = + ∑ u ∈ S, ∑ v ∈ D, (if f u = false ∧ f v = true then (1:ℝ) else 0) * + (if G.Adj u v then w u*w v else 0) := by + classical + unfold crossMass + rw [sum_filter] + apply sum_congr rfl + intro u _ + rw [sum_filter] + by_cases hu : f u = false + · simp only [hu,true_and,ite_true] + apply sum_congr rfl + intro v _ + split_ifs <;> simp + · simp [hu] + +end CliqueFreeIndependence.WeightedGraph + +namespace CliqueFreeIndependence.WeightedGraph +universe u +variable {V : Type u} [Fintype V] + +lemma sum_colored_cross [DecidableEq V] (G : SimpleGraph V) (w : V → ℝ) (S D : Finset V) : + (∑ f : V → Bool, crossMass G w (S.filter fun u ↦ f u = false) (D.filter fun v ↦ f v = true)) = + (Fintype.card (V → Bool) : ℝ)/4 * crossMass G w S D := by + simp_rw [crossMass_colored] + rw [sum_comm] + unfold crossMass + rw [mul_sum] + apply sum_congr rfl + intro u _ + rw [sum_comm,mul_sum] + apply sum_congr rfl + intro v _ + classical + by_cases huv : G.Adj u v + · simp only [ite_eq_left huv] + rw [← sum_mul,bool_pair_count u v huv.ne] + · simp [huv] + +/-- Full optimizer cross mass, including overlapping sets, with an explicit constant. -/ +theorem optimizer_cross_bound (k : ℕ) (G : SimpleGraph V) {w : V → ℝ} + (hw : IsOptimizer G w) (hfree : G.CliqueFree (k+2)) : + CrossBound G w (16*((k:ℝ)+2)^2) := by + classical + intro x hx S D hs ht + have hw0 := fun v ↦ (optimizer_stationary hw v).1.le + have hpoint (f : V → Bool) : + crossMass G w (S.filter fun u ↦ f u = false) (D.filter fun v ↦ f v = true) ≤ + (4*((k:ℝ)+2)^2)*growth x (mass w S) := by + have hSD : Disjoint (S.filter fun u ↦ f u = false) (D.filter fun v ↦ f v = true) := by + apply disjoint_left.2 + intro v hv hv' + have h1 := (mem_filter.1 hv).2 + have h2 := (mem_filter.1 hv').2 + rw [h1] at h2 + contradiction + have hS := mass_mono hw0 (filter_subset (fun u ↦ f u = false) S) + have hD := mass_mono hw0 (filter_subset (fun v ↦ f v = true) D) + have h := optimizer_cross_disjoint k G hw _ _ hSD hfree.cliqueFreeOn hx + (hS.trans hs) (hD.trans ht) + exact h.trans (mul_le_mul_of_nonneg_left + (growth_mono hx (mass_nonneg hw0 _) (mass_nonneg hw0 _) hS) (by positivity)) + have hsum := sum_le_sum (s := (univ : Finset (V → Bool))) fun f _ ↦ hpoint f + rw [sum_colored_cross] at hsum + simp only [sum_const,card_univ,nsmul_eq_mul] at hsum + have hn : 0 < (Fintype.card (V → Bool) : ℝ) := by exact_mod_cast Fintype.card_pos + apply (mul_le_mul_iff_right₀ hn).1 + nlinarith only [hsum] + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Deletion.lean b/lean/OAI/Combinatorics/CliqueFree/Deletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..c031d98df5cd051d4dc9c23f71e23253ddada78a --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Deletion.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.CliqueFree.OptimizerBounds +import OAI.Combinatorics.CliqueFree.MultiplierLaw + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +noncomputable def closedNeighbors (G : SimpleGraph V) (v : V) : Finset V := by + classical + exact insert v (neighbors G v) + +@[simp] lemma mem_closedNeighbors (G : SimpleGraph V) (u v : V) : + u ∈ closedNeighbors G v ↔ u = v ∨ G.Adj v u := by + classical + simp [closedNeighbors] + +lemma mass_closedNeighbors (G : SimpleGraph V) (w : V → ℝ) (v : V) : + mass w (closedNeighbors G v) = w v + neighborMass G w v := by + classical + exact sum_insert (by simp) -- the two expressions are definitionally the sums + +lemma edgeMass_closedNeighbors (G : SimpleGraph V) (w : V → ℝ) (v : V) : + edgeMass G (restrict (closedNeighbors G v) w) = + w v * neighborMass G w v + triangleAt G w v / 2 := by + classical + have hv : v ∉ neighbors G v := by simp + have hs : (∑ u ∈ neighbors G v, if G.Adj v u then w v * w u else 0) = + w v * neighborMass G w v := by + rw [neighborMass, mass, mul_sum] + apply sum_congr rfl + intro u hu + simp [(mem_neighbors G v u).1 hu] + have hs' : (∑ u ∈ neighbors G v, if G.Adj u v then w u * w v else 0) = + w v * neighborMass G w v := by + simp_rw [G.adj_comm, mul_comm] + exact hs + have ht : crossMass G w (neighbors G v) (neighbors G v) = triangleAt G w v := by + simpa [triangleAt, commonMass, inter_comm] using crossMass_neighbors G w (neighbors G v) v + rw [edgeMass_restrict] + have he : crossMass G w (closedNeighbors G v) (closedNeighbors G v) = + 2 * (w v * neighborMass G w v) + triangleAt G w v := by + simp only [closedNeighbors, crossMass, sum_insert hv, G.irrefl, ite_false, zero_add, + sum_add_distrib] + rw [hs,hs'] + change _ + (_ + crossMass G w (neighbors G v) (neighbors G v)) = _ + rw [ht] + ring + rw [he] + ring + +lemma optimizer_deletion_cost {G : SimpleGraph V} {w : V → ℝ} + (hw : IsOptimizer G w) (A : Finset V) : + potential G w - potential G (restrict Aᶜ w) = + mass w A + edgeMass G (restrict A w) := by + classical + have hq : ∀ v, 0 ≤ restrict Aᶜ w v := by + intro v + simp only [restrict] + split_ifs + · exact hw.1 v + · rfl + rw [(optimizer_divergence hw _ hq).2] + have hsum : (∑ v, (restrict Aᶜ w v * Real.log (restrict Aᶜ w v / w v) - + restrict Aᶜ w v + w v)) = mass w A := by + calc + _ = ∑ v, if v ∈ A then w v else 0 := by + apply sum_congr rfl + intro v _ + by_cases hv : v ∈ A + · simp [restrict,hv] + · simp [restrict,hv, (optimizer_stationary hw v).1.ne'] + _ = mass w A := by simp [mass] + have hdiff : restrict Aᶜ w - w = (-1 : ℝ) • restrict A w := by + ext v + by_cases hv : v ∈ A <;> simp [restrict,hv] + rw [hsum, hdiff] + have he := edgeMass_smul G (restrict A w) (-1) + simpa only [Pi.smul_def,smul_eq_mul,neg_one_sq,one_mul] using congrArg (mass w A + ·) he + +lemma potential_induce (G : SimpleGraph V) (w : V → ℝ) (A : Finset V) : + potential (G.induce (A : Set V)) (fun v ↦ w v) = potential G (restrict A w) := by + classical + have he : edgeMass (G.induce (A : Set V)) (fun v ↦ w v) = edgeMass G (restrict A w) := by + rw [edgeMass_restrict,edgeMass,crossMass] + congr 1 + simp only [SimpleGraph.induce_adj] + rw [← Finset.sum_subtype A (by simp) + (fun u ↦ ∑ v : (A : Set V), if G.Adj u v then w u * w v else 0)] + unfold crossMass + apply sum_congr rfl + intro u hu + exact (Finset.sum_subtype A (by simp) + (fun v ↦ if G.Adj u v then w u * w v else 0)).symm + rw [potential, potential, he] + congr 1 + rw [← Finset.sum_subtype A (by simp) (fun v ↦ vertexPotential (w v))] + have hvertex (v : V) : vertexPotential (restrict A w v) = + if v ∈ A then vertexPotential (w v) else 0 := by + by_cases hv : v ∈ A <;> simp [restrict,hv,vertexPotential] + simp_rw [hvertex] + simp + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/DisjointCross.lean b/lean/OAI/Combinatorics/CliqueFree/DisjointCross.lean new file mode 100644 index 0000000000000000000000000000000000000000..9eafc2f72a5da781d03a99a00bad78be280f061d --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/DisjointCross.lean @@ -0,0 +1,157 @@ +import OAI.Combinatorics.CliqueFree.EdgeState +import OAI.Combinatorics.CliqueFree.VariationalCross + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph +open Lottery +universe u +variable {V : Type u} [Fintype V] + +/-- A logarithm estimate with `log 2 ≤ 1` already applied. -/ +lemma log_multiplier_le (k : ℕ) {x : ℝ} (hx : 1 ≤ x) : + Real.log (1 + Real.exp (4*x) * multiplierBound k (Real.exp (-8*x))) ≤ + (5 + 10*(k:ℝ) + (k:ℝ)^2)*x := by + have hx0 : 0 ≤ x := by linarith + have hε : Real.exp (-8*x) ≤ 1 := Real.exp_le_one_iff.2 (by linarith) + have hb := multiplierBound_ge_one k (Real.exp_pos _) hε + have he : 1 ≤ Real.exp (4*x) := Real.one_le_exp_iff.2 (by linarith) + have hprod : 1 ≤ Real.exp (4*x) * multiplierBound k (Real.exp (-8*x)) := + one_le_mul_of_one_le_of_one_le he hb + have hm := Real.log_le_log (by positivity : 0 < 1 + Real.exp (4*x) * + multiplierBound k (Real.exp (-8*x))) + (show 1 + Real.exp (4*x) * multiplierBound k (Real.exp (-8*x)) ≤ + 2 * (Real.exp (4*x) * multiplierBound k (Real.exp (-8*x))) by linarith) + have hbpos := multiplierBound_pos k (Real.exp_pos (-8*x)) + have hlogb : Real.log (multiplierBound k (Real.exp (-8*x))) = + (((k:ℝ)+2)*k)*Real.log 2 + 8*(k:ℝ)*x := by + unfold multiplierBound + rw [Real.log_div (by positivity) (by positivity), Real.log_pow, Real.log_pow, Real.log_exp] + push_cast + ring + rw [Real.log_mul (by norm_num) (mul_pos (Real.exp_pos _) hbpos).ne', + Real.log_mul (Real.exp_ne_zero _) hbpos.ne', Real.log_exp,hlogb] at hm + have hlog2 : Real.log 2 ≤ 1 := by + have h := Real.log_le_sub_one_of_pos (by norm_num : (0:ℝ) < 2) + linarith + have hk : 0 ≤ (k:ℝ) := Nat.cast_nonneg _ + have hc : 0 ≤ (1 + ((k:ℝ)+2)*k) := by positivity + have haux := mul_le_mul_of_nonneg_left hlog2 hc + have hxaux := mul_le_mul_of_nonneg_left hx hc + nlinarith + +lemma cross_error_le {s t x : ℝ} (hx : 1 ≤ x) (hs : 0 ≤ s) (ht : 0 ≤ t) + (hslo : Real.exp (-x) ≤ s) (hsup : s ≤ Real.exp x) (htup : t ≤ Real.exp x) : + s^2 + t^2/2 + t ≤ 3 * Real.exp (4*x) * x * s := by + have hx0 : 0 ≤ x := by linarith + have h1 : s ≤ Real.exp (4*x) := hsup.trans (Real.exp_le_exp.2 (by linarith)) + have hss : s^2 ≤ Real.exp (4*x)*s := by nlinarith [mul_le_mul_of_nonneg_right h1 hs] + have hks : Real.exp (3*x) ≤ Real.exp (4*x)*s := by + calc + _ = Real.exp (4*x)*Real.exp (-x) := by rw [← Real.exp_add]; congr 1; ring + _ ≤ _ := mul_le_mul_of_nonneg_left hslo (Real.exp_pos _).le + have ht1 : t ≤ Real.exp (4*x)*s := + htup.trans ((Real.exp_le_exp.2 (by linarith : x ≤ 3*x)).trans hks) + have ht2 : t^2 ≤ Real.exp (4*x)*s := by + calc + _ ≤ (Real.exp x)^2 := sq_le_sq₀ ht (Real.exp_pos x).le |>.2 htup + _ = Real.exp (2*x) := by rw [sq,← Real.exp_add]; congr 1; ring + _ ≤ Real.exp (3*x) := Real.exp_le_exp.2 (by linarith) + _ ≤ _ := hks + have hscale := mul_le_mul_of_nonneg_left hx (mul_nonneg (Real.exp_pos (4*x)).le hs) + nlinarith + +lemma optimizer_cross_disjoint_moderate (k : ℕ) (G : SimpleGraph V) {w : V → ℝ} + (hw : IsOptimizer G w) (S D : Finset V) (hSD : Disjoint S D) + (hfree : G.CliqueFreeOn (↑S) (k+2)) {x : ℝ} (hx : 1 ≤ x) + (hslo : Real.exp (-x) ≤ mass w S) (hsup : mass w S ≤ Real.exp x) + (htup : mass w D ≤ Real.exp x) : + crossMass G w S D ≤ (8 + 10*(k:ℝ) + (k:ℝ)^2)*x*mass w S := by + have hwpos := fun v ↦ (optimizer_stationary hw v).1 + have hεhalf : Real.exp (-8*x) ≤ 1/2 := by + have hl : Real.log 2 ≤ 1 := by + have h := Real.log_le_sub_one_of_pos (by norm_num : (0:ℝ) < 2) + linarith + calc + _ ≤ Real.exp (-Real.log 2) := Real.exp_le_exp.2 (by linarith) + _ = 1/2 := by rw [Real.exp_neg,Real.exp_log (by norm_num)]; norm_num + obtain ⟨L,hp,hb,hm,he⟩ := sparse_multipliers_on k G hwpos S hfree (Real.exp_pos (-8*x)) hεhalf + have h := variational_cross_lottery G hw S D hSD L hp (Real.exp_pos (4*x)).le hb hm he + have hcancel : (Real.exp (4*x))^2 * Real.exp (-8*x) = 1 := by + rw [sq,← Real.exp_add,← Real.exp_add] + convert Real.exp_zero using 2 + ring + rw [hcancel,one_mul] at h + have hlog := log_multiplier_le k hx + have hw0 := fun v ↦ (hwpos v).le + have hs := mass_nonneg hw0 S + have ht := mass_nonneg hw0 D + have hlogs := mul_le_mul_of_nonneg_right + (mul_le_mul_of_nonneg_left hlog (Real.exp_pos (4*x)).le) hs + have herr := cross_error_le hx hs ht hslo hsup htup + apply (mul_le_mul_iff_right₀ (Real.exp_pos (4*x))).1 + nlinarith only [h,hlogs,herr] + +end CliqueFreeIndependence.WeightedGraph + +namespace CliqueFreeIndependence.WeightedGraph +universe u +variable {V : Type u} [Fintype V] + +lemma optimizer_cross_disjoint (k : ℕ) (G : SimpleGraph V) {w : V → ℝ} + (hw : IsOptimizer G w) (S D : Finset V) (hSD : Disjoint S D) + (hfree : G.CliqueFreeOn (↑S) (k+2)) {x : ℝ} (hx : 1 ≤ x) + (hsup : mass w S ≤ Real.exp x) (htup : mass w D ≤ Real.exp x) : + crossMass G w S D ≤ (4*((k:ℝ)+2)^2)*growth x (mass w S) := by + have hw0 := fun v ↦ (optimizer_stationary hw v).1.le + have hs := mass_nonneg hw0 S + have hk : 0 ≤ (k:ℝ) := Nat.cast_nonneg _ + have hcoeff : 8+10*(k:ℝ)+(k:ℝ)^2 ≤ 4*((k:ℝ)+2)^2 := by nlinarith + have hcoeff0 : 0 ≤ 8+10*(k:ℝ)+(k:ℝ)^2 := by positivity + rcases hs.eq_or_lt with hs | hs + · have hc := crossMass_le_product G hw0 S D + simpa [← hs] using hc + by_cases hlo : Real.exp (-x) ≤ mass w S + · have h := optimizer_cross_disjoint_moderate k G hw S D hSD hfree hx hlo hsup htup + have hg : x*mass w S ≤ growth x (mass w S) := by + unfold growth + nlinarith [mul_nonneg hs.le (le_max_left 0 (Real.log (1/mass w S)))] + calc + _ ≤ (8+10*(k:ℝ)+(k:ℝ)^2)*(x*mass w S) := by nlinarith only [h] + _ ≤ (8+10*(k:ℝ)+(k:ℝ)^2)*growth x (mass w S) := mul_le_mul_of_nonneg_left hg hcoeff0 + _ ≤ _ := mul_le_mul_of_nonneg_right hcoeff (growth_nonneg (by linarith) hs.le) + · let y := Real.log (1/mass w S) + have hxy : x ≤ y := by + have hlog := Real.log_le_log hs (le_of_not_ge hlo) + rw [Real.log_exp] at hlog + dsimp [y] + rw [one_div,Real.log_inv] + linarith + have hy : 1 ≤ y := hx.trans hxy + have hsy : Real.exp (-y) = mass w S := by + dsimp [y] + rw [one_div,Real.log_inv,neg_neg,Real.exp_log hs] + have h := optimizer_cross_disjoint_moderate k G hw S D hSD hfree hy hsy.le + (hsup.trans (Real.exp_le_exp.2 hxy)) (htup.trans (Real.exp_le_exp.2 hxy)) + have hg : y*mass w S ≤ growth x (mass w S) := by + unfold growth + have hmax := le_max_right 0 y + change y*mass w S ≤ mass w S*(x+max 0 y) + nlinarith [mul_le_mul_of_nonneg_right hmax hs.le] + calc + _ ≤ (8+10*(k:ℝ)+(k:ℝ)^2)*(y*mass w S) := by nlinarith only [h] + _ ≤ (8+10*(k:ℝ)+(k:ℝ)^2)*growth x (mass w S) := mul_le_mul_of_nonneg_left hg hcoeff0 + _ ≤ _ := mul_le_mul_of_nonneg_right hcoeff (growth_nonneg (by linarith) hs.le) + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/EdgeState.lean b/lean/OAI/Combinatorics/CliqueFree/EdgeState.lean new file mode 100644 index 0000000000000000000000000000000000000000..379b10aff31762575b2602ba4510312486d13cc3 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/EdgeState.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.CliqueFree.FiniteEntropy +import OAI.Combinatorics.CliqueFree.WeightedGraph + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +/-- Oriented edges, the disjoint union of the neighborhood state spaces. -/ +abbrev EdgeState (G : SimpleGraph V) := {e : V × V // G.Adj e.1 e.2} + +noncomputable instance edgeStateFintype (G : SimpleGraph V) : Fintype (EdgeState G) := + Subtype.fintype _ + +local instance (priority := 10000) edgeStateDecEq (G : SimpleGraph V) : DecidableEq (EdgeState G) := + Classical.decEq _ + +namespace EdgeState +variable {G : SimpleGraph V} +def src (e : EdgeState G) : V := e.val.1 +def dst (e : EdgeState G) : V := e.val.2 +omit [Fintype V] in +@[simp] lemma adj (e : EdgeState G) : G.Adj e.src e.dst := e.property + +def rev (e : EdgeState G) : EdgeState G := ⟨(e.dst, e.src), e.adj.symm⟩ +omit [Fintype V] in +@[simp] lemma src_rev (e : EdgeState G) : e.rev.src = e.dst := rfl +omit [Fintype V] in +@[simp] lemma dst_rev (e : EdgeState G) : e.rev.dst = e.src := rfl +omit [Fintype V] in +@[simp] lemma rev_rev (e : EdgeState G) : e.rev.rev = e := by cases e; rfl + +def revEquiv : EdgeState G ≃ EdgeState G where + toFun := rev + invFun := rev + left_inv := rev_rev + right_inv := rev_rev + +lemma sum_eq (f : V → V → ℝ) : + (∑ e : EdgeState G, f e.src e.dst) = ∑ u, ∑ v ∈ neighbors G u, f u v := by + classical + change (∑ e : {e : V × V // G.Adj e.1 e.2}, f e.val.1 e.val.2) = _ + rw [← Finset.sum_subtype (univ.filter fun e : V × V ↦ G.Adj e.1 e.2) + (by simp) (fun e : V × V ↦ f e.1 e.2)] + simp only [sum_filter, Fintype.sum_prod_type, neighbors] + +lemma sum_fiber (u : V) (f : V → ℝ) : + (∑ e : EdgeState G, if e.src = u then f e.dst else 0) = ∑ v ∈ neighbors G u, f v := by + classical + rw [sum_eq (fun a b ↦ if a = u then f b else 0)] + simp + +lemma sum_fiber' (u : V) (f : V → ℝ) : + (∑ e : EdgeState G, if u = e.src then f e.dst else 0) = ∑ v ∈ neighbors G u, f v := by + classical + simpa only [eq_comm] using sum_fiber u f + +end EdgeState + +lemma growth_nonneg {x s : ℝ} (hx : 0 ≤ x) (hs : 0 ≤ s) : 0 ≤ growth x s := + mul_nonneg hs (add_nonneg hx (le_max_left _ _)) + +@[simp] lemma growth_zero (x : ℝ) : growth x 0 = 0 := by simp [growth] + +lemma growth_small {x s : ℝ} (hs : 0 < s) (hs1 : s ≤ 1) : + growth x s = s * (x - Real.log s) := by + have hl : Real.log s ≤ 0 := Real.log_nonpos hs.le hs1 + simp [growth, Real.log_inv, max_eq_right (neg_nonneg.2 hl), sub_eq_add_neg] + +lemma growth_large {x s : ℝ} (hs : 1 ≤ s) : growth x s = s * x := by + have hl : 0 ≤ Real.log s := Real.log_nonneg hs + simp [growth, Real.log_inv, max_eq_left (neg_nonpos.2 hl)] + +lemma growth_mono {x : ℝ} (hx : 1 ≤ x) : MonotoneOn (growth x) (Set.Ici 0) := by + intro a ha b hb hab + change 0 ≤ a at ha + change 0 ≤ b at hb + rcases ha.eq_or_lt with ha | ha + · rw [← ha, growth_zero] + exact growth_nonneg (by linarith) hb + have hb0 : 0 < b := ha.trans_le hab + by_cases hb1 : b ≤ 1 + · rw [growth_small ha (hab.trans hb1), growth_small hb0 hb1] + have hrel := FiniteEntropy.relTerm_nonneg ha.le hb0.le (fun _ ↦ hb0) + rw [Real.log_div ha.ne' hb0.ne'] at hrel + have hlog : Real.log b ≤ 0 := Real.log_nonpos hb0.le hb1 + have hmul := mul_nonneg (sub_nonneg.2 hab) (show 0 ≤ x - 1 - Real.log b by linarith) + nlinarith + by_cases ha1 : 1 ≤ a + · rw [growth_large ha1, growth_large (le_of_not_ge hb1)] + exact mul_le_mul_of_nonneg_right hab (by linarith) + · rw [growth_small ha (le_of_not_ge ha1), growth_large (le_of_not_ge hb1)] + have hrel := FiniteEntropy.relTerm_nonneg ha.le (by norm_num : (0:ℝ) ≤ 1) + (fun _ ↦ by norm_num) + simp only [div_one] at hrel + have hamul := mul_nonneg (sub_nonneg.2 (le_of_not_ge ha1)) (show 0 ≤ x - 1 by linarith) + have hbmul := mul_nonneg (sub_nonneg.2 (le_of_not_ge hb1)) (show 0 ≤ x by linarith) + nlinarith + +lemma growth_le_twice {x s : ℝ} (hx : 1 ≤ x) (hs : 0 ≤ s) : + growth x s ≤ 2 * x * (s + Real.exp (-x)) := by + have hx0 : 0 ≤ x := by linarith + have hexp := Real.exp_pos (-x) + have hi (b : ℝ) (hb : Real.exp (-x) ≤ b) : growth x b ≤ 2 * x * b := by + have hb0 := hexp.trans_le hb + have hl : -Real.log b ≤ x := by + have := Real.log_le_log hexp hb + rw [Real.log_exp] at this + linarith + have hmax : max 0 (-Real.log b) ≤ x := max_le hx0 hl + simp only [growth, one_div, Real.log_inv] + nlinarith [mul_le_mul_of_nonneg_left hmax hb0.le] + by_cases h : Real.exp (-x) ≤ s + · have h' := hi s h + nlinarith [mul_nonneg hx0 hexp.le] + · have h' := (growth_mono hx hs hexp.le (le_of_not_ge h)).trans (hi _ le_rfl) + nlinarith [mul_nonneg hx0 hs] + +omit [Fintype V] in +lemma mass_union_le {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) (A B : Finset V) : + mass w (A ∪ B) ≤ mass w A + mass w B := by + have h := sum_union_inter (s₁ := A) (s₂ := B) (f := w) + have hn := mass_nonneg hw (A ∩ B) + change 0 ≤ ∑ u ∈ A ∩ B, w u at hn + change (∑ u ∈ A ∪ B, w u) ≤ (∑ u ∈ A, w u) + ∑ u ∈ B, w u + linarith + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/FiniteCoupling.lean b/lean/OAI/Combinatorics/CliqueFree/FiniteCoupling.lean new file mode 100644 index 0000000000000000000000000000000000000000..4b0d5626b2680fa7ac2d97bb99ef73445c4747b9 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/FiniteCoupling.lean @@ -0,0 +1,386 @@ +import OAI.Combinatorics.CliqueFree.Model + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence + +universe u v + +namespace FiniteCoupling +universe z +variable {I : Type u} {J : Type v} {E : Type z} +variable [Fintype I] [Fintype J] [Fintype E] +local instance : DecidableEq I := Classical.decEq I +local instance : DecidableEq J := Classical.decEq J +local instance : DecidableEq E := Classical.decEq E + +abbrev Law (p : I → ℝ) : Prop := (∀ i, 0 ≤ p i) ∧ ∑ i, p i = 1 +noncomputable def dist (p q : I → ℝ) : ℝ := (∑ i, |p i - q i|) / 2 + +def push (p : I → ℝ) (f : I → J) (y : J) : ℝ := ∑ i, if f i = y then p i else 0 + +def mix (p : I → ℝ) (q : I → J → ℝ) (y : J) : ℝ := ∑ i, p i * q i y + +lemma sum_push (p : I → ℝ) (f : I → J) (g : J → ℝ) : + ∑ y, push p f y * g y = ∑ i, p i * g (f i) := by + simp only [push, sum_mul] + rw [sum_comm] + apply sum_congr rfl + intro i _ + simp [ite_mul] + +lemma law_push {p : I → ℝ} (hp : Law p) (f : I → J) : Law (push p f) := by + refine ⟨fun y ↦ sum_nonneg fun i _ ↦ by split_ifs <;> simp_all, ?_⟩ + have h := sum_push p f (fun _ ↦ 1) + simpa [hp.2] using h + +lemma sum_mix (p : I → ℝ) (q : I → J → ℝ) (g : J → ℝ) : + ∑ y, mix p q y * g y = ∑ i, p i * ∑ y, q i y * g y := by + simp only [mix, sum_mul, mul_sum, mul_assoc] + exact sum_comm + +lemma law_mix {p : I → ℝ} {q : I → J → ℝ} (hp : Law p) (hq : ∀ i, Law (q i)) : + Law (mix p q) := by + refine ⟨fun y ↦ sum_nonneg fun i _ ↦ mul_nonneg (hp.1 i) ((hq i).1 y), ?_⟩ + have h := sum_mix p q (fun _ ↦ 1) + simpa only [mul_one, (hq _).2, hp.2] using h + +lemma law_dirac (j : J) : Law (fun y ↦ if y = j then (1 : ℝ) else 0) := by + constructor + · intro y; dsimp; split_ifs <;> norm_num + · simp + +lemma prob_event_le_one {p : I → ℝ} (hp : Law p) (b : I → Prop) [DecidablePred b] : + (∑ i, if b i then p i else 0) ≤ 1 := by + rw [← hp.2] + apply sum_le_sum + intro i _ + split_ifs <;> simp_all + +lemma expected_indicator_push {p : I → ℝ} (f : I → J) (b : J → Prop) [DecidablePred b] : + (∑ y, if b y then push p f y else 0) = ∑ i, if b (f i) then p i else 0 := by + simpa only [mul_ite, mul_one, mul_zero] using sum_push p f (fun y ↦ if b y then 1 else 0) + +lemma expected_indicator_mix (p : I → ℝ) (q : I → J → ℝ) (b : J → Prop) [DecidablePred b] : + (∑ y, if b y then mix p q y else 0) = + ∑ i, p i * ∑ y, if b y then q i y else 0 := by + simpa only [mul_ite, mul_one, mul_zero] using sum_mix p q (fun y ↦ if b y then 1 else 0) + +open MeasureTheory in +lemma exists_threshold_law (a : I → ℝ) (ha0 : ∀ i, 0 ≤ a i) (ha1 : ∀ i, a i ≤ 1) : + ∃ q : Finset I → ℝ, Law q ∧ + (∀ i, (∑ A, if i ∈ A then q A else 0) = a i) ∧ + (∀ i j, (∑ A, if i ∈ A ∧ j ∈ A then q A else 0) = min (a i) (a j)) := by + let μ : Measure ℝ := volume.restrict (Set.Icc 0 1) + have : IsFiniteMeasure μ := by + refine ⟨?_⟩ + simp [μ, Real.volume_Icc] + let f : ℝ → Finset I := fun t ↦ univ.filter (fun i ↦ t ≤ a i) + have hf : ∀ A, MeasurableSet (f ⁻¹' {A}) := by + intro A + have heq : f ⁻¹' {A} = ⋂ i, {t : ℝ | (t ≤ a i ↔ i ∈ A)} := by + ext t + simp only [Set.mem_preimage, Set.mem_singleton_iff, Finset.ext_iff, + f, mem_filter, mem_univ, true_and, Set.mem_iInter, Set.mem_ofPred_eq] + rw [heq] + apply MeasurableSet.iInter + intro i + by_cases hi : i ∈ A + · simpa only [hi, iff_true, Set.Iic] using (measurableSet_Iic : MeasurableSet (Set.Iic (a i))) + · simpa only [hi, iff_false, not_le, Set.Ioi] using (measurableSet_Ioi : MeasurableSet (Set.Ioi (a i))) + let q : Finset I → ℝ := fun A ↦ μ.real (f ⁻¹' {A}) + have hevent (b : Finset I → Prop) [DecidablePred b] : + (∑ A, if b A then q A else 0) = μ.real {t | b (f t)} := by + rw [← sum_filter] + have h := sum_measureReal_preimage_singleton (μ := μ) (univ.filter b) (fun A _ ↦ hf A) + convert h using 1; simp + have hmass (c : ℝ) (hc0 : 0 ≤ c) (hc1 : c ≤ 1) : + μ.real {t | t ≤ c} = c := by + change (volume.restrict (Set.Icc (0 : ℝ) 1)).real (Set.Iic c) = c + rw [measureReal_restrict_apply measurableSet_Iic] + have heq : Set.Iic c ∩ Set.Icc (0 : ℝ) 1 = Set.Icc 0 c := by + ext t + simp only [Set.mem_inter_iff, Set.mem_Iic, Set.mem_Icc] + constructor + · rintro ⟨ht, h0, _⟩; exact ⟨h0, ht⟩ + · rintro ⟨h0, htc⟩; exact ⟨htc, h0, htc.trans hc1⟩ + change volume.real (Set.Iic c ∩ Set.Icc (0 : ℝ) 1) = _ + rw [heq, measureReal_def, Real.volume_Icc] + simpa using ENNReal.toReal_ofReal hc0 + refine ⟨q, ⟨fun A ↦ measureReal_nonneg, ?_⟩, ?_, ?_⟩ + · have h := hevent (fun _ ↦ True) + simpa [μ, measureReal_def, Real.volume_Icc] using h + · intro i + trans μ.real {t | i ∈ f t} + · exact hevent (fun A ↦ i ∈ A) + simpa only [f, mem_filter, mem_univ, true_and] using hmass (a i) (ha0 i) (ha1 i) + · intro i j + trans μ.real {t | i ∈ f t ∧ j ∈ f t} + · exact hevent (fun A ↦ i ∈ A ∧ j ∈ A) + simpa only [f, mem_filter, mem_univ, true_and, le_min_iff] using + hmass (min (a i) (a j)) (le_min (ha0 i) (ha0 j)) ((min_le_left _ _).trans (ha1 i)) + +/-- A finite version of the first-accepted-trial construction, with states the +set of unfinished rows. The recursion strictly decreases that finite set. -/ +lemma joint_of_trials [Nonempty J] (p : I → J → ℝ) (hp : ∀ i, Law (p i)) + (t : E → ℝ) (ht : ∀ e, 0 ≤ t e) (A : E → Finset I) (label : E → J) + (hmarg : ∀ i y, (∑ e, if i ∈ A e ∧ label e = y then t e else 0) = p i y) + (D : I → I → ℝ) + (hpair : ∀ i j, + (∑ e, if Xor (i ∈ A e) (j ∈ A e) then t e else 0) ≤ + D i j * (∑ e, if i ∈ A e ∨ j ∈ A e then t e else 0)) : + ∃ q : (I → J) → ℝ, Law q ∧ + (∀ i y, (∑ f, if f i = y then q f else 0) = p i y) ∧ + (∀ i j, (∑ f, if f i ≠ f j then q f else 0) ≤ D i j) := by + have hacc (i : I) : (∑ e, if i ∈ A e then t e else 0) = 1 := by + have h := congrArg (fun g : J → ℝ ↦ ∑ y, g y) (funext (hmarg i)) + change (∑ y, ∑ e, if i ∈ A e ∧ label e = y then t e else 0) = ∑ y, p i y at h + rw [sum_comm, (hp i).2] at h + convert h using 1 + apply sum_congr rfl + intro e _ + by_cases hi : i ∈ A e <;> simp [hi] + let base : I → J := fun _ ↦ Classical.choice (inferInstance : Nonempty J) + have hpartial (S : Finset I) : + ∃ q : (I → J) → ℝ, Law q ∧ + (∀ i ∈ S, ∀ y, (∑ f, if f i = y then q f else 0) = p i y) ∧ + (∀ i ∈ S, ∀ j ∈ S, (∑ f, if f i ≠ f j then q f else 0) ≤ D i j) := by + refine Finset.strongInductionOn S ?_ + intro S ih + by_cases hS : S.Nonempty + · let active : E → Prop := fun e ↦ (S ∩ A e).Nonempty + let r : E → ℝ := fun e ↦ if active e then t e else 0 + let Q : ℝ := ∑ e, r e + have hr (e : E) : 0 ≤ r e := by dsimp [r]; split_ifs <;> simp_all + have hactive (i : I) (hi : i ∈ S) (e : E) (ha : i ∈ A e) : active e := + ⟨i, mem_inter.2 ⟨hi, ha⟩⟩ + have hQ : 0 < Q := by + obtain ⟨i, hi⟩ := hS + have hle : (∑ e, if i ∈ A e then t e else 0) ≤ Q := by + apply sum_le_sum + intro e _ + by_cases ha : i ∈ A e + · simp only [ha, ↓reduceIte, r, hactive i hi e ha, le_refl] + · simpa only [ha, ↓reduceIte] using hr e + rw [hacc] at hle + linarith + have hrec (e : E) : ∃ q : (I → J) → ℝ, Law q ∧ + (active e → + (∀ i ∈ S \ A e, ∀ y, (∑ f, if f i = y then q f else 0) = p i y) ∧ + (∀ i ∈ S \ A e, ∀ j ∈ S \ A e, + (∑ f, if f i ≠ f j then q f else 0) ≤ D i j)) := by + by_cases he : active e + · have hlt : S \ A e ⊂ S := by + refine Finset.ssubset_iff_subset_ne.2 ⟨sdiff_subset, ?_⟩ + intro heq + obtain ⟨i, hi⟩ := he + obtain ⟨hiS, hiA⟩ := mem_inter.1 hi + rw [← heq] at hiS + exact (mem_sdiff.1 hiS).2 hiA + obtain ⟨q, hq, hqm, hqd⟩ := ih (S \ A e) hlt + exact ⟨q, hq, fun _ ↦ ⟨hqm, hqd⟩⟩ + · exact ⟨_, law_dirac base, fun h ↦ (he h).elim⟩ + choose q hq hqrec using hrec + let update : E → (I → J) → (I → J) := + fun e f i ↦ if i ∈ A e then label e else f i + let coeff : E → ℝ := fun e ↦ r e / Q + have hcoeff : Law coeff := by + refine ⟨fun e ↦ div_nonneg (hr e) hQ.le, ?_⟩ + dsimp [coeff] + rw [← sum_div] + exact div_self hQ.ne' + let out : (I → J) → ℝ := mix coeff (fun e ↦ push (q e) (update e)) + refine ⟨out, law_mix hcoeff (fun e ↦ law_push (hq e) (update e)), ?_, ?_⟩ + · intro i hi y + change (∑ f, if f i = y then mix coeff (fun e ↦ push (q e) (update e)) f else 0) = _ + rw [expected_indicator_mix] + simp_rw [expected_indicator_push] + have heq (e : E) : + r e * (∑ f, if update e f i = y then q e f else 0) = + (if i ∈ A e ∧ label e = y then t e else 0) + + p i y * (r e - if i ∈ A e then t e else 0) := by + by_cases ha : i ∈ A e + · have hb := hactive i hi e ha + simp only [update, ha, ↓reduceIte, r, hb, true_and, sub_self, mul_zero, add_zero, + sum_ite_irrel, (hq e).2] + split_ifs <;> simp + · have hni : i ∈ S \ A e := mem_sdiff.2 ⟨hi, ha⟩ + by_cases hb : active e + · have hm := (hqrec e hb).1 i hni y + simp only [update, ha, ↓reduceIte, false_and, r, hb, sub_zero, zero_add] at * + rw [hm] + ring + · simp [r, hb, ha] + simp only [coeff, div_mul_eq_mul_div, ← sum_div] + simp_rw [heq] + rw [sum_add_distrib, ← mul_sum, sum_sub_distrib, hmarg, hacc] + change (p i y + p i y * (Q - 1)) / Q = p i y + field_simp + ring + · intro i hi j hj + change (∑ f, if f i ≠ f j then mix coeff (fun e ↦ push (q e) (update e)) f else 0) ≤ _ + have hem : (∑ f, if f i ≠ f j then mix coeff (fun e ↦ push (q e) (update e)) f else 0) = + ∑ e, coeff e * ∑ f, if f i ≠ f j then push (q e) (update e) f else 0 := + expected_indicator_mix coeff (fun e ↦ push (q e) (update e)) (fun f ↦ f i ≠ f j) + rw [hem] + simp_rw [expected_indicator_push] + have he (e : E) : + r e * (∑ f, if update e f i ≠ update e f j then q e f else 0) ≤ + D i j * r e + (if Xor (i ∈ A e) (j ∈ A e) then t e else 0) - + D i j * (if i ∈ A e ∨ j ∈ A e then t e else 0) := by + by_cases hai : i ∈ A e <;> by_cases haj : j ∈ A e + · have hb := hactive i hi e hai + simp [update, hai, haj, r, hb, Xor] + · have hb := hactive i hi e hai + have hle := mul_le_mul_of_nonneg_left + (prob_event_le_one (hq e) (fun f ↦ label e ≠ f j)) (ht e) + simpa [update, hai, haj, r, hb, Xor] using hle + · have hb := hactive j hj e haj + have hle := mul_le_mul_of_nonneg_left + (prob_event_le_one (hq e) (fun f ↦ f i ≠ label e)) (ht e) + simpa [update, hai, haj, r, hb, Xor] using hle + · by_cases hb : active e + · have hle := mul_le_mul_of_nonneg_left + ((hqrec e hb).2 i (mem_sdiff.2 ⟨hi, hai⟩) j (mem_sdiff.2 ⟨hj, haj⟩)) (ht e) + simpa [update, hai, haj, r, hb, Xor, mul_comm] using hle + · simp [r, hb, hai, haj, Xor] + have hsum := sum_le_sum (s := univ) (fun e _ ↦ he e) + rw [sum_sub_distrib, sum_add_distrib, ← mul_sum, ← mul_sum] at hsum + have hbound : (∑ e, r e * ∑ f, if update e f i ≠ update e f j then q e f else 0) ≤ + D i j * Q := by + have hpij := hpair i j + dsimp [Q] + linarith + simp only [coeff, div_mul_eq_mul_div, ← sum_div] + exact (div_le_iff₀ hQ).2 (by nlinarith [hbound]) + · refine ⟨_, law_dirac base, ?_, ?_⟩ <;> simp_all + obtain ⟨q, hq, hm, hd⟩ := hpartial univ + exact ⟨q, hq, fun i ↦ hm i (mem_univ i), fun i j ↦ hd i (mem_univ i) j (mem_univ j)⟩ + +lemma sum_abs_eq (a b : ℝ) : a + b - 2 * min a b = |a - b| := by + rcases le_total a b with h | h + · rw [min_eq_left h, abs_of_nonpos (sub_nonpos.2 h)]; ring + · rw [min_eq_right h, abs_of_nonneg (sub_nonneg.2 h)]; ring + +/-- The joint finite law in the shared rejection lemma, with its sharp bound. -/ +lemma shared_rejection [Nonempty J] (p : I → J → ℝ) (hp : ∀ i, Law (p i)) : + ∃ q : (I → J) → ℝ, Law q ∧ + (∀ i y, (∑ f, if f i = y then q f else 0) = p i y) ∧ + (∀ i j, (∑ f, if f i ≠ f j then q f else 0) ≤ + 2 * dist (p i) (p j) / (1 + dist (p i) (p j))) := by + have hbound (i : I) (y : J) : p i y ≤ 1 := by + rw [← (hp i).2] + exact single_le_sum (fun z _ ↦ (hp i).1 z) (mem_univ y) + have hex (y : J) := exists_threshold_law (fun i ↦ p i y) (fun i ↦ (hp i).1 y) (fun i ↦ hbound i y) + choose q hq hsingle hboth using hex + let t : J × Finset I → ℝ := fun e ↦ q e.1 e.2 + have hmarg (i : I) (y : J) : + (∑ e : J × Finset I, if i ∈ e.2 ∧ e.1 = y then t e else 0) = p i y := by + rw [Fintype.sum_prod_type] + calc + _ = ∑ z, if z = y then (∑ A, if i ∈ A then q z A else 0) else 0 := by + apply sum_congr rfl + intro z _ + by_cases hz : z = y <;> simp [hz, t] + _ = _ := by simp [hsingle] + have hxor (i j : I) (y : J) : + (∑ A, if Xor (i ∈ A) (j ∈ A) then q y A else 0) = |p i y - p j y| := by + calc + _ = ∑ A, ((if i ∈ A then q y A else 0) + (if j ∈ A then q y A else 0) - + 2 * (if i ∈ A ∧ j ∈ A then q y A else 0)) := by + apply sum_congr rfl + intro A _ + by_cases hi : i ∈ A <;> by_cases hj : j ∈ A <;> simp [hi, hj, Xor] + ring + _ = _ := by + rw [sum_sub_distrib, sum_add_distrib, ← mul_sum, hsingle, hsingle, hboth] + exact sum_abs_eq _ _ + have hor (i j : I) (y : J) : + (∑ A, if i ∈ A ∨ j ∈ A then q y A else 0) = + (p i y + p j y + |p i y - p j y|) / 2 := by + calc + _ = ∑ A, ((if i ∈ A then q y A else 0) + (if j ∈ A then q y A else 0) - + (if i ∈ A ∧ j ∈ A then q y A else 0)) := by + apply sum_congr rfl + intro A _ + by_cases hi : i ∈ A <;> by_cases hj : j ∈ A <;> simp [hi, hj] + _ = _ := by + rw [sum_sub_distrib, sum_add_distrib, hsingle, hsingle, hboth] + linarith [sum_abs_eq (p i y) (p j y)] + have hdist0 (i j : I) : 0 ≤ dist (p i) (p j) := + div_nonneg (sum_nonneg fun _ _ ↦ abs_nonneg _) (by norm_num) + apply joint_of_trials p hp t (fun e ↦ (hq e.1).1 e.2) Prod.snd Prod.fst hmarg + (fun i j ↦ 2 * dist (p i) (p j) / (1 + dist (p i) (p j))) + intro i j + have hden : 1 + dist (p i) (p j) ≠ 0 := by linarith [hdist0 i j] + have hX : (∑ e : J × Finset I, if Xor (i ∈ e.2) (j ∈ e.2) then t e else 0) = + 2 * dist (p i) (p j) := by + rw [Fintype.sum_prod_type] + simp only [t, hxor, dist] + ring + have hU : (∑ e : J × Finset I, if i ∈ e.2 ∨ j ∈ e.2 then t e else 0) = + 1 + dist (p i) (p j) := by + rw [Fintype.sum_prod_type] + simp only [t, hor, ← sum_div, sum_add_distrib, (hp i).2, (hp j).2, dist] + ring + change (∑ e : J × Finset I, if Xor (i ∈ e.2) (j ∈ e.2) then t e else 0) ≤ _ + rw [hX, hU, div_mul_cancel₀ _ hden] + +lemma sharp_bound_le (p q : I → ℝ) : 2 * dist p q / (1 + dist p q) ≤ 2 * dist p q := by + have hd : 0 ≤ dist p q := div_nonneg (sum_nonneg fun _ _ ↦ abs_nonneg _) (by norm_num) + apply div_le_self (by positivity) (by linarith) + +lemma positive_output {p : I → J → ℝ} {q : (I → J) → ℝ} (hq : Law q) + (hm : ∀ i y, (∑ f, if f i = y then q f else 0) = p i y) + {f : I → J} (hf : 0 < q f) (i : I) : 0 < p i (f i) := by + rw [← hm] + exact hf.trans_le (by + have h := single_le_sum (s := univ) (a := f) + (f := fun g ↦ if g i = f i then q g else 0) + (fun g _ ↦ by split_ifs <;> simp_all [hq.1 g]) (mem_univ f) + simpa using h) + +lemma marginal_expectation {p : I → J → ℝ} {q : (I → J) → ℝ} + (hm : ∀ i y, (∑ f, if f i = y then q f else 0) = p i y) (i : I) (g : J → ℝ) : + (∑ f, q f * g (f i)) = ∑ y, p i y * g y := by + have h := sum_push q (fun f ↦ f i) g + simpa only [push, hm] using h.symm + +lemma exists_positive_ge {q : I → ℝ} (hq : Law q) (f : I → ℝ) {L : ℝ} + (hL : L ≤ ∑ i, q i * f i) : ∃ i, 0 < q i ∧ L ≤ f i := by + by_contra h + have hf : ∀ i, 0 < q i → f i < L := by + intro i hi + by_contra hn + exact h ⟨i, hi, le_of_not_gt hn⟩ + obtain ⟨i, _, hi⟩ := (sum_pos_iff_of_nonneg (fun j (_ : j ∈ univ) ↦ hq.1 j)).1 + (show 0 < ∑ j, q j by rw [hq.2]; norm_num) + have hlt : (∑ j, q j * f j) < ∑ j, q j * L := by + apply sum_lt_sum + · intro j _ + rcases (hq.1 j).eq_or_lt with hj | hj + · simp [← hj] + · exact (mul_lt_mul_of_pos_left (hf j hj) hj).le + · exact ⟨i, mem_univ i, mul_lt_mul_of_pos_left (hf i hi) hi⟩ + rw [← sum_mul, hq.2, one_mul] at hlt + linarith + +noncomputable def bad (p : Prop) : ℝ := if p then 0 else 1 + +lemma bad_and (p q : Prop) : bad (p ∧ q) ≤ bad p + bad q := by + by_cases hp : p <;> by_cases hq : q <;> simp [bad, hp, hq] + +end FiniteCoupling + +end CliqueFreeIndependence + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/FiniteEntropy.lean b/lean/OAI/Combinatorics/CliqueFree/FiniteEntropy.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e8162528b4e2d4ca6af02274dd67c5c27b4234b --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/FiniteEntropy.lean @@ -0,0 +1,365 @@ +import OAI.Combinatorics.CliqueFree.Model + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence + +universe u v + +namespace FiniteEntropy + +variable {I : Type u} [Fintype I] + +/-- A finite real-valued probability vector. -/ +def IsProb (p : I → ℝ) : Prop := (∀ i, 0 ≤ p i) ∧ ∑ i, p i = 1 + +/-- Weighted row entropy, with the `0 log 0 = 0` convention. -/ +def entropy (w p : I → ℝ) : ℝ := ∑ i, p i * Real.log (w i / p i) + +/-- Relative entropy, used only when `q` is positive on the positive support of `p`. -/ +def divergence (p q : I → ℝ) : ℝ := ∑ i, p i * Real.log (p i / q i) + +/-- Total variation distance of two finite probability vectors. -/ +def tv (p q : I → ℝ) : ℝ := (∑ i, |p i - q i|) / 2 + +lemma relTerm_nonneg {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) + (hs : 0 < p → 0 < q) : 0 ≤ p * Real.log (p / q) - p + q := by + rcases hp.eq_or_lt with hp | hp + · simp [← hp, hq] + have hq' := hs hp + have h := Real.log_le_sub_one_of_pos (div_pos hq' hp) + have hl : Real.log (q / p) = -Real.log (p / q) := by + rw [Real.log_div hq'.ne' hp.ne', Real.log_div hp.ne' hq'.ne'] + ring + rw [hl] at h + have hm := mul_le_mul_of_nonneg_left h hp.le + have hc : p * (q / p - 1) = q - p := by field_simp + rw [hc] at hm + linarith + +lemma sqrt_sub_sq_le_relTerm {p q : ℝ} (hp : 0 ≤ p) (hq : 0 ≤ q) + (hs : 0 < p → 0 < q) : + (Real.sqrt p - Real.sqrt q) ^ 2 ≤ p * Real.log (p / q) - p + q := by + rcases hp.eq_or_lt with hp | hp + · simp [← hp, Real.sq_sqrt hq] + have hq' := hs hp + have hsp := Real.sqrt_pos.2 hp + have hsq := Real.sqrt_pos.2 hq' + have h := Real.log_le_sub_one_of_pos (div_pos hsq hsp) + have hl : Real.log (Real.sqrt q / Real.sqrt p) = -(Real.log (p / q)) / 2 := by + rw [Real.log_div hsq.ne' hsp.ne', Real.log_sqrt hq, Real.log_sqrt hp.le, + Real.log_div hp.ne' hq'.ne'] + ring + rw [hl] at h + have hm := mul_le_mul_of_nonneg_left h (show 0 ≤ 2 * p by positivity) + have hc : p * (Real.sqrt q / Real.sqrt p) = Real.sqrt p * Real.sqrt q := by + calc + _ = (Real.sqrt p) ^ 2 * (Real.sqrt q / Real.sqrt p) := by rw [Real.sq_sqrt hp.le] + _ = Real.sqrt p * Real.sqrt q := by field_simp + have hp2 := Real.sq_sqrt hp.le + have hq2 := Real.sq_sqrt hq + nlinarith + +lemma divergence_nonneg {p q : I → ℝ} (hp : IsProb p) (hq : IsProb q) + (hs : ∀ i, 0 < p i → 0 < q i) : 0 ≤ divergence p q := by + have h := sum_nonneg (s := univ) fun i _ ↦ relTerm_nonneg (hp.1 i) (hq.1 i) (hs i) + simpa [divergence, sum_add_distrib, sum_sub_distrib, hp.2, hq.2] using h + +lemma hellinger_le_divergence {p q : I → ℝ} (hp : IsProb p) (hq : IsProb q) + (hs : ∀ i, 0 < p i → 0 < q i) : + (∑ i, (Real.sqrt (p i) - Real.sqrt (q i)) ^ 2) ≤ divergence p q := by + have h := sum_le_sum (s := univ) fun i _ ↦ + sqrt_sub_sq_le_relTerm (hp.1 i) (hq.1 i) (hs i) + simpa [divergence, sum_add_distrib, sum_sub_distrib, hp.2, hq.2] using h + +lemma tv_nonneg (p q : I → ℝ) : 0 ≤ tv p q := by + exact div_nonneg (sum_nonneg fun _ _ ↦ abs_nonneg _) (by norm_num) + +lemma tv_sq_le_hellinger {p q : I → ℝ} (hp : IsProb p) (hq : IsProb q) : + tv p q ^ 2 ≤ ∑ i, (Real.sqrt (p i) - Real.sqrt (q i)) ^ 2 := by + let f := fun i ↦ |Real.sqrt (p i) - Real.sqrt (q i)| + let g := fun i ↦ Real.sqrt (p i) + Real.sqrt (q i) + have hfactor (i : I) : |p i - q i| = f i * g i := by + have he : p i - q i = + (Real.sqrt (p i) - Real.sqrt (q i)) * + (Real.sqrt (p i) + Real.sqrt (q i)) := by + nlinarith [Real.sq_sqrt (hp.1 i), Real.sq_sqrt (hq.1 i)] + rw [he, abs_mul, abs_of_nonneg (by positivity : 0 ≤ Real.sqrt (p i) + Real.sqrt (q i))] + have hsum : (∑ i, f i ^ 2) + (∑ i, g i ^ 2) = 4 := by + rw [← sum_add_distrib] + calc + _ = (∑ i, (2 * p i + 2 * q i)) := by + apply sum_congr rfl + intro i _ + dsimp [f, g] + rw [sq_abs] + nlinarith [Real.sq_sqrt (hp.1 i), Real.sq_sqrt (hq.1 i)] + _ = 4 := by norm_num [sum_add_distrib, ← mul_sum, hp.2, hq.2] + have hf0 : 0 ≤ ∑ i, f i ^ 2 := sum_nonneg fun _ _ ↦ sq_nonneg _ + have hg4 : ∑ i, g i ^ 2 ≤ 4 := by linarith + have hc := sum_mul_sq_le_sq_mul_sq univ f g + have hle := mul_le_mul_of_nonneg_left hg4 hf0 + have he : (∑ i, f i ^ 2) = ∑ i, (Real.sqrt (p i) - Real.sqrt (q i)) ^ 2 := by + simp [f] + rw [tv, show (∑ i, |p i - q i|) = ∑ i, f i * g i from sum_congr rfl (fun i _ ↦ hfactor i)] + rw [← he] + nlinarith + +lemma entropy_eq_sum {w p : I → ℝ} (hw : ∀ i, 0 < w i) (hp : ∀ i, 0 ≤ p i) : + entropy w p = ∑ i, (p i * Real.log (w i) - p i * Real.log (p i)) := by + apply sum_congr rfl + intro i _ + rcases (hp i).eq_or_lt with hi | hi + · simp [← hi] + · rw [Real.log_div (hw i).ne' hi.ne', mul_sub] + +lemma divergence_eq_sum {p q : I → ℝ} (hp : ∀ i, 0 ≤ p i) + (hs : ∀ i, 0 < p i → 0 < q i) : + divergence p q = ∑ i, (p i * Real.log (p i) - p i * Real.log (q i)) := by + apply sum_congr rfl + intro i _ + rcases (hp i).eq_or_lt with hi | hi + · simp [← hi] + · rw [Real.log_div hi.ne' (hs i hi).ne', mul_sub] + +lemma entropy_ge_neg_log_of_density {w p : I → ℝ} (_hw : ∀ i, 0 < w i) + (hp : IsProb p) {b : ℝ} (hb : 0 < b) (hden : ∀ i, p i ≤ b * w i) : + -Real.log b ≤ entropy w p := by + have hi (i : I) : p i * (-Real.log b) ≤ p i * Real.log (w i / p i) := by + rcases (hp.1 i).eq_or_lt with hi | hi + · simp [← hi] + apply mul_le_mul_of_nonneg_left _ hi.le + rw [← Real.log_inv] + apply Real.log_le_log (inv_pos.2 hb) + apply (le_div_iff₀ hi).2 + calc + b⁻¹ * p i = p i / b := by ring + _ ≤ w i := (div_le_iff₀ hb).2 (by simpa [mul_comm] using hden i) + have h := sum_le_sum (s := univ) fun i _ ↦ hi i + simpa [← sum_mul, hp.2, entropy] using h + +lemma tv_comm (p q : I → ℝ) : tv p q = tv q p := by + simp only [tv, abs_sub_comm] + +lemma tv_triangle (p q r : I → ℝ) : tv p r ≤ tv p q + tv q r := by + have h := sum_le_sum (s := univ) fun i _ ↦ abs_sub_le (p i) (q i) (r i) + simpa only [sum_add_distrib, tv, ← add_div] using div_le_div_of_nonneg_right h (by norm_num : (0 : ℝ) ≤ 2) + +lemma weighted_sq_le {a f : I → ℝ} (ha : IsProb a) : + (∑ i, a i * f i) ^ 2 ≤ ∑ i, a i * (f i) ^ 2 := by + let m := ∑ i, a i * f i + have h := sum_nonneg (s := univ) fun i _ ↦ + mul_nonneg (ha.1 i) (sq_nonneg (f i - m)) + have he : (∑ i, a i * (f i - m) ^ 2) = (∑ i, a i * (f i) ^ 2) - m ^ 2 := by + calc + _ = ∑ i, (a i * (f i) ^ 2 - 2 * (a i * f i) * m + a i * m ^ 2) := by + apply sum_congr rfl + intro i _ + ring + _ = _ := by + rw [sum_add_distrib, sum_sub_distrib, ← sum_mul, ← mul_sum, ← sum_mul, ha.2] + dsimp [m] + ring + rw [he] at h + dsimp [m] at h + linarith + +variable {J : Type v} [Fintype J] + +/-- Mixing finitely many probability vectors. -/ +lemma mix_isProb {a : J → ℝ} {p : J → I → ℝ} (ha : IsProb a) + (hp : ∀ j, IsProb (p j)) : IsProb (fun i ↦ ∑ j, a j * p j i) := by + refine ⟨fun i ↦ sum_nonneg fun j _ ↦ mul_nonneg (ha.1 j) ((hp j).1 i), ?_⟩ + rw [sum_comm] + simp_rw [← mul_sum, fun j ↦ (hp j).2, mul_one] + exact ha.2 + +omit [Fintype I] in +lemma mix_support {a : J → ℝ} {p : J → I → ℝ} (ha : ∀ j, 0 ≤ a j) + (hp : ∀ j i, 0 ≤ p j i) {j : J} (hj : 0 < a j) {i : I} (hi : 0 < p j i) : + 0 < ∑ k, a k * p k i := by + classical + exact (mul_pos hj hi).trans_le (single_le_sum + (fun k _ ↦ mul_nonneg (ha k) (hp k i)) (mem_univ j)) + +/-- The finite entropy-mixture identity for the averaged increment. -/ +lemma entropy_mix_gap {w : I → ℝ} (hw : ∀ i, 0 < w i) + {a : J → ℝ} {p : J → I → ℝ} (ha : IsProb a) (hp : ∀ j, IsProb (p j)) : + entropy w (fun i ↦ ∑ j, a j * p j i) - ∑ j, a j * entropy w (p j) = + ∑ j, a j * divergence (p j) (fun i ↦ ∑ k, a k * p k i) := by + let b := fun i ↦ ∑ j, a j * p j i + have hb := mix_isProb ha hp + have hd (j : J) : a j * divergence (p j) b = + a j * (∑ i, (p j i * Real.log (p j i) - p j i * Real.log (b i))) := by + rcases (ha.1 j).eq_or_lt with hj | hj + · simp [← hj] + · rw [divergence_eq_sum (hp j).1 + (fun i hi ↦ mix_support ha.1 (fun k ↦ (hp k).1) hj hi)] + change entropy w b - ∑ j, a j * entropy w (p j) = ∑ j, a j * divergence (p j) b + rw [entropy_eq_sum hw hb.1] + simp_rw [entropy_eq_sum hw (hp _).1, hd, mul_sum, mul_sub, sum_sub_distrib] + have he (f : I → ℝ) : (∑ i, b i * f i) = ∑ j, ∑ i, a j * (p j i * f i) := by + dsimp [b] + simp_rw [sum_mul, mul_assoc] + rw [sum_comm] + rw [he, he] + ring + +lemma average_tv_sq_le_average_divergence {a : J → ℝ} (ha : IsProb a) + {p q : J → I → ℝ} (hp : ∀ j, IsProb (p j)) (hq : ∀ j, IsProb (q j)) + (hs : ∀ j, 0 < a j → ∀ i, 0 < p j i → 0 < q j i) : + (∑ j, a j * tv (p j) (q j)) ^ 2 ≤ ∑ j, a j * divergence (p j) (q j) := by + apply (weighted_sq_le ha).trans + apply sum_le_sum + intro j _ + rcases (ha.1 j).eq_or_lt with hj | hj + · simp [← hj] + apply mul_le_mul_of_nonneg_left _ hj.le + exact (tv_sq_le_hellinger (hp j) (hq j)).trans + (hellinger_le_divergence (hp j) (hq j) (hs j hj)) + +omit [Fintype I] in +lemma mul_log_div {p w : ℝ} (hp : 0 ≤ p) (hw : 0 < w) : + p * Real.log (w / p) = p * Real.log w - p * Real.log p := by + rcases hp.eq_or_lt with hp | hp + · simp [← hp] + · rw [Real.log_div hw.ne' hp.ne', mul_sub] + +omit [Fintype I] in +lemma partial_entropy_le (s : Finset I) {w p : I → ℝ} + (hw : ∀ i ∈ s, 0 < w i) (hp : ∀ i ∈ s, 0 ≤ p i) + {m : ℝ} (hm : 0 < m) (hwm : ∑ i ∈ s, w i ≤ m) : + (∑ i ∈ s, p i * Real.log (w i / p i)) ≤ + (∑ i ∈ s, p i) * Real.log (m / (∑ i ∈ s, p i)) := by + let t := ∑ i ∈ s, p i + have ht : 0 ≤ t := sum_nonneg hp + rcases ht.eq_or_lt with ht | ht + · have hz : ∀ i ∈ s, p i = 0 := (sum_eq_zero_iff_of_nonneg hp).1 ht.symm + simp only [show (∑ i ∈ s, p i) = 0 from ht.symm, zero_mul] + apply le_of_eq + exact sum_eq_zero (fun i hi ↦ by rw [hz i hi, zero_mul]) + have hi (i : I) (his : i ∈ s) : + p i * Real.log (w i / p i) ≤ p i * Real.log (m / t) - p i + t * w i / m := by + rcases (hp i his).eq_or_lt with hpi | hpi + · simp only [← hpi, zero_mul, sub_self, zero_add] + exact (div_pos (mul_pos ht (hw i his)) hm).le + have hq : 0 < t * w i / m := div_pos (mul_pos ht (hw i his)) hm + have hr := relTerm_nonneg hpi.le hq.le (fun _ ↦ hq) + have hl : Real.log (p i / (t * w i / m)) = + Real.log (m / t) - Real.log (w i / p i) := by + rw [Real.log_div hpi.ne' hq.ne', + Real.log_div (mul_pos ht (hw i his)).ne' hm.ne', + Real.log_mul ht.ne' (hw i his).ne', + Real.log_div hm.ne' ht.ne', Real.log_div (hw i his).ne' hpi.ne'] + ring + rw [hl] at hr + nlinarith + have h := sum_le_sum hi + simp only [sum_add_distrib, sum_sub_distrib, ← sum_mul, ← sum_div, ← mul_sum] at h + have hq : t * (∑ i ∈ s, w i) / m ≤ t := by + apply (div_le_iff₀ hm).2 + exact mul_le_mul_of_nonneg_left hwm ht.le + change (∑ i ∈ s, p i * Real.log (w i / p i)) ≤ t * Real.log (m / t) + change (∑ i ∈ s, p i * Real.log (w i / p i)) ≤ + t * Real.log (m / t) - t + t * (∑ i ∈ s, w i) / m at h + linarith + +lemma prob_sum_on {p : I → ℝ} (hp : IsProb p) (D : Finset I) + (hs : ∀ i, i ∉ D → p i = 0) : ∑ i ∈ D, p i = 1 := by + rw [← hp.2] + exact sum_subset (subset_univ _) (fun i _ hi ↦ hs i hi) + +lemma entropy_sum_on {w p : I → ℝ} (D : Finset I) + (hs : ∀ i, i ∉ D → p i = 0) : entropy w p = ∑ i ∈ D, p i * Real.log (w i / p i) := by + symm + apply sum_subset (subset_univ _) + intro i _ hi + rw [hs i hi, zero_mul] + +lemma entropy_supported_le_log (D : Finset I) {w p : I → ℝ} + (hw : ∀ i ∈ D, 0 < w i) (hp : IsProb p) + (hs : ∀ i, i ∉ D → p i = 0) {m : ℝ} (hm : 0 < m) (hwm : ∑ i ∈ D, w i ≤ m) : + entropy w p ≤ Real.log m := by + have h := partial_entropy_le D hw (fun i _ ↦ hp.1 i) hm hwm + simpa only [prob_sum_on hp D hs, div_one, one_mul, ← entropy_sum_on D hs] using h + +lemma entropy_supported_concentration (D s : Finset I) (hsD : s ⊆ D) {w p : I → ℝ} + (hw : ∀ i ∈ D, 0 < w i) (hp : IsProb p) (hs : ∀ i, i ∉ D → p i = 0) + {m M : ℝ} (hm : 1 ≤ m) (hM : 0 < M) + (hwsmall : ∑ i ∈ s, w i ≤ m) (hwall : ∑ i ∈ D, w i ≤ M) : + entropy w p ≤ Real.log 2 + Real.log m + (1 - ∑ i ∈ s, p i) * Real.log M := by + classical + let t := ∑ i ∈ s, p i + let d := ∑ i ∈ D \ s, p i + have ht : 0 ≤ t := sum_nonneg fun i _ ↦ hp.1 i + have hd : 0 ≤ d := sum_nonneg fun i _ ↦ hp.1 i + have htd : d + t = 1 := by + dsimp [t, d] + rw [sum_sdiff hsD, prob_sum_on hp D hs] + have hm0 : 0 < m := lt_of_lt_of_le zero_lt_one hm + have hwc : (∑ i ∈ D \ s, w i) ≤ M := by + apply le_trans _ hwall + exact sum_le_sum_of_subset_of_nonneg sdiff_subset (fun i hi _ ↦ (hw i hi).le) + have ha := partial_entropy_le s (fun i hi ↦ hw i (hsD hi)) (fun i _ ↦ hp.1 i) hm0 hwsmall + have hc := partial_entropy_le (D \ s) (fun i hi ↦ hw i (mem_sdiff.1 hi).1) + (fun i _ ↦ hp.1 i) hM hwc + have he : entropy w p ≤ d * Real.log (M / d) + t * Real.log (m / t) := by + rw [entropy_sum_on D hs, ← sum_sdiff hsD] + exact add_le_add hc ha + rw [mul_log_div hd hM, mul_log_div ht hm0] at he + have hbin : -t * Real.log t - d * Real.log d ≤ Real.log 2 := by + have hb := Real.binEntropy_le_log_two (p := t) + have hd' : d = 1 - t := by linarith + rw [hd'] + simpa [Real.binEntropy, Real.log_inv] using hb + have hl := Real.log_nonneg hm + have ht1 : t ≤ 1 := by linarith + have hmterm : t * Real.log m ≤ Real.log m := by nlinarith + change entropy w p ≤ Real.log 2 + Real.log m + (1 - t) * Real.log M + have hd' : 1 - t = d := by linarith + rw [hd'] + linarith + +lemma entropy_tail_term {p w x a : ℝ} (hp : 0 ≤ p) (hw : 0 < w) + (hx : 0 < x) (hd : p ≤ x * w) : + (a + Real.log x) * (if p < w * Real.exp (-a) then p else 0) ≤ + p * (Real.log (w / p) + Real.log x) := by + rcases hp.eq_or_lt with hp | hp + · simp [← hp] + have hlog := Real.log_le_log hp hd + rw [Real.log_mul hx.ne' hw.ne'] at hlog + have hlower : 0 ≤ Real.log (w / p) + Real.log x := by + rw [Real.log_div hw.ne' hp.ne'] + linarith + split_ifs with hsmall + · have h := Real.log_lt_log hp hsmall + rw [Real.log_mul hw.ne' (Real.exp_ne_zero _), Real.log_exp] at h + have ha : a ≤ Real.log (w / p) := by + rw [Real.log_div hw.ne' hp.ne'] + linarith + nlinarith + · simpa using mul_nonneg hp.le hlower + +lemma entropy_tail {p w : I → ℝ} (hp : IsProb p) (hw : ∀ i, 0 < w i) + {x a : ℝ} (hx : 0 < x) (hd : ∀ i, p i ≤ x * w i) : + (a + Real.log x) * (∑ i, if p i < w i * Real.exp (-a) then p i else 0) ≤ + entropy w p + Real.log x := by + have h := sum_le_sum (s := univ) fun i _ ↦ + entropy_tail_term (a := a) (hp.1 i) (hw i) hx (hd i) + simpa only [mul_sum, mul_add, sum_add_distrib, ← sum_mul, hp.2, one_mul, + entropy] using h + +end FiniteEntropy + +end CliqueFreeIndependence + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/FiniteKernel.lean b/lean/OAI/Combinatorics/CliqueFree/FiniteKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..e26acd278f3344650559156f758b4d868656c481 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/FiniteKernel.lean @@ -0,0 +1,419 @@ +import OAI.Combinatorics.CliqueFree.FiniteEntropy + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence + +universe u v + +namespace FiniteKernel + +open FiniteEntropy +variable {I : Type u} [Fintype I] + +abbrev Kernel (I : Type u) := Matrix I I ℝ + +local instance : DecidableEq I := Classical.decEq I + +def Stochastic (P : Kernel I) : Prop := ∀ i, IsProb (P i) +def Stationary (π : I → ℝ) (P : Kernel I) : Prop := ∀ j, ∑ i, π i * P i j = π j +def Reversible (π : I → ℝ) (P : Kernel I) : Prop := ∀ i j, π i * P i j = π j * P j i + +noncomputable def lazy (P : Kernel I) : Kernel I := fun i j ↦ + ((if i = j then 1 else 0) + P i j) / 2 + +noncomputable def smoothed (P : Kernel I) (j : ℕ) : Kernel I := by + classical + exact P * lazy P ^ j + +def avgEntropy (π w : I → ℝ) (K : Kernel I) : ℝ := ∑ i, π i * entropy w (K i) + +lemma stochastic_one : Stochastic (1 : Kernel I) := by + classical + intro i + constructor + · intro j + simp only [Matrix.one_apply] + split_ifs <;> norm_num + · simp [Matrix.one_apply] + +lemma stochastic_mul {P Q : Kernel I} (hP : Stochastic P) (hQ : Stochastic Q) : + Stochastic (P * Q) := by + intro i + exact mix_isProb (hP i) hQ + +lemma stochastic_pow {P : Kernel I} (hP : Stochastic P) (n : ℕ) : Stochastic (P ^ n) := by + classical + induction n with + | zero => simpa using (stochastic_one (I := I)) + | succ n ih => simpa only [pow_succ] using stochastic_mul ih hP + +lemma stochastic_lazy {P : Kernel I} (hP : Stochastic P) : Stochastic (lazy P) := by + classical + intro i + constructor + · intro j + dsimp [lazy] + have := (hP i).1 j + split_ifs <;> positivity + · change (∑ j, ((if i = j then (1 : ℝ) else 0) + P i j) / 2) = 1 + rw [← sum_div, sum_add_distrib] + simp [(hP i).2] + +lemma stochastic_smoothed {P : Kernel I} (hP : Stochastic P) (j : ℕ) : + Stochastic (smoothed P j) := stochastic_mul hP (stochastic_pow (stochastic_lazy hP) j) + +lemma stationary_of_reversible {π : I → ℝ} {P : Kernel I} + (hP : Stochastic P) (hr : Reversible π P) : Stationary π P := by + intro j + calc + _ = ∑ i, π j * P j i := sum_congr rfl fun i _ ↦ hr i j + _ = π j := by rw [← mul_sum, (hP j).2, mul_one] + +lemma stationary_lazy {π : I → ℝ} {P : Kernel I} (hP : Stationary π P) : + Stationary π (lazy P) := by + classical + intro j + change (∑ i, π i * (((if i = j then 1 else 0) + P i j) / 2)) = π j + simp only [← mul_div_assoc, mul_add, ← sum_div, sum_add_distrib, + mul_ite, mul_one, mul_zero] + simp only [sum_ite_eq', mem_univ, ite_true] + rw [hP j] + ring + +omit [Fintype I] in +lemma reversible_one (π : I → ℝ) : Reversible π (1 : Kernel I) := by + classical + intro i j + by_cases h : i = j + · subst j; rfl + · simp [h, Ne.symm h] + +lemma reversible_mul {π : I → ℝ} {P Q : Kernel I} + (hP : Reversible π P) (hQ : Reversible π Q) (hc : Commute P Q) : + Reversible π (P * Q) := by + intro i j + rw [Matrix.mul_apply, mul_sum] + calc + _ = ∑ k, π j * (Q j k * P k i) := by + apply sum_congr rfl + intro k _ + calc + _ = (π i * P i k) * Q k j := by ring + _ = (π k * P k i) * Q k j := by rw [hP] + _ = (π k * Q k j) * P k i := by ring + _ = (π j * Q j k) * P k i := by rw [hQ] + _ = _ := by ring + _ = π j * (Q * P) j i := by rw [Matrix.mul_apply, mul_sum] + _ = _ := by rw [hc.eq] + +lemma reversible_pow {π : I → ℝ} {P : Kernel I} (hP : Reversible π P) (n : ℕ) : + Reversible π (P ^ n) := by + classical + induction n with + | zero => simpa using reversible_one π + | succ n ih => + rw [pow_succ] + exact reversible_mul ih hP ((Commute.refl P).pow_left n) + +omit [Fintype I] in +lemma reversible_lazy {π : I → ℝ} {P : Kernel I} (hP : Reversible π P) : + Reversible π (lazy P) := by + classical + intro i j + by_cases h : i = j + · subst j; rfl + · simp only [lazy, h, Ne.symm h, ite_false, zero_add] + rw [← mul_div_assoc, ← mul_div_assoc, hP i j] + +omit [Fintype I] in +lemma lazy_eq (P : Kernel I) : lazy P = (1 / 2 : ℝ) • (1 + P) := by + classical + ext i j + simp [lazy, Matrix.one_apply, div_eq_mul_inv, mul_comm] + +lemma commute_lazy (P : Kernel I) : Commute P (lazy P) := by + classical + rw [lazy_eq] + show P * ((1 / 2 : ℝ) • (1 + P)) = ((1 / 2 : ℝ) • (1 + P)) * P + simp [mul_add, add_mul] + +lemma reversible_smoothed {π : I → ℝ} {P : Kernel I} (hP : Reversible π P) (j : ℕ) : + Reversible π (smoothed P j) := by + classical + exact reversible_mul hP (reversible_pow (reversible_lazy hP) j) + ((commute_lazy P).pow_right j) + +lemma smoothed_zero (P : Kernel I) : smoothed P 0 = P := by + classical + simp [smoothed] + +lemma smoothed_succ (P : Kernel I) (j : ℕ) : + smoothed P (j + 1) = lazy P * smoothed P j := by + classical + unfold smoothed + rw [pow_succ', ← mul_assoc, (commute_lazy P).eq, mul_assoc] + +lemma smoothed_succ_right (P : Kernel I) (j : ℕ) : + smoothed P (j + 1) = smoothed P j * lazy P := by + classical + simp [smoothed, pow_succ, mul_assoc] + +lemma smoothed_density {P : Kernel I} (hP : Stochastic P) {b : I → ℝ} + (hb : ∀ i j, P i j ≤ b j) (n : ℕ) : ∀ i j, smoothed P n i j ≤ b j := by + classical + intro i j + unfold smoothed + rw [((commute_lazy P).pow_right n).eq, Matrix.mul_apply] + have hQ := stochastic_pow (stochastic_lazy hP) n + calc + _ ≤ ∑ k, (lazy P ^ n) i k * b j := + sum_le_sum fun k _ ↦ mul_le_mul_of_nonneg_left (hb k j) ((hQ i).1 k) + _ = b j := by rw [← sum_mul, (hQ i).2, one_mul] + +lemma pair_isProb {π : I → ℝ} (hπ : IsProb π) {Q : Kernel I} (hQ : Stochastic Q) : + IsProb (fun a : I × I ↦ π a.1 * Q a.1 a.2) := by + constructor + · intro a + exact mul_nonneg (hπ.1 a.1) ((hQ a.1).1 a.2) + · rw [Fintype.sum_prod_type] + simp_rw [← mul_sum, fun i ↦ (hQ i).2, mul_one] + exact hπ.2 + +lemma stationary_average {π : I → ℝ} {Q : Kernel I} (hQ : Stationary π Q) (f : I → ℝ) : + (∑ i, π i * ∑ j, Q i j * f j) = ∑ j, π j * f j := by + simp_rw [mul_sum, ← mul_assoc] + rw [sum_comm] + simp_rw [← sum_mul] + exact sum_congr rfl fun j _ ↦ by rw [hQ j] + +lemma entropy_increment {π w : I → ℝ} (hw : ∀ i, 0 < w i) + {Q K : Kernel I} (hQ : Stochastic Q) (hK : Stochastic K) (hs : Stationary π Q) : + avgEntropy π w (Q * K) - avgEntropy π w K = + ∑ i, π i * ∑ j, Q i j * divergence (K j) ((Q * K) i) := by + have he (i : I) := entropy_mix_gap hw (hQ i) hK + have he' : ∀ i, entropy w ((Q * K) i) - ∑ j, Q i j * entropy w (K j) = + ∑ j, Q i j * divergence (K j) ((Q * K) i) := he + simp_rw [← he', mul_sub, sum_sub_distrib] + rw [stationary_average hs] + rfl + +lemma entropy_increment_nonneg {π w : I → ℝ} (hπ : IsProb π) (hw : ∀ i, 0 < w i) + {Q K : Kernel I} (hQ : Stochastic Q) (hK : Stochastic K) (hs : Stationary π Q) : + 0 ≤ avgEntropy π w (Q * K) - avgEntropy π w K := by + rw [entropy_increment hw hQ hK hs] + apply sum_nonneg + intro i _ + apply mul_nonneg (hπ.1 i) + apply sum_nonneg + intro j _ + rcases ((hQ i).1 j).eq_or_lt with hj | hj + · simp [← hj] + exact mul_nonneg hj.le (divergence_nonneg (hK j) (stochastic_mul hQ hK i) + (fun k hk ↦ mix_support (hQ i).1 (fun z ↦ (hK z).1) hj hk)) + +lemma entropy_increment_tv {π w : I → ℝ} (hπ : IsProb π) (hw : ∀ i, 0 < w i) + {Q K : Kernel I} (hQ : Stochastic Q) (hK : Stochastic K) (hs : Stationary π Q) : + (∑ i, π i * ∑ j, Q i j * tv (K j) ((Q * K) i)) ^ 2 ≤ + avgEntropy π w (Q * K) - avgEntropy π w K := by + rw [entropy_increment hw hQ hK hs] + have h := average_tv_sq_le_average_divergence (pair_isProb hπ hQ) + (fun a : I × I ↦ hK a.2) (fun a : I × I ↦ stochastic_mul hQ hK a.1) + (fun a ha i hi ↦ mix_support (hQ a.1).1 (fun j ↦ (hK j).1) + (pos_of_mul_pos_right ha (hπ.1 a.1)) hi) + simpa only [Fintype.sum_prod_type, mul_assoc, ← mul_sum] using h + +lemma lazy_triangle_tv {π : I → ℝ} (hπ : IsProb π) {P K : Kernel I} + (hP : Stochastic P) : + (∑ i, π i * ∑ j, P i j * tv (K i) (K j)) ≤ + 2 * (∑ i, π i * ∑ j, lazy P i j * tv (K j) ((lazy P * K) i)) := by + classical + have hi (i : I) : (∑ j, P i j * tv (K i) (K j)) ≤ + 2 * ∑ j, lazy P i j * tv (K j) ((lazy P * K) i) := by + calc + _ ≤ ∑ j, P i j * (tv (K i) ((lazy P * K) i) + tv (K j) ((lazy P * K) i)) := by + apply sum_le_sum + intro j _ + apply mul_le_mul_of_nonneg_left _ ((hP i).1 j) + have := tv_triangle (K i) ((lazy P * K) i) (K j) + simpa only [tv_comm ((lazy P * K) i)] using this + _ = _ := by + have he (f : I → ℝ) : (∑ j, lazy P i j * f j) = + (f i + ∑ j, P i j * f j) / 2 := by + simp only [lazy, div_mul_eq_mul_div, add_mul, ← sum_div, sum_add_distrib, + ite_mul, one_mul, zero_mul] + simp + rw [he] + simp only [mul_add, sum_add_distrib, ← sum_mul, (hP i).2, one_mul] + ring + calc + _ ≤ ∑ i, π i * (2 * ∑ j, lazy P i j * tv (K j) ((lazy P * K) i)) := + sum_le_sum fun i _ ↦ mul_le_mul_of_nonneg_left (hi i) (hπ.1 i) + _ = _ := by simp_rw [← mul_assoc, mul_comm (π _ ) 2, mul_assoc, ← mul_sum] + +lemma smoothed_entropy_mono {π w : I → ℝ} (hπ : IsProb π) (hw : ∀ i, 0 < w i) + {P : Kernel I} (hP : Stochastic P) (hs : Stationary π P) : + Monotone (fun j ↦ avgEntropy π w (smoothed P j)) := by + apply monotone_nat_of_le_succ + intro j + rw [smoothed_succ] + exact sub_nonneg.1 (entropy_increment_nonneg hπ hw (stochastic_lazy hP) + (stochastic_smoothed hP j) (stationary_lazy hs)) + +lemma smoothed_row_distance_sq {π w : I → ℝ} (hπ : IsProb π) (hw : ∀ i, 0 < w i) + {P : Kernel I} (hP : Stochastic P) (hs : Stationary π P) (j : ℕ) : + (∑ i, π i * ∑ z, P i z * tv (smoothed P j i) (smoothed P j z)) ^ 2 ≤ + 4 * (avgEntropy π w (smoothed P (j + 1)) - avgEntropy π w (smoothed P j)) := by + have h := entropy_increment_tv hπ hw (stochastic_lazy hP) + (stochastic_smoothed hP j) (stationary_lazy hs) + have hc := lazy_triangle_tv (K := smoothed P j) hπ hP + have ha : 0 ≤ ∑ i, π i * ∑ z, P i z * tv (smoothed P j i) (smoothed P j z) := + sum_nonneg fun i _ ↦ mul_nonneg (hπ.1 i) + (sum_nonneg fun z _ ↦ mul_nonneg ((hP i).1 z) (tv_nonneg _ _)) + have hb : 0 ≤ ∑ i, π i * ∑ z, lazy P i z * tv (smoothed P j z) + ((lazy P * smoothed P j) i) := + sum_nonneg fun i _ ↦ mul_nonneg (hπ.1 i) + (sum_nonneg fun z _ ↦ mul_nonneg ((stochastic_lazy hP i).1 z) (tv_nonneg _ _)) + rw [smoothed_succ] + have hp := mul_nonneg (sub_nonneg.2 hc) (add_nonneg (mul_nonneg (show (0 : ℝ) ≤ 2 by norm_num) hb) ha) + nlinarith + +/-- Entropy telescoping gives the averaged triangle-row estimate. -/ +lemma exists_smoothed_row_distance {π w : I → ℝ} (hπ : IsProb π) (hw : ∀ i, 0 < w i) + {P : Kernel I} (hP : Stochastic P) (hs : Stationary π P) + {R : ℕ} (hR : 0 < R) {D : ℝ} + (hD : avgEntropy π w (smoothed P R) - avgEntropy π w (smoothed P 0) ≤ D) : + ∃ j < R, (∑ i, π i * ∑ z, P i z * tv (smoothed P j i) (smoothed P j z)) ^ 2 ≤ + 4 * D / R := by + have hR0 : (R : ℝ) ≠ 0 := by exact_mod_cast Nat.ne_of_gt hR + have hsum : (∑ j ∈ range R, (avgEntropy π w (smoothed P (j + 1)) - + avgEntropy π w (smoothed P j))) ≤ ∑ _j ∈ range R, D / (R : ℝ) := by + rw [sum_range_sub (fun j ↦ avgEntropy π w (smoothed P j)) R] + have he : (∑ _j ∈ range R, D / (R : ℝ)) = D := by + rw [sum_const, card_range, nsmul_eq_mul] + field_simp + rw [he] + exact hD + obtain ⟨j, hj, hle⟩ := exists_le_of_sum_le (nonempty_range_iff.2 (Nat.ne_of_gt hR)) hsum + refine ⟨j, mem_range.1 hj, ?_⟩ + calc + _ ≤ 4 * (avgEntropy π w (smoothed P (j + 1)) - avgEntropy π w (smoothed P j)) := + smoothed_row_distance_sq hπ hw hP hs j + _ ≤ 4 * (D / (R : ℝ)) := mul_le_mul_of_nonneg_left hle (by norm_num) + _ = _ := by ring + +variable {J : Type v} + +def Preserves (label : I → J) (P : Kernel I) : Prop := + ∀ i j, label i ≠ label j → P i j = 0 + +omit [Fintype I] in +lemma preserves_one (label : I → J) : Preserves label (1 : Kernel I) := by + intro i j hij + have h : i ≠ j := fun h ↦ hij (congrArg label h) + simp [h] + +lemma preserves_mul {label : I → J} {P Q : Kernel I} + (hP : Preserves label P) (hQ : Preserves label Q) : Preserves label (P * Q) := by + intro i j hij + rw [Matrix.mul_apply] + apply sum_eq_zero + intro k _ + by_cases hik : label i = label k + · have hkj : label k ≠ label j := fun h ↦ hij (hik.trans h) + rw [hQ k j hkj, mul_zero] + · rw [hP i k hik, zero_mul] + +lemma preserves_pow {label : I → J} {P : Kernel I} (hP : Preserves label P) (n : ℕ) : + Preserves label (P ^ n) := by + induction n with + | zero => simpa using preserves_one label + | succ n ih => simpa only [pow_succ] using preserves_mul ih hP + +omit [Fintype I] in +lemma preserves_lazy {label : I → J} {P : Kernel I} (hP : Preserves label P) : + Preserves label (lazy P) := by + intro i j hij + have h : i ≠ j := fun h ↦ hij (congrArg label h) + simp [lazy, h, hP i j hij] + +lemma preserves_smoothed {label : I → J} {P : Kernel I} (hP : Preserves label P) (n : ℕ) : + Preserves label (smoothed P n) := + preserves_mul hP (preserves_pow (preserves_lazy hP) n) + +def rowMass (K : Kernel I) (i : I) (A : Finset I) : ℝ := ∑ j ∈ A, K i j + +lemma rowMass_le_one {K : Kernel I} (hK : Stochastic K) (i : I) (A : Finset I) : + rowMass K i A ≤ 1 := by + rw [← (hK i).2] + exact sum_le_univ_sum_of_nonneg (hK i).1 + +lemma rowMass_mul (P Q : Kernel I) (i : I) (A : Finset I) : + rowMass (P * Q) i A = ∑ j, P i j * rowMass Q j A := by + unfold rowMass + simp only [Matrix.mul_apply, mul_sum] + rw [sum_comm] + +lemma rowMass_compl {K : Kernel I} (hK : Stochastic K) (i : I) (A : Finset I) : + rowMass K i Aᶜ = 1 - rowMass K i A := by + have h : rowMass K i A + rowMass K i Aᶜ = 1 := by + rw [rowMass, rowMass, sum_add_sum_compl, (hK i).2] + linarith + +lemma leakage_mul_le {P Q : Kernel I} (hP : Stochastic P) (hQ : Stochastic Q) + (i : I) (A B : Finset I) : + rowMass (P * Q) i Bᶜ ≤ rowMass P i Aᶜ + ∑ y ∈ Bᶜ, ∑ z ∈ A, P i z * Q z y := by + rw [rowMass_mul] + have hsplit : (∑ j, P i j * rowMass Q j Bᶜ) = + (∑ j ∈ A, P i j * rowMass Q j Bᶜ) + ∑ j ∈ Aᶜ, P i j * rowMass Q j Bᶜ := + (sum_add_sum_compl A _).symm + rw [hsplit] + have hle : (∑ j ∈ Aᶜ, P i j * rowMass Q j Bᶜ) ≤ rowMass P i Aᶜ := by + exact sum_le_sum fun j _ ↦ by + simpa only [mul_one] using + mul_le_mul_of_nonneg_left (rowMass_le_one hQ j Bᶜ) ((hP i).1 j) + have he : (∑ j ∈ A, P i j * rowMass Q j Bᶜ) = ∑ y ∈ Bᶜ, ∑ z ∈ A, P i z * Q z y := by + simp only [rowMass, mul_sum] + rw [sum_comm] + rw [he] + linarith + +lemma reversed_entropy_tail {μ w : I → ℝ} {K : Matrix I I ℝ} + (hμ : IsProb μ) (hw : ∀ i, 0 < w i) (hK : Stochastic K) + (hr : Reversible μ K) {x a : ℝ} (hx : 0 < x) + (hd : ∀ i j, K i j ≤ x * w j) : + (a + Real.log x) * + (∑ i, μ i * ∑ j, if K j i < w i * Real.exp (-a) then K i j else 0) ≤ + avgEntropy μ w K + Real.log x := by + have h := sum_le_sum (s := univ) fun i _ ↦ + mul_le_mul_of_nonneg_left (entropy_tail (a := a) (hK i) hw hx (hd i)) (hμ.1 i) + have heq : (∑ i, μ i * ∑ j, if K j i < w i * Real.exp (-a) then K i j else 0) = + ∑ i, μ i * ∑ j, if K i j < w j * Real.exp (-a) then K i j else 0 := by + simp only [mul_sum] + rw [sum_comm] + apply sum_congr rfl + intro i _ + apply sum_congr rfl + intro j _ + by_cases hb : K i j < w j * Real.exp (-a) + · simp only [hb, ↓reduceIte] + exact hr j i + · simp only [hb, ↓reduceIte, mul_zero] + rw [heq] + simpa only [mul_sum, mul_add, sum_add_distrib, ← sum_mul, hμ.2, one_mul, + avgEntropy, mul_left_comm] using h + +end FiniteKernel + +end CliqueFreeIndependence + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/IndependentSet.lean b/lean/OAI/Combinatorics/CliqueFree/IndependentSet.lean new file mode 100644 index 0000000000000000000000000000000000000000..4d6cb5dc1778201978cb49234b591a6c419e4a51 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/IndependentSet.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.CliqueFree.Deletion +import OAI.Combinatorics.CliqueFree.CrossBound +import OAI.Combinatorics.CliqueFree.TriangleBound + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +lemma exists_optimizer_triangle_bound (k : ℕ) : + ∃ B : ℝ, 0 < B ∧ ∀ {V : Type u} [Fintype V] (G : SimpleGraph V) (w : V → ℝ), + IsOptimizer G w → G.CliqueFree (k+2) → triangleMass G w ≤ B * edgeMass G w := by + have hC : 1 ≤ 16*((k : ℝ)+2)^2 := by nlinarith [Nat.cast_nonneg (α := ℝ) k] + obtain ⟨B,hB,hbound⟩ := weighted_triangles.{u} hC + exact ⟨B,hB,fun G w hw hf ↦ hbound G w (fun v ↦ (optimizer_stationary hw v).1) + (optimizer_cross_bound k G hw hf)⟩ + +lemma exists_cheap_vertex {G : SimpleGraph V} {w : V → ℝ} (hw : IsOptimizer G w) + [Nonempty V] {Δ B : ℝ} (hΔ : 3 ≤ Δ) (hB : 0 ≤ B) + (hdeg : ∀ v, (G.degree v : ℝ) ≤ Δ) (htri : triangleMass G w ≤ B * edgeMass G w) : + ∃ v, mass w (closedNeighbors G v) + edgeMass G (restrict (closedNeighbors G v) w) ≤ + (3+3*B/2) * Real.log Δ := by + have hwpos (v : V) : 0 < w v := (optimizer_stationary hw v).1 + have hp (v : V) : + w v * (mass w (closedNeighbors G v) + edgeMass G (restrict (closedNeighbors G v) w)) ≤ + w v + 2 * (w v * neighborMass G w v) + w v * triangleAt G w v / 2 := by + rw [mass_closedNeighbors,edgeMass_closedNeighbors] + have hv := (optimizer_stationary hw v).2.2 + have hN := neighborMass_nonneg G hw.1 v + have hsq : w v * w v ≤ w v := by nlinarith [hw.1 v] + have hmul := mul_le_mul_of_nonneg_right hsq hN + nlinarith + have hsum := sum_le_sum (s := univ) fun v _ ↦ hp v + simp only [sum_add_distrib, ← mul_sum, ← sum_div] at hsum + have he := edgeForm_self G w + rw [edgeForm_neighbor] at he + have ht : (∑ v, w v * triangleAt G w v) / 2 = 3*triangleMass G w := by + unfold triangleMass + ring + rw [he,ht] at hsum + have hedge := optimizer_edge_bound hw hΔ hdeg + have hlog : 1 ≤ Real.log Δ := le_of_lt <| (Real.lt_log_iff_exp_lt (by linarith)).2 + (Real.exp_one_lt_three.trans_le hΔ) + have hW : 0 ≤ ∑ v, w v := sum_nonneg (fun v _ ↦ hw.1 v) + have htot : (∑ v, w v * (mass w (closedNeighbors G v) + + edgeMass G (restrict (closedNeighbors G v) w))) ≤ + ((3+3*B/2)*Real.log Δ) * (∑ v, w v) := by + have h1 := mul_le_mul_of_nonneg_right hlog hW + have h2 := mul_le_mul_of_nonneg_left hedge (show 0 ≤ 2+3*B/2 by positivity) + nlinarith + by_contra h + push Not at h + have hlt (v : V) := mul_lt_mul_of_pos_left (h v) (hwpos v) + have hh := sum_lt_sum (s := univ) (fun v _ ↦ (hlt v).le) + ⟨Classical.arbitrary V, mem_univ _, hlt _⟩ + rw [← sum_mul] at hh + linarith + +lemma degree_induce_le (G : SimpleGraph V) (A : Finset V) (v : (A : Set V)) : + (G.induce (A : Set V)).degree v ≤ G.degree v := by + classical + rw [← SimpleGraph.card_neighborSet_eq_degree, ← SimpleGraph.card_neighborSet_eq_degree] + exact Fintype.card_le_of_injective + (fun u : (G.induce (A : Set V)).neighborSet v ↦ + (⟨u.val.val, u.property⟩ : G.neighborSet v)) + (fun u z h ↦ by + apply Subtype.ext + apply Subtype.ext + exact congrArg (fun x : G.neighborSet v ↦ (x : V)) h) + +omit [Fintype V] in +lemma indepSet_image_induce (G : SimpleGraph V) (A : Finset V) (I : Finset (A : Set V)) + (hI : (G.induce (A : Set V)).IsIndepSet (I : Set (A : Set V))) : + G.IsIndepSet (I.map ⟨Subtype.val, Subtype.val_injective⟩ : Set V) := by + classical + intro a ha b hb hab + obtain ⟨a',ha',rfl⟩ := mem_map.1 ha + obtain ⟨b',hb',rfl⟩ := mem_map.1 hb + exact hI ha' hb' (fun h ↦ hab (congrArg Subtype.val h)) + +omit [Fintype V] in +lemma indepSet_insert_induce (G : SimpleGraph V) (A : Finset V) (v : V) + (hA : ∀ b ∈ A, b ≠ v ∧ ¬G.Adj v b) + (I : Finset (A : Set V)) + (hI : (G.induce (A : Set V)).IsIndepSet (I : Set _)) : + G.IsIndepSet (↑(insert v (I.map ⟨Subtype.val, Subtype.val_injective⟩) : Finset V) : Set V) ∧ + (insert v (I.map ⟨Subtype.val, Subtype.val_injective⟩)).card = I.card + 1 := by + classical + have hnot (b : V) (hb : b ∈ I.map ⟨Subtype.val, Subtype.val_injective⟩) : + b ≠ v ∧ ¬G.Adj v b := by + obtain ⟨b',_,rfl⟩ := mem_map.1 hb + exact hA b' b'.property + have hi := indepSet_image_induce G A I hI + constructor + · intro a ha b hb hab + change a ∈ insert v (I.map _) at ha + change b ∈ insert v (I.map _) at hb + rw [mem_insert] at ha hb + rcases ha with rfl | ha + · rcases hb with rfl | hb + · exact fun _ ↦ hab rfl + · exact (hnot b hb).2 + · rcases hb with rfl | hb + · exact fun h ↦ (hnot a ha).2 h.symm + · exact hi ha hb hab + · rw [card_insert_of_notMem (fun h ↦ (hnot v h).1 rfl), card_map] + +/-- The maximum-degree induction controls the original variational functional, +not a surrogate objective or a conditional independence bound. -/ +lemma maximum_degree_potential_bound (k : ℕ) {B Δ : ℝ} (hB : 0 ≤ B) (hΔ : 3 ≤ Δ) + (htri : ∀ {U : Type u} [Fintype U] (H : SimpleGraph U) (w : U → ℝ), + IsOptimizer H w → H.CliqueFree (k+2) → triangleMass H w ≤ B * edgeMass H w) + (G : SimpleGraph V) (hf : G.CliqueFree (k+2)) (hdeg : ∀ v, (G.degree v : ℝ) ≤ Δ) : + ∃ I : Finset V, G.IsIndepSet (I : Set V) ∧ + ∀ q : V → ℝ, (∀ v, 0 ≤ q v) → + potential G q ≤ ((3+3*B/2)*Real.log Δ) * (I.card : ℝ) := by + classical + have aux : ∀ n : ℕ, ∀ (U : Type u) [Fintype U], Fintype.card U = n → + ∀ H : SimpleGraph U, H.CliqueFree (k+2) → (∀ v, (H.degree v : ℝ) ≤ Δ) → + ∃ I : Finset U, H.IsIndepSet (I : Set U) ∧ + ∀ q : U → ℝ, (∀ v, 0 ≤ q v) → + potential H q ≤ ((3+3*B/2)*Real.log Δ) * (I.card : ℝ) := by + intro n + induction n using Nat.strong_induction_on with + | h n ih => + intro U _ hn H hfree hdegree + rcases isEmpty_or_nonempty U with hU | hU + · let _ := hU + refine ⟨∅,by simp,?_⟩ + intro q _ + simp [potential,edgeMass,crossMass] + · let _ := hU + obtain ⟨w,hw⟩ := exists_optimizer H + obtain ⟨v,hv⟩ := exists_cheap_vertex hw hΔ hB hdegree (htri H w hw hfree) + let A : Finset U := (closedNeighbors H v)ᶜ + have hA : ∀ b ∈ A, b ≠ v ∧ ¬H.Adj v b := by + intro b hb + simpa [A] using hb + have hcard : Fintype.card (A : Set U) < n := by + rw [← hn] + exact Fintype.card_subtype_lt (x := v) (by simp [A]) + have hfreeA : (H.induce (A : Set U)).CliqueFree (k+2) := + (H.cliqueFree_induce_iff _ _).2 hfree.cliqueFreeOn + have hdegA (a : (A : Set U)) : ((H.induce (A : Set U)).degree a : ℝ) ≤ Δ := + (Nat.cast_le.2 (degree_induce_le H A a)).trans (hdegree a) + obtain ⟨I,hI,hIp⟩ := ih _ hcard (A : Set U) rfl (H.induce (A : Set U)) hfreeA hdegA + obtain ⟨hJ,hJcard⟩ := indepSet_insert_induce H A v hA I hI + refine ⟨insert v (I.map ⟨Subtype.val,Subtype.val_injective⟩),hJ,?_⟩ + intro q hq + have hres := hIp (fun a ↦ w a) (fun a ↦ hw.1 a) + rw [potential_induce] at hres + have hcost := optimizer_deletion_cost hw (closedNeighbors H v) + change potential H w - potential H (restrict A w) = _ at hcost + rw [hJcard,Nat.cast_add,Nat.cast_one] + have hmax := hw.2 q hq + nlinarith + exact aux _ V rfl G hf hdeg + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/LocalWalk.lean b/lean/OAI/Combinatorics/CliqueFree/LocalWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..83918f6fb0a013c736c68633c8936b826dd88e76 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/LocalWalk.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.CliqueFree.Reach +import OAI.Combinatorics.CliqueFree.FiniteKernel + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +namespace LocalWalk +open FiniteEntropy FiniteKernel +variable (G : SimpleGraph V) (w : V → ℝ) + +/-- The disjoint union of the neighborhood transition kernels. -/ +noncomputable def transition : Kernel (EdgeState G) := fun e f ↦ + if e.src = f.src then + if G.Adj e.dst f.dst then w f.dst / commonMass G w e.src e.dst else 0 + else 0 + +noncomputable def normalizer : ℝ := + ∑ e : EdgeState G, w e.src * w e.dst * commonMass G w e.src e.dst + +noncomputable def law : EdgeState G → ℝ := fun e ↦ + (w e.src * w e.dst * commonMass G w e.src e.dst) / normalizer G w + +noncomputable def vertexWeight : EdgeState G → ℝ := fun e ↦ w e.dst + +noncomputable def fiber (u : V) : Finset (EdgeState G) := by + classical + exact univ.filter (fun e ↦ e.src = u) + +@[simp] lemma mem_fiber (e : EdgeState G) (u : V) : e ∈ fiber G u ↔ e.src = u := by + classical + simp [fiber] + +lemma fiber_mass (u : V) : (∑ e ∈ fiber G u, vertexWeight G w e) = neighborMass G w u := by + classical + simp only [fiber, sum_filter, vertexWeight, EdgeState.sum_fiber, neighborMass, mass] + +lemma normalizer_eq : normalizer G w = 6 * triangleMass G w := by + rw [normalizer, EdgeState.sum_eq (fun u v ↦ w u * w v * commonMass G w u v), + triangleMass_eq_sum] + simp only [triangleAt, mul_sum, mul_assoc] + +variable {G w} +lemma transition_stochastic (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) : Stochastic (transition G w) := by + classical + intro e + constructor + · intro f + dsimp [transition] + split_ifs + · exact (div_pos (hw _) (hc _ _ e.adj)).le + all_goals exact le_rfl + · change (∑ f : EdgeState G, if e.src = f.src then + (if G.Adj e.dst f.dst then w f.dst / commonMass G w e.src e.dst else 0) else 0) = 1 + rw [EdgeState.sum_fiber' e.src (fun z ↦ + if G.Adj e.dst z then w z / commonMass G w e.src e.dst else 0)] + have hid (z : V) : (if G.Adj e.dst z then w z / commonMass G w e.src e.dst else 0) = + (if G.Adj e.dst z then w z else 0) / commonMass G w e.src e.dst := by + split_ifs <;> simp + simp_rw [hid] + rw [← sum_div, ← commonMass_eq_sum, div_self (hc _ _ e.adj).ne'] + +lemma normalizer_pos [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) : 0 < normalizer G w := by + exact sum_pos (fun e _ ↦ mul_pos (mul_pos (hw _) (hw _)) (hc _ _ e.adj)) univ_nonempty + +lemma law_isProb [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) : IsProb (law G w) := by + have hZ := normalizer_pos hw hc + constructor + · intro e + exact (div_pos (mul_pos (mul_pos (hw _) (hw _)) (hc _ _ e.adj)) hZ).le + · unfold law + rw [← sum_div] + exact div_self hZ.ne' + +lemma transition_reversible [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) : + Reversible (law G w) (transition G w) := by + classical + intro e f + by_cases hsrc : e.src = f.src + · by_cases hadj : G.Adj e.dst f.dst + · simp only [transition, hsrc, ite_true, hadj, hadj.symm, law] + have he := (hc _ _ e.adj).ne' + have hf := (hc _ _ f.adj).ne' + rw [hsrc] at he + field_simp [he, hf, (normalizer_pos hw hc).ne'] + · simp [transition, hsrc, hadj, G.adj_comm f.dst] + · simp [transition, hsrc, Ne.symm hsrc] + +lemma transition_fixed_src (e f : EdgeState G) (h : e.src ≠ f.src) : + transition G w e f = 0 := by simp [transition, h] + +lemma transition_density (hw : ∀ u, 0 < w u) {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) : + ∀ e f, transition G w e f ≤ x * vertexWeight G w f := by + classical + intro e f + have hc0 : 0 < commonMass G w e.src e.dst := (one_div_pos.2 hx).trans_le (hc _ _ e.adj) + dsimp [transition, vertexWeight] + split_ifs + · apply (div_le_iff₀ hc0).2 + have h := (div_le_iff₀ hx).1 (hc _ _ e.adj) + nlinarith [mul_le_mul_of_nonneg_left h (hw f.dst).le] + all_goals exact (mul_pos hx (hw _)).le + +lemma smoothed_fixed_src (n : ℕ) (e f : EdgeState G) (h : e.src ≠ f.src) : + smoothed (transition G w) n e f = 0 := + preserves_smoothed (label := EdgeState.src) transition_fixed_src n e f h + +lemma smoothed_supported (n : ℕ) (e f : EdgeState G) (h : f ∉ fiber G e.src) : + smoothed (transition G w) n e f = 0 := by + apply smoothed_fixed_src + intro he + apply h + exact (mem_fiber G f e.src).2 he.symm + +lemma smoothed_density (hw : ∀ u, 0 < w u) {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) (n : ℕ) : + ∀ e f, smoothed (transition G w) n e f ≤ x * vertexWeight G w f := by + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx).trans_le (hc u v huv) + exact FiniteKernel.smoothed_density (transition_stochastic hw hc0) (transition_density hw hx hc) n + +lemma entropy_bounds [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) (n : ℕ) (e : EdgeState G) : + -Real.log x ≤ entropy (vertexWeight G w) (smoothed (transition G w) n e) ∧ + entropy (vertexWeight G w) (smoothed (transition G w) n e) ≤ x := by + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx).trans_le (hc u v huv) + have hp := stochastic_smoothed (transition_stochastic hw hc0) n e + constructor + · exact entropy_ge_neg_log_of_density (w := vertexWeight G w) (fun f ↦ hw f.dst) hp hx + (smoothed_density hw hx hc n e) + · have h := entropy_supported_le_log (w := vertexWeight G w) (fiber G e.src) (fun f _ ↦ hw f.dst) hp + (smoothed_supported n e) (Real.exp_pos x) (by rw [fiber_mass]; exact hL e.src) + simpa only [Real.log_exp] using h + +end LocalWalk + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Lottery.lean b/lean/OAI/Combinatorics/CliqueFree/Lottery.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e620a051899635854f9b6a5ec0358b5d33cb208 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Lottery.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.CliqueFree.Model + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence +universe u +namespace Lottery +variable {α β : Type u} + +/-- A finite real lottery; list entries need not have distinct outcomes. -/ +abbrev Law (α : Type u) := List (ℝ × α) + +def expect (L : Law α) (f : α → ℝ) : ℝ := (L.map fun z ↦ z.1 * f z.2).sum + +def Positive (L : Law α) : Prop := ∀ z ∈ L, 0 ≤ z.1 + +def total (L : Law α) : ℝ := expect L (fun _ ↦ 1) + +def IsProb (L : Law α) : Prop := Positive L ∧ total L = 1 + +@[simp] lemma expect_nil (f : α → ℝ) : expect [] f = 0 := rfl +@[simp] lemma expect_cons (p : ℝ) (a : α) (L : Law α) (f : α → ℝ) : + expect ((p,a)::L) f = p*f a + expect L f := rfl +@[simp] lemma expect_singleton (p : ℝ) (a : α) (f : α → ℝ) : expect [(p,a)] f = p*f a := by + simp [expect] + +lemma expect_append (L K : Law α) (f : α → ℝ) : expect (L++K) f = expect L f + expect K f := by + simp [expect] + +lemma expect_add (L : Law α) (f g : α → ℝ) : + expect L (fun a ↦ f a + g a) = expect L f + expect L g := by + induction L with + | nil => simp + | cons z L ih => + rcases z with ⟨p,a⟩ + simp only [expect_cons,ih] + ring + +lemma expect_mul (L : Law α) (a : ℝ) (f : α → ℝ) : + expect L (fun z ↦ a*f z) = a * expect L f := by + induction L with + | nil => simp + | cons z L ih => + rcases z with ⟨p,a⟩ + simp only [expect_cons,ih] + ring + +lemma expect_const (L : Law α) (a : ℝ) : expect L (fun _ ↦ a) = a * total L := by + simpa only [mul_one,total] using expect_mul L a (fun _ ↦ 1) + +lemma expect_mono {L : Law α} (hL : Positive L) {f g : α → ℝ} + (h : ∀ z ∈ L, f z.2 ≤ g z.2) : expect L f ≤ expect L g := by + induction L with + | nil => rfl + | cons z L ih => + exact add_le_add (mul_le_mul_of_nonneg_left (h z (by simp)) (hL z (by simp))) + (ih (fun t ht ↦ hL t (by simp [ht])) (fun t ht ↦ h t (by simp [ht]))) + +lemma expect_sum {I : Type*} (L : Law α) (s : Finset I) (f : I → α → ℝ) : + expect L (fun a ↦ ∑ i ∈ s, f i a) = ∑ i ∈ s, expect L (f i) := by + classical + induction s using Finset.induction_on with + | empty => simp [expect_const] + | @insert i s hi ih => simp only [sum_insert hi,expect_add,ih] + +def transform (p : ℝ) (f : α → β) (L : Law α) : Law β := L.map (fun z ↦ (p*z.1,f z.2)) + +lemma expect_transform (p : ℝ) (f : α → β) (L : Law α) (g : β → ℝ) : + expect (transform p f L) g = p * expect L (g ∘ f) := by + induction L with + | nil => simp [transform] + | cons z L ih => + rcases z with ⟨q,a⟩ + simp only [transform,List.map_cons,expect_cons,Function.comp_apply] at * + rw [ih] + ring + +lemma total_transform (p : ℝ) (f : α → β) (L : Law α) : + total (transform p f L) = p * total L := expect_transform _ _ _ _ + +lemma positive_transform {p : ℝ} (hp : 0 ≤ p) (f : α → β) {L : Law α} (hL : Positive L) : + Positive (transform p f L) := by + intro z hz + obtain ⟨y,hy,rfl⟩ := List.mem_map.1 hz + exact mul_nonneg hp (hL y hy) + +lemma positive_append {L K : Law α} (hL : Positive L) (hK : Positive K) : Positive (L++K) := by + intro z hz + rcases List.mem_append.1 hz with hz | hz + · exact hL z hz + · exact hK z hz + +end Lottery + +end CliqueFreeIndependence + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Main.lean b/lean/OAI/Combinatorics/CliqueFree/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f1a47dcf0c0ca1f0087f813640ab3b47f3f2848 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Main.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.CliqueFree.MaxDegree + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeLog +open CliqueFreeIndependence.WeightedGraph + +lemma sum_degrees_real {V : Type*} [Fintype V] (G : SimpleGraph V) : + (∑ v, (G.degree v : ℝ)) = 2 * (G.edgeFinset.card : ℝ) := by + classical + exact_mod_cast G.sum_degrees_eq_twice_card_edges + +/-- The logarithmic independence bound for ordinary clique exclusion and the graph's own +average degree, with a constant uniform in graph size and average degree. -/ +theorem logarithmic_independence_bound (r : ℕ) (hr : 4 ≤ r) : + ∃ c : ℝ, 0 < c ∧ + ∀ {V : Type} [Fintype V] (G : SimpleGraph V), + G.CliqueFree r → 2 ≤ averageDegree G → + c * (Fintype.card V : ℝ) * Real.log (averageDegree G) / averageDegree G ≤ + (G.indepNum : ℝ) := by + classical + obtain ⟨B,hB,htri⟩ := exists_optimizer_triangle_bound.{0} (r-2) + let D : ℝ := 3+3*B/2 + have hD : 0 < D := by dsimp [D]; positivity + refine ⟨1/(16*D),by positivity,?_⟩ + intro V _ G hf hd + let d : ℝ := averageDegree G + have hd2 : 2 ≤ d := hd + have hdpos : 0 < d := by linarith + have hn : (Fintype.card V : ℝ) ≠ 0 := by + intro hn + have hz : averageDegree G = 0 := by simp [averageDegree,hn] + rw [hz] at hd + norm_num at hd + have hsum : (∑ v, (G.degree v : ℝ)) = (Fintype.card V : ℝ)*d := by + rw [sum_degrees_real] + dsimp [d, averageDegree] + field_simp + let A : Finset V := univ.filter fun v ↦ (G.degree v : ℝ) ≤ 2*d + have hAcard : (Fintype.card V : ℝ)/2 ≤ (Fintype.card (A : Set V) : ℝ) := by + have he : Fintype.card (A : Set V) = A.card := Fintype.card_coe A + rw [he] + exact degree_cutoff_card G hdpos hsum + have hk : r-2+2 = r := Nat.sub_add_cancel (by omega) + have hfree : (G.induce (A : Set V)).CliqueFree (r-2+2) := by + rw [hk] + exact (G.cliqueFree_induce_iff _ _).2 hf.cliqueFreeOn + have hdeg (v : (A : Set V)) : ((G.induce (A : Set V)).degree v : ℝ) ≤ 2*d := by + have hv : (G.degree v : ℝ) ≤ 2*d := (mem_filter.1 v.property).2 + exact (Nat.cast_le.2 (degree_induce_le G A v)).trans hv + have hmax := maximum_degree_independence (r-2) hB.le (by linarith : 3 ≤ 2*d) + htri (G.induce (A : Set V)) hfree hdeg + have hi : ((G.induce (A : Set V)).indepNum : ℝ) ≤ G.indepNum := + Nat.cast_le.2 (indepNum_induce_le G A) + have hlog : Real.log d ≤ Real.log (2*d) := + Real.log_le_log hdpos (by linarith) + have hlog0 : 0 ≤ Real.log d := Real.log_nonneg (by linarith) + have hnum : (Fintype.card V : ℝ)*Real.log d/2 ≤ + (Fintype.card (A : Set V) : ℝ)*Real.log (2*d) := by + have h1 := mul_le_mul_of_nonneg_right hAcard hlog0 + have h2 := mul_le_mul_of_nonneg_left hlog (Nat.cast_nonneg (α := ℝ) (Fintype.card (A : Set V))) + nlinarith + have hden : 0 < 8*D*d := by positivity + have hcompare := div_le_div_of_nonneg_right hnum hden.le + change (Fintype.card (A : Set V) : ℝ)*Real.log (2*d)/(4*D*(2*d)) ≤ _ at hmax + have heq : (1/(16*D))*(Fintype.card V : ℝ)*Real.log d/d = + ((Fintype.card V : ℝ)*Real.log d/2)/(8*D*d) := by + field_simp + ring + change (1/(16*D))*(Fintype.card V : ℝ)*Real.log d/d ≤ _ + rw [heq] + apply hcompare.trans + have hdeneq : 8*D*d = 4*D*(2*d) := by ring + rw [hdeneq] + exact hmax.trans hi + +end CliqueFreeLog + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/MaxDegree.lean b/lean/OAI/Combinatorics/CliqueFree/MaxDegree.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0a0fe89f67302474c6c55e9bfd2df7dfd7ffcce --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/MaxDegree.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.CliqueFree.IndependentSet + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +lemma log_le_one_add_quarter {t : ℝ} (ht : 0 < t) : Real.log t ≤ 1+t/4 := by + have h4 : Real.log 4 ≤ 2 := by + have h2 := Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2) + have he : Real.log 4 = 2*Real.log 2 := by + rw [show (4 : ℝ) = 2^2 by norm_num, Real.log_pow] + norm_num + linarith + have hh := Real.log_le_sub_one_of_pos (div_pos ht (by norm_num : (0 : ℝ) < 4)) + rw [Real.log_div ht.ne' (by norm_num : (4 : ℝ) ≠ 0)] at hh + linarith + +lemma neighborMass_const (G : SimpleGraph V) (p : ℝ) (v : V) : + neighborMass G (fun _ ↦ p) v = (G.degree v : ℝ)*p := by + simp only [neighborMass,mass,sum_const,nsmul_eq_mul,card_neighbors] + +lemma edgeMass_const_le (G : SimpleGraph V) {Δ : ℝ} + (hdeg : ∀ v, (G.degree v : ℝ) ≤ Δ) (p : ℝ) : + edgeMass G (fun _ ↦ p) ≤ (Fintype.card V : ℝ)*Δ*p^2/2 := by + have hs := sum_le_sum (s := univ) fun v _ ↦ mul_le_mul_of_nonneg_right (hdeg v) (sq_nonneg p) + simp only [sum_const,card_univ,nsmul_eq_mul] at hs + have he := edgeForm_self G (fun _ ↦ p) + rw [edgeForm_neighbor] at he + simp only [neighborMass_const] at he + have he' : (∑ u, p*((G.degree u : ℝ)*p)) = ∑ u, (G.degree u : ℝ)*p^2 := by + apply sum_congr rfl + intro u _ + ring + rw [he'] at he + nlinarith + +lemma potential_const_lower (G : SimpleGraph V) {Δ : ℝ} (hΔ : 1 < Δ) + (hdeg : ∀ v, (G.degree v : ℝ) ≤ Δ) : + (Fintype.card V : ℝ)*(Real.log Δ)^2/(4*Δ) ≤ + potential G (fun _ ↦ Real.log Δ / Δ) := by + have hΔpos : 0 < Δ := lt_trans zero_lt_one hΔ + have ht : 0 < Real.log Δ := Real.log_pos hΔ + have hp : 0 < Real.log Δ / Δ := div_pos ht hΔpos + have hlog := log_le_one_add_quarter ht + have hhe : Δ*(Real.log Δ/Δ) = Real.log Δ := by field_simp + have hterm : Real.log Δ/4 ≤ 1-Real.log (Real.log Δ/Δ)-Δ*(Real.log Δ/Δ)/2 := by + rw [Real.log_div ht.ne' hΔpos.ne', hhe] + linarith + have hc : 0 ≤ (Fintype.card V : ℝ) := Nat.cast_nonneg _ + have hmul := mul_le_mul_of_nonneg_left hterm (mul_nonneg hc hp.le) + have he := edgeMass_const_le G hdeg (Real.log Δ/Δ) + simp only [potential,vertexPotential,sum_const,card_univ,nsmul_eq_mul] + have heq : (Fintype.card V : ℝ)*(Real.log Δ)^2/(4*Δ) = + (Fintype.card V : ℝ)*(Real.log Δ/Δ)*(Real.log Δ/4) := by ring + rw [heq] + nlinarith + +/-- The quantitative maximum-degree independence bound. -/ +lemma maximum_degree_independence (k : ℕ) {B Δ : ℝ} (hB : 0 ≤ B) (hΔ : 3 ≤ Δ) + (htri : ∀ {U : Type u} [Fintype U] (H : SimpleGraph U) (w : U → ℝ), + IsOptimizer H w → H.CliqueFree (k+2) → triangleMass H w ≤ B * edgeMass H w) + (G : SimpleGraph V) (hf : G.CliqueFree (k+2)) (hdeg : ∀ v, (G.degree v : ℝ) ≤ Δ) : + (Fintype.card V : ℝ)*Real.log Δ/(4*(3+3*B/2)*Δ) ≤ (G.indepNum : ℝ) := by + have hΔpos : 0 < Δ := by linarith + have ht : 0 < Real.log Δ := Real.log_pos (by linarith) + have hD : 0 < 3+3*B/2 := by positivity + obtain ⟨I,hI,hIp⟩ := maximum_degree_potential_bound k hB hΔ htri G hf hdeg + have hupper := hIp (fun _ ↦ Real.log Δ/Δ) (fun _ ↦ (div_pos ht hΔpos).le) + have hlower := potential_const_lower G (by linarith : 1 < Δ) hdeg + have hc : (I.card : ℝ) ≤ G.indepNum := Nat.cast_le.2 hI.card_le_indepNum + have hfinal := hupper.trans (mul_le_mul_of_nonneg_left hc (mul_pos hD ht).le) + have hbound := hlower.trans hfinal + apply (mul_le_mul_iff_left₀ (mul_pos hD ht)).1 + convert hbound using 1 <;> field_simp + +lemma indepNum_induce_le (G : SimpleGraph V) (A : Finset V) : + (G.induce (A : Set V)).indepNum ≤ G.indepNum := by + classical + obtain ⟨I,hI⟩ := (G.induce (A : Set V)).exists_isNIndepSet_indepNum + have h := (indepSet_image_induce G A I hI.isIndepSet).card_le_indepNum + simpa only [card_map,hI.card_eq] using h + +lemma degree_cutoff_card (G : SimpleGraph V) {d : ℝ} (hd : 0 < d) + (hsum : (∑ v, (G.degree v : ℝ)) = (Fintype.card V : ℝ)*d) : + (Fintype.card V : ℝ)/2 ≤ ((univ.filter fun v ↦ (G.degree v : ℝ) ≤ 2*d).card : ℝ) := by + classical + let A : Finset V := univ.filter fun v ↦ (G.degree v : ℝ) ≤ 2*d + have hv (v : V) (h : v ∈ Aᶜ) : 2*d ≤ (G.degree v : ℝ) := by + have hh : ¬(G.degree v : ℝ) ≤ 2*d := by simpa [A] using h + exact le_of_lt (lt_of_not_ge hh) + have hlow := sum_le_sum (s := Aᶜ) fun v h ↦ hv v h + simp only [sum_const,nsmul_eq_mul] at hlow + have hu : (∑ v ∈ Aᶜ, (G.degree v : ℝ)) ≤ ∑ v, (G.degree v : ℝ) := by + exact sum_le_sum_of_subset_of_nonneg (subset_univ _) (fun _ _ _ ↦ Nat.cast_nonneg _) + have hcard : (A.card : ℝ)+(Aᶜ.card : ℝ) = Fintype.card V := by + exact_mod_cast card_add_card_compl A + change (Fintype.card V : ℝ)/2 ≤ (A.card : ℝ) + rw [hsum] at hu + nlinarith + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Model.lean b/lean/OAI/Combinatorics/CliqueFree/Model.lean new file mode 100644 index 0000000000000000000000000000000000000000..595268e60f828c53360aefb3f65b6dd36b703c1b --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Model.lean @@ -0,0 +1,13 @@ +import Mathlib + +namespace OAI + +namespace CliqueFreeLog + +noncomputable def averageDegree {V : Type*} [Fintype V] (G : SimpleGraph V) : ℝ := by + classical + exact 2 * (G.edgeFinset.card : ℝ) / (Fintype.card V : ℝ) + +end CliqueFreeLog + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/MultiplierLaw.lean b/lean/OAI/Combinatorics/CliqueFree/MultiplierLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2afb0b153488881e2f51c4fe313f10945906d11 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/MultiplierLaw.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.CliqueFree.Lottery +import OAI.Combinatorics.CliqueFree.Optimizer + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence +universe u +namespace WeightedGraph +open Lottery +variable {V : Type u} [Fintype V] + +/-- A weight vector restricted to a vertex set. -/ +noncomputable def restrict (A : Finset V) (w : V → ℝ) : V → ℝ := fun v ↦ if v ∈ A then w v else 0 + +lemma edgeMass_smul (G : SimpleGraph V) (w : V → ℝ) (a : ℝ) : + edgeMass G (fun v ↦ a*w v) = a^2 * edgeMass G w := by + have h : edgeForm G (fun v ↦ a*w v) (fun v ↦ a*w v) = a^2*edgeForm G w w := by + unfold edgeForm + rw [mul_sum] + apply sum_congr rfl + intro u _ + rw [mul_sum] + apply sum_congr rfl + intro v _ + split_ifs <;> ring + rw [edgeForm_self,edgeForm_self] at h + linarith + +lemma edgeMass_restrict (G : SimpleGraph V) (w : V → ℝ) (A : Finset V) : + edgeMass G (restrict A w) = crossMass G w A A / 2 := by + classical + unfold edgeMass crossMass restrict + congr 1 + calc + _ = ∑ u, ∑ v, if u ∈ A ∧ v ∈ A then (if G.Adj u v then w u*w v else 0) else 0 := by + apply sum_congr rfl + intro u _ + apply sum_congr rfl + intro v _ + by_cases hu : u ∈ A <;> by_cases hv : v ∈ A <;> simp [hu,hv] + _ = _ := by + simp only [ite_and] + simp_rw [sum_ite_irrel] + simp only [sum_const_zero] + rw [← sum_filter] + simp only [filter_mem_eq_inter,univ_inter] + apply sum_congr rfl + intro u hu + rw [← sum_filter] + simp + +lemma crossMass_restrict (G : SimpleGraph V) (w : V → ℝ) (A : Finset V) : + crossMass G w A A = ∑ v ∈ A, w v * mass w (A ∩ neighbors G v) := crossMass_factor G w A A + +lemma edgeMass_restrict_le (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + (A : Finset V) {t : ℝ} (hA : ∀ v ∈ A, mass w (A ∩ neighbors G v) ≤ t) : + edgeMass G (restrict A w) ≤ t * mass w A / 2 := by + rw [edgeMass_restrict,crossMass_restrict] + apply div_le_div_of_nonneg_right _ (by norm_num) + calc + _ ≤ ∑ v ∈ A, w v*t := sum_le_sum fun v hv ↦ mul_le_mul_of_nonneg_left (hA v hv) (hw v) + _ = _ := by rw [← sum_mul]; exact mul_comm _ _ + +/-- Bounded multipliers supported on A, regardless of the lottery weight of the entry. -/ +def BoundedOn (L : Law (V → ℝ)) (A : Finset V) (b : ℝ) : Prop := + ∀ z ∈ L, (∀ v, 0 ≤ z.2 v ∧ z.2 v ≤ b) ∧ (∀ v, v ∉ A → z.2 v = 0) + +noncomputable def expectedEdges (G : SimpleGraph V) (w : V → ℝ) (L : Law (V → ℝ)) : ℝ := + expect L (fun m ↦ edgeMass G (fun v ↦ w v*m v)) + +lemma expectedEdges_transform (G : SimpleGraph V) (w : V → ℝ) (L : Law (V → ℝ)) (p k : ℝ) : + expectedEdges G w (transform p (fun m v ↦ k*m v) L) = p*k^2*expectedEdges G w L := by + unfold expectedEdges + rw [expect_transform] + have he (m : V → ℝ) : edgeMass G (fun v ↦ w v*(k*m v)) = k^2*edgeMass G (fun v ↦ w v*m v) := by + convert edgeMass_smul G (fun v ↦ w v*m v) k using 2 + ext v + ring + change p * expect L (fun m ↦ edgeMass G (fun v ↦ w v*(k*m v))) = _ + simp_rw [he] + rw [expect_mul] + ring + +omit [Fintype V] in +lemma mean_transform (L : Law (V → ℝ)) (p k : ℝ) (v : V) : + expect (transform p (fun m v ↦ k*m v) L) (fun m ↦ m v) = p*k*expect L (fun m ↦ m v) := by + rw [expect_transform] + change p * expect L (fun m ↦ k*m v) = _ + rw [expect_mul] + ring + +omit [Fintype V] in +lemma bounded_transform {L : Law (V → ℝ)} {A : Finset V} {b B k : ℝ} + (hL : BoundedOn L A b) (hk : 0 ≤ k) (hkb : k*b ≤ B) (p : ℝ) : + BoundedOn (transform p (fun m v ↦ k*m v) L) A B := by + intro z hz + obtain ⟨y,hy,rfl⟩ := List.mem_map.1 hz + obtain ⟨hby,hsy⟩ := hL y hy + exact ⟨fun v ↦ ⟨mul_nonneg hk (hby v).1,(mul_le_mul_of_nonneg_left (hby v).2 hk).trans hkb⟩, + fun v hv ↦ by simp [hsy v hv]⟩ + +omit [Fintype V] in +lemma bounded_append {L K : Law (V → ℝ)} {A B S : Finset V} {b : ℝ} + (hL : BoundedOn L A b) (hK : BoundedOn K B b) (hA : A ⊆ S) (hB : B ⊆ S) : + BoundedOn (L++K) S b := by + intro z hz + rcases List.mem_append.1 hz with hz | hz + · exact ⟨(hL z hz).1,fun v hv ↦ (hL z hz).2 v (fun h ↦ hv (hA h))⟩ + · exact ⟨(hK z hz).1,fun v hv ↦ (hK z hz).2 v (fun h ↦ hv (hB h))⟩ + +lemma normalize_subprob (G : SimpleGraph V) (w : V → ℝ) {L : Law (V → ℝ)} + (hL : Positive L) (hsum : total L ≤ 1) {A : Finset V} {b : ℝ} (hb : 0 ≤ b) + (hbL : BoundedOn L A b) : + ∃ K : Law (V → ℝ), IsProb K ∧ BoundedOn K A b ∧ + (∀ v, expect K (fun m ↦ m v) = expect L (fun m ↦ m v)) ∧ + expectedEdges G w K = expectedEdges G w L := by + let K : Law (V → ℝ) := (1-total L,0)::L + refine ⟨K,⟨?_,?_⟩,?_,?_,?_⟩ + · intro z hz + rcases List.mem_cons.1 hz with rfl | hz + · exact sub_nonneg.2 hsum + · exact hL z hz + · simp [K,total,expect_cons] + · intro z hz + rcases List.mem_cons.1 hz with rfl | hz + · exact ⟨fun _ ↦ ⟨le_rfl,hb⟩,fun _ _ ↦ rfl⟩ + · exact hbL z hz + · intro v + simp [K] + · simp [K,expectedEdges,edgeMass,crossMass] + +end WeightedGraph +end CliqueFreeIndependence + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Numerical.lean b/lean/OAI/Combinatorics/CliqueFree/Numerical.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c3e2b0e146d7e024c572887a399cb8e7cae7c5e --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Numerical.lean @@ -0,0 +1,202 @@ +import OAI.Combinatorics.CliqueFree.Model + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence + +universe u v + +namespace Numerical + +lemma log_bounds {x : ℝ} (hx : 32 ≤ x) : 1 ≤ Real.log x ∧ 7 * Real.log x ≤ x := by + have hx0 : 0 < x := by linarith + have h32 : Real.log (32 : ℝ) = 5 * Real.log 2 := by + rw [show (32 : ℝ) = 2 ^ 5 by norm_num, Real.log_pow] + norm_num + have h4 : Real.log (4 : ℝ) = 2 * Real.log 2 := by + rw [show (4 : ℝ) = 2 ^ 2 by norm_num, Real.log_pow] + norm_num + have hlower := Real.log_le_log (by norm_num : (0 : ℝ) < 4) (show (4 : ℝ) ≤ x by linarith) + rw [h4] at hlower + have hupper := Real.log_le_sub_one_of_pos (div_pos hx0 (by norm_num : (0 : ℝ) < 32)) + rw [Real.log_div hx0.ne' (by norm_num), h32] at hupper + have h2l := Real.log_two_gt_d9 + have h2u := Real.log_two_lt_d9 + constructor <;> linarith + +lemma pow_six_le_exp {x : ℝ} (hx : 32 ≤ x) : x ^ 6 ≤ Real.exp x := by + have hx0 : 0 < x := by linarith + have hlog := log_bounds hx + calc + _ = Real.exp (6 * Real.log x) := by + have hp : Real.log (x ^ 6) = 6 * Real.log x := by simp only [Real.log_pow, Nat.cast_ofNat] + rw [← hp, Real.exp_log (pow_pos hx0 6)] + _ ≤ _ := Real.exp_le_exp.2 (by linarith) + +lemma exp_neg_le_inv_pow_seven {x : ℝ} (hx : 32 ≤ x) : + Real.exp (-x) ≤ 1 / x ^ 7 := by + have hx0 : 0 < x := by linarith + calc + _ ≤ Real.exp (-(7 * Real.log x)) := Real.exp_le_exp.2 (by linarith [(log_bounds hx).2]) + _ = _ := by + have hp : Real.log (x ^ 7) = 7 * Real.log x := by simp only [Real.log_pow, Nat.cast_ofNat] + rw [Real.exp_neg, ← hp, Real.exp_log (pow_pos hx0 7)] + simp only [one_div] + +noncomputable def threshold (x : ℝ) : ℝ := 1 / (Real.exp x * x ^ 6) + +lemma threshold_pos {x : ℝ} (hx : 0 < x) : 0 < threshold x := + one_div_pos.2 (mul_pos (Real.exp_pos x) (pow_pos hx 6)) + +lemma growth_factor_le {x : ℝ} (hx : 32 ≤ x) : + 1 + Real.exp x / threshold x ≤ Real.exp (4 * x) := by + have hx0 : 0 ≤ x := by linarith + have he1 : 1 ≤ Real.exp x := Real.one_le_exp_iff.2 hx0 + have he2 : 2 ≤ Real.exp x := by linarith [Real.add_one_le_exp x] + have hp3 : 1 ≤ Real.exp x ^ 3 := one_le_pow₀ he1 + have hid : Real.exp x / threshold x = Real.exp x * Real.exp x * x ^ 6 := by + unfold threshold + simp only [div_div_eq_mul_div, div_one] + ring + rw [hid, show 4 * x = (4 : ℕ) * x by norm_num, Real.exp_nat_mul] + calc + _ ≤ 1 + Real.exp x * Real.exp x * Real.exp x := + add_le_add le_rfl (mul_le_mul_of_nonneg_left (pow_six_le_exp hx) (by positivity)) + _ = 1 + Real.exp x ^ 3 := by ring + _ ≤ 2 * Real.exp x ^ 3 := by linarith + _ ≤ Real.exp x * Real.exp x ^ 3 := mul_le_mul_of_nonneg_right he2 (by positivity) + _ = _ := by ring + +lemma leakage_factor {x : ℝ} (hx : 0 < x) : + x ^ 2 * threshold x * Real.exp x = 1 / x ^ 4 := by + unfold threshold + field_simp [hx.ne', (Real.exp_pos x).ne'] + +lemma ceil_bounds {x : ℝ} (hx : 32 ≤ x) : + 0 < ⌈x⌉₊ ∧ x ≤ (⌈x⌉₊ : ℝ) ∧ (⌈x⌉₊ : ℝ) ≤ 2 * x := by + have hl := Nat.le_ceil x + have hu := Nat.ceil_lt_add_one (show 0 ≤ x by linarith) + refine ⟨?_, hl, by linarith⟩ + have : (0 : ℝ) < (⌈x⌉₊ : ℝ) := by linarith + exact_mod_cast this + +end Numerical + +end CliqueFreeIndependence + +open Filter +namespace CliqueFreeIndependence.Numerical + +def lossRatio (x : ℝ) : ℝ := Real.log x / Real.sqrt x + +def scale (X : ℝ) : ℕ → ℝ + | 0 => X + | n+1 => (scale X n)^2 + +lemma scale_ge {X : ℝ} (hX : 1 ≤ X) (n : ℕ) : X ≤ scale X n := by + induction n with + | zero => simp [scale] + | succ n ih => + have ht : 1 ≤ scale X n := hX.trans ih + dsimp [scale] + nlinarith + +lemma scale_ge_add {X : ℝ} (hX : 2 ≤ X) (n : ℕ) : X + n ≤ scale X n := by + induction n with + | zero => simp [scale] + | succ n ih => + have ht : 2 ≤ scale X n := hX.trans (scale_ge (by linarith) n) + simp only [scale, Nat.cast_add, Nat.cast_one] + nlinarith + +lemma lossRatio_nonneg {x : ℝ} (hx : 1 ≤ x) : 0 ≤ lossRatio x := + div_nonneg (Real.log_nonneg hx) (Real.sqrt_nonneg _) + +lemma lossRatio_square {x : ℝ} (hx : 16 ≤ x) : lossRatio (x^2) ≤ (1/2) * lossRatio x := by + have hx0 : 0 < x := by linarith + have hl : 0 ≤ Real.log x := Real.log_nonneg (by linarith) + have hsq := Real.sq_sqrt hx0.le + have hs0 := Real.sqrt_nonneg x + have hs : 4 ≤ Real.sqrt x := by nlinarith + unfold lossRatio + rw [Real.log_pow, Real.sqrt_sq hx0.le] + norm_num only [Nat.cast_ofNat] + apply (div_le_iff₀ hx0).2 + rw [mul_assoc, div_mul_eq_mul_div] + have hid : (Real.log x * x) / Real.sqrt x = Real.log x * Real.sqrt x := by + apply (div_eq_iff (by linarith : Real.sqrt x ≠ 0)).2 + nlinarith + have hid' : Real.log x / Real.sqrt x * x = Real.log x * Real.sqrt x := by + calc + _ = Real.log x * x / Real.sqrt x := by ring + _ = _ := hid + rw [hid'] + nlinarith [mul_le_mul_of_nonneg_left hs hl] + +lemma lossRatio_scale {X : ℝ} (hX : 16 ≤ X) (n : ℕ) : + lossRatio (scale X n) ≤ (1/2 : ℝ)^n * lossRatio X := by + induction n with + | zero => simp [scale] + | succ n ih => + have ht : 16 ≤ scale X n := hX.trans (scale_ge (by linarith) n) + calc + _ ≤ (1/2) * lossRatio (scale X n) := lossRatio_square ht + _ ≤ (1/2) * ((1/2 : ℝ)^n * lossRatio X) := mul_le_mul_of_nonneg_left ih (by norm_num) + _ = _ := by rw [pow_succ]; ring + +lemma inv_scale {X : ℝ} (hX : 2 ≤ X) (n : ℕ) : + 1 / scale X n ≤ (1/2 : ℝ)^n * (1/X) := by + induction n with + | zero => simp [scale] + | succ n ih => + have ht : 2 ≤ scale X n := hX.trans (scale_ge (by linarith) n) + have ht0 : 0 < scale X n := by linarith + have he : 1 / (scale X n)^2 ≤ (1/2) * (1 / scale X n) := by + apply (div_le_iff₀ (pow_pos ht0 2)).2 + field_simp + nlinarith + calc + _ ≤ (1/2) * (1 / scale X n) := he + _ ≤ (1/2) * ((1/2 : ℝ)^n * (1/X)) := mul_le_mul_of_nonneg_left ih (by norm_num) + _ = _ := by rw [pow_succ]; ring + +lemma exists_iteration_threshold (a : ℝ) : + ∃ X : ℝ, 32 ≤ X ∧ a * lossRatio X ≤ 1/4 := by + have h := (isLittleO_log_rpow_atTop (by norm_num : (0:ℝ) < 1/2)).tendsto_div_nhds_zero + have ht : Tendsto (fun x : ℝ ↦ a * lossRatio x) atTop (nhds 0) := by + simpa only [lossRatio, Real.sqrt_eq_rpow, mul_zero] using h.const_mul a + have he : ∀ᶠ x : ℝ in atTop, a * lossRatio x < 1/4 := + ht.eventually (gt_mem_nhds (by norm_num)) + obtain ⟨X,hX⟩ := eventually_atTop.1 he + exact ⟨max 32 X, le_max_left _ _, (hX (max 32 X) (le_max_right _ _)).le⟩ + +lemma recurrence_bound {B q ε t m s : ℝ} + (hB : 1 ≤ B) (hq0 : 0 ≤ q) (hq1 : q ≤ 1) + (_hε0 : 0 ≤ ε) (hε : ε ≤ q/4) (_ht : 0 ≤ t) (hm : 0 ≤ m) + (hs : s ≤ q/2) + (hstep : (1-ε)*t - s*m ≤ B*(2-2*q)*m) : + t ≤ B*(2-q)*m := by + have hB0 : 0 ≤ B := by linarith + have hb : 0 ≤ B*(2-q) := mul_nonneg hB0 (by linarith) + have hb2 : B*(2-q) ≤ 2*B := by nlinarith + have hnum : B*(2-2*q)+s ≤ (1-ε)*(B*(2-q)) := by + have he : ε * (B*(2-q)) ≤ (q/4)*(2*B) := + mul_le_mul hε hb2 hb (by positivity) + nlinarith [mul_nonneg (sub_nonneg.2 hB) hq0] + have hpos : 0 < 1-ε := by linarith + apply (mul_le_mul_iff_right₀ hpos).1 + have hh := mul_le_mul_of_nonneg_right hnum hm + nlinarith only [hh,hstep] + +end CliqueFreeIndependence.Numerical + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Optimizer.lean b/lean/OAI/Combinatorics/CliqueFree/Optimizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..9edd8e341fe2eac7a35ac74625db1d68e03c723e --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Optimizer.lean @@ -0,0 +1,250 @@ +import OAI.Combinatorics.CliqueFree.WeightedGraph + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph +universe u +variable {V : Type u} [Fintype V] + +/-- The directed bilinear edge form (twice the quadratic mass on the diagonal). -/ +noncomputable def edgeForm (G : SimpleGraph V) (a b : V → ℝ) : ℝ := + ∑ u, ∑ v, if G.Adj u v then a u * b v else 0 + +lemma edgeForm_self (G : SimpleGraph V) (a : V → ℝ) : edgeForm G a a = 2 * edgeMass G a := by + simp only [edgeForm,edgeMass,crossMass] + ring + +lemma edgeForm_symm (G : SimpleGraph V) (a b : V → ℝ) : edgeForm G a b = edgeForm G b a := by + unfold edgeForm + rw [sum_comm] + simp_rw [G.adj_comm,mul_comm] + +lemma edgeForm_add_left (G : SimpleGraph V) (a b c : V → ℝ) : + edgeForm G (a+b) c = edgeForm G a c + edgeForm G b c := by + unfold edgeForm + rw [← sum_add_distrib] + apply sum_congr rfl + intro u _ + rw [← sum_add_distrib] + apply sum_congr rfl + intro v _ + split_ifs <;> simp [Pi.add_apply,add_mul] + +lemma edgeForm_add_right (G : SimpleGraph V) (a b c : V → ℝ) : + edgeForm G a (b+c) = edgeForm G a b + edgeForm G a c := by + rw [edgeForm_symm,edgeForm_add_left,edgeForm_symm _ b,edgeForm_symm _ c] + +lemma edgeForm_neighbor (G : SimpleGraph V) (a b : V → ℝ) : + edgeForm G a b = ∑ u, a u * neighborMass G b u := by + simp only [edgeForm,neighborMass,mass,neighbors,sum_filter,mul_sum,mul_ite,mul_zero] + +lemma edgeMass_add (G : SimpleGraph V) (a b : V → ℝ) : + edgeMass G (a+b) = edgeMass G a + edgeMass G b + edgeForm G a b := by + have h := edgeForm_self G (a+b) + rw [edgeForm_add_left,edgeForm_add_right,edgeForm_add_right,edgeForm_self,edgeForm_self, + edgeForm_symm G b a] at h + linarith + +lemma edgeForm_mono (G : SimpleGraph V) {a b c d : V → ℝ} + (ha : ∀ v, 0 ≤ a v) (hb : ∀ v, 0 ≤ b v) (hac : ∀ v, a v ≤ c v) (hbd : ∀ v, b v ≤ d v) : + edgeForm G a b ≤ edgeForm G c d := by + apply sum_le_sum + intro u _ + apply sum_le_sum + intro v _ + split_ifs + · exact mul_le_mul (hac u) (hbd v) (hb v) ((ha u).trans (hac u)) + · rfl + +lemma edgeMass_mono_weight (G : SimpleGraph V) {w q : V → ℝ} + (hw : ∀ v, 0 ≤ w v) (hwq : ∀ v, w v ≤ q v) : edgeMass G w ≤ edgeMass G q := by + have h := edgeForm_mono G hw hw hwq hwq + rw [edgeForm_self,edgeForm_self] at h + linarith + +noncomputable def spike [DecidableEq V] (v : V) (t : ℝ) : V → ℝ := fun u ↦ if u = v then t else 0 + +lemma edgeForm_spike [DecidableEq V] (G : SimpleGraph V) (w : V → ℝ) (v : V) (t : ℝ) : + edgeForm G (spike v t) w = t * neighborMass G w v := by + rw [edgeForm_neighbor] + simp [spike,ite_mul] + +lemma edgeMass_spike [DecidableEq V] (G : SimpleGraph V) (v : V) (t : ℝ) : + edgeMass G (spike v t) = 0 := by + have h := edgeForm_self G (spike v t) + rw [edgeForm_spike] at h + have hn : neighborMass G (spike v t) v = 0 := by + simp [neighborMass,mass,neighbors,spike] + rw [hn] at h + linarith + +omit [Fintype V] in +lemma update_eq_add_spike [DecidableEq V] (w : V → ℝ) (v : V) (t : ℝ) : + Function.update w v t = w + spike v (t-w v) := by + funext u + by_cases h : u = v <;> simp [Function.update,spike,h] + +lemma edgeMass_update [DecidableEq V] (G : SimpleGraph V) (w : V → ℝ) (v : V) (t : ℝ) : + edgeMass G (Function.update w v t) = edgeMass G w + (t-w v)*neighborMass G w v := by + rw [update_eq_add_spike,edgeMass_add,edgeMass_spike,edgeForm_symm,edgeForm_spike] + ring + +/-- The vertex summand, with Mathlib's log(0)=0 convention. -/ +def vertexPotential (t : ℝ) : ℝ := t * (1-Real.log t) + +noncomputable def potential (G : SimpleGraph V) (w : V → ℝ) : ℝ := + ∑ v, vertexPotential (w v) - edgeMass G w + +def IsOptimizer (G : SimpleGraph V) (w : V → ℝ) : Prop := + (∀ v, 0 ≤ w v) ∧ ∀ q : V → ℝ, (∀ v, 0 ≤ q v) → potential G q ≤ potential G w + +lemma continuous_vertexPotential : Continuous vertexPotential := by + have h := continuous_id.sub Real.continuous_mul_log + convert h using 1 + ext x + simp [vertexPotential] + ring + +lemma continuous_edgeMass (G : SimpleGraph V) : Continuous (edgeMass G) := by + classical + unfold edgeMass crossMass + apply Continuous.div_const + apply continuous_finsetSum + intro u _ + apply continuous_finsetSum + intro v _ + split_ifs <;> fun_prop + +lemma continuous_potential (G : SimpleGraph V) : Continuous (potential G) := by + unfold potential + apply Continuous.sub _ (continuous_edgeMass G) + exact continuous_finsetSum _ fun v _ ↦ continuous_vertexPotential.comp (continuous_apply v) + +lemma vertexPotential_le_one {t : ℝ} (ht : 0 ≤ t) : vertexPotential t ≤ 1 := by + rcases ht.eq_or_lt with rfl | ht + · norm_num [vertexPotential] + have h := mul_le_mul_of_nonneg_left (Real.one_sub_inv_le_log_of_pos ht) ht.le + rw [mul_sub,mul_inv_cancel₀ ht.ne'] at h + unfold vertexPotential + nlinarith + +lemma potential_clamp (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) : + potential G w ≤ potential G (fun v ↦ min (w v) 1) := by + have hv (v : V) : vertexPotential (w v) ≤ vertexPotential (min (w v) 1) := by + by_cases h : w v ≤ 1 + · rw [min_eq_left h] + · rw [min_eq_right (le_of_not_ge h)] + simpa [vertexPotential] using vertexPotential_le_one (hw v) + have hs := sum_le_sum (s := univ) (fun v _ ↦ hv v) + have he := edgeMass_mono_weight G (fun v ↦ le_min (hw v) zero_le_one) (fun v ↦ min_le_left (w v) 1) + unfold potential + linarith + +lemma exists_optimizer (G : SimpleGraph V) : ∃ w : V → ℝ, IsOptimizer G w := by + let S : Set (V → ℝ) := Set.Icc 0 1 + have hS : IsCompact S := isCompact_Icc + have hne : S.Nonempty := ⟨0,by simp [S]⟩ + obtain ⟨w,hw,hmax⟩ := hS.exists_isMaxOn hne (continuous_potential G).continuousOn + refine ⟨w,hw.1,?_⟩ + intro q hq + apply (potential_clamp G hq).trans + apply hmax + exact ⟨fun v ↦ le_min (hq v) zero_le_one,fun v ↦ min_le_right (q v) 1⟩ + +lemma potential_update [DecidableEq V] (G : SimpleGraph V) (w : V → ℝ) (v : V) (t : ℝ) : + potential G (Function.update w v t) - potential G w = + vertexPotential t - vertexPotential (w v) - (t-w v)*neighborMass G w v := by + have hs : (∑ u, vertexPotential (Function.update w v t u)) = + ∑ u, vertexPotential (w u) + (vertexPotential t - vertexPotential (w v)) := by + rw [← add_sum_erase _ _ (mem_univ v), ← add_sum_erase _ _ (mem_univ v)] + simp only [Function.update_self] + have h : (∑ u ∈ univ.erase v, vertexPotential (Function.update w v t u)) = + ∑ u ∈ univ.erase v, vertexPotential (w u) := by + apply sum_congr rfl + intro u hu + rw [Function.update_of_ne (by simpa using (mem_erase.1 hu).1)] + rw [h] + ring + unfold potential + rw [hs,edgeMass_update] + ring + +lemma optimizer_stationary {G : SimpleGraph V} {w : V → ℝ} (hw : IsOptimizer G w) (v : V) : + 0 < w v ∧ Real.log (1/w v) = neighborMass G w v ∧ w v ≤ 1 := by + classical + let N := neighborMass G w v + let a := Real.exp (-N) + have ha : 0 < a := Real.exp_pos _ + have hN : 0 ≤ N := neighborMass_nonneg G hw.1 v + have ha1 : a ≤ 1 := Real.exp_le_one_iff.2 (by linarith) + have hloga : Real.log a = -N := Real.log_exp _ + have hmax := hw.2 (Function.update w v a) (fun u ↦ by + by_cases h : u = v + · subst u; simpa using ha.le + · simpa [h] using hw.1 u) + have heq := potential_update G w v a + have hbound : a ≤ w v * (1-Real.log (w v)-N) := by + rw [vertexPotential,vertexPotential,hloga] at heq + dsimp [N] at * + nlinarith only [hmax,heq] + have hwv : 0 < w v := by + have h0 := hw.1 v + by_contra hn + have hz : w v = 0 := le_antisymm (le_of_not_gt hn) h0 + simp only [hz,zero_mul] at hbound + linarith + have hwa : w v = a := by + by_contra hn + have hdiv : a / w v ≠ 1 := by + intro he + exact hn ((div_eq_one_iff_eq hwv.ne').1 he).symm + have hl := Real.log_lt_sub_one_of_pos (div_pos ha hwv) hdiv + rw [Real.log_div ha.ne' hwv.ne',hloga] at hl + have hh := mul_lt_mul_of_pos_left hl hwv + have hid : w v * (a / w v - 1) = a-w v := by field_simp + rw [hid] at hh + nlinarith + refine ⟨hwv,?_,hwa ▸ ha1⟩ + rw [one_div,Real.log_inv,hwa,hloga] + simp [N] + +/-- Expansion around a stationary positive maximizer. -/ +lemma optimizer_divergence {G : SimpleGraph V} {w : V → ℝ} (hw : IsOptimizer G w) + (q : V → ℝ) (hq : ∀ v, 0 ≤ q v) : + 0 ≤ potential G w - potential G q ∧ + potential G w - potential G q = + (∑ v, (q v * Real.log (q v / w v) - q v + w v)) + edgeMass G (q-w) := by + refine ⟨sub_nonneg.2 (hw.2 q hq),?_⟩ + have hsum (v : V) : vertexPotential (w v) - vertexPotential (q v) + + (q v-w v)*neighborMass G w v = q v*Real.log (q v/w v) - q v + w v := by + obtain ⟨hwv,hstat,_⟩ := optimizer_stationary hw v + rw [one_div,Real.log_inv] at hstat + rcases (hq v).eq_or_lt with hz | hqv + · simp [← hz,vertexPotential,hstat.symm] + ring + · rw [Real.log_div hqv.ne' hwv.ne'] + unfold vertexPotential + rw [← hstat] + ring + have he := edgeMass_add G (q-w) w + have hqw : q-w+w = q := sub_add_cancel _ _ + rw [hqw,edgeForm_neighbor] at he + simp only [Pi.sub_apply] at he + have hs := congrArg (fun f : V → ℝ ↦ ∑ v, f v) (funext hsum) + simp only [sum_add_distrib,sum_sub_distrib] at hs + unfold potential + simp only [sum_add_distrib,sum_sub_distrib] + linarith + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/OptimizerBounds.lean b/lean/OAI/Combinatorics/CliqueFree/OptimizerBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e38028e3cf66b2f0d6b4197cf5c757a0324b559 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/OptimizerBounds.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.CliqueFree.Optimizer + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +lemma sum_log_le_log_sum {p x : V → ℝ} (hp : ∀ v, 0 ≤ p v) + (hs : ∑ v, p v = 1) (hx : ∀ v, 0 < x v) : + (∑ v, p v * Real.log (x v)) ≤ Real.log (∑ v, p v * x v) := by + simpa only [smul_eq_mul] using strictConcaveOn_log_Ioi.concaveOn.le_map_sum + (t := univ) (w := p) (p := x) (fun v _ ↦ hp v) hs (fun v _ ↦ hx v) + +lemma card_neighbors (G : SimpleGraph V) (v : V) : (neighbors G v).card = G.degree v := by + classical + have he : neighbors G v = G.neighborFinset v := by ext u; simp + rw [he, G.card_neighborFinset_eq_degree] + +lemma sum_neighborMass (G : SimpleGraph V) (w : V → ℝ) : + (∑ v, neighborMass G w v) = ∑ v, (G.degree v : ℝ) * w v := by + classical + simp only [neighborMass, mass, neighbors, sum_filter] + rw [sum_comm] + apply sum_congr rfl + intro v _ + simp_rw [G.adj_comm] + rw [← sum_filter] + simp only [sum_const, nsmul_eq_mul] + rw [← card_neighbors G v] + rfl + +lemma optimizer_total_weight {G : SimpleGraph V} {w : V → ℝ} (hw : IsOptimizer G w) + [Nonempty V] {Δ : ℝ} (hΔ : 3 ≤ Δ) (hdeg : ∀ v, (G.degree v : ℝ) ≤ Δ) : + (Fintype.card V : ℝ) / Δ ≤ ∑ v, w v := by + have hn : 0 < (Fintype.card V : ℝ) := Nat.cast_pos.2 Fintype.card_pos + have hwpos (v : V) : 0 < w v := (optimizer_stationary hw v).1 + have hW : 0 < ∑ v, w v := sum_pos (fun v _ ↦ hwpos v) univ_nonempty + have hp : (∑ _v : V, (Fintype.card V : ℝ)⁻¹) = 1 := by + simp [hn.ne'] + have hj := sum_log_le_log_sum (fun _v ↦ (inv_pos.2 hn).le) hp hwpos + simp only [← mul_sum] at hj + have he : (∑ v, Real.log (w v)) = -∑ v, neighborMass G w v := by + rw [← sum_neg_distrib] + apply sum_congr rfl + intro v _ + have hv := (optimizer_stationary hw v).2.1 + rw [one_div, Real.log_inv] at hv + linarith + rw [he, sum_neighborMass] at hj + have hd := sum_le_sum (s := univ) fun v _ ↦ mul_le_mul_of_nonneg_right (hdeg v) (hw.1 v) + rw [← mul_sum] at hd + have hJ : Real.log ((Fintype.card V : ℝ) / (∑ v, w v)) ≤ + Δ * (∑ v, w v) / (Fintype.card V : ℝ) := by + rw [Real.log_div hn.ne' hW.ne'] + rw [Real.log_mul (inv_ne_zero hn.ne') hW.ne', Real.log_inv] at hj + have hm := mul_le_mul_of_nonneg_left hd (inv_pos.2 hn).le + simp only [div_eq_mul_inv] at * + nlinarith + have hΔpos : 0 < Δ := by linarith + have hl : 1 < Real.log Δ := (Real.lt_log_iff_exp_lt hΔpos).2 + (Real.exp_one_lt_three.trans_le hΔ) + by_contra h + have hlt : (∑ v, w v) < (Fintype.card V : ℝ) / Δ := lt_of_not_ge h + have hmul : Δ * (∑ v, w v) < Fintype.card V := by + nlinarith [(lt_div_iff₀ hΔpos).1 hlt] + have hlog := Real.log_lt_log hΔpos ((lt_div_iff₀ hW).2 hmul) + have hfrac : Δ * (∑ v, w v) / (Fintype.card V : ℝ) < 1 := + (div_lt_one hn).2 hmul + linarith + +lemma optimizer_edge_bound {G : SimpleGraph V} {w : V → ℝ} (hw : IsOptimizer G w) + [Nonempty V] {Δ : ℝ} (hΔ : 3 ≤ Δ) (hdeg : ∀ v, (G.degree v : ℝ) ≤ Δ) : + 2 * edgeMass G w ≤ Real.log Δ * (∑ v, w v) := by + have hn : 0 < (Fintype.card V : ℝ) := Nat.cast_pos.2 Fintype.card_pos + have hwpos (v : V) : 0 < w v := (optimizer_stationary hw v).1 + have hW : 0 < ∑ v, w v := sum_pos (fun v _ ↦ hwpos v) univ_nonempty + have hp : (∑ v, w v / (∑ u, w u)) = 1 := by rw [← sum_div, div_self hW.ne'] + have hj := sum_log_le_log_sum (fun v ↦ (div_pos (hwpos v) hW).le) hp + (fun v ↦ one_div_pos.2 (hwpos v)) + have hright : (∑ v, w v / (∑ u, w u) * (1 / w v)) = + (Fintype.card V : ℝ) / (∑ v, w v) := by + calc + _ = ∑ _v : V, 1 / (∑ u, w u) := by + apply sum_congr rfl + intro v _ + field_simp [(hwpos v).ne'] + _ = _ := by simp [div_eq_mul_inv] + have hleft : (∑ v, w v / (∑ u, w u) * Real.log (1 / w v)) = + 2 * edgeMass G w / (∑ v, w v) := by + rw [← edgeForm_self, edgeForm_neighbor, sum_div] + apply sum_congr rfl + intro v _ + rw [(optimizer_stationary hw v).2.1] + ring + rw [hleft, hright] at hj + have htotal := optimizer_total_weight hw hΔ hdeg + have hΔpos : 0 < Δ := by linarith + have hm : (Fintype.card V : ℝ) / (∑ v, w v) ≤ Δ := by + apply (div_le_iff₀ hW).2 + nlinarith [(div_le_iff₀ hΔpos).1 htotal] + have hh := hj.trans (Real.log_le_log (div_pos hn hW) hm) + exact (div_le_iff₀ hW).1 hh + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Packing.lean b/lean/OAI/Combinatorics/CliqueFree/Packing.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8777d19afcdfd2c619ef4377fadbb8bdedb3d4d --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Packing.lean @@ -0,0 +1,134 @@ +import OAI.Combinatorics.CliqueFree.MultiplierLaw + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph +open Lottery +universe u +variable {V : Type u} [Fintype V] + +/-- Greedy disjoint-neighborhood packing, with a subprobability lottery. The additional +zero outcome is inserted only at the end. -/ +lemma neighborhood_packing (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 < w v) + (A : Finset V) {s η b B : ℝ} (hs : 0 < s) (hη : 0 < η) (hb : 0 ≤ b) + (hB : 2 ≤ B) (hbig : 2/η*b ≤ B) (_hAs : mass w A ≤ s) + (hlocal : ∀ (R : Finset V), R ⊆ A → ∀ v ∈ R, + η*s < mass w (R ∩ neighbors G v) → + ∃ L : Law (V → ℝ), IsProb L ∧ BoundedOn L (R ∩ neighbors G v) b ∧ + (∀ u, expect L (fun m ↦ m u) = if u ∈ R ∩ neighbors G v then 1 else 0) ∧ + expectedEdges G w L ≤ η * (mass w (R ∩ neighbors G v))^2) : + ∃ L : Law (V → ℝ), Positive L ∧ total L ≤ 1/2+mass w A/(2*s) ∧ + BoundedOn L A B ∧ + (∀ u, expect L (fun m ↦ m u) = if u ∈ A then 1 else 0) ∧ + expectedEdges G w L ≤ 2*η*s*mass w A := by + classical + have hw0 := fun v ↦ (hw v).le + suffices hpack : ∀ R : Finset V, R ⊆ A → + ∃ L : Law (V → ℝ), Positive L ∧ total L ≤ 1/2+mass w R/(2*s) ∧ + BoundedOn L R B ∧ + (∀ u, expect L (fun m ↦ m u) = if u ∈ R then 1 else 0) ∧ + expectedEdges G w L ≤ 2*η*s*mass w R by exact hpack A Subset.rfl + intro R + refine Finset.strongInductionOn R ?_ + intro R ih hRA + by_cases hsmall : ∀ v ∈ R, mass w (R ∩ neighbors G v) ≤ η*s + · let m : V → ℝ := restrict R (fun _ ↦ 2) + let L : Law (V → ℝ) := [(1/2,m)] + refine ⟨L,?_,?_,?_,?_,?_⟩ + · intro z hz + have hz' : z = (1/2,m) := by simpa [L] using hz + rw [hz']; norm_num + · have hr := div_nonneg (mass_nonneg hw0 R) (by positivity : 0 ≤ 2*s) + simp only [L,total,expect_singleton,mul_one] + linarith + · intro z hz + have hz' : z = (1/2,m) := by simpa [L] using hz + rw [hz'] + refine ⟨?_,?_⟩ + · intro v + dsimp [m,restrict] + split_ifs <;> constructor <;> linarith + · intro v hv + simp [m,restrict,hv] + · intro v + simp [L,m,restrict] + · have he := edgeMass_restrict_le G hw0 R hsmall + have heq : (fun v ↦ w v*m v) = fun v ↦ 2*restrict R w v := by + funext v + by_cases hv : v ∈ R <;> simp [m,restrict,hv,mul_comm] + simp only [L,expectedEdges,expect_singleton,heq,edgeMass_smul] + have hn := mul_nonneg (mul_nonneg hη.le hs.le) (mass_nonneg hw0 R) + nlinarith + · push Not at hsmall + obtain ⟨v,hv,hvlarge⟩ := hsmall + let D := R ∩ neighbors G v + have hDR : D ⊆ R := inter_subset_left + have hDpos : 0 < mass w D := (mul_pos hη hs).trans hvlarge + have hDne : D.Nonempty := by + by_contra hn + have he : D = ∅ := not_nonempty_iff_eq_empty.1 hn + simp [he,mass] at hDpos + obtain ⟨L,hLp,hLb,hLm,hLe⟩ := hlocal R hRA v hv hvlarge + obtain ⟨K,hKp,hKt,hKb,hKm,hKe⟩ := ih (R \ D) (sdiff_ssubset hDR hDne) (sdiff_subset.trans hRA) + let p := mass w D / (2*s) + have hp : 0 < p := div_pos hDpos (by positivity) + have hpη : η/2 < p := by + apply (lt_div_iff₀ (by positivity : 0 < 2*s)).2 + nlinarith only [hvlarge] + have hik : (1/p)*b ≤ B := by + have hi : 1/p ≤ 2/η := by + apply (div_le_div_iff₀ hp hη).2 + linarith + exact (mul_le_mul_of_nonneg_right hi hb).trans hbig + let J := transform p (fun m u ↦ (1/p)*m u) L + have hJp : Positive J := positive_transform hp.le _ hLp.1 + have hJb : BoundedOn J D B := bounded_transform hLb (one_div_nonneg.2 hp.le) hik p + have hpart : mass w (R \ D) + mass w D = mass w R := by + exact sum_sdiff hDR + have hJt : total J = p := by + rw [total_transform,hLp.2,mul_one] + have hJm (u : V) : expect J (fun m ↦ m u) = if u ∈ D then 1 else 0 := by + rw [mean_transform,hLm,mul_one_div_cancel hp.ne',one_mul] + have hJe : expectedEdges G w J ≤ 2*η*s*mass w D := by + rw [expectedEdges_transform] + have he := mul_le_mul_of_nonneg_left hLe (by positivity : 0 ≤ p*(1/p)^2) + have hid : p*(1/p)^2*(η*(mass w D)^2) = 2*η*s*mass w D := by + dsimp [p] + field_simp + exact he.trans_eq hid + refine ⟨J++K,positive_append hJp hKp,?_,bounded_append hJb hKb hDR sdiff_subset,?_,?_⟩ + · change expect (J++K) (fun _ ↦ 1) ≤ _ + rw [expect_append] + change total J + total K ≤ _ + rw [hJt] + dsimp [p] + have hparts : mass w D/(2*s) + mass w (R \ D)/(2*s) = mass w R/(2*s) := by + rw [← add_div] + congr 1 + linarith only [hpart] + linarith only [hKt,hparts] + · intro u + rw [expect_append,hJm,hKm] + by_cases hu : u ∈ D + · have huR := hDR hu + simp [hu,huR] + · by_cases huR : u ∈ R <;> simp [hu,huR] + · change expect (J++K) _ ≤ _ + rw [expect_append] + change expectedEdges G w J + expectedEdges G w K ≤ _ + calc + _ ≤ 2*η*s*mass w D + 2*η*s*mass w (R \ D) := add_le_add hJe hKe + _ = _ := by rw [← mul_add,add_comm (mass w D),hpart] + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Peeling.lean b/lean/OAI/Combinatorics/CliqueFree/Peeling.lean new file mode 100644 index 0000000000000000000000000000000000000000..eef7da52959a5df813204319b76a5b2dfc424e01 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Peeling.lean @@ -0,0 +1,163 @@ +import OAI.Combinatorics.CliqueFree.Projection +import OAI.Combinatorics.CliqueFree.FiniteCoupling + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +open FiniteCoupling +lemma triangle_subgraph_surviving_le {G H : SimpleGraph V} {w : V → ℝ} + (hw : ∀ v, 0 ≤ w v) : + (∑ t : TriangleState G, if H.Adj t.first t.second ∧ H.Adj t.first t.third ∧ H.Adj t.second t.third + then TriangleState.weight w t else 0) ≤ 6 * triangleMass H w := by + classical + let S := {t : TriangleState G // H.Adj t.first t.second ∧ H.Adj t.first t.third ∧ H.Adj t.second t.third} + let f : S → TriangleState H := fun t ↦ ⟨t.val.val, t.property⟩ + have hf : Function.Injective f := by + intro a b hab + apply Subtype.ext + apply Subtype.ext + exact congrArg (fun t : TriangleState H ↦ t.val) hab + calc + _ = ∑ t : S, TriangleState.weight w t.val := by + rw [← sum_filter] + exact Finset.sum_subtype _ (by simp) _ + _ = ∑ t : S, TriangleState.weight w (f t) := rfl + _ ≤ ∑ t : TriangleState H, TriangleState.weight w t := + sum_injective_le f hf _ (fun t ↦ mul_nonneg (mul_nonneg (hw _) (hw _)) (hw _)) + _ = _ := TriangleState.sum_weight _ + +lemma triangle_deletion_bound {G H : SimpleGraph V} {w : V → ℝ} + (hw : ∀ v, 0 ≤ w v) : + 6 * triangleMass G w ≤ 6 * triangleMass H w + + 3 * ∑ e : EdgeState G, w e.src * w e.dst * commonMass G w e.src e.dst * bad (H.Adj e.src e.dst) := by + have ht (t : TriangleState G) : TriangleState.weight w t ≤ + (if H.Adj t.first t.second ∧ H.Adj t.first t.third ∧ H.Adj t.second t.third + then TriangleState.weight w t else 0) + + TriangleState.weight w t * (bad (H.Adj t.first t.second) + + bad (H.Adj t.first t.third) + bad (H.Adj t.second t.third)) := by + have hn : 0 ≤ TriangleState.weight w t := mul_nonneg (mul_nonneg (hw _) (hw _)) (hw _) + by_cases h1 : H.Adj t.first t.second <;> by_cases h2 : H.Adj t.first t.third <;> + by_cases h3 : H.Adj t.second t.third <;> simp [bad,h1,h2,h3] <;> linarith + have hs := sum_le_sum (s := univ) (fun t _ ↦ ht t) + simp only [sum_add_distrib, mul_add] at hs + rw [TriangleState.sum_weight] at hs + have h13 : (∑ t : TriangleState G, TriangleState.weight w t * bad (H.Adj t.first t.third)) = + ∑ t : TriangleState G, TriangleState.weight w t * bad (H.Adj t.first t.second) := + TriangleState.sum_flip w (fun t ↦ bad (H.Adj t.first t.second)) + have h23 : (∑ t : TriangleState G, TriangleState.weight w t * bad (H.Adj t.second t.third)) = + ∑ t : TriangleState G, TriangleState.weight w t * bad (H.Adj t.first t.second) := + TriangleState.sum_rotate w (fun t ↦ bad (H.Adj t.first t.second)) + rw [h13,h23,TriangleState.marginal w (fun u v ↦ bad (H.Adj u v))] at hs + have hsurv := triangle_subgraph_surviving_le (G := G) (H := H) hw + linarith + +/-- Delete exactly one unordered edge. -/ +def eraseEdge (G : SimpleGraph V) (u v : V) : SimpleGraph V where + Adj a b := G.Adj a b ∧ ¬ (a = u ∧ b = v ∨ a = v ∧ b = u) + symm := ⟨by + intro a b h + refine ⟨h.1.symm,?_⟩ + intro hab + apply h.2 + rcases hab with ⟨h1,h2⟩ | ⟨h1,h2⟩ + · exact Or.inr ⟨h2,h1⟩ + · exact Or.inl ⟨h2,h1⟩⟩ + loopless := ⟨fun a h ↦ G.irrefl h.1⟩ + +omit [Fintype V] in +lemma eraseEdge_le (G : SimpleGraph V) (u v : V) : eraseEdge G u v ≤ G := fun _ _ h ↦ h.1 + +lemma edgeMass_eraseEdge {G : SimpleGraph V} (w : V → ℝ) {u v : V} (huv : G.Adj u v) : + edgeMass (eraseEdge G u v) w = edgeMass G w - w u * w v := by + classical + have hn : u ≠ v := huv.ne + have heq (a b : V) : (if G.Adj a b then w a * w b else 0) = + (if (eraseEdge G u v).Adj a b then w a * w b else 0) + + (if a = u ∧ b = v then w u * w v else 0) + + (if a = v ∧ b = u then w v * w u else 0) := by + by_cases h1 : a = u ∧ b = v + · obtain ⟨rfl,rfl⟩ := h1 + simp [eraseEdge,huv,hn,Ne.symm hn] + by_cases h2 : a = v ∧ b = u + · obtain ⟨rfl,rfl⟩ := h2 + simp [eraseEdge,huv.symm,hn,Ne.symm hn] + simp only [eraseEdge, h1, h2, or_self, not_false_eq_true, and_true, ite_false, add_zero] + have he : crossMass G w univ univ = crossMass (eraseEdge G u v) w univ univ + 2 * w u * w v := by + unfold crossMass + simp_rw [heq,sum_add_distrib] + simp [ite_and] + + ring + unfold edgeMass + linarith + +lemma sum_removed_directed {G : SimpleGraph V} {u v : V} (huv : G.Adj u v) + (f : V → V → ℝ) : + (∑ e : EdgeState G, f e.src e.dst * bad ((eraseEdge G u v).Adj e.src e.dst)) = + f u v + f v u := by + classical + have hn : u ≠ v := huv.ne + have heq (a b : V) : (if G.Adj a b then f a b * bad ((eraseEdge G u v).Adj a b) else 0) = + (if a = u ∧ b = v then f u v else 0) + (if a = v ∧ b = u then f v u else 0) := by + by_cases h1 : a = u ∧ b = v + · obtain ⟨rfl,rfl⟩ := h1 + simp [eraseEdge,huv,hn,Ne.symm hn,bad] + by_cases h2 : a = v ∧ b = u + · obtain ⟨rfl,rfl⟩ := h2 + simp [eraseEdge,huv.symm,hn,Ne.symm hn,bad] + by_cases ha : G.Adj a b <;> simp [eraseEdge,h1,h2,bad,ha] + rw [EdgeState.sum_eq (fun a b ↦ f a b * bad ((eraseEdge G u v).Adj a b))] + simp only [neighbors,sum_filter] + simp_rw [heq,sum_add_distrib,ite_and] + simp + +lemma triangleMass_eraseEdge {G : SimpleGraph V} {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + {u v : V} (huv : G.Adj u v) : + triangleMass G w - w u * w v * commonMass G w u v ≤ triangleMass (eraseEdge G u v) w := by + have h := triangle_deletion_bound (G := G) (H := eraseEdge G u v) hw + rw [sum_removed_directed huv (fun a b ↦ w a * w b * commonMass G w a b), commonMass_comm G w v u] at h + nlinarith only [h] + +lemma peeling (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 < w v) + {τ : ℝ} (hτ : 0 < τ) : + ∃ H : SimpleGraph V, H ≤ G ∧ + (∀ u v, H.Adj u v → τ ≤ commonMass H w u v) ∧ + triangleMass G w - τ * edgeMass G w ≤ triangleMass H w := by + classical + let S : Finset (SimpleGraph V) := univ.filter (fun H ↦ H ≤ G) + obtain ⟨H,hHS,hmax⟩ := S.exists_max_image (fun H ↦ triangleMass H w - τ * edgeMass H w) + ⟨G,by simp [S]⟩ + have hHG : H ≤ G := (mem_filter.1 hHS).2 + have hw0 := fun v ↦ (hw v).le + refine ⟨H,hHG,?_,?_⟩ + · intro u v huv + by_contra hn + have hc : commonMass H w u v < τ := lt_of_not_ge hn + have hle := hmax (eraseEdge H u v) (by simp [S]; exact (eraseEdge_le H u v).trans hHG) + rw [edgeMass_eraseEdge w huv] at hle + have ht := triangleMass_eraseEdge hw0 huv + have hprod : 0 < w u * w v := mul_pos (hw u) (hw v) + nlinarith [mul_lt_mul_of_pos_left hc hprod] + · have hle := hmax G (by simp [S]) + have he := edgeMass_nonneg H hw0 + nlinarith + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Projection.lean b/lean/OAI/Combinatorics/CliqueFree/Projection.lean new file mode 100644 index 0000000000000000000000000000000000000000..448a21cfa0c7ce11b2b85598fcf9256f2bb65e8b --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Projection.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.CliqueFree.TriangleState + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +variable {U : Type v} [Fintype U] + +lemma sum_injective_le {I : Type u} {J : Type v} [Fintype I] [Fintype J] + (f : I → J) (hf : Function.Injective f) (g : J → ℝ) (hg : ∀ j, 0 ≤ g j) : + (∑ i, g (f i)) ≤ ∑ j, g j := by + classical + calc + _ = ∑ j ∈ univ.image f, g j := (sum_image (fun _ _ _ _ h ↦ hf h)).symm + _ ≤ _ := sum_le_univ_sum_of_nonneg hg + +/-- A weight-preserving, directed-edge-injective projection. -/ +structure EdgeProjection (H : SimpleGraph U) (G : SimpleGraph V) (π : U → V) : Prop where + map_adj : ∀ a b, H.Adj a b → G.Adj (π a) (π b) + inj : ∀ a b c d, H.Adj a b → H.Adj c d → π a = π c → π b = π d → a = c ∧ b = d + +namespace EdgeProjection +variable {H : SimpleGraph U} {G : SimpleGraph V} {π : U → V} + +def edgeMap (h : EdgeProjection H G π) (e : EdgeState H) : EdgeState G := + ⟨(π e.src, π e.dst), h.map_adj _ _ e.adj⟩ + +omit [Fintype V] [Fintype U] in +lemma edgeMap_injective (h : EdgeProjection H G π) : Function.Injective h.edgeMap := by + intro e f hef + have heq := congrArg Subtype.val hef + have hpair := h.inj e.src e.dst f.src f.dst e.adj f.adj + (congrArg Prod.fst heq) (congrArg Prod.snd heq) + exact Subtype.ext (Prod.ext hpair.1 hpair.2) + +omit [Fintype V] [Fintype U] in +lemma mass_image_le {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) (A : Finset U) : + mass w (A.image π) ≤ mass (w ∘ π) A := by + classical + exact sum_image_le_of_nonneg (fun _ _ ↦ hw _) + +lemma crossMass_edge_sum (H : SimpleGraph U) (w : U → ℝ) (A B : Finset U) : + crossMass H w A B = + ∑ e : EdgeState H, if e.src ∈ A ∧ e.dst ∈ B then w e.src * w e.dst else 0 := by + classical + rw [EdgeState.sum_eq (fun a b ↦ if a ∈ A ∧ b ∈ B then w a * w b else 0)] + have heq : (∑ a, ∑ b ∈ neighbors H a, if a ∈ A ∧ b ∈ B then w a * w b else 0) = + ∑ a, if a ∈ A then (∑ b, if b ∈ B then if H.Adj a b then w a * w b else 0 else 0) else 0 := by + apply sum_congr rfl + intro a _ + by_cases ha : a ∈ A + · simp only [ha, true_and, ↓reduceIte, neighbors, sum_filter] + apply sum_congr rfl + intro b _ + by_cases hb : b ∈ B <;> simp [hb] + · simp [ha] + rw [heq] + simp [crossMass] + +lemma crossMass_le (h : EdgeProjection H G π) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + (A B : Finset U) : + crossMass H (w ∘ π) A B ≤ crossMass G w (A.image π) (B.image π) := by + classical + rw [crossMass_edge_sum, crossMass_edge_sum] + calc + _ ≤ ∑ e : EdgeState H, + if (h.edgeMap e).src ∈ A.image π ∧ (h.edgeMap e).dst ∈ B.image π + then w (h.edgeMap e).src * w (h.edgeMap e).dst else 0 := by + apply sum_le_sum + intro e _ + by_cases he : e.src ∈ A ∧ e.dst ∈ B + · have hi : (h.edgeMap e).src ∈ A.image π ∧ (h.edgeMap e).dst ∈ B.image π := + ⟨mem_image.2 ⟨e.src, he.1, rfl⟩, mem_image.2 ⟨e.dst, he.2, rfl⟩⟩ + simp only [he, hi] + exact le_rfl + · simp only [he, ↓reduceIte] + split_ifs + · exact mul_nonneg (hw _) (hw _) + · exact le_rfl + _ ≤ _ := sum_injective_le h.edgeMap h.edgeMap_injective + (fun e ↦ if e.src ∈ A.image π ∧ e.dst ∈ B.image π then w e.src * w e.dst else 0) + (fun e ↦ by split_ifs; exact mul_nonneg (hw _) (hw _); exact le_rfl) + +lemma crossBound (h : EdgeProjection H G π) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + {C : ℝ} (hC : 0 ≤ C) (hc : CrossBound G w C) : CrossBound H (w ∘ π) C := by + classical + intro x hx A B hA hB + have hAi := mass_image_le (π := π) hw A + have hBi := mass_image_le (π := π) hw B + exact (h.crossMass_le hw A B).trans ((hc x hx _ _ (hAi.trans hA) (hBi.trans hB)).trans + (mul_le_mul_of_nonneg_left (growth_mono hx (mass_nonneg hw _) (mass_nonneg (fun u ↦ hw (π u)) _) hAi) hC)) + +lemma edgeMass_le (h : EdgeProjection H G π) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) : + edgeMass H (w ∘ π) ≤ edgeMass G w := by + classical + have hsum : (∑ e : EdgeState H, w (π e.src) * w (π e.dst)) ≤ + ∑ e : EdgeState G, w e.src * w e.dst := + sum_injective_le h.edgeMap h.edgeMap_injective (fun e ↦ w e.src * w e.dst) + (fun e ↦ mul_nonneg (hw _) (hw _)) + unfold edgeMass + rw [crossMass_edge_sum, crossMass_edge_sum] + simpa only [mem_univ, true_and, ↓reduceIte, Function.comp_apply] using + div_le_div_of_nonneg_right hsum (by norm_num : (0 : ℝ) ≤ 2) + +omit [Fintype V] in +lemma neighbor_injective (h : EdgeProjection H G π) (a : U) : + Set.InjOn π (neighbors H a) := by + intro b hb c hc heq + exact (h.inj a b a c ((mem_neighbors _ _ _).1 hb) ((mem_neighbors _ _ _).1 hc) rfl heq).2 + +lemma neighborhood_image (h : EdgeProjection H G π) (a : U) : + (neighbors H a).image π ⊆ neighbors G (π a) := by + intro b hb + obtain ⟨c, hc, rfl⟩ := mem_image.1 hb + exact (mem_neighbors _ _ _).2 (h.map_adj _ _ ((mem_neighbors _ _ _).1 hc)) + +lemma neighborMass_le (h : EdgeProjection H G π) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) (a : U) : + neighborMass H (w ∘ π) a ≤ neighborMass G w (π a) := by + classical + calc + _ = mass w ((neighbors H a).image π) := (sum_image (h.neighbor_injective a)).symm + _ ≤ _ := mass_mono hw (h.neighborhood_image a) + +end EdgeProjection + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Reach.lean b/lean/OAI/Combinatorics/CliqueFree/Reach.lean new file mode 100644 index 0000000000000000000000000000000000000000..437a1bfe61ce68984fb7e1fb64db887c4560e3a6 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Reach.lean @@ -0,0 +1,222 @@ +import OAI.Combinatorics.CliqueFree.EdgeState + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +/-- Whole-graph sets that contain most of the walk. -/ +noncomputable def enlarge (G : SimpleGraph V) (w : V → ℝ) (t : ℝ) (A : Finset V) : Finset V := + A ∪ univ.filter (fun y ↦ t ≤ mass w (A ∩ neighbors G y)) + +noncomputable def reach (G : SimpleGraph V) (w : V → ℝ) (t : ℝ) (v : V) : ℕ → Finset V + | 0 => neighbors G v + | n+1 => enlarge G w t (reach G w t v n) + +lemma subset_enlarge (G : SimpleGraph V) (w : V → ℝ) (t : ℝ) (A : Finset V) : + A ⊆ enlarge G w t A := subset_union_left + +lemma not_mem_enlarge (G : SimpleGraph V) (w : V → ℝ) (t : ℝ) (A : Finset V) + {y : V} (hy : y ∉ enlarge G w t A) : + y ∉ A ∧ mass w (A ∩ neighbors G y) < t := by + simpa [enlarge, not_or, not_le] using hy + +lemma enlarge_mass (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + {L t : ℝ} (hL : ∀ u, neighborMass G w u ≤ L) (ht : 0 < t) (A : Finset V) : + mass w (enlarge G w t A) ≤ (1 + L / t) * mass w A := by + let B := univ.filter (fun y ↦ t ≤ mass w (A ∩ neighbors G y)) + have hm : t * mass w B ≤ L * mass w A := by + calc + _ = ∑ y ∈ B, w y * t := by rw [← sum_mul]; exact mul_comm _ _ + _ ≤ ∑ y ∈ B, w y * mass w (A ∩ neighbors G y) := by + exact sum_le_sum fun y hy ↦ mul_le_mul_of_nonneg_left (mem_filter.1 hy).2 (hw y) + _ ≤ ∑ y, w y * mass w (A ∩ neighbors G y) := by + exact sum_le_univ_sum_of_nonneg (fun y ↦ mul_nonneg (hw y) (mass_nonneg hw _)) + _ = crossMass G w univ A := (crossMass_factor G w univ A).symm + _ = ∑ y ∈ A, w y * neighborMass G w y := crossMass_all_left G w A + _ ≤ ∑ y ∈ A, w y * L := sum_le_sum fun y _ ↦ mul_le_mul_of_nonneg_left (hL y) (hw y) + _ = L * mass w A := by rw [← sum_mul]; exact mul_comm _ _ + have hB : mass w B ≤ L / t * mass w A := by + calc + _ ≤ L * mass w A / t := (le_div_iff₀ ht).2 (by nlinarith) + _ = _ := by ring + have hu := mass_union_le hw A B + change mass w (A ∪ B) ≤ _ + nlinarith + +lemma reach_mass (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + {L t : ℝ} (hL0 : 0 ≤ L) (hL : ∀ u, neighborMass G w u ≤ L) (ht : 0 < t) + (v : V) (n : ℕ) : mass w (reach G w t v n) ≤ (1 + L / t) ^ n * neighborMass G w v := by + have hfac : 0 ≤ 1 + L / t := by positivity + induction n with + | zero => simp [reach, neighborMass] + | succ n ih => + exact (enlarge_mass G hw hL ht _).trans (by + have h := mul_le_mul_of_nonneg_left ih hfac + simpa only [pow_succ', mul_assoc] using h) + +lemma reach_mass_exp (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + {x : ℝ} (hx : 32 ≤ x) (hL : ∀ v, neighborMass G w v ≤ Real.exp x) + {n : ℕ} (hn : (n : ℝ) ≤ 2 * x) (v : V) : + mass w (reach G w (Numerical.threshold x) v n) ≤ Real.exp (20 * x ^ 2) := by + have hx0 : 0 < x := by linarith + have ht := Numerical.threshold_pos hx0 + have hfac : 0 ≤ 1 + Real.exp x / Numerical.threshold x := by positivity + have hfacn := pow_le_pow_left₀ hfac (Numerical.growth_factor_le hx) n + calc + _ ≤ (1 + Real.exp x / Numerical.threshold x) ^ n * neighborMass G w v := + reach_mass G hw (Real.exp_pos x).le hL ht v n + _ ≤ Real.exp (4 * x) ^ n * Real.exp x := + mul_le_mul hfacn (hL v) (neighborMass_nonneg G hw v) (by positivity) + _ = Real.exp ((n : ℝ) * (4 * x) + x) := by rw [Real.exp_add, Real.exp_nat_mul] + _ ≤ _ := Real.exp_le_exp.2 (by nlinarith) + +lemma growth_le_of_lower {x Y s : ℝ} (hx : 1 ≤ x) (hs : 1 / x ≤ s) : + growth Y s ≤ s * (Y + Real.log x) := by + have hx0 : 0 < x := by linarith + have hs0 : 0 < s := (one_div_pos.2 hx0).trans_le hs + have hrec : 1 / s ≤ x := by + apply (div_le_iff₀ hs0).2 + have h := (div_le_iff₀ hx0).1 hs + nlinarith + have hl := Real.log_le_log (one_div_pos.2 hs0) hrec + have hm : max 0 (Real.log (1 / s)) ≤ Real.log x := max_le (Real.log_nonneg hx) hl + exact mul_le_mul_of_nonneg_left (add_le_add le_rfl hm) hs0.le + +noncomputable def badSet (G : SimpleGraph V) (w : V → ℝ) (S : V → Finset V) + (b : ℝ) (v : V) : Finset V := + (neighbors G v).filter (fun u ↦ b < mass w (S v ∩ neighbors G u)) + +lemma badSet_subset (G : SimpleGraph V) (w : V → ℝ) (S : V → Finset V) + (b : ℝ) (v : V) : badSet G w S b v ⊆ neighbors G v := filter_subset _ _ + +lemma badSet_mass_bound (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ u, 0 ≤ w u) + {C Y : ℝ} (hCross : CrossBound G w C) (hY : 1 ≤ Y) + (S : V → Finset V) (b : ℝ) (v : V) + (hv : neighborMass G w v ≤ Real.exp Y) (hS : mass w (S v) ≤ Real.exp Y) : + b * mass w (badSet G w S b v) ≤ C * growth Y (neighborMass G w v) := by + calc + _ = ∑ u ∈ badSet G w S b v, w u * b := by rw [← sum_mul]; exact mul_comm _ _ + _ ≤ ∑ u ∈ badSet G w S b v, w u * mass w (S v ∩ neighbors G u) := by + exact sum_le_sum fun u hu ↦ mul_le_mul_of_nonneg_left ((mem_filter.1 hu).2.le) (hw u) + _ ≤ ∑ u ∈ neighbors G v, w u * mass w (S v ∩ neighbors G u) := by + exact sum_le_sum_of_subset_of_nonneg (badSet_subset G w S b v) + (fun u _ _ ↦ mul_nonneg (hw u) (mass_nonneg hw _)) + _ = crossMass G w (neighbors G v) (S v) := (crossMass_factor _ _ _ _).symm + _ ≤ _ := hCross Y hY _ _ hv hS + +lemma conditional_bad_bound (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ u, 0 ≤ w u) + {C x k : ℝ} (hC : 0 ≤ C) (hx : 1 ≤ x) (hk : 0 ≤ k) + (hCross : CrossBound G w C) (v : V) (B : Finset V) (hB : B ⊆ neighbors G v) + (hs : 1 / x ≤ neighborMass G w v) (hL : neighborMass G w v ≤ Real.exp x) + (hh : neighborMass G w v / x ≤ triangleAt G w v) + (hb : mass w B ≤ k * neighborMass G w v) : + crossMass G w B (neighbors G v) ≤ + (2 * C * x ^ 2 * (k + x * Real.exp (-x))) * triangleAt G w v := by + have hx0 : 0 < x := by linarith + have hxsv : 1 ≤ x * neighborMass G w v := by + have := (div_le_iff₀ hx0).1 hs + nlinarith + have hhh : neighborMass G w v ≤ x * triangleAt G w v := by + have := (div_le_iff₀ hx0).1 hh + nlinarith + have he : Real.exp (-x) ≤ x * Real.exp (-x) * neighborMass G w v := by + nlinarith [mul_le_mul_of_nonneg_left hxsv (Real.exp_pos (-x)).le] + have hf : 0 ≤ 2 * C * x := by positivity + have hf' : 0 ≤ 2 * C * x * (k + x * Real.exp (-x)) := by positivity + calc + _ ≤ C * growth x (mass w B) := hCross x hx _ _ ((mass_mono hw hB).trans hL) hL + _ ≤ C * (2 * x * (mass w B + Real.exp (-x))) := + mul_le_mul_of_nonneg_left (growth_le_twice hx (mass_nonneg hw B)) hC + _ = (2 * C * x) * (mass w B + Real.exp (-x)) := by ring + _ ≤ (2 * C * x) * (k * neighborMass G w v + + x * Real.exp (-x) * neighborMass G w v) := + mul_le_mul_of_nonneg_left (add_le_add hb he) hf + _ = (2 * C * x * (k + x * Real.exp (-x))) * neighborMass G w v := by ring + _ ≤ (2 * C * x * (k + x * Real.exp (-x))) * (x * triangleAt G w v) := + mul_le_mul_of_nonneg_left hhh hf' + _ = _ := by ring + +lemma reach_bad_mass (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ u, 0 ≤ w u) + {C x : ℝ} (hC : 0 ≤ C) (hCross : CrossBound G w C) (hx : 32 ≤ x) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + {n : ℕ} (hn : (n : ℝ) ≤ 2 * x) {v : V} (hv : (neighbors G v).Nonempty) : + mass w (badSet G w (fun u ↦ reach G w (Numerical.threshold x) u n) (x ^ 8) v) ≤ + (21 * C / x ^ 6) * neighborMass G w v := by + have hx0 : 0 < x := by linarith + have hx1 : 1 ≤ x := by linarith + have hY : 1 ≤ 20 * x ^ 2 := by nlinarith + have hxY : x ≤ 20 * x ^ 2 := by nlinarith + have hs := neighborMass_ge_of_commonMass G hw hc hv + have hS := reach_mass_exp G hw hx hL hn v + have hm := badSet_mass_bound G hw hCross hY + (fun u ↦ reach G w (Numerical.threshold x) u n) (x ^ 8) v + ((hL v).trans (Real.exp_le_exp.2 hxY)) hS + have hg := growth_le_of_lower (Y := 20 * x ^ 2) hx1 hs + have hlog : Real.log x ≤ x ^ 2 := by + have := Real.log_le_self hx0.le + nlinarith + have hgs : growth (20 * x ^ 2) (neighborMass G w v) ≤ + neighborMass G w v * (21 * x ^ 2) := by + apply hg.trans + apply mul_le_mul_of_nonneg_left _ (neighborMass_nonneg G hw v) + linarith + have hm' := hm.trans (mul_le_mul_of_nonneg_left hgs hC) + calc + _ ≤ C * (neighborMass G w v * (21 * x ^ 2)) / x ^ 8 := by + apply (le_div_iff₀ (pow_pos hx0 8)).2 + nlinarith [hm'] + _ = _ := by field_simp [hx0.ne'] + +noncomputable def exceptionalConstant (C : ℝ) : ℝ := 42 * C ^ 2 + 2 * C +noncomputable def entropyConstant (C : ℝ) : ℝ := 10 + exceptionalConstant C +noncomputable def smoothingConstant (C : ℝ) : ℝ := 2 * Real.sqrt (entropyConstant C + 1) + +lemma exceptionalConstant_nonneg {C : ℝ} (hC : 0 ≤ C) : 0 ≤ exceptionalConstant C := by + unfold exceptionalConstant + positivity + +lemma reach_bad_cross (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ u, 0 ≤ w u) + {C x : ℝ} (hC : 0 ≤ C) (hCross : CrossBound G w C) (hx : 32 ≤ x) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + {n : ℕ} (hn : (n : ℝ) ≤ 2 * x) (v : V) : + crossMass G w (badSet G w (fun u ↦ reach G w (Numerical.threshold x) u n) (x ^ 8) v) + (neighbors G v) ≤ (exceptionalConstant C / x ^ 4) * triangleAt G w v := by + have hx0 : 0 < x := by linarith + by_cases hv : (neighbors G v).Nonempty + · have hbad := reach_bad_mass G hw hC hCross hx hL hc hn hv + have hcond := conditional_bad_bound G hw hC (show 1 ≤ x by linarith) + (show 0 ≤ 21 * C / x ^ 6 by positivity) hCross v _ + (badSet_subset G w _ _ v) (neighborMass_ge_of_commonMass G hw hc hv) (hL v) + (by simpa only [one_div, div_eq_mul_inv, one_mul, mul_one, mul_comm] using triangleAt_ge_of_commonMass G hw hc v) + hbad + have hnum : 2 * C * x ^ 2 * (21 * C / x ^ 6 + x * Real.exp (-x)) ≤ + exceptionalConstant C / x ^ 4 := by + calc + _ ≤ 2 * C * x ^ 2 * (21 * C / x ^ 6 + x * (1 / x ^ 7)) := by + apply mul_le_mul_of_nonneg_left _ (by positivity) + exact add_le_add le_rfl (mul_le_mul_of_nonneg_left (Numerical.exp_neg_le_inv_pow_seven hx) hx0.le) + _ = _ := by unfold exceptionalConstant; field_simp [hx0.ne']; ring + exact hcond.trans (mul_le_mul_of_nonneg_right hnum (triangleAt_nonneg G hw v)) + · have he := not_nonempty_iff_eq_empty.1 hv + simp [badSet, he, crossMass, triangleAt] + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/SparseMultipliers.lean b/lean/OAI/Combinatorics/CliqueFree/SparseMultipliers.lean new file mode 100644 index 0000000000000000000000000000000000000000..a559cafb38ab9dae827dcb316f6b6e948b2b7014 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/SparseMultipliers.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.CliqueFree.Packing + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph +open Lottery +universe u +variable {V : Type u} [Fintype V] + +/-- The bound `b_(k+2)(ε)`, indexed by the excess clique size. -/ +noncomputable def multiplierBound (k : ℕ) (ε : ℝ) : ℝ := 2^((k+2)*k) / ε^k + +lemma multiplierBound_pos (k : ℕ) {ε : ℝ} (hε : 0 < ε) : 0 < multiplierBound k ε := by + unfold multiplierBound + positivity + +lemma multiplierBound_ge_one (k : ℕ) {ε : ℝ} (hε : 0 < ε) (hε1 : ε ≤ 1) : + 1 ≤ multiplierBound k ε := by + unfold multiplierBound + apply (le_div_iff₀ (pow_pos hε k)).2 + simpa using (pow_le_one₀ hε.le hε1 : ε^k ≤ 1).trans (one_le_pow₀ (by norm_num : (1:ℝ) ≤ 2)) + +lemma multiplierBound_step (k : ℕ) {ε : ℝ} (hε : 0 < ε) : + multiplierBound (k+1) ε = (8/ε)*multiplierBound k (ε/4) := by + have hn : (k+1+2)*(k+1) = 3+2*k+(k+2)*k := by ring + have hp : (2:ℝ)^((k+1+2)*(k+1)) = 8*4^k*2^((k+2)*k) := by + rw [hn,pow_add,pow_add,pow_mul] + norm_num + unfold multiplierBound + rw [hp,pow_succ,div_pow] + field_simp + +lemma sparse_multipliers_on (k : ℕ) (G : SimpleGraph V) {w : V → ℝ} + (hw : ∀ v, 0 < w v) (A : Finset V) (hfree : G.CliqueFreeOn (↑A) (k+2)) + {ε : ℝ} (hε : 0 < ε) (hεhalf : ε ≤ 1/2) : + ∃ L : Law (V → ℝ), IsProb L ∧ BoundedOn L A (multiplierBound k ε) ∧ + (∀ v, expect L (fun m ↦ m v) = if v ∈ A then 1 else 0) ∧ + expectedEdges G w L ≤ ε * (mass w A)^2 := by + classical + induction k generalizing A ε with + | zero => + let m : V → ℝ := restrict A (fun _ ↦ 1) + let L : Law (V → ℝ) := [(1,m)] + have he : edgeMass G (restrict A w) = 0 := by + rw [edgeMass_restrict] + have hc : crossMass G w A A = 0 := by + unfold crossMass + apply sum_eq_zero + intro u hu + apply sum_eq_zero + intro v hv + have hnot : ¬ G.Adj u v := by + intro hadj + exact ((SimpleGraph.cliqueFreeOn_two G).1 hfree) hu hv hadj.ne hadj + simp [hnot] + rw [hc,zero_div] + refine ⟨L,⟨?_,?_⟩,?_,?_,?_⟩ + · intro z hz + have hz' : z = (1,m) := by simpa [L] using hz + rw [hz']; norm_num + · simp [L,total] + · intro z hz + have hz' : z = (1,m) := by simpa [L] using hz + rw [hz'] + constructor + · intro v + simp only [m,restrict,multiplierBound,Nat.mul_zero,pow_zero,div_one] + split_ifs <;> norm_num + · intro v hv + simp [m,restrict,hv] + · intro v + simp [L,m,restrict] + · have heq : (fun v ↦ w v*m v) = restrict A w := by + funext v + by_cases hv : v ∈ A <;> simp [m,restrict,hv] + simp only [L,expectedEdges,Lottery.expect_singleton,heq,he,mul_zero] + positivity + | succ k ih => + by_cases hA : A = ∅ + · subst A + refine ⟨[(1,0)],⟨?_,by simp [total]⟩,?_,?_,?_⟩ + · intro z hz + have hz' : z = (1,0) := by simpa using hz + rw [hz']; norm_num + · intro z hz + have hz' : z = (1,0) := by simpa using hz + rw [hz'] + exact ⟨fun _ ↦ ⟨le_rfl,(multiplierBound_pos (k+1) hε).le⟩,fun _ _ ↦ rfl⟩ + · intro v; simp + · simp [expectedEdges,edgeMass,crossMass,mass] + have hmass : 0 < mass w A := by + exact sum_pos (fun v _ ↦ hw v) (nonempty_iff_ne_empty.2 hA) + let η := ε/4 + let b := multiplierBound k η + have hη : 0 < η := by dsimp [η]; positivity + have hηhalf : η ≤ 1/2 := by dsimp [η]; linarith + have hb := (multiplierBound_pos k hη).le + have hbig : 2/η*b = multiplierBound (k+1) ε := by + rw [multiplierBound_step k hε] + dsimp [η,b] + congr 1 + ring + have hB : 2 ≤ multiplierBound (k+1) ε := by + rw [← hbig] + have hb1 : 1 ≤ b := multiplierBound_ge_one k hη (by linarith) + have hi : 2 ≤ 2/η := (le_div_iff₀ hη).2 (by linarith) + nlinarith + obtain ⟨L,hLp,hLt,hLb,hLm,hLe⟩ := neighborhood_packing G hw A hmass hη hb hB hbig.le le_rfl + (by + intro R hRA v hv hlarge + apply ih (R ∩ neighbors G v) + · apply SimpleGraph.CliqueFreeOn.subset G _ (SimpleGraph.CliqueFreeOn.of_succ G hfree (hRA hv)) + intro u hu + exact ⟨hRA (mem_inter.1 hu).1,(mem_neighbors G v u).1 (mem_inter.1 hu).2⟩ + · exact hη + · exact hηhalf) + have ht : total L ≤ 1 := by + have he : 1/2+mass w A/(2*mass w A) = 1 := by + field_simp [hmass.ne'] + norm_num + exact hLt.trans_eq he + obtain ⟨K,hKp,hKb,hKm,hKe⟩ := normalize_subprob G w hLp ht (multiplierBound_pos (k+1) hε).le hLb + refine ⟨K,hKp,hKb,fun v ↦ (hKm v).trans (hLm v),?_⟩ + rw [hKe] + have hε0 := mul_nonneg hε.le (sq_nonneg (mass w A)) + dsimp [η] at hLe + nlinarith + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/Splitting.lean b/lean/OAI/Combinatorics/CliqueFree/Splitting.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7e9ee5f5f810375e3c04ebcc93c496aca06120c --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/Splitting.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.CliqueFree.Projection + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +namespace Splitting +variable {G : SimpleGraph V} + +noncomputable def graph (F : EdgeState G → EdgeState G) + (hF : ∀ e, (F e).src = e.src) (good : EdgeState G → Prop) : SimpleGraph (EdgeState G) where + Adj a b := ∃ e, good e ∧ good e.rev ∧ F e = a ∧ F e.rev = b + symm := ⟨by + rintro a b ⟨e, he, hr, ha, hb⟩ + exact ⟨e.rev, hr, by simpa using he, hb, by simpa using ha⟩⟩ + loopless := ⟨by + rintro a ⟨e, he, hr, ha, hb⟩ + have heq : e.src = e.dst := by + calc + e.src = (F e).src := (hF e).symm + _ = (F e.rev).src := congrArg EdgeState.src (ha.trans hb.symm) + _ = e.dst := hF e.rev + exact e.adj.ne heq⟩ + +omit [Fintype V] in +lemma projection (F : EdgeState G → EdgeState G) + (hF : ∀ e, (F e).src = e.src) (good : EdgeState G → Prop) : + EdgeProjection (graph F hF good) G EdgeState.src := by + have endpoints {a b : EdgeState G} {e : EdgeState G} (ha : F e = a) (hb : F e.rev = b) : + a.src = e.src ∧ b.src = e.dst := + ⟨by rw [← ha, hF], by rw [← hb, hF]; rfl⟩ + constructor + · rintro a b ⟨e, _, _, ha, hb⟩ + obtain ⟨hs, ht⟩ := endpoints ha hb + rw [hs, ht] + exact e.adj + · rintro a b c d ⟨e, _, _, ha, hb⟩ ⟨f, _, _, hc, hd⟩ hac hbd + obtain ⟨he1, he2⟩ := endpoints ha hb + obtain ⟨hf1, hf2⟩ := endpoints hc hd + have hef : e = f := Subtype.ext (Prod.ext (he1.symm.trans (hac.trans hf1)) + (he2.symm.trans (hbd.trans hf2))) + subst f + exact ⟨ha.symm.trans hc, hb.symm.trans hd⟩ + +lemma neighborMass_le (w : V → ℝ) (F : EdgeState G → EdgeState G) + (hF : ∀ e, (F e).src = e.src) (good : EdgeState G → Prop) + (K : EdgeState G → EdgeState G → ℝ) (hK0 : ∀ a e, 0 ≤ K a e) + (hK1 : ∀ a, ∑ e, K a e = 1) {L : ℝ} (hL : 0 ≤ L) + (hadm : ∀ e, good e → w e.dst ≤ L * K (F e) e) (a : EdgeState G) : + neighborMass (graph F hF good) (w ∘ EdgeState.src) a ≤ L := by + classical + let H := graph F hF good + let N := ↑(neighbors H a) + have hproj := projection F hF good + let f : N → EdgeState G := fun b ↦ + ⟨(a.src, b.val.src), hproj.map_adj _ _ ((mem_neighbors _ _ _).1 b.property)⟩ + have hf : Function.Injective f := by + intro b c heq + apply Subtype.ext + apply hproj.neighbor_injective a b.property c.property + exact congrArg (fun e : EdgeState G ↦ e.dst) heq + have hle (b : N) : w b.val.src ≤ L * K a (f b) := by + obtain ⟨e, he, _, ha, hb⟩ := (mem_neighbors H a b.val).1 b.property + have hef : f b = e := by + apply Subtype.ext + apply Prod.ext + · exact (congrArg EdgeState.src ha).symm.trans (hF e) + · exact (congrArg EdgeState.src hb).symm.trans (hF e.rev) + rw [hef, ← ha] + have hd : b.val.src = e.dst := (congrArg EdgeState.src hb).symm.trans (hF e.rev) + simpa only [hd] using hadm e he + calc + _ = ∑ b : N, w b.val.src := (sum_coe_sort (neighbors H a) (fun b ↦ w b.src)).symm + _ ≤ ∑ b : N, L * K a (f b) := sum_le_sum (fun b _ ↦ hle b) + _ = L * ∑ b : N, K a (f b) := (mul_sum _ _ _).symm + _ ≤ L * ∑ e, K a e := mul_le_mul_of_nonneg_left (sum_injective_le f hf (K a) (hK0 a)) hL + _ = L := by rw [hK1, mul_one] + +/-- All three corner agreements and all six admissible incidences. -/ +def Survives (F : EdgeState G → EdgeState G) (good : EdgeState G → Prop) + (t : TriangleState G) : Prop := + F t.edge12 = F t.edge13 ∧ + F t.edge12.rev = F t.edge23 ∧ + F t.edge13.rev = F t.edge23.rev ∧ + good t.edge12 ∧ good t.edge12.rev ∧ good t.edge13 ∧ good t.edge13.rev ∧ + good t.edge23 ∧ good t.edge23.rev + +lemma triangleMass_surviving_le {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + (F : EdgeState G → EdgeState G) (hF : ∀ e, (F e).src = e.src) + (good : EdgeState G → Prop) : + (∑ t : TriangleState G, if Survives F good t then TriangleState.weight w t else 0) ≤ + 6 * triangleMass (graph F hF good) (w ∘ EdgeState.src) := by + classical + let H := graph F hF good + let S := {t : TriangleState G // Survives F good t} + let f : S → TriangleState H := fun t ↦ + ⟨(F t.val.edge12, F t.val.edge12.rev, F t.val.edge13.rev), + ⟨t.val.edge12, t.property.2.2.2.1, t.property.2.2.2.2.1, rfl, rfl⟩, + ⟨t.val.edge13, t.property.2.2.2.2.2.1, t.property.2.2.2.2.2.2.1, t.property.1.symm, rfl⟩, + ⟨t.val.edge23, t.property.2.2.2.2.2.2.2.1, t.property.2.2.2.2.2.2.2.2, + t.property.2.1.symm, t.property.2.2.1.symm⟩⟩ + have coords (t : S) : + (f t).first.src = t.val.first ∧ (f t).second.src = t.val.second ∧ + (f t).third.src = t.val.third := by + change (F t.val.edge12).src = _ ∧ (F t.val.edge12.rev).src = _ ∧ (F t.val.edge13.rev).src = _ + simp only [hF] + exact ⟨rfl, rfl, rfl⟩ + have hf : Function.Injective f := by + intro t s hts + apply Subtype.ext + apply Subtype.ext + apply Prod.ext + · exact (coords t).1.symm.trans ((congrArg (fun a : TriangleState H ↦ a.first.src) hts).trans (coords s).1) + · apply Prod.ext + · exact (coords t).2.1.symm.trans ((congrArg (fun a : TriangleState H ↦ a.second.src) hts).trans (coords s).2.1) + · exact (coords t).2.2.symm.trans ((congrArg (fun a : TriangleState H ↦ a.third.src) hts).trans (coords s).2.2) + calc + _ = ∑ t : S, TriangleState.weight w t.val := by + rw [← sum_filter] + exact Finset.sum_subtype _ (by simp) _ + _ = ∑ t : S, TriangleState.weight (w ∘ EdgeState.src) (f t) := by + apply sum_congr rfl + intro t _ + simp only [TriangleState.weight, Function.comp_apply, (coords t).1, (coords t).2.1, (coords t).2.2] + _ ≤ ∑ t : TriangleState H, TriangleState.weight (w ∘ EdgeState.src) t := + sum_injective_le f hf _ (fun t ↦ mul_nonneg (mul_nonneg (hw _) (hw _)) (hw _)) + _ = _ := TriangleState.sum_weight _ + +end Splitting + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/SplittingLoss.lean b/lean/OAI/Combinatorics/CliqueFree/SplittingLoss.lean new file mode 100644 index 0000000000000000000000000000000000000000..4dd136640a6f221d8ba4b08fe22c5b53b184da30 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/SplittingLoss.lean @@ -0,0 +1,227 @@ +import OAI.Combinatorics.CliqueFree.Splitting +import OAI.Combinatorics.CliqueFree.WalkCoupling +import OAI.Combinatorics.CliqueFree.FiniteCoupling + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +namespace Splitting +open FiniteCoupling +variable {G : SimpleGraph V} + +omit [Fintype V] in +lemma bad_survives (F : EdgeState G → EdgeState G) (good : EdgeState G → Prop) + (t : TriangleState G) : + bad (Survives F good t) ≤ bad (F t.edge12 = F t.edge13) + + bad (F t.edge12.rev = F t.edge23) + bad (F t.edge13.rev = F t.edge23.rev) + + bad (good t.edge12) + bad (good t.edge12.rev) + bad (good t.edge13) + + bad (good t.edge13.rev) + bad (good t.edge23) + bad (good t.edge23.rev) := by + unfold Survives + have h1 := bad_and (F t.edge12 = F t.edge13) + (F t.edge12.rev = F t.edge23 ∧ F t.edge13.rev = F t.edge23.rev ∧ + good t.edge12 ∧ good t.edge12.rev ∧ good t.edge13 ∧ good t.edge13.rev ∧ + good t.edge23 ∧ good t.edge23.rev) + have h2 := bad_and (F t.edge12.rev = F t.edge23) + (F t.edge13.rev = F t.edge23.rev ∧ good t.edge12 ∧ good t.edge12.rev ∧ + good t.edge13 ∧ good t.edge13.rev ∧ good t.edge23 ∧ good t.edge23.rev) + have h3 := bad_and (F t.edge13.rev = F t.edge23.rev) + (good t.edge12 ∧ good t.edge12.rev ∧ good t.edge13 ∧ good t.edge13.rev ∧ + good t.edge23 ∧ good t.edge23.rev) + have h4 := bad_and (good t.edge12) + (good t.edge12.rev ∧ good t.edge13 ∧ good t.edge13.rev ∧ good t.edge23 ∧ good t.edge23.rev) + have h5 := bad_and (good t.edge12.rev) + (good t.edge13 ∧ good t.edge13.rev ∧ good t.edge23 ∧ good t.edge23.rev) + have h6 := bad_and (good t.edge13) (good t.edge13.rev ∧ good t.edge23 ∧ good t.edge23.rev) + have h7 := bad_and (good t.edge13.rev) (good t.edge23 ∧ good t.edge23.rev) + have h8 := bad_and (good t.edge23) (good t.edge23.rev) + linarith + +lemma bad_mass_le {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + (F : EdgeState G → EdgeState G) (good : EdgeState G → Prop) : + (∑ t : TriangleState G, TriangleState.weight w t * bad (Survives F good t)) ≤ + 3 * (∑ t, TriangleState.weight w t * bad (F t.edge12 = F t.edge13)) + + 6 * (∑ t, TriangleState.weight w t * bad (good t.edge12)) := by + have h := sum_le_sum (s := univ) fun t _ ↦ + mul_le_mul_of_nonneg_left (bad_survives F good t) + (show 0 ≤ TriangleState.weight w t from + mul_nonneg (mul_nonneg (hw t.first) (hw t.second)) (hw t.third)) + simp only [mul_add, sum_add_distrib] at h + obtain ⟨h1,h2,h3,h4,h5⟩ := TriangleState.sum_edge_permutations w (fun e ↦ bad (good e)) + have hc2 : (∑ t : TriangleState G, TriangleState.weight w t * bad (F t.edge12.rev = F t.edge23)) = + ∑ t : TriangleState G, TriangleState.weight w t * bad (F t.edge12 = F t.edge13) := by + have h := TriangleState.sum_rotate w (fun t ↦ bad (F t.edge12 = F t.edge13)) + convert h using 1 + apply sum_congr rfl + intro t _ + change _ * bad (F t.edge12.rev = F t.edge23) = _ * bad (F t.edge23 = F t.edge12.rev) + rw [eq_comm (a := F t.edge23)] + have hc3 : (∑ t : TriangleState G, TriangleState.weight w t * bad (F t.edge13.rev = F t.edge23.rev)) = + ∑ t : TriangleState G, TriangleState.weight w t * bad (F t.edge12 = F t.edge13) := + (TriangleState.sum_rotate w (fun t ↦ bad (F (TriangleState.rotate t).edge12 = F (TriangleState.rotate t).edge13))).trans + (TriangleState.sum_rotate w (fun t ↦ bad (F t.edge12 = F t.edge13))) + rw [h1,h2,h3,h4,h5,hc2,hc3] at h + linarith + +lemma surviving_mass_eq {w : V → ℝ} + (F : EdgeState G → EdgeState G) (good : EdgeState G → Prop) : + (∑ t : TriangleState G, if Survives F good t then TriangleState.weight w t else 0) = + 6 * triangleMass G w - ∑ t : TriangleState G, TriangleState.weight w t * bad (Survives F good t) := by + rw [← TriangleState.sum_weight, ← sum_sub_distrib] + apply sum_congr rfl + intro t _ + by_cases ht : Survives F good t <;> simp [bad, ht] + +open FiniteEntropy FiniteKernel LocalWalk + +/-- The finite-law aggregate of all corner and incidence losses. -/ +lemma expected_loss_le [Nonempty (EdgeState G)] {w : V → ℝ} (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) + (K : Kernel (EdgeState G)) {q : (EdgeState G → EdgeState G) → ℝ} + (hq : Law q) (hm : ∀ i y, (∑ F, if F i = y then q F else 0) = K i y) + (hp : ∀ i j, (∑ F, if F i ≠ F j then q F else 0) ≤ 2 * tv (K i) (K j)) + (good : (EdgeState G → EdgeState G) → EdgeState G → Prop) + (b : EdgeState G → EdgeState G → Prop) + (hb : ∀ F e, good F e ↔ b e (F e)) : + (∑ F, q F * ∑ t : TriangleState G, TriangleState.weight w t * bad (Survives F (good F) t)) ≤ + normalizer G w * + (6 * (∑ e, law G w e * ∑ z, transition G w e z * tv (K e) (K z)) + + 6 * (∑ e, law G w e * ∑ y, K e y * bad (b e y))) := by + have hcoup (i j : EdgeState G) : (∑ F, q F * bad (F i = F j)) ≤ 2 * tv (K i) (K j) := by + convert hp i j using 1 + apply sum_congr rfl + intro F _ + by_cases h : F i = F j <;> simp [bad, h] + have hadm (e : EdgeState G) : (∑ F, q F * bad (good F e)) = ∑ y, K e y * bad (b e y) := by + simp_rw [hb] + exact marginal_expectation hm e (fun y ↦ bad (b e y)) + have hcorner : (∑ F, q F * ∑ t : TriangleState G, + TriangleState.weight w t * bad (F t.edge12 = F t.edge13)) ≤ + 2 * normalizer G w * (∑ e, law G w e * ∑ z, transition G w e z * tv (K e) (K z)) := by + calc + _ = ∑ t : TriangleState G, TriangleState.weight w t * ∑ F, q F * bad (F t.edge12 = F t.edge13) := by + simp only [mul_sum] + rw [sum_comm] + congr 1 + ext t + apply sum_congr rfl + intro F _ + ring + _ ≤ ∑ t : TriangleState G, TriangleState.weight w t * (2 * tv (K t.edge12) (K t.edge13)) := + sum_le_sum fun t _ ↦ mul_le_mul_of_nonneg_left (hcoup _ _) (TriangleState.weight_pos hw t).le + _ = 2 * ∑ t : TriangleState G, TriangleState.weight w t * tv (K t.edge12) (K t.edge13) := by + rw [mul_sum] + apply sum_congr rfl + intro t _ + ring + _ = _ := by + rw [triangle_pair_sum hw hc (fun e z ↦ tv (K e) (K z))] + ring + have hincidence : (∑ F, q F * ∑ t : TriangleState G, TriangleState.weight w t * bad (good F t.edge12)) = + normalizer G w * ∑ e, law G w e * ∑ y, K e y * bad (b e y) := by + calc + _ = ∑ t : TriangleState G, TriangleState.weight w t * ∑ F, q F * bad (good F t.edge12) := by + simp only [mul_sum] + rw [sum_comm] + congr 1 + ext t + apply sum_congr rfl + intro F _ + ring + _ = _ := by simp_rw [hadm]; exact triangle_edge_sum hw hc (fun e ↦ ∑ y, K e y * bad (b e y)) + have h := sum_le_sum (s := univ) fun F _ ↦ + mul_le_mul_of_nonneg_left (bad_mass_le (fun u ↦ (hw u).le) F (good F)) (hq.1 F) + simp only [mul_add, sum_add_distrib, ← mul_assoc] at h + have hid (a : ℝ) (f : (EdgeState G → EdgeState G) → ℝ) : + (∑ F, q F * a * f F) = a * ∑ F, q F * f F := by + simp only [mul_sum] + apply sum_congr rfl + intro F _ + ring + rw [hid, hid, hincidence] at h + nlinarith + +/-- Splitting from a joint kernel preserving first coordinates, with two averaged losses. -/ +lemma exists_graph [Nonempty (EdgeState G)] {w : V → ℝ} (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) + (K : Kernel (EdgeState G)) (hK : Stochastic K) + (hblock : ∀ e z, e.src ≠ z.src → K e z = 0) + {a D δ : ℝ} + (hD : (∑ e, law G w e * ∑ z, transition G w e z * tv (K e) (K z)) ≤ D) + (hδ : (∑ e, law G w e * ∑ y, + if K y e < w e.dst * Real.exp (-a) then K e y else 0) ≤ δ) : + ∃ H : SimpleGraph (EdgeState G), EdgeProjection H G EdgeState.src ∧ + (∀ z, neighborMass H (w ∘ EdgeState.src) z ≤ Real.exp a) ∧ + (1 - 6 * D - 6 * δ) * triangleMass G w ≤ triangleMass H (w ∘ EdgeState.src) := by + obtain ⟨q,hq,hm,hp⟩ := shared_rejection K hK + have hp' (i j : EdgeState G) : (∑ F, if F i ≠ F j then q F else 0) ≤ 2 * tv (K i) (K j) := + (hp i j).trans (sharp_bound_le (K i) (K j)) + let b : EdgeState G → EdgeState G → Prop := fun e y ↦ w e.dst * Real.exp (-a) ≤ K y e + let good : (EdgeState G → EdgeState G) → EdgeState G → Prop := fun F e ↦ b e (F e) + have hb (e y : EdgeState G) : K e y * bad (b e y) = + if K y e < w e.dst * Real.exp (-a) then K e y else 0 := by + by_cases h : K y e < w e.dst * Real.exp (-a) + · simp [b,bad,h,not_le.2 h] + · simp [b,bad,h,le_of_not_gt h] + have hloss := expected_loss_le hw hc K hq hm hp' good b (fun _ _ ↦ Iff.rfl) + simp_rw [hb] at hloss + have hZ := (normalizer_pos hw hc).le + have hZeq := normalizer_eq G w + have hbound : (∑ F, q F * ∑ t : TriangleState G, TriangleState.weight w t * bad (Survives F (good F) t)) ≤ + normalizer G w * (6 * D + 6 * δ) := + hloss.trans (mul_le_mul_of_nonneg_left (by linarith [hD,hδ]) hZ) + let S : (EdgeState G → EdgeState G) → ℝ := fun F ↦ + ∑ t : TriangleState G, if Survives F (good F) t then TriangleState.weight w t else 0 + have havg : normalizer G w * (1 - 6 * D - 6 * δ) ≤ ∑ F, q F * S F := by + dsimp [S] + simp_rw [surviving_mass_eq] + rw [show (∑ F, q F * (6 * triangleMass G w - + ∑ t : TriangleState G, TriangleState.weight w t * bad (Survives F (good F) t))) = + 6 * triangleMass G w - ∑ F, q F * ∑ t : TriangleState G, + TriangleState.weight w t * bad (Survives F (good F) t) by + simp only [mul_sub, sum_sub_distrib, ← sum_mul, hq.2, one_mul]] + nlinarith + obtain ⟨F,hFq,hFS⟩ := exists_positive_ge hq S havg + have hF (e : EdgeState G) : (F e).src = e.src := by + have hpos := positive_output hq hm hFq e + by_contra hn + have hzero := hblock e (F e) (Ne.symm hn) + linarith + let H := graph F hF (good F) + refine ⟨H,projection F hF (good F),?_,?_⟩ + · intro z + apply neighborMass_le w F hF (good F) K (fun a e ↦ (hK a).1 e) + (fun a ↦ (hK a).2) (Real.exp_pos a).le ?_ z + intro e he + have hh : w e.dst * Real.exp (-a) ≤ K (F e) e := he + have ht := mul_le_mul_of_nonneg_left hh (Real.exp_pos a).le + have hid : Real.exp a * (w e.dst * Real.exp (-a)) = w e.dst := by + calc + _ = w e.dst * (Real.exp a * Real.exp (-a)) := by ring + _ = _ := by rw [← Real.exp_add]; simp + rwa [hid] at ht + · have ht := triangleMass_surviving_le (fun v ↦ (hw v).le) F hF (good F) + change S F ≤ 6 * triangleMass H (w ∘ EdgeState.src) at ht + rw [hZeq] at hFS + nlinarith only [ht, hFS] + +end Splitting + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/TriangleBound.lean b/lean/OAI/Combinatorics/CliqueFree/TriangleBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3187bf9012f04013c7fed818f4ed677e42ef823 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/TriangleBound.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.CliqueFree.VertexSplitting +import OAI.Combinatorics.CliqueFree.Peeling + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph +universe u +variable {V : Type u} [Fintype V] + +omit [Fintype V] in +lemma EdgeProjection.of_le {G H : SimpleGraph V} (hHG : H ≤ G) : EdgeProjection H G id where + map_adj := fun _ _ h ↦ hHG h + inj := fun _ _ _ _ _ _ h1 h2 ↦ ⟨h1,h2⟩ + +lemma neighborMass_bot (w : V → ℝ) (u : V) : neighborMass (⊥ : SimpleGraph V) w u = 0 := by + simp [neighborMass, neighbors, mass] + +lemma triangleMass_bot (w : V → ℝ) : triangleMass (⊥ : SimpleGraph V) w = 0 := by + simp [triangleMass,triangleAt,neighbors] + +lemma splittingConstant_nonneg {C : ℝ} (hC : 1 ≤ C) : 0 ≤ splittingConstant C := by + unfold splittingConstant smoothingConstant entropyConstant exceptionalConstant + positivity + +/-- One reduction step, allowing an arbitrary finite vertex type of copies. -/ +lemma neighborhood_reduction (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ u, 0 < w u) + {C x : ℝ} (hC : 1 ≤ C) (hCross : CrossBound G w C) (hx : 32 ≤ x) + (hε : splittingConstant C * Numerical.lossRatio x ≤ 1) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) : + ∃ (U : Type u) (_ : Fintype U) (J : SimpleGraph U) (π : U → V), + EdgeProjection J G π ∧ (∀ a, neighborMass J (w ∘ π) a ≤ Real.exp (Real.sqrt x)) ∧ + (1-splittingConstant C * Numerical.lossRatio x) * triangleMass G w - edgeMass G w / x ≤ + triangleMass J (w ∘ π) := by + have hx0 : 0 < x := by linarith + have hw0 := fun v ↦ (hw v).le + have hε0 : 0 ≤ splittingConstant C * Numerical.lossRatio x := + mul_nonneg (splittingConstant_nonneg hC) (Numerical.lossRatio_nonneg (by linarith)) + obtain ⟨H,hHG,hc,hpeel⟩ := peeling G hw (one_div_pos.2 hx0) + have hprojH := EdgeProjection.of_le hHG + have hcH : CrossBound H w C := by + simpa only [Function.comp_id] using hprojH.crossBound hw0 (by linarith) hCross + have hLH : ∀ u, neighborMass H w u ≤ Real.exp x := by + intro u + exact (hprojH.neighborMass_le hw0 u).trans (hL u) + by_cases hne : Nonempty (EdgeState H) + · let := hne + obtain ⟨J,hproj,hJ,hT⟩ := weighted_splitting hw hC hcH hx hc hLH + refine ⟨EdgeState H,inferInstance,J,EdgeState.src,?_,hJ,?_⟩ + · exact ⟨fun a b h ↦ hHG (hproj.map_adj a b h),hproj.inj⟩ + · change (1-splittingConstant C * Numerical.lossRatio x) * triangleMass H w ≤ + triangleMass J (w ∘ EdgeState.src) at hT + have hh := mul_le_mul_of_nonneg_left hpeel (sub_nonneg.2 hε) + have hm := div_nonneg (edgeMass_nonneg G hw0) hx0.le + rw [one_div_mul_eq_div] at hh + nlinarith only [hT, hh, mul_nonneg hε0 hm] + · have hbot : H = ⊥ := by + apply SimpleGraph.ext + funext a b + apply propext + simpa only [SimpleGraph.bot_adj, iff_false] using + (fun hab : H.Adj a b ↦ hne ⟨⟨(a,b),hab⟩⟩) + rw [hbot,triangleMass_bot] at hpeel + refine ⟨V,inferInstance,⊥,id,EdgeProjection.of_le bot_le,?_,?_⟩ + · intro a + simp only [Function.comp_id,neighborMass_bot] + exact (Real.exp_pos _).le + · simp only [Function.comp_id,triangleMass_bot] + rw [one_div_mul_eq_div] at hpeel + nlinarith [mul_nonneg hε0 (triangleMass_nonneg G hw0)] + +/-- Uniform triangle bound at the reverse-squaring scale. -/ +lemma triangle_bound_scale {C X : ℝ} (hC : 1 ≤ C) (hX : 32 ≤ X) + (hsmall : splittingConstant C * Numerical.lossRatio X ≤ 1/4) (n : ℕ) : + ∀ {V : Type u} [Fintype V] (G : SimpleGraph V) (w : V → ℝ), + (∀ u, 0 < w u) → CrossBound G w C → + (∀ u, neighborMass G w u ≤ Real.exp (Numerical.scale X n)) → + triangleMass G w ≤ (1+Real.exp X/3) * (2-(1/2:ℝ)^n) * edgeMass G w := by + induction n with + | zero => + intro V _ G w hw hCross hL + have ht := triangleMass_le_of_neighborMass G (fun v ↦ (hw v).le) hL + simp only [Numerical.scale, pow_zero] at ht ⊢ + have he := edgeMass_nonneg G (fun v ↦ (hw v).le) + nlinarith + | succ n ih => + intro V _ G w hw hCross hL + let x := Numerical.scale X (n+1) + let q : ℝ := (1/2:ℝ)^(n+1) + let ε := splittingConstant C * Numerical.lossRatio x + have hx : 32 ≤ x := hX.trans (Numerical.scale_ge (by linarith) _) + have hq0 : 0 ≤ q := by positivity + have hq1 : q ≤ 1 := pow_le_one₀ (by norm_num) (by norm_num) + have hε0 : 0 ≤ ε := mul_nonneg (splittingConstant_nonneg hC) + (Numerical.lossRatio_nonneg (by linarith)) + have hε : ε ≤ q/4 := by + have hh := mul_le_mul_of_nonneg_left (Numerical.lossRatio_scale (by linarith : 16 ≤ X) (n+1)) + (splittingConstant_nonneg hC) + have hh2 := mul_le_mul_of_nonneg_left hsmall hq0 + dsimp [ε,x,q] + nlinarith only [hh,hh2] + obtain ⟨U,inst,J,π,hproj,hJ,hstep⟩ := neighborhood_reduction G hw hC hCross hx + (by linarith : ε ≤ 1) hL + let := inst + have hsqrt : Real.sqrt x = Numerical.scale X n := by + dsimp [x,Numerical.scale] + exact Real.sqrt_sq (by linarith [Numerical.scale_ge (by linarith : 1 ≤ X) n]) + rw [hsqrt] at hJ + have hJcross := hproj.crossBound (fun v ↦ (hw v).le) (by linarith) hCross + have hupper := ih J (w ∘ π) (fun a ↦ hw (π a)) hJcross hJ + have hmass := hproj.edgeMass_le (fun v ↦ (hw v).le) + have hcoeff : 0 ≤ (1+Real.exp X/3)*(2-(1/2:ℝ)^n) := by + apply mul_nonneg (by positivity) + have hp : (1/2:ℝ)^n ≤ 1 := pow_le_one₀ (by norm_num) (by norm_num) + linarith + have hupperG := hupper.trans (mul_le_mul_of_nonneg_left hmass hcoeff) + have hqeq : (1/2:ℝ)^n = 2*q := by dsimp [q]; rw [pow_succ]; ring + rw [hqeq] at hupperG + have hinv : 1/x ≤ q/2 := by + have hi := Numerical.inv_scale (by linarith : 2 ≤ X) (n+1) + have hXi : 1/X ≤ 1/2 := (one_div_le_one_div_of_le (by norm_num) (by linarith)) + have hi2 := mul_le_mul_of_nonneg_left hXi hq0 + dsimp [x,q] at * + linarith + apply Numerical.recurrence_bound (by linarith [Real.exp_pos X] : 1 ≤ 1+Real.exp X/3) + hq0 hq1 hε0 hε (triangleMass_nonneg G (fun v ↦ (hw v).le)) + (edgeMass_nonneg G (fun v ↦ (hw v).le)) hinv + calc + (1-ε)*triangleMass G w - (1/x)*edgeMass G w = + (1-ε)*triangleMass G w - edgeMass G w/x := by ring + _ ≤ triangleMass J (w ∘ π) := hstep + _ ≤ _ := hupperG + +/-- The weighted triangle theorem with a size-independent constant. -/ +theorem weighted_triangles {C : ℝ} (hC : 1 ≤ C) : + ∃ B : ℝ, 0 < B ∧ ∀ {V : Type u} [Fintype V] (G : SimpleGraph V) (w : V → ℝ), + (∀ v, 0 < w v) → CrossBound G w C → triangleMass G w ≤ B * edgeMass G w := by + obtain ⟨X,hX,hsmall⟩ := Numerical.exists_iteration_threshold (splittingConstant C) + refine ⟨2*(1+Real.exp X/3),by positivity,?_⟩ + intro V _ G w hw hCross + obtain ⟨n,hn⟩ := exists_nat_ge (mass w (univ : Finset V)) + have hL : ∀ v, neighborMass G w v ≤ Real.exp (Numerical.scale X n) := by + intro v + calc + _ ≤ mass w univ := mass_mono (fun v ↦ (hw v).le) (subset_univ _) + _ ≤ n := hn + _ ≤ Numerical.scale X n := by + have hh := Numerical.scale_ge_add (by linarith : 2 ≤ X) n + linarith + _ ≤ Real.exp (Numerical.scale X n) := by linarith [Real.add_one_le_exp (Numerical.scale X n)] + have ht := triangle_bound_scale hC hX hsmall n G w hw hCross hL + have he := edgeMass_nonneg G (fun v ↦ (hw v).le) + have hB : 0 ≤ 1+Real.exp X/3 := by positivity + have hq : 0 ≤ (1/2:ℝ)^n := by positivity + nlinarith [mul_nonneg hB hq, mul_nonneg (mul_nonneg hB hq) he] + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/TriangleState.lean b/lean/OAI/Combinatorics/CliqueFree/TriangleState.lean new file mode 100644 index 0000000000000000000000000000000000000000..4424f9096b5ca2891649b9cf7838e5072a593ba4 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/TriangleState.lean @@ -0,0 +1,195 @@ +import OAI.Combinatorics.CliqueFree.EdgeState + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +abbrev TriangleState (G : SimpleGraph V) := + {t : V × V × V // G.Adj t.1 t.2.1 ∧ G.Adj t.1 t.2.2 ∧ G.Adj t.2.1 t.2.2} + +noncomputable instance triangleStateFintype (G : SimpleGraph V) : Fintype (TriangleState G) := + Subtype.fintype _ + +namespace TriangleState +variable {G : SimpleGraph V} +def first (t : TriangleState G) : V := t.val.1 +def second (t : TriangleState G) : V := t.val.2.1 +def third (t : TriangleState G) : V := t.val.2.2 + +omit [Fintype V] in +@[simp] lemma adj12 (t : TriangleState G) : G.Adj t.first t.second := t.property.1 +omit [Fintype V] in +@[simp] lemma adj13 (t : TriangleState G) : G.Adj t.first t.third := t.property.2.1 +omit [Fintype V] in +@[simp] lemma adj23 (t : TriangleState G) : G.Adj t.second t.third := t.property.2.2 + +def edge12 (t : TriangleState G) : EdgeState G := ⟨(t.first, t.second), t.adj12⟩ +def edge13 (t : TriangleState G) : EdgeState G := ⟨(t.first, t.third), t.adj13⟩ +def edge23 (t : TriangleState G) : EdgeState G := ⟨(t.second, t.third), t.adj23⟩ + +def swap (t : TriangleState G) : TriangleState G := + ⟨(t.second, t.first, t.third), t.adj12.symm, t.adj23, t.adj13⟩ +def rotate (t : TriangleState G) : TriangleState G := + ⟨(t.second, t.third, t.first), t.adj23, t.adj12.symm, t.adj13.symm⟩ + +def swapEquiv : TriangleState G ≃ TriangleState G where + toFun := swap + invFun := swap + left_inv t := by cases t; rfl + right_inv t := by cases t; rfl + +def rotateEquiv : TriangleState G ≃ TriangleState G where + toFun := rotate + invFun := rotate ∘ rotate + left_inv t := by cases t; rfl + right_inv t := by cases t; rfl + +noncomputable def weight (w : V → ℝ) (t : TriangleState G) : ℝ := + w t.first * w t.second * w t.third + +omit [Fintype V] in +lemma weight_pos {w : V → ℝ} (hw : ∀ u, 0 < w u) (t : TriangleState G) : + 0 < weight w t := mul_pos (mul_pos (hw _) (hw _)) (hw _) + +omit [Fintype V] in +@[simp] lemma weight_swap (w : V → ℝ) (t : TriangleState G) : + weight w (swap t) = weight w t := by unfold weight swap first second third; ring +omit [Fintype V] in +@[simp] lemma weight_rotate (w : V → ℝ) (t : TriangleState G) : + weight w (rotate t) = weight w t := by unfold weight rotate first second third; ring + +lemma sum_rotate (w : V → ℝ) (f : TriangleState G → ℝ) : + (∑ t, weight w t * f (rotate t)) = ∑ t, weight w t * f t := by + simpa only [rotateEquiv, Equiv.coe_fn_mk, weight_rotate] using rotateEquiv.sum_comp (fun t ↦ weight w t * f t) + +lemma sum_swap (w : V → ℝ) (f : TriangleState G → ℝ) : + (∑ t, weight w t * f (swap t)) = ∑ t, weight w t * f t := by + simpa only [swapEquiv, Equiv.coe_fn_mk, weight_swap] using swapEquiv.sum_comp (fun t ↦ weight w t * f t) + +lemma sum_eq (f : V → V → V → ℝ) : + (∑ t : TriangleState G, f t.first t.second t.third) = + ∑ u, ∑ v ∈ neighbors G u, ∑ z ∈ neighbors G u, + if G.Adj v z then f u v z else 0 := by + classical + change (∑ t : {t : V × V × V // _}, f t.val.1 t.val.2.1 t.val.2.2) = _ + rw [← Finset.sum_subtype (univ.filter fun t : V × V × V ↦ + G.Adj t.1 t.2.1 ∧ G.Adj t.1 t.2.2 ∧ G.Adj t.2.1 t.2.2) + (by simp) (fun t : V × V × V ↦ f t.1 t.2.1 t.2.2)] + simp only [sum_filter, Fintype.sum_prod_type, neighbors] + apply sum_congr rfl + intro u _ + apply sum_congr rfl + intro v _ + by_cases huv : G.Adj u v + · simp only [huv, true_and, ↓reduceIte] + apply sum_congr rfl + intro z _ + by_cases huz : G.Adj u z <;> simp [huz] + · simp [huv] + +lemma sum_weight (w : V → ℝ) : (∑ t : TriangleState G, weight w t) = 6 * triangleMass G w := by + simp only [weight] + rw [sum_eq (fun u v z ↦ w u * w v * w z), triangleMass_eq_sum] + simp only [triangleAt, commonMass_eq_sum, mul_sum, mul_ite, mul_zero, mul_assoc] + +lemma marginal (w : V → ℝ) (f : V → V → ℝ) : + (∑ t : TriangleState G, weight w t * f t.first t.second) = + ∑ e : EdgeState G, w e.src * w e.dst * commonMass G w e.src e.dst * f e.src e.dst := by + simp only [weight] + rw [sum_eq (fun u v z ↦ w u * w v * w z * f u v), EdgeState.sum_eq (fun u v ↦ w u * w v * commonMass G w u v * f u v)] + apply sum_congr rfl + intro u _ + apply sum_congr rfl + intro v _ + rw [commonMass_eq_sum] + simp only [mul_sum, sum_mul, mul_ite, ite_mul, mul_zero, zero_mul] + +end TriangleState + +namespace TriangleState +variable {G : SimpleGraph V} + +def flip (t : TriangleState G) : TriangleState G := + ⟨(t.first, t.third, t.second), t.adj13, t.adj12, t.adj23.symm⟩ + +def flipEquiv : TriangleState G ≃ TriangleState G where + toFun := flip + invFun := flip + left_inv t := by cases t; rfl + right_inv t := by cases t; rfl + +omit [Fintype V] in +@[simp] lemma weight_flip (w : V → ℝ) (t : TriangleState G) : + weight w (flip t) = weight w t := by unfold weight flip first second third; ring + +lemma sum_flip (w : V → ℝ) (f : TriangleState G → ℝ) : + (∑ t, weight w t * f (flip t)) = ∑ t, weight w t * f t := by + simpa only [flipEquiv, Equiv.coe_fn_mk, weight_flip] using + flipEquiv.sum_comp (fun t ↦ weight w t * f t) + +abbrev CornerPairs (G : SimpleGraph V) := + {p : EdgeState G × EdgeState G // p.1.src = p.2.src ∧ G.Adj p.1.dst p.2.dst} + +def cornerEquiv : TriangleState G ≃ CornerPairs G where + toFun t := ⟨(t.edge12, t.edge13), rfl, t.adj23⟩ + invFun p := ⟨(p.val.1.src, p.val.1.dst, p.val.2.dst), p.val.1.adj, + by rw [p.property.1]; exact p.val.2.adj, p.property.2⟩ + left_inv t := by cases t; rfl + right_inv p := by + apply Subtype.ext + apply Prod.ext + · rfl + · apply Subtype.ext + exact Prod.ext p.property.1 rfl + +lemma corner_sum (w : V → ℝ) (f : EdgeState G → EdgeState G → ℝ) : + (∑ t : TriangleState G, weight w t * f t.edge12 t.edge13) = + ∑ e : EdgeState G, ∑ z : EdgeState G, + if e.src = z.src ∧ G.Adj e.dst z.dst + then w e.src * w e.dst * w z.dst * f e z else 0 := by + classical + calc + _ = ∑ p : CornerPairs G, w p.val.1.src * w p.val.1.dst * w p.val.2.dst * f p.val.1 p.val.2 := + (cornerEquiv.sum_comp (fun p ↦ w p.val.1.src * w p.val.1.dst * w p.val.2.dst * f p.val.1 p.val.2)) + _ = ∑ p : EdgeState G × EdgeState G, + if p.1.src = p.2.src ∧ G.Adj p.1.dst p.2.dst + then w p.1.src * w p.1.dst * w p.2.dst * f p.1 p.2 else 0 := by + rw [← Finset.sum_subtype (univ.filter fun p : EdgeState G × EdgeState G ↦ + p.1.src = p.2.src ∧ G.Adj p.1.dst p.2.dst) (by simp) + (fun p ↦ w p.1.src * w p.1.dst * w p.2.dst * f p.1 p.2), sum_filter] + _ = _ := Fintype.sum_prod_type _ + +end TriangleState + +namespace TriangleState +variable {G : SimpleGraph V} +lemma sum_edge_permutations (w : V → ℝ) (g : EdgeState G → ℝ) : + (∑ t, weight w t * g t.edge12.rev) = (∑ t, weight w t * g t.edge12) ∧ + (∑ t, weight w t * g t.edge13) = (∑ t, weight w t * g t.edge12) ∧ + (∑ t, weight w t * g t.edge13.rev) = (∑ t, weight w t * g t.edge12) ∧ + (∑ t, weight w t * g t.edge23) = (∑ t, weight w t * g t.edge12) ∧ + (∑ t, weight w t * g t.edge23.rev) = (∑ t, weight w t * g t.edge12) := by + refine ⟨sum_swap w (fun t ↦ g t.edge12), sum_flip w (fun t ↦ g t.edge12), ?_, + sum_rotate w (fun t ↦ g t.edge12), ?_⟩ + · exact (sum_rotate w (fun t ↦ g (rotate t).edge12)).trans (sum_rotate w (fun t ↦ g t.edge12)) + · exact (sum_rotate w (fun t ↦ g (swap t).edge12)).trans (sum_swap w (fun t ↦ g t.edge12)) +end TriangleState + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/VariationalCross.lean b/lean/OAI/Combinatorics/CliqueFree/VariationalCross.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c7a9f0cd3b30d6ce6593486cadfd00d8f077342 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/VariationalCross.lean @@ -0,0 +1,174 @@ +import OAI.Combinatorics.CliqueFree.Optimizer +import OAI.Combinatorics.CliqueFree.SparseMultipliers + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph +open Lottery +universe u +variable {V : Type u} [Fintype V] + +lemma edgeForm_smul_left (G : SimpleGraph V) (a b : V → ℝ) (t : ℝ) : + edgeForm G (fun v ↦ t*a v) b = t*edgeForm G a b := by + unfold edgeForm + simp only [mul_sum,mul_ite,mul_zero] + apply sum_congr rfl + intro u _ + apply sum_congr rfl + intro v _ + split_ifs <;> ring + +lemma edgeForm_smul_right (G : SimpleGraph V) (a b : V → ℝ) (t : ℝ) : + edgeForm G a (fun v ↦ t*b v) = t*edgeForm G a b := by + rw [edgeForm_symm,edgeForm_smul_left,edgeForm_symm G b a] + +lemma edgeMass_lin_sub (G : SimpleGraph V) (a b : V → ℝ) (k : ℝ) : + edgeMass G (fun v ↦ k*a v-b v) = + k^2*edgeMass G a + edgeMass G b - k*edgeForm G a b := by + have he : (fun v ↦ k*a v-b v) = (fun v ↦ k*a v)+(fun v ↦ (-1)*b v) := by + ext v; simp; ring + rw [he,edgeMass_add,edgeMass_smul,edgeMass_smul,edgeForm_smul_left,edgeForm_smul_right] + ring + +lemma edgeForm_restrict (G : SimpleGraph V) (w : V → ℝ) (S D : Finset V) : + edgeForm G (restrict S w) (restrict D w) = crossMass G w S D := by + classical + unfold edgeForm crossMass restrict + calc + _ = ∑ u, if u ∈ S then ∑ v, if v ∈ D then (if G.Adj u v then w u*w v else 0) else 0 else 0 := by + apply sum_congr rfl + intro u _ + by_cases hu : u ∈ S + · simp only [hu,ite_true] + apply sum_congr rfl + intro v _ + by_cases hv : v ∈ D <;> simp [hv] + · simp [hu] + _ = _ := by + rw [← sum_filter] + simp only [filter_mem_eq_inter,univ_inter] + apply sum_congr rfl + intro u hu + rw [← sum_filter] + simp + +lemma expected_weight (w : V → ℝ) (L : Law (V → ℝ)) (S : Finset V) + (hmean : ∀ v, expect L (fun m ↦ m v) = if v ∈ S then 1 else 0) : + expect L (fun m ↦ ∑ v, w v*m v) = mass w S := by + classical + rw [expect_sum] + simp_rw [Lottery.expect_mul,hmean,mul_ite,mul_one,mul_zero] + rw [← sum_filter] + simp [mass] + +lemma expected_edgeForm (G : SimpleGraph V) (w : V → ℝ) (L : Law (V → ℝ)) (S D : Finset V) + (hmean : ∀ v, expect L (fun m ↦ m v) = if v ∈ S then 1 else 0) : + expect L (fun m ↦ edgeForm G (fun v ↦ w v*m v) (restrict D w)) = crossMass G w S D := by + classical + rw [← edgeForm_restrict] + simp only [edgeForm_neighbor] + rw [expect_sum] + apply sum_congr rfl + intro u _ + have hf : (fun m : V → ℝ ↦ w u*m u*neighborMass G (restrict D w) u) = + (fun m ↦ (w u*neighborMass G (restrict D w) u)*m u) := by ext m; ring + rw [hf,Lottery.expect_mul,hmean] + by_cases hu : u ∈ S <;> simp [restrict,hu] + +lemma vertex_divergence_upper {w y L : ℝ} (hw : 0 < w) (hy : 0 ≤ y) (hL : y ≤ L) : + (w*(1+y))*Real.log ((w*(1+y))/w) - w*(1+y) + w ≤ w*y*Real.log (1+L) := by + have hy1 : 0 < 1+y := by linarith + have hL1 : 0 < 1+L := hy1.trans_le (by linarith) + have hlog := Real.log_le_sub_one_of_pos hy1 + have hmono := Real.log_le_log hy1 (by linarith : 1+y ≤ 1+L) + have hlo : w*y*Real.log (1+y) ≤ w*y*Real.log (1+L) := + mul_le_mul_of_nonneg_left hmono (mul_nonneg hw.le hy) + have hcancel : w*(1+y)/w = 1+y := by field_simp + rw [hcancel] + nlinarith [mul_le_mul_of_nonneg_left hlog hw.le] + +lemma variational_cross_lottery (G : SimpleGraph V) {w : V → ℝ} (hw : IsOptimizer G w) + (S D : Finset V) (hSD : Disjoint S D) (L : Law (V → ℝ)) (hp : IsProb L) + {b k ε : ℝ} (hk : 0 ≤ k) (hb : BoundedOn L S b) + (hm : ∀ v, expect L (fun m ↦ m v) = if v ∈ S then 1 else 0) + (he : expectedEdges G w L ≤ ε*(mass w S)^2) : + k*crossMass G w S D ≤ k^2*ε*(mass w S)^2 + (mass w D)^2/2 + mass w D + + k*Real.log (1+k*b)*mass w S := by + classical + have hwpos := fun v ↦ (optimizer_stationary hw v).1 + have hw0 := fun v ↦ (hwpos v).le + let cost (m : V → ℝ) : ℝ := + k*Real.log (1+k*b)*(∑ v, w v*m v) + mass w D + + (k^2*edgeMass G (fun v ↦ w v*m v) + edgeMass G (restrict D w) - + k*edgeForm G (fun v ↦ w v*m v) (restrict D w)) + have hcost (z : ℝ × (V → ℝ)) (hz : z ∈ L) : 0 ≤ cost z.2 := by + let m := z.2 + have hm0 := fun v ↦ (hb z hz).1 v |>.1 + have hmb := fun v ↦ (hb z hz).1 v |>.2 + have hmD (v : V) (hv : v ∈ D) : m v = 0 := + (hb z hz).2 v (disjoint_left.1 hSD · hv) + let q : V → ℝ := fun v ↦ if v ∈ D then 0 else w v*(1+k*m v) + have hq (v : V) : 0 ≤ q v := by + dsimp [q] + split_ifs + · exact le_rfl + · exact mul_nonneg (hw0 v) (by nlinarith [mul_nonneg hk (hm0 v)]) + obtain ⟨hdiv,heq⟩ := optimizer_divergence hw q hq + rw [heq] at hdiv + have hve (v : V) : q v*Real.log (q v/w v)-q v+w v ≤ + k*Real.log (1+k*b)*(w v*m v) + if v ∈ D then w v else 0 := by + by_cases hv : v ∈ D + · simp [q,hv,hmD v hv] + · have hh := vertex_divergence_upper (hwpos v) (mul_nonneg hk (hm0 v)) + (mul_le_mul_of_nonneg_left (hmb v) hk) + dsimp [q] + rw [ite_eq_right hv,ite_eq_right hv] + nlinarith only [hh] + have hD : (∑ v, if v ∈ D then w v else 0) = mass w D := by + rw [← sum_filter]; simp [mass] + have hvs : (∑ v, (q v*Real.log (q v/w v)-q v+w v)) ≤ + k*Real.log (1+k*b)*(∑ v, w v*m v) + mass w D := by + calc + _ ≤ ∑ v, (k*Real.log (1+k*b)*(w v*m v) + if v ∈ D then w v else 0) := + sum_le_sum fun v _ ↦ hve v + _ = _ := by rw [sum_add_distrib,← mul_sum,hD] + have hqsub : q-w = fun v ↦ k*(w v*m v)-restrict D w v := by + ext v + by_cases hv : v ∈ D <;> simp [q,restrict,hv,hmD v,Pi.sub_apply] + ring + rw [hqsub,edgeMass_lin_sub] at hdiv + dsimp [cost,m] + linarith only [hdiv,hvs] + have havg : 0 ≤ expect L cost := by + have hh := expect_mono hp.1 (f := fun _ ↦ 0) (g := cost) (fun z hz ↦ hcost z hz) + simpa [Lottery.expect_const] using hh + have hec : expect L cost = + k*Real.log (1+k*b)*mass w S + mass w D + + (k^2*expectedEdges G w L + edgeMass G (restrict D w) - k*crossMass G w S D) := by + have hsub (a b : (V → ℝ) → ℝ) : expect L (fun m ↦ a m-b m) = expect L a-expect L b := by + have hf : (fun m ↦ a m-b m) = (fun m ↦ a m+(-1)*b m) := by ext m; ring + rw [hf,expect_add,Lottery.expect_mul]; ring + dsimp [cost] + rw [expect_add,expect_add,hsub,expect_add,Lottery.expect_mul,expected_weight w L S hm, + Lottery.expect_const,hp.2,mul_one,Lottery.expect_mul,Lottery.expect_const,hp.2,mul_one,Lottery.expect_mul, + expected_edgeForm G w L S D hm] + rfl + rw [hec] at havg + have hDedge : edgeMass G (restrict D w) ≤ (mass w D)^2/2 := by + rw [edgeMass_restrict] + exact div_le_div_of_nonneg_right (by simpa [sq] using crossMass_le_product G hw0 D D) (by norm_num) + have hmult := mul_le_mul_of_nonneg_left he (sq_nonneg k) + nlinarith only [havg,hDedge,hmult] + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/VertexSplitting.lean b/lean/OAI/Combinatorics/CliqueFree/VertexSplitting.lean new file mode 100644 index 0000000000000000000000000000000000000000..977d37895a89cf944590e54f331fcad389c68d33 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/VertexSplitting.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.CliqueFree.SplittingLoss + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +noncomputable def splittingConstant (C : ℝ) : ℝ := + 6 * (smoothingConstant C + entropyConstant C + 1) + +lemma splitting_error_le {C x : ℝ} (hC : 1 ≤ C) (hx : 32 ≤ x) : + 6 * (smoothingConstant C * Real.sqrt (Real.log x / x)) + + 6 * ((entropyConstant C + 1) * Real.log x / (Real.sqrt x + Real.log x)) ≤ + splittingConstant C * (Real.log x / Real.sqrt x) := by + have hx0 : 0 < x := by linarith + have hl := (Numerical.log_bounds hx).1 + have hl0 : 0 ≤ Real.log x := by linarith + have hs : 0 < Real.sqrt x := Real.sqrt_pos.2 hx0 + have hA : 0 ≤ entropyConstant C + 1 := by + unfold entropyConstant exceptionalConstant + positivity + have hB : 0 ≤ smoothingConstant C := by unfold smoothingConstant; positivity + have hslog : Real.sqrt (Real.log x) ≤ Real.log x := by + have hh := Real.sq_sqrt hl0 + have hn := Real.sqrt_nonneg (Real.log x) + nlinarith + have h1 : Real.sqrt (Real.log x / x) ≤ Real.log x / Real.sqrt x := by + rw [Real.sqrt_div hl0] + exact div_le_div_of_nonneg_right hslog hs.le + have h2 : (entropyConstant C + 1) * Real.log x / (Real.sqrt x + Real.log x) ≤ + (entropyConstant C + 1) * (Real.log x / Real.sqrt x) := by + rw [← mul_div_assoc] + exact div_le_div_of_nonneg_left (mul_nonneg hA hl0) hs (by linarith) + unfold splittingConstant + nlinarith [mul_le_mul_of_nonneg_left h1 hB] + +/-- Weighted vertex splitting with explicit constants. -/ +lemma weighted_splitting {G : SimpleGraph V} [Nonempty (EdgeState G)] {w : V → ℝ} + (hw : ∀ u, 0 < w u) {C x : ℝ} (hC : 1 ≤ C) (hCross : CrossBound G w C) + (hx : 32 ≤ x) (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) : + ∃ H : SimpleGraph (EdgeState G), EdgeProjection H G EdgeState.src ∧ + (∀ z, neighborMass H (w ∘ EdgeState.src) z ≤ Real.exp (Real.sqrt x)) ∧ + (1 - splittingConstant C * (Real.log x / Real.sqrt x)) * triangleMass G w ≤ + triangleMass H (w ∘ EdgeState.src) := by + open FiniteEntropy FiniteKernel LocalWalk in + have hx0 : 0 < x := by linarith + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx0).trans_le (hc u v huv) + obtain ⟨j,_,hH,hD⟩ := LocalWalk.exists_smooth_index hw hC hCross hx hc hL + let K := FiniteKernel.smoothed (LocalWalk.transition G w) j + have hP := LocalWalk.transition_stochastic hw hc0 + have hK := FiniteKernel.stochastic_smoothed hP j + have hrev := FiniteKernel.reversible_smoothed (LocalWalk.transition_reversible hw hc0) j + have htail := FiniteKernel.reversed_entropy_tail (LocalWalk.law_isProb hw hc0) + (fun e : EdgeState G ↦ hw e.dst) hK hrev hx0 (LocalWalk.smoothed_density hw hx0 hc j) + (a := Real.sqrt x) + have hden : 0 < Real.sqrt x + Real.log x := by + have hs := Real.sqrt_pos.2 hx0 + linarith [(Numerical.log_bounds hx).1] + have hδ : (∑ e, LocalWalk.law G w e * ∑ y, + if K y e < w e.dst * Real.exp (-Real.sqrt x) then K e y else 0) ≤ + (entropyConstant C + 1) * Real.log x / (Real.sqrt x + Real.log x) := by + apply (le_div_iff₀ hden).2 + dsimp [K] + change FiniteKernel.avgEntropy (LocalWalk.law G w) (fun e ↦ w e.dst) + (FiniteKernel.smoothed (LocalWalk.transition G w) j) ≤ entropyConstant C * Real.log x at hH + nlinarith only [htail,hH] + obtain ⟨H,hproj,hneigh,htri⟩ := Splitting.exists_graph hw hc0 K hK + (LocalWalk.smoothed_fixed_src j) hD hδ + refine ⟨H,hproj,hneigh,?_⟩ + have hn := triangleMass_nonneg G (fun u ↦ (hw u).le) + have he := splitting_error_le hC hx + nlinarith [mul_le_mul_of_nonneg_right he hn] + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/WalkCoupling.lean b/lean/OAI/Combinatorics/CliqueFree/WalkCoupling.lean new file mode 100644 index 0000000000000000000000000000000000000000..32f93003e65da245d25e49969f2440607676cf8f --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/WalkCoupling.lean @@ -0,0 +1,57 @@ +import OAI.Combinatorics.CliqueFree.WalkEntropy +import OAI.Combinatorics.CliqueFree.TriangleState + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +namespace LocalWalk +open FiniteEntropy FiniteKernel +variable {G : SimpleGraph V} {w : V → ℝ} +lemma triangle_pair_sum [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) + (f : EdgeState G → EdgeState G → ℝ) : + (∑ t : TriangleState G, TriangleState.weight w t * f t.edge12 t.edge13) = + normalizer G w * ∑ e, law G w e * ∑ z, transition G w e z * f e z := by + rw [TriangleState.corner_sum] + simp only [mul_sum] + apply sum_congr rfl + intro e _ + apply sum_congr rfl + intro z _ + have he := (hc _ _ e.adj).ne' + have hZ := (normalizer_pos hw hc).ne' + by_cases hs : e.src = z.src + · by_cases ha : G.Adj e.dst z.dst + · simp only [hs, ha, true_and, ↓reduceIte, transition, law] + rw [hs] at he + field_simp + · simp [hs, ha, transition] + · simp [hs, transition] + +lemma triangle_edge_sum [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) (f : EdgeState G → ℝ) : + (∑ t : TriangleState G, TriangleState.weight w t * f t.edge12) = + normalizer G w * ∑ e, law G w e * f e := by + rw [triangle_pair_sum hw hc (fun e _ ↦ f e)] + simp only [← sum_mul, (transition_stochastic hw hc _).2, one_mul] +end LocalWalk + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/WalkEntropy.lean b/lean/OAI/Combinatorics/CliqueFree/WalkEntropy.lean new file mode 100644 index 0000000000000000000000000000000000000000..68a59237ad331eef29b94686d865f99c7102f103 --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/WalkEntropy.lean @@ -0,0 +1,386 @@ +import OAI.Combinatorics.CliqueFree.LocalWalk + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +attribute [local instance 10000] edgeStateDecEq + +namespace LocalWalk +open FiniteEntropy FiniteKernel +variable {G : SimpleGraph V} {w : V → ℝ} + +noncomputable def liftSet (u : V) (A : Finset V) : Finset (EdgeState G) := + univ.filter (fun e ↦ e.src = u ∧ e.dst ∈ A) + +@[simp] lemma mem_liftSet (u : V) (A : Finset V) (e : EdgeState G) : + e ∈ liftSet (G := G) u A ↔ e.src = u ∧ e.dst ∈ A := by simp [liftSet] + +lemma liftSet_subset_fiber (u : V) (A : Finset V) : liftSet (G := G) u A ⊆ fiber G u := by + intro e he + exact (mem_fiber G e u).2 ((mem_liftSet u A e).1 he).1 + +lemma sum_liftSet (u : V) (A : Finset V) (f : V → ℝ) : + (∑ e ∈ liftSet (G := G) u A, f e.dst) = ∑ v ∈ A ∩ neighbors G u, f v := by + rw [liftSet, sum_filter] + have he : (∑ e : EdgeState G, if e.src = u ∧ e.dst ∈ A then f e.dst else 0) = + ∑ e : EdgeState G, if e.src = u then (if e.dst ∈ A then f e.dst else 0) else 0 := by + apply sum_congr rfl + intro e _ + by_cases hs : e.src = u <;> by_cases hd : e.dst ∈ A <;> simp [hs, hd] + rw [he, EdgeState.sum_fiber u (fun v ↦ if v ∈ A then f v else 0), ← sum_filter] + congr 1 + ext v + simp [and_comm] + +lemma lazy_neighbor_density (hw : ∀ u, 0 < w u) {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + (e f : EdgeState G) (h : e.dst ≠ f.dst) : + lazy (transition G w) e f ≤ if G.Adj e.dst f.dst then x * w f.dst else 0 := by + have hef : e ≠ f := fun he ↦ h (congrArg EdgeState.dst he) + simp only [lazy, hef, ite_false, zero_add] + have hp := transition_density hw hx hc e f + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx).trans_le (hc u v huv) + have hn := (transition_stochastic hw hc0 e).1 f + by_cases hadj : G.Adj e.dst f.dst + · rw [ite_eq_left hadj] + change transition G w e f ≤ x * w f.dst at hp + linarith + · simp [transition, hadj] + +lemma liftSet_adj_mass_le (hw : ∀ u, 0 ≤ w u) (u y : V) (A : Finset V) : + (∑ z ∈ liftSet (G := G) u A, if G.Adj z.dst y then w z.dst else 0) ≤ + mass w (A ∩ neighbors G y) := by + rw [sum_liftSet u A (fun z ↦ if G.Adj z y then w z else 0), ← sum_filter] + have he : (A ∩ neighbors G u).filter (fun z ↦ G.Adj z y) = + (A ∩ neighbors G y) ∩ neighbors G u := by + ext z + simp [G.adj_comm z y, and_assoc, and_comm] + rw [he] + exact mass_mono hw inter_subset_left + +lemma incoming_good_le (hw : ∀ u, 0 < w u) {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + {t : ℝ} (ht : 0 ≤ t) (n : ℕ) (e : EdgeState G) (A : Finset V) : + (∑ y ∈ (liftSet (G := G) e.src (enlarge G w t A))ᶜ, + ∑ z ∈ liftSet (G := G) e.src A, + smoothed (transition G w) n e z * lazy (transition G w) z y) ≤ + x ^ 2 * t * neighborMass G w e.src := by + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx).trans_le (hc u v huv) + have hP := transition_stochastic hw hc0 + have hQ := stochastic_lazy hP + have hpt := preserves_lazy (label := EdgeState.src) (transition_fixed_src (G := G) (w := w)) + have hrow (y : EdgeState G) (hy : y ∈ (liftSet (G := G) e.src (enlarge G w t A))ᶜ) : + (∑ z ∈ liftSet (G := G) e.src A, + smoothed (transition G w) n e z * lazy (transition G w) z y) ≤ + if y.src = e.src then x ^ 2 * t * w y.dst else 0 := by + by_cases hsrc : y.src = e.src + · rw [ite_eq_left hsrc] + have hyout : y.dst ∉ enlarge G w t A := by + intro h + exact (mem_compl.1 hy) ((mem_liftSet _ _ _).2 ⟨hsrc, h⟩) + have hymass := (not_mem_enlarge G w t A hyout).2.le + calc + _ ≤ ∑ z ∈ liftSet (G := G) e.src A, + (if G.Adj z.dst y.dst then w z.dst else 0) * (x ^ 2 * w y.dst) := by + apply sum_le_sum + intro z hz + have hzA := ((mem_liftSet _ _ _).1 hz).2 + have hzy : z.dst ≠ y.dst := by + intro h + apply hyout + exact subset_enlarge G w t A (h ▸ hzA) + have h1 := smoothed_density hw hx hc n e z + have h2 := lazy_neighbor_density hw hx hc z y hzy + change smoothed (transition G w) n e z ≤ x * w z.dst at h1 + have hm := mul_le_mul h1 h2 ((hQ z).1 y) (mul_pos hx (hw z.dst)).le + by_cases hadj : G.Adj z.dst y.dst + · simpa only [ite_eq_left hadj] using hm.trans_eq (by rw [ite_eq_left hadj]; ring) + · simpa only [ite_eq_right hadj, mul_zero, zero_mul] using hm + _ = (∑ z ∈ liftSet (G := G) e.src A, + if G.Adj z.dst y.dst then w z.dst else 0) * (x ^ 2 * w y.dst) := + (sum_mul _ _ _).symm + _ ≤ mass w (A ∩ neighbors G y.dst) * (x ^ 2 * w y.dst) := + mul_le_mul_of_nonneg_right (liftSet_adj_mass_le (fun u ↦ (hw u).le) _ _ _) + (mul_nonneg (sq_nonneg x) (hw y.dst).le) + _ ≤ t * (x ^ 2 * w y.dst) := mul_le_mul_of_nonneg_right hymass + (mul_nonneg (sq_nonneg x) (hw y.dst).le) + _ = _ := by ring + · rw [ite_eq_right hsrc] + apply le_of_eq + apply sum_eq_zero + intro z hz + have hzs := ((mem_liftSet _ _ _).1 hz).1 + rw [hpt z y (fun h ↦ hsrc (h.symm.trans hzs)), mul_zero] + calc + _ ≤ ∑ y ∈ (liftSet (G := G) e.src (enlarge G w t A))ᶜ, + if y.src = e.src then x ^ 2 * t * w y.dst else 0 := sum_le_sum hrow + _ ≤ ∑ y : EdgeState G, if y.src = e.src then x ^ 2 * t * w y.dst else 0 := by + apply sum_le_univ_sum_of_nonneg + intro y + split_ifs + · exact mul_nonneg (mul_nonneg (sq_nonneg x) ht) (hw _).le + · exact le_rfl + _ = _ := by + rw [EdgeState.sum_fiber e.src (fun y ↦ x ^ 2 * t * w y), ← mul_sum] + rfl + +lemma reach_leakage (hw : ∀ u, 0 < w u) {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + {L t : ℝ} (hL : ∀ u, neighborMass G w u ≤ L) (ht : 0 ≤ t) + (n : ℕ) (e : EdgeState G) : + rowMass (smoothed (transition G w) n) e + (liftSet (G := G) e.src (reach G w t e.dst n))ᶜ ≤ n * (x ^ 2 * t * L) := by + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx).trans_le (hc u v huv) + have hP := transition_stochastic hw hc0 + induction n with + | zero => + simp only [smoothed_zero, Nat.cast_zero, zero_mul, reach] + apply le_of_eq + apply sum_eq_zero + intro f hf + have hf' := mem_compl.1 hf + by_cases hs : e.src = f.src + · have ha : ¬G.Adj e.dst f.dst := by + intro h + exact hf' ((mem_liftSet _ _ _).2 ⟨hs.symm, (mem_neighbors G _ _).2 h⟩) + simp [transition, hs, ha] + · exact transition_fixed_src e f hs + | succ n ih => + rw [smoothed_succ_right] + have h := leakage_mul_le (stochastic_smoothed hP n) (stochastic_lazy hP) e + (liftSet (G := G) e.src (reach G w t e.dst n)) + (liftSet (G := G) e.src (reach G w t e.dst (n+1))) + have hinc := incoming_good_le hw hx hc ht n e (reach G w t e.dst n) + have hmass := mul_le_mul_of_nonneg_left (hL e.src) (mul_nonneg (sq_nonneg x) ht) + simp only [reach] at h + simp only [Nat.cast_add, Nat.cast_one] + change rowMass (smoothed (transition G w) n * lazy (transition G w)) e + (liftSet (G := G) e.src (enlarge G w t (reach G w t e.dst n)))ᶜ ≤ _ + calc + _ ≤ _ := h + _ ≤ n * (x ^ 2 * t * L) + x ^ 2 * t * L := + add_le_add ih (hinc.trans hmass) + _ = _ := by ring + +lemma law_rev (e : EdgeState G) : law G w e.rev = law G w e := by + simp only [law, EdgeState.src_rev, EdgeState.dst_rev, commonMass_comm G w e.dst e.src] + ring + +lemma law_bad_sum (B : V → Finset V) (hB : ∀ v, B v ⊆ neighbors G v) : + (∑ e : EdgeState G, if e.src ∈ B e.dst then law G w e else 0) = + (∑ v, w v * crossMass G w (B v) (neighbors G v)) / normalizer G w := by + have hr := EdgeState.revEquiv (G := G) |>.sum_comp + (fun e : EdgeState G ↦ if e.src ∈ B e.dst then law G w e else 0) + simp only [EdgeState.revEquiv, Equiv.coe_fn_mk, EdgeState.src_rev, EdgeState.dst_rev, + law_rev] at hr + rw [← hr] + unfold law + rw [EdgeState.sum_eq (fun u v ↦ if v ∈ B u then + w u * w v * commonMass G w u v / normalizer G w else 0)] + simp_rw [crossMass_neighbors, mul_sum, sum_div] + apply sum_congr rfl + intro v _ + rw [← sum_filter] + have he : (neighbors G v).filter (fun u ↦ u ∈ B v) = B v := + filter_mem_eq_inter.trans (inter_eq_right.2 (hB v)) + rw [he] + apply sum_congr rfl + intro u _ + rw [commonMass_comm G w v u] + ring + +lemma law_bad_le [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + (hc : ∀ u v, G.Adj u v → 0 < commonMass G w u v) + (B : V → Finset V) (hB : ∀ v, B v ⊆ neighbors G v) {q : ℝ} + (hb : ∀ v, crossMass G w (B v) (neighbors G v) ≤ q * triangleAt G w v) : + (∑ e : EdgeState G, if e.src ∈ B e.dst then law G w e else 0) ≤ q := by + rw [law_bad_sum B hB, div_le_iff₀ (normalizer_pos hw hc)] + calc + _ ≤ ∑ v, w v * (q * triangleAt G w v) := + sum_le_sum fun v _ ↦ mul_le_mul_of_nonneg_left (hb v) (hw v).le + _ = q * normalizer G w := by + rw [normalizer_eq, triangleMass_eq_sum, mul_sum] + apply sum_congr rfl + intro v _ + ring + +lemma entropy_good_row (hw : ∀ u, 0 < w u) {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) + {t : ℝ} (ht : 0 ≤ t) (n : ℕ) (e : EdgeState G) {b : ℝ} (hb : 1 ≤ b) + (he : e.src ∉ badSet G w (fun v ↦ reach G w t v n) b e.dst) : + entropy (vertexWeight G w) (smoothed (transition G w) n e) ≤ + Real.log 2 + Real.log b + (n * (x ^ 2 * t * Real.exp x)) * x := by + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx).trans_le (hc u v huv) + have hP := transition_stochastic hw hc0 + have hsmall : mass w (reach G w t e.dst n ∩ neighbors G e.src) ≤ b := by + by_contra! h + exact he (mem_filter.2 ⟨(mem_neighbors G _ _).2 e.adj.symm, h⟩) + have h := entropy_supported_concentration (w := vertexWeight G w) + (fiber G e.src) (liftSet (G := G) e.src (reach G w t e.dst n)) + (liftSet_subset_fiber _ _) (fun f _ ↦ hw f.dst) (stochastic_smoothed hP n e) + (smoothed_supported n e) hb (Real.exp_pos x) + (by change (∑ f ∈ liftSet (G := G) e.src (reach G w t e.dst n), w f.dst) ≤ b + rw [sum_liftSet]; exact hsmall) + (by rw [fiber_mass]; exact hL _) + rw [Real.log_exp] at h + have hl := reach_leakage hw hx hc hL ht n e + rw [rowMass_compl (stochastic_smoothed hP n)] at hl + exact h.trans (add_le_add le_rfl (mul_le_mul_of_nonneg_right hl hx.le)) + +lemma averaged_entropy_bound [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) + {t : ℝ} (ht : 0 ≤ t) (n : ℕ) {b q : ℝ} (hb : 1 ≤ b) + (hbad : (∑ e : EdgeState G, + if e.src ∈ badSet G w (fun v ↦ reach G w t v n) b e.dst then law G w e else 0) ≤ q) : + avgEntropy (law G w) (vertexWeight G w) (smoothed (transition G w) n) ≤ + Real.log 2 + Real.log b + (n * (x ^ 2 * t * Real.exp x)) * x + q * x := by + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx).trans_le (hc u v huv) + have hmu := law_isProb hw hc0 + let A := Real.log 2 + Real.log b + (n * (x ^ 2 * t * Real.exp x)) * x + have hA : 0 ≤ A := by + dsimp [A] + have hl2 : 0 ≤ Real.log 2 := Real.log_nonneg (by norm_num) + have hlb : 0 ≤ Real.log b := Real.log_nonneg hb + positivity + have hrow (e : EdgeState G) : + entropy (vertexWeight G w) (smoothed (transition G w) n e) ≤ + A + if e.src ∈ badSet G w (fun v ↦ reach G w t v n) b e.dst then x else 0 := by + split_ifs with he + · exact (entropy_bounds hw hx hc hL n e).2.trans (by linarith) + · simpa only [add_zero] using entropy_good_row hw hx hc hL ht n e hb he + calc + _ ≤ ∑ e, law G w e * + (A + if e.src ∈ badSet G w (fun v ↦ reach G w t v n) b e.dst then x else 0) := + sum_le_sum fun e _ ↦ mul_le_mul_of_nonneg_left (hrow e) (hmu.1 e) + _ = A + (∑ e : EdgeState G, + if e.src ∈ badSet G w (fun v ↦ reach G w t v n) b e.dst then law G w e else 0) * x := by + simp only [mul_add, sum_add_distrib, ← sum_mul, hmu.2, one_mul, mul_ite, mul_zero] + rw [sum_mul] + simp only [ite_mul, zero_mul] + _ ≤ _ := add_le_add le_rfl (mul_le_mul_of_nonneg_right hbad hx.le) + +lemma avg_entropy_lower [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + {x : ℝ} (hx : 0 < x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) (n : ℕ) : + -Real.log x ≤ avgEntropy (law G w) (vertexWeight G w) (smoothed (transition G w) n) := by + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx).trans_le (hc u v huv) + have hmu := law_isProb hw hc0 + calc + _ = (∑ e, law G w e) * (-Real.log x) := by rw [hmu.2, one_mul] + _ = ∑ e, law G w e * (-Real.log x) := sum_mul _ _ _ + _ ≤ _ := sum_le_sum fun e _ ↦ mul_le_mul_of_nonneg_left + (entropy_bounds hw hx hc hL n e).1 (hmu.1 e) + +lemma avg_entropy_upper [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + {C x : ℝ} (hC : 0 ≤ C) (hCross : CrossBound G w C) (hx : 32 ≤ x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) + (n : ℕ) (hn : (n : ℝ) ≤ 2 * x) : + avgEntropy (law G w) (vertexWeight G w) (smoothed (transition G w) n) ≤ + entropyConstant C * Real.log x := by + have hx0 : 0 < x := by linarith + have hx1 : 1 ≤ x := by linarith + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx0).trans_le (hc u v huv) + have hbad := law_bad_le hw hc0 + (badSet G w (fun u ↦ reach G w (Numerical.threshold x) u n) (x ^ 8)) + (badSet_subset G w _ _) (reach_bad_cross G (fun u ↦ (hw u).le) hC hCross hx hL hc hn) + have hb : (1 : ℝ) ≤ x ^ 8 := one_le_pow₀ hx1 + have h := averaged_entropy_bound hw hx0 hc hL (Numerical.threshold_pos hx0).le n hb hbad + rw [Real.log_pow] at h + have hleak : ((n : ℝ) * (x ^ 2 * Numerical.threshold x * Real.exp x)) * x ≤ 1 := by + rw [Numerical.leakage_factor hx0] + calc + _ = (n : ℝ) / x ^ 3 := by field_simp [hx0.ne'] + _ ≤ (2 * x) / x ^ 3 := div_le_div_of_nonneg_right hn (pow_pos hx0 3).le + _ = 2 / x ^ 2 := by field_simp [hx0.ne'] + _ ≤ 1 := (div_le_iff₀ (pow_pos hx0 2)).2 (by nlinarith) + have hE := exceptionalConstant_nonneg hC + have hq : (exceptionalConstant C / x ^ 4) * x ≤ exceptionalConstant C * Real.log x := by + calc + _ = exceptionalConstant C / x ^ 3 := by field_simp [hx0.ne'] + _ ≤ exceptionalConstant C := (div_le_iff₀ (pow_pos hx0 3)).2 (by + simpa only [mul_one] using mul_le_mul_of_nonneg_left (one_le_pow₀ hx1 (n := 3)) hE) + _ ≤ _ := by nlinarith [(Numerical.log_bounds hx).1] + have hl2 : Real.log 2 ≤ Real.log x := Real.log_le_log (by norm_num) (by linarith) + have hl1 := (Numerical.log_bounds hx).1 + unfold entropyConstant + norm_num only [Nat.cast_ofNat] at h + linarith + +noncomputable def rowDistance (n : ℕ) : ℝ := + ∑ e : EdgeState G, law G w e * ∑ f, transition G w e f * + tv (smoothed (transition G w) n e) (smoothed (transition G w) n f) + +/-- The `C`-dependent entropy smoothing bound. -/ +lemma exists_smooth_index [Nonempty (EdgeState G)] (hw : ∀ u, 0 < w u) + {C x : ℝ} (hC : 1 ≤ C) (hCross : CrossBound G w C) (hx : 32 ≤ x) + (hc : ∀ u v, G.Adj u v → 1 / x ≤ commonMass G w u v) + (hL : ∀ u, neighborMass G w u ≤ Real.exp x) : + ∃ j < ⌈x⌉₊, + avgEntropy (law G w) (vertexWeight G w) (smoothed (transition G w) j) ≤ + entropyConstant C * Real.log x ∧ + rowDistance (G := G) (w := w) j ≤ smoothingConstant C * Real.sqrt (Real.log x / x) := by + have hx0 : 0 < x := by linarith + have hC0 : 0 ≤ C := by linarith + have hc0 : ∀ u v, G.Adj u v → 0 < commonMass G w u v := + fun u v huv ↦ (one_div_pos.2 hx0).trans_le (hc u v huv) + have hmu := law_isProb hw hc0 + have hP := transition_stochastic hw hc0 + have hs := stationary_of_reversible hP (transition_reversible hw hc0) + have hceil := Numerical.ceil_bounds hx + have hlow := avg_entropy_lower hw hx0 hc hL 0 + have hupp := avg_entropy_upper hw hC0 hCross hx hc hL ⌈x⌉₊ hceil.2.2 + have hD : avgEntropy (law G w) (vertexWeight G w) (smoothed (transition G w) ⌈x⌉₊) - + avgEntropy (law G w) (vertexWeight G w) (smoothed (transition G w) 0) ≤ + (entropyConstant C + 1) * Real.log x := by linarith + obtain ⟨j, hj, hdist⟩ := exists_smoothed_row_distance hmu (fun e ↦ hw e.dst) hP hs hceil.1 hD + refine ⟨j, hj, ?_, ?_⟩ + · exact (smoothed_entropy_mono hmu (fun e ↦ hw e.dst) hP hs (Nat.le_of_lt hj)).trans hupp + · have hA : 0 ≤ entropyConstant C + 1 := by + have := exceptionalConstant_nonneg hC0 + unfold entropyConstant + linarith + have hlog : 0 ≤ Real.log x := ((Numerical.log_bounds hx).1.trans' (by norm_num)) + have href : rowDistance (G := G) (w := w) j ^ 2 ≤ + 4 * ((entropyConstant C + 1) * Real.log x) / x := by + exact hdist.trans (div_le_div_of_nonneg_left (by positivity) hx0 hceil.2.1) + have hf : 0 ≤ Real.log x / x := div_nonneg hlog hx0.le + have hsq : (smoothingConstant C * Real.sqrt (Real.log x / x)) ^ 2 = + 4 * ((entropyConstant C + 1) * Real.log x) / x := by + rw [mul_pow, smoothingConstant, mul_pow, Real.sq_sqrt hA, Real.sq_sqrt hf] + ring + have hn : 0 ≤ smoothingConstant C * Real.sqrt (Real.log x / x) := by + unfold smoothingConstant + positivity + nlinarith + +end LocalWalk + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CliqueFree/WeightedGraph.lean b/lean/OAI/Combinatorics/CliqueFree/WeightedGraph.lean new file mode 100644 index 0000000000000000000000000000000000000000..908670dc75c63b23c590269a6c51ac9cbc4eb57c --- /dev/null +++ b/lean/OAI/Combinatorics/CliqueFree/WeightedGraph.lean @@ -0,0 +1,204 @@ +import OAI.Combinatorics.CliqueFree.Numerical + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +attribute [local instance] Classical.propDecidable + +namespace CliqueFreeIndependence.WeightedGraph + +universe u v + +variable {V : Type u} [Fintype V] + +def mass (w : V → ℝ) (A : Finset V) : ℝ := ∑ v ∈ A, w v + +noncomputable def neighbors (G : SimpleGraph V) (v : V) : Finset V := by + classical + exact univ.filter (G.Adj v) + +@[simp] lemma mem_neighbors (G : SimpleGraph V) (u v : V) : + v ∈ neighbors G u ↔ G.Adj u v := by + classical + simp [neighbors] + +noncomputable def crossMass (G : SimpleGraph V) (w : V → ℝ) (A B : Finset V) : ℝ := by + classical + exact ∑ u ∈ A, ∑ v ∈ B, if G.Adj u v then w u * w v else 0 + +/-- Unordered edge mass, written as half the directed edge mass. -/ +noncomputable def edgeMass (G : SimpleGraph V) (w : V → ℝ) : ℝ := + crossMass G w univ univ / 2 + +noncomputable def neighborMass (G : SimpleGraph V) (w : V → ℝ) (u : V) : ℝ := + mass w (neighbors G u) + +noncomputable def commonMass (G : SimpleGraph V) (w : V → ℝ) (u v : V) : ℝ := by + classical + exact mass w (neighbors G u ∩ neighbors G v) + +/-- Twice the triangle mass in the weighted neighborhood of u. -/ +noncomputable def triangleAt (G : SimpleGraph V) (w : V → ℝ) (u : V) : ℝ := + ∑ v ∈ neighbors G u, w v * commonMass G w u v + +/-- Unordered triangle mass, written as one sixth of the ordered triangle mass. -/ +noncomputable def triangleMass (G : SimpleGraph V) (w : V → ℝ) : ℝ := + (∑ u, w u * triangleAt G w u) / 6 + +/-- The growth function `g_x`, including its zero convention. Only nonnegative `s` are used. -/ +noncomputable def growth (x s : ℝ) : ℝ := s * (x + max 0 (Real.log (1 / s))) + +/-- The full cross-mass property; sets may overlap. -/ +def CrossBound (G : SimpleGraph V) (w : V → ℝ) (C : ℝ) : Prop := + ∀ (x : ℝ), 1 ≤ x → ∀ (A B : Finset V), + mass w A ≤ Real.exp x → mass w B ≤ Real.exp x → + crossMass G w A B ≤ C * growth x (mass w A) + +omit [Fintype V] in +lemma mass_nonneg {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) (A : Finset V) : + 0 ≤ mass w A := sum_nonneg fun v _ ↦ hw v + +omit [Fintype V] in +lemma mass_mono {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) {A B : Finset V} (hAB : A ⊆ B) : + mass w A ≤ mass w B := sum_le_sum_of_subset_of_nonneg hAB (fun v _ _ ↦ hw v) + +omit [Fintype V] in +lemma crossMass_symm (G : SimpleGraph V) (w : V → ℝ) (A B : Finset V) : + crossMass G w A B = crossMass G w B A := by + classical + unfold crossMass + rw [sum_comm] + simp_rw [G.adj_comm, mul_comm] + +omit [Fintype V] in +lemma crossMass_nonneg (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + (A B : Finset V) : 0 ≤ crossMass G w A B := by + classical + exact sum_nonneg fun u _ ↦ sum_nonneg fun v _ ↦ by + split_ifs + · exact mul_nonneg (hw u) (hw v) + · exact le_rfl + +omit [Fintype V] in +lemma crossMass_le_product (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + (A B : Finset V) : crossMass G w A B ≤ mass w A * mass w B := by + classical + unfold crossMass mass + rw [sum_mul_sum] + exact sum_le_sum fun u _ ↦ sum_le_sum fun v _ ↦ by + split_ifs + · exact le_rfl + · exact mul_nonneg (hw u) (hw v) + +lemma crossMass_factor (G : SimpleGraph V) (w : V → ℝ) (A B : Finset V) : + crossMass G w A B = ∑ u ∈ A, w u * mass w (B ∩ neighbors G u) := by + classical + unfold crossMass mass + apply sum_congr rfl + intro u _ + rw [← filter_mem_eq_inter] + simp only [sum_filter, mem_neighbors, mul_sum, mul_ite, mul_zero] + +lemma commonMass_comm (G : SimpleGraph V) (w : V → ℝ) (u v : V) : + commonMass G w u v = commonMass G w v u := by + classical + simp [commonMass, inter_comm] + +lemma commonMass_nonneg (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) (u v : V) : + 0 ≤ commonMass G w u v := mass_nonneg hw _ + +lemma neighborMass_nonneg (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) (u : V) : + 0 ≤ neighborMass G w u := mass_nonneg hw _ + +lemma commonMass_le_neighborMass (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + (u v : V) : commonMass G w u v ≤ neighborMass G w u := by + classical + exact mass_mono hw inter_subset_left + +lemma edgeMass_nonneg (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) : + 0 ≤ edgeMass G w := div_nonneg (crossMass_nonneg G hw _ _) (by norm_num) + +lemma triangleAt_nonneg (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) (u : V) : + 0 ≤ triangleAt G w u := + sum_nonneg fun v _ ↦ mul_nonneg (hw v) (commonMass_nonneg G hw u v) + +lemma triangleMass_nonneg (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) : + 0 ≤ triangleMass G w := div_nonneg + (sum_nonneg fun u _ ↦ mul_nonneg (hw u) (triangleAt_nonneg G hw u)) (by norm_num) + +lemma edgeMass_eq_sum (G : SimpleGraph V) (w : V → ℝ) : + 2 * edgeMass G w = ∑ u, w u * neighborMass G w u := by + classical + rw [edgeMass, crossMass_factor] + simp only [univ_inter, neighborMass] + ring + +lemma triangleMass_eq_sum (G : SimpleGraph V) (w : V → ℝ) : + 6 * triangleMass G w = ∑ u, w u * triangleAt G w u := by + unfold triangleMass + ring + +lemma triangleAt_le (G : SimpleGraph V) {w : V → ℝ} (hw : ∀ v, 0 ≤ w v) + {L : ℝ} (hL : ∀ u, neighborMass G w u ≤ L) (u : V) : + triangleAt G w u ≤ L * neighborMass G w u := by + calc + _ ≤ ∑ v ∈ neighbors G u, w v * L := sum_le_sum fun v _ ↦ + mul_le_mul_of_nonneg_left ((commonMass_le_neighborMass G hw u v).trans (hL u)) (hw v) + _ = _ := by rw [← sum_mul]; exact mul_comm _ _ + +lemma triangleMass_le_of_neighborMass (G : SimpleGraph V) {w : V → ℝ} + (hw : ∀ v, 0 ≤ w v) {L : ℝ} (hL : ∀ u, neighborMass G w u ≤ L) : + triangleMass G w ≤ L / 3 * edgeMass G w := by + have h : 6 * triangleMass G w ≤ L * (2 * edgeMass G w) := by + rw [triangleMass_eq_sum, edgeMass_eq_sum, mul_sum] + exact sum_le_sum fun u _ ↦ by + have := mul_le_mul_of_nonneg_left (triangleAt_le G hw hL u) (hw u) + nlinarith + linarith + +lemma neighborMass_ge_of_commonMass (G : SimpleGraph V) {w : V → ℝ} + (hw : ∀ v, 0 ≤ w v) {τ : ℝ} (hc : ∀ u v, G.Adj u v → τ ≤ commonMass G w u v) + {u : V} (hu : (neighbors G u).Nonempty) : τ ≤ neighborMass G w u := by + rcases hu with ⟨v, hv⟩ + exact (hc u v (mem_neighbors G u v |>.1 hv)).trans (commonMass_le_neighborMass G hw u v) + +lemma triangleAt_ge_of_commonMass (G : SimpleGraph V) {w : V → ℝ} + (hw : ∀ v, 0 ≤ w v) {τ : ℝ} (hc : ∀ u v, G.Adj u v → τ ≤ commonMass G w u v) + (u : V) : τ * neighborMass G w u ≤ triangleAt G w u := by + calc + _ = ∑ v ∈ neighbors G u, w v * τ := by rw [← sum_mul]; exact mul_comm _ _ + _ ≤ _ := sum_le_sum fun v hv ↦ mul_le_mul_of_nonneg_left + (hc u v (mem_neighbors G u v |>.1 hv)) (hw v) + +lemma commonMass_eq_sum (G : SimpleGraph V) (w : V → ℝ) (u v : V) : + commonMass G w u v = ∑ z ∈ neighbors G u, if G.Adj v z then w z else 0 := by + classical + unfold commonMass mass + rw [← filter_mem_eq_inter, sum_filter] + simp only [mem_neighbors] + +lemma crossMass_all_right (G : SimpleGraph V) (w : V → ℝ) (A : Finset V) : + crossMass G w A univ = ∑ u ∈ A, w u * neighborMass G w u := by + classical + rw [crossMass_factor] + simp [neighborMass] + +lemma crossMass_all_left (G : SimpleGraph V) (w : V → ℝ) (A : Finset V) : + crossMass G w univ A = ∑ u ∈ A, w u * neighborMass G w u := by + rw [crossMass_symm, crossMass_all_right] + +lemma crossMass_neighbors (G : SimpleGraph V) (w : V → ℝ) + (A : Finset V) (v : V) : + crossMass G w A (neighbors G v) = ∑ u ∈ A, w u * commonMass G w u v := by + rw [crossMass_factor] + simp only [commonMass, inter_comm] + +end CliqueFreeIndependence.WeightedGraph + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Averaging.lean b/lean/OAI/Combinatorics/Coboundary/Averaging.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd7fe8896189193291f61a38243668af2f47c219 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Averaging.lean @@ -0,0 +1,519 @@ +import OAI.Combinatorics.Coboundary.LinkSpectrum + +namespace OAI + +/-! +Finite F2 averaging and bounded-cone estimates for weighted local cochains. +-/ + +noncomputable section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix +open scoped BigOperators InnerProductSpace + +namespace CoboundaryExpanders.Averaging + +section +open scoped BigOperators +variable {A B G : Type} [Fintype A] [Fintype B] [Fintype G] + [DecidableEq A] [DecidableEq B] [DecidableEq G] + +def supportNorm (w : A → ℝ) (f : A → ZMod 2) : ℝ := + ∑ a, if f a = 0 then 0 else w a + +omit [DecidableEq A] in +lemma supportNorm_nonneg (w : A → ℝ) (hw : ∀ a, 0 ≤ w a) (f : A → ZMod 2) : + 0 ≤ supportNorm w f := by + apply Finset.sum_nonneg + intro a _ + split_ifs + · exact le_rfl + · exact hw a + +omit [Fintype B] [DecidableEq B] in +lemma support_indicator_sum_le (s : Finset B) (f : B → ZMod 2) : + (if ∑ b ∈ s, f b = 0 then (0 : ℝ) else 1) ≤ + ∑ b ∈ s, if f b = 0 then (0 : ℝ) else 1 := by + split_ifs with h + · exact Finset.sum_nonneg (fun b _ => by split_ifs <;> norm_num) + · obtain ⟨b, hb, hfb⟩ : ∃ b ∈ s, f b ≠ 0 := by + by_contra hh + push Not at hh + exact h (Finset.sum_eq_zero hh) + calc + (1 : ℝ) = (if f b = 0 then 0 else 1) := by simp [hfb] + _ ≤ ∑ b ∈ s, if f b = 0 then (0 : ℝ) else 1 := + Finset.single_le_sum (f := fun b => if f b = 0 then (0 : ℝ) else 1) + (fun b _ => by split_ifs <;> norm_num) hb + +omit [DecidableEq G] in +lemma exists_le_of_sum_le [Nonempty G] (v : G → ℝ) (c : ℝ) + (h : ∑ g, v g ≤ Fintype.card G * c) : ∃ g, v g ≤ c := by + by_contra hn + push Not at hn + have hh : Fintype.card G * c < ∑ g, v g := by + simpa using Finset.sum_lt_sum_of_nonempty (Finset.univ_nonempty) (fun g _ => hn g) + linarith + +omit [DecidableEq A] [DecidableEq G] in +theorem exists_small_dual [Nonempty G] + (wA : A → ℝ) (hwA : ∀ a, 0 ≤ wA a) (hwSum : ∑ a, wA a = 1) + (wB : B → ℝ) (hwB : ∀ b, 0 ≤ wB b) + (act : G → B → B) (C : ℝ) (hC : 0 ≤ C) + (H : A → Finset B) (R : ℕ) (hH : ∀ a, (H a).card ≤ R) + (hOcc : ∀ a b, b ∈ H a → ∀ t, ((Finset.univ.filter (fun g => act g b = t)).card : ℝ) ≤ + Fintype.card G * C * wB t) + (f : B → ZMod 2) : + ∃ g, supportNorm wA (fun a => ∑ b ∈ H a, f (act g b)) ≤ + (R : ℝ) * C * supportNorm wB f := by + apply exists_le_of_sum_le + have hnon : 0 ≤ supportNorm wB f := supportNorm_nonneg wB hwB f + have hp (a : A) (b : B) (hb : b ∈ H a) : + ∑ g, (if f (act g b) = 0 then (0 : ℝ) else 1) ≤ + Fintype.card G * C * supportNorm wB f := by + have he : (∑ g, if f (act g b) = 0 then (0 : ℝ) else 1) = + ∑ t, ((Finset.univ.filter (fun g => act g b = t)).card : ℝ) * + (if f t = 0 then (0 : ℝ) else 1) := by + simp only [← Finset.sum_boole, Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro g _ + rw [Finset.sum_eq_single (act g b)] + · simp + · intro t _ ht + simp [ht.symm] + · simp + rw [he, supportNorm, Finset.mul_sum] + apply Finset.sum_le_sum + intro t _ + split_ifs with ht + · simp + · simpa using hOcc a b hb t + calc + (∑ g, supportNorm wA (fun a => ∑ b ∈ H a, f (act g b))) ≤ + ∑ g, ∑ a, wA a * ∑ b ∈ H a, if f (act g b) = 0 then (0 : ℝ) else 1 := by + apply Finset.sum_le_sum + intro g _ + apply Finset.sum_le_sum + intro a _ + have hh := mul_le_mul_of_nonneg_left (support_indicator_sum_le (H a) (fun b => f (act g b))) (hwA a) + simpa only [mul_ite, mul_zero, mul_one] using hh + _ = ∑ a, wA a * ∑ b ∈ H a, ∑ g, if f (act g b) = 0 then (0 : ℝ) else 1 := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + rw [← Finset.mul_sum, Finset.sum_comm] + _ ≤ ∑ a, wA a * ((H a).card * (Fintype.card G * C * supportNorm wB f)) := by + apply Finset.sum_le_sum + intro a _ + apply mul_le_mul_of_nonneg_left _ (hwA a) + simpa using Finset.sum_le_sum (fun b (hb : b ∈ H a) => hp a b hb) + _ ≤ ∑ a, wA a * ((R : ℝ) * (Fintype.card G * C * supportNorm wB f)) := by + apply Finset.sum_le_sum + intro a _ + apply mul_le_mul_of_nonneg_left _ (hwA a) + apply mul_le_mul_of_nonneg_right (by exact_mod_cast hH a) + positivity + _ = Fintype.card G * ((R : ℝ) * C * supportNorm wB f) := by + rw [← Finset.sum_mul, hwSum] + ring + +end + +open scoped BigOperators +variable {G A B : Type} [Group G] [Fintype G] [Fintype A] [Fintype B] + [DecidableEq G] [DecidableEq A] [DecidableEq B] + [MulAction G A] [MulAction G B] + +omit [Fintype G] [DecidableEq G] [DecidableEq A] in +lemma sum_smul (g : G) (f : A → ℝ) : (∑ a, f (g • a)) = ∑ a, f a := by + exact (Equiv.sum_comp (MulAction.toPerm g) f) + +omit [Fintype A] [DecidableEq G] [DecidableEq A] in +lemma action_average_eq (a b : A) (h : ∃ g : G, g • a = b) (f : A → ℝ) : + (∑ g : G, f (g • a)) = ∑ g : G, f (g • b) := by + obtain ⟨h, rfl⟩ := h + simpa [mul_smul] using (Equiv.sum_comp (Equiv.mulRight h) (fun g : G => f (g • a))).symm + +omit [DecidableEq G] [DecidableEq A] in +lemma transitive_average (a : A) (hTrans : ∀ b, ∃ g : G, g • a = b) (f : A → ℝ) : + (Fintype.card A : ℝ) * (∑ g : G, f (g • a)) = + Fintype.card G * ∑ b : A, f b := by + calc + (Fintype.card A : ℝ) * (∑ g : G, f (g • a)) = ∑ b : A, ∑ g : G, f (g • b) := by + symm + have h (b : A) := (action_average_eq a b (hTrans b) f).symm + simp_rw [h] + simp + _ = ∑ g : G, ∑ b : A, f (g • b) := Finset.sum_comm + _ = Fintype.card G * ∑ b : A, f b := by simp [sum_smul] + +omit [Fintype B] [DecidableEq G] [DecidableEq A] in +theorem occupation_le_incidence (I : A → B → Prop) [DecidableRel I] + (hI : ∀ (g : G) a b, I a b → I (g • a) (g • b)) + (hTrans : ∀ a a' : A, ∃ g : G, g • a = a') + (b : B) (a : A) (hab : I a b) (t : B) : + (Fintype.card A : ℝ) * ((Finset.univ.filter (fun g : G => g • b = t)).card : ℝ) ≤ + Fintype.card G * ((Finset.univ.filter (fun a : A => I a t)).card : ℝ) := by + have hh : (∑ g : G, if g • b = t then (1 : ℝ) else 0) ≤ + ∑ g : G, if I (g • a) t then (1 : ℝ) else 0 := by + apply Finset.sum_le_sum + intro g _ + by_cases ht : g • b = t + · have hi := hI g a b hab + simp only [ht] at hi + simp [ht, hi] + · simp only [ht, ↓reduceIte] + split_ifs <;> norm_num + have hh' := mul_le_mul_of_nonneg_left hh (Nat.cast_nonneg (Fintype.card A) : (0 : ℝ) ≤ _) + rw [transitive_average a (hTrans a) (fun a => if I a t then (1 : ℝ) else 0)] at hh' + simpa only [Finset.sum_boole] using hh' + +end CoboundaryExpanders.Averaging + +namespace CoboundaryExpanders.InfiniteChains.Cone +open Attachment +variable {V : Type} [DecidableEq V] + +def eval (f : Finset V → k) : Raw V →ₗ[k] k := Finsupp.linearCombination k f + +omit [DecidableEq V] in +@[simp] lemma eval_single (f : Finset V → k) (s : Finset V) (a : k) : + eval f (Finsupp.single s a) = a * f s := by simp [eval, smul_eq_mul] + +omit [DecidableEq V] in +lemma eval_support (f : Finset V → k) (c : Raw V) : + eval f c = ∑ s ∈ c.support, f s := by + rw [eval, Finsupp.linearCombination_apply, Finsupp.sum] + apply Finset.sum_congr rfl + intro s hs + have hn : c s ≠ 0 := Finsupp.mem_support_iff.mp hs + have ho : c s = 1 := by + have he : ∀ a : k, a = 0 ∨ a = 1 := by decide + exact (he (c s)).resolve_left hn + simp [ho] + +def delta (f : Finset V → k) (s : Finset V) : k := + eval f (rawBoundary (Finsupp.single s 1)) + +lemma eval_delta (f : Finset V → k) (c : Raw V) : + eval (delta f) c = eval f (rawBoundary c) := by + have hh : eval (delta f) = (eval f).comp rawBoundary := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, eval_single] + have hsingle : Finsupp.single s a = a • Finsupp.single s (1 : k) := by simp + rw [hsingle, map_smul, map_smul] + rfl + exact LinearMap.congr_fun hh c + +@[simp] lemma delta_eq_sum (f : Finset V → k) (s : Finset V) : + delta f s = ∑ v ∈ s, f (s.erase v) := by simp [delta] + +@[simp] lemma delta_delta (f : Finset V → k) (s : Finset V) : delta (delta f) s = 0 := by + rw [delta, eval_delta] + change eval f ((rawBoundary.comp rawBoundary) (Finsupp.single s 1)) = 0 + rw [rawBoundary_squared] + simp + +def correction (T : Raw V →ₗ[k] Raw V) (f : Finset V → k) (s : Finset V) : k := + eval f (T (Finsupp.single s 1)) + +omit [DecidableEq V] in +lemma eval_correction (T : Raw V →ₗ[k] Raw V) (f : Finset V → k) (c : Raw V) : + eval (correction T f) c = eval f (T c) := by + have hh : eval (correction T f) = (eval f).comp T := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, eval_single] + have hsingle : Finsupp.single s a = a • Finsupp.single s (1 : k) := by simp + rw [hsingle, map_smul, map_smul] + rfl + exact LinearMap.congr_fun hh c + +lemma correction_identity {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} (H : BoundedCone X n R) + (f : Finset V → k) (s : Finset V) (hs : s ∈ X.faces) (hn : s.card ≤ n) : + f s + delta (correction H.hom f) s = eval (delta f) (H.hom (Finsupp.single s 1)) := by + have hh := congrArg (eval f) (H.contraction s hs hn) + rw [map_add, eval_single, one_mul, ← eval_delta f (H.hom (Finsupp.single s 1)), + ← eval_correction H.hom f (rawBoundary (Finsupp.single s 1))] at hh + change _ + delta (correction H.hom f) s = f s at hh + rw [← hh] + simp [add_assoc, CharTwo.add_self_eq_zero] + +variable {G : Type} [Group G] [MulAction G V] +open scoped Pointwise + +def pull (g : G) (f : Finset V → k) (s : Finset V) : k := f (g • s) + +lemma eval_pull (g : G) (f : Finset V → k) (c : Raw V) : + eval (pull g f) c = eval f (relabel (fun v => g • v) c) := by + have hh : eval (pull g f) = (eval f).comp (relabel (fun v => g • v)) := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp [pull, Finset.image_smul] + exact LinearMap.congr_fun hh c + +lemma delta_pull (g : G) (f : Finset V → k) (s : Finset V) : + delta (pull g f) s = pull g (delta f) s := by + rw [delta, eval_pull] + have hh := LinearMap.congr_fun (relabel_boundary (fun v : V => g • v) + (MulAction.injective g)) (Finsupp.single s 1) + simp only [LinearMap.comp_apply, relabel_single, Finset.image_smul] at hh + rw [← hh] + rfl + +@[simp] lemma pull_inv (g : G) (f : Finset V → k) : pull g (pull g⁻¹ f) = f := by + funext s + simp [pull] + +def movedCorrection (g : G) (T : Raw V →ₗ[k] Raw V) (f : Finset V → k) : Finset V → k := + pull g⁻¹ (correction T (pull g f)) + +lemma movedCorrection_identity {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} (H : BoundedCone X n R) + (g : G) (f : Finset V → k) (s : Finset V) (hs : s ∈ X.faces) (hn : s.card ≤ n) : + f (g • s) + delta (movedCorrection g H.hom f) (g • s) = + ∑ t ∈ (H.hom (Finsupp.single s 1)).support, delta f (g • t) := by + have hh := correction_identity H (pull g f) s hs hn + have he : delta (movedCorrection g H.hom f) (g • s) = + delta (correction H.hom (pull g f)) s := by + rw [movedCorrection, delta_pull] + simp [pull] + rw [he] + simpa only [pull, funext (delta_pull g f), eval_support] using hh + +end CoboundaryExpanders.InfiniteChains.Cone + +namespace CoboundaryExpanders.InfiniteChains.FiniteWeights + +section +open Attachment Cone Averaging +open scoped BigOperators Pointwise +variable {V : Type} [Fintype V] [DecidableEq V] + +def weight (X : CoboundaryExpanders.InfiniteChains.Complex V) (N r : ℕ) (s : Finset V) : ℝ := + if s ∈ level X r then cofaces X N s / ((N.choose r : ℝ) * (level X N).card) else 0 + +lemma weight_nonneg (X : CoboundaryExpanders.InfiniteChains.Complex V) (N r : ℕ) (s : Finset V) : 0 ≤ weight X N r s := by + unfold weight + split_ifs <;> positivity + +lemma cofaces_eq_sum (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (s : Finset V) : + (cofaces X N s : ℝ) = ∑ t ∈ level X N, if s ⊆ t then (1 : ℝ) else 0 := by + simp [cofaces] + +lemma subsets_level (X : CoboundaryExpanders.InfiniteChains.Complex V) {N r : ℕ} (t : Finset V) (ht : t ∈ level X N) : + (level X r).filter (fun s => s ⊆ t) = t.powersetCard r := by + ext s + simp only [Finset.mem_filter, mem_level, Finset.mem_powersetCard] + constructor + · intro h; exact ⟨h.2,h.1.2⟩ + · intro h; exact ⟨⟨X.downward (mem_level X N t |>.mp ht).1 h.1,h.2⟩,h.1⟩ + +lemma sum_cofaces (X : CoboundaryExpanders.InfiniteChains.Complex V) (N r : ℕ) : + (∑ s ∈ level X r, (cofaces X N s : ℝ)) = + (N.choose r : ℝ) * (level X N).card := by + simp_rw [cofaces_eq_sum] + rw [Finset.sum_comm] + have h (t : Finset V) (ht : t ∈ level X N) : + (∑ s ∈ level X r, if s ⊆ t then (1 : ℝ) else 0) = N.choose r := by + rw [Finset.sum_boole, subsets_level X t ht, Finset.card_powersetCard, + (mem_level X N t).mp ht |>.2] + rw [Finset.sum_congr rfl h] + simp [mul_comm] + +lemma weight_sum (X : CoboundaryExpanders.InfiniteChains.Complex V) {N r : ℕ} (hr : r ≤ N) (hN : (level X N).Nonempty) : + ∑ s : Finset V, weight X N r s = 1 := by + have hc : (N.choose r : ℝ) * (level X N).card ≠ 0 := + mul_ne_zero (Nat.cast_ne_zero.mpr (Nat.choose_pos hr).ne') + (Nat.cast_ne_zero.mpr hN.card_pos.ne') + simp only [weight, ← Finset.sum_filter] + have he : Finset.univ.filter (fun s : Finset V => s ∈ level X r) = level X r := by ext; simp + rw [he, ← Finset.sum_div, sum_cofaces, div_self hc] + +variable {G : Type} [Group G] [Fintype G] [MulAction G V] + +def Invariant (G : Type) [Group G] [MulAction G V] (X : CoboundaryExpanders.InfiniteChains.Complex V) : Prop := + ∀ (g : G) s, s ∈ X.faces → g • s ∈ X.faces + +omit [Fintype V] [Fintype G] in +lemma invariant_iff {X : CoboundaryExpanders.InfiniteChains.Complex V} (hX : Invariant G X) (g : G) (s : Finset V) : + g • s ∈ X.faces ↔ s ∈ X.faces := by + constructor + · intro h + simpa using hX g⁻¹ (g • s) h + · exact hX g s + +omit [Fintype G] in +lemma level_smul_iff {X : CoboundaryExpanders.InfiniteChains.Complex V} (hX : Invariant G X) (g : G) (r : ℕ) (s : Finset V) : + g • s ∈ level X r ↔ s ∈ level X r := by + simp only [mem_level, invariant_iff hX, Finset.card_smul_finset] + +omit [Fintype G] in +lemma cofaces_smul {X : CoboundaryExpanders.InfiniteChains.Complex V} (hX : Invariant G X) (g : G) (N : ℕ) (s : Finset V) : + cofaces X N (g • s) = cofaces X N s := by + unfold cofaces + symm + apply Finset.card_bij (fun t _ => g • t) + · intro t ht + exact Finset.mem_filter.mpr ⟨(level_smul_iff hX g N t).mpr (Finset.mem_filter.mp ht).1, + Finset.smul_finset_subset_smul_finset (Finset.mem_filter.mp ht).2⟩ + · intro t ht u hu he + exact MulAction.injective g he + · intro t ht + refine ⟨g⁻¹ • t, ?_, by simp⟩ + refine Finset.mem_filter.mpr ⟨(level_smul_iff hX g⁻¹ N t).mpr (Finset.mem_filter.mp ht).1, ?_⟩ + have hh := Finset.smul_finset_subset_smul_finset (a := g⁻¹) (Finset.mem_filter.mp ht).2 + simpa using hh + +omit [Fintype G] in +lemma weight_smul {X : CoboundaryExpanders.InfiniteChains.Complex V} (hX : Invariant G X) (g : G) (N r : ℕ) (s : Finset V) : + weight X N r (g • s) = weight X N r s := by + simp only [weight, level_smul_iff hX, cofaces_smul hX] + +omit [Fintype G] in +lemma norm_pull {X : CoboundaryExpanders.InfiniteChains.Complex V} (hX : Invariant G X) (g : G) (N r : ℕ) (f : Finset V → k) : + supportNorm (weight X N r) (pull g f) = supportNorm (weight X N r) f := by + classical + unfold supportNorm + apply Finset.sum_bij (fun s _ => g • s) + · intro s hs; exact Finset.mem_univ _ + · intro s hs t ht he; exact MulAction.injective g he + · intro s hs; exact ⟨g⁻¹ • s, Finset.mem_univ _, by simp⟩ + · intro s hs; simp only [pull, weight_smul hX]; rfl + +@[instance_reducible] +def faceAction {X : CoboundaryExpanders.InfiniteChains.Complex V} (hX : Invariant G X) (r : ℕ) : MulAction G (X.Face r) where + smul g s := ⟨g • s.val, hX g s.val s.property.1, by simp [s.property.2]⟩ + one_smul s := Subtype.ext (one_smul _ _) + mul_smul g h s := Subtype.ext (mul_smul g h s.val) + +end + +open Attachment Cone Averaging +open scoped BigOperators Pointwise +variable {V : Type} [Fintype V] [DecidableEq V] + +instance faceFintype (X : CoboundaryExpanders.InfiniteChains.Complex V) (r : ℕ) : Fintype (X.Face r) := Fintype.ofFinite _ + +omit [DecidableEq V] in +lemma card_faces (X : CoboundaryExpanders.InfiniteChains.Complex V) (r : ℕ) : Fintype.card (X.Face r) = (level X r).card := by + let e : X.Face r ≃ ↥(level X r) := + { toFun := fun s => ⟨s.val, (mem_level X r s.val).mpr s.property⟩ + invFun := fun s => ⟨s.val,(mem_level X r s.val).mp s.property⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + exact (Fintype.card_congr e).trans (Fintype.card_coe _) + +lemma count_incident (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (s : Finset V) : + (Finset.univ.filter (fun t : X.Face N => s ⊆ t.val)).card = cofaces X N s := by + unfold cofaces + apply Finset.card_bij (fun t _ => t.val) + · intro t ht + exact Finset.mem_filter.mpr ⟨(mem_level X N t.val).mpr t.property,(Finset.mem_filter.mp ht).2⟩ + · intro t ht u hu he; exact Subtype.ext he + · intro t ht + refine ⟨⟨t,(mem_level X N t).mp (Finset.mem_filter.mp ht).1⟩,?_,rfl⟩ + simp only [Finset.mem_filter, Finset.mem_univ, true_and] + exact (Finset.mem_filter.mp ht).2 + +variable {G : Type} [Group G] [Fintype G] [DecidableEq G] [MulAction G V] + +omit [DecidableEq G] in +lemma occupancy {X : CoboundaryExpanders.InfiniteChains.Complex V} {N r : ℕ} (hX : Invariant G X) (hP : Pure X N) + (hTrans : ∀ a b : X.Face N, ∃ g : G, g • a.val = b.val) + (hr : r ≤ N) (s : Finset V) (hs : s ∈ level X r) (t : Finset V) : + ((Finset.univ.filter (fun g : G => g • s = t)).card : ℝ) ≤ + Fintype.card G * (N.choose r : ℝ) * weight X N r t := by + classical + by_cases ht : t ∈ level X r + · obtain ⟨a,ha,hsa⟩ := hP.2 s ((mem_level X r s).mp hs).1 + let aa : X.Face N := ⟨a, (mem_level X N a).mp ha⟩ + let : MulAction G (X.Face N) := faceAction hX N + have htrans : ∀ a b : X.Face N, ∃ g : G, g • a = b := by + intro a b + obtain ⟨g,hg⟩ := hTrans a b + exact ⟨g, Subtype.ext hg⟩ + have hi : ∀ (g : G) (a : X.Face N) (b : Finset V), b ⊆ a.val → + g • b ⊆ (g • a).val := by + intro g a b hb + exact Finset.smul_finset_subset_smul_finset hb + have hh := occupation_le_incidence (fun a : X.Face N => fun b : Finset V => b ⊆ a.val) + hi htrans s aa hsa t + rw [card_faces, count_incident] at hh + have hc : 0 < ((level X N).card : ℝ) := Nat.cast_pos.mpr hP.1.card_pos + have hb : (N.choose r : ℝ) ≠ 0 := Nat.cast_ne_zero.mpr (Nat.choose_pos hr).ne' + rw [weight, ite_eq_left ht] + apply le_of_mul_le_mul_left _ hc + calc + ((level X N).card : ℝ) * ((Finset.univ.filter (fun g : G => g • s = t)).card : ℝ) ≤ + Fintype.card G * (cofaces X N t : ℝ) := hh + _ = (level X N).card * (Fintype.card G * (N.choose r : ℝ) * + (cofaces X N t / ((N.choose r : ℝ) * (level X N).card))) := by + field_simp + · have hempty : Finset.univ.filter (fun g : G => g • s = t) = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + intro g hg + have he := (Finset.mem_filter.mp hg).2 + have hmem := (level_smul_iff hX g r s).mpr hs + exact ht (he ▸ hmem) + simp [hempty, weight, ht] + +omit [DecidableEq G] in +theorem weighted_correction {X : CoboundaryExpanders.InfiniteChains.Complex V} {N n r R : ℕ} + (hX : Invariant G X) (hP : Pure X N) + (hTrans : ∀ a b : X.Face N, ∃ g : G, g • a.val = b.val) + (H : BoundedCone X n R) (hr : r ≤ n) (hrN : r+1 ≤ N) + (f : Finset V → k) : + ∃ b : Finset V → k, + supportNorm (weight X N r) (fun s => f s + delta b s) ≤ + (R : ℝ) * (N.choose (r+1) : ℝ) * supportNorm (weight X N (r+1)) (delta f) := by + classical + let L : Finset V → Finset (Finset V) := fun s => + if s ∈ level X r then (H.hom (Finsupp.single s 1)).support else ∅ + have hL (s : Finset V) : (L s).card ≤ R := by + dsimp only [L] + split_ifs with hs + · obtain ⟨hs',he⟩ := (mem_level X r s).mp hs + exact H.bound s hs' (by omega) + · simp + have hLS (s t : Finset V) (ht : t ∈ L s) : t ∈ level X (r+1) := by + dsimp only [L] at ht + split_ifs at ht with hs + · obtain ⟨hs',he⟩ := (mem_level X r s).mp hs + have hh := ((mem_supported _ _).mp (H.support s hs' (by omega))) t (Finsupp.mem_support_iff.mp ht) + exact (mem_level X (r+1) t).mpr ⟨hh.1, by simpa [he] using hh.2⟩ + · simp at ht + obtain ⟨g,hg⟩ := exists_small_dual (G := G) + (weight X N r) (weight_nonneg X N r) (weight_sum X (by omega) hP.1) + (weight X N (r+1)) (weight_nonneg X N (r+1)) + (fun g t => g • t) (N.choose (r+1) : ℝ) (Nat.cast_nonneg _) + L R hL (fun s t ht u => occupancy hX hP hTrans hrN t (hLS s t ht) u) + (delta f) + refine ⟨movedCorrection g H.hom f, ?_⟩ + rw [← norm_pull hX g] + have he : supportNorm (weight X N r) + (pull g (fun s => f s + delta (movedCorrection g H.hom f) s)) = + supportNorm (weight X N r) (fun s => ∑ t ∈ L s, delta f (g • t)) := by + unfold supportNorm + apply Finset.sum_congr rfl + intro s _ + by_cases hs : s ∈ level X r + · obtain ⟨hs',hsr⟩ := (mem_level X r s).mp hs + have hh := movedCorrection_identity H g f s hs' (by omega) + simp only [pull, L, ite_eq_left hs, hh] + · simp [weight, hs] + exact he ▸ hg + +end CoboundaryExpanders.InfiniteChains.FiniteWeights + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Chains.lean b/lean/OAI/Combinatorics/Coboundary/Chains.lean new file mode 100644 index 0000000000000000000000000000000000000000..628fcccf63ac5afe2fb2f26f191eece25d667d78 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Chains.lean @@ -0,0 +1,844 @@ +import Mathlib + +namespace OAI + +/-! +Augmented F2 simplicial chains, boundaries, exactness, and relative attachments. +-/ + +noncomputable section +open scoped BigOperators + +namespace CoboundaryExpanders.InfiniteChains + +section +variable {V : Type} [DecidableEq V] +abbrev k := ZMod 2 + +def rawBoundary : (Finset V →₀ k) →ₗ[k] (Finset V →₀ k) := + Finsupp.linearCombination k (fun s => ∑ v ∈ s, Finsupp.single (s.erase v) 1) + +@[simp] lemma rawBoundary_single (s : Finset V) (r : k) : + rawBoundary (Finsupp.single s r) = ∑ v ∈ s, Finsupp.single (s.erase v) r := by + simp [rawBoundary, Finset.smul_sum] + +lemma rawBoundary_squared : (rawBoundary (V := V)).comp rawBoundary = 0 := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro r + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, rawBoundary_single, map_sum, + LinearMap.zero_apply] + have he : (∑ a ∈ s, ∑ b ∈ s.erase a, Finsupp.single ((s.erase a).erase b) r) = + ∑ x ∈ s.offDiag, Finsupp.single ((s.erase x.1).erase x.2) r := by + have hd : s.offDiag = (s ×ˢ s).filter (fun x => x.1 ≠ x.2) := by + ext x; simp [Finset.mem_offDiag, and_assoc] + rw [hd, Finset.sum_filter, Finset.sum_product] + apply Finset.sum_congr rfl + intro a ha + rw [← Finset.sum_filter] + congr 1 + ext b + simp [Finset.mem_erase, ne_comm, and_comm] + rw [he] + apply Finset.sum_involution (fun x _ => x.swap) + · intro x hx + rw [Finset.erase_right_comm] + ext z + simp only [Finsupp.add_apply] + exact CharTwo.add_self_eq_zero _ + · intro x hx _ heq + exact (Finset.mem_offDiag.mp hx).2.2 (congrArg Prod.fst heq).symm + · intro x _; exact Prod.swap_swap x + · intro x hx + exact Finset.mem_offDiag.mpr ⟨(Finset.mem_offDiag.mp hx).2.1, + (Finset.mem_offDiag.mp hx).1, (Finset.mem_offDiag.mp hx).2.2.symm⟩ + +def rawCone (a : V) : (Finset V →₀ k) →ₗ[k] (Finset V →₀ k) := + Finsupp.linearCombination k (fun s => + if a ∈ s then 0 else Finsupp.single (insert a s) 1) + +@[simp] lemma rawCone_single (a : V) (s : Finset V) (r : k) : + rawCone a (Finsupp.single s r) = + if a ∈ s then 0 else Finsupp.single (insert a s) r := by + by_cases h : a ∈ s <;> simp [rawCone, h] + +lemma raw_contraction (a : V) : + rawBoundary.comp (rawCone a) + (rawCone a).comp rawBoundary = LinearMap.id := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro r + simp only [LinearMap.add_apply, LinearMap.comp_apply, Finsupp.lsingle_apply, + LinearMap.id_apply, rawCone_single, rawBoundary_single, map_sum] + by_cases ha : a ∈ s + · rw [ite_eq_left ha, map_zero, zero_add] + rw [Finset.sum_eq_single a] + · simp [Finset.insert_erase ha] + · intro b hb hba + simp [Finset.mem_erase, Ne.symm hba, ha] + · exact fun h => (h ha).elim + · rw [ite_eq_right ha, rawBoundary_single, Finset.sum_insert ha, Finset.erase_insert ha] + have he : (∑ b ∈ s, Finsupp.single ((insert a s).erase b) r) = + ∑ b ∈ s, Finsupp.single (insert a (s.erase b)) r := by + apply Finset.sum_congr rfl + intro b hb + rw [Finset.erase_insert_of_ne (show a ≠ b from by intro he; subst b; exact ha hb)] + rw [he] + have he' : (∑ b ∈ s, if a ∈ s.erase b then 0 else Finsupp.single (insert a (s.erase b)) r) = + ∑ b ∈ s, Finsupp.single (insert a (s.erase b)) r := by + apply Finset.sum_congr rfl + intro b _ + rw [ite_eq_right (fun h => ha (Finset.mem_of_mem_erase h))] + rw [he', add_assoc] + have hz : (∑ b ∈ s, Finsupp.single (insert a (s.erase b)) r) + + (∑ b ∈ s, Finsupp.single (insert a (s.erase b)) r) = 0 := by + ext z + exact CharTwo.add_self_eq_zero _ + rw [hz, add_zero] + +structure Complex (V : Type) where + faces : Set (Finset V) + empty_mem : ∅ ∈ faces + downward : ∀ {σ τ}, σ ∈ faces → τ ⊆ σ → τ ∈ faces + +namespace Complex +variable (X : CoboundaryExpanders.InfiniteChains.Complex V) +abbrev Face (n : ℕ) := {s : Finset V // s ∈ X.faces ∧ s.card = n} +instance (n : ℕ) : DecidableEq (X.Face n) := Classical.decEq _ +abbrev Chains (n : ℕ) := X.Face n →₀ k + +def erase (n : ℕ) (s : X.Face (n+1)) (v : ↥s.val) : X.Face n := + ⟨s.val.erase v.val, X.downward s.property.1 (Finset.erase_subset _ _), by + rw [Finset.card_erase_of_mem v.property, s.property.2]; omega⟩ + +def boundary (n : ℕ) : X.Chains (n+1) →ₗ[k] X.Chains n := + Finsupp.linearCombination k (fun s => ∑ v : ↥s.val, Finsupp.single (X.erase n s v) 1) + +@[simp] lemma boundary_single (n : ℕ) (s : X.Face (n+1)) (r : k) : + X.boundary n (Finsupp.single s r) = ∑ v : ↥s.val, Finsupp.single (X.erase n s v) r := by + simp [boundary, Finset.smul_sum] + +def embed (n : ℕ) : X.Chains n →ₗ[k] (Finset V →₀ k) := Finsupp.lmapDomain k k Subtype.val + +omit [DecidableEq V] in +@[simp] lemma embed_single (n : ℕ) (s : X.Face n) (r : k) : + X.embed n (Finsupp.single s r) = Finsupp.single s.val r := by + change Finsupp.mapDomain Subtype.val (Finsupp.single s r) = _ + exact Finsupp.mapDomain_single + +omit [DecidableEq V] in +lemma embed_injective (n : ℕ) : Function.Injective (X.embed n) := + Finsupp.mapDomain_injective Subtype.val_injective + +lemma embed_boundary (n : ℕ) : + (X.embed n).comp (X.boundary n) = rawBoundary.comp (X.embed (n+1)) := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro r + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, boundary_single, + map_sum, embed_single, rawBoundary_single] + exact Finset.sum_coe_sort s.val (fun v => Finsupp.single (s.val.erase v) r) + +@[simp] lemma boundary_squared (n : ℕ) : + (X.boundary n).comp (X.boundary (n+1)) = 0 := by + apply LinearMap.ext + intro c + apply X.embed_injective n + change (X.embed n).comp (X.boundary n) (X.boundary (n+1) c) = _ + rw [embed_boundary] + change rawBoundary ((X.embed (n+1)).comp (X.boundary (n+1)) c) = _ + rw [embed_boundary] + change rawBoundary.comp rawBoundary (X.embed (n+2) c) = _ + rw [rawBoundary_squared] + simp + +def IsConePoint (a : V) : Prop := ∀ σ ∈ X.faces, insert a σ ∈ X.faces + +def cone (a : V) (ha : X.IsConePoint a) (n : ℕ) : X.Chains n →ₗ[k] X.Chains (n+1) := + Finsupp.linearCombination k (fun s => if h : a ∈ s.val then 0 else + Finsupp.single ⟨insert a s.val, ha s.val s.property.1, by + rw [Finset.card_insert_of_notMem h, s.property.2]⟩ 1) + +lemma embed_cone (a : V) (ha : X.IsConePoint a) (n : ℕ) : + (X.embed (n+1)).comp (X.cone a ha n) = (rawCone a).comp (X.embed n) := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro r + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, cone, + Finsupp.linearCombination_single, embed_single, rawCone_single] + by_cases h : a ∈ s.val + · rw [dite_eq_left h, smul_zero, map_zero, ite_eq_left h] + · rw [dite_eq_right h, map_smul, embed_single, ite_eq_right h] + simp + +lemma contraction (a : V) (ha : X.IsConePoint a) (n : ℕ) : + (X.boundary (n+1)).comp (X.cone a ha (n+1)) + + (X.cone a ha n).comp (X.boundary n) = LinearMap.id := by + apply LinearMap.ext + intro c + apply X.embed_injective (n+1) + simp only [LinearMap.add_apply, LinearMap.comp_apply, LinearMap.id_apply, map_add] + change (X.embed (n+1)).comp (X.boundary (n+1)) (X.cone a ha (n+1) c) + + (X.embed (n+1)).comp (X.cone a ha n) (X.boundary n c) = _ + rw [embed_boundary, embed_cone] + change rawBoundary ((X.embed (n+2)).comp (X.cone a ha (n+1)) c) + + rawCone a ((X.embed n).comp (X.boundary n) c) = _ + rw [embed_boundary, embed_cone] + exact LinearMap.congr_fun (raw_contraction a) (X.embed (n+1) c) + +lemma boundary_exact_of_cone (a : V) (ha : X.IsConePoint a) (n : ℕ) : + Function.Exact (X.boundary (n+1)) (X.boundary n) := by + intro c + constructor + · intro hc + refine ⟨X.cone a ha (n+1) c, ?_⟩ + have hh := LinearMap.congr_fun (X.contraction a ha n) c + simpa [hc] using hh + · rintro ⟨b,rfl⟩ + exact LinearMap.congr_fun (X.boundary_squared n) b + +open CategoryTheory + +def chainComplex : ChainComplex (ModuleCat k) ℕ := + ChainComplex.of (fun i => ModuleCat.of k (X.Chains (i+1))) + (fun i => ModuleCat.ofHom (X.boundary (i+1))) + (fun i => ModuleCat.hom_ext (X.boundary_squared (i+1))) + +@[simp] lemma chainComplex_d (n : ℕ) : + X.chainComplex.d (n+1) n = ModuleCat.ofHom (X.boundary (n+1)) := by + simp [chainComplex, ChainComplex.of_d] + +lemma chainComplex_exactAt_of_cone (a : V) (ha : X.IsConePoint a) (n : ℕ) : + X.chainComplex.ExactAt (n+1) := by + rw [HomologicalComplex.exactAt_iff' _ (n+2) (n+1) n (by simp) (by simp)] + apply (ShortComplex.ShortExact.moduleCat_exact_iff_function_exact _).mpr + change Function.Exact (X.chainComplex.d (n+2) (n+1)) (X.chainComplex.d (n+1) n) + rw [chainComplex_d, chainComplex_d] + exact (X.boundary_exact_of_cone a ha (n+1)) + +lemma chainComplex_homology_isZero_of_cone (a : V) (ha : X.IsConePoint a) (n : ℕ) : + Limits.IsZero (X.chainComplex.homology (n+1)) := + (HomologicalComplex.exactAt_iff_isZero_homology _ _).mp + (X.chainComplex_exactAt_of_cone a ha n) + +def full (V : Type) : CoboundaryExpanders.InfiniteChains.Complex V where + faces := Set.univ + empty_mem := Set.mem_univ _ + downward := fun _ _ => Set.mem_univ _ + +lemma full_isConePoint (a : V) : (full V).IsConePoint a := fun _ _ => Set.mem_univ _ + +def sumCoefficients (n : ℕ) : X.Chains n →ₗ[k] k := + Finsupp.linearCombination k (fun _ => 1) + +omit [DecidableEq V] in +@[simp] lemma sumCoefficients_single (n : ℕ) (s : X.Face n) (r : k) : + X.sumCoefficients n (Finsupp.single s r) = r := by + simp [sumCoefficients] + +omit [DecidableEq V] in +lemma embed_zero (c : X.Chains 0) : + X.embed 0 c = Finsupp.single ∅ (X.sumCoefficients 0 c) := by + have hh : X.embed 0 = (Finsupp.lsingle ∅).comp (X.sumCoefficients 0) := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro r + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, embed_single, sumCoefficients_single] + have hs : s.val = ∅ := Finset.card_eq_zero.mp s.property.2 + rw [hs] + exact LinearMap.congr_fun hh c + +omit [DecidableEq V] in +lemma sumCoefficients_zero_injective : Function.Injective (X.sumCoefficients 0) := by + intro c d he + apply X.embed_injective 0 + rw [embed_zero, embed_zero, he] + +lemma augmentation_boundary_zero : + (X.sumCoefficients 0).comp (X.boundary 0) = X.sumCoefficients 1 := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro r + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, boundary_single, + map_sum, sumCoefficients_single] + simp [s.property.2] + +lemma augmentation_boundary : + (X.sumCoefficients 1).comp (X.boundary 1) = 0 := by + rw [← augmentation_boundary_zero, LinearMap.comp_assoc, boundary_squared, LinearMap.comp_zero] + +lemma augmentation_exact_of_cone (a : V) (ha : X.IsConePoint a) : + Function.Exact (X.boundary 1) (X.sumCoefficients 1) := by + intro c + rw [← X.augmentation_boundary_zero] + change X.sumCoefficients 0 (X.boundary 0 c) = 0 ↔ _ + rw [← map_zero (X.sumCoefficients 0), X.sumCoefficients_zero_injective.eq_iff] + exact X.boundary_exact_of_cone a ha 0 c + +lemma augmentation_surjective_of_cone (a : V) (ha : X.IsConePoint a) : + Function.Surjective (X.sumCoefficients 1) := by + intro r + let s : X.Face 1 := ⟨{a}, by simpa using ha ∅ X.empty_mem, by simp⟩ + exact ⟨Finsupp.single s r, X.sumCoefficients_single 1 s r⟩ + +end Complex +end + +namespace Attachment +variable {V W : Type} [DecidableEq V] [DecidableEq W] +abbrev Raw (V : Type) := Finset V →₀ k + +def supported (P : Set (Finset V)) : Submodule k (Raw V) := + Finsupp.supported k k P + +omit [DecidableEq V] in +lemma mem_supported (P : Set (Finset V)) (c : Raw V) : + c ∈ supported P ↔ ∀ s, c s ≠ 0 → s ∈ P := by + simp [supported, Finsupp.mem_supported, Set.subset_def, Finsupp.mem_support_iff] + +lemma single_mem_supported {P : Set (Finset V)} {s : Finset V} (hs : s ∈ P) (a : k) : + Finsupp.single s a ∈ supported P := by + rw [mem_supported] + intro t ht + by_cases h : s = t + · simpa [← h] using hs + · exact (ht (Finsupp.single_eq_of_ne (Ne.symm h))).elim + +omit [DecidableEq V] [DecidableEq W] in +lemma map_supported (T : Raw V →ₗ[k] Raw W) (P : Set (Finset V)) (Q : Set (Finset W)) + (h : ∀ s ∈ P, ∀ a : k, T (Finsupp.single s a) ∈ supported Q) + (c : Raw V) (hc : c ∈ supported P) : T c ∈ supported Q := by + rw [← Finsupp.sum_single c, Finsupp.sum, map_sum] + apply Submodule.sum_mem + intro s hs + exact h s ((mem_supported P c).mp hc s (Finsupp.mem_support_iff.mp hs)) (c s) + +def append (F : Finset W) : Raw V →ₗ[k] Raw (W ⊕ V) := + Finsupp.lmapDomain k k (F.disjSum ·) + +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma append_single (F : Finset W) (s : Finset V) (a : k) : + append F (Finsupp.single s a) = Finsupp.single (F.disjSum s) a := + Finsupp.mapDomain_single + +def project (F : Finset W) : Raw (W ⊕ V) →ₗ[k] Raw V := + Finsupp.linearCombination k (fun s => + if s.toLeft = F then Finsupp.single s.toRight 1 else 0) + +omit [DecidableEq V] in +@[simp] lemma project_single (F : Finset W) (s : Finset (W ⊕ V)) (a : k) : + project F (Finsupp.single s a) = + if s.toLeft = F then Finsupp.single s.toRight a else 0 := by + by_cases h : s.toLeft = F <;> simp [project, h] + +omit [DecidableEq V] in +@[simp] lemma project_append (F : Finset W) : + (project (V := V) F).comp (append F) = LinearMap.id := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp + +lemma project_apply (F : Finset W) (c : Raw (W ⊕ V)) (t : Finset V) : + project F c t = c (F.disjSum t) := by + induction c using Finsupp.induction_linear with + | zero => simp + | add c d hc hd => simp only [map_add, Finsupp.add_apply, hc, hd] + | single s a => + simp only [project_single] + by_cases h : s.toLeft = F + · rw [ite_eq_left h] + have he : s = F.disjSum t ↔ s.toRight = t := by + rw [Finset.eq_disjSum_iff] + simp [h] + simp only [Finsupp.single_apply, he] + · rw [ite_eq_right h] + have he : s ≠ F.disjSum t := by + intro he + exact h (by simp [he]) + simp [he] + +def joinFaces (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) : Set (Finset (W ⊕ V)) := + {s | s.toLeft ⊆ F ∧ s.toRight ∈ O.faces} + +def oldFaces (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) : Set (Finset (W ⊕ V)) := + {s | s ∈ joinFaces F O ∧ s.toLeft ≠ F} + +omit [DecidableEq V] [DecidableEq W] in +lemma joinFaces_downward (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) + {s t : Finset (W ⊕ V)} (hs : s ∈ joinFaces F O) (ht : t ⊆ s) : + t ∈ joinFaces F O := + ⟨(Finset.toLeft_subset_toLeft ht).trans hs.1, + O.downward hs.2 (Finset.toRight_subset_toRight ht)⟩ + +omit [DecidableEq V] [DecidableEq W] in +lemma oldFaces_downward (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) + {s t : Finset (W ⊕ V)} (hs : s ∈ oldFaces F O) (ht : t ⊆ s) : + t ∈ oldFaces F O := by + refine ⟨joinFaces_downward F O hs.1 ht, ?_⟩ + intro he + apply hs.2 + apply Finset.Subset.antisymm hs.1.1 + rw [← he] + exact Finset.toLeft_subset_toLeft ht + +lemma project_eq_zero_iff (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (c : Raw (W ⊕ V)) + (hc : c ∈ supported (joinFaces F O)) : + project F c = 0 ↔ c ∈ supported (oldFaces F O) := by + rw [mem_supported] at hc ⊢ + constructor + · intro hz s hs + refine ⟨hc s hs, ?_⟩ + intro he + have he' : F.disjSum s.toRight = s := by + rw [← he, Finset.toLeft_disjSum_toRight] + have := congrArg (fun b : Raw V => b s.toRight) hz + rw [project_apply, he'] at this + exact hs this + · intro h + apply Finsupp.ext + intro t + rw [project_apply] + by_contra he + obtain ⟨_, ht⟩ := h (F.disjSum t) he + exact ht (by simp) + +lemma boundary_supported (P : Set (Finset V)) + (hdown : ∀ {s t}, s ∈ P → t ⊆ s → t ∈ P) + (c : Raw V) (hc : c ∈ supported P) : rawBoundary c ∈ supported P := by + apply map_supported rawBoundary P P _ c hc + intro s hs a + rw [rawBoundary_single] + apply Submodule.sum_mem + intro v hv + exact single_mem_supported (hdown hs (Finset.erase_subset v s)) a + +lemma erase_disjSum_inl (A : Finset W) (B : Finset V) (w : W) : + (A.disjSum B).erase (.inl w) = (A.erase w).disjSum B := by + ext (x | x) <;> simp [Finset.mem_erase] + +lemma erase_disjSum_inr (A : Finset W) (B : Finset V) (v : V) : + (A.disjSum B).erase (.inr v) = A.disjSum (B.erase v) := by + ext (x | x) <;> simp [Finset.mem_erase] + +lemma boundary_disjSum_single (A : Finset W) (B : Finset V) (a : k) : + rawBoundary (Finsupp.single (A.disjSum B) a) = + (∑ w ∈ A, Finsupp.single ((A.erase w).disjSum B) a) + + (∑ v ∈ B, Finsupp.single (A.disjSum (B.erase v)) a) := by + rw [rawBoundary_single, Finset.sum_disjSum] + simp only [erase_disjSum_inl, erase_disjSum_inr] + +lemma project_boundary_single (F : Finset W) (s : Finset (W ⊕ V)) (a : k) + (hs : s.toLeft ⊆ F) : + project F (rawBoundary (Finsupp.single s a)) = + rawBoundary (project F (Finsupp.single s a)) := by + conv_lhs => rw [← Finset.toLeft_disjSum_toRight (u := s)] + rw [boundary_disjSum_single, map_add, map_sum, map_sum] + have hleft : (∑ w ∈ s.toLeft, + project F (Finsupp.single ((s.toLeft.erase w).disjSum s.toRight) a)) = 0 := by + apply Finset.sum_eq_zero + intro w hw + have he : s.toLeft.erase w ≠ F := by + intro he + have hf : w ∈ s.toLeft.erase w := he ▸ hs hw + exact Finset.notMem_erase w s.toLeft hf + simp [he] + rw [hleft, zero_add, project_single] + by_cases he : s.toLeft = F + · simp only [he, Finset.toLeft_disjSum, Finset.toRight_disjSum, project_single, + ite_true, rawBoundary_single] + · simp only [project_single, Finset.toLeft_disjSum, he, ite_false, map_zero, + Finset.sum_const_zero] + +lemma project_boundary (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (c : Raw (W ⊕ V)) + (hc : c ∈ supported (joinFaces F O)) : + project F (rawBoundary c) = rawBoundary (project F c) := by + rw [← Finsupp.sum_single c, Finsupp.sum, map_sum, map_sum, map_sum, map_sum] + apply Finset.sum_congr rfl + intro s hs + exact project_boundary_single F s (c s) + (((mem_supported _ c).mp hc s (Finsupp.mem_support_iff.mp hs)).1) + +lemma append_supported (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (c : Raw V) + (hc : c ∈ supported O.faces) : append F c ∈ supported (joinFaces F O) := by + apply map_supported (append F) O.faces (joinFaces F O) _ c hc + intro s hs a + rw [append_single] + apply single_mem_supported + exact ⟨by simp, by simpa using hs⟩ + +lemma project_supported (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (c : Raw (W ⊕ V)) + (hc : c ∈ supported (joinFaces F O)) : project F c ∈ supported O.faces := by + apply map_supported (project F) (joinFaces F O) O.faces _ c hc + intro s hs a + rw [project_single] + split_ifs + · exact single_mem_supported hs.2 a + · exact Submodule.zero_mem _ + +def graded (P : Set (Finset V)) (n : ℕ) : Set (Finset V) := + {s | s ∈ P ∧ s.card = n} + +omit [DecidableEq V] in +lemma supported_mono {P Q : Set (Finset V)} (h : P ⊆ Q) : + supported P ≤ supported Q := by + intro c hc + rw [mem_supported] at hc ⊢ + exact fun s hs => h (hc s hs) + +omit [DecidableEq V] in +lemma graded_forget (P : Set (Finset V)) (n : ℕ) : + supported (graded P n) ≤ supported P := + supported_mono (fun _ hs => hs.1) + +lemma boundary_graded (P : Set (Finset V)) + (hdown : ∀ {s t}, s ∈ P → t ⊆ s → t ∈ P) (n : ℕ) + (c : Raw V) (hc : c ∈ supported (graded P (n+1))) : + rawBoundary c ∈ supported (graded P n) := by + apply map_supported rawBoundary (graded P (n+1)) (graded P n) _ c hc + intro s hs a + rw [rawBoundary_single] + apply Submodule.sum_mem + intro v hv + apply single_mem_supported + refine ⟨hdown hs.1 (Finset.erase_subset v s), ?_⟩ + rw [Finset.card_erase_of_mem hv, hs.2] + omega + +lemma append_graded (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) + (c : Raw V) (hc : c ∈ supported (graded O.faces n)) : + append F c ∈ supported (graded (joinFaces F O) (F.card+n)) := by + apply map_supported (append F) (graded O.faces n) + (graded (joinFaces F O) (F.card+n)) _ c hc + intro s hs a + rw [append_single] + apply single_mem_supported + refine ⟨⟨by simp, by simpa using hs.1⟩, ?_⟩ + simp [hs.2] + +lemma project_graded (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) + (c : Raw (W ⊕ V)) (hc : c ∈ supported (graded (joinFaces F O) (F.card+n))) : + project F c ∈ supported (graded O.faces n) := by + rw [mem_supported] at hc ⊢ + intro t ht + rw [project_apply] at ht + obtain ⟨hs, hn⟩ := hc (F.disjSum t) ht + refine ⟨by simpa using hs.2, ?_⟩ + simp only [Finset.card_disjSum] at hn + omega + +def ExactIn (P : Set (Finset V)) (n : ℕ) : Prop := + ∀ c ∈ supported (graded P n), rawBoundary c = 0 → + ∃ b ∈ supported (graded P (n+1)), rawBoundary b = c + +theorem relative_filling (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) + (hO : ExactIn O.faces n) + (c : Raw (W ⊕ V)) + (hc : c ∈ supported (graded (joinFaces F O) (F.card+n))) + (hδ : rawBoundary c ∈ supported (oldFaces F O)) : + ∃ b ∈ supported (graded (joinFaces F O) (F.card+n+1)), + c - rawBoundary b ∈ supported (graded (oldFaces F O) (F.card+n)) := by + have hc' := graded_forget (joinFaces F O) (F.card+n) hc + have hδ' := boundary_supported (joinFaces F O) (joinFaces_downward F O) c hc' + have hz : rawBoundary (project F c) = 0 := by + rw [← project_boundary F O c hc'] + exact (project_eq_zero_iff F O (rawBoundary c) hδ').mpr hδ + obtain ⟨b, hb, hbc⟩ := hO (project F c) (project_graded F O n c hc) hz + have hab : append F b ∈ supported (graded (joinFaces F O) (F.card+n+1)) := by + simpa [Nat.add_assoc] using append_graded F O (n+1) b hb + refine ⟨append F b, hab, ?_⟩ + have hDB := boundary_graded (joinFaces F O) (joinFaces_downward F O) + (F.card+n) (append F b) hab + have hsub := (supported (graded (joinFaces F O) (F.card+n))).sub_mem hc hDB + have hsub' := graded_forget (joinFaces F O) (F.card+n) hsub + have hzero : project F (c - rawBoundary (append F b)) = 0 := by + rw [map_sub, project_boundary F O (append F b) + (graded_forget (joinFaces F O) (F.card+n+1) hab)] + have hep : project F (append F b) = b := + congrArg (fun f : Raw V →ₗ[k] Raw V => f b) (project_append F) + rw [hep, hbc, sub_self] + have hold := (project_eq_zero_iff F O _ hsub').mp hzero + rw [mem_supported] at hsub hold ⊢ + exact fun s hs => ⟨hold s hs, (hsub s hs).2⟩ + +omit [DecidableEq V] [DecidableEq W] in +lemma low_degree_old (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) (hn : n < F.card) + (c : Raw (W ⊕ V)) (hc : c ∈ supported (graded (joinFaces F O) n)) : + c ∈ supported (graded (oldFaces F O) n) := by + rw [mem_supported] at hc ⊢ + intro s hs + obtain ⟨hface, hcard⟩ := hc s hs + refine ⟨⟨hface, ?_⟩, hcard⟩ + intro he + have h := Finset.card_toLeft_add_card_toRight (u := s) + rw [he, hcard] at h + omega + +def RelativeExactIn (P Q : Set (Finset V)) (n : ℕ) : Prop := + ∀ c ∈ supported (graded Q n), rawBoundary c ∈ supported P → + ∃ b ∈ supported (graded Q (n+1)), + c - rawBoundary b ∈ supported (graded P n) + +lemma relativeExactIn_join (F : Finset W) (O : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) + (hO : F.card ≤ n → ExactIn O.faces (n-F.card)) : + RelativeExactIn (oldFaces F O) (joinFaces F O) n := by + intro c hc hδ + by_cases hn : F.card ≤ n + · have he : F.card + (n-F.card) = n := Nat.add_sub_of_le hn + simpa only [he] using relative_filling F O (n-F.card) (hO hn) c + (by simpa only [he] using hc) hδ + · refine ⟨0, Submodule.zero_mem _, ?_⟩ + simpa using (low_degree_old F O n (by omega) c hc) + +omit [DecidableEq V] in +lemma finite_stage (P : ℕ → Set (Finset V)) (hP : Monotone P) (n : ℕ) + (c : Raw V) (hc : c ∈ supported (graded (⋃ m, P m) n)) : + ∃ m, c ∈ supported (graded (P m) n) := by + have hdir : Directed (· ⊆ ·) P := fun i j => + ⟨max i j, hP (le_max_left i j), hP (le_max_right i j)⟩ + have hs : (c.support : Set (Finset V)) ⊆ ⋃ m, P m := by + intro s hs + exact ((mem_supported _ c).mp hc s (Finsupp.mem_support_iff.mp hs)).1 + obtain ⟨m, hm⟩ := hdir.exists_mem_subset_of_finset_subset_biUnion hs + refine ⟨m, ?_⟩ + rw [mem_supported] at hc ⊢ + exact fun s hs => ⟨hm (Finsupp.mem_support_iff.mpr hs), (hc s hs).2⟩ + +lemma push_filling (P Q : Set (Finset V)) (n : ℕ) + (hPQ : RelativeExactIn P Q (n+1)) + (b : Raw V) (hb : b ∈ supported (graded Q (n+1))) + (hδ : rawBoundary b ∈ supported P) : + ∃ a ∈ supported (graded P (n+1)), rawBoundary a = rawBoundary b := by + obtain ⟨e, _, he⟩ := hPQ b hb hδ + refine ⟨b - rawBoundary e, he, ?_⟩ + rw [map_sub] + have hh := LinearMap.congr_fun (rawBoundary_squared (V := V)) e + change rawBoundary (rawBoundary e) = 0 at hh + rw [hh, sub_zero] + +theorem exactIn_initial_of_filtration (P : ℕ → Set (Finset V)) + (hP : Monotone P) (n : ℕ) + (hstep : ∀ m, RelativeExactIn (P m) (P (m+1)) (n+1)) + (hunion : ExactIn (⋃ m, P m) n) : ExactIn (P 0) n := by + intro c hc hcz + have hcu : c ∈ supported (graded (⋃ m, P m) n) := + supported_mono (P := graded (P 0) n) (Q := graded (⋃ m, P m) n) + (fun s hs => ⟨Set.mem_iUnion.mpr ⟨0, hs.1⟩, hs.2⟩) hc + obtain ⟨b, hb, hbc⟩ := hunion c hcu hcz + obtain ⟨m, hbm⟩ := finite_stage P hP (n+1) b hb + have hdesc : ∀ m, ∀ b ∈ supported (graded (P m) (n+1)), rawBoundary b = c → + ∃ a ∈ supported (graded (P 0) (n+1)), rawBoundary a = c := by + intro m + induction m with + | zero => exact fun b hb hbc => ⟨b, hb, hbc⟩ + | succ m ih => + intro b hb hbc + have hδ : rawBoundary b ∈ supported (P m) := by + rw [hbc] + exact supported_mono (hP (Nat.zero_le m)) (graded_forget (P 0) n hc) + obtain ⟨a, ha, hab⟩ := push_filling (P m) (P (m+1)) n (hstep m) b hb hδ + exact ih a ha (hab.trans hbc) + exact hdesc m b hbm hbc + +omit [DecidableEq V] in +lemma embed_supported_equiv (X : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) (c : X.Chains n) : + X.embed n c = ((Finsupp.supportedEquivFinsupp (R := k) + (graded X.faces n)).symm c : Raw V) := by + let e := Finsupp.supportedEquivFinsupp (M := k) (R := k) (graded X.faces n) + have he : X.embed n = (Finsupp.supported k k (graded X.faces n)).subtype.comp + e.symm.toLinearMap := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, + CoboundaryExpanders.InfiniteChains.Complex.embed_single] + exact (Finsupp.supportedEquivFinsupp_symm_single (R := k) (graded X.faces n) s a).symm + exact LinearMap.congr_fun he c + +omit [DecidableEq V] in +lemma embed_mem_graded (X : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) (c : X.Chains n) : + X.embed n c ∈ supported (graded X.faces n) := by + rw [embed_supported_equiv] + exact ((Finsupp.supportedEquivFinsupp (R := k) (graded X.faces n)).symm c).property + +omit [DecidableEq V] in +lemma exists_embed_of_mem_graded (X : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) (c : Raw V) + (hc : c ∈ supported (graded X.faces n)) : ∃ b : X.Chains n, X.embed n b = c := by + let e := Finsupp.supportedEquivFinsupp (M := k) (R := k) (graded X.faces n) + have hc' : c ∈ Finsupp.supported k k (graded X.faces n) := hc + refine ⟨e ⟨c, hc'⟩, ?_⟩ + exact (embed_supported_equiv X n _).trans + (congrArg Subtype.val (e.symm_apply_apply ⟨c, hc'⟩)) + +lemma exactIn_iff_boundary_exact (X : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) : + ExactIn X.faces (n+1) ↔ Function.Exact (X.boundary (n+1)) (X.boundary n) := by + constructor + · intro h c + constructor + · intro hc + have hz : rawBoundary (X.embed (n+1) c) = 0 := by + calc + rawBoundary (X.embed (n+1) c) = X.embed n (X.boundary n c) := + (LinearMap.congr_fun (X.embed_boundary n) c).symm + _ = 0 := by rw [hc, map_zero] + obtain ⟨b, hb, hbc⟩ := h _ (embed_mem_graded X (n+1) c) hz + obtain ⟨a, rfl⟩ := exists_embed_of_mem_graded X (n+2) b hb + refine ⟨a, X.embed_injective (n+1) ?_⟩ + exact (LinearMap.congr_fun (X.embed_boundary (n+1)) a).trans hbc + · rintro ⟨b, rfl⟩ + exact LinearMap.congr_fun (X.boundary_squared n) b + · intro h c hc hz + obtain ⟨a, rfl⟩ := exists_embed_of_mem_graded X (n+1) c hc + have ha : X.boundary n a = 0 := by + apply X.embed_injective n + rw [map_zero] + exact (LinearMap.congr_fun (X.embed_boundary n) a).trans hz + obtain ⟨b, hb⟩ := (h a).mp ha + refine ⟨X.embed (n+2) b, embed_mem_graded X (n+2) b, ?_⟩ + calc + rawBoundary (X.embed (n+2) b) = X.embed (n+1) (X.boundary (n+1) b) := + (LinearMap.congr_fun (X.embed_boundary (n+1)) b).symm + _ = X.embed (n+1) a := congrArg (X.embed (n+1)) hb + +lemma chainComplex_exactAt_of_exactIn (X : CoboundaryExpanders.InfiniteChains.Complex V) (n : ℕ) + (h : ExactIn X.faces (n+2)) : X.chainComplex.ExactAt (n+1) := by + rw [HomologicalComplex.exactAt_iff' _ (n+2) (n+1) n (by simp) (by simp)] + apply (CategoryTheory.ShortComplex.ShortExact.moduleCat_exact_iff_function_exact _).mpr + change Function.Exact (X.chainComplex.d (n+2) (n+1)) (X.chainComplex.d (n+1) n) + rw [CoboundaryExpanders.InfiniteChains.Complex.chainComplex_d, CoboundaryExpanders.InfiniteChains.Complex.chainComplex_d] + exact (exactIn_iff_boundary_exact X (n+1)).mp h + +omit [DecidableEq V] in +lemma split_union (A B : Set (Finset V)) (n : ℕ) (c : Raw V) + (hc : c ∈ supported (graded (A ∪ B) n)) : + ∃ a ∈ supported (graded A n), ∃ b ∈ supported (graded B n), c = a+b := by + classical + refine ⟨c.filter (· ∈ A), ?_, c.filter (· ∉ A), ?_, ?_⟩ + · rw [mem_supported] + intro s hs + have ha : s ∈ A := by + by_contra hn + exact hs (Finsupp.filter_apply_neg _ _ hn) + have hs' : c s ≠ 0 := by simpa [Finsupp.filter_apply, ha] using hs + exact ⟨ha, ((mem_supported _ c).mp hc s hs').2⟩ + · rw [mem_supported] + intro s hs + have ha : s ∉ A := by + intro hy + exact hs (by simp [hy]) + have hs' : c s ≠ 0 := by simpa [Finsupp.filter_apply, ha] using hs + obtain ⟨hAB, hn⟩ := (mem_supported _ c).mp hc s hs' + exact ⟨hAB.resolve_left ha, hn⟩ + · exact (Finsupp.filter_add_filter_not c (· ∈ A)).symm + +lemma boundary_piece_supported (P A B : Set (Finset V)) + (hAB : A ∩ B ⊆ P) (a b : Raw V) + (ha : rawBoundary a ∈ supported A) (hb : rawBoundary b ∈ supported B) + (hab : rawBoundary (a+b) ∈ supported P) : rawBoundary a ∈ supported P := by + rw [mem_supported] at ha hb hab ⊢ + intro s hs + by_contra hp + have hz : rawBoundary (a+b) s = 0 := by + by_contra he + exact hp (hab s he) + have hs' : rawBoundary b s ≠ 0 := by + intro hbz + rw [map_add, Finsupp.add_apply, hbz, add_zero] at hz + exact hs hz + exact hp (hAB ⟨ha s hs, hb s hs'⟩) + +lemma relativeExactIn_union (P A B : Set (Finset V)) (n : ℕ) + (hA : ∀ {s t}, s ∈ A → t ⊆ s → t ∈ A) + (hB : ∀ {s t}, s ∈ B → t ⊆ s → t ∈ B) + (hAB : A ∩ B ⊆ P) + (hPA : RelativeExactIn P A n) (hPB : RelativeExactIn P B n) : + RelativeExactIn P (A ∪ B) n := by + intro c hc hδ + obtain ⟨a, ha, b, hb, rfl⟩ := split_union A B n c hc + have hda := boundary_supported A hA a (graded_forget A n ha) + have hdb := boundary_supported B hB b (graded_forget B n hb) + have had := boundary_piece_supported P A B hAB a b hda hdb hδ + have hbd : rawBoundary b ∈ supported P := by + have he : rawBoundary b = rawBoundary (a+b) - rawBoundary a := by + rw [map_add]; abel + rw [he] + exact (supported P).sub_mem hδ had + obtain ⟨ea, hea, hae⟩ := hPA a ha had + obtain ⟨eb, heb, hbe⟩ := hPB b hb hbd + refine ⟨ea+eb, ?_, ?_⟩ + · apply Submodule.add_mem + · exact supported_mono (P := graded A (n+1)) (Q := graded (A ∪ B) (n+1)) + (fun s hs => ⟨Or.inl hs.1, hs.2⟩) hea + · exact supported_mono (P := graded B (n+1)) (Q := graded (A ∪ B) (n+1)) + (fun s hs => ⟨Or.inr hs.1, hs.2⟩) heb + · have he : a+b-rawBoundary (ea+eb) = (a-rawBoundary ea)+(b-rawBoundary eb) := by + rw [map_add]; abel + rw [he] + exact Submodule.add_mem _ hae hbe + +lemma relativeExactIn_empty (P : Set (Finset V)) (n : ℕ) : + RelativeExactIn P ∅ n := by + intro c hc _ + have hz : c = 0 := by + ext s + by_contra hs + exact ((mem_supported _ c).mp hc s hs).1 + subst c + exact ⟨0, Submodule.zero_mem _, by simp⟩ + +lemma relativeExactIn_finite_union {ι : Type*} (P : Set (Finset V)) + (A : ι → Set (Finset V)) (n : ℕ) + (hA : ∀ i, ∀ {s t}, s ∈ A i → t ⊆ s → t ∈ A i) + (hAB : ∀ i j, i ≠ j → A i ∩ A j ⊆ P) + (hPA : ∀ i, RelativeExactIn P (A i) n) (I : Finset ι) : + RelativeExactIn P (⋃ i ∈ I, A i) n := by + classical + induction I using Finset.induction_on with + | empty => simpa using relativeExactIn_empty P n + | @insert i I hi ih => + rw [Finset.set_biUnion_insert] + apply relativeExactIn_union P (A i) (⋃ j ∈ I, A j) n (hA i) _ _ (hPA i) ih + · intro s t hs ht + obtain ⟨j, hj, hs⟩ := Set.mem_iUnion₂.mp hs + exact Set.mem_iUnion₂.mpr ⟨j, hj, hA j hs ht⟩ + · intro s hs + obtain ⟨j, hj, hjs⟩ := Set.mem_iUnion₂.mp hs.2 + exact hAB i j (by intro he; exact hi (he ▸ hj)) ⟨hs.1, hjs⟩ + +theorem relativeExactIn_iUnion {ι : Type*} (P : Set (Finset V)) + (A : ι → Set (Finset V)) (n : ℕ) + (hA : ∀ i, ∀ {s t}, s ∈ A i → t ⊆ s → t ∈ A i) + (hAB : ∀ i j, i ≠ j → A i ∩ A j ⊆ P) + (hPA : ∀ i, RelativeExactIn P (A i) n) : + RelativeExactIn P (⋃ i, A i) n := by + classical + intro c hc hδ + have hs : (c.support : Set (Finset V)) ⊆ ⋃ i, A i := by + intro s hs + exact ((mem_supported _ c).mp hc s (Finsupp.mem_support_iff.mp hs)).1 + obtain ⟨I, hI, hcs⟩ := Set.finite_subset_iUnion c.support.finite_toSet hs + have hci : c ∈ supported (graded (⋃ i ∈ hI.toFinset, A i) n) := by + rw [mem_supported] at hc ⊢ + intro s hs + refine ⟨?_, (hc s hs).2⟩ + simpa only [hI.mem_toFinset] using hcs (Finsupp.mem_support_iff.mpr hs) + obtain ⟨b, hb, hbc⟩ := relativeExactIn_finite_union P A n hA hAB hPA hI.toFinset c hci hδ + refine ⟨b, ?_, hbc⟩ + apply supported_mono (P := graded (⋃ i ∈ hI.toFinset, A i) (n+1)) _ hb + intro s hs + obtain ⟨i, _, his⟩ := Set.mem_iUnion₂.mp hs.1 + exact ⟨Set.mem_iUnion.mpr ⟨i, his⟩, hs.2⟩ + +end Attachment +end CoboundaryExpanders.InfiniteChains + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Complex.lean b/lean/OAI/Combinatorics/Coboundary/Complex.lean new file mode 100644 index 0000000000000000000000000000000000000000..99a375f2fe64793b9581bb9c0612100e5f05bce8 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Complex.lean @@ -0,0 +1,790 @@ +import Mathlib + +namespace OAI + +noncomputable section + +/-! +Finite pure complexes, weighted F2 norms, distance to actual coboundaries, and the full main statement. +-/ + +section +open scoped BigOperators +open Filter + +namespace CoboundaryExpanders + +/-- A finite abstract simplicial complex, including its empty face. Every +labelled vertex is a vertex of the complex, so unused labels are disallowed. -/ +structure Complex where + vertexCount : ℕ + faces : Finset (Finset (Fin vertexCount)) + empty_mem : ∅ ∈ faces + downward : ∀ {σ τ}, σ ∈ faces → τ ⊆ σ → τ ∈ faces + vertex_mem : ∀ v, {v} ∈ faces + +namespace Complex + +/-- Faces of dimension `i`, i.e. with exactly `i+1` vertices. -/ +def facesOf (X : Complex) (i : ℕ) : Finset (Finset (Fin X.vertexCount)) := + X.faces.filter (fun σ => σ.card = i + 1) + +def Face (X : Complex) (i : ℕ) := {σ // σ ∈ X.facesOf i} + +instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := Subtype.fintype _ +instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := Classical.decEq _ + +/-- Nonempty top face set and every face contained in an `s`-face: exact purity. -/ +def Pure (X : Complex) (s : ℕ) : Prop := + (X.facesOf s).Nonempty ∧ + ∀ σ ∈ X.faces, ∃ τ ∈ X.facesOf s, σ ⊆ τ + +/-- Connectedness of the one-skeleton, including nonemptiness. -/ +def Connected (X : Complex) : Prop := + Nonempty (Fin X.vertexCount) ∧ + ∀ v w : Fin X.vertexCount, + Relation.ReflTransGen (fun a b => a ≠ b ∧ {a, b} ∈ X.faces) v w + +abbrev Cochain (X : Complex) (i : ℕ) := X.Face i → ZMod 2 + +/-- Source equation (weights), with ambient pure dimension `s`. -/ +def weight (X : Complex) (s i : ℕ) (σ : X.Face i) : ℝ := + (((X.facesOf s).filter (fun τ => σ.val ⊆ τ)).card : ℝ) / + ((Nat.choose (s + 1) (i + 1) : ℝ) * (X.facesOf s).card) + +/-- The source's weighted support norm, not the unweighted Hamming norm. -/ +def norm (X : Complex) (s i : ℕ) (f : X.Cochain i) : ℝ := + ∑ σ : X.Face i, if f σ ≠ 0 then X.weight s i σ else 0 + +/-- Simplicial coboundary with coefficients in F₂. -/ +def coboundary (X : Complex) (i : ℕ) (f : X.Cochain i) : X.Cochain (i + 1) := + fun τ => ∑ σ : X.Face i, if σ.val ⊆ τ.val then f σ else 0 + +/-- Actual coboundaries; in degree zero use constants, as in the manuscript. -/ +def coboundaries (X : Complex) : (i : ℕ) → Set (X.Cochain i) + | 0 => {f | ∃ c : ZMod 2, f = fun _ => c} + | i + 1 => Set.range (X.coboundary i) + +def cocycles (X : Complex) (i : ℕ) : Set (X.Cochain i) := + {f | X.coboundary i f = 0} + +/-- Distance in the source norm. On a nonempty subspace of this finite cochain +space the infimum is a minimum; no closure or cocycle relaxation is used. -/ +def distance (X : Complex) (s i : ℕ) (f : X.Cochain i) + (A : Set (X.Cochain i)) : ℝ := + sInf ((fun a => X.norm s i (f - a)) '' A) + +/-- Number of top-dimensional faces incident to the given vertex. -/ +def topDegree (X : Complex) (s : ℕ) (v : Fin X.vertexCount) : ℕ := + ((X.facesOf s).filter (fun τ => v ∈ τ)).card + +end Complex + +/-- The complete main assertion `thm:main`. Both constants are chosen outside +all three quantifiers `m`, `i`, and `f`. Vertex growth is convergence to infinity, +not mere existence of one arbitrarily large complex. -/ +def MainStatement : Prop := + ∀ d : ℕ, 3 ≤ d → + ∃ (D : ℕ) (ε : ℝ), 0 < ε ∧ + ∃ X : ℕ → Complex, + (∀ m, (X m).Pure d ∧ (X m).Connected) ∧ + Tendsto (fun m => ((X m).facesOf 0).card) atTop atTop ∧ + (∀ m (v : Fin (X m).vertexCount), (X m).topDegree d v ≤ D) ∧ + ∀ m i, i < d → ∀ f : (X m).Cochain i, + ε * (X m).distance d i f ((X m).coboundaries i) ≤ + (X m).norm d (i + 1) ((X m).coboundary i f) + +end CoboundaryExpanders + +end + +open CategoryTheory +open scoped BigOperators +open CategoryTheory Finsupp +open CategoryTheory Finsupp MonoidalCategory +open scoped BigOperators Matrix +open scoped Matrix +open scoped MonoidAlgebra +open CategoryTheory CategoryTheory.Limits +open Filter + +namespace CoboundaryExpanders.Complex + +attribute [reducible] Face + +local instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i + +@[simp] theorem mem_facesOf (X : Complex) (i : ℕ) (σ) : + σ ∈ X.facesOf i ↔ σ ∈ X.faces ∧ σ.card = i + 1 := by + simp [facesOf] + +@[simp] theorem face_card {X : Complex} {i : ℕ} (σ : X.Face i) : + σ.val.card = i + 1 := (mem_facesOf X i _).1 σ.property |>.2 + +theorem face_mem {X : Complex} {i : ℕ} (σ : X.Face i) : + σ.val ∈ X.faces := (mem_facesOf X i _).1 σ.property |>.1 + +theorem weight_nonneg (X : Complex) (s i : ℕ) (σ : X.Face i) : + 0 ≤ X.weight s i σ := by + exact div_nonneg (Nat.cast_nonneg _) (mul_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + +theorem weight_pos {X : Complex} {s i : ℕ} (hX : X.Pure s) (hi : i ≤ s) + (σ : X.Face i) : 0 < X.weight s i σ := by + obtain ⟨τ, hτ, hστ⟩ := hX.2 σ.val (face_mem σ) + have hn : 0 < ((X.facesOf s).filter (fun τ => σ.val ⊆ τ)).card := + Finset.card_pos.mpr ⟨τ, Finset.mem_filter.mpr ⟨hτ, hστ⟩⟩ + exact div_pos (Nat.cast_pos.mpr hn) + (mul_pos (Nat.cast_pos.mpr (Nat.choose_pos (Nat.succ_le_succ hi))) + (Nat.cast_pos.mpr hX.1.card_pos)) + +@[simp] theorem norm_zero (X : Complex) (s i : ℕ) : X.norm s i 0 = 0 := by + simp [norm] + +theorem norm_nonneg (X : Complex) (s i : ℕ) (f : X.Cochain i) : + 0 ≤ X.norm s i f := by + apply Finset.sum_nonneg + intro σ _ + split_ifs + · exact X.weight_nonneg s i σ + · exact le_rfl + +theorem norm_eq_zero_iff {X : Complex} {s i : ℕ} (hX : X.Pure s) (hi : i ≤ s) + (f : X.Cochain i) : X.norm s i f = 0 ↔ f = 0 := by + constructor + · intro hf + ext σ + change f σ = 0 + by_contra hσ + have hle : X.weight s i σ ≤ X.norm s i f := by + have := Finset.single_le_sum (f := fun ρ : X.Face i => + if f ρ ≠ 0 then X.weight s i ρ else 0) + (fun ρ (_ : ρ ∈ Finset.univ) => by + split_ifs + · exact X.weight_nonneg s i ρ + · exact le_rfl) (Finset.mem_univ σ) + simpa only [norm, ite_eq_left hσ] using this + exact (not_le_of_gt (weight_pos hX hi σ)) (hf ▸ hle) + · rintro rfl + exact X.norm_zero s i + +@[simp] theorem coboundary_zero (X : Complex) (i : ℕ) : X.coboundary i 0 = 0 := by + ext τ + simp [coboundary] + +@[simp] theorem coboundary_add (X : Complex) (i : ℕ) (f g : X.Cochain i) : + X.coboundary i (f + g) = X.coboundary i f + X.coboundary i g := by + ext τ + simp only [coboundary, Pi.add_apply, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro σ _ + split_ifs <;> simp + +@[simp] theorem coboundary_smul (X : Complex) (i : ℕ) (c : ZMod 2) (f : X.Cochain i) : + X.coboundary i (c • f) = c • X.coboundary i f := by + ext τ + simp only [coboundary, Pi.smul_apply, Finset.smul_sum] + apply Finset.sum_congr rfl + intro σ _ + split_ifs <;> simp + +def coboundaryLinear (X : Complex) (i : ℕ) : X.Cochain i →ₗ[ZMod 2] X.Cochain (i + 1) where + toFun := X.coboundary i + map_add' := X.coboundary_add i + map_smul' := X.coboundary_smul i + +@[simp] theorem zero_mem_coboundaries (X : Complex) (i : ℕ) : + 0 ∈ X.coboundaries i := by + cases i with + | zero => exact ⟨0, rfl⟩ + | succ i => exact ⟨0, X.coboundary_zero i⟩ + +theorem coboundaries_nonempty (X : Complex) (i : ℕ) : + (X.coboundaries i).Nonempty := ⟨0, X.zero_mem_coboundaries i⟩ + +theorem distance_attained (X : Complex) (s i : ℕ) (f : X.Cochain i) + (A : Set (X.Cochain i)) (hA : A.Nonempty) : + ∃ a ∈ A, X.distance s i f A = X.norm s i (f - a) := by + have hfin : (((fun a => X.norm s i (f - a)) '' A) : Set ℝ).Finite := + (Set.toFinite A).image _ + obtain ⟨a, ha, heq⟩ := (hA.image (fun a => X.norm s i (f - a))).csInf_mem hfin + exact ⟨a, ha, heq.symm⟩ + +theorem distance_nonneg (X : Complex) (s i : ℕ) (f : X.Cochain i) + (A : Set (X.Cochain i)) (hA : A.Nonempty) : + 0 ≤ X.distance s i f A := by + obtain ⟨a, _, ha⟩ := X.distance_attained s i f A hA + rw [ha] + exact X.norm_nonneg s i (f - a) + +theorem distance_le_norm (X : Complex) (s i : ℕ) (f : X.Cochain i) + {A : Set (X.Cochain i)} {a : X.Cochain i} (ha : a ∈ A) : + X.distance s i f A ≤ X.norm s i (f - a) := by + apply csInf_le + · exact ⟨0, by rintro _ ⟨b, _, rfl⟩; exact X.norm_nonneg s i (f - b)⟩ + · exact ⟨a, ha, rfl⟩ + +theorem distance_eq_zero_iff {X : Complex} {s i : ℕ} (hX : X.Pure s) (hi : i ≤ s) + (f : X.Cochain i) {A : Set (X.Cochain i)} (hA : A.Nonempty) : + X.distance s i f A = 0 ↔ f ∈ A := by + constructor + · intro h + obtain ⟨a, ha, hfa⟩ := X.distance_attained s i f A hA + have heq : f - a = 0 := (norm_eq_zero_iff hX hi _).mp (hfa.symm.trans h) + exact sub_eq_zero.mp heq ▸ ha + · intro hf + apply le_antisymm + · simpa using X.distance_le_norm s i f hf + · exact X.distance_nonneg s i f A hA + +theorem cocycle_mem_coboundaries_of_expansion {X : Complex} {s i : ℕ} + (hX : X.Pure s) (hi : i ≤ s) {ε : ℝ} (hε : 0 < ε) + (hexp : ∀ f : X.Cochain i, + ε * X.distance s i f (X.coboundaries i) ≤ X.norm s (i + 1) (X.coboundary i f)) + {f : X.Cochain i} (hf : f ∈ X.cocycles i) : f ∈ X.coboundaries i := by + have he := hexp f + change X.coboundary i f = 0 at hf + rw [hf, X.norm_zero] at he + have hd : X.distance s i f (X.coboundaries i) = 0 := + le_antisymm (by nlinarith) + (X.distance_nonneg s i f _ (X.coboundaries_nonempty i)) + exact (distance_eq_zero_iff hX hi f (X.coboundaries_nonempty i)).mp hd + +theorem card_between_faces {X : Complex} {i j k : ℕ} + (σ : X.Face i) (τ : X.Face k) (hστ : σ.val ⊆ τ.val) (hij : i ≤ j) : + (Finset.univ.filter (fun ρ : X.Face j => + σ.val ⊆ ρ.val ∧ ρ.val ⊆ τ.val)).card = + Nat.choose ((k + 1) - (i + 1)) ((j + 1) - (i + 1)) := by + classical + have himage : + (Finset.univ.filter (fun ρ : X.Face j => + σ.val ⊆ ρ.val ∧ ρ.val ⊆ τ.val)).image Subtype.val = + (τ.val.powersetCard (j + 1)).filter (σ.val ⊆ ·) := by + ext ρ + simp only [Finset.mem_image, Finset.mem_filter, Finset.mem_univ, true_and, + Finset.mem_powersetCard] + constructor + · rintro ⟨ρ', ⟨hσρ, hρτ⟩, rfl⟩ + exact ⟨⟨hρτ, face_card ρ'⟩, hσρ⟩ + · rintro ⟨⟨hρτ, hρcard⟩, hσρ⟩ + exact ⟨⟨ρ, (mem_facesOf X j ρ).mpr + ⟨X.downward (face_mem τ) hρτ, hρcard⟩⟩, ⟨hσρ, hρτ⟩, rfl⟩ + have h := Finset.card_filter_powersetCard_subset σ.val τ.val (j + 1) hστ + (by simpa using Nat.succ_le_succ hij) + rw [← himage, Finset.card_image_of_injective _ Subtype.val_injective] at h + simpa only [face_card] using h + +@[simp] theorem coboundary_coboundary (X : Complex) (i : ℕ) (f : X.Cochain i) : + X.coboundary (i + 1) (X.coboundary i f) = 0 := by + classical + ext τ + change (∑ ρ : X.Face (i + 1), if ρ.val ⊆ τ.val then + (∑ σ : X.Face i, if σ.val ⊆ ρ.val then f σ else 0) else 0) = 0 + calc + _ = ∑ ρ : X.Face (i + 1), ∑ σ : X.Face i, + if σ.val ⊆ ρ.val ∧ ρ.val ⊆ τ.val then f σ else 0 := by + apply Finset.sum_congr rfl + intro ρ _ + by_cases h : ρ.val ⊆ τ.val <;> simp [h] + _ = ∑ σ : X.Face i, ∑ ρ : X.Face (i + 1), + if σ.val ⊆ ρ.val ∧ ρ.val ⊆ τ.val then f σ else 0 := Finset.sum_comm + _ = 0 := by + apply Finset.sum_eq_zero + intro σ _ + by_cases hστ : σ.val ⊆ τ.val + · have hc : (Finset.univ.filter (fun ρ : X.Face (i + 1) => + σ.val ⊆ ρ.val ∧ ρ.val ⊆ τ.val)).card = 2 := by + simpa using card_between_faces σ τ hστ (Nat.le_succ i) + rw [← Finset.sum_filter, Finset.sum_const, hc] + have htwo : (2 : ZMod 2) = 0 := by decide + simp [nsmul_eq_mul, htwo] + · apply Finset.sum_eq_zero + intro ρ _ + exact ite_eq_right (fun h => hστ (h.1.trans h.2)) + +theorem sum_face_eq {A : Type*} [AddCommMonoid A] (X : Complex) (i : ℕ) + (g : Finset (Fin X.vertexCount) → A) : + (∑ σ : X.Face i, g σ.val) = ∑ σ ∈ X.facesOf i, g σ := + (Finset.sum_subtype (X.facesOf i) (fun _ => Iff.rfl) g).symm + +def cofaceCount (X : Complex) (s : ℕ) (σ : Finset (Fin X.vertexCount)) : ℕ := + ((X.facesOf s).filter (σ ⊆ ·)).card + +theorem cofaceCount_eq_sum (X : Complex) (s : ℕ) (σ : Finset (Fin X.vertexCount)) : + X.cofaceCount s σ = ∑ τ : X.Face s, if σ ⊆ τ.val then (1 : ℕ) else 0 := by + rw [sum_face_eq X s (fun τ => if σ ⊆ τ then (1 : ℕ) else 0), Finset.sum_boole] + rfl + +theorem sum_cofaceCount {X : Complex} {i s n : ℕ} (σ : X.Face i) (his : i ≤ s) : + (∑ ρ : X.Face s, if σ.val ⊆ ρ.val then X.cofaceCount n ρ.val else 0) = + X.cofaceCount n σ.val * Nat.choose ((n + 1) - (i + 1)) ((s + 1) - (i + 1)) := by + classical + calc + _ = ∑ ρ : X.Face s, ∑ τ : X.Face n, + if σ.val ⊆ ρ.val ∧ ρ.val ⊆ τ.val then (1 : ℕ) else 0 := by + apply Finset.sum_congr rfl + intro ρ _ + by_cases h : σ.val ⊆ ρ.val <;> simp [h, cofaceCount_eq_sum] + _ = ∑ τ : X.Face n, ∑ ρ : X.Face s, + if σ.val ⊆ ρ.val ∧ ρ.val ⊆ τ.val then (1 : ℕ) else 0 := Finset.sum_comm + _ = ∑ τ : X.Face n, if σ.val ⊆ τ.val then + Nat.choose ((n + 1) - (i + 1)) ((s + 1) - (i + 1)) else 0 := by + apply Finset.sum_congr rfl + intro τ _ + by_cases hστ : σ.val ⊆ τ.val + · rw [ite_eq_left hστ, Finset.sum_boole] + exact card_between_faces σ τ hστ his + · rw [ite_eq_right hστ] + apply Finset.sum_eq_zero + intro ρ _ + exact ite_eq_right (fun h => hστ (h.1.trans h.2)) + _ = _ := by + rw [cofaceCount_eq_sum, Finset.sum_mul] + apply Finset.sum_congr rfl + intro τ _ + split_ifs <;> simp + +theorem sum_cofaceCount_real {X : Complex} {i s n : ℕ} (σ : X.Face i) (his : i ≤ s) : + (∑ ρ : X.Face s, if σ.val ⊆ ρ.val then (X.cofaceCount n ρ.val : ℝ) else 0) = + (X.cofaceCount n σ.val : ℝ) * Nat.choose ((n + 1) - (i + 1)) ((s + 1) - (i + 1)) := by + exact_mod_cast sum_cofaceCount (n := n) σ his + +theorem facesOf_nonempty_of_pure {X : Complex} {n s : ℕ} + (hX : X.Pure n) (hsn : s ≤ n) : (X.facesOf s).Nonempty := by + obtain ⟨τ, hτ⟩ := hX.1 + have hτcard := ((mem_facesOf X n τ).mp hτ).2 + obtain ⟨σ, hστ, hσcard⟩ := Finset.exists_subset_card_eq + (show s + 1 ≤ τ.card by omega) + exact ⟨σ, (mem_facesOf X s σ).mpr + ⟨X.downward ((mem_facesOf X n τ).mp hτ).1 hστ, hσcard⟩⟩ + +theorem weight_eq_cofaceCount (X : Complex) (n i : ℕ) (σ : X.Face i) : + X.weight n i σ = (X.cofaceCount n σ.val : ℝ) / + ((Nat.choose (n + 1) (i + 1) : ℝ) * (X.facesOf n).card) := rfl + +theorem weight_averaging {X : Complex} {i s n : ℕ} (hX : (X.facesOf n).Nonempty) + (his : i ≤ s) (hsn : s ≤ n) (σ : X.Face i) : + (∑ ρ : X.Face s, if σ.val ⊆ ρ.val then X.weight n s ρ else 0) = + (Nat.choose (s + 1) (i + 1) : ℝ) * X.weight n i σ := by + classical + have hF : ((X.facesOf n).card : ℝ) ≠ 0 := + ne_of_gt (Nat.cast_pos.mpr hX.card_pos) + have hAi : (Nat.choose (n + 1) (i + 1) : ℝ) ≠ 0 := + ne_of_gt (Nat.cast_pos.mpr (Nat.choose_pos (Nat.succ_le_succ (his.trans hsn)))) + have hAs : (Nat.choose (n + 1) (s + 1) : ℝ) ≠ 0 := + ne_of_gt (Nat.cast_pos.mpr (Nat.choose_pos (Nat.succ_le_succ hsn))) + have hchoose : + (Nat.choose (n + 1) (s + 1) : ℝ) * Nat.choose (s + 1) (i + 1) = + (Nat.choose (n + 1) (i + 1) : ℝ) * + Nat.choose ((n + 1) - (i + 1)) ((s + 1) - (i + 1)) := by + exact_mod_cast Nat.choose_mul (n := n + 1) (Nat.succ_le_succ his) + calc + _ = (∑ ρ : X.Face s, if σ.val ⊆ ρ.val then (X.cofaceCount n ρ.val : ℝ) else 0) / + ((Nat.choose (n + 1) (s + 1) : ℝ) * (X.facesOf n).card) := by + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro ρ _ + split_ifs <;> simp [weight_eq_cofaceCount] + _ = ((X.cofaceCount n σ.val : ℝ) * + Nat.choose ((n + 1) - (i + 1)) ((s + 1) - (i + 1))) / + ((Nat.choose (n + 1) (s + 1) : ℝ) * (X.facesOf n).card) := by + rw [sum_cofaceCount_real σ his] + _ = _ := by + rw [weight_eq_cofaceCount] + field_simp + linear_combination -(X.cofaceCount n σ.val : ℝ) * hchoose + +@[simp] theorem cofaceCount_self {X : Complex} {i : ℕ} (σ : X.Face i) : + X.cofaceCount i σ.val = 1 := by + classical + have hfilter : (X.facesOf i).filter (σ.val ⊆ ·) = {σ.val} := by + ext τ + simp only [Finset.mem_filter, Finset.mem_singleton] + constructor + · rintro ⟨hτ, hστ⟩ + exact (Finset.eq_of_subset_of_card_le hστ (by + rw [face_card σ, ((mem_facesOf X i τ).mp hτ).2])).symm + · rintro rfl + exact ⟨σ.property, Finset.Subset.refl _⟩ + simp [cofaceCount, hfilter] + +@[simp] theorem weight_top {X : Complex} {s : ℕ} (σ : X.Face s) : + X.weight s s σ = 1 / (X.facesOf s).card := by + simp [weight_eq_cofaceCount] + +def skeletonScale (X : Complex) (n s : ℕ) : ℝ := + ((Nat.choose (n + 1) (s + 1) : ℝ) * (X.facesOf n).card) / (X.facesOf s).card + +theorem skeletonScale_pos {X : Complex} {n s : ℕ} (hX : X.Pure n) (hsn : s ≤ n) : + 0 < X.skeletonScale n s := by + exact div_pos + (mul_pos (Nat.cast_pos.mpr (Nat.choose_pos (Nat.succ_le_succ hsn))) + (Nat.cast_pos.mpr hX.1.card_pos)) + (Nat.cast_pos.mpr (facesOf_nonempty_of_pure hX hsn).card_pos) + +theorem skeletonScale_mul_topweight {X : Complex} {n s : ℕ} + (hX : X.Pure n) (hsn : s ≤ n) (ρ : X.Face s) : + X.skeletonScale n s * X.weight n s ρ = + (X.cofaceCount n ρ.val : ℝ) * X.weight s s ρ := by + have hCount : ((X.facesOf n).card : ℝ) ≠ 0 := + ne_of_gt (Nat.cast_pos.mpr hX.1.card_pos) + have hChoose : (Nat.choose (n + 1) (s + 1) : ℝ) ≠ 0 := + ne_of_gt (Nat.cast_pos.mpr (Nat.choose_pos (Nat.succ_le_succ hsn))) + rw [skeletonScale, weight_eq_cofaceCount, weight_top] + field_simp + +theorem skeleton_topweight_comparison {X : Complex} {n s : ℕ} + (hX : X.Pure n) (hsn : s ≤ n) {a b : ℝ} (ha : 0 < a) (hb : 0 < b) + (hcount : ∀ ρ : X.Face s, a ≤ X.cofaceCount n ρ.val ∧ X.cofaceCount n ρ.val ≤ b) + (ρ : X.Face s) : + (X.skeletonScale n s / b) * X.weight n s ρ ≤ X.weight s s ρ ∧ + X.weight s s ρ ≤ (X.skeletonScale n s / a) * X.weight n s ρ := by + have heq := skeletonScale_mul_topweight hX hsn ρ + have hw := X.weight_nonneg s s ρ + constructor + · rw [div_mul_eq_mul_div, div_le_iff₀ hb, heq] + simpa only [mul_comm] using mul_le_mul_of_nonneg_right (hcount ρ).2 hw + · rw [div_mul_eq_mul_div, le_div_iff₀ ha, heq] + simpa only [mul_comm] using mul_le_mul_of_nonneg_right (hcount ρ).1 hw + +theorem skeleton_weight_comparison {X : Complex} {i s n : ℕ} + (hX : X.Pure n) (his : i ≤ s) (hsn : s ≤ n) {a b : ℝ} (ha : 0 < a) + (hcount : ∀ ρ : X.Face s, a ≤ X.cofaceCount n ρ.val ∧ X.cofaceCount n ρ.val ≤ b) + (σ : X.Face i) : + (X.skeletonScale n s / b) * X.weight n i σ ≤ X.weight s i σ ∧ + X.weight s i σ ≤ (X.skeletonScale n s / a) * X.weight n i σ := by + classical + have hXs := facesOf_nonempty_of_pure hX hsn + obtain ⟨ρ₀, hρ₀⟩ := facesOf_nonempty_of_pure hX hsn + have hb : 0 < b := (ha.trans_le (hcount ⟨ρ₀, hρ₀⟩).1).trans_le + (hcount ⟨ρ₀, hρ₀⟩).2 + have hB : (0 : ℝ) < Nat.choose (s + 1) (i + 1) := + Nat.cast_pos.mpr (Nat.choose_pos (Nat.succ_le_succ his)) + have sum_scaled (c : ℝ) (t : ℕ) : + (∑ ρ : X.Face s, if σ.val ⊆ ρ.val then c * X.weight t s ρ else 0) = + c * ∑ ρ : X.Face s, if σ.val ⊆ ρ.val then X.weight t s ρ else 0 := by + simp only [Finset.mul_sum, mul_ite, mul_zero] + constructor + · have hlo : + (∑ ρ : X.Face s, if σ.val ⊆ ρ.val then + (X.skeletonScale n s / b) * X.weight n s ρ else 0) ≤ + ∑ ρ : X.Face s, if σ.val ⊆ ρ.val then X.weight s s ρ else 0 := by + apply Finset.sum_le_sum + intro ρ _ + split_ifs + · exact (skeleton_topweight_comparison hX hsn ha hb hcount ρ).1 + · exact le_rfl + rw [sum_scaled, weight_averaging hX.1 his hsn σ, + weight_averaging hXs his le_rfl σ] at hlo + apply (mul_le_mul_iff_right₀ hB).mp + simpa only [mul_assoc, mul_left_comm, mul_comm] using hlo + · have hhi : + (∑ ρ : X.Face s, if σ.val ⊆ ρ.val then X.weight s s ρ else 0) ≤ + ∑ ρ : X.Face s, if σ.val ⊆ ρ.val then + (X.skeletonScale n s / a) * X.weight n s ρ else 0 := by + apply Finset.sum_le_sum + intro ρ _ + split_ifs + · exact (skeleton_topweight_comparison hX hsn ha hb hcount ρ).2 + · exact le_rfl + rw [sum_scaled, weight_averaging hX.1 his hsn σ, + weight_averaging hXs his le_rfl σ] at hhi + apply (mul_le_mul_iff_right₀ hB).mp + simpa only [mul_assoc, mul_left_comm, mul_comm] using hhi + +theorem norm_le_of_weight_le {X : Complex} {r s i : ℕ} {c : ℝ} + (hw : ∀ σ : X.Face i, X.weight r i σ ≤ c * X.weight s i σ) + (f : X.Cochain i) : X.norm r i f ≤ c * X.norm s i f := by + rw [norm, norm, Finset.mul_sum] + apply Finset.sum_le_sum + intro σ _ + split_ifs + · exact hw σ + · simp + +theorem distance_le_of_weight_le {X : Complex} {r s i : ℕ} {c : ℝ} + (hw : ∀ σ : X.Face i, X.weight r i σ ≤ c * X.weight s i σ) + (f : X.Cochain i) {A : Set (X.Cochain i)} (hA : A.Nonempty) : + X.distance r i f A ≤ c * X.distance s i f A := by + obtain ⟨a, ha, heq⟩ := X.distance_attained s i f A hA + rw [heq] + exact (X.distance_le_norm r i f ha).trans (norm_le_of_weight_le hw (f - a)) + +theorem skeleton_norm_comparison {X : Complex} {i s n : ℕ} + (hX : X.Pure n) (his : i ≤ s) (hsn : s ≤ n) {a b : ℝ} (ha : 0 < a) + (hcount : ∀ ρ : X.Face s, a ≤ X.cofaceCount n ρ.val ∧ X.cofaceCount n ρ.val ≤ b) + (f : X.Cochain i) : + (X.skeletonScale n s / b) * X.norm n i f ≤ X.norm s i f ∧ + X.norm s i f ≤ (X.skeletonScale n s / a) * X.norm n i f := by + constructor + · rw [norm, norm, Finset.mul_sum] + apply Finset.sum_le_sum + intro σ _ + split_ifs + · exact (skeleton_weight_comparison hX his hsn ha hcount σ).1 + · simp + · exact norm_le_of_weight_le + (fun σ => (skeleton_weight_comparison hX his hsn ha hcount σ).2) f + +theorem skeleton_distance_comparison {X : Complex} {i s n : ℕ} + (hX : X.Pure n) (his : i ≤ s) (hsn : s ≤ n) {a b : ℝ} (ha : 0 < a) + (hcount : ∀ ρ : X.Face s, a ≤ X.cofaceCount n ρ.val ∧ X.cofaceCount n ρ.val ≤ b) + (f : X.Cochain i) {A : Set (X.Cochain i)} (hA : A.Nonempty) : + (X.skeletonScale n s / b) * X.distance n i f A ≤ X.distance s i f A ∧ + X.distance s i f A ≤ (X.skeletonScale n s / a) * X.distance n i f A := by + obtain ⟨ρ₀, hρ₀⟩ := facesOf_nonempty_of_pure hX hsn + have hb : 0 < b := (ha.trans_le (hcount ⟨ρ₀, hρ₀⟩).1).trans_le + (hcount ⟨ρ₀, hρ₀⟩).2 + constructor + · obtain ⟨a₀, ha₀, heq⟩ := X.distance_attained s i f A hA + rw [heq] + exact (mul_le_mul_of_nonneg_left (X.distance_le_norm n i f ha₀) + (le_of_lt (div_pos (skeletonScale_pos hX hsn) hb))).trans + (skeleton_norm_comparison hX his hsn ha hcount (f - a₀)).1 + · exact distance_le_of_weight_le + (fun σ => (skeleton_weight_comparison hX his hsn ha hcount σ).2) f hA + +theorem skeleton_expansion_on_common_cochains {X : Complex} {i s n : ℕ} + (hX : X.Pure n) (his : i < s) (hsn : s ≤ n) {M η : ℝ} + (hη : 0 ≤ η) + (hcount : ∀ ρ : X.Face s, 1 ≤ (X.cofaceCount n ρ.val : ℝ) ∧ X.cofaceCount n ρ.val ≤ M) + (hvanish : X.cocycles i = X.coboundaries i) + (hcosystolic : ∀ f : X.Cochain i, + η * X.distance n i f (X.cocycles i) ≤ X.norm n (i + 1) (X.coboundary i f)) + (f : X.Cochain i) : + (η / M) * X.distance s i f (X.coboundaries i) ≤ + X.norm s (i + 1) (X.coboundary i f) := by + obtain ⟨ρ₀, hρ₀⟩ := facesOf_nonempty_of_pure hX hsn + have hM : 0 < M := (zero_lt_one.trans_le (hcount ⟨ρ₀, hρ₀⟩).1).trans_le + (hcount ⟨ρ₀, hρ₀⟩).2 + have hΛ : 0 < X.skeletonScale n s := skeletonScale_pos hX hsn + have hdist := (skeleton_distance_comparison hX his.le hsn zero_lt_one hcount + f (X.coboundaries_nonempty i)).2 + simp only [div_one] at hdist + have hexp := hcosystolic f + rw [hvanish] at hexp + calc + _ ≤ (η / M) * (X.skeletonScale n s * X.distance n i f (X.coboundaries i)) := + mul_le_mul_of_nonneg_left hdist (div_nonneg hη hM.le) + _ = (X.skeletonScale n s / M) * + (η * X.distance n i f (X.coboundaries i)) := by ring + _ ≤ (X.skeletonScale n s / M) * X.norm n (i + 1) (X.coboundary i f) := + mul_le_mul_of_nonneg_left hexp (div_nonneg hΛ.le hM.le) + _ ≤ _ := (skeleton_norm_comparison hX his hsn zero_lt_one hcount + (X.coboundary i f)).1 + +@[reducible] def skeleton (X : Complex) (s : ℕ) : Complex where + vertexCount := X.vertexCount + faces := X.faces.filter (fun σ => σ.card ≤ s + 1) + empty_mem := Finset.mem_filter.mpr ⟨X.empty_mem, by simp⟩ + downward := by + intro σ τ hσ hτ + rw [Finset.mem_filter] at hσ ⊢ + exact ⟨X.downward hσ.1 hτ, (Finset.card_le_card hτ).trans hσ.2⟩ + vertex_mem := fun v => Finset.mem_filter.mpr ⟨X.vertex_mem v, by simp⟩ + +@[simp] theorem mem_skeleton_faces (X : Complex) (s : ℕ) (σ) : + σ ∈ (X.skeleton s).faces ↔ σ ∈ X.faces ∧ σ.card ≤ s + 1 := + by simp only [skeleton, Finset.mem_filter] + +@[simp] theorem skeleton_facesOf {X : Complex} {s i : ℕ} (his : i ≤ s) : + (X.skeleton s).facesOf i = X.facesOf i := by + ext σ + simp only [mem_facesOf, skeleton, Finset.mem_filter] + constructor + · exact fun h => ⟨h.1.1, h.2⟩ + · exact fun h => ⟨⟨h.1, h.2 ▸ Nat.succ_le_succ his⟩, h.2⟩ + +theorem skeleton_pure {X : Complex} {n s : ℕ} (hX : X.Pure n) (hsn : s ≤ n) : + (X.skeleton s).Pure s := by + refine ⟨?_, ?_⟩ + · rw [skeleton_facesOf le_rfl] + exact facesOf_nonempty_of_pure hX hsn + · intro σ hσ + obtain ⟨hσX, hσs⟩ := (mem_skeleton_faces X s σ).mp hσ + obtain ⟨τ, hτ, hστ⟩ := hX.2 σ hσX + obtain ⟨ρ, hσρ, hρτ, hρcard⟩ := Finset.exists_subsuperset_card_eq hστ hσs + (by rw [((mem_facesOf X n τ).mp hτ).2]; exact Nat.succ_le_succ hsn) + refine ⟨ρ, ?_, hσρ⟩ + rw [skeleton_facesOf le_rfl] + exact (mem_facesOf X s ρ).mpr ⟨X.downward ((mem_facesOf X n τ).mp hτ).1 hρτ, + hρcard⟩ + +theorem skeleton_connected {X : Complex} (hX : X.Connected) {s : ℕ} (hs : 1 ≤ s) : + (X.skeleton s).Connected := by + refine ⟨hX.1, fun v w => ?_⟩ + apply Relation.ReflTransGen.mono (fun a b hab => ?_) v w (hX.2 v w) + refine ⟨hab.1, (mem_skeleton_faces X s _).mpr ⟨hab.2, ?_⟩⟩ + have hcard := Finset.card_insert_le a ({b} : Finset (Fin X.vertexCount)) + simp only [Finset.card_singleton] at hcard + omega + +def skeletonFaceEquiv (X : Complex) {i s : ℕ} (his : i ≤ s) : + X.Face i ≃ (X.skeleton s).Face i := + Equiv.subtypeEquivRight (fun σ => by rw [skeleton_facesOf his]) + +@[simp] theorem skeletonFaceEquiv_val (X : Complex) {i s : ℕ} (his : i ≤ s) + (σ : X.Face i) : (X.skeletonFaceEquiv his σ).val = σ.val := rfl + +@[simp] theorem skeletonFaceEquiv_symm_val (X : Complex) {i s : ℕ} (his : i ≤ s) + (σ : (X.skeleton s).Face i) : ((X.skeletonFaceEquiv his).symm σ).val = σ.val := rfl + +def skeletonCochainEquiv (X : Complex) {i s : ℕ} (his : i ≤ s) : + X.Cochain i ≃ₗ[ZMod 2] (X.skeleton s).Cochain i := + LinearEquiv.funCongrLeft (ZMod 2) (ZMod 2) (X.skeletonFaceEquiv his).symm + +@[simp] theorem skeletonCochainEquiv_apply (X : Complex) {i s : ℕ} (his : i ≤ s) + (f : X.Cochain i) (σ : (X.skeleton s).Face i) : + X.skeletonCochainEquiv his f σ = f ((X.skeletonFaceEquiv his).symm σ) := rfl + +@[simp] theorem skeleton_weight (X : Complex) {i s : ℕ} (his : i ≤ s) + (σ : X.Face i) : + (X.skeleton s).weight s i (X.skeletonFaceEquiv his σ) = X.weight s i σ := by + simp only [weight, skeleton_facesOf le_rfl, skeletonFaceEquiv_val] + +@[simp] theorem skeleton_norm (X : Complex) {i s : ℕ} (his : i ≤ s) + (f : X.Cochain i) : + (X.skeleton s).norm s i (X.skeletonCochainEquiv his f) = X.norm s i f := by + unfold norm + apply (Fintype.sum_equiv (X.skeletonFaceEquiv his) _ _ ?_).symm + intro σ + simp only [skeletonCochainEquiv_apply, Equiv.symm_apply_apply, skeleton_weight] + +@[simp] theorem skeleton_coboundary (X : Complex) {i s : ℕ} (his : i < s) + (f : X.Cochain i) : + (X.skeleton s).coboundary i (X.skeletonCochainEquiv his.le f) = + X.skeletonCochainEquiv his (X.coboundary i f) := by + ext τ + simp only [coboundary, skeletonCochainEquiv_apply] + apply (Fintype.sum_equiv (X.skeletonFaceEquiv his.le) _ _ ?_).symm + intro σ + simp only [Equiv.symm_apply_apply, + skeletonFaceEquiv_val, skeletonFaceEquiv_symm_val] + rfl + +@[simp] theorem skeleton_distance_image (X : Complex) {i s : ℕ} (his : i ≤ s) + (f : X.Cochain i) (A : Set (X.Cochain i)) : + (X.skeleton s).distance s i (X.skeletonCochainEquiv his f) + ((X.skeletonCochainEquiv his) '' A) = X.distance s i f A := by + unfold distance + congr 1 + rw [Set.image_image] + have hf : (fun a => (X.skeleton s).norm s i + (X.skeletonCochainEquiv his f - X.skeletonCochainEquiv his a)) = + (fun a => X.norm s i (f - a)) := by + funext a + rw [← map_sub, skeleton_norm] + rw [hf] + +theorem skeleton_coboundaries (X : Complex) {i s : ℕ} (his : i ≤ s) : + (X.skeletonCochainEquiv his) '' X.coboundaries i = + (X.skeleton s).coboundaries i := by + ext f + cases i with + | zero => + constructor + · rintro ⟨g, ⟨c, rfl⟩, rfl⟩ + exact ⟨c, rfl⟩ + · rintro ⟨c, rfl⟩ + exact ⟨fun _ => c, ⟨c, rfl⟩, rfl⟩ + | succ i => + have hi : i < s := his + constructor + · rintro ⟨g, ⟨a, rfl⟩, rfl⟩ + exact ⟨X.skeletonCochainEquiv hi.le a, X.skeleton_coboundary hi a⟩ + · rintro ⟨a, rfl⟩ + obtain ⟨a₀, rfl⟩ := (X.skeletonCochainEquiv hi.le).surjective a + exact ⟨X.coboundary i a₀, ⟨a₀, rfl⟩, (X.skeleton_coboundary hi a₀).symm⟩ + +theorem skeleton_expansion {X : Complex} {i s n : ℕ} + (hX : X.Pure n) (his : i < s) (hsn : s ≤ n) {M η : ℝ} + (hη : 0 ≤ η) + (hcount : ∀ ρ : X.Face s, 1 ≤ (X.cofaceCount n ρ.val : ℝ) ∧ X.cofaceCount n ρ.val ≤ M) + (hvanish : X.cocycles i = X.coboundaries i) + (hcosystolic : ∀ f : X.Cochain i, + η * X.distance n i f (X.cocycles i) ≤ X.norm n (i + 1) (X.coboundary i f)) + (f : (X.skeleton s).Cochain i) : + (η / M) * (X.skeleton s).distance s i f ((X.skeleton s).coboundaries i) ≤ + (X.skeleton s).norm s (i + 1) ((X.skeleton s).coboundary i f) := by + obtain ⟨f₀, rfl⟩ := (X.skeletonCochainEquiv his.le).surjective f + rw [← X.skeleton_coboundaries his.le, skeleton_distance_image, + skeleton_coboundary X his, skeleton_norm] + exact skeleton_expansion_on_common_cochains hX his hsn hη hcount hvanish hcosystolic f₀ + +def vertexFaceEquiv (X : Complex) : Fin X.vertexCount ≃ X.Face 0 := + Equiv.ofBijective (fun v => ⟨{v}, (mem_facesOf X 0 _).mpr + ⟨X.vertex_mem v, Finset.card_singleton v⟩⟩) (by + constructor + · intro v w h + exact Finset.singleton_injective (congrArg Subtype.val h) + · intro σ + obtain ⟨v, hv⟩ := Finset.card_eq_one.mp (face_card σ) + exact ⟨v, Subtype.ext hv.symm⟩) + +@[simp] theorem vertexFaceEquiv_val (X : Complex) (v : Fin X.vertexCount) : + (X.vertexFaceEquiv v).val = {v} := rfl + +theorem card_facesOf_zero (X : Complex) : (X.facesOf 0).card = X.vertexCount := by + have h := Fintype.card_congr X.vertexFaceEquiv + simpa only [Fintype.card_fin, Fintype.card_coe] using h.symm + +theorem coboundary_zero_degree (X : Complex) (f : X.Cochain 0) (τ : X.Face 1) : + X.coboundary 0 f τ = ∑ v ∈ τ.val, f (X.vertexFaceEquiv v) := by + rw [coboundary, ← Equiv.sum_comp X.vertexFaceEquiv] + simp only [vertexFaceEquiv_val, Finset.singleton_subset_iff, Finset.sum_ite_mem, + Finset.univ_inter] + +@[simp] theorem coboundary_const (X : Complex) (c : ZMod 2) : + X.coboundary 0 (fun _ => c) = 0 := by + ext τ + rw [coboundary_zero_degree] + simp only [Finset.sum_const, face_card, Nat.reduceAdd, Pi.zero_apply, nsmul_eq_mul] + have htwo : (2 : ZMod 2) = 0 := by decide + simp only [Nat.cast_ofNat, htwo, zero_mul] + +theorem coboundaries_subset_cocycles (X : Complex) (i : ℕ) : + X.coboundaries i ⊆ X.cocycles i := by + cases i with + | zero => + rintro f ⟨c, rfl⟩ + exact X.coboundary_const c + | succ i => + rintro f ⟨g, rfl⟩ + exact X.coboundary_coboundary i g + +theorem cocycles_zero_eq_coboundaries_of_connected {X : Complex} (hX : X.Connected) : + X.cocycles 0 = X.coboundaries 0 := by + apply Set.Subset.antisymm + · intro f hf + have hδ : X.coboundary 0 f = 0 := hf + have hedge : ∀ v w : Fin X.vertexCount, + v ≠ w ∧ {v, w} ∈ X.faces → + f (X.vertexFaceEquiv v) = f (X.vertexFaceEquiv w) := by + intro v w hvw + let τ : X.Face 1 := ⟨{v, w}, (mem_facesOf X 1 _).mpr + ⟨hvw.2, by simp [hvw.1]⟩⟩ + have he := congrFun hδ τ + rw [coboundary_zero_degree] at he + have hsum : f (X.vertexFaceEquiv v) + f (X.vertexFaceEquiv w) = 0 := by + simpa [τ, hvw.1] using he + have hchar : - f (X.vertexFaceEquiv w) = f (X.vertexFaceEquiv w) := by + exact CharTwo.neg_eq _ + exact (eq_neg_of_add_eq_zero_left hsum).trans hchar + have hpath : ∀ v w : Fin X.vertexCount, + f (X.vertexFaceEquiv v) = f (X.vertexFaceEquiv w) := by + intro v w + induction hX.2 v w using Relation.ReflTransGen.head_induction_on with + | refl => rfl + | head hab _ ih => exact (hedge _ _ hab).trans ih + obtain ⟨v₀⟩ := hX.1 + refine ⟨f (X.vertexFaceEquiv v₀), ?_⟩ + funext σ + obtain ⟨v, rfl⟩ := X.vertexFaceEquiv.surjective σ + exact hpath v v₀ + · exact X.coboundaries_subset_cocycles 0 + +end CoboundaryExpanders.Complex + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Cones.lean b/lean/OAI/Combinatorics/Coboundary/Cones.lean new file mode 100644 index 0000000000000000000000000000000000000000..020b8476c79e517dba615c27e0750dcd5554c992 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Cones.lean @@ -0,0 +1,1100 @@ +import OAI.Combinatorics.Coboundary.Chains + +namespace OAI + +noncomputable section + +/-! +Quantitative chain cones, face-model transport, relabeling, and exactness under retractions. +-/ + +section +open scoped BigOperators + +namespace CoboundaryExpanders.InfiniteChains.Cone +open Attachment +variable {V W : Type} [DecidableEq V] [DecidableEq W] + +omit [DecidableEq V] in +lemma twice (c : Raw V) : c + c = 0 := by + ext s + exact CharTwo.add_self_eq_zero _ + +def size (c : Raw V) : ℕ := c.support.card + +omit [DecidableEq V] in +@[simp] lemma size_zero : size (0 : Raw V) = 0 := by simp [size] + +lemma size_add_le (c d : Raw V) : size (c+d) ≤ size c + size d := + (Finset.card_le_card Finsupp.support_add).trans (Finset.card_union_le _ _) + +omit [DecidableEq V] in +lemma size_smul_le (a : k) (c : Raw V) : size (a • c) ≤ size c := + Finset.card_le_card Finsupp.support_smul + +omit [DecidableEq V] in +lemma size_single_le (s : Finset V) (a : k) : size (Finsupp.single s a) ≤ 1 := by + exact (Finset.card_le_card Finsupp.support_single_subset).trans (by simp) + +lemma size_sum_le {ι : Type*} (S : Finset ι) (c : ι → Raw V) : + size (∑ i ∈ S, c i) ≤ ∑ i ∈ S, size (c i) := + (Finset.card_le_card Finsupp.support_finsetSum).trans Finset.card_biUnion_le + +omit [DecidableEq V] in +lemma size_map_le (T : Raw V →ₗ[k] Raw W) (P : Set (Finset V)) (C : ℕ) + (hT : ∀ s ∈ P, size (T (Finsupp.single s 1)) ≤ C) + (c : Raw V) (hc : c ∈ supported P) : size (T c) ≤ C * size c := by + conv_lhs => rw [← Finsupp.sum_single c, Finsupp.sum, map_sum] + calc + size (∑ s ∈ c.support, T (Finsupp.single s (c s))) ≤ + ∑ s ∈ c.support, size (T (Finsupp.single s (c s))) := size_sum_le _ _ + _ ≤ ∑ _s ∈ c.support, C := by + apply Finset.sum_le_sum + intro s hs + have he : Finsupp.single s (c s) = c s • Finsupp.single s (1 : k) := by simp + rw [he, map_smul] + exact (size_smul_le _ _).trans + (hT s ((mem_supported P c).mp hc s (Finsupp.mem_support_iff.mp hs))) + _ = C * size c := by simp [size, Nat.mul_comm] + +lemma size_rawCone_le (a : V) (c : Raw V) : size (rawCone a c) ≤ size c := by + have h := size_map_le (rawCone a) Set.univ 1 (fun s _ => by + rw [rawCone_single] + split_ifs + · simp + · exact size_single_le _ _) c (by rw [mem_supported]; simp) + simpa using h + +lemma rawCone_supported (a : V) (P Q : Set (Finset V)) + (h : ∀ s ∈ P, a ∉ s → insert a s ∈ Q) + (c : Raw V) (hc : c ∈ supported P) : rawCone a c ∈ supported Q := by + apply map_supported _ P Q _ c hc + intro s hs r + rw [rawCone_single] + split_ifs with ha + · exact Submodule.zero_mem _ + · exact single_mem_supported (h s hs ha) r + +lemma rawCone_graded (a : V) (P Q : Set (Finset V)) (n : ℕ) + (h : ∀ s ∈ P, a ∉ s → insert a s ∈ Q) + (c : Raw V) (hc : c ∈ supported (graded P n)) : + rawCone a c ∈ supported (graded Q (n+1)) := by + apply rawCone_supported a (graded P n) (graded Q (n+1)) _ c hc + intro s hs ha + exact ⟨h s hs.1 ha, by rw [Finset.card_insert_of_notMem ha, hs.2]⟩ + +noncomputable def carrierFill (apex : Finset V → V) (s : Finset V) : Raw V := + rawCone (apex s) (Finsupp.single s 1 + ∑ v : s, carrierFill apex (s.erase v.val)) +termination_by s.card +decreasing_by exact Finset.card_erase_lt_of_mem v.property + +lemma carrierFill_eq (apex : Finset V → V) (s : Finset V) : + carrierFill apex s = rawCone (apex s) + (Finsupp.single s 1 + ∑ v ∈ s, carrierFill apex (s.erase v)) := by + rw [carrierFill] + congr 2 + exact Finset.sum_coe_sort s (fun v => carrierFill apex (s.erase v)) + +noncomputable def carrierMap (apex : Finset V → V) : Raw V →ₗ[k] Raw V := + Finsupp.linearCombination k (carrierFill apex) + +@[simp] lemma carrierMap_single (apex : Finset V → V) (s : Finset V) (a : k) : + carrierMap apex (Finsupp.single s a) = a • carrierFill apex s := by + simp [carrierMap] + +lemma boundary_carrierFill (apex : Finset V → V) (s : Finset V) : + rawBoundary (carrierFill apex s) = + Finsupp.single s 1 + ∑ v ∈ s, carrierFill apex (s.erase v) := by + induction s using Finset.strongInductionOn with + | _ s ih => + have hdd := LinearMap.congr_fun (rawBoundary_squared (V := V)) (Finsupp.single s 1) + have hz := congrArg (carrierMap apex) hdd + simp only [LinearMap.comp_apply, LinearMap.zero_apply, rawBoundary_single, + map_sum, carrierMap_single, one_smul, map_zero] at hz + have he : rawBoundary (∑ v ∈ s, carrierFill apex (s.erase v)) = rawBoundary (Finsupp.single s 1) := by + rw [map_sum] + trans ∑ v ∈ s, (Finsupp.single (s.erase v) 1 + ∑ w ∈ s.erase v, + carrierFill apex ((s.erase v).erase w)) + · apply Finset.sum_congr rfl + intro v hv + exact ih (s.erase v) (Finset.erase_ssubset hv) + · rw [Finset.sum_add_distrib, hz, add_zero, rawBoundary_single] + have hcycle : rawBoundary (Finsupp.single s 1 + ∑ v ∈ s, + carrierFill apex (s.erase v)) = 0 := by + rw [map_add, he, twice] + rw [carrierFill_eq] + have h := LinearMap.congr_fun (raw_contraction (apex s)) + (Finsupp.single s 1 + ∑ v ∈ s, carrierFill apex (s.erase v)) + simpa only [LinearMap.add_apply, LinearMap.comp_apply, LinearMap.id_apply, + hcycle, map_zero, add_zero] using h + +lemma carrierMap_contraction (apex : Finset V → V) : + rawBoundary.comp (carrierMap apex) + (carrierMap apex).comp rawBoundary = LinearMap.id := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp only [LinearMap.add_apply, LinearMap.comp_apply, Finsupp.lsingle_apply, carrierMap_single, + map_smul, boundary_carrierFill, rawBoundary_single, map_sum, LinearMap.id_apply] + rw [smul_add, Finset.smul_sum] + have h : (∑ v ∈ s, a • carrierFill apex (s.erase v)) + + (∑ v ∈ s, a • carrierFill apex (s.erase v)) = 0 := twice _ + rw [add_assoc, h, add_zero] + simp + +def carrierBound : ℕ → ℕ + | 0 => 1 + | n+1 => 1 + (n+1)*carrierBound n + +lemma carrierFill_size (apex : Finset V → V) (s : Finset V) : + size (carrierFill apex s) ≤ carrierBound s.card := by + induction s using Finset.strongInductionOn with + | _ s ih => + rw [carrierFill_eq] + calc + size (rawCone (apex s) _) ≤ size (Finsupp.single s 1 + + ∑ v ∈ s, carrierFill apex (s.erase v)) := size_rawCone_le _ _ + _ ≤ 1 + ∑ v ∈ s, size (carrierFill apex (s.erase v)) := + (size_add_le _ _).trans (Nat.add_le_add (size_single_le _ _) (size_sum_le _ _)) + _ ≤ 1 + s.card * carrierBound (s.card-1) := by + apply Nat.add_le_add_left + calc + (∑ v ∈ s, size (carrierFill apex (s.erase v))) ≤ + ∑ _v ∈ s, carrierBound (s.card-1) := by + apply Finset.sum_le_sum + intro v hv + simpa only [Finset.card_erase_of_mem hv] using ih (s.erase v) (Finset.erase_ssubset hv) + _ = _ := by simp + _ = carrierBound s.card := by + cases he : s.card with + | zero => simp [carrierBound] + | succ n => simp [carrierBound] + +lemma carrierFill_supported (X : CoboundaryExpanders.InfiniteChains.Complex V) (C : Finset V → Set (Finset V)) + (apex : Finset V → V) + (hself : ∀ s ∈ X.faces, s ∈ C s) + (hmono : ∀ s ∈ X.faces, ∀ t ⊆ s, C t ⊆ C s) + (hcone : ∀ s ∈ X.faces, ∀ t ∈ C s, insert (apex s) t ∈ C s) + (s : Finset V) (hs : s ∈ X.faces) : + carrierFill apex s ∈ supported (graded (C s) (s.card+1)) := by + induction s using Finset.strongInductionOn with + | _ s ih => + rw [carrierFill_eq] + apply rawCone_graded (apex s) (C s) (C s) s.card + (fun t ht _ => hcone s hs t ht) + apply Submodule.add_mem + · exact single_mem_supported (P := graded (C s) s.card) ⟨hself s hs, rfl⟩ _ + · apply Submodule.sum_mem + intro v hv + have hi := ih (s.erase v) (Finset.erase_ssubset hv) + (X.downward hs (Finset.erase_subset _ _)) + apply supported_mono (P := graded (C (s.erase v)) ((s.erase v).card+1)) + (Q := graded (C s) s.card) ?_ hi + intro t ht + refine ⟨hmono s hs _ (Finset.erase_subset _ _) ht.1, ?_⟩ + have htcard := ht.2 + rw [Finset.card_erase_of_mem hv] at htcard + have hpos := Finset.card_pos.mpr ⟨v, hv⟩ + omega + +def link (v : V) : Raw V →ₗ[k] Raw V := + Finsupp.linearCombination k (fun s => + if v ∈ s then Finsupp.single (s.erase v) 1 else 0) + +@[simp] lemma link_single (v : V) (s : Finset V) (a : k) : + link v (Finsupp.single s a) = + if v ∈ s then Finsupp.single (s.erase v) a else 0 := by + by_cases h : v ∈ s <;> simp [link, h] + +def without (v : V) : Raw V →ₗ[k] Raw V := + Finsupp.linearCombination k (fun s => + if v ∈ s then 0 else Finsupp.single s 1) + +@[simp] lemma without_single (v : V) (s : Finset V) (a : k) : + without v (Finsupp.single s a) = if v ∈ s then 0 else Finsupp.single s a := by + by_cases h : v ∈ s <;> simp [without, h] + +lemma cone_link_without (v : V) (c : Raw V) : + rawCone v (link v c) + without v c = c := by + have h : (rawCone v).comp (link v) + without v = LinearMap.id := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp only [LinearMap.add_apply, LinearMap.comp_apply, Finsupp.lsingle_apply, + link_single, without_single, LinearMap.id_apply] + by_cases hv : v ∈ s + · simp [hv, Finset.insert_erase hv] + · simp [hv] + exact LinearMap.congr_fun h c + +lemma link_boundary (v : V) : + (link v).comp rawBoundary = rawBoundary.comp (link v) := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, rawBoundary_single, map_sum, + link_single] + by_cases hv : v ∈ s + · rw [ite_eq_left hv, rawBoundary_single] + rw [← Finset.sum_erase_add _ _ hv] + simp only [Finset.mem_erase, ne_eq, not_true_eq_false, false_and, ite_false, add_zero] + apply Finset.sum_congr rfl + intro w hw + have hwv := (Finset.mem_erase.mp hw).1 + rw [ite_eq_left ⟨Ne.symm hwv, hv⟩, Finset.erase_right_comm] + · rw [ite_eq_right hv, map_zero] + apply Finset.sum_eq_zero + intro w hw + exact ite_eq_right (fun h => hv (Finset.mem_of_mem_erase h)) + +lemma link_cycle (v : V) (c : Raw V) (hc : rawBoundary c = 0) : + rawBoundary (link v c) = 0 := by + have h := LinearMap.congr_fun (link_boundary v) c + simpa [hc] using h.symm + +lemma link_supported (v : V) (P Q : Set (Finset V)) + (h : ∀ s ∈ P, v ∈ s → s.erase v ∈ Q) + (c : Raw V) (hc : c ∈ supported P) : link v c ∈ supported Q := by + apply map_supported _ P Q _ c hc + intro s hs a + rw [link_single] + split_ifs with hv + · exact single_mem_supported (h s hs hv) a + · exact Submodule.zero_mem _ + +lemma link_graded (v : V) (P Q : Set (Finset V)) (n : ℕ) + (h : ∀ s ∈ P, v ∈ s → s.erase v ∈ Q) + (c : Raw V) (hc : c ∈ supported (graded P (n+1))) : + link v c ∈ supported (graded Q n) := by + apply link_supported v (graded P (n+1)) (graded Q n) _ c hc + intro s hs hv + exact ⟨h s hs.1 hv, by rw [Finset.card_erase_of_mem hv, hs.2]; omega⟩ + +lemma without_supported (v : V) (P : Set (Finset V)) + (c : Raw V) (hc : c ∈ supported P) : + without v c ∈ supported {s | s ∈ P ∧ v ∉ s} := by + apply map_supported _ P _ _ c hc + intro s hs a + rw [without_single] + split_ifs with hv + · exact Submodule.zero_mem _ + · exact single_mem_supported (P := {s | s ∈ P ∧ v ∉ s}) ⟨hs, hv⟩ a + +lemma link_size (v : V) (c : Raw V) : size (link v c) ≤ size c := by + have h := size_map_le (link v) Set.univ 1 (fun s _ => by + rw [link_single] + split_ifs + · exact size_single_le _ _ + · simp) c (by rw [mem_supported]; simp) + simpa using h + +lemma without_size (v : V) (c : Raw V) : size (without v c) ≤ size c := by + have h := size_map_le (without v) Set.univ 1 (fun s _ => by + rw [without_single] + split_ifs + · simp + · exact size_single_le _ _) c (by rw [mem_supported]; simp) + simpa using h + +lemma elimination_identity (v : V) (c b : Raw V) (hb : rawBoundary b = link v c) : + rawBoundary (rawCone v b) + (without v c + b) = c := by + have h := LinearMap.congr_fun (raw_contraction v) b + have he : rawBoundary (rawCone v b) + rawCone v (link v c) = b := by + simpa only [LinearMap.add_apply, LinearMap.comp_apply, LinearMap.id_apply, hb] using h + have he' : rawBoundary (rawCone v b) = b + rawCone v (link v c) := by + calc + rawBoundary (rawCone v b) = rawBoundary (rawCone v b) + + (rawCone v (link v c) + rawCone v (link v c)) := by rw [twice, add_zero] + _ = b + rawCone v (link v c) := by rw [← add_assoc, he] + rw [he'] + calc + b + rawCone v (link v c) + (without v c + b) = + (rawCone v (link v c) + without v c) + (b+b) := by ac_rfl + _ = c := by rw [twice, add_zero, cone_link_without] + +lemma elimination_cycle (v : V) (c b : Raw V) (hc : rawBoundary c = 0) + (hb : rawBoundary b = link v c) : rawBoundary (without v c + b) = 0 := by + have he := congrArg rawBoundary (elimination_identity v c b hb) + have hdd := LinearMap.congr_fun (rawBoundary_squared (V := V)) (rawCone v b) + have hdd' : rawBoundary (rawBoundary (rawCone v b)) = 0 := hdd + simpa only [map_add, hdd', zero_add, hc] using he + +lemma boundary_single_size (s : Finset V) (a : k) : + size (rawBoundary (Finsupp.single s a)) ≤ s.card := by + rw [rawBoundary_single] + calc + size (∑ v ∈ s, Finsupp.single (s.erase v) a) ≤ + ∑ v ∈ s, size (Finsupp.single (s.erase v) a) := size_sum_le _ _ + _ ≤ ∑ _v ∈ s, 1 := Finset.sum_le_sum (fun _ _ => size_single_le _ _) + _ = s.card := by simp + +omit [DecidableEq V] [DecidableEq W] in +lemma linear_eq_on_supported (A B : Raw V →ₗ[k] Raw W) (P : Set (Finset V)) + (h : ∀ s ∈ P, A (Finsupp.single s 1) = B (Finsupp.single s 1)) + (c : Raw V) (hc : c ∈ supported P) : A c = B c := by + conv_lhs => rw [← Finsupp.sum_single c, Finsupp.sum, map_sum] + conv_rhs => rw [← Finsupp.sum_single c, Finsupp.sum, map_sum] + apply Finset.sum_congr rfl + intro s hs + have he : Finsupp.single s (c s) = c s • Finsupp.single s (1 : k) := by simp + rw [he, map_smul, map_smul, + h s ((mem_supported P c).mp hc s (Finsupp.mem_support_iff.mp hs))] + +structure BoundedCone (X : CoboundaryExpanders.InfiniteChains.Complex V) (n R : ℕ) where + hom : Raw V →ₗ[k] Raw V + support : ∀ s ∈ X.faces, s.card ≤ n → + hom (Finsupp.single s 1) ∈ supported (graded X.faces (s.card+1)) + contraction : ∀ s ∈ X.faces, s.card ≤ n → + rawBoundary (hom (Finsupp.single s 1)) + hom (rawBoundary (Finsupp.single s 1)) = + Finsupp.single s 1 + bound : ∀ s ∈ X.faces, s.card ≤ n → size (hom (Finsupp.single s 1)) ≤ R + +namespace BoundedCone +variable {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} (H : BoundedCone X n R) + +lemma map_graded (r : ℕ) (hr : r ≤ n) (c : Raw V) + (hc : c ∈ supported (graded X.faces r)) : + H.hom c ∈ supported (graded X.faces (r+1)) := by + apply map_supported _ (graded X.faces r) _ _ c hc + intro s hs a + have he : Finsupp.single s a = a • Finsupp.single s (1 : k) := by simp + rw [he, map_smul] + apply Submodule.smul_mem + have h := H.support s hs.1 (hs.2.trans_le hr) + simpa only [hs.2] using h + +lemma contraction_apply (r : ℕ) (hr : r ≤ n) (c : Raw V) + (hc : c ∈ supported (graded X.faces r)) : + rawBoundary (H.hom c) + H.hom (rawBoundary c) = c := by + apply linear_eq_on_supported + (rawBoundary.comp H.hom + H.hom.comp rawBoundary) LinearMap.id + (graded X.faces r) _ c hc + intro s hs + exact H.contraction s hs.1 (hs.2.trans_le hr) + +lemma size_apply (r : ℕ) (hr : r ≤ n) (c : Raw V) + (hc : c ∈ supported (graded X.faces r)) : size (H.hom c) ≤ R * size c := + size_map_le H.hom (graded X.faces r) R + (fun s hs => H.bound s hs.1 (hs.2.trans_le hr)) c hc + +lemma fills (r : ℕ) (hr : r ≤ n) (c : Raw V) + (hc : c ∈ supported (graded X.faces r)) (hz : rawBoundary c = 0) : + rawBoundary (H.hom c) = c := by + simpa only [hz, map_zero, add_zero] using H.contraction_apply r hr c hc + +include H in +lemma exactIn (r : ℕ) (hr : r ≤ n) : ExactIn X.faces r := by + intro c hc hz + exact ⟨H.hom c, H.map_graded r hr c hc, H.fills r hr c hc hz⟩ + +lemma newCycle_supported (s : Finset V) (hs : s ∈ X.faces) (hr : s.card = n+1) : + Finsupp.single s 1 + H.hom (rawBoundary (Finsupp.single s 1)) ∈ + supported (graded X.faces (n+1)) := by + apply Submodule.add_mem + · exact single_mem_supported (P := graded X.faces (n+1)) ⟨hs, hr⟩ _ + · apply H.map_graded n le_rfl + apply boundary_graded X.faces (fun {_ _} hs h => X.downward hs h) n + exact single_mem_supported (P := graded X.faces (n+1)) ⟨hs, hr⟩ _ + +lemma newCycle_cycle (s : Finset V) (hs : s ∈ X.faces) (hr : s.card = n+1) : + rawBoundary (Finsupp.single s 1 + H.hom (rawBoundary (Finsupp.single s 1))) = 0 := by + have hb : rawBoundary (Finsupp.single s 1) ∈ supported (graded X.faces n) := by + apply boundary_graded X.faces (fun {_ _} hs h => X.downward hs h) n + exact single_mem_supported (P := graded X.faces (n+1)) ⟨hs, hr⟩ _ + have hd := LinearMap.congr_fun (rawBoundary_squared (V := V)) (Finsupp.single s 1) + have hh := H.contraction_apply n le_rfl _ hb + rw [show rawBoundary (rawBoundary (Finsupp.single s 1)) = 0 from hd, map_zero, add_zero] at hh + rw [map_add, hh, twice] + +lemma newCycle_size (s : Finset V) (hs : s ∈ X.faces) (hr : s.card = n+1) : + size (Finsupp.single s 1 + H.hom (rawBoundary (Finsupp.single s 1))) ≤ 1+R*(n+1) := by + have hb : rawBoundary (Finsupp.single s 1) ∈ supported (graded X.faces n) := by + apply boundary_graded X.faces (fun {_ _} hs h => X.downward hs h) n + exact single_mem_supported (P := graded X.faces (n+1)) ⟨hs, hr⟩ _ + exact (size_add_le _ _).trans (Nat.add_le_add (size_single_le _ _) + ((H.size_apply n le_rfl _ hb).trans + (Nat.mul_le_mul_left R (by simpa [hr] using boundary_single_size s (1 : k))))) + +noncomputable def extend (S : ℕ) + (fill : ∀ c : Raw V, c ∈ supported (graded X.faces (n+1)) → + rawBoundary c = 0 → size c ≤ 1+R*(n+1) → + ∃ b : Raw V, b ∈ supported (graded X.faces (n+2)) ∧ + rawBoundary b = c ∧ size b ≤ S) : BoundedCone X (n+1) (max R S) := by + classical + let z (s : Finset V) := Finsupp.single s 1 + H.hom (rawBoundary (Finsupp.single s 1)) + have hex (s : Finset V) (hs : s ∈ X.faces ∧ s.card = n+1) : + ∃ b : Raw V, b ∈ supported (graded X.faces (n+2)) ∧ + rawBoundary b = z s ∧ size b ≤ S := + fill (z s) (H.newCycle_supported s hs.1 hs.2) + (H.newCycle_cycle s hs.1 hs.2) (H.newCycle_size s hs.1 hs.2) + let f (s : Finset V) : Raw V := + if hs : s ∈ X.faces ∧ s.card = n+1 then (hex s hs).choose + else H.hom (Finsupp.single s 1) + let T : Raw V →ₗ[k] Raw V := Finsupp.linearCombination k f + have hT (s : Finset V) : T (Finsupp.single s 1) = f s := by simp [T] + have hold (s : Finset V) (hs : s.card ≤ n) : + T (Finsupp.single s 1) = H.hom (Finsupp.single s 1) := by + rw [hT] + simp only [f, dite_eq_right (show ¬(s ∈ X.faces ∧ s.card = n+1) from by omega)] + have hboundary (s : Finset V) (hs : s.card ≤ n+1) : + T (rawBoundary (Finsupp.single s 1)) = H.hom (rawBoundary (Finsupp.single s 1)) := by + rw [rawBoundary_single, map_sum, map_sum] + apply Finset.sum_congr rfl + intro v hv + apply hold + rw [Finset.card_erase_of_mem hv] + omega + refine ⟨T, ?_, ?_, ?_⟩ + · intro s hs hn + by_cases he : s.card = n+1 + · rw [hT] + have hspec := (hex s ⟨hs, he⟩).choose_spec.1 + dsimp only [f] + rw [dite_eq_left (show s ∈ X.faces ∧ s.card = n+1 from ⟨hs, he⟩)] + simpa only [he, Nat.add_assoc] using hspec + · rw [hold s (by omega)] + exact H.support s hs (by omega) + · intro s hs hn + rw [hboundary s hn] + by_cases he : s.card = n+1 + · rw [hT] + have hb : rawBoundary (f s) = z s := by + dsimp only [f] + rw [dite_eq_left (show s ∈ X.faces ∧ s.card = n+1 from ⟨hs, he⟩)] + exact (hex s ⟨hs, he⟩).choose_spec.2.1 + rw [hb] + dsimp [z] + rw [add_assoc, twice, add_zero] + · rw [hold s (by omega)] + exact H.contraction s hs (by omega) + · intro s hs hn + by_cases he : s.card = n+1 + · rw [hT] + have hb : size (f s) ≤ S := by + dsimp only [f] + rw [dite_eq_left (show s ∈ X.faces ∧ s.card = n+1 from ⟨hs, he⟩)] + exact (hex s ⟨hs, he⟩).choose_spec.2.2 + exact hb.trans (Nat.le_max_right _ _) + · rw [hold s (by omega)] + exact (H.bound s hs (by omega)).trans (Nat.le_max_left _ _) + +noncomputable def initial (X : CoboundaryExpanders.InfiniteChains.Complex V) (a : V) (ha : {a} ∈ X.faces) : + BoundedCone X 0 1 where + hom := rawCone a + support := by + intro s hs hn + have he : s = ∅ := Finset.card_eq_zero.mp (Nat.eq_zero_of_le_zero hn) + subst s + simpa [rawCone_single] using + (single_mem_supported (P := graded X.faces 1) ⟨ha, by simp⟩ (1 : k)) + contraction := by + intro s _ _ + exact LinearMap.congr_fun (raw_contraction a) (Finsupp.single s 1) + bound := by + intro s _ _ + exact (size_rawCone_le _ _).trans (size_single_le _ _) + +end BoundedCone + +def vertices (c : Raw V) : Finset V := c.support.biUnion id + +lemma mem_vertices (c : Raw V) (s : Finset V) (hs : c s ≠ 0) (v : V) (hv : v ∈ s) : + v ∈ vertices c := Finset.mem_biUnion.mpr ⟨s, Finsupp.mem_support_iff.mpr hs, hv⟩ + +lemma vertices_card_le (P : Set (Finset V)) (r : ℕ) (c : Raw V) + (hc : c ∈ supported (graded P r)) : (vertices c).card ≤ r * size c := by + calc + (vertices c).card ≤ ∑ s ∈ c.support, s.card := Finset.card_biUnion_le + _ = r * size c := by + rw [Finset.sum_congr rfl (fun s hs => + ((mem_supported _ _).mp hc s (Finsupp.mem_support_iff.mp hs)).2)] + simp [size, Nat.mul_comm] + +def allowed (X : CoboundaryExpanders.InfiniteChains.Complex V) (bad : V → Prop) (A : Finset V) : CoboundaryExpanders.InfiniteChains.Complex V where + faces := {s | s ∈ X.faces ∧ ∀ v ∈ s, bad v → v ∈ A} + empty_mem := ⟨X.empty_mem, by simp⟩ + downward := fun hs hts => ⟨X.downward hs.1 hts, fun v hv => hs.2 v (hts hv)⟩ + +omit [DecidableEq V] in +lemma allowed_forget (X : CoboundaryExpanders.InfiniteChains.Complex V) (bad : V → Prop) (A : Finset V) (r : ℕ) : + supported (graded (allowed X bad A).faces r) ≤ supported (graded X.faces r) := + supported_mono (fun _ hs => ⟨hs.1.1, hs.2⟩) + +lemma removeBad (X : CoboundaryExpanders.InfiniteChains.Complex V) (bad : V → Prop) (r R : ℕ) + (linkFill : ∀ v, bad v → ∀ c : Raw V, + c ∈ supported (graded X.faces r) → rawBoundary c = 0 → + ∃ b : Raw V, + b ∈ supported (graded {s | s ∈ X.faces ∧ + (∀ w ∈ s, ¬bad w) ∧ insert v s ∈ X.faces} r) ∧ + rawBoundary b = link v c ∧ size b ≤ R * size c) + (A : Finset V) (hA : ∀ v ∈ A, bad v) (c : Raw V) + (hc : c ∈ supported (graded (allowed X bad A).faces r)) (hz : rawBoundary c = 0) : + ∃ e c' : Raw V, + e ∈ supported (graded X.faces (r+1)) ∧ + c' ∈ supported (graded (allowed X bad ∅).faces r) ∧ + rawBoundary c' = 0 ∧ rawBoundary e + c' = c ∧ + size e + size c' ≤ (2*R+2)^A.card * size c := by + induction A using Finset.induction_on generalizing c with + | empty => + refine ⟨0, c, Submodule.zero_mem _, hc, hz, by simp, ?_⟩ + simp + | @insert v A hv ih => + have hcX := allowed_forget X bad (insert v A) r hc + obtain ⟨b, hb, hdb, hsize⟩ := linkFill v (hA v (Finset.mem_insert_self _ _)) c hcX hz + let P : Set (Finset V) := {s | s ∈ X.faces ∧ (∀ w ∈ s, ¬ bad w) ∧ insert v s ∈ X.faces} + have hbP : b ∈ supported (graded P r) := hb + have hbA : b ∈ supported (graded (allowed X bad A).faces r) := by + apply supported_mono (P := graded P r) (Q := graded (allowed X bad A).faces r) ?_ hbP + intro s hs + exact ⟨⟨hs.1.1, fun w hw hbad => False.elim (hs.1.2.1 w hw hbad)⟩, hs.2⟩ + have hwA : without v c ∈ supported (graded (allowed X bad A).faces r) := by + have hw := without_supported v (graded (allowed X bad (insert v A)).faces r) c hc + apply supported_mono (P := {s | s ∈ graded (allowed X bad (insert v A)).faces r ∧ v ∉ s}) + (Q := graded (allowed X bad A).faces r) ?_ hw + intro s hs + refine ⟨⟨hs.1.1.1, ?_⟩, hs.1.2⟩ + intro w hw hbad + rcases Finset.mem_insert.mp (hs.1.1.2 w hw hbad) with he | he + · exact False.elim (hs.2 (he ▸ hw)) + · exact he + have hz' := elimination_cycle v c b hz hdb + obtain ⟨e, c', he, hc', hz'', hec', hbound⟩ := + ih (fun w hw => hA w (Finset.mem_insert_of_mem hw)) + (without v c + b) (Submodule.add_mem _ hwA hbA) hz' + have hcone : rawCone v b ∈ supported (graded X.faces (r+1)) := + rawCone_graded v P X.faces r (fun s hs _ => hs.2.2) b hbP + refine ⟨rawCone v b + e, c', Submodule.add_mem _ hcone he, hc', hz'', ?_, ?_⟩ + · rw [map_add, add_assoc, hec'] + exact elimination_identity v c b hdb + · have hnew : size (without v c + b) ≤ (R+1)*size c := by + have hw := without_size v c + have hadd := size_add_le (without v c) b + nlinarith + have hconesize : size (rawCone v b) ≤ R*size c := (size_rawCone_le _ _).trans hsize + have hp : 1 ≤ (2*R+2)^A.card := Nat.one_le_pow _ _ (by omega) + have hh := Nat.mul_le_mul_left ((2*R+2)^A.card) hnew + have hbnd := size_add_le (rawCone v b) e + rw [Finset.card_insert_of_notMem hv, pow_succ] + nlinarith + +def relabel (f : V → W) : Raw V →ₗ[k] Raw W := + Finsupp.lmapDomain k k (Finset.image f) + +omit [DecidableEq V] in +@[simp] lemma relabel_single (f : V → W) (s : Finset V) (a : k) : + relabel f (Finsupp.single s a) = Finsupp.single (s.image f) a := by + simp [relabel] + +omit [DecidableEq V] in +lemma relabel_size (f : V → W) (c : Raw V) : size (relabel f c) ≤ size c := by + have h := size_map_le (relabel f) Set.univ 1 (fun s _ => by + rw [relabel_single]; exact size_single_le _ _) c (by rw [mem_supported]; simp) + simpa using h + +omit [DecidableEq V] in +lemma relabel_supported (f : V → W) (P : Set (Finset V)) (Q : Set (Finset W)) + (h : ∀ s ∈ P, s.image f ∈ Q) (c : Raw V) (hc : c ∈ supported P) : + relabel f c ∈ supported Q := by + apply map_supported _ P Q _ c hc + intro s hs a + rw [relabel_single] + exact single_mem_supported (h s hs) a + +omit [DecidableEq V] in +lemma relabel_graded (f : V → W) (P : Set (Finset V)) (Q : Set (Finset W)) (r : ℕ) + (h : ∀ s ∈ P, s.image f ∈ Q) + (hinj : ∀ s ∈ P, Set.InjOn f (s : Set V)) + (c : Raw V) (hc : c ∈ supported (graded P r)) : + relabel f c ∈ supported (graded Q r) := by + apply relabel_supported f (graded P r) (graded Q r) _ c hc + intro s hs + exact ⟨h s hs.1, (Finset.card_image_of_injOn (hinj s hs.1)).trans hs.2⟩ + +omit [DecidableEq V] in +lemma relabel_injective (f : V → W) (hf : Function.Injective f) : + Function.Injective (relabel f) := + Finsupp.mapDomain_injective (Finset.image_injective hf) + +lemma relabel_boundary (f : V → W) (hf : Function.Injective f) : + rawBoundary.comp (relabel f) = (relabel f).comp rawBoundary := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, relabel_single, + rawBoundary_single, map_sum, Finset.sum_image, hf.injOn] + apply Finset.sum_congr rfl + intro v hv + rw [Finset.image_erase hf] + +omit [DecidableEq V] in +lemma relabel_comp {U : Type} [DecidableEq U] (f : V → W) (g : W → U) : + (relabel g).comp (relabel f) = relabel (g ∘ f) := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp [Finset.image_image] + +lemma relabel_id : relabel (id : V → V) = LinearMap.id := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp + +lemma relabel_retraction (f : V → W) (g : W → V) (P : Set (Finset W)) + (h : ∀ s ∈ P, ∀ w ∈ s, f (g w) = w) + (c : Raw W) (hc : c ∈ supported P) : relabel f (relabel g c) = c := by + apply linear_eq_on_supported ((relabel f).comp (relabel g)) LinearMap.id P _ c hc + intro s hs + simp only [LinearMap.comp_apply, relabel_single, LinearMap.id_apply] + congr 1 + rw [Finset.image_image] + calc + s.image (f ∘ g) = s.image id := Finset.image_congr (fun w hw => h s hs w hw) + _ = s := Finset.image_id + +end CoboundaryExpanders.InfiniteChains.Cone + +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix + +namespace CoboundaryExpanders.InfiniteChains.Cone +open Attachment +variable {V W : Type} [DecidableEq V] [DecidableEq W] + +def unlabel (f : V → W) (hf : Function.Injective f) : Raw W →ₗ[k] Raw V := + Finsupp.lmapDomain k k (fun s : Finset W => s.preimage f hf.injOn) + +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma unlabel_single (f : V → W) (hf : Function.Injective f) (s : Finset W) (a : k) : + unlabel f hf (Finsupp.single s a) = Finsupp.single (s.preimage f hf.injOn) a := by + simp [unlabel] + +omit [DecidableEq V] in +lemma preimage_image (f : V → W) (hf : Function.Injective f) (s : Finset V) : + (s.image f).preimage f hf.injOn = s := by + ext v + simp [hf.eq_iff] + +omit [DecidableEq V] in +@[simp] lemma unlabel_relabel (f : V → W) (hf : Function.Injective f) (c : Raw V) : + unlabel f hf (relabel f c) = c := by + have he : (unlabel f hf).comp (relabel f) = LinearMap.id := by + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro a + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, relabel_single, unlabel_single, + preimage_image f hf s, LinearMap.id_apply] + exact LinearMap.congr_fun he c + +omit [DecidableEq W] in +lemma unlabel_size (f : V → W) (hf : Function.Injective f) (c : Raw W) : + size (unlabel f hf c) ≤ size c := by + have h := size_map_le (unlabel f hf) Set.univ 1 (fun s _ => by + rw [unlabel_single]; exact size_single_le _ _) c (by rw [mem_supported]; simp) + simpa using h + +structure FaceModel (X : CoboundaryExpanders.InfiniteChains.Complex V) (Y : CoboundaryExpanders.InfiniteChains.Complex W) where + vertex : V → W + injective : Function.Injective vertex + face_iff : ∀ s : Finset V, s.image vertex ∈ Y.faces ↔ s ∈ X.faces + cover : ∀ t ∈ Y.faces, ∃ s ∈ X.faces, s.image vertex = t + +namespace FaceModel +variable {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + +omit [DecidableEq V] in +lemma relabel_supported (c : Raw V) (hc : c ∈ supported X.faces) : + relabel M.vertex c ∈ supported Y.faces := + Cone.relabel_supported M.vertex X.faces Y.faces (fun s hs => (M.face_iff s).mpr hs) c hc + +omit [DecidableEq V] in +lemma unlabel_face (t : Finset W) (ht : t ∈ Y.faces) : + t.preimage M.vertex M.injective.injOn ∈ X.faces ∧ + (t.preimage M.vertex M.injective.injOn).image M.vertex = t ∧ + (t.preimage M.vertex M.injective.injOn).card = t.card := by + obtain ⟨s,hs,he⟩ := M.cover t ht + subst t + rw [preimage_image M.vertex M.injective s] + exact ⟨hs,rfl,(Finset.card_image_of_injective s M.injective).symm⟩ + +lemma unlabel_graded (r : ℕ) (c : Raw W) (hc : c ∈ supported (graded Y.faces r)) : + unlabel M.vertex M.injective c ∈ supported (graded X.faces r) := by + apply map_supported _ (graded Y.faces r) (graded X.faces r) _ c hc + intro t ht a + rw [unlabel_single] + have hh := M.unlabel_face t ht.1 + exact single_mem_supported (P := graded X.faces r) ⟨hh.1,hh.2.2.trans ht.2⟩ a + +omit [DecidableEq V] in +lemma relabel_unlabel (c : Raw W) (hc : c ∈ supported Y.faces) : + relabel M.vertex (unlabel M.vertex M.injective c) = c := by + apply linear_eq_on_supported ((relabel M.vertex).comp (unlabel M.vertex M.injective)) + LinearMap.id Y.faces _ c hc + intro t ht + simp only [LinearMap.comp_apply,unlabel_single,relabel_single,LinearMap.id_apply, + (M.unlabel_face t ht).2.1] + +lemma unlabel_boundary (c : Raw W) (hc : c ∈ supported Y.faces) : + unlabel M.vertex M.injective (rawBoundary c) = + rawBoundary (unlabel M.vertex M.injective c) := by + apply linear_eq_on_supported ((unlabel M.vertex M.injective).comp rawBoundary) + (rawBoundary.comp (unlabel M.vertex M.injective)) Y.faces _ c hc + intro t ht + obtain ⟨s,hs,he⟩ := M.cover t ht + subst t + rw [← relabel_single M.vertex s 1] + change unlabel M.vertex M.injective (rawBoundary (relabel M.vertex (Finsupp.single s 1))) = _ + have hb := LinearMap.congr_fun (Cone.relabel_boundary M.vertex M.injective) (Finsupp.single s 1) + change rawBoundary (relabel M.vertex (Finsupp.single s 1)) = + relabel M.vertex (rawBoundary (Finsupp.single s 1)) at hb + simp only [LinearMap.comp_apply] at * + rw [hb,unlabel_relabel,unlabel_relabel] + +def pullCone {n R : ℕ} (H : BoundedCone Y n R) : BoundedCone X n R where + hom := (unlabel M.vertex M.injective).comp (H.hom.comp (relabel M.vertex)) + support := by + intro s hs hn + change unlabel M.vertex M.injective (H.hom (relabel M.vertex (Finsupp.single s 1))) ∈ _ + rw [relabel_single] + have hc := Finset.card_image_of_injective s M.injective + have hh := H.support (s.image M.vertex) ((M.face_iff s).mpr hs) (hc.trans_le hn) + rw [hc] at hh + exact M.unlabel_graded (s.card+1) _ hh + contraction := by + intro s hs hn + have hc := Finset.card_image_of_injective s M.injective + have hin := (M.face_iff s).mpr hs + have hsupport := H.support (s.image M.vertex) hin (hc.trans_le hn) + have hplain := supported_mono (P := graded Y.faces ((s.image M.vertex).card+1)) + (Q := Y.faces) (fun _ ht => ht.1) hsupport + have hh := congrArg (unlabel M.vertex M.injective) + (H.contraction (s.image M.vertex) hin (hc.trans_le hn)) + rw [map_add,M.unlabel_boundary _ hplain] at hh + have hb := LinearMap.congr_fun (Cone.relabel_boundary M.vertex M.injective) (Finsupp.single s 1) + change rawBoundary (relabel M.vertex (Finsupp.single s 1)) = + relabel M.vertex (rawBoundary (Finsupp.single s 1)) at hb + rw [relabel_single] at hb + rw [hb,unlabel_single,preimage_image M.vertex M.injective s] at hh + simpa only [LinearMap.comp_apply,relabel_single] using hh + bound := by + intro s hs hn + change size (unlabel M.vertex M.injective (H.hom (relabel M.vertex (Finsupp.single s 1)))) ≤ _ + apply (unlabel_size _ _ _).trans + rw [relabel_single] + exact H.bound (s.image M.vertex) ((M.face_iff s).mpr hs) + ((Finset.card_image_of_injective s M.injective).trans_le hn) + +def pushCone {n R : ℕ} (H : BoundedCone X n R) : BoundedCone Y n R where + hom := (relabel M.vertex).comp (H.hom.comp (unlabel M.vertex M.injective)) + support := by + intro t ht hn + obtain ⟨s,hs,he⟩ := M.cover t ht + subst t + rw [Finset.card_image_of_injective s M.injective] at hn ⊢ + change relabel M.vertex (H.hom (unlabel M.vertex M.injective (Finsupp.single (s.image M.vertex) 1))) ∈ _ + rw [unlabel_single,preimage_image M.vertex M.injective s] + exact Cone.relabel_graded M.vertex X.faces Y.faces (s.card+1) + (fun a ha => (M.face_iff a).mpr ha) (fun _ _ => M.injective.injOn) + _ (H.support s hs hn) + contraction := by + intro t ht hn + obtain ⟨s,hs,he⟩ := M.cover t ht + subst t + rw [Finset.card_image_of_injective s M.injective] at hn + change rawBoundary (relabel M.vertex (H.hom (unlabel M.vertex M.injective (Finsupp.single (s.image M.vertex) 1)))) + + relabel M.vertex (H.hom (unlabel M.vertex M.injective (rawBoundary (Finsupp.single (s.image M.vertex) 1)))) = _ + rw [←relabel_single,unlabel_relabel] + have hb (c : Raw V) := LinearMap.congr_fun (Cone.relabel_boundary M.vertex M.injective) c + change ∀ c : Raw V, rawBoundary (relabel M.vertex c) = relabel M.vertex (rawBoundary c) at hb + rw [hb,hb,unlabel_relabel,←map_add,H.contraction s hs hn] + bound := by + intro t ht hn + obtain ⟨s,hs,he⟩ := M.cover t ht + subst t + rw [Finset.card_image_of_injective s M.injective] at hn + change size (relabel M.vertex (H.hom (unlabel M.vertex M.injective (Finsupp.single (s.image M.vertex) 1)))) ≤ _ + rw [unlabel_single,preimage_image M.vertex M.injective s] + exact (relabel_size _ _).trans (H.bound s hs hn) + +end FaceModel +end CoboundaryExpanders.InfiniteChains.Cone + +end + +section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix +open scoped BigOperators InnerProductSpace + +namespace CoboundaryExpanders.InfiniteChains.Cone +open Attachment +variable {V : Type} [DecidableEq V] +attribute [local instance] Classical.propDecidable + +def VertexPath (X : CoboundaryExpanders.InfiniteChains.Complex V) (x y : V) : Prop := + Relation.ReflTransGen (fun a b => ({a,b}:Finset V) ∈ X.faces) x y + +def vertexEval (P : V → Prop) : Raw V →ₗ[k] k := + Finsupp.linearCombination k (fun s => ∑v∈s, (if P v then 1 else 0 : k)) +omit [DecidableEq V] in +@[simp] lemma vertexEval_single (P : V → Prop) (s : Finset V) (a : k) : + vertexEval P (Finsupp.single s a) = a * ∑v∈s, (if P v then 1 else 0 : k) := by + simp [vertexEval] + +lemma vertexEval_boundary {X : CoboundaryExpanders.InfiniteChains.Complex V} (P : V → Prop) + (hP : ∀ a b, ({a,b}:Finset V) ∈ X.faces → (P a ↔ P b)) + (c : Raw V) (hc : c ∈ supported (graded X.faces 2)) : + vertexEval P (rawBoundary c) = 0 := by + have hsingle (s : Finset V) (hs : s ∈ graded X.faces 2) : + vertexEval P (rawBoundary (Finsupp.single s 1)) = 0 := by + obtain ⟨a,b,hab,rfl⟩ := Finset.card_eq_two.mp hs.2 + have hp := hP a b hs.1 + rw [rawBoundary_single,Finset.sum_insert (show a ∉ ({b}:Finset V) by simpa using hab), + Finset.sum_singleton,map_add] + have hea : ({a,b}:Finset V).erase a = {b} := by simp [hab] + have heb : ({a,b}:Finset V).erase b = {a} := by + rw [Finset.erase_insert_of_ne hab,Finset.erase_singleton] + rfl + rw [hea,heb,vertexEval_single,vertexEval_single] + simp only [one_mul,Finset.sum_singleton] + by_cases ha : P a + · have hb := hp.mp ha + simp only [ite_eq_left ha,ite_eq_left hb] + exact CharTwo.add_self_eq_zero _ + · have hb : ¬P b := fun h => ha (hp.mpr h) + simp only [ite_eq_right ha,ite_eq_right hb,zero_add] + rw [←Finsupp.sum_single c,Finsupp.sum,map_sum,map_sum] + apply Finset.sum_eq_zero + intro s hs + have he : Finsupp.single s (c s) = c s • Finsupp.single s (1:k) := by simp + rw [he,map_smul,map_smul,hsingle s ((mem_supported _ c).mp hc s (Finsupp.mem_support_iff.mp hs)),smul_zero] + +theorem BoundedCone.vertexPath {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} (H : BoundedCone X n R) + (hn : 1 ≤ n) (x y : V) (hx : ({x}:Finset V) ∈ X.faces) + (hy : ({y}:Finset V) ∈ X.faces) : VertexPath X x y := by + let P : V → Prop := VertexPath X x + have hP (a b : V) (hab : ({a,b}:Finset V) ∈ X.faces) : P a ↔ P b := by + constructor + · intro ha; exact ha.tail hab + · intro hb; exact hb.tail (by simpa [Finset.pair_comm] using hab) + let c : Raw V := Finsupp.single {x} 1+Finsupp.single {y} 1 + have hc : c ∈ supported (graded X.faces 1) := by + dsimp only [c] + apply Submodule.add_mem + · exact single_mem_supported (P:=graded X.faces 1) ⟨hx,Finset.card_singleton x⟩ _ + · exact single_mem_supported (P:=graded X.faces 1) ⟨hy,Finset.card_singleton y⟩ _ + have hz : rawBoundary c = 0 := by + simp only [c,map_add,rawBoundary_single,Finset.sum_singleton,Finset.erase_singleton] + exact twice _ + have hb := vertexEval_boundary P hP (H.hom c) (H.map_graded 1 hn c hc) + rw [H.fills 1 hn c hc hz] at hb + have hpx : P x := Relation.ReflTransGen.refl + by_contra hpy + have hpy' : ¬P y := hpy + simp only [c,map_add,vertexEval_single,Finset.sum_singleton,one_mul,ite_eq_left hpx,ite_eq_right hpy',add_zero] at hb + exact one_ne_zero hb +end CoboundaryExpanders.InfiniteChains.Cone + +end + +open scoped Polynomial BigOperators + +namespace CoboundaryExpanders.InfiniteChains.Cone + +section +open Attachment +variable {V W : Type} [DecidableEq V] [DecidableEq W] + +lemma exactIn_equivalence (e : V ≃ W) (P : Set (Finset V)) (Q : Set (Finset W)) + (he : ∀ s, s ∈ P ↔ s.image e ∈ Q) (r : ℕ) (hQ : ExactIn Q r) : ExactIn P r := by + intro c hc hz + have hm (s : Finset W) (hs : s ∈ Q) : s.image e.symm ∈ P := by + apply (he _).mpr + simpa only [Finset.image_image,Equiv.apply_symm_apply,Function.comp_def,Finset.image_id'] using hs + have ha : relabel e c ∈ supported (graded Q r) := + relabel_graded e P Q r (fun s hs => (he s).mp hs) (fun _ _ => e.injective.injOn) c hc + have haz : rawBoundary (relabel e c) = 0 := by + have h := LinearMap.congr_fun (relabel_boundary e e.injective) c + change rawBoundary (relabel e c) = relabel e (rawBoundary c) at h + rw [h,hz,map_zero] + obtain ⟨b,hb,heq⟩ := hQ _ ha haz + refine ⟨relabel e.symm b,relabel_graded e.symm Q P (r+1) hm + (fun _ _ => e.symm.injective.injOn) b hb,?_⟩ + have h := LinearMap.congr_fun (relabel_boundary e.symm e.symm.injective) b + change rawBoundary (relabel e.symm b) = relabel e.symm (rawBoundary b) at h + rw [h,heq] + exact relabel_retraction e.symm e (graded P r) + (fun _ _ _ _ => e.symm_apply_apply _) c hc + +lemma image_erase_of_injOn (f : V → W) (s : Finset V) + (hf : Set.InjOn f (s : Set V)) (v : V) (hv : v ∈ s) : + (s.erase v).image f = (s.image f).erase (f v) := by + ext w + constructor + · rintro hw + obtain ⟨u,hu,rfl⟩ := Finset.mem_image.mp hw + refine Finset.mem_erase.mpr ⟨?_,Finset.mem_image.mpr ⟨u,(Finset.mem_erase.mp hu).2,rfl⟩⟩ + intro he + exact (Finset.mem_erase.mp hu).1 (hf (Finset.mem_erase.mp hu).2 hv he) + · intro hw + exact Finset.erase_image_subset_image_erase f s v hw +lemma relabel_boundary_on (f : V → W) (P : Set (Finset V)) + (hf : ∀ s ∈ P, Set.InjOn f (s : Set V)) + (c : Raw V) (hc : c ∈ supported P) : + rawBoundary (relabel f c) = relabel f (rawBoundary c) := by + apply linear_eq_on_supported (rawBoundary.comp (relabel f)) ((relabel f).comp rawBoundary) P _ c hc + intro s hs + simp only [LinearMap.comp_apply,relabel_single,rawBoundary_single,map_sum] + rw [Finset.sum_image] + · apply Finset.sum_congr rfl + intro v hv + rw [image_erase_of_injOn f s (hf s hs) v hv] + · exact hf s hs + +theorem exactIn_retract (f : V → W) (g : W → V) (P : Set (Finset V)) (Q : Set (Finset W)) + (hf : ∀ s ∈ P, s.image f ∈ Q) (hg : ∀ s ∈ Q, s.image g ∈ P) + (hfi : ∀ s ∈ P, Set.InjOn f (s : Set V)) + (hgi : ∀ s ∈ Q, Set.InjOn g (s : Set W)) + (hret : ∀ s ∈ P, ∀ v ∈ s, g (f v) = v) + (r : ℕ) (hQ : ExactIn Q r) : ExactIn P r := by + intro c hc hz + have hfc := relabel_graded f P Q r hf hfi c hc + have hfz : rawBoundary (relabel f c) = 0 := by + rw [relabel_boundary_on f (graded P r) (fun s hs => hfi s hs.1) c hc,hz,map_zero] + obtain ⟨b,hb,hbc⟩ := hQ _ hfc hfz + refine ⟨relabel g b,relabel_graded g Q P (r+1) hg hgi b hb,?_⟩ + rw [relabel_boundary_on g (graded Q (r+1)) (fun s hs => hgi s hs.1) b hb,hbc] + exact relabel_retraction g f (graded P r) (fun s hs => hret s hs.1) c hc +noncomputable def BoundedCone.retract {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} {n R : ℕ} + (H : BoundedCone Y n R) (f : V → W) (g : W → V) + (hf : ∀ s ∈ X.faces, s.image f ∈ Y.faces) + (hg : ∀ s ∈ Y.faces, s.image g ∈ X.faces) + (hfi : ∀ s ∈ X.faces, Set.InjOn f (s : Set V)) + (hgi : ∀ s ∈ Y.faces, Set.InjOn g (s : Set W)) + (hret : ∀ s ∈ X.faces, ∀ v ∈ s, g (f v) = v) : BoundedCone X n R where + hom := (relabel g).comp (H.hom.comp (relabel f)) + support := by + intro s hs hn + have hcard : (s.image f).card = s.card := Finset.card_image_of_injOn (hfi s hs) + have hH := H.support (s.image f) (hf s hs) (hcard.trans_le hn) + simpa only [LinearMap.comp_apply,relabel_single,hcard] using + relabel_graded g Y.faces X.faces ((s.image f).card+1) hg hgi _ hH + contraction := by + intro s hs hn + have hcard : (s.image f).card = s.card := Finset.card_image_of_injOn (hfi s hs) + have hH := H.support (s.image f) (hf s hs) (hcard.trans_le hn) + have hb := relabel_boundary_on g (graded Y.faces ((s.image f).card+1)) + (fun t ht => hgi t ht.1) _ hH + have hc := congrArg (relabel g) (H.contraction (s.image f) (hf s hs) (hcard.trans_le hn)) + have hbf := relabel_boundary_on f X.faces hfi (Finsupp.single s 1) (single_mem_supported hs 1) + simp only [LinearMap.comp_apply,relabel_single] at hbf ⊢ + rw [hb,← hbf,← map_add,hc] + simpa only [relabel_single] using relabel_retraction g f X.faces hret _ (single_mem_supported hs 1) + bound := by + intro s hs hn + simp only [LinearMap.comp_apply,relabel_single] + apply (relabel_size g _).trans + exact H.bound (s.image f) (hf s hs) ((Finset.card_image_of_injOn (hfi s hs)).trans_le hn) + +theorem relativeExactIn_retract (f : V → W) (g : W → V) + (P Q : Set (Finset V)) (U T : Set (Finset W)) + (hQ : ∀ {s t}, s ∈ Q → t ⊆ s → t ∈ Q) + (hf : ∀ s ∈ Q, s.image f ∈ T) (hg : ∀ s ∈ T, s.image g ∈ Q) + (hfOld : ∀ s ∈ P ∩ Q, s.image f ∈ U) (hgOld : ∀ s ∈ U, s.image g ∈ P) + (hfi : ∀ s ∈ Q, Set.InjOn f (s : Set V)) + (hgi : ∀ s ∈ T, Set.InjOn g (s : Set W)) (hUT : U ⊆ T) + (hret : ∀ s ∈ Q, ∀ v ∈ s, g (f v) = v) + (r : ℕ) (H : RelativeExactIn U T r) : RelativeExactIn P Q r := by + intro c hc hz + have hbc := boundary_supported Q hQ c (graded_forget Q r hc) + have hz' : rawBoundary c ∈ supported (P ∩ Q) := by + rw [mem_supported] at hz hbc ⊢ + exact fun s hs => ⟨hz s hs,hbc s hs⟩ + have hfc := relabel_graded f Q T r hf hfi c hc + have hfz : rawBoundary (relabel f c) ∈ supported U := by + rw [relabel_boundary_on f (graded Q r) (fun s hs => hfi s hs.1) c hc] + exact relabel_supported f (P ∩ Q) U hfOld _ hz' + obtain ⟨b,hb,hres⟩ := H _ hfc hfz + refine ⟨relabel g b,relabel_graded g T Q (r+1) hg hgi b hb,?_⟩ + have hh := relabel_graded g U P r hgOld (fun s hs => hgi s (hUT hs)) _ hres + rw [map_sub,← relabel_boundary_on g (graded T (r+1)) (fun s hs => hgi s hs.1) b hb, + relabel_retraction g f (graded Q r) (fun s hs => hret s hs.1) c hc] at hh + exact hh +end + +section +variable {V : Type} [DecidableEq V] +def tagBy (F : Finset V) (v : V) : V ⊕ V := if v ∈ F then Sum.inl v else Sum.inr v +lemma untag_tagBy (F : Finset V) (v : V) : Sum.elim id id (tagBy F v) = v := by + simp only [tagBy]; split <;> rfl +lemma tagBy_injective (F : Finset V) : Function.Injective (tagBy F) := by + intro v w he + have hh := congrArg (Sum.elim id id) he + simpa only [untag_tagBy] using hh +lemma tagBy_left (F s : Finset V) : (s.image (tagBy F)).toLeft = s ∩ F := by + ext v + simp only [Finset.mem_toLeft,Finset.mem_image,Finset.mem_inter] + constructor + · rintro ⟨w,hw,he⟩ + by_cases hh : w ∈ F + · simp only [tagBy,ite_eq_left hh,Sum.inl.injEq] at he + exact he ▸ ⟨hw,hh⟩ + · simp [tagBy,hh] at he + · rintro ⟨hv,hF⟩ + exact ⟨v,hv,by simp [tagBy,hF]⟩ +lemma tagBy_right (F s : Finset V) : (s.image (tagBy F)).toRight = s \ F := by + ext v + simp only [Finset.mem_toRight,Finset.mem_image,Finset.mem_sdiff] + constructor + · rintro ⟨w,hw,he⟩ + by_cases hh : w ∈ F + · simp [tagBy,hh] at he + · simp only [tagBy,ite_eq_right hh,Sum.inr.injEq] at he + exact he ▸ ⟨hw,hh⟩ + · rintro ⟨hv,hF⟩ + exact ⟨v,hv,by simp [tagBy,hF]⟩ +lemma untag_image (s : Finset (V ⊕ V)) : s.image (Sum.elim id id) = s.toLeft ∪ s.toRight := by + ext v + simp only [Finset.mem_image,Finset.mem_union,Finset.mem_toLeft,Finset.mem_toRight] + constructor + · rintro ⟨(w|w),hw,he⟩ + · exact Or.inl (he ▸ hw) + · exact Or.inr (he ▸ hw) + · rintro (h|h) + · exact ⟨Sum.inl v,h,rfl⟩ + · exact ⟨Sum.inr v,h,rfl⟩ +end + +open Attachment +variable {V W : Type} [DecidableEq V] [DecidableEq W] [Nonempty V] +lemma exactIn_of_image (f : V → W) (hinj : Function.Injective f) + (P : Set (Finset V)) (Q : Set (Finset W)) + (hf : ∀ s ∈ P, s.image f ∈ Q) + (hg : ∀ s ∈ Q, ∃ t ∈ P, t.image f = s) + (r : ℕ) (H : ExactIn Q r) : ExactIn P r := by + classical + let g := Function.invFun f + have hgf (v : V) : g (f v) = v := Function.leftInverse_invFun hinj v + have hfg (s) (hs : s ∈ Q) (w) (hw : w ∈ s) : f (g w) = w := by + obtain ⟨t,_,rfl⟩ := hg s hs + obtain ⟨v,hv,rfl⟩ := Finset.mem_image.mp hw + rw [hgf] + apply exactIn_retract f g P Q hf ?_ (fun _ _ => hinj.injOn) ?_ (fun _ _ v _ => hgf v) r H + · intro s hs + obtain ⟨t,ht,rfl⟩ := hg s hs + simpa [Finset.image_image,Function.comp_def,hgf] using ht + · intro s hs v hv w hw he + rw [← hfg s hs v hv,← hfg s hs w hw,he] +end CoboundaryExpanders.InfiniteChains.Cone + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Cosets.lean b/lean/OAI/Combinatorics/Coboundary/Cosets.lean new file mode 100644 index 0000000000000000000000000000000000000000..11ba49d28ee831303a761cf9384fbdf74b00f57e --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Cosets.lean @@ -0,0 +1,455 @@ +import OAI.Combinatorics.Coboundary.Cones + +namespace OAI + +noncomputable section + +/-! +Typed coset complexes, their links, face models, and connectedness from generation. +-/ + +section +open scoped BigOperators + +namespace CoboundaryExpanders.TypedCosetFaces +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) +abbrev Vertex := (i : I) × G ⧸ H i +instance : DecidableEq (Vertex H) := Classical.decEq _ +def vertex (g : G) (i : I) : Vertex H := ⟨i, QuotientGroup.mk g⟩ +def face (g : G) (A : Finset I) : Finset (Vertex H) := A.image (vertex H g) +def types (σ : Finset (Vertex H)) : Finset I := σ.image Sigma.fst +def IsFace (σ : Finset (Vertex H)) : Prop := ∃ g A, face H g A = σ +def stabilizer (A : Finset I) : Subgroup G := ⨅ i ∈ A, H i + +omit [DecidableEq I] in +@[simp] theorem mem_stabilizer (A : Finset I) (g : G) : + g ∈ stabilizer H A ↔ ∀ i ∈ A, g ∈ H i := by simp [stabilizer] + +omit [DecidableEq I] in +lemma vertex_injective (g : G) : Function.Injective (vertex H g) := by + intro i j hij + exact congrArg Sigma.fst hij + +omit [DecidableEq I] in +@[simp] theorem face_card (g : G) (A : Finset I) : (face H g A).card = A.card := + Finset.card_image_of_injective _ (vertex_injective H g) + +@[simp] theorem types_face (g : G) (A : Finset I) : types H (face H g A) = A := by + simp [types, face, Finset.image_image, vertex, Function.comp_def] + +omit [DecidableEq I] in +@[simp] lemma vertex_mem (g h : G) (i : I) (A : Finset I) : + vertex H g i ∈ face H h A ↔ i ∈ A ∧ (QuotientGroup.mk g : G ⧸ H i) = QuotientGroup.mk h := by + constructor + · intro hi + obtain ⟨j,hj,he⟩ := Finset.mem_image.mp hi + have hji : j = i := congrArg Sigma.fst he + subst j + exact ⟨hj, (eq_of_heq (Sigma.mk.inj_iff.mp he).2).symm⟩ + · rintro ⟨hi,he⟩ + apply Finset.mem_image.mpr + exact ⟨i, hi, by simp [vertex, he]⟩ + +omit [DecidableEq I] in +lemma face_eq_iff (g h : G) (A : Finset I) : + face H g A = face H h A ↔ g⁻¹*h ∈ stabilizer H A := by + rw [mem_stabilizer] + constructor + · intro he i hi + have hm : vertex H g i ∈ face H h A := by + rw [← he] + exact Finset.mem_image.mpr ⟨i,hi,rfl⟩ + exact QuotientGroup.leftRel_apply.mp (Quotient.exact ((vertex_mem H g h i A).mp hm).2) + · intro he + apply Finset.ext + intro x + rcases x with ⟨i,x⟩ + induction x using Quotient.inductionOn with | h x => + change vertex H x i ∈ face H g A ↔ vertex H x i ∈ face H h A + rw [vertex_mem, vertex_mem] + by_cases hi : i ∈ A + · have hg : (QuotientGroup.mk g : G ⧸ H i) = QuotientGroup.mk h := + Quotient.sound (QuotientGroup.leftRel_apply.mpr (he i hi)) + rw [hg] + · simp [hi] + +abbrev FaceOfType (A : Finset I) := {σ : Finset (Vertex H) // IsFace H σ ∧ types H σ = A} + +def quotientFace (A : Finset I) : G ⧸ stabilizer H A → FaceOfType H A := + Quotient.lift (fun g => ⟨face H g A, ⟨g,A,rfl⟩, types_face H g A⟩) (by + intro g h he + apply Subtype.ext + exact (face_eq_iff H g h A).mpr (QuotientGroup.leftRel_apply.mp he)) + +lemma quotientFace_bijective (A : Finset I) : Function.Bijective (quotientFace H A) := by + constructor + · intro a b he + induction a using Quotient.inductionOn with | h a => + induction b using Quotient.inductionOn with | h b => + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + exact (face_eq_iff H a b A).mp (congrArg Subtype.val he) + · rintro ⟨σ,hσ,hA⟩ + obtain ⟨g,B,rfl⟩ := hσ + have hBA : B = A := by simpa using hA + subst B + exact ⟨QuotientGroup.mk g,rfl⟩ + +def faceEquiv (A : Finset I) : G ⧸ stabilizer H A ≃ FaceOfType H A := + Equiv.ofBijective (quotientFace H A) (quotientFace_bijective H A) + +@[simp] lemma faceEquiv_mk (A : Finset I) (g : G) : + (faceEquiv H A (QuotientGroup.mk g)).val = face H g A := rfl + +end CoboundaryExpanders.TypedCosetFaces + +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix + +namespace CoboundaryExpanders.TypedCosetFaces + +section +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +abbrev Remaining (A : Finset I) := {i : I // i ∉ A} + +def linkGroups (A : Finset I) (j : Remaining A) : Subgroup (stabilizer H A) := + (H j.val).comap (stabilizer H A).subtype + +def linkVertex (A : Finset I) : Vertex (linkGroups H A) → Vertex H := + fun x => ⟨x.1.val,Quotient.lift (fun g : stabilizer H A => + (QuotientGroup.mk g.val : G ⧸ H x.1.val)) (by + intro g h he + apply Quotient.sound + have hh : g⁻¹*h ∈ linkGroups H A x.1 := QuotientGroup.leftRel_apply.mp he + exact QuotientGroup.leftRel_apply.mpr hh) x.2⟩ + +omit [DecidableEq I] in +@[simp] lemma linkVertex_vertex (A : Finset I) (g : stabilizer H A) (j : Remaining A) : + linkVertex H A (vertex (linkGroups H A) g j) = vertex H g.val j.val := rfl + +omit [DecidableEq I] in +lemma linkVertex_injective (A : Finset I) : Function.Injective (linkVertex H A) := by + rintro ⟨i,x⟩ ⟨j,y⟩ he + have hij : i = j := Subtype.ext (congrArg Sigma.fst he) + subst j + congr 1 + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + have hq := (Sigma.mk.inj_iff.mp he).2 + have hh := QuotientGroup.leftRel_apply.mp (Quotient.exact (eq_of_heq hq)) + exact hh + +omit [DecidableEq I] in +lemma linkVertex_type_not_mem (A : Finset I) (v : Vertex (linkGroups H A)) : + (linkVertex H A v).1 ∉ A := v.1.property + +@[simp] lemma linkFace_image (A : Finset I) (g : stabilizer H A) (B : Finset (Remaining A)) : + (face (linkGroups H A) g B).image (linkVertex H A) = face H g.val (B.image Subtype.val) := by + simp only [face,Finset.image_image,Function.comp_def,linkVertex_vertex] + +def IsLinkFace (A : Finset I) (s : Finset (Vertex H)) : Prop := + Disjoint s (face H 1 A) ∧ IsFace H (s ∪ face H 1 A) + +lemma types_of_mem {s : Finset (Vertex H)} {v : Vertex H} (hv : v ∈ s) : + v.1 ∈ types H s := Finset.mem_image.mpr ⟨v,hv,rfl⟩ + +omit [DecidableEq I] in +lemma face_subset_iff (g h : G) (A B : Finset I) : + face H g A ⊆ face H h B ↔ A ⊆ B ∧ ∀ i ∈ A, + (QuotientGroup.mk g : G ⧸ H i) = QuotientGroup.mk h := by + constructor + · intro hs + have hh i hi := (vertex_mem H g h i B).mp (hs (Finset.mem_image.mpr ⟨i,hi,rfl⟩)) + exact ⟨fun i hi => (hh i hi).1,fun i hi => (hh i hi).2⟩ + · rintro ⟨hAB,hgh⟩ v hv + obtain ⟨i,hi,rfl⟩ := Finset.mem_image.mp hv + exact (vertex_mem H g h i B).mpr ⟨hAB hi,hgh i hi⟩ + +theorem isLinkFace_iff (A : Finset I) (s : Finset (Vertex H)) : + IsLinkFace H A s ↔ ∃ g : stabilizer H A, ∃ B : Finset (Remaining A), + (face (linkGroups H A) g B).image (linkVertex H A) = s := by + classical + constructor + · rintro ⟨hdis,g,C,hgC⟩ + have hAs : face H 1 A ⊆ face H g C := by rw [hgC]; exact Finset.subset_union_right + obtain ⟨hAC,hAg⟩ := (face_subset_iff H 1 g A C).mp hAs + have hg : g ∈ stabilizer H A := by + rw [mem_stabilizer] + intro i hi + have hh := QuotientGroup.leftRel_apply.mp (Quotient.exact (hAg i hi)) + simpa only [inv_one,one_mul] using hh + let gg : stabilizer H A := ⟨g,hg⟩ + let B : Finset (Remaining A) := (C \ A).subtype (fun i => i ∉ A) + have hB : B.image Subtype.val = C \ A := by + ext i + simp only [B,Finset.mem_image,Finset.mem_subtype,Finset.mem_sdiff] + constructor + · rintro ⟨j,hj,rfl⟩; exact hj + · intro hi; exact ⟨⟨i,hi.2⟩,hi,rfl⟩ + refine ⟨gg,B,?_⟩ + rw [linkFace_image,hB] + ext v + constructor + · intro hv + obtain ⟨i,hi,rfl⟩ := Finset.mem_image.mp hv + have his := Finset.mem_sdiff.mp hi + have hm : vertex H g i ∈ s ∪ face H 1 A := by + rw [← hgC]; exact Finset.mem_image.mpr ⟨i,his.1,rfl⟩ + rcases Finset.mem_union.mp hm with hm | hm + · exact hm + · exact False.elim (his.2 ((vertex_mem H g 1 i A).mp hm).1) + · intro hv + have hvc : v ∈ face H g C := by rw [hgC]; exact Finset.mem_union_left _ hv + obtain ⟨i,hi,rfl⟩ := Finset.mem_image.mp hvc + have hiA : i ∉ A := by + intro hiA + have hmm : vertex H g i ∈ face H 1 A := + (vertex_mem H g 1 i A).mpr ⟨hiA,(hAg i hiA).symm⟩ + exact Finset.disjoint_left.mp hdis hv hmm + exact Finset.mem_image.mpr ⟨i,Finset.mem_sdiff.mpr ⟨hi,hiA⟩,rfl⟩ + · rintro ⟨g,B,rfl⟩ + rw [linkFace_image] + have hA : face H g.val A = face H 1 A := by + apply (face_eq_iff H g.val 1 A).mpr + simpa only [mul_one] using (stabilizer H A).inv_mem g.property + constructor + · apply Finset.disjoint_left.mpr + intro v hv hvA + obtain ⟨i,hi,rfl⟩ := Finset.mem_image.mp hv + obtain ⟨j,hj,rfl⟩ := Finset.mem_image.mp hi + exact j.property ((vertex_mem H g.val 1 j.val A).mp hvA).1 + · refine ⟨g.val,B.image Subtype.val ∪ A,?_⟩ + rw [face,Finset.image_union] + change face H g.val (B.image Subtype.val) ∪ face H g.val A = _ + rw [hA] + +theorem linkFace_iff (A : Finset I) (s : Finset (Vertex (linkGroups H A))) : + IsFace (linkGroups H A) s ↔ IsLinkFace H A (s.image (linkVertex H A)) := by + rw [isLinkFace_iff] + constructor + · rintro ⟨g,B,rfl⟩; exact ⟨g,B,rfl⟩ + · rintro ⟨g,B,he⟩ + exact ⟨g,B,Finset.image_injective (linkVertex_injective H A) he⟩ + +end + +section +variable {G G' I I' : Type} [Group G] [Group G'] [DecidableEq I] [DecidableEq I'] + (H : I → Subgroup G) (H' : I' → Subgroup G') + (e : G ≃* G') (r : I ≃ I') + (he : ∀ i g, g ∈ H i ↔ e g ∈ H' (r i)) + +def isoVertex : Vertex H → Vertex H' := fun x => + ⟨r x.1,Quotient.lift (fun g : G => (QuotientGroup.mk (e g) : G' ⧸ H' (r x.1))) (by + intro g h hh + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + have hm := (he x.1 (g⁻¹*h)).mp (QuotientGroup.leftRel_apply.mp hh) + simpa using hm) x.2⟩ + +omit [DecidableEq I] [DecidableEq I'] in +@[simp] lemma isoVertex_vertex (g : G) (i : I) : + isoVertex H H' e r he (vertex H g i) = vertex H' (e g) (r i) := rfl + +omit [DecidableEq I] [DecidableEq I'] in +lemma isoVertex_injective : Function.Injective (isoVertex H H' e r he) := by + rintro ⟨i,x⟩ ⟨j,y⟩ hxy + have hij : i = j := r.injective (congrArg Sigma.fst hxy) + subst j + congr 1 + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + have hh := QuotientGroup.leftRel_apply.mp + (Quotient.exact (eq_of_heq (Sigma.mk.inj_iff.mp hxy).2)) + apply (he i (x⁻¹*y)).mpr + simpa using hh + +omit [DecidableEq I] [DecidableEq I'] in +lemma isoVertex_surjective : Function.Surjective (isoVertex H H' e r he) := by + rintro ⟨i,q⟩ + induction q using Quotient.inductionOn with | h q => + refine ⟨vertex H (e.symm q) (r.symm i),?_⟩ + simp only [isoVertex_vertex,e.apply_symm_apply,r.apply_symm_apply] + rfl + +def vertexEquiv : Vertex H ≃ Vertex H' := + Equiv.ofBijective (isoVertex H H' e r he) + ⟨isoVertex_injective H H' e r he,isoVertex_surjective H H' e r he⟩ + +omit [DecidableEq I] in +@[simp] lemma isoFace_image (g : G) (A : Finset I) : + (face H g A).image (isoVertex H H' e r he) = face H' (e g) (A.image r) := by + simp only [face,Finset.image_image,Function.comp_def,isoVertex_vertex] + +theorem isoFace_iff (s : Finset (Vertex H)) : + IsFace H' (s.image (isoVertex H H' e r he)) ↔ IsFace H s := by + constructor + · rintro ⟨g,A,hg⟩ + refine ⟨e.symm g,A.image r.symm,?_⟩ + apply Finset.image_injective (isoVertex_injective H H' e r he) + rw [isoFace_image,e.apply_symm_apply] + have hi : (A.image r.symm).image r = A := by ext i; simp + rw [hi] + exact hg + · rintro ⟨g,A,rfl⟩ + exact ⟨e g,A.image r,(isoFace_image H H' e r he g A).symm⟩ + +end + +section +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +def vertexLinkGroups (i : I) (j : {j : I // j ≠ i}) : Subgroup (H i) := + (H j.val).comap (H i).subtype + +def singleStabilizerEquiv (i : I) : H i ≃* stabilizer H {i} := + MulEquiv.subgroupCongr (by ext g; simp [mem_stabilizer]) + +def singleTypesEquiv (i : I) : {j : I // j ≠ i} ≃ Remaining ({i} : Finset I) := + Equiv.subtypeEquivRight (fun j => by simp) + +omit [DecidableEq I] in +lemma singletonGroups_correspond (i : I) (j : {j : I // j ≠ i}) (g : H i) : + g ∈ vertexLinkGroups H i j ↔ singleStabilizerEquiv H i g ∈ + linkGroups H {i} (singleTypesEquiv i j) := Iff.rfl + +def vertexLinkEmbedding (i : I) : Vertex (vertexLinkGroups H i) → Vertex H := + (linkVertex H {i}) ∘ isoVertex (vertexLinkGroups H i) (linkGroups H {i}) + (singleStabilizerEquiv H i) (singleTypesEquiv i) (singletonGroups_correspond H i) + +omit [DecidableEq I] in +lemma vertexLinkEmbedding_injective (i : I) : Function.Injective (vertexLinkEmbedding H i) := + (linkVertex_injective H {i}).comp (isoVertex_injective _ _ _ _ _) + +omit [DecidableEq I] in +@[simp] lemma vertexLinkEmbedding_vertex (i : I) (g : H i) (j : {j : I // j ≠ i}) : + vertexLinkEmbedding H i (vertex (vertexLinkGroups H i) g j) = vertex H g.val j.val := rfl + +theorem vertexLinkFace_iff (i : I) (s : Finset (Vertex (vertexLinkGroups H i))) : + IsFace (vertexLinkGroups H i) s ↔ IsLinkFace H {i} (s.image (vertexLinkEmbedding H i)) := by + unfold vertexLinkEmbedding + rw [← Finset.image_image,← linkFace_iff,isoFace_iff] + +lemma vertexLinkFace_surjective (i : I) (s : Finset (Vertex H)) (hs : IsLinkFace H {i} s) : + ∃ t : Finset (Vertex (vertexLinkGroups H i)), IsFace (vertexLinkGroups H i) t ∧ + t.image (vertexLinkEmbedding H i) = s := by + obtain ⟨g,A,hg⟩ := (isLinkFace_iff H {i} s).mp hs + let e := singleStabilizerEquiv H i + let r := singleTypesEquiv i + refine ⟨face _ (e.symm g) (A.image r.symm),⟨_,_,rfl⟩,?_⟩ + unfold vertexLinkEmbedding + rw [← Finset.image_image,isoFace_image,e.apply_symm_apply] + have hi : (A.image r.symm).image r = A := by + rw [Finset.image_image] + have hcomp : (r ∘ r.symm) = id := by funext x; exact r.apply_symm_apply x + rw [hcomp,Finset.image_id] + rw [hi] + exact hg + +end + +open InfiniteChains InfiniteChains.Cone +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +lemma subset_face {s : Finset (Vertex H)} {g : G} {A : Finset I} (hs : s ⊆ face H g A) : + face H g (types H s) = s := by + apply Finset.Subset.antisymm + · intro v hv + obtain ⟨i,hi,rfl⟩ := Finset.mem_image.mp hv + obtain ⟨w,hw,he⟩ := Finset.mem_image.mp hi + obtain ⟨j,hj,hje⟩ := Finset.mem_image.mp (hs hw) + have hj' : j = i := by simpa only [←hje,vertex] using he + subst j + simpa only [hje] using hw + · intro v hv + obtain ⟨i,hi,he⟩ := Finset.mem_image.mp (hs hv) + apply Finset.mem_image.mpr + refine ⟨i,?_,he⟩ + exact Finset.mem_image.mpr ⟨v,hv,by rw [←he]; rfl⟩ + +lemma IsFace.downward {s t : Finset (Vertex H)} (hs : IsFace H s) (ht : t ⊆ s) : IsFace H t := by + obtain ⟨g,A,rfl⟩ := hs + exact ⟨g,types H t,subset_face H ht⟩ + +def complex : CoboundaryExpanders.InfiniteChains.Complex (Vertex H) where + faces := {s | IsFace H s} + empty_mem := ⟨1,∅,Finset.image_empty _⟩ + downward := fun hs ht => hs.downward H ht + +def linkComplex (A : Finset I) : CoboundaryExpanders.InfiniteChains.Complex (Vertex H) where + faces := {s | IsLinkFace H A s} + empty_mem := ⟨Finset.disjoint_empty_left _,by simpa only [Finset.empty_union] using (show IsFace H (face H 1 A) from ⟨1,A,rfl⟩)⟩ + downward := by + intro s t hs ht + refine ⟨Finset.disjoint_left.mpr ?_,hs.2.downward H (Finset.union_subset_union ht (Finset.Subset.refl _))⟩ + intro v hv hv' + exact Finset.disjoint_left.mp hs.1 (ht hv) hv' + +end CoboundaryExpanders.TypedCosetFaces + +end + +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix +open scoped BigOperators InnerProductSpace + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains InfiniteChains.Cone +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +lemma vertexPath_common (g : G) (i j : I) : + VertexPath (complex H) (vertex H g i) (vertex H g j) := by + apply Relation.ReflTransGen.single + exact ⟨g,{i,j},by simp [face]⟩ + +lemma vertexPath_symm {x y : Vertex H} (h : VertexPath (complex H) x y) : + VertexPath (complex H) y x := by + induction h with + | refl => exact Relation.ReflTransGen.refl + | tail _ hxy ih => + exact (Relation.ReflTransGen.single (by simpa only [Finset.pair_comm] using hxy)).trans ih + +lemma vertexPath_mul (hgen : Subgroup.closure (⋃ i, (H i : Set G)) = ⊤) (base : I) (x : G) : + ∀ g, VertexPath (complex H) (vertex H g base) (vertex H (g*x) base) := by + have hx : x ∈ Subgroup.closure (⋃ i, (H i : Set G)) := by rw [hgen]; trivial + induction hx using Subgroup.closure_induction with + | mem x hx => + obtain ⟨i,hi⟩ := Set.mem_iUnion.mp hx + intro g + have he : vertex H g i = vertex H (g*x) i := by + apply Sigma.mk.inj_iff.mpr + refine ⟨rfl,heq_of_eq ?_⟩ + exact Quotient.sound (QuotientGroup.leftRel_apply.mpr (by simpa using hi)) + have hleft := vertexPath_common H g base i + have hright := vertexPath_common H (g*x) i base + rw [←he] at hright + exact hleft.trans hright + | one => intro g; simpa only [mul_one,VertexPath] using (Relation.ReflTransGen.refl : VertexPath (complex H) (vertex H g base) _) + | mul x y hx hy ihx ihy => intro g; simpa only [mul_assoc,VertexPath] using (ihx g).trans (ihy (g*x)) + | inv x hx ih => + intro g + simpa only [mul_assoc,inv_mul_cancel,mul_one] using vertexPath_symm H (ih (g*x⁻¹)) + +lemma vertexPath_of_generate (hgen : Subgroup.closure (⋃ i, (H i : Set G)) = ⊤) + (base : I) (x y : Vertex H) : VertexPath (complex H) x y := by + obtain ⟨i,x⟩ := x + obtain ⟨j,y⟩ := y + induction x using Quotient.inductionOn with | h g => + induction y using Quotient.inductionOn with | h h => + change VertexPath (complex H) (vertex H g i) (vertex H h j) + have hd := vertexPath_mul H hgen base (g⁻¹*h) g + simp only [←mul_assoc,mul_inv_cancel,one_mul] at hd + exact (vertexPath_common H g i base).trans (hd.trans (vertexPath_common H h base j)) + +end CoboundaryExpanders.TypedCosetFaces + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Expansion.lean b/lean/OAI/Combinatorics/Coboundary/Expansion.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a9b18e680148a7a90ff75ef18c91d20f211cc85 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Expansion.lean @@ -0,0 +1,920 @@ +import OAI.Combinatorics.Coboundary.Mixing +import OAI.Combinatorics.Coboundary.Averaging + +namespace OAI + +/-! +Local repairs, fat-ladder inequalities, and uniform raw cosystolic expansion. +-/ + +noncomputable section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix +open scoped BigOperators InnerProductSpace + +namespace CoboundaryExpanders.FatLadders +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +def linkRestrict (s : Finset V) (g : Finset V → k) (a : Finset V) : k := g (s ∪ a) +def linkLift (s : Finset V) (b : Finset V → k) (t : Finset V) : k := + if s ⊆ t then b (t \ s) else 0 + +def linkNorm (w : Finset V → ℝ) (s : Finset V) (j : ℕ) (f : Finset V → k) : ℝ := + ∑ a ∈ level j, if Disjoint s a then atom (fun a => w (s ∪ a)) f a else 0 + +omit [Fintype V] in +lemma linkLift_support (s : Finset V) (b : Finset V → k) : + ∀ t, ¬ s ⊆ t → linkLift s b t = 0 := fun _ ht => ite_eq_right ht + +omit [Fintype V] in +lemma delta_linkLift {s t : Finset V} (hst : s ⊆ t) (b : Finset V → k) : + delta (linkLift s b) t = delta b (t \ s) := by + unfold delta + calc + (∑ v ∈ t, linkLift s b (t.erase v)) = ∑ v ∈ t \ s, linkLift s b (t.erase v) := by + symm + apply Finset.sum_subset (Finset.sdiff_subset) + intro v hvt hvs + apply linkLift_support + rw [Finset.subset_erase] + simp only [hst,true_and] + simpa [hvt] using hvs + _ = _ := by + apply Finset.sum_congr rfl + intro v hv + have hvn := (Finset.mem_sdiff.mp hv).2 + rw [linkLift,ite_eq_left (Finset.subset_erase.mpr ⟨hst,hvn⟩),Finset.erase_sdiff_comm] + +omit [Fintype V] in +lemma delta_linkRestrict (s : Finset V) (g : Finset V → k) + (hg : ∀ t, ¬ s ⊆ t → g t = 0) {a : Finset V} (hdis : Disjoint s a) : + delta (linkRestrict s g) a = delta g (s ∪ a) := by + have hsd : (s ∪ a) \ s = a := Finset.union_sdiff_cancel_left hdis + have hs : s ⊆ s ∪ a := Finset.subset_union_left + have he : delta g (s ∪ a) = ∑ v ∈ a, g ((s ∪ a).erase v) := by + unfold delta + symm + apply Finset.sum_subset (Finset.subset_union_right) + intro v hv hva + apply hg + rw [Finset.subset_erase] + simp only [hs,true_and] + exact not_not.mpr ((Finset.mem_union.mp hv).resolve_right hva) + rw [he] + apply Finset.sum_congr rfl + intro v hv + have hn : v ∉ s := fun h => Finset.disjoint_left.mp hdis h hv + change g (s ∪ a.erase v) = g ((s∪a).erase v) + congr 1 + ext u + simp only [Finset.mem_union,Finset.mem_erase] + have hu : u ∈ s → u ≠ v := fun hu he => hn (he ▸ hu) + tauto + +lemma starNorm_linkNorm (w : Finset V → ℝ) (s : Finset V) (r : ℕ) + (hr : s.card ≤ r) (g : Finset V → k) : + starNorm w r s g = linkNorm w s (r-s.card) (linkRestrict s g) := by + unfold starNorm starSum linkNorm + rw [← Finset.sum_filter,← Finset.sum_filter] + symm + apply Finset.sum_bij (fun a _ => s ∪ a) + · intro a ha + obtain ⟨ha,hd⟩ := Finset.mem_filter.mp ha + refine Finset.mem_filter.mpr ⟨mem_level.mpr ?_,Finset.subset_union_left⟩ + rw [Finset.card_union_of_disjoint hd,mem_level.mp ha] + omega + · intro a ha b hb he + have ha' := (Finset.mem_filter.mp ha).2 + have hb' := (Finset.mem_filter.mp hb).2 + have h := congrArg (fun t : Finset V => t \ s) he + simpa only [Finset.union_sdiff_cancel_left ha',Finset.union_sdiff_cancel_left hb'] using h + · intro t ht + obtain ⟨ht,hst⟩ := Finset.mem_filter.mp ht + refine ⟨t \ s,Finset.mem_filter.mpr ⟨mem_level.mpr ?_,(Finset.disjoint_left.mpr (fun v hv hvs => (Finset.mem_sdiff.mp hvs).2 hv))⟩,?_⟩ + · rw [Finset.card_sdiff_of_subset hst,mem_level.mp ht] + · exact Finset.union_sdiff_of_subset hst + · intro a ha + rfl + +lemma linkNorm_congr (w : Finset V → ℝ) (s : Finset V) (j : ℕ) + (f g : Finset V → k) (he : ∀ a, a.card = j → Disjoint s a → f a = g a) : + linkNorm w s j f = linkNorm w s j g := by + apply Finset.sum_congr rfl + intro a ha + split_ifs with h + · rw [atom,atom,he a (mem_level.mp ha) h] + · rfl + +theorem linkCorrection_of_links {w : Finset V → ℝ} {r : ℕ} {C : ℝ} + (hlocal : ∀ s : Finset V, s.Nonempty → s.card ≤ r → + ∀ f : Finset V → k, ∃ b : Finset V → k, + linkNorm w s (r-s.card) (f+delta b) ≤ + C*linkNorm w s (r-s.card+1) (delta f)) : LinkCorrection w r C := by + intro s hs hr g hg + obtain ⟨b,hb⟩ := hlocal s hs hr (linkRestrict s g) + refine ⟨linkLift s b,linkLift_support s b,?_,?_⟩ + · intro he t ht + by_cases hst : s ⊆ t + · have hts : t = s := (Finset.eq_of_subset_of_card_le hst (by rw [mem_level.mp ht,he])).symm + subst t + rw [delta_linkLift (Finset.Subset.refl _),Finset.sdiff_self] + simp [delta] + · unfold delta + apply Finset.sum_eq_zero + intro v hv + exact linkLift_support s b _ (fun h => hst (h.trans (Finset.erase_subset _ _))) + · rw [starNorm_linkNorm w s r hr,starNorm_linkNorm w s (r+1) (by omega)] + have hl : linkNorm w s (r-s.card) (linkRestrict s (g+delta (linkLift s b))) = + linkNorm w s (r-s.card) (linkRestrict s g+delta b) := by + apply linkNorm_congr + intro a ha hd + change g (s∪a)+delta (linkLift s b) (s∪a) = g (s∪a)+delta b a + rw [delta_linkLift Finset.subset_union_left,Finset.union_sdiff_cancel_left hd] + have hd : linkNorm w s (r+1-s.card) (linkRestrict s (delta g)) = + linkNorm w s (r-s.card+1) (delta (linkRestrict s g)) := by + have he : r+1-s.card = r-s.card+1 := by omega + rw [he] + apply linkNorm_congr + intro a ha hda + exact (delta_linkRestrict s g hg hda).symm + rw [hl,hd] + exact hb + +end CoboundaryExpanders.FatLadders + +namespace CoboundaryExpanders.InfiniteChains +namespace FiniteWeights +open Cone Averaging +open scoped Pointwise +variable {V : Type} [DecidableEq V] [Fintype V] +attribute [local instance] Classical.propDecidable + +def rawNorm (X : CoboundaryExpanders.InfiniteChains.Complex V) (N r : ℕ) (f : Finset V → k) : ℝ := + ∑ s ∈ level X r, if f s ≠ 0 then (cofaces X N s:ℝ) else 0 + +lemma rawNorm_nonneg (X : CoboundaryExpanders.InfiniteChains.Complex V) (N r : ℕ) (f : Finset V → k) : 0 ≤ rawNorm X N r f := by + apply Finset.sum_nonneg + intro s hs + split_ifs <;> positivity + +lemma rawNorm_weight (X : CoboundaryExpanders.InfiniteChains.Complex V) {N r : ℕ} (hr : r ≤ N) (hP : (level X N).Nonempty) + (f : Finset V → k) : + rawNorm X N r f = ((N.choose r:ℝ)*(level X N).card)*supportNorm (weight X N r) f := by + have hd : (N.choose r:ℝ)*(level X N).card ≠ 0 := by + exact mul_ne_zero (by exact_mod_cast (Nat.choose_pos hr).ne') + (by exact_mod_cast (Finset.card_pos.mpr hP).ne') + unfold rawNorm + calc + _ = ∑ s ∈ level X r, ((N.choose r:ℝ)*(level X N).card)* + (if f s = 0 then 0 else weight X N r s) := by + apply Finset.sum_congr rfl + intro s hs + by_cases hf : f s = 0 + · simp [hf] + · simp only [hf,ne_eq,not_false_eq_true,ite_true,ite_false,weight,ite_eq_left hs] + exact (mul_div_cancel₀ _ hd).symm + _ = ∑ s, ((N.choose r:ℝ)*(level X N).card)* + (if f s = 0 then 0 else weight X N r s) := by + apply Finset.sum_subset (Finset.subset_univ _) + intro s hs hn + simp [weight,hn] + _ = _ := (Finset.mul_sum _ _ _).symm + +theorem raw_correction {G : Type} [Group G] [Fintype G] [MulAction G V] + {X : CoboundaryExpanders.InfiniteChains.Complex V} {N n r R : ℕ} (hX : Invariant G X) (hP : Pure X N) + (hTrans : ∀ a b : X.Face N, ∃ g : G, g • a.val = b.val) + (H : BoundedCone X n R) (hr : r ≤ n) (hrN : r+1 ≤ N) (f : Finset V → k) : + ∃ b : Finset V → k, + rawNorm X N r (f+delta b) ≤ (R:ℝ)*(N.choose r)*rawNorm X N (r+1) (delta f) := by + obtain ⟨b,hb⟩ := weighted_correction hX hP hTrans H hr hrN f + refine ⟨b,?_⟩ + rw [rawNorm_weight X (by omega) hP.1,rawNorm_weight X hrN hP.1] + have hh := mul_le_mul_of_nonneg_left hb + (show 0 ≤ (N.choose r:ℝ)*(level X N).card by positivity) + change (N.choose r:ℝ) * (level X N).card * supportNorm (weight X N r) + (fun s => f s + delta b s) ≤ _ + simpa only [mul_assoc,mul_left_comm,mul_comm] using hh + +lemma linkNorm_cofaces (X : CoboundaryExpanders.InfiniteChains.Complex V) {N : ℕ} {s : Finset V} (hs : s ∈ X.faces) + (hN : s.card ≤ N) (j : ℕ) (f : Finset V → k) : + FatLadders.linkNorm (fun t => (cofaces X N t:ℝ)) s j f = + rawNorm (X.faceLink s hs) (N-s.card) j f := by + have hl : FatLadders.level (V:=V) j = Finset.univ.filter (fun a : Finset V => a.card = j) := by + ext a; simp [FatLadders.level] + unfold FatLadders.linkNorm rawNorm level + rw [hl] + simp only [Finset.sum_filter] + apply Finset.sum_congr rfl + intro a ha + by_cases hc : a.card = j + · simp only [hc, and_true,ite_true] + by_cases hd : Disjoint s a + · rw [ite_eq_left hd] + have he := cofaces_link X hs hN hd + by_cases hf : a ∈ (X.faceLink s hs).faces + · simp only [ite_eq_left hf,FatLadders.atom] + rw [←he] + by_cases hz : f a = 0 <;> simp [hz] + · have hz := cofaces_zero_of_not_face (X.faceLink s hs) (N-s.card) hf + simp only [FatLadders.atom] + rw [←he,hz] + simp [hf] + · have hf : a ∉ (X.faceLink s hs).faces := fun h => hd h.1 + simp [hd,hf] + · simp [hc] + +end FiniteWeights +end CoboundaryExpanders.InfiniteChains + +namespace CoboundaryExpanders.TypedCosetFaces + +section +open InfiniteChains +open scoped Pointwise +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +omit [DecidableEq I] in +lemma IsFace.type_injective {s : Finset (Vertex H)} (hs : IsFace H s) : + Set.InjOn Sigma.fst (s : Set (Vertex H)) := by + obtain ⟨g,A,rfl⟩ := hs + intro x hx y hy hxy + obtain ⟨i,hi,rfl⟩ := Finset.mem_image.mp hx + obtain ⟨j,hj,rfl⟩ := Finset.mem_image.mp hy + change i=j at hxy + subst j + rfl + +def faceStabilizer (s : Finset (Vertex H)) : Subgroup G := MulAction.stabilizer G s + +omit [DecidableEq I] in +lemma faceStabilizer_fixes (s : Finset (Vertex H)) (g : faceStabilizer H s) : + (g.val:G) • s = s := g.property + +lemma facesLinkInvariant {s : Finset (Vertex H)} (hs : IsFace H s) + (g : faceStabilizer H s) {a : Finset (Vertex H)} + (ha : a ∈ ((complex H).faceLink s hs).faces) : + g • a ∈ ((complex H).faceLink s hs).faces := by + change Disjoint s ((g.val:G) • a) ∧ IsFace H (s ∪ (g.val:G) • a) + have hg := faceStabilizer_fixes H s g + constructor + · have hd : Disjoint ((g.val:G) • s) ((g.val:G) • a) := by + simp only [Finset.smul_finset_def] + exact (Finset.disjoint_image (f:=fun v : Vertex H => (g.val:G) • v) + (MulAction.injective (β:=Vertex H) (g.val:G))).mpr ha.1 + simpa only [hg] using hd + · have hh := ha.2.smul H (g.val:G) + rw [Finset.smul_finset_union,hg] at hh + exact hh + +lemma facesLinkTransitive [Fintype I] {s : Finset (Vertex H)} (hs : IsFace H s) + {a b : Finset (Vertex H)} (ha : a ∈ ((complex H).faceLink s hs).faces) + (hb : b ∈ ((complex H).faceLink s hs).faces) + (hsc : s.card ≤ Fintype.card I) + (hac : a.card = Fintype.card I-s.card) + (hbc : b.card = Fintype.card I-s.card) : + ∃ g : faceStabilizer H s, g • a = b := by + have hsa : (s∪a).card = Fintype.card I := by + rw [Finset.card_union_of_disjoint ha.1,hac,Nat.add_sub_of_le hsc] + have hsb : (s∪b).card = Fintype.card I := by + rw [Finset.card_union_of_disjoint hb.1,hbc,Nat.add_sub_of_le hsc] + obtain ⟨g,hg⟩ := chamber_transitive H ha.2 hb.2 hsa hsb + have hpoint (v : Vertex H) (hv : v ∈ s) : g • v = v := by + apply hb.2.type_injective H + · rw [←hg] + exact Finset.mem_smul_finset.mpr ⟨v,Finset.mem_union_left a hv,rfl⟩ + · exact Finset.mem_union_left b hv + · rfl + have hfix : g • s = s := by + change s.image (fun v => g • v) = s + calc + _ = s.image id := Finset.image_congr hpoint + _ = s := Finset.image_id + have hdis : Disjoint s (g • a) := by + rw [←hfix] + simp only [Finset.smul_finset_def] + exact (Finset.disjoint_image (f:=fun v : Vertex H => g • v) + (MulAction.injective (β:=Vertex H) g)).mpr ha.1 + refine ⟨⟨g,hfix⟩,?_⟩ + change g • a = b + rw [Finset.smul_finset_union,hfix] at hg + have he := congrArg (fun t : Finset (Vertex H) => t \ s) hg + simpa only [Finset.union_sdiff_cancel_left hdis,Finset.union_sdiff_cancel_left hb.1] using he + +end + +open InfiniteChains FiniteWeights Cone +open scoped Pointwise +variable {G I : Type} [Group G] [Fintype G] [DecidableEq I] [Fintype I] (H : I → Subgroup G) +omit [Fintype G] [DecidableEq I] [Fintype I] in +lemma delta_agrees (g : Finset (Vertex H) → k) : Cone.delta g = FatLadders.delta g := by + funext s + exact Cone.delta_eq_sum g s + +theorem linkCorrection_of_cones {R r : ℕ} + (hR : ProperLinkCones (complex H) (Fintype.card I) R) (hr : r < Fintype.card I) : + FatLadders.LinkCorrection (fun t => (cofaces (complex H) (Fintype.card I) t : ℝ)) r + ((R:ℝ)*2^(Fintype.card I)) := by + apply FatLadders.linkCorrection_of_links + intro s hne hsr f + by_cases hs : s ∈ (complex H).faces + · let : Fintype (faceStabilizer H s) := Fintype.ofFinite _ + have hsc : s.card ≤ Fintype.card I := by omega + have hlocal := hR s hne hs (by omega) + have hp := pure_link (finite_pure H) hs + have hi : Invariant (faceStabilizer H s) ((complex H).faceLink s hs) := + fun g a ha => facesLinkInvariant H hs g ha + have ht : ∀ a b : ((complex H).faceLink s hs).Face (Fintype.card I-s.card), + ∃ g : faceStabilizer H s, g • a.val = b.val := by + intro a b + exact facesLinkTransitive H hs a.property.1 b.property.1 hsc a.property.2 b.property.2 + obtain ⟨b,hb⟩ := raw_correction hi hp ht hlocal.some + (show r-s.card ≤ Fintype.card I-s.card-1 by omega) + (show r-s.card+1 ≤ Fintype.card I-s.card by omega) f + refine ⟨b,?_⟩ + rw [linkNorm_cofaces (complex H) hs hsc,linkNorm_cofaces (complex H) hs hsc] + rw [delta_agrees H b,delta_agrees H f] at hb + apply hb.trans + apply mul_le_mul_of_nonneg_right _ (rawNorm_nonneg _ _ _ _) + apply mul_le_mul_of_nonneg_left _ (Nat.cast_nonneg R) + have hc := Nat.choose_le_two_pow (Fintype.card I-s.card) (r-s.card) + have he : 2^(Fintype.card I-s.card) ≤ 2^(Fintype.card I) := + Nat.pow_le_pow_right (by decide) (Nat.sub_le _ _) + exact_mod_cast hc.trans he + · have hz (a : Finset (Vertex H)) : cofaces (complex H) (Fintype.card I) (s∪a) = 0 := + cofaces_zero_of_not_face _ _ (fun ha => hs ((complex H).downward ha Finset.subset_union_left)) + refine ⟨0,?_⟩ + simp [FatLadders.linkNorm,FatLadders.atom,hz] + +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.Construction +open InfiniteChains FiniteWeights TypedCosetFaces + +theorem uniform_actual_linkCorrection (n : ℕ) (hn : 1 ≤ n) : + ∃ Q C : ℕ, ∀ p : ℕ, ∀ _ : Fact p.Prime, Q < p → + ∀ m : ℕ, 2 ≤ m → + letI : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + ∀ r : ℕ, r < n+1 → + FatLadders.LinkCorrection + (fun t => (cofaces (TypedCosetFaces.complex (reducedLocalGroup p n hn m)) (n+1) t : ℝ)) r C := by + obtain ⟨Q,R,h⟩ := uniform_actual_proper_link_cones n hn + refine ⟨Q,R*2^(n+1),?_⟩ + intro p hp hq m hm + let : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + intro r hr + have hh := linkCorrection_of_cones (reducedLocalGroup p n hn m) + (by simpa only [Fintype.card_fin] using h p hp hq m hm) + (by simpa only [Fintype.card_fin] using hr) + simpa only [Fintype.card_fin,Nat.cast_mul,Nat.cast_pow,Nat.cast_ofNat] using hh + +end CoboundaryExpanders.Construction + +namespace CoboundaryExpanders.FatLadders +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +omit [Fintype V] in +@[simp] lemma delta_zero : delta (0 : Finset V → k) = 0 := by funext s; simp [delta] +omit [Fintype V] in +@[simp] lemma delta_add (f g : Finset V → k) : delta (f+g) = delta f + delta g := by + funext s + simp [delta,Finset.sum_add_distrib] + +omit [Fintype V] in +lemma delta_insert (f : Finset V → k) (v : V) (s : Finset V) (hv : v ∉ s) : + delta f (insert v s) = f s + delta (fun t => f (insert v t)) s := by + unfold delta + rw [Finset.sum_insert hv,Finset.erase_insert hv] + congr 1 + apply Finset.sum_congr rfl + intro x hx + rw [Finset.erase_insert_of_ne (by intro e; subst v; exact hv hx)] + +omit [Fintype V] in +@[simp] theorem delta_delta (f : Finset V → k) : delta (delta f) = 0 := by + funext s + change delta (delta f) s = 0 + induction s using Finset.induction_on generalizing f with + | empty => simp [delta] + | @insert v s hv ih => + rw [delta_insert _ v s hv] + have he : delta (fun t => delta f (insert v t)) s = + delta f s + delta (delta (fun t => f (insert v t))) s := by + unfold delta + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x hx + exact delta_insert f v (s.erase x) (fun h => hv (Finset.mem_of_mem_erase h)) + rw [he,ih] + simp [CharTwo.add_self_eq_zero] + +omit [Fintype V] in +lemma delta_support {s : Finset V} {f : Finset V → k} + (hf : ∀ t, ¬s ⊆ t → f t = 0) : ∀ t, ¬s ⊆ t → delta f t = 0 := by + intro t ht + apply Finset.sum_eq_zero + intro x hx + exact hf _ (fun h => ht (h.trans (Finset.erase_subset _ _))) + +omit [DecidableEq V] in +@[simp] lemma norm_zero (w : Finset V → ℝ) (r) : norm w r 0 = 0 := by simp [norm,atom] + +omit [DecidableEq V] in +lemma norm_add_le {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (r) (f g : Finset V → k) : + norm w r (f+g) ≤ norm w r f + norm w r g := by + rw [norm,norm,norm,← Finset.sum_add_distrib] + exact Finset.sum_le_sum (fun s _ => atom_add_le hw f g s) + +def WeightedEq (w : Finset V → ℝ) (r : ℕ) (f g : Finset V → k) : Prop := + ∀ s ∈ level r, w s ≠ 0 → f s = g s + +omit [DecidableEq V] in +lemma WeightedEq.atom_eq {w : Finset V → ℝ} {r : ℕ} {f g : Finset V → k} + (h : WeightedEq w r f g) {s} (hs : s ∈ level r) : atom w f s = atom w g s := by + by_cases hz : w s = 0 + · simp [atom,hz] + · rw [atom,atom,h s hs hz] + +omit [DecidableEq V] in +lemma WeightedEq.norm_eq {w : Finset V → ℝ} {r : ℕ} {f g : Finset V → k} + (h : WeightedEq w r f g) : norm w r f = norm w r g := + Finset.sum_congr rfl (fun _ hs => h.atom_eq hs) + +lemma WeightedEq.starNorm_eq {w : Finset V → ℝ} {r : ℕ} {f g : Finset V → k} + (h : WeightedEq w r f g) (s) : starNorm w r s f = starNorm w r s g := by + apply Finset.sum_congr rfl + intro t ht + rw [h.atom_eq ht] + +omit [DecidableEq V] in +lemma WeightedEq.add_right {w : Finset V → ℝ} {r : ℕ} {f g : Finset V → k} + (h : WeightedEq w r f g) (b : Finset V → k) : WeightedEq w r (f+b) (g+b) := by + intro s hs hw + simp only [Pi.add_apply,h s hs hw] + +lemma WeightedEq.delta_eq {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + {f g : Finset V → k} (h : WeightedEq w r f g) : WeightedEq w (r+1) (delta f) (delta g) := by + intro s hs hws + apply Finset.sum_congr rfl + intro x hx + have he : s.erase x ∈ level r := by + apply mem_level.mpr + rw [Finset.card_erase_of_mem hx,mem_level.mp hs] + omega + apply h _ he + intro hz + exact hws (hw.weight_eq_zero_of_base (Finset.erase_subset x s) hz) + +lemma WeightedEq.nearMinimal {w : Finset V → ℝ} {r : ℕ} {f g : Finset V → k} + (h : WeightedEq w r f g) {ε : ℝ} (hf : NearMinimal w r ε f) : NearMinimal w r ε g := by + intro s hs hsr b hb + have hh := hf s hs hsr b hb + rwa [h.starNorm_eq s,(h.add_right (delta b)).starNorm_eq s] at hh + +lemma fatFamily_top_eq {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + (N r : ℕ) (θ : ℕ → ℝ) (f : Finset V → k) : + WeightedEq w r f (indicator (fatFamily w N r θ f)) := by + intro s hs hws + have hpos := lt_of_le_of_ne (hw s) (Ne.symm hws) + have hc := mem_level.mp hs + simp only [indicator,fatFamily,hc,le_refl,true_and,Nat.sub_self,fatAt,hpos,and_true] + have htwo : ∀ x : k, x = 0 ∨ x = 1 := by decide + rcases htwo (f s) with hf | hf <;> simp [hf] + +theorem small_cochain_expansion {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + (hN : 0 < N) (hrN : r ≤ N) (hw0 : w ∅ = 1) {η lam ε C : ℝ} + (hη : 0 < η) (hlam : 0 ≤ lam) (hε : 0 ≤ ε) (hC : 0 < C) + (hεsmall : ε*(2:ℝ)^r ≤ 1/2) + (hηsmall : C*(2:ℝ)^(r+1)*((2:ℝ)^N*(N:ℝ)^2*(r:ℝ)*(2*η)) ≤ 1/4) + (hbudget : ∀ a ≤ r, lam*fatBudget N η a ≤ η) + (hmix : LocalMixing w N lam) (hcor : LinkCorrection w r C) + (f : Finset V → k) (hmin : NearMinimal w r ε f) + (hsmall : norm w r f < 1/fatBudget N η r) : + (1/4:ℝ)*norm w r f ≤ C*(2:ℝ)^(r+1)*norm w (r+1) (delta f) := by + let F := fatFamily w N r (fatThreshold N r η) f + have hEq := fatFamily_top_eq hw.nonneg N r (fatThreshold N r η) f + have hF : ¬ F ∅ := fat_empty_false hw hN hrN hw0 hη f hsmall + have hbad : C*(2:ℝ)^(r+1)*norm w (r+1) (indicator (fun T => ¬NoBad F T)) ≤ + (1/4:ℝ)*norm w r (indicator F) := by + have hd := fat_degeneracy_bound hw hN hrN hη hlam hbudget hmix f (r+1) + have hh := mul_le_mul_of_nonneg_left hd (show 0 ≤ C*(2:ℝ)^(r+1) by positivity) + have hh' := mul_le_mul_of_nonneg_right hηsmall (norm_nonneg hw.nonneg r f) + rw [hEq.norm_eq] at hh' + exact hh.trans (by simpa only [← mul_assoc,hEq.norm_eq] using hh') + have hh := small_set_expansion hw.nonneg hF hε hC hεsmall (hEq.nearMinimal hmin) hcor hbad + rwa [← hEq.norm_eq,← (hEq.delta_eq hw).norm_eq] at hh + +end CoboundaryExpanders.FatLadders + +namespace CoboundaryExpanders.LocalRepair + +variable {A B : Type*} [AddCommGroup A] [AddCommGroup B] + +structure Size (A : Type*) [AddCommGroup A] where + val : A → ℝ + zero : val 0 = 0 + nonneg : ∀ a, 0 ≤ val a + triangle : ∀ a b, val (a+b) ≤ val a + val b + +instance : CoeFun (Size A) (fun _ => A → ℝ) := ⟨Size.val⟩ + +theorem repair [Fintype A] (na : Size A) (nb : Size B) (δ : A →+ B) + (P : B → Prop) {C : ℝ} (_ : 0 ≤ C) + (hstep : ∀ a : A, ¬ P (δ a) → ∃ u : A, + nb (δ (a+u)) < nb (δ a) ∧ + na u ≤ C * (nb (δ a) - nb (δ (a+u)))) (f : A) : + ∃ h : A, P (δ (f+h)) ∧ nb (δ (f+h)) ≤ nb (δ f) ∧ + na h ≤ C * (nb (δ f) - nb (δ (f+h))) := by + classical + let S : Finset A := Finset.univ.filter (fun h => + na h ≤ C * (nb (δ f) - nb (δ (f+h)))) + have hz : (0 : A) ∈ S := by simp [S,na.zero] + obtain ⟨h,hh,hmin⟩ := S.exists_min_image (fun h => nb (δ (f+h))) ⟨0,hz⟩ + have hbound : na h ≤ C * (nb (δ f) - nb (δ (f+h))) := (Finset.mem_filter.mp hh).2 + refine ⟨h,?_,by simpa only [add_zero] using hmin 0 hz,hbound⟩ + by_contra hp + obtain ⟨u,hu,hcost⟩ := hstep (f+h) hp + have hmem : h+u ∈ S := by + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + calc + na (h+u) ≤ na h + na u := na.triangle h u + _ ≤ C * (nb (δ f) - nb (δ (f+h))) + + C * (nb (δ (f+h)) - nb (δ ((f+h)+u))) := add_le_add hbound hcost + _ = C * (nb (δ f) - nb (δ (f+(h+u)))) := by rw [add_assoc]; ring + have hcontra := hmin (h+u) hmem + rw [← add_assoc] at hcontra + exact (not_lt_of_ge hcontra) hu + +theorem cosystolic_correction [Fintype A] (na : Size A) (nb : Size B) + (δ : A →+ B) (P : B → Prop) {C μ : ℝ} (hC : 0 ≤ C) (hμ : 0 < μ) + (hstep : ∀ a : A, ¬ P (δ a) → ∃ u : A, + nb (δ (a+u)) < nb (δ a) ∧ + na u ≤ C * (nb (δ a) - nb (δ (a+u)))) + (hsmall : ∀ a : A, P (δ a) → nb (δ a) < μ → δ a = 0) + (hunit : ∀ a : A, na a ≤ 1) + (f : A) : + ∃ h : A, δ (f+h) = 0 ∧ na h ≤ max C (1/μ) * nb (δ f) := by + by_cases hf : nb (δ f) < μ + · obtain ⟨h,hp,hdecrease,hbound⟩ := repair na nb δ P hC hstep f + have hz := hsmall (f+h) hp (hdecrease.trans_lt hf) + refine ⟨h,hz,?_⟩ + rw [hz,nb.zero,sub_zero] at hbound + exact hbound.trans (mul_le_mul_of_nonneg_right (le_max_left _ _) (nb.nonneg _)) + · refine ⟨-f,by simp,?_⟩ + calc + na (-f) ≤ 1 := hunit _ + _ ≤ (1/μ) * nb (δ f) := by + have hh : μ ≤ nb (δ f) := le_of_not_gt hf + have hd := div_le_div_of_nonneg_right hh hμ.le + simpa [div_self (ne_of_gt hμ),div_eq_mul_inv,mul_comm] using hd + _ ≤ max C (1/μ) * nb (δ f) := + mul_le_mul_of_nonneg_right (le_max_right _ _) (nb.nonneg _) + +end CoboundaryExpanders.LocalRepair + +namespace CoboundaryExpanders.FatLadders + +section +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +lemma support_starNorm {w : Finset V → ℝ} {r : ℕ} {s : Finset V} {f : Finset V → k} + (hf : ∀ t, ¬s ⊆ t → f t = 0) : starNorm w r s f = norm w r f := by + apply Finset.sum_congr rfl + intro t ht + by_cases hs : s ⊆ t + · exact ite_eq_left hs + · simp [hs,atom,hf t hs] + +lemma local_global_difference (w : Finset V → ℝ) (r : ℕ) (s : Finset V) + (f g : Finset V → k) (hg : ∀ t, ¬s ⊆ t → g t = 0) : + norm w r f - norm w r (f+g) = starNorm w r s f - starNorm w r s (f+g) := by + unfold norm starNorm starSum + rw [← Finset.sum_sub_distrib,← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro t ht + by_cases hs : s ⊆ t + · simp [hs] + · simp [hs,atom,hg t hs] + +theorem nearMinimal_repair_step {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + {r : ℕ} {ε C : ℝ} (hε : 0 < ε) (hC : 0 ≤ C) + (hcor : LinkCorrection w (r-1) C) (f : Finset V → k) + (hmin : ¬NearMinimal w r ε f) : + ∃ u : Finset V → k, norm w r (f+delta u) < norm w r f ∧ + norm w (r-1) u ≤ (2*C/ε)*(norm w r f-norm w r (f+delta u)) := by + unfold NearMinimal at hmin + push Not at hmin + obtain ⟨s,hs,hsr,b,hb,hdec⟩ := hmin + obtain ⟨c,hc,htop,hcost⟩ := hcor s hs (by omega) b hb + let u := b+delta c + have hdu : delta u = delta b := by simp [u] + have hu : ∀ t, ¬s ⊆ t → u t = 0 := by + intro t ht + simp [u,hb t ht,delta_support hc t ht] + have hd : ∀ t, ¬s ⊆ t → delta b t = 0 := delta_support hb + have hdiff := local_global_difference w r s f (delta b) hd + have hm := starNorm_nonneg hw r s f + have hm' := starNorm_nonneg hw r s (f+delta b) + have hpositive : 0 < starNorm w r s f := by nlinarith + have hstrict : norm w r (f+delta b) < norm w r f := by nlinarith + have hid : delta b = f+(f+delta b) := by + funext t + simp only [Pi.add_apply,← add_assoc,CharTwo.add_self_eq_zero,zero_add] + have htriangle : starNorm w r s (delta b) ≤ + starNorm w r s f+starNorm w r s (f+delta b) := by + conv_lhs => rw [hid] + exact starNorm_add_le hw r s f (f+delta b) + have hrone : r-1+1 = r := by have := hs.card_pos; omega + rw [hrone,support_starNorm hu] at hcost + refine ⟨u,by rwa [hdu],?_⟩ + rw [hdu] + calc + norm w (r-1) u ≤ C*starNorm w r s (delta b) := hcost + _ ≤ C*(starNorm w r s f+starNorm w r s (f+delta b)) := + mul_le_mul_of_nonneg_left htriangle hC + _ ≤ 2*C*starNorm w r s f := by nlinarith + _ ≤ (2*C/ε)*(norm w r f-norm w r (f+delta b)) := by + rw [div_mul_eq_mul_div] + apply (le_div_iff₀ hε).mpr + have hsmall : ε*starNorm w r s f ≤ norm w r f-norm w r (f+delta b) := by linarith + nlinarith [mul_le_mul_of_nonneg_left hsmall (show 0 ≤ 2*C by positivity)] + +def normSize (w : Finset V → ℝ) (hw : ∀ s, 0 ≤ w s) (r : ℕ) : + LocalRepair.Size (Finset V → k) where + val := norm w r + zero := norm_zero w r + nonneg := norm_nonneg hw r + triangle := norm_add_le hw r + +def deltaHom : (Finset V → k) →+ (Finset V → k) where + toFun := delta + map_zero' := delta_zero + map_add' := delta_add + +theorem repair_coboundary {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + {r : ℕ} {ε C : ℝ} (hε : 0 < ε) (hC : 0 ≤ C) + (hcor : LinkCorrection w (r-1) C) (f : Finset V → k) : + ∃ h : Finset V → k, NearMinimal w r ε (delta (f+h)) ∧ + norm w r (delta (f+h)) ≤ norm w r (delta f) ∧ + norm w (r-1) h ≤ (2*C/ε)*(norm w r (delta f)-norm w r (delta (f+h))) := by + apply LocalRepair.repair (normSize w hw (r-1)) (normSize w hw r) deltaHom + (NearMinimal w r ε) (div_nonneg (by positivity) hε.le) _ f + intro a ha + obtain ⟨u,hdec,hcost⟩ := nearMinimal_repair_step hw hε hC hcor (delta a) ha + refine ⟨u,?_,?_⟩ + · change norm w r (delta (a+u)) < norm w r (delta a) + simpa only [delta_add] using hdec + · change norm w (r-1) u ≤ (2*C/ε)*(norm w r (delta a)-norm w r (delta (a+u))) + simpa only [delta_add] using hcost + +end + +section +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +lemma norm_le_choose {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (hw0 : w ∅ = 1) (r : ℕ) (f : Finset V → k) : + norm w r f ≤ (Nat.choose N r : ℝ) := by + calc + norm w r f ≤ ∑ t ∈ level r, w t := Finset.sum_le_sum (fun t _ => atom_le_weight hw.nonneg f t) + _ = starSum r ∅ w := by simp [starSum] + _ = _ := by rw [hw.balance ∅ r (by simp)]; simp [hw0] + +theorem cosystolic_from_local {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + (hN : 0 < N) (hrN : r ≤ N) (hw0 : w ∅ = 1) {η lam ε C : ℝ} + (hη : 0 < η) (hlam : 0 ≤ lam) (hε : 0 < ε) (hC : 0 < C) + (hεsmall : ε*(2:ℝ)^r ≤ 1/2) + (hηsmall : C*(2:ℝ)^(r+1)*((2:ℝ)^N*(N:ℝ)^2*(r:ℝ)*(2*η)) ≤ 1/4) + (hbudget : ∀ a ≤ r, lam*fatBudget N η a ≤ η) + (hmix : LocalMixing w N lam) (hcor : LinkCorrection w r C) + (hcor' : LinkCorrection w (r-1) C) (f : Finset V → k) : + ∃ h : Finset V → k, norm w r (delta (f+h)) = 0 ∧ + norm w (r-1) h ≤ + (1+2*C/ε+(Nat.choose N (r-1):ℝ)*fatBudget N η r)*norm w r (delta f) := by + let μ := 1/fatBudget N η r + have hμ : 0 < μ := one_div_pos.mpr (fatBudget_pos hN hη r) + have hC0 : 0 ≤ 2*C/ε := div_nonneg (by positivity) hε.le + have hB0 : 0 ≤ (Nat.choose N (r-1):ℝ)*fatBudget N η r := + mul_nonneg (Nat.cast_nonneg _) (fatBudget_pos hN hη r).le + by_cases hf : norm w r (delta f) < μ + · obtain ⟨h,hmin,hdecrease,hcost⟩ := repair_coboundary hw.nonneg hε hC.le hcor' f + have hs := small_cochain_expansion hw hN hrN hw0 hη hlam hε.le hC hεsmall hηsmall + hbudget hmix hcor (delta (f+h)) hmin (hdecrease.trans_lt hf) + rw [delta_delta,norm_zero,mul_zero] at hs + have hz : norm w r (delta (f+h)) = 0 := by + have hn := norm_nonneg hw.nonneg r (delta (f+h)) + linarith + refine ⟨h,hz,?_⟩ + rw [hz,sub_zero] at hcost + apply hcost.trans + apply mul_le_mul_of_nonneg_right _ (norm_nonneg hw.nonneg r (delta f)) + linarith + · refine ⟨-f,by simp,?_⟩ + have hbig : μ ≤ norm w r (delta f) := le_of_not_gt hf + have hbound := mul_le_mul_of_nonneg_left hbig hB0 + have hident : (Nat.choose N (r-1):ℝ)*fatBudget N η r*μ = (Nat.choose N (r-1):ℝ) := by + dsimp [μ] + field_simp [ne_of_gt (fatBudget_pos hN hη r)] + rw [hident] at hbound + calc + norm w (r-1) (-f) ≤ (Nat.choose N (r-1):ℝ) := norm_le_choose hw hw0 _ _ + _ ≤ (Nat.choose N (r-1):ℝ)*fatBudget N η r*norm w r (delta f) := hbound + _ ≤ _ := by + apply mul_le_mul_of_nonneg_right _ (norm_nonneg hw.nonneg r (delta f)) + linarith + +theorem uniform_cosystolic_from_local (N r : ℕ) (hN : 0 < N) (hrN : r ≤ N) + (C : ℝ) (hC : 0 < C) : + ∃ lam K : ℝ, 0 < lam ∧ 0 < K ∧ + ∀ (V : Type) [Fintype V] [DecidableEq V] (w : Finset V → ℝ), Balanced w N → w ∅ = 1 → + LocalMixing w N lam → LinkCorrection w r C → LinkCorrection w (r-1) C → + ∀ f : Finset V → k, ∃ h : Finset V → k, + norm w r (delta (f+h)) = 0 ∧ norm w (r-1) h ≤ K*norm w r (delta f) := by + let A : ℝ := C*(2:ℝ)^(r+1)*(2:ℝ)^N*(N:ℝ)^2*(r:ℝ)*2 + have hA : 0 ≤ A := by dsimp [A]; positivity + let η : ℝ := 1/(4*(A+1)) + have hden : 0 < 4*(A+1) := by linarith + have hη : 0 < η := one_div_pos.mpr hden + have hηsmall : C*(2:ℝ)^(r+1)*((2:ℝ)^N*(N:ℝ)^2*(r:ℝ)*(2*η)) ≤ 1/4 := by + have hh : A*η ≤ 1/4 := by + dsimp [η] + rw [mul_one_div] + apply (div_le_iff₀ hden).mpr + linarith + convert hh using 1 + dsimp [A] + ring + let ε : ℝ := 1/(2*(2:ℝ)^r) + have hε : 0 < ε := by dsimp [ε]; positivity + have hεsmall : ε*(2:ℝ)^r ≤ 1/2 := by dsimp [ε]; field_simp; norm_num + obtain ⟨lam,hlam,hbudget⟩ := exists_mixing_tolerance N r hN hη + let K : ℝ := 1+2*C/ε+(Nat.choose N (r-1):ℝ)*fatBudget N η r + have hK : 0 < K := by + have hb := fatBudget_pos hN hη r + dsimp [K] + positivity + refine ⟨lam,K,hlam,hK,?_⟩ + intro V _ _ w hw hw0 hmix hcor hcor' f + exact cosystolic_from_local hw hN hrN hw0 hη hlam.le hε hC hεsmall hηsmall hbudget + hmix hcor hcor' f + +end + +section +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +omit [Fintype V] [DecidableEq V] in +lemma atom_scale (w : Finset V → ℝ) (a : ℝ) (f : Finset V → k) (s) : + atom (fun t => a*w t) f s = a*atom w f s := by + unfold atom + split_ifs <;> simp +omit [DecidableEq V] in +lemma norm_scale (w : Finset V → ℝ) (a : ℝ) (r) (f : Finset V → k) : + norm (fun t => a*w t) r f = a*norm w r f := by + simp only [norm,atom_scale,Finset.mul_sum] +lemma starSum_scale (w : Finset V → ℝ) (a : ℝ) (r s) : + starSum r s (fun t => a*w t) = a*starSum r s w := by + simp only [starSum,Finset.mul_sum] + apply Finset.sum_congr rfl + intro t ht + split_ifs <;> simp +lemma starNorm_scale (w : Finset V → ℝ) (a : ℝ) (r s) (f : Finset V → k) : + starNorm (fun t => a*w t) r s f = a*starNorm w r s f := by + unfold starNorm starSum + simp only [atom_scale,Finset.mul_sum] + apply Finset.sum_congr rfl + intro t ht + split_ifs <;> simp +lemma collisionMass_scale (w : Finset V → ℝ) (a : ℝ) (F : Finset V → Prop) (s) : + collisionMass (fun t => a*w t) F s = a*collisionMass w F s := by + simp only [collisionMass,Finset.mul_sum] + apply Finset.sum_congr rfl + intro t ht + split_ifs <;> simp +lemma Balanced.scale {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + {a : ℝ} (ha : 0 ≤ a) : Balanced (fun t => a*w t) N := by + refine ⟨fun s => mul_nonneg ha (hw.nonneg s),fun s hs => by rw [hw.vanish s hs,mul_zero],?_⟩ + intro s r hr + rw [starSum_scale,hw.balance s r hr] + ring +lemma LinkCorrection.scale {w : Finset V → ℝ} {r : ℕ} {C a : ℝ} + (hc : LinkCorrection w r C) (ha : 0 ≤ a) : LinkCorrection (fun t => a*w t) r C := by + intro s hs hsr g hg + obtain ⟨b,hb,he,hbound⟩ := hc s hs hsr g hg + refine ⟨b,hb,he,?_⟩ + rw [starNorm_scale,starNorm_scale,mul_left_comm C a] + exact mul_le_mul_of_nonneg_left hbound ha +lemma LinkCorrection.mono {w : Finset V → ℝ} (hw : ∀s,0≤w s) + {r : ℕ} {C D : ℝ} (hc : LinkCorrection w r C) (hCD : C ≤ D) : LinkCorrection w r D := by + intro s hs hsr g hg + obtain ⟨b,hb,he,hbound⟩ := hc s hs hsr g hg + exact ⟨b,hb,he,hbound.trans (mul_le_mul_of_nonneg_right hCD (starNorm_nonneg hw _ _ _))⟩ +lemma LocalMixing.scale {w : Finset V → ℝ} {N : ℕ} {lam a : ℝ} + (hm : LocalMixing w N lam) (ha : 0 < a) : LocalMixing (fun t => a*w t) N lam := by + intro F s hs t ht hbound + rw [starNorm_scale] at hbound + have hb : starNorm w (s.card+1) s (indicator F) ≤ t*(N-s.card:ℕ)*w s := by + apply (mul_le_mul_iff_right₀ ha).mp + simpa only [mul_assoc,mul_left_comm,mul_comm] using hbound + have h := mul_le_mul_of_nonneg_left (hm F s hs t ht hb) ha.le + rw [collisionMass_scale,starNorm_scale] + simpa only [mul_assoc,mul_left_comm,mul_comm] using h +lemma LocalMixing.mono {w : Finset V → ℝ} (hw : ∀s,0≤w s) + {N : ℕ} {lam mu : ℝ} (hm : LocalMixing w N lam) (hlm : lam ≤ mu) : + LocalMixing w N mu := by + intro F s hs t ht hbound + apply (hm F s hs t ht hbound).trans + apply mul_le_mul_of_nonneg_right _ (starNorm_nonneg hw _ _ _) + exact mul_le_mul_of_nonneg_right (add_le_add_right hlm t) (Nat.cast_nonneg N) + +end + +theorem uniform_all_cosystolic_from_local (N : ℕ) (hN : 0 < N) (C : ℝ) (hC : 0 < C) : + ∃ lam K : ℝ, 0 < lam ∧ 0 < K ∧ + ∀ (V : Type) [Fintype V] [DecidableEq V] (w : Finset V → ℝ), Balanced w N → w ∅ = 1 → + LocalMixing w N lam → (∀ r < N, LinkCorrection w r C) → + ∀ r < N, ∀ f : Finset V → k, ∃ h : Finset V → k, + norm w r (delta (f+h)) = 0 ∧ norm w (r-1) h ≤ K*norm w r (delta f) := by + have aux : ∀ m ≤ N, ∃ lam K : ℝ, 0 < lam ∧ 0 < K ∧ + ∀ (V : Type) [Fintype V] [DecidableEq V] (w : Finset V → ℝ), Balanced w N → w ∅ = 1 → + LocalMixing w N lam → (∀ r < N, LinkCorrection w r C) → + ∀ r < m, ∀ f : Finset V → k, ∃ h : Finset V → k, + norm w r (delta (f+h)) = 0 ∧ norm w (r-1) h ≤ K*norm w r (delta f) := by + intro m + induction m with + | zero => + intro _ + refine ⟨1,1,by norm_num,by norm_num,?_⟩ + intro V _ _ w hw hw0 hm hc r hr + omega + | succ m ih => + intro hmN + obtain ⟨l₀,K₀,hl₀,hK₀,h₀⟩ := ih (by omega) + obtain ⟨l₁,K₁,hl₁,hK₁,h₁⟩ := uniform_cosystolic_from_local N m hN (by omega) C hC + refine ⟨min l₀ l₁,max K₀ K₁,lt_min hl₀ hl₁,hK₀.trans_le (le_max_left _ _),?_⟩ + intro V _ _ w hw hw0 hm hc r hr f + rcases Nat.lt_succ_iff_lt_or_eq.mp hr with hr | rfl + · obtain ⟨h,hz,hb⟩ := h₀ V w hw hw0 (hm.mono hw.nonneg (min_le_left _ _)) hc r hr f + exact ⟨h,hz,hb.trans (mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg hw.nonneg r _))⟩ + · obtain ⟨h,hz,hb⟩ := h₁ V w hw hw0 (hm.mono hw.nonneg (min_le_right _ _)) + (hc r (by omega)) (hc (r-1) (by omega)) f + exact ⟨h,hz,hb.trans (mul_le_mul_of_nonneg_right (le_max_right _ _) (norm_nonneg hw.nonneg r _))⟩ + exact aux N le_rfl + +theorem uniform_raw_cosystolic_from_local (N : ℕ) (hN : 0 < N) (C : ℝ) (hC : 0 < C) : + ∃ lam K : ℝ, 0 < lam ∧ 0 < K ∧ + ∀ (V : Type) [Fintype V] [DecidableEq V] (w : Finset V → ℝ), Balanced w N → 0 < w ∅ → + LocalMixing w N lam → (∀ r < N, LinkCorrection w r C) → + ∀ r < N, ∀ f : Finset V → k, ∃ h : Finset V → k, + norm w r (delta (f+h)) = 0 ∧ norm w (r-1) h ≤ K*norm w r (delta f) := by + obtain ⟨lam,K,hlam,hK,hh⟩ := uniform_all_cosystolic_from_local N hN C hC + refine ⟨lam,K,hlam,hK,?_⟩ + intro V _ _ w hw hw0 hmix hcor r hr f + have ha : 0 < (w ∅)⁻¹ := inv_pos.mpr hw0 + have hn : (w ∅)⁻¹*w ∅ = 1 := inv_mul_cancel₀ hw0.ne' + obtain ⟨h,hz,hb⟩ := hh V (fun s => (w ∅)⁻¹*w s) (hw.scale ha.le) hn + (hmix.scale ha) (fun r hr => (hcor r hr).scale ha.le) r hr f + simp only [norm_scale] at hz hb + refine ⟨h,(mul_eq_zero.mp hz).resolve_left ha.ne',?_⟩ + apply (mul_le_mul_iff_right₀ ha).mp + simpa only [mul_comm,mul_left_comm,mul_assoc] using hb +end CoboundaryExpanders.FatLadders + +namespace CoboundaryExpanders.Construction +open InfiniteChains FiniteWeights TypedCosetFaces + +theorem uniform_actual_raw_cosystolic (n : ℕ) (hn : 2 ≤ n) : + ∃ Q : ℕ, ∃ K : ℝ, 0 < K ∧ ∀ p : ℕ, ∀ _ : Fact p.Prime, Q < p → + ∀ m : ℕ, 2 ≤ m → + letI : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + let w := fun t => (cofaces (TypedCosetFaces.complex (reducedLocalGroup p n (by omega) m)) (n+1) t : ℝ) + ∀ r : ℕ, r < n+1 → ∀ f : Finset (Vertex (reducedLocalGroup p n (by omega) m)) → ZMod 2, + ∃ h, FatLadders.norm w r (FatLadders.delta (f+h)) = 0 ∧ + FatLadders.norm w (r-1) h ≤ K * FatLadders.norm w r (FatLadders.delta f) := by + obtain ⟨Q₀,C,hC⟩ := uniform_actual_linkCorrection n (by omega) + have hCp : 0 < (C:ℝ)+1 := by positivity + obtain ⟨lam,K,hlam,hK,hraw⟩ := FatLadders.uniform_raw_cosystolic_from_local (n+1) (by omega) ((C:ℝ)+1) hCp + obtain ⟨Q₁,hmix⟩ := uniform_actual_mixing n hn hlam + refine ⟨max Q₀ Q₁,K,hK,?_⟩ + intro p hp hq m hm + let : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + dsimp only + have hP := finite_pure (reducedLocalGroup p n (by omega) m) + rw [Fintype.card_fin] at hP + apply hraw _ _ (cofaces_balanced _ (n+1)) + · exact_mod_cast (cofaces_pos_iff hP ∅).mpr (TypedCosetFaces.complex _).empty_mem + · exact hmix p hp ((le_max_right _ _).trans_lt hq) m hm + · intro r hr + exact (hC p hp ((le_max_left _ _).trans_lt hq) m hm r hr).mono + (fun s => Nat.cast_nonneg _) (by linarith) +end CoboundaryExpanders.Construction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/FatLadders.lean b/lean/OAI/Combinatorics/Coboundary/FatLadders.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8e2d99c49368c2dfc977f452087709a8964f8f6 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/FatLadders.lean @@ -0,0 +1,978 @@ +import Mathlib + +namespace OAI + +/-! +Balanced chamber weights, fat ladders, degeneracy, and cochain counting. +-/ + +noncomputable section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix + +namespace CoboundaryExpanders.FatLadders + +section +attribute [local instance] Classical.propDecidable +variable {V : Type*} [DecidableEq V] + +inductive Path (F : Finset V → Prop) (s : Finset V) : Finset V → Prop + | refl : F s → Path F s s + | step {a : Finset V} (v : V) : Path F s a → v ∉ a → F (insert v a) → + Path F s (insert v a) + +namespace Path +variable {F : Finset V → Prop} {s a : Finset V} +lemma fat (h : Path F s a) : F a := by cases h with | refl h => exact h | step _ _ _ h => exact h +lemma subset (h : Path F s a) : s ⊆ a := by + induction h with + | refl _ => exact Finset.Subset.refl _ + | step v _ _ _ ih => exact ih.trans (Finset.subset_insert _ _) +lemma start (h : Path F s a) : F s := by + induction h with | refl h => exact h | step _ _ _ _ ih => exact ih +end Path + +def NoBad (F : Finset V → Prop) (T : Finset V) : Prop := + ∀ a ⊆ T, ∀ x ∈ a, ∀ y ∈ a, x ≠ y → + F (a.erase x) → F (a.erase y) → F ((a.erase x).erase y) + +def Minimal (F : Finset V → Prop) (s : Finset V) : Prop := + F s ∧ ∀ x ∈ s, ¬ F (s.erase x) + +lemma Path.erase_fat {F : Finset V → Prop} {s a T : Finset V} + (h : Path F s a) (hT : a ⊆ T) (hn : NoBad F T) (x : V) (hx : x ∈ s) + (he : F (a.erase x)) : F (s.erase x) := by + induction h with + | refl _ => exact he + | @step b v hb hv hf ih => + have hxb : x ∈ b := hb.subset hx + have hvx : v ≠ x := by intro e; subst v; exact hv hxb + have hfb : F b := hb.fat + have hsmall : F (b.erase x) := by + have hh := hn (insert v b) hT v (Finset.mem_insert_self _ _) x + (Finset.mem_insert_of_mem hxb) hvx (by simpa [Finset.erase_insert hv] using hfb) he + simpa only [Finset.erase_insert hv] using hh + exact ih ((Finset.subset_insert v b).trans hT) hsmall + +lemma Path.erase_path {F : Finset V → Prop} {s a T : Finset V} + (h : Path F s a) (hT : a ⊆ T) (hn : NoBad F T) (x : V) (hx : x ∉ s) + (he : F (a.erase x)) : Path F s (a.erase x) := by + induction h with + | refl hf => simpa [Finset.erase_eq_of_notMem hx] using Path.refl hf + | @step b v hb hv hf ih => + by_cases hvx : v = x + · subst v + simpa only [Finset.erase_insert hv] using hb + · by_cases hxb : x ∈ b + · have hsmall : F (b.erase x) := by + have hh := hn (insert v b) hT v (Finset.mem_insert_self _ _) x + (Finset.mem_insert_of_mem hxb) hvx + (by simpa only [Finset.erase_insert hv] using hb.fat) he + simpa only [Finset.erase_insert hv] using hh + have hp := ih ((Finset.subset_insert v b).trans hT) hsmall + have hv' : v ∉ b.erase x := fun hh => hv (Finset.mem_of_mem_erase hh) + rw [Finset.erase_insert_of_ne hvx] + exact Path.step v hp hv' (by simpa only [Finset.erase_insert_of_ne hvx] using he) + · have hnot : x ∉ insert v b := by simp [hxb,Ne.symm hvx] + simpa only [Finset.erase_eq_of_notMem hnot] using Path.step v hb hv hf + +theorem exchange {F : Finset V → Prop} {s T : Finset V} (hs : Minimal F s) + (hn : NoBad F T) {x y : V} (hx : x ∈ T) (hy : y ∈ T) + (hp : Path F s (T.erase x)) (hf : F (T.erase y)) : + Path F s (T.erase y) := by + by_cases hxy : x = y + · simpa only [hxy] using hp + have he : F ((T.erase x).erase y) := hn T (Finset.Subset.refl _) x hx y hy hxy hp.fat hf + have hys : y ∉ s := by + intro h + exact hs.2 y h (hp.erase_fat (Finset.erase_subset _ _) hn y h he) + have hr := hp.erase_path (Finset.erase_subset _ _) hn y hys he + have hxi : x ∉ (T.erase x).erase y := by simp + have hrep : insert x ((T.erase x).erase y) = T.erase y := by + rw [Finset.erase_right_comm,Finset.insert_erase] + exact Finset.mem_erase.mpr ⟨hxy,hx⟩ + rw [← hrep] + exact Path.step x hr hxi (hrep ▸ hf) + +abbrev k := ZMod 2 + +def indicator (F : Finset V → Prop) (s : Finset V) : k := if F s then 1 else 0 + +def delta (f : Finset V → k) (s : Finset V) : k := ∑ x ∈ s, f (s.erase x) + +lemma path_indicator_le_support {F : Finset V → Prop} {s a : Finset V} : + indicator (Path F s) a ≠ 0 → indicator F a ≠ 0 := by + intro h + simp only [indicator,ne_eq,ite_eq_right_iff,one_ne_zero,imp_false,not_not] at h ⊢ + exact h.fat + +theorem localized_boundary_support {F : Finset V → Prop} {s T : Finset V} + (hs : Minimal F s) (hn : NoBad F T) + (hb : delta (indicator (Path F s)) T ≠ 0) : + delta (indicator F) T ≠ 0 := by + have hex : ∃ x ∈ T, Path F s (T.erase x) := by + by_contra h + push Not at h + apply hb + apply Finset.sum_eq_zero + intro x hx + simp only [indicator,ite_eq_right (h x hx)] + obtain ⟨x,hx,hp⟩ := hex + have he : delta (indicator (Path F s)) T = delta (indicator F) T := by + apply Finset.sum_congr rfl + intro y hy + apply congrArg (fun b : Prop => if b then (1:k) else 0) + apply propext + exact ⟨Path.fat, fun hf => exchange hs hn hx hy hp hf⟩ + rwa [← he] + +lemma indicator_vanish {F : Finset V → Prop} {s a : Finset V} (h : ¬ s ⊆ a) : + indicator (Path F s) a = 0 := by + exact ite_eq_right (fun hp => h hp.subset) + +theorem exists_minimal_path (F : Finset V → Prop) (a : Finset V) (ha : F a) : + ∃ s ⊆ a, Minimal F s ∧ Path F s a := by + induction a using Finset.strongInductionOn with + | _ a ih => + by_cases h : ∃ x ∈ a, F (a.erase x) + · obtain ⟨x,hx,hf⟩ := h + obtain ⟨s,hs,hm,hp⟩ := ih (a.erase x) (Finset.erase_ssubset hx) hf + refine ⟨s,hs.trans (Finset.erase_subset _ _),hm,?_⟩ + have he : insert x (a.erase x) = a := Finset.insert_erase hx + have hf' : F (insert x (a.erase x)) := by rwa [he] + simpa only [he] using Path.step x hp (Finset.notMem_erase _ _) hf' + · refine ⟨a,Finset.Subset.refl _,⟨ha,?_⟩,Path.refl ha⟩ + intro x hx hf + exact h ⟨x,hx,hf⟩ + +lemma minimal_nonempty {F : Finset V → Prop} (hF : ¬ F ∅) {s : Finset V} + (hs : Minimal F s) : s.Nonempty := by + by_contra h + have he := Finset.not_nonempty_iff_eq_empty.mp h + subst s + exact hF hs.1 + +end + +section +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +def level (r : ℕ) : Finset (Finset V) := Finset.univ.powersetCard r +omit [DecidableEq V] in +@[simp] lemma mem_level {r : ℕ} {s : Finset V} : s ∈ level (V:=V) r ↔ s.card = r := by + simp [level] + +def atom (w : Finset V → ℝ) (f : Finset V → k) (s : Finset V) : ℝ := + if f s = 0 then 0 else w s + +def norm (w : Finset V → ℝ) (r : ℕ) (f : Finset V → k) : ℝ := + ∑ s ∈ level r, atom w f s + +def starSum (r : ℕ) (s : Finset V) (f : Finset V → ℝ) : ℝ := + ∑ t ∈ level r, if s ⊆ t then f t else 0 + +def starNorm (w : Finset V → ℝ) (r : ℕ) (s : Finset V) (f : Finset V → k) : ℝ := + starSum r s (atom w f) + +omit [Fintype V] [DecidableEq V] in +lemma atom_nonneg {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (f : Finset V → k) (s) : + 0 ≤ atom w f s := by unfold atom; split_ifs; exact le_rfl; exact hw s +omit [DecidableEq V] in +lemma norm_nonneg {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (r) (f : Finset V → k) : + 0 ≤ norm w r f := Finset.sum_nonneg (fun s _ => atom_nonneg hw f s) +lemma starNorm_nonneg {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (r s) (f : Finset V → k) : + 0 ≤ starNorm w r s f := by + apply Finset.sum_nonneg + intro t ht + split_ifs + · exact atom_nonneg hw f t + · exact le_rfl +omit [Fintype V] [DecidableEq V] in +lemma atom_add_le {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (f g : Finset V → k) (s) : + atom w (f+g) s ≤ atom w f s + atom w g s := by + unfold atom + simp only [Pi.add_apply] + by_cases hf : f s = 0 <;> by_cases hg : g s = 0 <;> simp [hf,hg] + split_ifs <;> linarith [hw s] + +lemma starNorm_add_le {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (r s) (f g : Finset V → k) : + starNorm w r s (f+g) ≤ starNorm w r s f + starNorm w r s g := by + rw [starNorm,starNorm,starNorm,starSum,starSum,starSum,← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro t ht + split_ifs + · exact atom_add_le hw f g t + · simp + +lemma starSum_mono {r : ℕ} {s : Finset V} {f g : Finset V → ℝ} + (h : ∀ t ∈ level r, s ⊆ t → f t ≤ g t) : starSum r s f ≤ starSum r s g := by + apply Finset.sum_le_sum + intro t ht + split_ifs with hs + · exact h t ht hs + · rfl + +omit [Fintype V] in +lemma subsets_card_le (S : Finset (Finset V)) (t : Finset V) : + (S.filter (fun s => s ⊆ t)).card ≤ 2^t.card := by + rw [← Finset.card_powerset] + exact Finset.card_le_card (by intro s hs; exact Finset.mem_powerset.mpr (Finset.mem_filter.mp hs).2) + +lemma sum_star_le (S : Finset (Finset V)) (r : ℕ) (f : Finset V → ℝ) + (hf : ∀ t, 0 ≤ f t) : + (∑ s ∈ S, starSum r s f) ≤ (2:ℝ)^r * ∑ t ∈ level r, f t := by + unfold starSum + rw [Finset.sum_comm,Finset.mul_sum] + apply Finset.sum_le_sum + intro t ht + have he : (∑ s ∈ S, if s ⊆ t then f t else 0) = + ((S.filter (fun s => s ⊆ t)).card : ℝ) * f t := by + rw [← Finset.sum_filter] + simp + rw [he] + apply mul_le_mul_of_nonneg_right _ (hf t) + have hh := subsets_card_le S t + have hr := mem_level.mp ht + rw [hr] at hh + exact_mod_cast hh + +omit [Fintype V] in +lemma ladder_difference (w : Finset V → ℝ) (F : Finset V → Prop) (s t : Finset V) : + atom w (indicator F + indicator (Path F s)) t = + atom w (indicator F) t - atom w (indicator (Path F s)) t := by + by_cases hp : Path F s t + · have hf := hp.fat + simp [atom,indicator,hp,hf,CharTwo.add_self_eq_zero] + · by_cases hf : F t <;> simp [atom,indicator,hp,hf] + +lemma ladder_star_difference (w : Finset V → ℝ) (F : Finset V → Prop) (r) (s : Finset V) : + starNorm w r s (indicator F + indicator (Path F s)) = + starNorm w r s (indicator F) - starNorm w r s (indicator (Path F s)) := by + unfold starNorm starSum + rw [← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro t ht + split_ifs + · exact ladder_difference w F s t + · ring + +def minimalFaces (F : Finset V → Prop) : Finset (Finset V) := + Finset.univ.filter (Minimal F) + +lemma norm_le_ladders {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + (F : Finset V → Prop) (r : ℕ) : + norm w r (indicator F) ≤ ∑ s ∈ minimalFaces F, starNorm w r s (indicator (Path F s)) := by + unfold norm starNorm starSum + rw [Finset.sum_comm] + apply Finset.sum_le_sum + intro t ht + by_cases hF : F t + · obtain ⟨s,hst,hs,hp⟩ := exists_minimal_path F t hF + have hmem : s ∈ minimalFaces F := by simp [minimalFaces,hs] + calc + atom w (indicator F) t = + (if s ⊆ t then atom w (indicator (Path F s)) t else 0) := by simp [atom,indicator,hF,hp,hst] + _ ≤ ∑ a ∈ minimalFaces F, if a ⊆ t then atom w (indicator (Path F a)) t else 0 := by + apply Finset.single_le_sum _ hmem + intro a ha + split_ifs + · exact atom_nonneg hw _ _ + · exact le_rfl + · have hh : atom w (indicator F) t = 0 := by simp [atom,indicator,hF] + rw [hh] + apply Finset.sum_nonneg + intro a ha + split_ifs + · exact atom_nonneg hw _ _ + · exact le_rfl + +def NearMinimal (w : Finset V → ℝ) (r : ℕ) (ε : ℝ) (f : Finset V → k) : Prop := + ∀ s : Finset V, s.Nonempty → s.card < r → ∀ b : Finset V → k, + (∀ t, ¬ s ⊆ t → b t = 0) → + (1-ε) * starNorm w r s f ≤ starNorm w r s (f + delta b) + +def LinkCorrection (w : Finset V → ℝ) (r : ℕ) (C : ℝ) : Prop := + ∀ s : Finset V, s.Nonempty → s.card ≤ r → ∀ g : Finset V → k, + (∀ t, ¬ s ⊆ t → g t = 0) → + ∃ b : Finset V → k, (∀ t, ¬ s ⊆ t → b t = 0) ∧ + (s.card = r → ∀ t ∈ level r, delta b t = 0) ∧ + starNorm w r s (g + delta b) ≤ C * starNorm w (r+1) s (delta g) + +lemma ladder_local_estimate {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + {F : Finset V → Prop} (hF : ¬ F ∅) {r : ℕ} {ε C : ℝ} + (hε : 0 ≤ ε) (hmin : NearMinimal w r ε (indicator F)) + (hcor : LinkCorrection w r C) {s : Finset V} (hs : Minimal F s) (hr : s.card ≤ r) : + starNorm w r s (indicator (Path F s)) ≤ + C * starNorm w (r+1) s (delta (indicator (Path F s))) + + ε * starNorm w r s (indicator F) := by + let g := indicator (Path F s) + obtain ⟨b,hb,hbe,hcorr⟩ := hcor s (minimal_nonempty hF hs) hr g + (fun t ht => indicator_vanish ht) + have hnear : (1-ε) * starNorm w r s (indicator F) ≤ + starNorm w r s (indicator F + delta b) := by + rcases lt_or_eq_of_le hr with hlt | heq + · exact hmin s (minimal_nonempty hF hs) hlt b hb + · have hd : starNorm w r s (indicator F + delta b) = starNorm w r s (indicator F) := by + unfold starNorm starSum + apply Finset.sum_congr rfl + intro t ht + simp only [atom,Pi.add_apply,hbe heq t ht,add_zero] + rw [hd] + nlinarith [starNorm_nonneg hw r s (indicator F)] + have hid : indicator F + delta b = (g + delta b) + (indicator F + g) := by + funext t + change indicator F t + delta b t = (g t + delta b t) + (indicator F t + g t) + calc + _ = (indicator F t + delta b t) + (g t + g t) := by rw [CharTwo.add_self_eq_zero,add_zero] + _ = _ := by abel + rw [hid] at hnear + have hh := starNorm_add_le hw r s (g + delta b) (indicator F + g) + have hd := ladder_star_difference w F r s + change starNorm w r s (indicator F + g) = _ at hd + rw [hd] at hh + linarith + +lemma starNorm_eq_zero_of_card {w : Finset V → ℝ} {r : ℕ} {s : Finset V} + (hr : r < s.card) (f : Finset V → k) : starNorm w r s f = 0 := by + apply Finset.sum_eq_zero + intro t ht + have hn : ¬ s ⊆ t := by intro h; have := Finset.card_le_card h; have := mem_level.mp ht; omega + exact ite_eq_right hn + +lemma boundary_star_estimate {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + {F : Finset V → Prop} {s : Finset V} (hs : Minimal F s) (r : ℕ) : + starNorm w (r+1) s (delta (indicator (Path F s))) ≤ + starNorm w (r+1) s (delta (indicator F)) + + starNorm w (r+1) s (indicator (fun T => ¬ NoBad F T)) := by + unfold starNorm starSum + rw [← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro t ht + by_cases hst : s ⊆ t + · simp only [ite_eq_left hst] + by_cases hd : delta (indicator (Path F s)) t = 0 + · simp only [atom,hd] + split_ifs <;> linarith [hw t] + · by_cases hn : NoBad F t + · have hh := localized_boundary_support hs hn hd + simp only [atom,ite_eq_right hd,ite_eq_right hh] + exact le_add_of_nonneg_right (by split_ifs <;> linarith [hw t]) + · simp only [atom,ite_eq_right hd,indicator,ite_eq_left hn,one_ne_zero,ite_false] + exact le_add_of_nonneg_left (by split_ifs <;> linarith [hw t]) + · simp only [ite_eq_right hst,add_zero,le_refl] + +theorem fat_ladder_inequality {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + {F : Finset V → Prop} (hF : ¬ F ∅) {r : ℕ} {ε C : ℝ} + (hε : 0 ≤ ε) (hC : 0 ≤ C) (hmin : NearMinimal w r ε (indicator F)) + (hcor : LinkCorrection w r C) : + (1 - ε*(2:ℝ)^r) * norm w r (indicator F) ≤ + C*(2:ℝ)^(r+1) * (norm w (r+1) (delta (indicator F)) + + norm w (r+1) (indicator (fun T => ¬ NoBad F T))) := by + let S := minimalFaces F + have hloc (s : Finset V) (hs : s ∈ S) : + starNorm w r s (indicator (Path F s)) ≤ + C * starNorm w (r+1) s (delta (indicator (Path F s))) + + ε * starNorm w r s (indicator F) := by + have hsm : Minimal F s := (Finset.mem_filter.mp hs).2 + by_cases hr : s.card ≤ r + · exact ladder_local_estimate hw hF hε hmin hcor hsm hr + · rw [starNorm_eq_zero_of_card (lt_of_not_ge hr)] + exact add_nonneg (mul_nonneg hC (starNorm_nonneg hw _ _ _)) + (mul_nonneg hε (starNorm_nonneg hw _ _ _)) + have hlocsum := Finset.sum_le_sum hloc + rw [Finset.sum_add_distrib,← Finset.mul_sum,← Finset.mul_sum] at hlocsum + have hb : (∑ s ∈ S, starNorm w (r+1) s (delta (indicator (Path F s)))) ≤ + (2:ℝ)^(r+1) * (norm w (r+1) (delta (indicator F)) + + norm w (r+1) (indicator (fun T => ¬ NoBad F T))) := by + calc + _ ≤ (∑ s ∈ S, ( starNorm w (r+1) s (delta (indicator F)) + + starNorm w (r+1) s (indicator (fun T => ¬ NoBad F T)))) := by + apply Finset.sum_le_sum + intro s hs + exact boundary_star_estimate hw (Finset.mem_filter.mp hs).2 r + _ = (∑ s ∈ S, starNorm w (r+1) s (delta (indicator F))) + + (∑ s ∈ S, starNorm w (r+1) s (indicator (fun T => ¬ NoBad F T))) := Finset.sum_add_distrib + _ ≤ (2:ℝ)^(r+1) * norm w (r+1) (delta (indicator F)) + + (2:ℝ)^(r+1) * norm w (r+1) (indicator (fun T => ¬ NoBad F T)) := + add_le_add (sum_star_le S (r+1) _ (atom_nonneg hw _)) + (sum_star_le S (r+1) _ (atom_nonneg hw _)) + _ = _ := by ring + have hf : (∑ s ∈ S, starNorm w r s (indicator F)) ≤ (2:ℝ)^r * norm w r (indicator F) := + sum_star_le S r _ (atom_nonneg hw _) + have hcover := norm_le_ladders hw F r + change norm w r (indicator F) ≤ ∑ s ∈ S, starNorm w r s (indicator (Path F s)) at hcover + have htotal := hcover.trans (hlocsum.trans + (add_le_add (mul_le_mul_of_nonneg_left hb hC) (mul_le_mul_of_nonneg_left hf hε))) + nlinarith + +theorem small_set_expansion {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + {F : Finset V → Prop} (hF : ¬ F ∅) {r : ℕ} {ε C : ℝ} + (hε : 0 ≤ ε) (hC : 0 < C) (hεsmall : ε*(2:ℝ)^r ≤ 1/2) + (hmin : NearMinimal w r ε (indicator F)) (hcor : LinkCorrection w r C) + (hbad : C*(2:ℝ)^(r+1) * norm w (r+1) (indicator (fun T => ¬ NoBad F T)) ≤ + (1/4:ℝ) * norm w r (indicator F)) : + (1/4:ℝ) * norm w r (indicator F) ≤ C*(2:ℝ)^(r+1) * + norm w (r+1) (delta (indicator F)) := by + have h := fat_ladder_inequality hw hF hε hC.le hmin hcor + have hf := norm_nonneg hw r (indicator F) + have he := mul_le_mul_of_nonneg_right hεsmall hf + nlinarith + +end + +section +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +def chamberWeight {A : Type*} [Fintype A] (c : A → Finset V) (μ : A → ℝ) + (s : Finset V) : ℝ := ∑ a, if s ⊆ c a then μ a else 0 + +omit [Fintype V] in +lemma chamberWeight_nonneg {A : Type*} [Fintype A] (c : A → Finset V) (μ : A → ℝ) + (hμ : ∀ a, 0 ≤ μ a) (s) : 0 ≤ chamberWeight c μ s := by + apply Finset.sum_nonneg + intro a ha + split_ifs + · exact hμ a + · rfl + +omit [Fintype V] in +lemma chamberWeight_mono {A : Type*} [Fintype A] (c : A → Finset V) (μ : A → ℝ) + (hμ : ∀ a, 0 ≤ μ a) {s t : Finset V} (hst : s ⊆ t) : + chamberWeight c μ t ≤ chamberWeight c μ s := by + apply Finset.sum_le_sum + intro a ha + by_cases ht : t ⊆ c a + · simp only [ite_eq_left ht,ite_eq_left (hst.trans ht),le_refl] + · simp only [ite_eq_right ht] + split_ifs + · exact hμ a + · rfl + +lemma count_cofaces (s t : Finset V) (R : ℕ) (hsR : s.card ≤ R) : + ∑ u ∈ level R, (if s ⊆ u ∧ u ⊆ t then (1:ℝ) else 0) = + if s ⊆ t then (Nat.choose (t.card-s.card) (R-s.card):ℝ) else 0 := by + by_cases hst : s ⊆ t + · rw [ite_eq_left hst,← Finset.sum_filter] + have he : (level R).filter (fun u => s ⊆ u ∧ u ⊆ t) = + (t.powersetCard R).filter (s ⊆ ·) := by + ext u + simp only [Finset.mem_filter,mem_level,Finset.mem_powersetCard] + tauto + rw [he] + simp only [Finset.sum_const,nsmul_eq_mul,mul_one] + exact_mod_cast Finset.card_filter_powersetCard_subset s t R hst hsR + · rw [ite_eq_right hst] + apply Finset.sum_eq_zero + intro u hu + exact ite_eq_right (fun hh => hst (hh.1.trans hh.2)) + +theorem chamberWeight_balance {A : Type*} [Fintype A] + (c : A → Finset V) (μ : A → ℝ) (N : ℕ) (hc : ∀ a, (c a).card = N) + (s : Finset V) (R : ℕ) (hsR : s.card ≤ R) : + starSum R s (chamberWeight c μ) = + (Nat.choose (N-s.card) (R-s.card):ℝ) * chamberWeight c μ s := by + unfold starSum chamberWeight + simp_rw [Finset.mul_sum] + have he (t : Finset V) : + (if s ⊆ t then ∑ a, if t ⊆ c a then μ a else 0 else 0) = + ∑ a, if s ⊆ t ∧ t ⊆ c a then μ a else 0 := by + by_cases h : s ⊆ t <;> simp [h] + simp_rw [he] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a ha + have he' : (∑ t ∈ level R, if s ⊆ t ∧ t ⊆ c a then μ a else 0) = + (∑ t ∈ level R, if s ⊆ t ∧ t ⊆ c a then (1:ℝ) else 0) * μ a := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro t ht + split_ifs <;> ring + rw [he',count_cofaces s (c a) R hsR,hc a] + split_ifs <;> ring + +structure Balanced (w : Finset V → ℝ) (N : ℕ) : Prop where + nonneg : ∀ s, 0 ≤ w s + vanish : ∀ s, N < s.card → w s = 0 + balance : ∀ s R, s.card ≤ R → starSum R s w = + (Nat.choose (N-s.card) (R-s.card):ℝ)*w s + +lemma chamberWeight_balanced {A : Type*} [Fintype A] + (c : A → Finset V) (μ : A → ℝ) (N : ℕ) (hc : ∀ a, (c a).card = N) + (hμ : ∀ a, 0 ≤ μ a) : Balanced (chamberWeight c μ) N := by + refine ⟨chamberWeight_nonneg c μ hμ,?_,chamberWeight_balance c μ N hc⟩ + intro s hs + apply Finset.sum_eq_zero + intro a ha + exact ite_eq_right (by intro h; have := Finset.card_le_card h; rw [hc a] at this; omega) + +lemma choose_le_two_pow (n k : ℕ) : (Nat.choose n k : ℝ) ≤ (2:ℝ)^n := by + exact_mod_cast Nat.choose_le_two_pow n k + +lemma Balanced.star_le {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (s : Finset V) (R : ℕ) : starSum R s w ≤ (2:ℝ)^N * w s := by + by_cases hs : s.card ≤ R + · rw [hw.balance s R hs] + apply mul_le_mul_of_nonneg_right _ (hw.nonneg s) + exact (choose_le_two_pow _ _).trans (pow_le_pow_right₀ (by norm_num) (Nat.sub_le _ _)) + · have he : starSum R s w = 0 := by + apply Finset.sum_eq_zero + intro t ht + exact ite_eq_right (by intro h; have := Finset.card_le_card h; have := mem_level.mp ht; omega) + rw [he] + exact mul_nonneg (by positivity) (hw.nonneg s) + +lemma Balanced.weight_eq_zero_of_base {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + {s t : Finset V} (hst : s ⊆ t) (hs : w s = 0) : w t = 0 := by + have hle : w t ≤ starSum t.card s w := by + calc + w t = (if s ⊆ t then w t else 0) := (ite_eq_left hst).symm + _ ≤ starSum t.card s w := by + unfold starSum + apply Finset.single_le_sum (a := t) (f := fun u : Finset V => if s ⊆ u then w u else 0) _ (mem_level.mpr rfl) + intro u hu + split_ifs + · exact hw.nonneg u + · rfl + rw [hw.balance s t.card (Finset.card_le_card hst),hs,mul_zero] at hle + exact le_antisymm hle (hw.nonneg t) + +lemma sum_children (f : Finset V → ℝ) (j : ℕ) : + (∑ s ∈ level j, starSum (j+1) s f) = + (j+1:ℝ) * ∑ t ∈ level (j+1), f t := by + unfold starSum + rw [Finset.sum_comm,Finset.mul_sum] + apply Finset.sum_congr rfl + intro t ht + have he : (level j).filter (fun s => s ⊆ t) = t.powersetCard j := by + ext s + simp only [Finset.mem_filter,mem_level,Finset.mem_powersetCard] + tauto + rw [← Finset.sum_filter,Finset.sum_const,nsmul_eq_mul,he,Finset.card_powersetCard] + have htc := mem_level.mp ht + rw [htc,Nat.choose_succ_self_right] + push_cast + rfl + +end + +section +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +def Collision (F : Finset V → Prop) (s a : Finset V) : Prop := + ∃ x ∈ a, ∃ y ∈ a, x ≠ y ∧ (a.erase x).erase y = s ∧ + F (a.erase x) ∧ F (a.erase y) + +omit [Fintype V] in +lemma Collision.card {F : Finset V → Prop} {s a : Finset V} + (h : Collision F s a) : a.card = s.card+2 := by + obtain ⟨x,hx,y,hy,hxy,he,hfx,hfy⟩ := h + subst s + have hye : y ∈ a.erase x := Finset.mem_erase.mpr ⟨Ne.symm hxy,hy⟩ + rw [Finset.card_erase_of_mem hye,Finset.card_erase_of_mem hx] + have hh := Finset.one_le_card.mpr ⟨y,hye⟩ + rw [Finset.card_erase_of_mem hx] at hh + omega + +omit [Fintype V] in +lemma Collision.base_lt {F : Finset V → Prop} {r : ℕ} + (hcap : ∀ a, F a → a.card ≤ r) {s a : Finset V} + (h : Collision F s a) : s.card < r := by + have hc := h.card + obtain ⟨x,hx,y,hy,hxy,he,hfx,hfy⟩ := h + have hf := hcap _ hfx + rw [Finset.card_erase_of_mem hx] at hf + omega + +def collisionMass (w : Finset V → ℝ) (F : Finset V → Prop) (s : Finset V) : ℝ := + ∑ a ∈ level (s.card+2), if Collision F s a then w a else 0 + +def thinBases (F : Finset V → Prop) (r : ℕ) : Finset (Finset V) := + Finset.univ.filter (fun s => s.card < r ∧ ¬ F s) + +lemma collisionMass_nonneg {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + (F : Finset V → Prop) (s) : 0 ≤ collisionMass w F s := by + apply Finset.sum_nonneg + intro a ha + split_ifs + · exact hw a + · rfl + +lemma bad_face_cover {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + {F : Finset V → Prop} {r : ℕ} (hcap : ∀ a, F a → a.card ≤ r) (T : Finset V) : + atom w (indicator (fun T => ¬ NoBad F T)) T ≤ + ∑ s ∈ thinBases F r, ∑ a ∈ level (s.card+2), + if Collision F s a ∧ a ⊆ T then w T else 0 := by + have hn (s : Finset V) : 0 ≤ ∑ a ∈ level (s.card+2), + if Collision F s a ∧ a ⊆ T then w T else 0 := by + apply Finset.sum_nonneg + intro a ha + split_ifs + · exact hw T + · rfl + by_cases hbad : ¬ NoBad F T + · have h := hbad + unfold NoBad at h + push Not at h + obtain ⟨a,ha,x,hx,y,hy,hxy,hfx,hfy,hthin⟩ := h + let s := (a.erase x).erase y + have hcol : Collision F s a := ⟨x,hx,y,hy,hxy,rfl,hfx,hfy⟩ + have hs : s ∈ thinBases F r := by + simp only [thinBases,Finset.mem_filter,Finset.mem_univ,true_and] + exact ⟨hcol.base_lt hcap,hthin⟩ + have hle : w T ≤ ∑ b ∈ level (s.card+2), + if Collision F s b ∧ b ⊆ T then w T else 0 := by + calc + w T = (if Collision F s a ∧ a ⊆ T then w T else 0) := (ite_eq_left ⟨hcol,ha⟩).symm + _ ≤ _ := by + apply Finset.single_le_sum (a := a) _ (mem_level.mpr hcol.card) + intro b hb + split_ifs + · exact hw T + · rfl + simp only [atom,indicator,ite_eq_left hbad,one_ne_zero,ite_false] + exact hle.trans (Finset.single_le_sum (fun s _ => hn s) hs) + · simp only [atom,indicator,ite_eq_right hbad,ite_true] + exact Finset.sum_nonneg (fun s _ => hn s) + +theorem bad_mass_le {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + {F : Finset V → Prop} (hcap : ∀ a, F a → a.card ≤ r) (R : ℕ) : + norm w R (indicator (fun T => ¬ NoBad F T)) ≤ + (2:ℝ)^N * ∑ s ∈ thinBases F r, collisionMass w F s := by + calc + _ ≤ ∑ T ∈ level R, ∑ s ∈ thinBases F r, ∑ a ∈ level (s.card+2), + if Collision F s a ∧ a ⊆ T then w T else 0 := + Finset.sum_le_sum (fun T hT => bad_face_cover hw.nonneg hcap T) + _ = ∑ s ∈ thinBases F r, ∑ a ∈ level (s.card+2), + if Collision F s a then starSum R a w else 0 := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro s hs + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a ha + by_cases hcol : Collision F s a <;> simp [hcol,starSum] + _ ≤ (2:ℝ)^N * ∑ s ∈ thinBases F r, collisionMass w F s := by + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro s hs + unfold collisionMass + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro a ha + by_cases hcol : Collision F s a + · simp only [ite_eq_left hcol] + exact hw.star_le a R + · simp only [ite_eq_right hcol,mul_zero,le_refl] + +omit [DecidableEq V] in +lemma level_eq_filter (j : ℕ) : level (V:=V) j = Finset.univ.filter (fun s => s.card = j) := by + ext s + simp + +omit [DecidableEq V] in +lemma sum_thinBases (F : Finset V → Prop) (r : ℕ) (f : Finset V → ℝ) : + (∑ s ∈ thinBases F r, f s) = + ∑ j ∈ Finset.range r, ∑ s ∈ level j, if F s then 0 else f s := by + unfold thinBases + rw [Finset.sum_filter] + simp_rw [level_eq_filter,Finset.sum_filter] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro s hs + by_cases hf : F s + · simp [hf] + · simp [hf] + +theorem degeneracy_estimate {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + (hrN : r ≤ N) {F : Finset V → Prop} (hcap : ∀ a, F a → a.card ≤ r) + (θ : ℕ → ℝ) (lam : ℝ) (hθ : ∀ j < r, 0 ≤ θ j+lam) + (hpair : ∀ s, s.card < r → ¬ F s → + collisionMass w F s ≤ (θ s.card+lam)*(N:ℝ)* + starNorm w (s.card+1) s (indicator F)) (R : ℕ) : + norm w R (indicator (fun T => ¬NoBad F T)) ≤ + (2:ℝ)^N * (N:ℝ)^2 * + ∑ j ∈ Finset.range r, (θ j+lam)*norm w (j+1) (indicator F) := by + apply (bad_mass_le hw hcap R).trans + rw [sum_thinBases] + have hsum : (∑ j ∈ Finset.range r, ∑ s ∈ level j, + if F s then 0 else collisionMass w F s) ≤ + (N:ℝ)^2 * ∑ j ∈ Finset.range r, (θ j+lam)*norm w (j+1) (indicator F) := by + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro j hj + have hjr := Finset.mem_range.mp hj + have hc : 0 ≤ (θ j+lam)*(N:ℝ) := mul_nonneg (hθ j hjr) (Nat.cast_nonneg N) + calc + _ ≤ ∑ s ∈ level j, (θ j+lam)*(N:ℝ)*starNorm w (j+1) s (indicator F) := by + apply Finset.sum_le_sum + intro s hs + have he := mem_level.mp hs + by_cases hf : F s + · rw [ite_eq_left hf] + exact mul_nonneg hc (starNorm_nonneg hw.nonneg _ _ _) + · rw [ite_eq_right hf] + simpa only [he] using hpair s (by omega) hf + _ = (θ j+lam)*(N:ℝ)*(j+1:ℝ)*norm w (j+1) (indicator F) := by + rw [← Finset.mul_sum] + change (θ j+lam)*(N:ℝ)*(∑ s ∈ level j, starSum (j+1) s (atom w (indicator F))) = _ + rw [sum_children] + simp only [norm,mul_assoc] + _ ≤ (N:ℝ)^2*((θ j+lam)*norm w (j+1) (indicator F)) := by + have hjN : (j+1:ℝ) ≤ N := by exact_mod_cast (show j+1 ≤ N by omega) + have hn := norm_nonneg hw.nonneg (j+1) (indicator F) + nlinarith [mul_le_mul_of_nonneg_left hjN (mul_nonneg hc hn)] + have h := mul_le_mul_of_nonneg_left hsum (show (0:ℝ) ≤ 2^N by positivity) + simpa only [mul_assoc] using h + +end + +section +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +omit [Fintype V] [DecidableEq V] in +@[simp] lemma atom_indicator (w : Finset V → ℝ) (F : Finset V → Prop) (s : Finset V) : + atom w (indicator F) s = if F s then w s else 0 := by + by_cases h : F s <;> simp [atom,indicator,h] + +def fatAt (w : Finset V → ℝ) (N : ℕ) (θ : ℕ → ℝ) (f : Finset V → k) : + ℕ → Finset V → Prop + | 0, s => f s ≠ 0 ∧ 0 < w s + | k+1, s => 0 < w s ∧ θ s.card * (N-s.card:ℕ) * w s ≤ + starNorm w (s.card+1) s (indicator (fatAt w N θ f k)) + +def fatFamily (w : Finset V → ℝ) (N r : ℕ) (θ : ℕ → ℝ) (f : Finset V → k) + (s : Finset V) : Prop := s.card ≤ r ∧ fatAt w N θ f (r-s.card) s + +lemma fatFamily_cap (w : Finset V → ℝ) (N r : ℕ) (θ : ℕ → ℝ) (f : Finset V → k) : + ∀ s, fatFamily w N r θ f s → s.card ≤ r := fun _ h => h.1 + +lemma fatFamily_recurrence (w : Finset V → ℝ) (N r : ℕ) (θ : ℕ → ℝ) + (f : Finset V → k) (s : Finset V) (hs : s.card < r) : + fatFamily w N r θ f s ↔ 0 < w s ∧ + θ s.card * (N-s.card:ℕ) * w s ≤ + starNorm w (s.card+1) s (indicator (fatFamily w N r θ f)) := by + have he : r-s.card = (r-s.card-1)+1 := by omega + have hh : starNorm w (s.card+1) s (indicator (fatAt w N θ f (r-s.card-1))) = + starNorm w (s.card+1) s (indicator (fatFamily w N r θ f)) := by + unfold starNorm starSum + apply Finset.sum_congr rfl + intro t ht + have htc := mem_level.mp ht + have htr : t.card ≤ r := by omega + have hidx : r-t.card = r-s.card-1 := by omega + simp only [atom_indicator,fatFamily,htr,true_and,hidx] + unfold fatFamily + rw [he] + simp only [fatAt,show s.card ≤ r from hs.le,true_and] + rw [hh] + rfl + +lemma fatFamily_top_norm {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + (N r : ℕ) (θ : ℕ → ℝ) (f : Finset V → k) : + norm w r (indicator (fatFamily w N r θ f)) = norm w r f := by + apply Finset.sum_congr rfl + intro s hs + have hc := mem_level.mp hs + simp only [atom_indicator,fatFamily,hc,Nat.sub_self,le_refl,true_and,fatAt] + by_cases hf : f s = 0 + · simp [hf,atom] + · by_cases hp : 0 < w s + · simp [hf,hp,atom] + · have hz : w s = 0 := le_antisymm (le_of_not_gt hp) (hw s) + simp [hz,atom] + +theorem fat_markov {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + (hrN : r ≤ N) (θ : ℕ → ℝ) (hθ : ∀ j < r, 0 ≤ θ j) + (f : Finset V → k) (j : ℕ) (hj : j < r) : + θ j * norm w j (indicator (fatFamily w N r θ f)) ≤ + (N:ℝ) * norm w (j+1) (indicator (fatFamily w N r θ f)) := by + let F := fatFamily w N r θ f + have hlocal (s : Finset V) (hs : s ∈ level j) : + θ j * (N-j:ℕ) * atom w (indicator F) s ≤ + starNorm w (j+1) s (indicator F) := by + have he := mem_level.mp hs + by_cases hf : F s + · have h := (fatFamily_recurrence w N r θ f s (by omega)).mp hf + simpa only [atom_indicator,ite_eq_left hf,he] using h.2 + · simp only [atom_indicator,ite_eq_right hf,mul_zero] + exact starNorm_nonneg hw.nonneg _ _ _ + have hsum := Finset.sum_le_sum hlocal + simp only [← Finset.mul_sum] at hsum + change θ j * (N-j:ℕ) * norm w j (indicator F) ≤ + ∑ s ∈ level j, starSum (j+1) s (atom w (indicator F)) at hsum + rw [sum_children] at hsum + change θ j * (N-j:ℕ) * norm w j (indicator F) ≤ + (j+1:ℝ)*norm w (j+1) (indicator F) at hsum + have hn := norm_nonneg hw.nonneg j (indicator F) + have hn' := norm_nonneg hw.nonneg (j+1) (indicator F) + have hnj : (1:ℝ) ≤ (N-j:ℕ) := by exact_mod_cast (show 1 ≤ N-j by omega) + have hjN : (j+1:ℝ) ≤ N := by exact_mod_cast (show j+1 ≤ N by omega) + have hleft := mul_le_mul_of_nonneg_right hnj (mul_nonneg (hθ j hj) hn) + have hright := mul_le_mul_of_nonneg_right hjN hn' + change θ j * norm w j (indicator F) ≤ _ + nlinarith + +def fatBudget (N : ℕ) (η : ℝ) : ℕ → ℝ + | 0 => 1 + | k+1 => (N:ℝ) * (fatBudget N η k)^2 / η + +lemma fatBudget_pos {N : ℕ} (hN : 0 < N) {η : ℝ} (hη : 0 < η) (k : ℕ) : + 0 < fatBudget N η k := by + induction k with + | zero => norm_num [fatBudget] + | succ k ih => simp only [fatBudget]; positivity + +def fatThreshold (N r : ℕ) (η : ℝ) (j : ℕ) : ℝ := η / fatBudget N η (r-j-1) + +lemma fatThreshold_pos {N : ℕ} (hN : 0 < N) {η : ℝ} (hη : 0 < η) (r j : ℕ) : + 0 < fatThreshold N r η j := div_pos hη (fatBudget_pos hN hη _) + +theorem fat_mass_bound {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + (hN : 0 < N) (hrN : r ≤ N) {η : ℝ} (hη : 0 < η) (f : Finset V → k) + (a : ℕ) (ha : a ≤ r) : + norm w (r-a) (indicator (fatFamily w N r (fatThreshold N r η) f)) ≤ + fatBudget N η a * norm w r f := by + let θ := fatThreshold N r η + let F := fatFamily w N r θ f + induction a with + | zero => + simp only [Nat.sub_zero,fatBudget,one_mul] + exact le_of_eq (fatFamily_top_norm hw.nonneg N r θ f) + | succ a ih => + have har : a ≤ r := by omega + have hi := ih har + have hj : r-(a+1) < r := by omega + have ht : θ (r-(a+1)) = η / fatBudget N η a := by + unfold θ fatThreshold + congr 2 + omega + have hidx : r-(a+1)+1 = r-a := by omega + have hm := fat_markov hw hrN θ (fun j _ => (fatThreshold_pos hN hη r j).le) f _ hj + change θ (r-(a+1))*norm w (r-(a+1)) (indicator F) ≤ + (N:ℝ)*norm w (r-(a+1)+1) (indicator F) at hm + rw [ht,hidx] at hm + have hb := fatBudget_pos hN hη a + have hh := hm.trans (mul_le_mul_of_nonneg_left hi (Nat.cast_nonneg N)) + have hdiv : 0 < η / fatBudget N η a := div_pos hη hb + have hh' : norm w (r-(a+1)) (indicator F) ≤ + (N:ℝ)*(fatBudget N η a*norm w r f)/(η/fatBudget N η a) := + (le_div_iff₀ hdiv).mpr (by simpa only [mul_comm] using hh) + calc + _ ≤ (N:ℝ) * (fatBudget N η a * norm w r f) / (η / fatBudget N η a) := hh' + _ = fatBudget N η (a+1)*norm w r f := by + simp only [fatBudget] + field_simp + +lemma fat_empty_false {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + (hN : 0 < N) (hrN : r ≤ N) (hw0 : w ∅ = 1) {η : ℝ} (hη : 0 < η) + (f : Finset V → k) (hf : norm w r f < 1 / fatBudget N η r) : + ¬ fatFamily w N r (fatThreshold N r η) f ∅ := by + intro hF + have hm := fat_mass_bound hw hN hrN hη f r le_rfl + have he : norm w 0 (indicator (fatFamily w N r (fatThreshold N r η) f)) = 1 := by + simp [norm,level,atom_indicator,hF,hw0] + rw [Nat.sub_self,he] at hm + have hb := fatBudget_pos hN hη r + have hlt := (lt_div_iff₀ hb).mp hf + nlinarith + +end + +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +omit [Fintype V] [DecidableEq V] in +lemma atom_le_weight {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (f : Finset V → k) (s) : + atom w f s ≤ w s := by unfold atom; split_ifs; exact hw s; rfl + +lemma starNorm_le_starSum {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (r s) (f : Finset V → k) : + starNorm w r s f ≤ starSum r s w := starSum_mono (fun _ _ _ => atom_le_weight hw f _) + +def LocalMixing (w : Finset V → ℝ) (N : ℕ) (lam : ℝ) : Prop := + ∀ (F : Finset V → Prop) (s : Finset V), s.card < N → ∀ t : ℝ, 0 ≤ t → + starNorm w (s.card+1) s (indicator F) ≤ t*(N-s.card:ℕ)*w s → + collisionMass w F s ≤ (t+lam)*(N:ℝ)*starNorm w (s.card+1) s (indicator F) + +lemma fat_thin_children {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + (θ : ℕ → ℝ) (f : Finset V → k) (s : Finset V) (hs : s.card < r) + (hf : ¬ fatFamily w N r θ f s) : + starNorm w (s.card+1) s (indicator (fatFamily w N r θ f)) ≤ + θ s.card * (N-s.card:ℕ) * w s := by + by_cases hp : 0 < w s + · have hn : ¬ θ s.card * (N-s.card:ℕ) * w s ≤ + starNorm w (s.card+1) s (indicator (fatFamily w N r θ f)) := by + intro h + exact hf ((fatFamily_recurrence w N r θ f s hs).mpr ⟨hp,h⟩) + exact (lt_of_not_ge hn).le + · have hz : w s = 0 := le_antisymm (le_of_not_gt hp) (hw.nonneg s) + have hh := starNorm_le_starSum hw.nonneg (s.card+1) s + (indicator (fatFamily w N r θ f)) + rw [hw.balance s (s.card+1) (by omega),hz,mul_zero] at hh + simpa only [hz,mul_zero] using hh + +theorem fat_degeneracy_bound {w : Finset V → ℝ} {N r : ℕ} (hw : Balanced w N) + (hN : 0 < N) (hrN : r ≤ N) {η lam : ℝ} (hη : 0 < η) (hlam : 0 ≤ lam) + (hbudget : ∀ a ≤ r, lam * fatBudget N η a ≤ η) + (hmix : LocalMixing w N lam) (f : Finset V → k) (R : ℕ) : + norm w R (indicator (fun T => ¬NoBad (fatFamily w N r (fatThreshold N r η) f) T)) ≤ + (2:ℝ)^N * (N:ℝ)^2 * (r:ℝ) * (2*η) * norm w r f := by + let θ := fatThreshold N r η + let F := fatFamily w N r θ f + have hpair : ∀ s, s.card < r → ¬F s → collisionMass w F s ≤ + (θ s.card+lam)*(N:ℝ)*starNorm w (s.card+1) s (indicator F) := by + intro s hs hf + exact hmix F s (by omega) (θ s.card) (fatThreshold_pos hN hη r s.card).le + (fat_thin_children hw θ f s hs hf) + have hd := degeneracy_estimate hw hrN (fatFamily_cap w N r θ f) θ lam + (fun j _ => add_nonneg (fatThreshold_pos hN hη r j).le hlam) hpair R + have hs : (∑ j ∈ Finset.range r, (θ j+lam)*norm w (j+1) (indicator F)) ≤ + (r:ℝ)*(2*η)*norm w r f := by + calc + _ ≤ ∑ j ∈ Finset.range r, (2*η)*norm w r f := by + apply Finset.sum_le_sum + intro j hj + have hjr := Finset.mem_range.mp hj + have hidx : r-(r-j-1) = j+1 := by omega + have hb := fatBudget_pos hN hη (r-j-1) + have hm := fat_mass_bound hw hN hrN hη f (r-j-1) (by omega) + rw [hidx] at hm + have hθlam : 0 ≤ θ j+lam := add_nonneg (fatThreshold_pos hN hη r j).le hlam + calc + (θ j+lam)*norm w (j+1) (indicator F) ≤ + (θ j+lam)*(fatBudget N η (r-j-1)*norm w r f) := + mul_le_mul_of_nonneg_left hm hθlam + _ = (η+lam*fatBudget N η (r-j-1))*norm w r f := by + unfold θ fatThreshold + field_simp + _ ≤ (2*η)*norm w r f := by + apply mul_le_mul_of_nonneg_right _ (norm_nonneg hw.nonneg r f) + linarith [hbudget (r-j-1) (by omega)] + _ = _ := by simp only [Finset.sum_const,Finset.card_range,nsmul_eq_mul]; ring + have hmult := mul_le_mul_of_nonneg_left hs (show (0:ℝ) ≤ 2^N*(N:ℝ)^2 by positivity) + exact hd.trans (by simpa only [mul_assoc] using hmult) + +theorem exists_mixing_tolerance (N r : ℕ) (hN : 0 < N) {η : ℝ} (hη : 0 < η) : + ∃ lam : ℝ, 0 < lam ∧ ∀ a ≤ r, lam*fatBudget N η a ≤ η := by + let S := ∑ a ∈ Finset.range (r+1), fatBudget N η a + have hS : 0 ≤ S := Finset.sum_nonneg (fun a _ => (fatBudget_pos hN hη a).le) + have hden : 0 < 1+S := by linarith + refine ⟨η/(1+S),div_pos hη hden,?_⟩ + intro a ha + have hle : fatBudget N η a ≤ S := Finset.single_le_sum + (fun b _ => (fatBudget_pos hN hη b).le) (Finset.mem_range.mpr (by omega)) + have hh : fatBudget N η a ≤ 1+S := by linarith + calc + η/(1+S)*fatBudget N η a ≤ η/(1+S)*(1+S) := + mul_le_mul_of_nonneg_left hh (div_pos hη hden).le + _ = η := div_mul_cancel₀ η (ne_of_gt hden) + +end CoboundaryExpanders.FatLadders + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Joins.lean b/lean/OAI/Combinatorics/Coboundary/Joins.lean new file mode 100644 index 0000000000000000000000000000000000000000..880cee6c1edb253269653ae9ff1a38807dd39ee6 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Joins.lean @@ -0,0 +1,775 @@ +import OAI.Combinatorics.Coboundary.Cones + +namespace OAI + +noncomputable section + +/-! +Binary and finite joins, augmented exactness, and bounded cone constructions. +-/ + +section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix + +namespace CoboundaryExpanders.InfiniteChains.Join + +section +open Attachment Cone +variable {V W : Type} [DecidableEq V] [DecidableEq W] + +def complex (X : CoboundaryExpanders.InfiniteChains.Complex W) (Y : CoboundaryExpanders.InfiniteChains.Complex V) : CoboundaryExpanders.InfiniteChains.Complex (W ⊕ V) where + faces := {s | s.toLeft ∈ X.faces ∧ s.toRight ∈ Y.faces} + empty_mem := by simpa [Finset.toLeft, Finset.toRight] using And.intro X.empty_mem Y.empty_mem + downward := by + intro s t hs ht + exact ⟨X.downward hs.1 (by intro x hx; simpa using ht (by simpa using hx : Sum.inl x ∈ t)), + Y.downward hs.2 (by intro x hx; simpa using ht (by simpa using hx : Sum.inr x ∈ t))⟩ + +def prepend (B : Finset V) : Raw W →ₗ[k] Raw (W ⊕ V) := + Finsupp.lmapDomain k k (·.disjSum B) + +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma prepend_single (B : Finset V) (A : Finset W) (a : k) : + prepend B (Finsupp.single A a) = Finsupp.single (A.disjSum B) a := + Finsupp.mapDomain_single + +lemma prepend_boundary (B : Finset V) (c : Raw W) : + rawBoundary (prepend B c) = prepend B (rawBoundary c) + + ∑ v ∈ B, prepend (B.erase v) c := by + induction c using Finsupp.induction_linear with + | zero => simp + | add c d hc hd => simp only [map_add, hc, hd, Finset.sum_add_distrib]; abel + | single A a => + rw [prepend_single, boundary_disjSum_single, rawBoundary_single, map_sum] + simp only [prepend_single] + +def leftAction (T : Raw W →ₗ[k] Raw W) : Raw (W ⊕ V) →ₗ[k] Raw (W ⊕ V) := + Finsupp.linearCombination k (fun s => prepend s.toRight (T (Finsupp.single s.toLeft 1))) + +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma leftAction_single (T : Raw W →ₗ[k] Raw W) + (s : Finset (W ⊕ V)) (a : k) : + leftAction T (Finsupp.single s a) = prepend s.toRight (T (Finsupp.single s.toLeft a)) := by + simp [leftAction, ← map_smul] + +omit [DecidableEq V] [DecidableEq W] in +lemma leftAction_prepend (T : Raw W →ₗ[k] Raw W) (B : Finset V) (c : Raw W) : + leftAction T (prepend B c) = prepend B (T c) := by + induction c using Finsupp.induction_linear with + | zero => simp + | add c d hc hd => simp only [map_add, hc, hd] + | single A a => simp + +lemma leftAction_homotopy (T : Raw W →ₗ[k] Raw W) (A : Finset W) (B : Finset V) : + rawBoundary (leftAction T (Finsupp.single (A.disjSum B) 1)) + + leftAction T (rawBoundary (Finsupp.single (A.disjSum B) 1)) = + prepend B (rawBoundary (T (Finsupp.single A 1)) + T (rawBoundary (Finsupp.single A 1))) := by + rw [show Finsupp.single (A.disjSum B) (1 : k) = prepend B (Finsupp.single A 1) by simp] + rw [leftAction_prepend, prepend_boundary, prepend_boundary, map_add, map_sum] + simp only [leftAction_prepend] + rw [map_add] + have hz := twice (∑ v ∈ B, prepend (B.erase v) (T (Finsupp.single A 1))) + have he : ∀ a b c : Raw (W ⊕ V), (a+b)+(c+b) = (a+c)+(b+b) := by intros; abel + rw [he, hz, add_zero] + +lemma left_contraction {X : CoboundaryExpanders.InfiniteChains.Complex W} {n R : ℕ} (H : BoundedCone X n R) + (s : Finset (W ⊕ V)) (hs : s.toLeft ∈ X.faces) (hn : s.toLeft.card ≤ n) : + rawBoundary (leftAction H.hom (Finsupp.single s 1)) + + leftAction H.hom (rawBoundary (Finsupp.single s 1)) = Finsupp.single s 1 := by + rw [← Finset.toLeft_disjSum_toRight (u := s)] + rw [leftAction_homotopy] + rw [H.contraction s.toLeft hs hn, prepend_single] + +lemma leftAction_graded {X : CoboundaryExpanders.InfiniteChains.Complex W} (Y : CoboundaryExpanders.InfiniteChains.Complex V) {n R : ℕ} + (H : BoundedCone X n R) (r : ℕ) (c : Raw (W ⊕ V)) + (hc : c ∈ supported (graded {s | s ∈ (complex X Y).faces ∧ s.toLeft.card ≤ n} r)) : + leftAction H.hom c ∈ supported (graded (complex X Y).faces (r+1)) := by + apply map_supported _ _ _ _ c hc + intro s hs a + rw [leftAction_single] + have hH := H.map_graded s.toLeft.card hs.1.2 (Finsupp.single s.toLeft a) + (single_mem_supported (P := graded X.faces s.toLeft.card) ⟨hs.1.1.1, rfl⟩ a) + apply map_supported (prepend s.toRight) (graded X.faces (s.toLeft.card+1)) + (graded (complex X Y).faces (r+1)) _ _ hH + intro A hA b + rw [prepend_single] + apply single_mem_supported + refine ⟨⟨?_, ?_⟩, ?_⟩ + · simpa using hA.1 + · simpa using hs.1.1.2 + · rw [Finset.card_disjSum, hA.2] + have he := Finset.card_toLeft_add_card_toRight (u := s) + dsimp [graded] at hs + omega + +lemma fill_small_left {X : CoboundaryExpanders.InfiniteChains.Complex W} (Y : CoboundaryExpanders.InfiniteChains.Complex V) {n R : ℕ} + (H : BoundedCone X n R) (r : ℕ) (c : Raw (W ⊕ V)) + (hc : c ∈ supported (graded {s | s ∈ (complex X Y).faces ∧ s.toLeft.card ≤ n} r)) + (hz : rawBoundary c = 0) : + ∃ b ∈ supported (graded (complex X Y).faces (r+1)), rawBoundary b = c := by + refine ⟨leftAction H.hom c, leftAction_graded Y H r c hc, ?_⟩ + have he := linear_eq_on_supported + (rawBoundary.comp (leftAction H.hom) + (leftAction H.hom).comp rawBoundary) + LinearMap.id (graded {s | s ∈ (complex X Y).faces ∧ s.toLeft.card ≤ n} r) + (fun s hs => left_contraction H s hs.1.1.1 hs.1.2) c hc + change rawBoundary (leftAction H.hom c) + leftAction H.hom (rawBoundary c) = c at he + simpa only [hz, map_zero, add_zero] using he + +end + +open Attachment Cone +variable {V W : Type} [DecidableEq V] [DecidableEq W] + +def truncated (X : CoboundaryExpanders.InfiniteChains.Complex W) (Y : CoboundaryExpanders.InfiniteChains.Complex V) (M : ℕ) : Set (Finset (W ⊕ V)) := + {s | s ∈ (complex X Y).faces ∧ s.toLeft.card ≤ M} + +omit [DecidableEq V] [DecidableEq W] in +lemma truncated_downward (X : CoboundaryExpanders.InfiniteChains.Complex W) (Y : CoboundaryExpanders.InfiniteChains.Complex V) (M : ℕ) : + ∀ {s t}, s ∈ truncated X Y M → t ⊆ s → t ∈ truncated X Y M := by + intro s t hs ht + exact ⟨(complex X Y).downward hs.1 ht, + (Finset.card_le_card (Finset.toLeft_subset_toLeft ht)).trans hs.2⟩ + +lemma relative_enlarge_old (P O Q : Set (Finset V)) (r : ℕ) + (hQ : ∀ {s t}, s ∈ Q → t ⊆ s → t ∈ Q) + (hOP : O ⊆ P) (hPQ : P ∩ Q ⊆ O) (h : RelativeExactIn O Q r) : + RelativeExactIn P Q r := by + intro c hc hz + have hb := boundary_supported Q hQ c (graded_forget Q r hc) + have hδ : rawBoundary c ∈ supported O := by + rw [mem_supported] at hz hb ⊢ + exact fun s hs => hPQ ⟨hz s hs, hb s hs⟩ + obtain ⟨b, hbc, hres⟩ := h c hc hδ + exact ⟨b, hbc, supported_mono (P := graded O r) (Q := graded P r) (fun s hs => ⟨hOP hs.1, hs.2⟩) hres⟩ + +lemma relativeExactIn_self (P : Set (Finset V)) (r : ℕ) : RelativeExactIn P P r := by + intro c hc _ + refine ⟨0, Submodule.zero_mem _, ?_⟩ + simpa using hc + +lemma truncated_step (X : CoboundaryExpanders.InfiniteChains.Complex W) (Y : CoboundaryExpanders.InfiniteChains.Complex V) (M r m : ℕ) + (hr : r ≤ M+m+1) (hY : ∀ j ≤ m, ExactIn Y.faces j) : + RelativeExactIn (truncated X Y M) (truncated X Y (M+1)) r := by + classical + let I := {F : Finset W // F ∈ X.faces ∧ F.card = M+1} + let A : I → Set (Finset (W ⊕ V)) := fun F => joinFaces F.val Y + have hAP (F : I) : RelativeExactIn (truncated X Y M) (A F) r := by + apply relative_enlarge_old (truncated X Y M) (oldFaces F.val Y) (A F) r + (joinFaces_downward F.val Y) + · intro s hs + refine ⟨⟨X.downward F.property.1 hs.1.1, hs.1.2⟩, ?_⟩ + have hlt := Finset.card_lt_card (Finset.ssubset_iff_subset_ne.mpr ⟨hs.1.1, hs.2⟩) + rw [F.property.2] at hlt + omega + · intro s hs + refine ⟨hs.2, ?_⟩ + intro he + have hn := hs.1.2 + rw [he, F.property.2] at hn + omega + · apply relativeExactIn_join + intro hf + exact hY (r-F.val.card) (by rw [F.property.2]; omega) + have hAA (F G : I) (hFG : F ≠ G) : A F ∩ A G ⊆ truncated X Y M := by + intro s hs + refine ⟨⟨X.downward F.property.1 hs.1.1, hs.1.2⟩, ?_⟩ + have hle := Finset.card_le_card hs.1.1 + rw [F.property.2] at hle + by_contra hnot + have he : s.toLeft.card = M+1 := by omega + have hF : s.toLeft = F.val := Finset.eq_of_subset_of_card_le hs.1.1 (by omega) + have hG : s.toLeft = G.val := Finset.eq_of_subset_of_card_le hs.2.1 (by rw [G.property.2, he]) + exact hFG (Subtype.ext (hF.symm.trans hG)) + have hU := relativeExactIn_iUnion (truncated X Y M) A r + (fun F => joinFaces_downward F.val Y) hAA hAP + have he : truncated X Y (M+1) = truncated X Y M ∪ ⋃ F : I, A F := by + ext s + constructor + · intro hs + by_cases hn : s.toLeft.card ≤ M + · exact Or.inl ⟨hs.1, hn⟩ + · apply Or.inr + exact Set.mem_iUnion.mpr ⟨⟨s.toLeft, hs.1.1, by have := hs.2; omega⟩, + ⟨Finset.Subset.refl _, hs.1.2⟩⟩ + · intro hs + rcases hs with hs | hs + · exact ⟨hs.1, hs.2.trans (by omega)⟩ + · obtain ⟨F, hF⟩ := Set.mem_iUnion.mp hs + exact ⟨⟨X.downward F.property.1 hF.1, hF.2⟩, + (Finset.card_le_card hF.1).trans_eq F.property.2⟩ + rw [he] + apply relativeExactIn_union _ _ _ r (truncated_downward X Y M) _ + (fun _ hs => hs.1) (relativeExactIn_self _ r) hU + intro s t hs ht + obtain ⟨F, hF⟩ := Set.mem_iUnion.mp hs + exact Set.mem_iUnion.mpr ⟨F, joinFaces_downward F.val Y hF ht⟩ + +theorem exactIn_join {X : CoboundaryExpanders.InfiniteChains.Complex W} (Y : CoboundaryExpanders.InfiniteChains.Complex V) {n R : ℕ} + (H : BoundedCone X n R) (m : ℕ) (hY : ∀ j ≤ m, ExactIn Y.faces j) + (r : ℕ) (hr : r ≤ n+m+1) : ExactIn (complex X Y).faces r := by + have hf (M : ℕ) : ∀ c ∈ supported (graded (truncated X Y (n+M)) r), + rawBoundary c = 0 → ∃ b ∈ supported (graded (complex X Y).faces (r+1)), + rawBoundary b = c := by + induction M with + | zero => + intro c hc hz + exact fill_small_left Y H r c (by simpa only [Nat.add_zero, truncated] using hc) hz + | succ M ih => + intro c hc hz + obtain ⟨e, he, hres⟩ := truncated_step X Y (n+M) r m (by omega) hY c + (by simpa only [Nat.add_assoc, Nat.succ_eq_add_one] using hc) (by rw [hz]; exact Submodule.zero_mem _) + have hzres : rawBoundary (c-rawBoundary e) = 0 := by + rw [map_sub, hz] + have hh := LinearMap.congr_fun (rawBoundary_squared (V := W ⊕ V)) e + change rawBoundary (rawBoundary e) = 0 at hh + rw [hh, sub_self] + obtain ⟨b, hb, hbc⟩ := ih (c-rawBoundary e) hres hzres + refine ⟨e+b, Submodule.add_mem _ ?_ hb, ?_⟩ + · exact supported_mono (P := graded (truncated X Y (n+M+1)) (r+1)) + (Q := graded (complex X Y).faces (r+1)) (fun s hs => ⟨hs.1.1, hs.2⟩) he + · rw [map_add, hbc] + abel + intro c hc hz + apply hf r c _ hz + rw [mem_supported] at hc ⊢ + intro s hs + refine ⟨⟨(hc s hs).1, ?_⟩, (hc s hs).2⟩ + have he := Finset.card_toLeft_add_card_toRight (u := s) + have hcard := (hc s hs).2 + omega + +end CoboundaryExpanders.InfiniteChains.Join + +namespace CoboundaryExpanders.InfiniteChains.Cone.BoundedCone +open Attachment +variable {V : Type} [DecidableEq V] {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} + +def cut (H : BoundedCone X n R) : Raw V →ₗ[k] Raw V := + Finsupp.linearCombination k (fun s => if s.card ≤ n then H.hom (Finsupp.single s 1) else 0) + +@[simp] lemma cut_single (H : BoundedCone X n R) (s : Finset V) (a : k) : + H.cut (Finsupp.single s a) = if s.card ≤ n then H.hom (Finsupp.single s a) else 0 := by + by_cases h : s.card ≤ n <;> simp [cut, h, ← map_smul] + +lemma cut_boundary (H : BoundedCone X n R) (s : Finset V) (hs : s.card ≤ n+1) : + H.cut (rawBoundary (Finsupp.single s 1)) = H.hom (rawBoundary (Finsupp.single s 1)) := by + simp only [rawBoundary_single, map_sum] + apply Finset.sum_congr rfl + intro v hv + rw [cut_single, ite_eq_left] + rw [Finset.card_erase_of_mem hv] + omega + +def normalize (H : BoundedCone X n R) : BoundedCone X n R where + hom := H.cut + support := by + intro s hs hn + rw [cut_single, ite_eq_left hn] + exact H.support s hs hn + contraction := by + intro s hs hn + rw [cut_single, ite_eq_left hn, cut_boundary H s (by omega)] + exact H.contraction s hs hn + bound := by + intro s hs hn + rw [cut_single, ite_eq_left hn] + exact H.bound s hs hn + +end CoboundaryExpanders.InfiniteChains.Cone.BoundedCone + +namespace CoboundaryExpanders.InfiniteChains.Join + +section +open Attachment Cone +variable {V W : Type} [DecidableEq V] [DecidableEq W] + +def crossLinear : Raw W →ₗ[k] (Raw V →ₗ[k] Raw (W ⊕ V)) := + Finsupp.linearCombination k (fun A => append A) + +def cross (c : Raw W) (d : Raw V) : Raw (W ⊕ V) := crossLinear c d + +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma cross_single_left (A : Finset W) (a : k) (d : Raw V) : + cross (Finsupp.single A a) d = a • append A d := by simp [cross, crossLinear] + +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma cross_single_right (c : Raw W) (B : Finset V) (b : k) : + cross c (Finsupp.single B b) = b • prepend B c := by + induction c using Finsupp.induction_linear with + | zero => simp [cross] + | add c d hc hd => simp only [cross, map_add, LinearMap.add_apply] at *; rw [hc, hd, smul_add] + | single A a => simp [cross_single_left, mul_comm] + +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma cross_zero_left (d : Raw V) : cross (0 : Raw W) d = 0 := by simp [cross] +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma cross_zero_right (c : Raw W) : cross c (0 : Raw V) = 0 := by simp [cross] +omit [DecidableEq V] [DecidableEq W] in +lemma cross_add_left (c e : Raw W) (d : Raw V) : cross (c+e) d = cross c d + cross e d := by + simp [cross] +omit [DecidableEq V] [DecidableEq W] in +lemma cross_add_right (c : Raw W) (d e : Raw V) : cross c (d+e) = cross c d + cross c e := by + simp [cross] +omit [DecidableEq V] [DecidableEq W] in +lemma cross_sum_left {ι : Type*} (I : Finset ι) (c : ι → Raw W) (d : Raw V) : + cross (∑ i ∈ I, c i) d = ∑ i ∈ I, cross (c i) d := by simp [cross] +omit [DecidableEq V] [DecidableEq W] in +lemma cross_sum_right {ι : Type*} (I : Finset ι) (c : Raw W) (d : ι → Raw V) : + cross c (∑ i ∈ I, d i) = ∑ i ∈ I, cross c (d i) := by simp [cross] + +lemma cross_boundary (c : Raw W) (d : Raw V) : + rawBoundary (cross c d) = cross (rawBoundary c) d + cross c (rawBoundary d) := by + induction c using Finsupp.induction_linear with + | zero => simp + | add c e hc he => + simp only [cross_add_left, map_add, hc, he] + abel + | single A a => + induction d using Finsupp.induction_linear with + | zero => simp + | add d e hd he => + simp only [cross_add_right, map_add, hd, he] + abel + | single B b => + simp only [map_smul, rawBoundary_single, cross_single_right, cross_sum_right] + simp [prepend_single, map_sum, Finset.smul_sum, mul_comm, + erase_disjSum_inl, erase_disjSum_inr] + +lemma cross_graded (X : CoboundaryExpanders.InfiniteChains.Complex W) (Y : CoboundaryExpanders.InfiniteChains.Complex V) (a b : ℕ) (c : Raw W) (d : Raw V) + (hc : c ∈ supported (graded X.faces a)) (hd : d ∈ supported (graded Y.faces b)) : + cross c d ∈ supported (graded (complex X Y).faces (a+b)) := by + let T : Raw W →ₗ[k] Raw (W ⊕ V) := (LinearMap.applyₗ (R := k) d).comp crossLinear + change T c ∈ _ + apply map_supported T _ _ _ c hc + intro A hA z + change cross (Finsupp.single A z) d ∈ _ + rw [cross_single_left] + apply Submodule.smul_mem + apply map_supported (append A) (graded Y.faces b) _ _ d hd + intro B hB t + rw [append_single] + exact single_mem_supported (P := graded (complex X Y).faces (a+b)) ⟨⟨by simpa using hA.1, by simpa using hB.1⟩, + by rw [Finset.card_disjSum, hA.2, hB.2]⟩ t + +lemma cross_size (c : Raw W) (d : Raw V) : size (cross c d) ≤ size c * size d := by + let T : Raw W →ₗ[k] Raw (W ⊕ V) := (LinearMap.applyₗ (R := k) d).comp crossLinear + have hT (A : Finset W) (_ : A ∈ Set.univ) : size (T (Finsupp.single A 1)) ≤ size d := by + change size (cross (Finsupp.single A 1) d) ≤ _ + rw [cross_single_left, one_smul] + exact (size_map_le (append A) Set.univ 1 (fun B _ => by simpa using size_single_le (A.disjSum B) (1 : k)) + d (by rw [mem_supported]; simp)).trans_eq (by omega) + exact (size_map_le T Set.univ (size d) hT c (by rw [mem_supported]; simp)).trans_eq (Nat.mul_comm _ _) + +def operator (T : Raw W →ₗ[k] Raw W) (U : Raw V →ₗ[k] Raw V) : + Raw (W ⊕ V) →ₗ[k] Raw (W ⊕ V) := + Finsupp.linearCombination k (fun s => + cross (T (Finsupp.single s.toLeft 1)) (U (Finsupp.single s.toRight 1))) + +omit [DecidableEq V] [DecidableEq W] in +@[simp] lemma operator_single (T : Raw W →ₗ[k] Raw W) (U : Raw V →ₗ[k] Raw V) + (A : Finset W) (B : Finset V) : + operator T U (Finsupp.single (A.disjSum B) 1) = + cross (T (Finsupp.single A 1)) (U (Finsupp.single B 1)) := by simp [operator] + +lemma operator_boundary (T : Raw W →ₗ[k] Raw W) (U : Raw V →ₗ[k] Raw V) + (A : Finset W) (B : Finset V) : + operator T U (rawBoundary (Finsupp.single (A.disjSum B) 1)) = + cross (T (rawBoundary (Finsupp.single A 1))) (U (Finsupp.single B 1)) + + cross (T (Finsupp.single A 1)) (U (rawBoundary (Finsupp.single B 1))) := by + rw [boundary_disjSum_single, map_add, map_sum, map_sum] + simp only [operator_single, rawBoundary_single, map_sum, cross_sum_left, cross_sum_right] + +def residual (T : Raw V →ₗ[k] Raw V) : Raw V →ₗ[k] Raw V := + LinearMap.id + rawBoundary.comp T + T.comp rawBoundary + +lemma residual_eq (T : Raw V →ₗ[k] Raw V) (c : Raw V) : + residual T c = c + rawBoundary (T c) + T (rawBoundary c) := rfl + +lemma residual_boundary (T : Raw V →ₗ[k] Raw V) (c : Raw V) : + rawBoundary (residual T c) = residual T (rawBoundary c) := by + have hh (x : Raw V) : rawBoundary (rawBoundary x) = 0 := + LinearMap.congr_fun (rawBoundary_squared (V := V)) x + simp [residual_eq, map_add, hh] + +def joinHom (T : Raw W →ₗ[k] Raw W) (U : Raw V →ₗ[k] Raw V) : + Raw (W ⊕ V) →ₗ[k] Raw (W ⊕ V) := + operator T LinearMap.id + operator (residual T) U + +lemma joinHom_contraction (T : Raw W →ₗ[k] Raw W) (U : Raw V →ₗ[k] Raw V) + (A : Finset W) (B : Finset V) : + rawBoundary (joinHom T U (Finsupp.single (A.disjSum B) 1)) + + joinHom T U (rawBoundary (Finsupp.single (A.disjSum B) 1)) = + Finsupp.single (A.disjSum B) 1 + + cross (residual T (Finsupp.single A 1)) (residual U (Finsupp.single B 1)) := by + simp only [joinHom, LinearMap.add_apply, operator_single, map_add, cross_boundary, + LinearMap.id_apply, operator_boundary, residual_boundary] + rw [residual_eq U, cross_add_right, cross_add_right] + have he := residual_eq T (Finsupp.single A 1) + have he' := congrArg (fun x => cross x (Finsupp.single B 1)) he + rw [cross_add_left, cross_add_left] at he' + have h0 : cross (Finsupp.single A 1) (Finsupp.single B 1) = Finsupp.single (A.disjSum B) 1 := by simp + rw [h0] at he' + have h2 (x : Raw (W ⊕ V)) : x+x = 0 := twice x + rw [he'] + abel_nf + simp only [two_smul ℤ, twice, zero_add, add_zero] + +end + +open Attachment Cone +variable {V W : Type} [DecidableEq V] [DecidableEq W] + +lemma cut_boundary_high {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} (H : BoundedCone X n R) + (s : Finset V) (hs : n+1 < s.card) : H.cut (rawBoundary (Finsupp.single s 1)) = 0 := by + rw [rawBoundary_single, map_sum] + apply Finset.sum_eq_zero + intro v hv + rw [BoundedCone.cut_single, ite_eq_right] + rw [Finset.card_erase_of_mem hv] + omega + +lemma residual_cut_low {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} (H : BoundedCone X n R) + (s : Finset V) (hs : s ∈ X.faces) (hn : s.card ≤ n) : + residual H.cut (Finsupp.single s 1) = 0 := by + rw [residual_eq, add_assoc] + have he := H.normalize.contraction s hs hn + change rawBoundary (H.cut (Finsupp.single s 1)) + H.cut (rawBoundary (Finsupp.single s 1)) = _ at he + rw [he, twice] + +lemma residual_cut_graded {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} (H : BoundedCone X n R) + (s : Finset V) (hs : s ∈ X.faces) : + residual H.cut (Finsupp.single s 1) ∈ supported (graded X.faces s.card) := by + by_cases hn : s.card ≤ n + · rw [residual_cut_low H s hs hn] + exact Submodule.zero_mem _ + rw [residual_eq, BoundedCone.cut_single, ite_eq_right hn, map_zero, add_zero] + apply Submodule.add_mem _ (single_mem_supported (P := graded X.faces s.card) ⟨hs, rfl⟩ _) + by_cases he : s.card = n+1 + · rw [H.cut_boundary s (by omega)] + rw [he] + apply H.map_graded n le_rfl + apply boundary_graded X.faces (fun {_ _} ht h => X.downward ht h) n + exact single_mem_supported (P := graded X.faces (n+1)) ⟨hs, he⟩ _ + · rw [cut_boundary_high H s (by omega)] + exact Submodule.zero_mem _ + +lemma residual_cut_size {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} (H : BoundedCone X n R) + (s : Finset V) (hs : s ∈ X.faces) : + size (residual H.cut (Finsupp.single s 1)) ≤ 1+R*(n+1) := by + by_cases hn : s.card ≤ n + · rw [residual_cut_low H s hs hn, size_zero] + omega + rw [residual_eq, BoundedCone.cut_single, ite_eq_right hn, map_zero, add_zero] + by_cases he : s.card = n+1 + · have hb : rawBoundary (Finsupp.single s 1) ∈ supported (graded X.faces n) := by + apply boundary_graded X.faces (fun {_ _} ht h => X.downward ht h) n + exact single_mem_supported (P := graded X.faces (n+1)) ⟨hs, he⟩ _ + rw [H.cut_boundary s (by omega)] + exact (size_add_le _ _).trans (Nat.add_le_add (size_single_le s (1 : k)) + ((H.size_apply n le_rfl _ hb).trans (Nat.mul_le_mul_left R (by simpa [he] using boundary_single_size s (1 : k))))) + · rw [cut_boundary_high H s (by omega), add_zero] + exact (size_single_le s (1 : k)).trans (by omega) + +def boundedCone {X : CoboundaryExpanders.InfiniteChains.Complex W} {Y : CoboundaryExpanders.InfiniteChains.Complex V} {n m R S : ℕ} + (H : BoundedCone X n R) (K : BoundedCone Y m S) : + BoundedCone (complex X Y) (n+m+1) (max R ((1+R*(n+1))*S)) where + hom := joinHom H.cut K.cut + support := by + intro s hs hn + rw [← Finset.toLeft_disjSum_toRight (u := s)] + simp only [joinHom, LinearMap.add_apply, operator_single, LinearMap.id_apply] + by_cases hA : s.toLeft.card ≤ n + · rw [residual_cut_low H s.toLeft hs.1 hA, cross_zero_left, add_zero] + have hg := cross_graded X Y (s.toLeft.card+1) s.toRight.card + (H.cut (Finsupp.single s.toLeft 1)) (Finsupp.single s.toRight 1) + (H.normalize.support s.toLeft hs.1 hA) (single_mem_supported (P := graded Y.faces s.toRight.card) ⟨hs.2, rfl⟩ _) + convert hg using 1 + simp [Finset.card_disjSum, Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] + · have hB : s.toRight.card ≤ m := by + have hcard := Finset.card_toLeft_add_card_toRight (u := s) + omega + rw [BoundedCone.cut_single, ite_eq_right hA, cross_zero_left, zero_add] + have hg := cross_graded X Y s.toLeft.card (s.toRight.card+1) + (residual H.cut (Finsupp.single s.toLeft 1)) (K.cut (Finsupp.single s.toRight 1)) + (residual_cut_graded H s.toLeft hs.1) (K.normalize.support s.toRight hs.2 hB) + convert hg using 1 + simp [Finset.card_disjSum, Nat.add_assoc] + contraction := by + intro s hs hn + rw [← Finset.toLeft_disjSum_toRight (u := s), joinHom_contraction] + by_cases hA : s.toLeft.card ≤ n + · rw [residual_cut_low H s.toLeft hs.1 hA, cross_zero_left, add_zero] + · have hB : s.toRight.card ≤ m := by + have hcard := Finset.card_toLeft_add_card_toRight (u := s) + omega + rw [residual_cut_low K s.toRight hs.2 hB, cross_zero_right, add_zero] + bound := by + intro s hs hn + rw [← Finset.toLeft_disjSum_toRight (u := s)] + simp only [joinHom, LinearMap.add_apply, operator_single, LinearMap.id_apply] + by_cases hA : s.toLeft.card ≤ n + · rw [residual_cut_low H s.toLeft hs.1 hA, cross_zero_left, add_zero] + exact ((cross_size _ _).trans (Nat.mul_le_mul + (H.normalize.bound s.toLeft hs.1 hA) (size_single_le s.toRight (1 : k)))).trans + (by simp) + · have hB : s.toRight.card ≤ m := by + have hcard := Finset.card_toLeft_add_card_toRight (u := s) + omega + rw [BoundedCone.cut_single, ite_eq_right hA, cross_zero_left, zero_add] + exact ((cross_size _ _).trans (Nat.mul_le_mul (residual_cut_size H s.toLeft hs.1) + (K.normalize.bound s.toRight hs.2 hB))).trans (Nat.le_max_right _ _) + +end CoboundaryExpanders.InfiniteChains.Join + +end + +open scoped Polynomial BigOperators + +namespace CoboundaryExpanders.InfiniteChains.Join + +section +open Attachment Cone +open scoped BigOperators +variable {V : Type} [DecidableEq V] +def fiber {L : ℕ} (s : Finset (Fin L × V)) (i : Fin L) : Finset V := + (s.filter fun x => x.1 = i).image Prod.snd +@[simp] lemma mem_fiber {L : ℕ} (s : Finset (Fin L × V)) (i : Fin L) (v : V) : + v ∈ fiber s i ↔ (i,v) ∈ s := by + simp only [fiber,Finset.mem_image,Finset.mem_filter] + constructor + · rintro ⟨⟨j,w⟩,⟨hm,hj⟩,hw⟩ + dsimp only at hj hw + simpa only [hj,hw] using hm + · intro h + exact ⟨(i,v),⟨h,rfl⟩,rfl⟩ +def finiteComplex {L : ℕ} (X : Fin L → CoboundaryExpanders.InfiniteChains.Complex V) : InfiniteChains.Complex (Fin L × V) where + faces := {s | ∀ i, fiber s i ∈ (X i).faces} + empty_mem := by intro i; simpa only [fiber,Finset.filter_empty,Finset.image_empty] using (X i).empty_mem + downward := by + intro s t hs hts i + apply (X i).downward (hs i) + intro v hv + rw [mem_fiber] at hv ⊢ + exact hts hv + +def splitEquiv (L : ℕ) : (Fin (L+1) × V) ≃ (V ⊕ (Fin L × V)) where + toFun x := Fin.cases (Sum.inl x.2) (fun i => Sum.inr (i,x.2)) x.1 + invFun := Sum.elim (fun v => (0,v)) (fun x => (x.1.succ,x.2)) + left_inv := by rintro ⟨i,v⟩; induction i using Fin.cases <;> rfl + right_inv := by intro x; cases x <;> rfl +omit [DecidableEq V] in +@[simp] lemma splitEquiv_zero (L : ℕ) (v : V) : splitEquiv L (0,v) = Sum.inl v := rfl +omit [DecidableEq V] in +@[simp] lemma splitEquiv_succ (L : ℕ) (i : Fin L) (v : V) : + splitEquiv L (i.succ,v) = Sum.inr (i,v) := rfl +lemma split_left {L : ℕ} (s : Finset (Fin (L+1) × V)) : + (s.image (splitEquiv L)).toLeft = fiber s 0 := by + ext v + rw [Finset.mem_toLeft,mem_fiber] + constructor + · rintro hh + obtain ⟨x,hx,he⟩ := Finset.mem_image.mp hh + have he' : x = (0,v) := (splitEquiv L).injective (he.trans (splitEquiv_zero L v).symm) + exact he' ▸ hx + · intro hh + exact Finset.mem_image.mpr ⟨(0,v),hh,rfl⟩ +lemma split_right_fiber {L : ℕ} (s : Finset (Fin (L+1) × V)) (i : Fin L) : + fiber (s.image (splitEquiv L)).toRight i = fiber s i.succ := by + ext v + rw [mem_fiber,Finset.mem_toRight,mem_fiber] + constructor + · rintro hh + obtain ⟨x,hx,he⟩ := Finset.mem_image.mp hh + have he' : x = (i.succ,v) := (splitEquiv L).injective (he.trans (splitEquiv_succ L i v).symm) + exact he' ▸ hx + · intro hh + exact Finset.mem_image.mpr ⟨(i.succ,v),hh,rfl⟩ +lemma finiteComplex_split {L : ℕ} (X : Fin (L+1) → CoboundaryExpanders.InfiniteChains.Complex V) (s : Finset (Fin (L+1) × V)) : + s ∈ (finiteComplex X).faces ↔ + s.image (splitEquiv L) ∈ (complex (X 0) (finiteComplex (fun i => X i.succ))).faces := by + change (∀ i, fiber s i ∈ (X i).faces) ↔ + (s.image (splitEquiv L)).toLeft ∈ (X 0).faces ∧ + ∀ i, fiber (s.image (splitEquiv L)).toRight i ∈ (X i.succ).faces + simp only [split_left,split_right_fiber] + constructor + · exact fun h => ⟨h 0,fun i => h i.succ⟩ + · rintro ⟨h0,h⟩ i + induction i using Fin.cases + · exact h0 + · exact h _ +lemma finiteComplex_one (X : Fin 1 → CoboundaryExpanders.InfiniteChains.Complex V) (s : Finset (Fin 1 × V)) : + s ∈ (finiteComplex X).faces ↔ s.image Prod.snd ∈ (X 0).faces := by + have h : fiber s 0 = s.image Prod.snd := by + unfold fiber + congr 1 + apply Finset.filter_true_of_mem + intro x hx + exact Subsingleton.elim _ _ + change (∀ i, fiber s i ∈ (X i).faces) ↔ _ + simp only [Fin.forall_fin_one,h] +def oneEquiv : (Fin 1 × V) ≃ V where + toFun := Prod.snd + invFun v := (0,v) + left_inv := by rintro ⟨i,v⟩; have hi : i = 0 := Subsingleton.elim _ _; simp only [hi] + right_inv _ := rfl + +theorem exactIn_finiteComplex (L : ℕ) (X : Fin (L+1) → CoboundaryExpanders.InfiniteChains.Complex V) + (a : Fin (L+1) → ℕ) (ha : ∀ i, 0 < a i) + (hcones : ∀ i, ∃ R : ℕ, Nonempty (BoundedCone (X i) (a i-1) R)) + (r : ℕ) (hr : r < ∑ i, a i) : ExactIn (finiteComplex X).faces r := by + induction L generalizing r with + | zero => + obtain ⟨R,⟨H⟩⟩ := hcones 0 + apply exactIn_equivalence oneEquiv _ (X 0).faces (finiteComplex_one X) r + apply H.exactIn r + have he : (∑ i, a i) = a 0 := Fin.sum_univ_one a + rw [he] at hr + omega + | succ L ih => + obtain ⟨R,⟨H⟩⟩ := hcones 0 + let b : ℕ := ∑ i : Fin (L+1), a i.succ + have hb : 0 < b := by + exact Finset.sum_pos (fun i _ => ha i.succ) Finset.univ_nonempty + have hY : ∀ j ≤ b-1, ExactIn (finiteComplex (fun i : Fin (L+1) => X i.succ)).faces j := by + intro j hj + exact ih (fun i => X i.succ) (fun i => a i.succ) (fun i => ha i.succ) + (fun i => hcones i.succ) j (by change j < b; omega) + apply exactIn_equivalence (splitEquiv (L+1)) _ _ (finiteComplex_split X) r + apply exactIn_join (finiteComplex (fun i => X i.succ)) H (b-1) hY r + rw [Fin.sum_univ_succ] at hr + have h0 := ha 0 + change r < a 0 + b at hr + omega +end + +section +open Attachment Cone +variable {V W : Type} [DecidableEq V] [DecidableEq W] +lemma exactIn_empty_left [Nonempty W] (X : CoboundaryExpanders.InfiniteChains.Complex V) (Y : CoboundaryExpanders.InfiniteChains.Complex W) + (hX : ∀ s ∈ X.faces, s = ∅) (r : ℕ) (hY : ExactIn Y.faces r) : + ExactIn (complex X Y).faces r := by + classical + let f : V ⊕ W → W := Sum.elim (fun _ => Classical.choice (inferInstance : Nonempty W)) id + have hret (s : Finset (V ⊕ W)) (hs : s ∈ (complex X Y).faces) : + ∀ v ∈ s, Sum.inr (f v) = v := by + intro v hv + cases v with + | inl v => + have hh : v ∈ s.toLeft := by simpa using hv + rw [hX s.toLeft hs.1] at hh + exact False.elim (Finset.notMem_empty _ hh) + | inr w => rfl + have him (s : Finset (V ⊕ W)) (hs : s ∈ (complex X Y).faces) : s.image f = s.toRight := by + ext w + constructor + · rintro hh + obtain ⟨v,hv,rfl⟩ := Finset.mem_image.mp hh + rw [Finset.mem_toRight,hret s hs v hv] + exact hv + · intro hh + exact Finset.mem_image.mpr ⟨Sum.inr w,by simpa using hh,rfl⟩ + apply exactIn_retract f Sum.inr (complex X Y).faces Y.faces + (fun s hs => (him s hs).symm ▸ hs.2) _ _ _ hret r hY + · intro s hs + change _ ∈ X.faces ∧ _ ∈ Y.faces + have hl : (s.image (Sum.inr : W → V ⊕ W)).toLeft = ∅ := by ext v; simp [Finset.mem_toLeft] + have hr : (s.image (Sum.inr : W → V ⊕ W)).toRight = s := by ext w; simp [Finset.mem_toRight] + rw [hl,hr] + exact ⟨X.empty_mem,hs⟩ + · intro s hs x hx y hy hh + have he := congrArg (Sum.inr : W → V ⊕ W) hh + rwa [hret s hs x hx,hret s hs y hy] at he + · intro s hs + exact Sum.inr_injective.injOn +lemma exactIn_empty_right [Nonempty V] (X : CoboundaryExpanders.InfiniteChains.Complex V) (Y : CoboundaryExpanders.InfiniteChains.Complex W) + (hY : ∀ s ∈ Y.faces, s = ∅) (r : ℕ) (hX : ExactIn X.faces r) : + ExactIn (complex X Y).faces r := by + classical + let f : V ⊕ W → V := Sum.elim id (fun _ => Classical.choice (inferInstance : Nonempty V)) + have hret (s : Finset (V ⊕ W)) (hs : s ∈ (complex X Y).faces) : + ∀ v ∈ s, Sum.inl (f v) = v := by + intro v hv + cases v with + | inr v => + have hh : v ∈ s.toRight := by simpa using hv + rw [hY s.toRight hs.2] at hh + exact False.elim (Finset.notMem_empty _ hh) + | inl w => rfl + have him (s : Finset (V ⊕ W)) (hs : s ∈ (complex X Y).faces) : s.image f = s.toLeft := by + ext w + constructor + · rintro hh + obtain ⟨v,hv,rfl⟩ := Finset.mem_image.mp hh + rw [Finset.mem_toLeft,hret s hs v hv] + exact hv + · intro hh + exact Finset.mem_image.mpr ⟨Sum.inl w,by simpa using hh,rfl⟩ + apply exactIn_retract f Sum.inl (complex X Y).faces X.faces + (fun s hs => (him s hs).symm ▸ hs.1) _ _ _ hret r hX + · intro s hs + change _ ∈ X.faces ∧ _ ∈ Y.faces + have hl : (s.image (Sum.inl : V → V ⊕ W)).toLeft = s := by ext v; simp [Finset.mem_toLeft] + have hr : (s.image (Sum.inl : V → V ⊕ W)).toRight = ∅ := by ext w; simp [Finset.mem_toRight] + rw [hl,hr] + exact ⟨hs,Y.empty_mem⟩ + · intro s hs x hx y hy hh + have he := congrArg (Sum.inl : V → V ⊕ W) hh + rwa [hret s hs x hx,hret s hs y hy] at he + · intro s hs + exact Sum.inl_injective.injOn +end + +open Attachment Cone +open scoped BigOperators +variable {V : Type} [DecidableEq V] +lemma finiteComplex_only_empty {L : ℕ} (X : Fin L → CoboundaryExpanders.InfiniteChains.Complex V) + (hX : ∀ i s, s ∈ (X i).faces → s = ∅) + (s : Finset (Fin L × V)) (hs : s ∈ (finiteComplex X).faces) : s = ∅ := by + apply Finset.eq_empty_iff_forall_notMem.mpr + rintro ⟨i,v⟩ hv + have hh : v ∈ fiber s i := (mem_fiber s i v).mpr hv + rw [hX i (fiber s i) (hs i)] at hh + exact Finset.notMem_empty _ hh + +theorem exactIn_finiteComplex_all [Nonempty V] (L : ℕ) (X : Fin (L+1) → CoboundaryExpanders.InfiniteChains.Complex V) + (a : Fin (L+1) → ℕ) + (hcones : ∀ i, 0 < a i → ∃ R : ℕ, Nonempty (BoundedCone (X i) (a i-1) R)) + (hzero : ∀ i, a i = 0 → ∀ s ∈ (X i).faces, s = ∅) + (r : ℕ) (hr : r < ∑ i, a i) : ExactIn (finiteComplex X).faces r := by + induction L generalizing r with + | zero => + have he : (∑ i, a i) = a 0 := Fin.sum_univ_one a + rw [he] at hr + obtain ⟨R,⟨H⟩⟩ := hcones 0 (by omega) + apply exactIn_equivalence oneEquiv _ (X 0).faces (finiteComplex_one X) r + exact H.exactIn r (by omega) + | succ L ih => + let b : ℕ := ∑ i : Fin (L+1), a i.succ + rw [Fin.sum_univ_succ] at hr + change r < a 0 + b at hr + apply exactIn_equivalence (splitEquiv (L+1)) _ _ (finiteComplex_split X) r + by_cases h0 : a 0 = 0 + · apply exactIn_empty_left (X 0) (finiteComplex (fun i => X i.succ)) (hzero 0 h0) r + exact ih (fun i => X i.succ) (fun i => a i.succ) (fun i => hcones i.succ) + (fun i => hzero i.succ) r (by change r < b; omega) + · obtain ⟨R,⟨H⟩⟩ := hcones 0 (by omega) + by_cases hb : b = 0 + · have hz (i : Fin (L+1)) : a i.succ = 0 := by + have he := Finset.sum_eq_zero_iff.mp hb + exact he i (Finset.mem_univ _) + apply exactIn_empty_right (X 0) (finiteComplex (fun i => X i.succ)) + (finiteComplex_only_empty _ (fun i => hzero i.succ (hz i))) r + exact H.exactIn r (by omega) + · have hY : ∀ j ≤ b-1, ExactIn (finiteComplex (fun i : Fin (L+1) => X i.succ)).faces j := by + intro j hj + exact ih (fun i => X i.succ) (fun i => a i.succ) (fun i => hcones i.succ) + (fun i => hzero i.succ) j (by change j < b; omega) + apply exactIn_join _ H (b-1) hY r + omega +end CoboundaryExpanders.InfiniteChains.Join + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/LinkSpectrum.lean b/lean/OAI/Combinatorics/Coboundary/LinkSpectrum.lean new file mode 100644 index 0000000000000000000000000000000000000000..04cf0ebfad1ac889080ed2ec2663ba814adbdd42 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/LinkSpectrum.lean @@ -0,0 +1,1204 @@ +import OAI.Combinatorics.Coboundary.Links + +namespace OAI + +/-! +Rank-two incidence geometry, weighted Rayleigh inequalities, and spectral bounds for links. +-/ + +noncomputable section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix + +namespace CoboundaryExpanders.RankTwoGeometry + +section +open MatrixOpposition TypedCosetFaces Elementary +open scoped Matrix +variable {K : Type} [Field K] + +def matrix3 (a b c : K) : Matrix (Fin 3) (Fin 3) K := !![1,a,c; 0,1,b; 0,0,1] +lemma matrix3_det (a b c : K) : (matrix3 a b c).det = 1 := by + simp [matrix3,Matrix.det_fin_three] +def upper3 (a b c : K) : upperGroup K 3 := + ⟨⟨matrix3 a b c,matrix3_det a b c⟩,by + apply (mem_upperGroup _).mpr + intro i j hji + fin_cases i <;> fin_cases j <;> norm_num [matrix3,Matrix.one_apply,Fin.le_iff_val_le_val] at *⟩ + +def ca (g : upperGroup K 3) : K := g.val 0 1 +def cb (g : upperGroup K 3) : K := g.val 1 2 +def cc (g : upperGroup K 3) : K := g.val 0 2 + +@[simp] lemma ca_upper3 (a b c : K) : ca (upper3 a b c) = a := rfl +@[simp] lemma cb_upper3 (a b c : K) : cb (upper3 a b c) = b := rfl +@[simp] lemma cc_upper3 (a b c : K) : cc (upper3 a b c) = c := rfl + +lemma upper3_coords (g : upperGroup K 3) : upper3 (ca g) (cb g) (cc g) = g := by + apply Subtype.ext + apply Matrix.SpecialLinearGroup.ext + intro i j + have hg := (mem_upperGroup g.val).mp g.property + change matrix3 (ca g) (cb g) (cc g) i j = g.val i j + fin_cases i <;> fin_cases j <;> + first | rfl | rw [hg _ _ (by decide)]; rfl + +@[ext] lemma upper_ext {g h : upperGroup K 3} + (ha : ca g = ca h) (hb : cb g = cb h) (hc : cc g = cc h) : g = h := by + rw [←upper3_coords g,←upper3_coords h,ha,hb,hc] + +lemma upper3_mul (a b c a' b' c' : K) : + upper3 a b c * upper3 a' b' c' = upper3 (a+a') (b+b') (c+c'+a*b') := by + apply Subtype.ext + apply Matrix.SpecialLinearGroup.ext + intro i j + change (matrix3 a b c * matrix3 a' b' c') i j = matrix3 (a+a') (b+b') (c+c'+a*b') i j + fin_cases i <;> fin_cases j <;> simp [matrix3,Matrix.mul_apply,Fin.sum_univ_succ] <;> ring + +@[simp] lemma ca_mul (g h : upperGroup K 3) : ca (g*h) = ca g+ca h := by + rw [←upper3_coords g,←upper3_coords h,upper3_mul]; rfl +@[simp] lemma cb_mul (g h : upperGroup K 3) : cb (g*h) = cb g+cb h := by + rw [←upper3_coords g,←upper3_coords h,upper3_mul]; rfl +@[simp] lemma cc_mul (g h : upperGroup K 3) : cc (g*h) = cc g+cc h+ca g*cb h := by + rw [←upper3_coords g,←upper3_coords h,upper3_mul]; rfl +@[simp] lemma ca_one : ca (1 : upperGroup K 3) = 0 := by simp [ca] +@[simp] lemma cb_one : cb (1 : upperGroup K 3) = 0 := by simp [cb] +@[simp] lemma cc_one : cc (1 : upperGroup K 3) = 0 := by simp [cc] +@[simp] lemma ca_inv (g : upperGroup K 3) : ca g⁻¹ = -ca g := by + have h := ca_mul g⁻¹ g + simp only [inv_mul_cancel,ca_one] at h + linear_combination -h +@[simp] lemma cb_inv (g : upperGroup K 3) : cb g⁻¹ = -cb g := by + have h := cb_mul g⁻¹ g + simp only [inv_mul_cancel,cb_one] at h + linear_combination -h +@[simp] lemma cc_inv (g : upperGroup K 3) : cc g⁻¹ = -cc g+ca g*cb g := by + have h := cc_mul g⁻¹ g + simp only [inv_mul_cancel,cc_one,ca_inv] at h + linear_combination -h + +def pointCut : Cut 3 := ⟨2,by decide⟩ +def lineCut : Cut 3 := ⟨1,by decide⟩ +lemma mem_pointGroup (g : upperGroup K 3) : + g ∈ cutGroups K 3 pointCut ↔ cb g = 0 ∧ cc g = 0 := by + simp only [cutGroups,mem_suffixGroup,pointCut] + refine ⟨fun h => ⟨h 1 2 (by decide) (by decide), h 0 2 (by decide) (by decide)⟩,?_⟩ + rintro ⟨hb,hc⟩ i j hi hj + fin_cases i <;> fin_cases j <;> simp_all [cb,cc] +lemma mem_lineGroup (g : upperGroup K 3) : + g ∈ cutGroups K 3 lineCut ↔ ca g = 0 ∧ cc g = 0 := by + simp only [cutGroups,mem_suffixGroup,lineCut] + refine ⟨fun h => ⟨h 0 1 (by decide) (by decide), h 0 2 (by decide) (by decide)⟩,?_⟩ + rintro ⟨ha,hc⟩ i j hi hj + fin_cases i <;> fin_cases j <;> simp_all [ca,cc] + +lemma point_rel (g h : upperGroup K 3) : + g⁻¹*h ∈ cutGroups K 3 pointCut ↔ cb g = cb h ∧ cc g = cc h := by + rw [mem_pointGroup]; simp only [cb_mul,cb_inv,cc_mul,cc_inv,ca_inv] + constructor + · rintro ⟨hb,hc⟩ + have he : cb g = cb h := by linear_combination -hb + refine ⟨he,?_⟩ + rw [he] at hc + linear_combination -hc + · rintro ⟨hb,hc⟩; rw [hb,hc]; constructor <;> ring +lemma line_rel (g h : upperGroup K 3) : + g⁻¹*h ∈ cutGroups K 3 lineCut ↔ + ca g = ca h ∧ cc g-ca g*cb g = cc h-ca h*cb h := by + rw [mem_lineGroup]; simp only [ca_mul,ca_inv,cc_mul,cc_inv] + constructor + · rintro ⟨ha,hc⟩ + have he : ca g = ca h := by linear_combination -ha + refine ⟨he,?_⟩ + rw [he] at hc ⊢ + linear_combination -hc + · rintro ⟨ha,hc⟩; rw [ha]; constructor + · ring + · rw [ha] at hc; linear_combination -hc + +end + +open MatrixOpposition TypedCosetFaces InfiniteChains Cone +variable {K : Type} [Field K] +local instance : DecidableEq K := Classical.decEq _ + +abbrev Vert (K : Type) := (K × K) ⊕ (K × K) + +def cosetVertex : Vert K → Vertex (cutGroups K 3) + | .inl P => vertex (cutGroups K 3) (upper3 0 P.1 P.2) pointCut + | .inr L => vertex (cutGroups K 3) (upper3 L.1 0 L.2) lineCut + +lemma point_vertex (g : upperGroup K 3) : + cosetVertex (.inl (cb g,cc g)) = vertex (cutGroups K 3) g pointCut := by + dsimp only [cosetVertex,vertex] + apply congrArg (Sigma.mk _) + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + exact (point_rel _ _).mpr ⟨rfl,rfl⟩ +lemma line_vertex (g : upperGroup K 3) : + cosetVertex (.inr (ca g,cc g-ca g*cb g)) = vertex (cutGroups K 3) g lineCut := by + dsimp only [cosetVertex,vertex] + apply congrArg (Sigma.mk _) + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + apply (line_rel _ _).mpr + simp + +lemma cuts3 (i : Cut 3) : i = pointCut ∨ i = lineCut := by + have hi := i.property + by_cases h : i.val = 2 + · exact Or.inl (Subtype.ext h) + · exact Or.inr (Subtype.ext (by dsimp [lineCut]; omega)) + +lemma cosetVertex_injective : Function.Injective (cosetVertex (K:=K)) := by + intro x y h + cases x with + | inl P => + cases y with + | inl Q => + have hh := QuotientGroup.leftRel_apply.mp + (Quotient.exact (eq_of_heq (Sigma.mk.inj_iff.mp h).2)) + have he := (point_rel _ _).mp hh + congr 1 + exact Prod.ext he.1 he.2 + | inr L => + have he := congrArg (fun v => v.1.val) h + norm_num [cosetVertex,vertex,pointCut,lineCut] at he + | inr L => + cases y with + | inl P => + have he := congrArg (fun v => v.1.val) h + norm_num [cosetVertex,vertex,pointCut,lineCut] at he + | inr M => + have hh := QuotientGroup.leftRel_apply.mp + (Quotient.exact (eq_of_heq (Sigma.mk.inj_iff.mp h).2)) + have he := (line_rel _ _).mp hh + congr 1 + apply Prod.ext he.1 + simpa using he.2 + +lemma cosetVertex_surjective : Function.Surjective (cosetVertex (K:=K)) := by + rintro ⟨i,q⟩ + induction q using Quotient.inductionOn with | h g => + rcases cuts3 i with rfl | rfl + · exact ⟨.inl (cb g,cc g),point_vertex g⟩ + · exact ⟨.inr (ca g,cc g-ca g*cb g),line_vertex g⟩ + +def vertexEquiv : Vert K ≃ Vertex (cutGroups K 3) := + Equiv.ofBijective cosetVertex ⟨cosetVertex_injective,cosetVertex_surjective⟩ + +def incident (P L : K × K) : Prop := P.2 = L.1*P.1+L.2 + +def incidenceComplex (K : Type) [Field K] : CoboundaryExpanders.InfiniteChains.Complex (Vert K) where + faces := {s | ∃ P L : K×K, incident P L ∧ s ⊆ {Sum.inl P,Sum.inr L}} + empty_mem := ⟨(0,0),(0,0),by simp [incident],Finset.empty_subset _⟩ + downward := by + rintro s t ⟨P,L,hPL,hs⟩ ht + exact ⟨P,L,hPL,ht.trans hs⟩ + +lemma fullFace (g : upperGroup K 3) : + ({Sum.inl (cb g,cc g),Sum.inr (ca g,cc g-ca g*cb g)} : Finset (Vert K)).image cosetVertex = + face (cutGroups K 3) g {pointCut,lineCut} := by + simp only [Finset.image_insert,Finset.image_singleton,point_vertex,line_vertex,face] + +lemma face_subset_fullFace (g : upperGroup K 3) (A : Finset (Cut 3)) : + face (cutGroups K 3) g A ⊆ face (cutGroups K 3) g {pointCut,lineCut} := by + apply Finset.image_subset_image + intro i _ + rcases cuts3 i with rfl | rfl <;> simp + +lemma cosetVertex_face_iff (s : Finset (Vert K)) : + s.image cosetVertex ∈ (TypedCosetFaces.complex (cutGroups K 3)).faces ↔ + s ∈ (incidenceComplex K).faces := by + constructor + · rintro ⟨g,A,hg⟩ + refine ⟨(cb g,cc g),(ca g,cc g-ca g*cb g),?_,?_⟩ + · dsimp [incident]; ring + · apply (Finset.image_subset_image_iff cosetVertex_injective).mp + rw [fullFace,←hg] + exact face_subset_fullFace g A + · rintro ⟨P,L,hPL,hs⟩ + have he : (ca (upper3 L.1 P.1 P.2),cc (upper3 L.1 P.1 P.2)- + ca (upper3 L.1 P.1 P.2)*cb (upper3 L.1 P.1 P.2)) = L := by + apply Prod.ext + · rfl + · change P.2-L.1*P.1 = L.2 + rw [hPL]; ring + have hf := fullFace (upper3 L.1 P.1 P.2) + simp only [ca_upper3,cb_upper3,cc_upper3] at he hf + rw [he] at hf + apply IsFace.downward (H:=cutGroups K 3) ⟨_,_,rfl⟩ + rw [←hf] + exact Finset.image_subset_image hs + +def incidenceModel : FaceModel (incidenceComplex K) (TypedCosetFaces.complex (cutGroups K 3)) where + vertex := cosetVertex + injective := cosetVertex_injective + face_iff := cosetVertex_face_iff + cover := by + intro t ht + let s := t.image vertexEquiv.symm + have he : s.image cosetVertex = t := by + change s.image vertexEquiv = t + simp only [s,Finset.image_image,Function.comp_def,Equiv.apply_symm_apply,Finset.image_id'] + exact ⟨s,by rwa [←cosetVertex_face_iff,he],he⟩ + +end CoboundaryExpanders.RankTwoGeometry + +namespace CoboundaryExpanders.RankTwo +variable {K : Type} [Field K] [Fintype K] +local instance : DecidableEq K := Classical.decEq _ + +def lineSum (f : K → K → ℝ) (a b : K) : ℝ := ∑ x, f x (a*x+b) +def pointSum (g : K → K → ℝ) (x y : K) : ℝ := ∑ a, g a (y-a*x) +def energy (f : K → K → ℝ) : ℝ := ∑ x, ∑ y, (f x y)^2 + +def pairing (f g : K → K → ℝ) : ℝ := ∑ x, ∑ y, f x y * g x y + +omit [Field K] in +lemma energy_nonneg (f : K → K → ℝ) : 0 ≤ energy f := by + exact Finset.sum_nonneg (fun _ _ => Finset.sum_nonneg (fun _ _ => sq_nonneg _)) + +lemma affine_sum (x y x' : K) (h : x' ≠ x) (f : K → ℝ) : + ∑ a, f (a*x'+(y-a*x)) = ∑ z, f z := by + let e := (Equiv.mulRight₀ (x'-x) (sub_ne_zero.mpr h)).trans (Equiv.addRight y) + apply Fintype.sum_equiv e + intro a + congr 1 + change a*x'+(y-a*x) = a*(x'-x)+y + ring + +lemma adjoint (f g : K → K → ℝ) : pairing (lineSum f) g = pairing f (pointSum g) := by + unfold pairing lineSum pointSum + simp only [Finset.sum_mul, Finset.mul_sum] + conv_lhs => arg 2; ext a; rw [Finset.sum_comm] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + conv_rhs => rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + apply Fintype.sum_equiv (Equiv.addLeft (a*x)) + intro b + simp + +lemma gram (f : K → K → ℝ) (x y : K) : + pointSum (lineSum f) x y = + (Fintype.card K : ℝ) * f x y + ∑ x' ∈ Finset.univ.erase x, ∑ y', f x' y' := by + classical + unfold pointSum lineSum + rw [Finset.sum_comm, ← Finset.sum_erase_add _ _ (Finset.mem_univ x)] + have he (x' : K) (hx' : x' ∈ Finset.univ.erase x) : + ∑ a, f x' (a*x'+(y-a*x)) = ∑ y', f x' y' := + affine_sum x y x' (Finset.mem_erase.mp hx').1 (f x') + rw [Finset.sum_congr rfl he] + have hy (a : K) : a*x+(y-a*x) = y := by ring + simp only [hy, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + ring + +lemma gram_mean_zero (f : K → K → ℝ) (hf : ∑ x, ∑ y, f x y = 0) (x y : K) : + pointSum (lineSum f) x y = (Fintype.card K : ℝ) * f x y - ∑ y', f x y' := by + classical + rw [gram] + have h := Finset.sum_erase_add Finset.univ (fun x => ∑ y, f x y) (Finset.mem_univ x) + rw [hf] at h + linarith + +omit [Field K] in +lemma energy_eq_pairing (f : K → K → ℝ) : energy f = pairing f f := by + simp only [energy, pairing, pow_two] + +theorem incidence_energy_identity (f : K → K → ℝ) (hf : ∑ x, ∑ y, f x y = 0) : + energy (lineSum f) = (Fintype.card K : ℝ) * energy f - ∑ x, (∑ y, f x y)^2 := by + rw [energy_eq_pairing, adjoint] + simp only [pairing, gram_mean_zero f hf, mul_sub, Finset.sum_sub_distrib] + simp only [← Finset.sum_mul] + have h (x : K) : ∑ y, f x y * ((Fintype.card K : ℝ) * f x y) = + (Fintype.card K : ℝ) * ∑ y, (f x y)^2 := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + ring + simp only [h, ← Finset.mul_sum, ← pow_two, energy] + +theorem incidence_energy_bound (f : K → K → ℝ) (hf : ∑ x, ∑ y, f x y = 0) : + energy (lineSum f) ≤ (Fintype.card K : ℝ) * energy f := by + rw [incidence_energy_identity f hf] + have : 0 ≤ ∑ x, (∑ y, f x y)^2 := Finset.sum_nonneg (fun _ _ => sq_nonneg _) + linarith + +omit [Field K] in +lemma pairing_sq_le (f g : K → K → ℝ) : pairing f g ^ 2 ≤ energy f * energy g := by + simpa only [Fintype.sum_prod_type, pairing, energy] using + Finset.sum_mul_sq_le_sq_mul_sq (Finset.univ : Finset (K × K)) + (fun z => f z.1 z.2) (fun z => g z.1 z.2) + +theorem incidence_pairing_bound (f g : K → K → ℝ) (hf : ∑ x, ∑ y, f x y = 0) : + pairing (lineSum f) g ^ 2 ≤ (Fintype.card K : ℝ) * energy f * energy g := by + exact (pairing_sq_le (lineSum f) g).trans + (mul_le_mul_of_nonneg_right (incidence_energy_bound f hf) (energy_nonneg g)) + +def total (f : K → K → ℝ) : ℝ := ∑ x, ∑ y, f x y + +def center (f : K → K → ℝ) (x y : K) : ℝ := + f x y - total f / (Fintype.card K : ℝ)^2 + +lemma card_pos : (0 : ℝ) < Fintype.card K := by exact_mod_cast Fintype.card_pos + +lemma total_center (f : K → K → ℝ) : total (center f) = 0 := by + have hq := card_pos (K := K) + simp only [total, center, Finset.sum_sub_distrib, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul] + field_simp + ring + +lemma energy_center (f : K → K → ℝ) : + energy (center f) = energy f - (total f)^2 / (Fintype.card K : ℝ)^2 := by + have hq := card_pos (K := K) + have he (x y : K) : (center f x y)^2 = (f x y)^2 - + (2 * total f / (Fintype.card K : ℝ)^2) * f x y + + (total f / (Fintype.card K : ℝ)^2)^2 := by unfold center; ring + simp only [energy, he, Finset.sum_add_distrib, Finset.sum_sub_distrib, + ← Finset.mul_sum, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + change energy f - (2*total f/(Fintype.card K : ℝ)^2)*total f + + (Fintype.card K : ℝ)*((Fintype.card K : ℝ)*(total f/(Fintype.card K : ℝ)^2)^2) = _ + unfold energy + field_simp + ring + +lemma energy_center_le (f : K → K → ℝ) : energy (center f) ≤ energy f := by + rw [energy_center] + exact sub_le_self _ (div_nonneg (sq_nonneg _) (sq_nonneg _)) + +lemma total_lineSum (f : K → K → ℝ) : + total (lineSum f) = (Fintype.card K : ℝ) * total f := by + unfold total lineSum + calc + (∑ a, ∑ b, ∑ x, f x (a*x+b)) = ∑ a, ∑ x, ∑ b, f x (a*x+b) := by + apply Finset.sum_congr rfl; intro a _; exact Finset.sum_comm + _ = ∑ a : K, ∑ x, ∑ y, f x y := by + apply Finset.sum_congr rfl; intro a _ + apply Finset.sum_congr rfl; intro x _ + exact Equiv.sum_comp (Equiv.addLeft (a*x)) (f x) + _ = _ := by simp + +lemma lineSum_center (f : K → K → ℝ) (a b : K) : + lineSum (center f) a b = lineSum f a b - total f / (Fintype.card K : ℝ) := by + have hq := card_pos (K := K) + simp only [lineSum, center, Finset.sum_sub_distrib, Finset.sum_const, + Finset.card_univ, nsmul_eq_mul] + congr 1 + field_simp + +lemma incidence_center (f g : K → K → ℝ) : + pairing (lineSum (center f)) (center g) = + pairing (lineSum f) g - total f * total g / (Fintype.card K : ℝ) := by + have hq := card_pos (K := K) + have he (a b : K) : lineSum (center f) a b * center g a b = + lineSum f a b * g a b - (total g / (Fintype.card K : ℝ)^2) * lineSum f a b - + (total f / (Fintype.card K : ℝ)) * g a b + + total f * total g / (Fintype.card K : ℝ)^3 := by + rw [lineSum_center] + unfold center + field_simp + ring + simp only [pairing, he, Finset.sum_add_distrib, Finset.sum_sub_distrib, + ← Finset.mul_sum, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + change pairing (lineSum f) g - (total g / (Fintype.card K : ℝ)^2)*total (lineSum f) - + (total f / (Fintype.card K : ℝ))*total g + + (Fintype.card K : ℝ)*((Fintype.card K : ℝ)*(total f*total g/(Fintype.card K : ℝ)^3)) = _ + rw [total_lineSum] + unfold pairing + field_simp + ring + +theorem opposition_rayleigh (f g : K → K → ℝ) (hfg : total f + total g = 0) : + 2 * pairing (lineSum f) g ≤ + Real.sqrt (Fintype.card K : ℝ) * (energy f + energy g) := by + have hq := card_pos (K := K) + have hsq := Real.sq_sqrt hq.le + have hsqp := Real.sqrt_pos.mpr hq + let c := pairing (lineSum (center f)) (center g) + have hc : c^2 ≤ (Fintype.card K : ℝ) * energy (center f) * energy (center g) := + incidence_pairing_bound (center f) (center g) (total_center f) + have he : 2*c ≤ Real.sqrt (Fintype.card K : ℝ) * + (energy (center f) + energy (center g)) := by + have h0 := energy_nonneg (center f) + have h1 := energy_nonneg (center g) + have h2 := sq_nonneg (energy (center f) - energy (center g)) + have h3 : 0 ≤ Real.sqrt (Fintype.card K : ℝ) * + (energy (center f)+energy (center g)) := by positivity + apply le_of_sq_le_sq _ h3 + simp only [mul_pow, hsq] + nlinarith only [hc, mul_nonneg hq.le h2] + have hcent : pairing (lineSum f) g ≤ c := by + dsimp [c] + rw [incidence_center] + have hh : total f * total g ≤ 0 := by + have hg : total g = -total f := by linarith only [hfg] + rw [hg, mul_neg, ← pow_two] + exact neg_nonpos.mpr (sq_nonneg _) + have hd := div_nonpos_of_nonpos_of_nonneg hh hq.le + linarith + calc + 2*pairing (lineSum f) g ≤ 2*c := by linarith + _ ≤ _ := he + _ ≤ _ := mul_le_mul_of_nonneg_left + (add_le_add (energy_center_le f) (energy_center_le g)) hsqp.le + +end CoboundaryExpanders.RankTwo + +namespace CoboundaryExpanders.EdgeMixing +variable {V : Type*} [Fintype V] +def mass (e : V → V → ℝ) (x : V) : ℝ := ∑ y, e x y +def energy (e : V → V → ℝ) (f : V → ℝ) : ℝ := ∑ x, mass e x * (f x)^2 +def pairing (e : V → V → ℝ) (f g : V → ℝ) : ℝ := ∑ x, ∑ y, e x y * f x * g y +def Rayleigh (e : V → V → ℝ) (lam : ℝ) : Prop := + ∀ f : V → ℝ, (∑ x, mass e x * f x) = 0 → pairing e f f ≤ lam*energy e f +end CoboundaryExpanders.EdgeMixing + +namespace CoboundaryExpanders.RankTwo +variable {K : Type} [Field K] [Fintype K] +local instance : DecidableEq K := Classical.decEq _ +abbrev Vert (K : Type) := (K×K) ⊕ (K×K) +def edge : Vert K → Vert K → ℝ + | .inl P, .inr L => if P.2 = L.1*P.1+L.2 then 1 else 0 + | .inr L, .inl P => if P.2 = L.1*P.1+L.2 then 1 else 0 + | _, _ => 0 + +omit [Fintype K] in +lemma edge_symm (x y : Vert K) : edge x y = edge y x := by + cases x <;> cases y <;> rfl +omit [Fintype K] in +lemma edge_nonneg (x y : Vert K) : 0 ≤ edge x y := by + cases x <;> cases y <;> dsimp [edge] <;> positivity + +lemma point_degree (P : K×K) : EdgeMixing.mass edge (.inl P) = Fintype.card K := by + simp only [EdgeMixing.mass,Fintype.sum_sum_type,edge,Finset.sum_const_zero,zero_add, + Fintype.sum_prod_type] + have he (a b : K) : P.2 = a*P.1+b ↔ b = P.2-a*P.1 := by + constructor <;> intro h <;> linear_combination -h + simp only [he] + simp +lemma line_degree (L : K×K) : EdgeMixing.mass edge (.inr L) = Fintype.card K := by + simp only [EdgeMixing.mass,Fintype.sum_sum_type,edge,Finset.sum_const_zero,add_zero, + Fintype.sum_prod_type] + simp +lemma edge_degree (v : Vert K) : EdgeMixing.mass edge v = Fintype.card K := by + cases v with + | inl P => exact point_degree P + | inr L => exact line_degree L + +lemma cross_pairing (f g : K → K → ℝ) : + (∑ P : K×K, ∑ L : K×K, + (if P.2 = L.1*P.1+L.2 then (1:ℝ) else 0)*f P.1 P.2*g L.1 L.2) = + pairing (lineSum f) g := by + rw [Finset.sum_comm] + simp only [Fintype.sum_prod_type] + unfold pairing lineSum + apply Finset.sum_congr rfl + intro a _ + apply Finset.sum_congr rfl + intro b _ + simp only [Finset.sum_mul] + apply Finset.sum_congr rfl + intro x _ + simp + +lemma edge_pairing (F : Vert K → ℝ) : + EdgeMixing.pairing edge F F = 2 * pairing + (lineSum (fun x y => F (.inl (x,y)))) (fun a b => F (.inr (a,b))) := by + let f : K → K → ℝ := fun x y => F (.inl (x,y)) + let g : K → K → ℝ := fun x y => F (.inr (x,y)) + change _ = 2*pairing (lineSum f) g + have hleft := cross_pairing f g + have hright : (∑ L : K×K, ∑ P : K×K, + (if P.2 = L.1*P.1+L.2 then (1:ℝ) else 0)*g L.1 L.2*f P.1 P.2) = + pairing (lineSum f) g := by + rw [Finset.sum_comm] + convert hleft using 1 + apply Finset.sum_congr rfl + intro P _ + apply Finset.sum_congr rfl + intro L _ + ring + simp only [EdgeMixing.pairing,Fintype.sum_sum_type,edge,zero_mul,Finset.sum_const_zero, + zero_add,add_zero] + change (∑ P : K×K, ∑ L : K×K, + (if P.2=L.1*P.1+L.2 then (1:ℝ) else 0)*f P.1 P.2*g L.1 L.2) + + (∑ L : K×K, ∑ P : K×K, + (if P.2=L.1*P.1+L.2 then (1:ℝ) else 0)*g L.1 L.2*f P.1 P.2) = _ + rw [hleft,hright] + ring + +lemma edge_energy (F : Vert K → ℝ) : EdgeMixing.energy edge F = + (Fintype.card K : ℝ) * (energy (fun x y => F (.inl (x,y))) + + energy (fun x y => F (.inr (x,y)))) := by + simp only [EdgeMixing.energy,edge_degree,Fintype.sum_sum_type,Fintype.sum_prod_type, + ←Finset.mul_sum,energy] + +lemma edge_mean (F : Vert K → ℝ) : (∑ v,EdgeMixing.mass edge v*F v) = + (Fintype.card K : ℝ) * (total (fun x y => F (.inl (x,y))) + + total (fun x y => F (.inr (x,y)))) := by + simp only [edge_degree,Fintype.sum_sum_type,Fintype.sum_prod_type,←Finset.mul_sum,total] + +theorem edge_rayleigh : EdgeMixing.Rayleigh (edge (K:=K)) + (Real.sqrt (Fintype.card K : ℝ)/(Fintype.card K : ℝ)) := by + intro F hF + have hq : (Fintype.card K : ℝ) ≠ 0 := ne_of_gt card_pos + rw [edge_mean] at hF + have hmean := (mul_eq_zero.mp hF).resolve_left hq + rw [edge_pairing,edge_energy] + have he := opposition_rayleigh (fun x y => F (.inl (x,y))) (fun x y => F (.inr (x,y))) hmean + convert he using 1 + field_simp + +end CoboundaryExpanders.RankTwo + +namespace CoboundaryExpanders.EdgeMixing +variable {V W : Type} [Fintype V] [Fintype W] +lemma sum_embedding (f : V → W) (hf : Function.Injective f) (F : W → ℝ) + (hF : ∀ y, y ∉ Set.range f → F y = 0) : (∑ y,F y) = ∑ x,F (f x) := by + classical + rw [←Finset.sum_image (s:=Finset.univ) (f:=F) (g:=f) (fun _ _ _ _ h => hf h)] + symm + apply Finset.sum_subset (Finset.subset_univ _) + intro y _ hy + exact hF y (by simpa only [Finset.mem_image,Finset.mem_univ,true_and,Set.mem_range] using hy) + +structure Embedding (e : V → V → ℝ) (d : W → W → ℝ) where + vertex : V → W + injective : Function.Injective vertex + edge_eq : ∀ x y, d (vertex x) (vertex y) = e x y + outside_zero : ∀ y, y ∉ Set.range vertex → ∀ z, d y z = 0 + +namespace Embedding +variable {e : V → V → ℝ} {d : W → W → ℝ} (M : Embedding e d) + (hd : ∀ x y,d x y = d y x) +include M hd + +lemma mass_map (x : V) : mass d (M.vertex x) = mass e x := by + unfold mass + rw [sum_embedding M.vertex M.injective _ (fun y hy => by rw [hd,M.outside_zero y hy])] + simp only [M.edge_eq] +omit hd [Fintype V] in +lemma mass_outside (y : W) (hy : y ∉ Set.range M.vertex) : mass d y = 0 := by + simp only [mass,M.outside_zero y hy,Finset.sum_const_zero] +lemma mean_pull (F : W → ℝ) : (∑ y,mass d y*F y) = ∑ x,mass e x*F (M.vertex x) := by + rw [sum_embedding M.vertex M.injective _ (fun y hy => by rw [M.mass_outside y hy,zero_mul])] + simp only [M.mass_map hd] +lemma energy_pull (F : W → ℝ) : energy d F = energy e (F ∘ M.vertex) := by + unfold energy + rw [sum_embedding M.vertex M.injective _ (fun y hy => by rw [M.mass_outside y hy,zero_mul])] + simp only [M.mass_map hd,Function.comp_apply] +lemma pairing_pull (F H : W → ℝ) : pairing d F H = pairing e (F ∘ M.vertex) (H ∘ M.vertex) := by + unfold pairing + rw [sum_embedding M.vertex M.injective _ (fun y hy => by + simp only [M.outside_zero y hy,zero_mul,Finset.sum_const_zero])] + apply Finset.sum_congr rfl + intro x _ + rw [sum_embedding M.vertex M.injective _ (fun y hy => by + rw [hd,M.outside_zero y hy,zero_mul,zero_mul])] + simp only [M.edge_eq,Function.comp_apply] + +theorem push {lam : ℝ} (he : Rayleigh e lam) : Rayleigh d lam := by + intro F hF + rw [M.mean_pull hd] at hF + rw [M.pairing_pull hd,M.energy_pull hd] + exact he (F ∘ M.vertex) hF +end Embedding +end CoboundaryExpanders.EdgeMixing + +namespace CoboundaryExpanders.InfiniteChains +namespace FiniteWeights +variable {V : Type} [Fintype V] [DecidableEq V] +def level (X : CoboundaryExpanders.InfiniteChains.Complex V) (r : ℕ) : Finset (Finset V) := by + classical + exact Finset.univ.filter (fun s => s ∈ X.faces ∧ s.card = r) + +omit [DecidableEq V] in +@[simp] lemma mem_level (X : CoboundaryExpanders.InfiniteChains.Complex V) (r : ℕ) (s : Finset V) : + s ∈ level X r ↔ s ∈ X.faces ∧ s.card = r := by simp [level] + +def cofaces (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (s : Finset V) : ℕ := + ((level X N).filter (fun t => s ⊆ t)).card + +def Pure (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) : Prop := + (level X N).Nonempty ∧ ∀ s ∈ X.faces, ∃ t ∈ level X N, s ⊆ t + +lemma cofaces_zero_of_not_face (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) {s : Finset V} (hs : s ∉ X.faces) : + cofaces X N s = 0 := by + unfold cofaces + apply Finset.card_eq_zero.mpr + apply Finset.eq_empty_iff_forall_notMem.mpr + intro t ht + obtain ⟨ht,hst⟩ := Finset.mem_filter.mp ht + exact hs (X.downward ((mem_level X N t).mp ht).1 hst) + +lemma cofaces_link (X : CoboundaryExpanders.InfiniteChains.Complex V) {N : ℕ} {s : Finset V} (hs : s ∈ X.faces) + (hN : s.card ≤ N) {a : Finset V} (hd : Disjoint s a) : + cofaces (X.faceLink s hs) (N-s.card) a = cofaces X N (s∪a) := by + unfold cofaces + apply Finset.card_bij (fun t _ => s∪t) + · intro t ht + obtain ⟨ht,hat⟩ := Finset.mem_filter.mp ht + obtain ⟨ht,hcard⟩ := (mem_level _ _ _).mp ht + refine Finset.mem_filter.mpr ⟨(mem_level _ _ _).mpr ⟨ht.2,?_⟩, + Finset.union_subset_union (Finset.Subset.refl _) hat⟩ + rw [Finset.card_union_of_disjoint ht.1,hcard] + omega + · intro t ht u hu he + have hd1 := ((mem_level _ _ _).mp (Finset.mem_filter.mp ht).1).1.1 + have hd2 := ((mem_level _ _ _).mp (Finset.mem_filter.mp hu).1).1.1 + have hh := congrArg (fun t : Finset V => t\s) he + simpa only [Finset.union_sdiff_cancel_left hd1,Finset.union_sdiff_cancel_left hd2] using hh + · intro t ht + obtain ⟨ht,hat⟩ := Finset.mem_filter.mp ht + obtain ⟨ht,hcard⟩ := (mem_level _ _ _).mp ht + have hst : s ⊆ t := Finset.subset_union_left.trans hat + have hdis : Disjoint s (t\s) := Finset.disjoint_left.mpr (fun v hv hv' => (Finset.mem_sdiff.mp hv').2 hv) + refine ⟨t\s,Finset.mem_filter.mpr ⟨(mem_level _ _ _).mpr ⟨⟨hdis,?_⟩,?_⟩,?_⟩,?_⟩ + · rwa [Finset.union_sdiff_of_subset hst] + · rw [Finset.card_sdiff_of_subset hst,hcard] + · intro v hv + exact Finset.mem_sdiff.mpr ⟨hat (Finset.mem_union_right _ hv),fun h => Finset.disjoint_left.mp hd h hv⟩ + · exact Finset.union_sdiff_of_subset hst + +lemma pure_link {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} (hP : Pure X N) {s : Finset V} (hs : s ∈ X.faces) : + Pure (X.faceLink s hs) (N-s.card) := by + have extension : ∀ a ∈ (X.faceLink s hs).faces, + ∃ t ∈ level (X.faceLink s hs) (N-s.card), a ⊆ t := by + intro a ha + obtain ⟨t,ht,hat⟩ := hP.2 _ ha.2 + have ht' := (mem_level X N t).mp ht + have hst := Finset.subset_union_left.trans hat + refine ⟨t\s,(mem_level _ _ _).mpr ⟨⟨?_,?_⟩,?_⟩,?_⟩ + · exact Finset.disjoint_left.mpr (fun v hv hv' => (Finset.mem_sdiff.mp hv').2 hv) + · rw [Finset.union_sdiff_of_subset hst]; exact ht'.1 + · rw [Finset.card_sdiff_of_subset hst,ht'.2] + · intro v hv + exact Finset.mem_sdiff.mpr ⟨hat (Finset.mem_union_right _ hv), fun h => Finset.disjoint_left.mp ha.1 h hv⟩ + obtain ⟨t,ht,_⟩ := extension ∅ (X.faceLink s hs).empty_mem + exact ⟨⟨t,ht⟩,extension⟩ + +end FiniteWeights + +open FiniteWeights +variable {V W : Type} [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] +attribute [local instance] Classical.propDecidable + +namespace Cone.FaceModel +variable {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + +lemma cofaces_image (N : ℕ) (s : Finset V) : + cofaces Y N (s.image M.vertex) = cofaces X N s := by + unfold cofaces + symm + apply Finset.card_bij (fun t _ => t.image M.vertex) + · intro t ht + obtain ⟨ht,hst⟩ := Finset.mem_filter.mp ht + obtain ⟨ht,hcard⟩ := (mem_level _ _ _).mp ht + exact Finset.mem_filter.mpr ⟨(mem_level _ _ _).mpr + ⟨(M.face_iff t).mpr ht,by rwa [Finset.card_image_of_injective t M.injective]⟩, + Finset.image_subset_image hst⟩ + · intro t ht u hu he + exact Finset.image_injective M.injective he + · intro t ht + obtain ⟨ht,hst⟩ := Finset.mem_filter.mp ht + obtain ⟨ht,hcard⟩ := (mem_level _ _ _).mp ht + obtain ⟨u,hu,he⟩ := M.cover t ht + refine ⟨u,Finset.mem_filter.mpr ⟨(mem_level _ _ _).mpr ⟨hu,?_⟩,?_⟩,he⟩ + · rw [←he,Finset.card_image_of_injective u M.injective] at hcard + exact hcard + · rw [←he] at hst + exact (Finset.image_subset_image_iff M.injective).mp hst + +omit [Fintype V] [Fintype W] [DecidableEq V] in +lemma vertex_in_range {y : W} (hy : ({y}:Finset W) ∈ Y.faces) : y ∈ Set.range M.vertex := by + obtain ⟨s,hs,he⟩ := M.cover {y} hy + have h : y ∈ s.image M.vertex := by rw [he]; simp + obtain ⟨x,hx,hxy⟩ := Finset.mem_image.mp h + exact ⟨x,hxy⟩ + +end Cone.FaceModel + +namespace FiniteWeights + +def edge (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (x y : V) : ℝ := + if x ≠ y then (cofaces X N {x,y}:ℝ) else 0 +lemma edge_symm (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (x y : V) : edge X N x y = edge X N y x := by + simp only [edge,ne_comm,Finset.pair_comm] +lemma edge_nonneg (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (x y : V) : 0 ≤ edge X N x y := by + unfold edge; split_ifs <;> positivity +lemma edge_zero_of_not_face (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) {x : V} (hx : ({x}:Finset V) ∉ X.faces) + (y : V) : edge X N x y = 0 := by + unfold edge + split_ifs + · rw [cofaces_zero_of_not_face X N (fun h => hx (X.downward h (by simp))),Nat.cast_zero] + · rfl + +lemma cofaces_pos {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} (hP : Pure X N) {s : Finset V} (hs : s ∈ X.faces) : + 0 < cofaces X N s := by + obtain ⟨t,ht,hst⟩ := hP.2 s hs + exact Finset.card_pos.mpr ⟨t,Finset.mem_filter.mpr ⟨ht,hst⟩⟩ +lemma cofaces_pos_iff {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} (hP : Pure X N) (s : Finset V) : + 0 < cofaces X N s ↔ s ∈ X.faces := by + refine ⟨fun h => ?_,cofaces_pos hP⟩ + by_contra hs + rw [cofaces_zero_of_not_face X N hs] at h + omega + +end FiniteWeights + +namespace Cone.FaceModel +variable {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + +def spectralEmbedding (N : ℕ) : EdgeMixing.Embedding (edge X N) (edge Y N) where + vertex := M.vertex + injective := M.injective + edge_eq := by + intro x y + simp only [edge,M.injective.ne_iff] + split_ifs + · have h := M.cofaces_image N {x,y} + simpa only [Finset.image_insert,Finset.image_singleton] using congrArg (fun a : ℕ => (a:ℝ)) h + · rfl + outside_zero := by + intro y hy z + apply edge_zero_of_not_face Y N + exact fun h => hy (M.vertex_in_range h) + +include M in +theorem rayleigh_push {N : ℕ} {lam : ℝ} (hX : EdgeMixing.Rayleigh (edge X N) lam) : + EdgeMixing.Rayleigh (edge Y N) lam := + (M.spectralEmbedding N).push (edge_symm Y N) hX +end Cone.FaceModel +end CoboundaryExpanders.InfiniteChains + +namespace CoboundaryExpanders.InfiniteChains.FiniteWeights +variable {V : Type} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable +lemma cofaces_top (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (s : Finset V) (hs : s.card = N) : + cofaces X N s = if s ∈ X.faces then 1 else 0 := by + by_cases hf : s ∈ X.faces + · rw [ite_eq_left hf] + have he : (level X N).filter (fun t => s ⊆ t) = {s} := by + ext t + simp only [Finset.mem_filter,mem_level,Finset.mem_singleton] + constructor + · rintro ⟨⟨ht,hcard⟩,hst⟩ + exact (Finset.eq_of_subset_of_card_le hst (by omega)).symm + · rintro rfl + exact ⟨⟨hf,hs⟩,Finset.Subset.refl _⟩ + simp only [cofaces,he,Finset.card_singleton] + · rw [ite_eq_right hf,cofaces_zero_of_not_face X N hf] +end CoboundaryExpanders.InfiniteChains.FiniteWeights + +namespace CoboundaryExpanders.RankTwoGeometry +open InfiniteChains FiniteWeights MatrixOpposition +variable {K : Type} [Field K] [Fintype K] +local instance : DecidableEq K := Classical.decEq _ + +omit [Fintype K] in +lemma point_line_face (P L : K×K) : + ({Sum.inl P,Sum.inr L}:Finset (Vert K)) ∈ (incidenceComplex K).faces ↔ incident P L := by + constructor + · rintro ⟨P',L',hPL,hs⟩ + have hP := hs (Finset.mem_insert_self _ _) + have hL := hs (Finset.mem_insert_of_mem (Finset.mem_singleton_self _)) + simp only [Finset.mem_insert,Finset.mem_singleton,Sum.inl.injEq,Sum.inr.injEq, + Sum.inl_ne_inr,Sum.inr_ne_inl,false_or,or_false] at hP hL + simpa only [hP,hL] using hPL + · intro hPL + exact ⟨P,L,hPL,Finset.Subset.refl _⟩ +omit [Fintype K] in +lemma point_point_not_face (P Q : K×K) (hPQ : P ≠ Q) : + ({Sum.inl P,Sum.inl Q}:Finset (Vert K)) ∉ (incidenceComplex K).faces := by + rintro ⟨P',L',hPL,hs⟩ + have hP := hs (Finset.mem_insert_self _ _) + have hQ := hs (Finset.mem_insert_of_mem (Finset.mem_singleton_self _)) + simp only [Finset.mem_insert,Finset.mem_singleton,Sum.inl.injEq,Sum.inl_ne_inr,or_false] at hP hQ + exact hPQ (hP.trans hQ.symm) +omit [Fintype K] in +lemma line_line_not_face (L M : K×K) (hLM : L ≠ M) : + ({Sum.inr L,Sum.inr M}:Finset (Vert K)) ∉ (incidenceComplex K).faces := by + rintro ⟨P',L',hPL,hs⟩ + have hL := hs (Finset.mem_insert_self _ _) + have hM := hs (Finset.mem_insert_of_mem (Finset.mem_singleton_self _)) + simp only [Finset.mem_insert,Finset.mem_singleton,Sum.inr.injEq,Sum.inr_ne_inl,false_or] at hL hM + exact hLM (hL.trans hM.symm) + +lemma incidence_edge (x y : Vert K) : edge (incidenceComplex K) 2 x y = RankTwo.edge x y := by + cases x with + | inl P => + cases y with + | inl Q => + by_cases h : P = Q + · subst Q; simp [edge,RankTwo.edge] + · simp [edge,RankTwo.edge,h,cofaces_zero_of_not_face _ 2 (point_point_not_face P Q h)] + | inr L => + rw [edge,ite_eq_left (by simp),cofaces_top _ 2 _ (by simp),point_line_face] + simp only [RankTwo.edge,incident] + split_ifs <;> simp_all + | inr L => + cases y with + | inl P => + rw [edge_symm,RankTwo.edge_symm] + rw [edge,ite_eq_left (by simp),cofaces_top _ 2 _ (by simp),point_line_face] + simp only [RankTwo.edge,incident] + split_ifs <;> simp_all + | inr M => + by_cases h : L = M + · subst M; simp [edge,RankTwo.edge] + · simp [edge,RankTwo.edge,h,cofaces_zero_of_not_face _ 2 (line_line_not_face L M h)] + +theorem incidence_rayleigh : EdgeMixing.Rayleigh (edge (incidenceComplex K) 2) + (Real.sqrt (Fintype.card K : ℝ)/(Fintype.card K : ℝ)) := by + convert RankTwo.edge_rayleigh (K:=K) using 1 + funext x y + exact incidence_edge x y + +end CoboundaryExpanders.RankTwoGeometry + +namespace CoboundaryExpanders.MatrixOpposition +open InfiniteChains FiniteWeights TypedCosetFaces +variable {K : Type} [Field K] [Fintype K] +noncomputable instance cutVertexFintype (N : ℕ) : Fintype (Vertex (cutGroups K N)) := Fintype.ofFinite _ + +theorem cut3_rayleigh : EdgeMixing.Rayleigh (edge (TypedCosetFaces.complex (cutGroups K 3)) 2) + (Real.sqrt (Fintype.card K : ℝ)/(Fintype.card K : ℝ)) := by + classical + exact RankTwoGeometry.incidenceModel.rayleigh_push RankTwoGeometry.incidence_rayleigh +end CoboundaryExpanders.MatrixOpposition + +namespace CoboundaryExpanders.EdgeMixing + +section +variable {V W : Type} [Fintype V] [Fintype W] +attribute [local instance] Classical.propDecidable +namespace Embedding +variable {e : V → V → ℝ} {d : W → W → ℝ} (M : Embedding e d) +def extend (f : V → ℝ) (y : W) : ℝ := + if h : y ∈ Set.range M.vertex then f h.choose else 0 +omit [Fintype W] in +lemma extend_map (f : V → ℝ) (x : V) : M.extend f (M.vertex x) = f x := by + dsimp [extend] + rw [dite_eq_left (show M.vertex x ∈ Set.range M.vertex from ⟨x,rfl⟩)] + congr 1 + exact M.injective (Exists.choose_spec (show M.vertex x ∈ Set.range M.vertex from ⟨x,rfl⟩)) +omit [Fintype W] in +lemma extend_comp (f : V → ℝ) : M.extend f ∘ M.vertex = f := funext (M.extend_map f) +include M in +theorem pull (hd : ∀ x y,d x y = d y x) {lam : ℝ} (h : Rayleigh d lam) : Rayleigh e lam := by + intro f hf + have hh := h (M.extend f) (by + rw [M.mean_pull hd] + simpa only [M.extend_map] using hf) + rwa [M.pairing_pull hd,M.energy_pull hd,M.extend_comp] at hh +end Embedding + +end + +variable {A B : Type} [Fintype A] [Fintype B] +def bipartiteEdge : A ⊕ B → A ⊕ B → ℝ + | Sum.inl _,Sum.inr _ => 1 + | Sum.inr _,Sum.inl _ => 1 + | _,_ => 0 +@[simp] lemma bipartite_mass_left (a : A) : mass (bipartiteEdge (B:=B)) (Sum.inl a) = Fintype.card B := by + simp [mass,Fintype.sum_sum_type,bipartiteEdge] +@[simp] lemma bipartite_mass_right (b : B) : mass (bipartiteEdge (A:=A)) (Sum.inr b) = Fintype.card A := by + simp [mass,Fintype.sum_sum_type,bipartiteEdge] + +lemma bipartite_rayleigh : Rayleigh (bipartiteEdge (A:=A) (B:=B)) 0 := by + intro f hf + have hm : (Fintype.card B:ℝ)*(∑a,f (Sum.inl a))+(Fintype.card A:ℝ)*(∑b,f (Sum.inr b)) = 0 := by + simpa only [Fintype.sum_sum_type,bipartite_mass_left,bipartite_mass_right,←Finset.mul_sum] using hf + have hp : pairing bipartiteEdge f f = 2*(∑a,f (Sum.inl a))*(∑b,f (Sum.inr b)) := by + simp only [pairing,Fintype.sum_sum_type,bipartiteEdge,zero_mul,one_mul, + Finset.sum_const_zero,zero_add,add_zero,←Finset.mul_sum,←Finset.sum_mul] + ring + rw [hp,zero_mul] + by_cases ha : IsEmpty A + · let := ha + simp + · have han : 0 < (Fintype.card A:ℝ) := by exact_mod_cast Fintype.card_pos_iff.mpr (not_isEmpty_iff.mp ha) + have hmult := congrArg (fun r : ℝ => r*(∑a,f (Sum.inl a))) hm + have hsq := mul_nonneg (Nat.cast_nonneg (Fintype.card B) : (0:ℝ) ≤ _) (sq_nonneg (∑a,f (Sum.inl a))) + have hprod : (∑a,f (Sum.inl a))*(∑b,f (Sum.inr b)) ≤ 0 := by + apply (mul_le_mul_iff_right₀ han).mp + change (Fintype.card A:ℝ)*((∑a,f (Sum.inl a))*(∑b,f (Sum.inr b))) ≤ (Fintype.card A:ℝ)*0 + nlinarith [hmult,hsq] + linarith +end CoboundaryExpanders.EdgeMixing + +namespace CoboundaryExpanders.InfiniteChains.Join +open Cone FiniteWeights +variable {V W : Type} [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] +attribute [local instance] Classical.propDecidable +omit [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] in +@[simp] lemma left_single_inl (x : V) : ({Sum.inl x}:Finset (V ⊕ W)).toLeft = {x} := by ext y; simp +omit [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] in +@[simp] lemma right_single_inl (x : V) : ({Sum.inl x}:Finset (V ⊕ W)).toRight = ∅ := by ext y; simp +omit [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] in +@[simp] lemma left_single_inr (x : W) : ({Sum.inr x}:Finset (V ⊕ W)).toLeft = ∅ := by ext y; simp +omit [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] in +@[simp] lemma right_single_inr (x : W) : ({Sum.inr x}:Finset (V ⊕ W)).toRight = {x} := by ext y; simp + +abbrev TrueVertex (X : CoboundaryExpanders.InfiniteChains.Complex V) := {x : V // ({x}:Finset V) ∈ X.faces} + +def rankOneEmbedding {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} + (hX : RankBound X 1) (hY : RankBound Y 1) : + EdgeMixing.Embedding (EdgeMixing.bipartiteEdge (A:=TrueVertex X) (B:=TrueVertex Y)) + (edge (complex X Y) 2) where + vertex := Sum.map Subtype.val Subtype.val + injective := Sum.map_injective.mpr ⟨Subtype.val_injective,Subtype.val_injective⟩ + edge_eq := by + intro x y + cases x with + | inl a => + cases y with + | inl b => + change edge (complex X Y) 2 (Sum.inl a.val) (Sum.inl b.val) = 0 + by_cases hab : a = b + · subst b; simp [edge] + · have hv : a.val ≠ b.val := fun h => hab (Subtype.ext h) + have hne : Sum.inl a.val ≠ (Sum.inl b.val : V ⊕ W) := fun h => hv (Sum.inl.inj h) + have hnot : ({Sum.inl a.val,Sum.inl b.val}:Finset (V ⊕ W)) ∉ (complex X Y).faces := by + intro h + have hh := hX {a.val,b.val} (by simpa [complex] using h.1) + rw [Finset.card_pair hv] at hh + omega + simp [edge,hne,cofaces_zero_of_not_face _ _ hnot] + | inr b => + change edge (complex X Y) 2 (Sum.inl a.val) (Sum.inr b.val) = 1 + rw [edge,ite_eq_left (by simp),cofaces_top _ _ _ (Finset.card_pair (by simp))] + have hf : ({Sum.inl a.val,Sum.inr b.val}:Finset (V ⊕ W)) ∈ (complex X Y).faces := by + simpa [complex] using And.intro a.property b.property + simp [hf] + | inr a => + cases y with + | inl b => + change edge (complex X Y) 2 (Sum.inr a.val) (Sum.inl b.val) = 1 + rw [edge,ite_eq_left (by simp),cofaces_top _ _ _ (Finset.card_pair (by simp))] + have hf : ({Sum.inr a.val,Sum.inl b.val}:Finset (V ⊕ W)) ∈ (complex X Y).faces := by + simpa [complex] using And.intro b.property a.property + simp [hf] + | inr b => + change edge (complex X Y) 2 (Sum.inr a.val) (Sum.inr b.val) = 0 + by_cases hab : a = b + · subst b; simp [edge] + · have hv : a.val ≠ b.val := fun h => hab (Subtype.ext h) + have hne : Sum.inr a.val ≠ (Sum.inr b.val : V ⊕ W) := fun h => hv (Sum.inr.inj h) + have hnot : ({Sum.inr a.val,Sum.inr b.val}:Finset (V ⊕ W)) ∉ (complex X Y).faces := by + intro h + have hh := hY {a.val,b.val} (by simpa [complex] using h.2) + rw [Finset.card_pair hv] at hh + omega + simp [edge,hne,cofaces_zero_of_not_face _ _ hnot] + outside_zero := by + intro x hx y + apply edge_zero_of_not_face + intro h + cases x with + | inl a => + have ha : ({a}:Finset V) ∈ X.faces := by simpa [complex] using h.1 + exact hx ⟨Sum.inl ⟨a,ha⟩,rfl⟩ + | inr b => + have hb : ({b}:Finset W) ∈ Y.faces := by simpa [complex] using h.2 + exact hx ⟨Sum.inr ⟨b,hb⟩,rfl⟩ + +lemma rankOne_rayleigh {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} + (hX : RankBound X 1) (hY : RankBound Y 1) : EdgeMixing.Rayleigh (edge (complex X Y) 2) 0 := + (rankOneEmbedding hX hY).push (edge_symm _ _) EdgeMixing.bipartite_rayleigh +end CoboundaryExpanders.InfiniteChains.Join + +namespace CoboundaryExpanders.EdgeMixing +variable {V : Type} [Fintype V] +lemma rayleigh_mono {e : V → V → ℝ} (he : ∀ x y,0 ≤ e x y) {a b : ℝ} + (h : Rayleigh e a) (hab : a ≤ b) : Rayleigh e b := by + intro f hf + apply (h f hf).trans + apply mul_le_mul_of_nonneg_right hab + exact Finset.sum_nonneg (fun x _ => mul_nonneg (Finset.sum_nonneg (fun y _ => he x y)) (sq_nonneg _)) +end CoboundaryExpanders.EdgeMixing + +namespace CoboundaryExpanders.InfiniteChains +open Cone FiniteWeights +variable {V W : Type} [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] + +def TopSpectral (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (lam : ℝ) : Prop := + ∀ s : Finset V, ∀ hs : s ∈ X.faces, s.card+2 = N → + EdgeMixing.Rayleigh (edge (X.faceLink s hs) 2) lam + +lemma Cone.FaceModel.rayleigh_pull {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + (N : ℕ) {lam : ℝ} (hY : EdgeMixing.Rayleigh (edge Y N) lam) : + EdgeMixing.Rayleigh (edge X N) lam := + (M.spectralEmbedding N).pull (edge_symm Y N) hY + +lemma Cone.FaceModel.pushTopSpectral {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + {N : ℕ} {lam : ℝ} (h : TopSpectral X N lam) : TopSpectral Y N lam := by + intro t ht hn + obtain ⟨s,hs,rfl⟩ := M.cover t ht + rw [Finset.card_image_of_injective _ M.injective] at hn + exact (M.linkModel s hs).rayleigh_push (h s hs hn) +lemma Cone.FaceModel.pullTopSpectral {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + {N : ℕ} {lam : ℝ} (h : TopSpectral Y N lam) : TopSpectral X N lam := by + intro s hs hn + apply (M.linkModel s hs).rayleigh_pull 2 + apply h + rwa [Finset.card_image_of_injective _ M.injective] + +theorem Join.topSpectral {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} {A B : ℕ} {lam : ℝ} + (hX : RankBound X A) (hY : RankBound Y B) (h0 : 0 ≤ lam) + (hTX : TopSpectral X A lam) (hTY : TopSpectral Y B lam) : + TopSpectral (Join.complex X Y) (A+B) lam := by + intro s hs hn + have hL := hX s.toLeft hs.1 + have hR := hY s.toRight hs.2 + have hC := Finset.card_toLeft_add_card_toRight (u:=s) + rw [Join.link_eq hs] + by_cases hA : s.toLeft.card = A + · have hB : s.toRight.card+2 = B := by omega + exact (Join.emptyLeftModel (hX.terminal hs.1 hA)).rayleigh_push (hTY _ hs.2 hB) + by_cases hB : s.toRight.card = B + · have hAl : s.toLeft.card+2 = A := by omega + exact (Join.emptyRightModel (hY.terminal hs.2 hB)).rayleigh_push (hTX _ hs.1 hAl) + have hAl : A-s.toLeft.card = 1 := by omega + have hBl : B-s.toRight.card = 1 := by omega + apply EdgeMixing.rayleigh_mono (edge_nonneg _ _) _ h0 + exact Join.rankOne_rayleigh (hAl ▸ hX.link hs.1) (hBl ▸ hY.link hs.2) + +lemma TopSpectral.vertexCriterion {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} {lam : ℝ} + (hBase : N = 2 → EdgeMixing.Rayleigh (edge X 2) lam) + (hVertex : ∀ v : V, ∀ hv : {v} ∈ X.faces, TopSpectral (X.faceLink {v} hv) (N-1) lam) : + TopSpectral X N lam := by + intro s hs hn + by_cases he : s = ∅ + · subst s + simpa only [faceLink_empty] using hBase (by simpa using hn.symm) + obtain ⟨v,hv⟩ := Finset.nonempty_iff_ne_empty.mpr he + have hvx : {v} ∈ X.faces := X.downward hs (Finset.singleton_subset_iff.mpr hv) + have hu : {v} ∪ s.erase v = s := by simp [Finset.insert_erase hv] + have ht : s.erase v ∈ (X.faceLink {v} hvx).faces := by + constructor + · simp + · rwa [hu] + have hc : (s.erase v).card = s.card-1 := Finset.card_erase_of_mem hv + have hp := Finset.card_pos.mpr ⟨v,hv⟩ + have HH := hVertex v hvx (s.erase v) ht (by omega) + rw [faceLink_iterated] at HH + have heq : X.faceLink ({v} ∪ s.erase v) ht.2 = X.faceLink s hs := by + apply complex_eq + ext a + simp only [Complex.faceLink, hu] + rwa [heq] at HH +end CoboundaryExpanders.InfiniteChains + +namespace CoboundaryExpanders.MatrixOpposition +open SphericalOpposition SphericalOpposition.CompleteFlag TypedCosetFaces InfiniteChains Cone +open scoped Pointwise +variable {K : Type} [Field K] {N : ℕ} +lemma cut_middle_topSpectral [Fintype K] {a b : ℕ} {lam : ℝ} + (ha : 0 < a) (hb : 0 < b) (h0 : 0 ≤ lam) + (hA : TopSpectral (TypedCosetFaces.complex (cutGroups K a)) (a-1) lam) + (hB : TopSpectral (TypedCosetFaces.complex (cutGroups K b)) (b-1) lam) : + TopSpectral (linkComplex (cutGroups K (a+b)) {middleCut ha hb}) ((a-1)+(b-1)) lam := by + classical + let : Fintype (Vertex (productGroups (cutGroups K a) (cutGroups K b))) := Fintype.ofFinite _ + let : Fintype (Vertex (vertexLinkGroups (cutGroups K (a+b)) (middleCut ha hb))) := Fintype.ofFinite _ + have hj := Join.topSpectral cut_rankBound cut_rankBound h0 hA hB + exact (singleLinkModel _ _).pushTopSpectral + ((cutProductLinkModel ha hb).pushTopSpectral + ((productModel (cutGroups K a) (cutGroups K b)).pullTopSpectral hj)) + +theorem cut_topSpectral [Fintype K] (N : ℕ) : + TopSpectral (TypedCosetFaces.complex (cutGroups K N)) (N-1) + (Real.sqrt (Fintype.card K : ℝ)/(Fintype.card K : ℝ)) := by + classical + induction N using Nat.strong_induction_on with | h N ih => + apply TopSpectral.vertexCriterion + · intro hbase + have hN : N = 3 := by omega + subst N + exact cut3_rayleigh + intro v hv + rcases v with ⟨c,v⟩ + induction v using Quotient.inductionOn with | h g => + have hstandard : TopSpectral (linkComplex (cutGroups K N) {c}) (N-1-1) + (Real.sqrt (Fintype.card K : ℝ)/(Fintype.card K : ℝ)) := by + rcases c with ⟨a,ha,haN⟩ + obtain ⟨b,hNb⟩ := Nat.exists_eq_add_of_le (Nat.le_of_lt haN) + subst N + have hb : 0 < b := by omega + have hbN : b < a+b := by omega + have hc := cut_middle_topSpectral ha hb (by positivity) + (ih a haN) (ih b hbN) + have he : (a-1)+(b-1) = a+b-1-1 := by omega + rwa [he] at hc + rw [standard_link_eq] at hstandard + have hm := (actionModel (cutGroups K N) g).linkModel {vertex (cutGroups K N) 1 c} + (standard_singleton_face _ _) + have hh := hm.pushTopSpectral hstandard + have he : (actionModel (cutGroups K N) g).vertex (vertex (cutGroups K N) 1 c) = + vertex (cutGroups K N) g c := by + change g • vertex (cutGroups K N) 1 c = _ + rw [smul_vertex,mul_one] + have hi : ({vertex (cutGroups K N) 1 c} : Finset _).image + (actionModel (cutGroups K N) g).vertex = {vertex (cutGroups K N) g c} := by + rw [Finset.image_singleton,he] + + rw [faceLink_congr _ hv hi] at hh + exact hh + +end CoboundaryExpanders.MatrixOpposition + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains Cone +open scoped Pointwise +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + [Fintype (Vertex H)] +lemma allVertexTopSpectral_of_standard {N : ℕ} {lam : ℝ} + (hs : ∀ i : I, TopSpectral (linkComplex H {i}) N lam) : + ∀ v : Vertex H, ∀ hv : {v} ∈ (complex H).faces, + TopSpectral ((complex H).faceLink {v} hv) N lam := by + rintro ⟨i,v⟩ hv + induction v using Quotient.inductionOn with | h g => + have hh := hs i + rw [standard_link_eq] at hh + have hh' := ((actionModel H g).linkModel {vertex H 1 i} (standard_singleton_face H i)).pushTopSpectral hh + have he : (actionModel H g).vertex (vertex H 1 i) = vertex H g i := by + change g • vertex H 1 i = _ + rw [smul_vertex,mul_one] + have hi : ({vertex H 1 i} : Finset _).image (actionModel H g).vertex = {vertex H g i} := by + rw [Finset.image_singleton,he] + rw [faceLink_congr _ hv hi] at hh' + exact hh' +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.Construction +open InfiniteChains Cone TypedCosetFaces SphericalOpposition.CompleteFlag MatrixOpposition +noncomputable local instance finiteFintype (A : Type) [Finite A] : Fintype A := Fintype.ofFinite A + +theorem actual_topSpectral (n : ℕ) (hn : 2 ≤ n) (p : ℕ) [Fact p.Prime] + (m : ℕ) (hm : 2 ≤ m) : + TopSpectral (TypedCosetFaces.complex (reducedLocalGroup p n (by omega) m)) (n+1) + (Real.sqrt (p:ℝ)/(p:ℝ)) := by + let : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + have hspherical := (cutSphericalModel (K:=ZMod p) (N:=n+1)).pushTopSpectral + (cut_topSpectral (K:=ZMod p) (n+1)) + have hspherical' : TopSpectral (stdFlag (ZMod p) (n+1)).complex n + (Real.sqrt (p:ℝ)/(p:ℝ)) := by + simpa only [Nat.add_sub_cancel,ZMod.card] using hspherical + apply TopSpectral.vertexCriterion + · omega + apply allVertexTopSpectral_of_standard + intro cut + have hc := (sphericalLinkModel p n (by omega) hm cut).pullTopSpectral hspherical' + have ha := (actualVertexLinkModel p n (by omega) m cut).pushTopSpectral hc + simpa only [Nat.add_sub_cancel] using ha +end CoboundaryExpanders.Construction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Links.lean b/lean/OAI/Combinatorics/Coboundary/Links.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b9b5ab7e9720e9cd88ac860e3a3a7664f23a0cf --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Links.lean @@ -0,0 +1,1047 @@ +import OAI.GroupTheory.Congruence.Basic +import OAI.GroupTheory.Congruence.Patterns +import OAI.Combinatorics.Coboundary.Joins + +namespace OAI + +/-! +Coset-link identifications, product and cut models, and all proper-link cone bounds. +-/ + +noncomputable section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix + +namespace CoboundaryExpanders.Construction + +section +open Patterns MatrixOpposition SphericalOpposition.CompleteFlag +open scoped Pointwise +variable (p n : ℕ) [Fact p.Prime] + +def localReducedHom (hn : 1 ≤ n) (m : ℕ) (cut : Fin (n+1)) : + localGroup p n hn cut →* reducedLocalGroup p n hn m cut where + toFun g := ⟨localQuotientMap p n hn m cut g, + ⟨⟨g.val,localGroup_le_U p n hn cut g.property⟩,g.property,rfl⟩⟩ + map_one' := by apply Subtype.ext; exact map_one _ + map_mul' g h := by apply Subtype.ext; exact map_mul _ g h + +lemma localReducedHom_surjective (hn : 1 ≤ n) (m : ℕ) (cut : Fin (n+1)) : + Function.Surjective (localReducedHom p n hn m cut) := by + rintro ⟨q,hq⟩ + obtain ⟨g,hg,hgq⟩ := hq + exact ⟨⟨g.val,hg⟩,Subtype.ext hgq⟩ + +lemma localQuotient_cross_injective (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) + (cut j : Fin (n+1)) (g : localGroup p n hn cut) (h : localGroup p n hn j) + (he : localQuotientMap p n hn m cut g = localQuotientMap p n hn m j h) : + g.val = h.val := by + apply localGroups_reduction_injective p n hn hm cut j g h + exact congrArg (fun q : Gquot p (n+1) m => + (QuotientGroup.quotientKerEquivRange (uReduction p (n+1) m) q).val) he + +lemma localReducedHom_injective (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) : + Function.Injective (localReducedHom p n hn m cut) := by + intro g h he + apply Subtype.ext + exact localQuotient_cross_injective p n hn hm cut cut g h (congrArg Subtype.val he) + +def localReducedEquiv (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) : + localGroup p n hn cut ≃* reducedLocalGroup p n hn m cut := + MulEquiv.ofBijective (localReducedHom p n hn m cut) + ⟨localReducedHom_injective p n hn hm cut,localReducedHom_surjective p n hn m cut⟩ + +lemma localReducedHom_mem_iff (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) + (cut j : Fin (n+1)) (g : localGroup p n hn cut) : + (localReducedHom p n hn m cut g).val ∈ reducedLocalGroup p n hn m j ↔ + g.val ∈ localGroup p n hn j := by + constructor + · rintro ⟨b,hb,he⟩ + have he' : localQuotientMap p n hn m j ⟨b.val,hb⟩ = + localQuotientMap p n hn m cut g := he + exact (localQuotient_cross_injective p n hn hm j cut ⟨b.val,hb⟩ g he') ▸ hb + · intro hg + exact ⟨⟨g.val,localGroup_le_U p n hn j hg⟩,hg,rfl⟩ + +def reducedFlagEquiv (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) : + reducedLocalGroup p n hn m cut ≃* + (stdFlag (ZMod p) (n+1)).unipotentFlagStabilizer := + (localReducedEquiv p n hn hm cut).symm.trans (localFlagEquiv p n hn cut) + +lemma reducedFlagEquiv_stabilizer (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) + (cut j : Fin (n+1)) (q : reducedLocalGroup p n hn m cut) : + (reducedFlagEquiv p n hn hm cut q).val ∈ + MulAction.stabilizer ((Fin (n+1) → ZMod p) ≃ₗ[ZMod p] (Fin (n+1) → ZMod p)) + ((oppFlag (ZMod p) (n+1)).space ⟨n+1-(cutOrder cut j).val,by omega⟩) ↔ + q.val ∈ reducedLocalGroup p n hn m j := by + change (localFlagEquiv p n hn cut ((localReducedEquiv p n hn hm cut).symm q)).val ∈ _ ↔ _ + rw [localFlagEquiv_stabilizer] + have he : (localReducedHom p n hn m cut ((localReducedEquiv p n hn hm cut).symm q)).val = q.val := + congrArg Subtype.val ((localReducedEquiv p n hn hm cut).apply_symm_apply q) + exact (localReducedHom_mem_iff p n hn hm cut j + ((localReducedEquiv p n hn hm cut).symm q)).symm.trans (by rw [he]) + +end + +section +open Patterns MatrixOpposition TypedCosetFaces SphericalOpposition.CompleteFlag +open scoped Pointwise +variable (p n : ℕ) [Fact p.Prime] + +def quotientLinkGroups (hn : 1 ≤ n) (m : ℕ) (cut : Fin (n+1)) + (j : {j : Fin (n+1) // j ≠ cut}) : Subgroup (reducedLocalGroup p n hn m cut) := + (reducedLocalGroup p n hn m j.val).comap (reducedLocalGroup p n hn m cut).subtype + +lemma quotientLinkGroups_correspond (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) + (cut : Fin (n+1)) (j : {j : Fin (n+1) // j ≠ cut}) + (q : reducedLocalGroup p n hn m cut) : + q ∈ quotientLinkGroups p n hn m cut j ↔ + reducedFlagEquiv p n hn hm cut q ∈ + (stdFlag (ZMod p) (n+1)).vertexStabilizers (oppFlag (ZMod p) (n+1)) + (localTypeEquiv cut j) := by + change q.val ∈ reducedLocalGroup p n hn m j.val ↔ + reducedFlagEquiv p n hn hm cut q ∈ MulAction.stabilizer _ + ((oppFlag (ZMod p) (n+1)).baseSpace (localTypeEquiv cut j)) + have hr : properIndex (N:=n+1) (localTypeEquiv cut j) = + (⟨n+1-(cutOrder cut j.val).val,by omega⟩ : Fin (n+2)) := + Fin.ext (localTypeEquiv_rank cut j) + rw [baseSpace,hr] + rw [MulAction.mem_stabilizer_iff] + change q.val ∈ reducedLocalGroup p n hn m j.val ↔ + (reducedFlagEquiv p n hn hm cut q).val • + (oppFlag (ZMod p) (n+1)).space ⟨n+1-(cutOrder cut j.val).val,by omega⟩ = + (oppFlag (ZMod p) (n+1)).space ⟨n+1-(cutOrder cut j.val).val,by omega⟩ + exact (reducedFlagEquiv_stabilizer p n hn hm cut j.val q).symm + +def quotientLinkVertexModel (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) : + Vertex (quotientLinkGroups p n hn m cut) → Submodule (ZMod p) (Fin (n+1) → ZMod p) := + ((stdFlag (ZMod p) (n+1)).cosetVertexMap (oppFlag (ZMod p) (n+1))) ∘ + isoVertex (quotientLinkGroups p n hn m cut) + ((stdFlag (ZMod p) (n+1)).vertexStabilizers (oppFlag (ZMod p) (n+1))) + (reducedFlagEquiv p n hn hm cut) (localTypeEquiv cut) + (quotientLinkGroups_correspond p n hn hm cut) + +lemma quotientLinkVertexModel_injective (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) : + Function.Injective (quotientLinkVertexModel p n hn hm cut) := + ((stdFlag (ZMod p) (n+1)).cosetVertexMap_injective (oppFlag (ZMod p) (n+1))).comp + (isoVertex_injective _ _ _ _ _) + +theorem quotientLinkFace_iff (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) + (s : Finset (Vertex (quotientLinkGroups p n hn m cut))) : + IsFace (quotientLinkGroups p n hn m cut) s ↔ + s.image (quotientLinkVertexModel p n hn hm cut) ∈ + (stdFlag (ZMod p) (n+1)).complex.faces := by + unfold quotientLinkVertexModel + rw [← Finset.image_image,← cosetFace_iff stdFlags_opposite,isoFace_iff] + +theorem quotientLinkFace_surjective (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) + (s : Finset (Submodule (ZMod p) (Fin (n+1) → ZMod p))) + (hs : s ∈ (stdFlag (ZMod p) (n+1)).complex.faces) : + ∃ t : Finset (Vertex (quotientLinkGroups p n hn m cut)), + IsFace (quotientLinkGroups p n hn m cut) t ∧ + t.image (quotientLinkVertexModel p n hn hm cut) = s := by + obtain ⟨g,A,hg⟩ := opposedFace_coset stdFlags_opposite s hs + let e := reducedFlagEquiv p n hn hm cut + let r := localTypeEquiv cut + refine ⟨face (quotientLinkGroups p n hn m cut) (e.symm g) (A.image r.symm),⟨_,_,rfl⟩,?_⟩ + unfold quotientLinkVertexModel + rw [← Finset.image_image,isoFace_image,e.apply_symm_apply] + have hi : (A.image r.symm).image r = A := by ext j; simp + rw [hi] + exact hg + +def actualLinkEmbedding (hn : 1 ≤ n) (m : ℕ) (cut : Fin (n+1)) : + Vertex (quotientLinkGroups p n hn m cut) → Vertex (reducedLocalGroup p n hn m) := + vertexLinkEmbedding (reducedLocalGroup p n hn m) cut + +lemma actualLinkEmbedding_injective (hn : 1 ≤ n) (m : ℕ) (cut : Fin (n+1)) : + Function.Injective (actualLinkEmbedding p n hn m cut) := + vertexLinkEmbedding_injective _ _ + +theorem actualLinkFace_iff (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) + (s : Finset (Vertex (quotientLinkGroups p n hn m cut))) : + IsLinkFace (reducedLocalGroup p n hn m) {cut} + (s.image (actualLinkEmbedding p n hn m cut)) ↔ + s.image (quotientLinkVertexModel p n hn hm cut) ∈ + (stdFlag (ZMod p) (n+1)).complex.faces := by + exact (vertexLinkFace_iff (reducedLocalGroup p n hn m) cut s).symm.trans + (quotientLinkFace_iff p n hn hm cut s) + +lemma actualLinkFace_surjective (hn : 1 ≤ n) (m : ℕ) (cut : Fin (n+1)) + (s : Finset (Vertex (reducedLocalGroup p n hn m))) + (hs : IsLinkFace (reducedLocalGroup p n hn m) {cut} s) : + ∃ t : Finset (Vertex (quotientLinkGroups p n hn m cut)), + IsFace (quotientLinkGroups p n hn m cut) t ∧ + t.image (actualLinkEmbedding p n hn m cut) = s := + vertexLinkFace_surjective _ _ _ hs + +end + +open InfiniteChains InfiniteChains.Cone TypedCosetFaces SphericalOpposition.CompleteFlag +open Patterns MatrixOpposition +variable (p n : ℕ) [Fact p.Prime] + +def sphericalLinkModel (hn : 1 ≤ n) {m : ℕ} (hm : 2 ≤ m) (cut : Fin (n+1)) : + FaceModel (TypedCosetFaces.complex (quotientLinkGroups p n hn m cut)) + (stdFlag (ZMod p) (n+1)).complex where + vertex := quotientLinkVertexModel p n hn hm cut + injective := quotientLinkVertexModel_injective p n hn hm cut + face_iff := fun s => (quotientLinkFace_iff p n hn hm cut s).symm + cover := fun t ht => quotientLinkFace_surjective p n hn hm cut t ht + +def actualVertexLinkModel (hn : 1 ≤ n) (m : ℕ) (cut : Fin (n+1)) : + FaceModel (TypedCosetFaces.complex (quotientLinkGroups p n hn m cut)) + (linkComplex (reducedLocalGroup p n hn m) {cut}) where + vertex := actualLinkEmbedding p n hn m cut + injective := actualLinkEmbedding_injective p n hn m cut + face_iff := fun s => (vertexLinkFace_iff (reducedLocalGroup p n hn m) cut s).symm + cover := fun t ht => actualLinkFace_surjective p n hn m cut t ht + +theorem uniform_actual_vertex_cones (n : ℕ) (hn : 1 ≤ n) : + ∃ Q R : ℕ, ∀ p : ℕ, ∀ _ : Fact p.Prime, Q < p → + ∀ m : ℕ, 2 ≤ m → ∀ cut : Fin (n+1), + Nonempty (BoundedCone (linkComplex (reducedLocalGroup p n hn m) {cut}) (n-1) R) := by + obtain ⟨Q,R,h⟩ := exists_uniform_cones (n-1) + refine ⟨Q,R,?_⟩ + intro p hp hq m hm cut + have hc := h (ZMod p) (Fin (n+1) → ZMod p) (n+1) (stdFlag (ZMod p) (n+1)) (by omega) + (by simpa only [ZMod.card] using hq) + exact ⟨(actualVertexLinkModel p n hn m cut).pushCone + ((sphericalLinkModel p n hn hm cut).pullCone hc.some)⟩ + +end CoboundaryExpanders.Construction + +namespace CoboundaryExpanders.InfiniteChains +namespace Complex +variable {V : Type} [DecidableEq V] (X : CoboundaryExpanders.InfiniteChains.Complex V) + +def faceLink (s : Finset V) (hs : s ∈ X.faces) : CoboundaryExpanders.InfiniteChains.Complex V where + faces := {a | Disjoint s a ∧ s ∪ a ∈ X.faces} + empty_mem := ⟨Finset.disjoint_empty_right _,by simpa using hs⟩ + downward := by + intro a b ha hb + exact ⟨Finset.disjoint_left.mpr (fun v hv hv' => Finset.disjoint_left.mp ha.1 hv (hb hv')), + X.downward ha.2 (Finset.union_subset_union (Finset.Subset.refl _) hb)⟩ + +end Complex + +open Cone +variable {V W : Type} [DecidableEq V] [DecidableEq W] +attribute [local instance] Classical.propDecidable + +namespace Cone.FaceModel +variable {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + +def linkModel (s : Finset V) (hs : s ∈ X.faces) : + FaceModel (X.faceLink s hs) (Y.faceLink (s.image M.vertex) ((M.face_iff s).mpr hs)) where + vertex := M.vertex + injective := M.injective + face_iff := by + intro a + change Disjoint (s.image M.vertex) (a.image M.vertex) ∧ + s.image M.vertex ∪ a.image M.vertex ∈ Y.faces ↔ + Disjoint s a ∧ s ∪ a ∈ X.faces + rw [←Finset.image_union,M.face_iff,Finset.disjoint_image M.injective] + cover := by + intro t ht + obtain ⟨a,ha,he⟩ := M.cover t (Y.downward ht.2 Finset.subset_union_right) + refine ⟨a,⟨?_,?_⟩,he⟩ + · rw [←Finset.disjoint_image M.injective,he] + exact ht.1 + · apply (M.face_iff _).mp + rw [Finset.image_union,he] + exact ht.2 + +end Cone.FaceModel + +omit [DecidableEq V] in +lemma complex_eq {X Y : CoboundaryExpanders.InfiniteChains.Complex V} (h : X.faces = Y.faces) : X = Y := by + cases X; cases Y; cases h; rfl + +lemma faceLink_empty (X : CoboundaryExpanders.InfiniteChains.Complex V) : X.faceLink ∅ X.empty_mem = X := by + apply complex_eq + ext s + simp [Complex.faceLink] + +lemma faceLink_iterated (X : CoboundaryExpanders.InfiniteChains.Complex V) {s a : Finset V} (hs : s ∈ X.faces) + (ha : a ∈ (X.faceLink s hs).faces) : + (X.faceLink s hs).faceLink a ha = X.faceLink (s∪a) ha.2 := by + apply complex_eq + ext t + change (Disjoint a t ∧ Disjoint s (a∪t) ∧ s∪(a∪t) ∈ X.faces) ↔ + (Disjoint (s∪a) t ∧ (s∪a)∪t ∈ X.faces) + simp only [Finset.disjoint_union_left,Finset.disjoint_union_right,ha.1,true_and,Finset.union_assoc] + tauto + +namespace Join + +omit [DecidableEq V] [DecidableEq W] in +lemma mem_link_left {X : CoboundaryExpanders.InfiniteChains.Complex W} {Y : CoboundaryExpanders.InfiniteChains.Complex V} {s : Finset (W ⊕ V)} + (hs : s ∈ (complex X Y).faces) : s.toLeft ∈ X.faces := hs.1 +omit [DecidableEq V] [DecidableEq W] in +lemma mem_link_right {X : CoboundaryExpanders.InfiniteChains.Complex W} {Y : CoboundaryExpanders.InfiniteChains.Complex V} {s : Finset (W ⊕ V)} + (hs : s ∈ (complex X Y).faces) : s.toRight ∈ Y.faces := hs.2 + +omit [DecidableEq V] [DecidableEq W] in +lemma disjoint_split (s t : Finset (W ⊕ V)) : + Disjoint s t ↔ Disjoint s.toLeft t.toLeft ∧ Disjoint s.toRight t.toRight := by + rw [Finset.disjoint_left,Finset.disjoint_left,Finset.disjoint_left] + constructor + · intro h + constructor + · intro v hv hv'; exact h (by simpa using hv) (by simpa using hv') + · intro v hv hv'; exact h (by simpa using hv) (by simpa using hv') + · rintro ⟨hL,hR⟩ (v|v) hv hv' + · exact hL (by simpa using hv) (by simpa using hv') + · exact hR (by simpa using hv) (by simpa using hv') + +lemma link_eq {X : CoboundaryExpanders.InfiniteChains.Complex W} {Y : CoboundaryExpanders.InfiniteChains.Complex V} {s : Finset (W ⊕ V)} + (hs : s ∈ (complex X Y).faces) : + (complex X Y).faceLink s hs = + complex (X.faceLink s.toLeft hs.1) (Y.faceLink s.toRight hs.2) := by + apply complex_eq + ext t + change (Disjoint s t ∧ (s∪t).toLeft ∈ X.faces ∧ (s∪t).toRight ∈ Y.faces) ↔ + (Disjoint s.toLeft t.toLeft ∧ s.toLeft∪t.toLeft ∈ X.faces) ∧ + (Disjoint s.toRight t.toRight ∧ s.toRight∪t.toRight ∈ Y.faces) + rw [disjoint_split,Finset.toLeft_union,Finset.toRight_union] + tauto + +def emptyLeftModel {X : CoboundaryExpanders.InfiniteChains.Complex W} {Y : CoboundaryExpanders.InfiniteChains.Complex V} + (hX : ∀ s ∈ X.faces, s = ∅) : FaceModel Y (complex X Y) where + vertex := Sum.inr + injective := Sum.inr_injective + face_iff := by + intro s + change (s.image Sum.inr).toLeft ∈ X.faces ∧ (s.image Sum.inr).toRight ∈ Y.faces ↔ _ + have hL : (s.image (Sum.inr : V → W ⊕ V)).toLeft = ∅ := by ext a; simp + have hR : (s.image (Sum.inr : V → W ⊕ V)).toRight = s := by ext a; simp + rw [hL,hR] + simp only [X.empty_mem,true_and] + cover := by + intro t ht + refine ⟨t.toRight,ht.2,?_⟩ + have he := Finset.toLeft_disjSum_toRight (u:=t) + rw [hX t.toLeft ht.1] at he + rw [Finset.empty_disjSum,Finset.map_eq_image] at he + exact he + +end Join +end CoboundaryExpanders.InfiniteChains + +namespace CoboundaryExpanders.TypedCosetFaces +variable {G K I J : Type} [Group G] [Group K] [DecidableEq I] [DecidableEq J] + (H : I → Subgroup G) (L : J → Subgroup K) + +def productGroups : I ⊕ J → Subgroup (G × K) + | Sum.inl i => (H i).prod ⊤ + | Sum.inr j => (⊤ : Subgroup G).prod (L j) + +def productVertex : Vertex (productGroups H L) → Vertex H ⊕ Vertex L + | ⟨Sum.inl i,q⟩ => Quotient.lift (fun g : G × K => Sum.inl (vertex H g.1 i)) (by + intro g h hgh + apply congrArg Sum.inl + refine Sigma.ext (by rfl) (heq_of_eq ?_) + apply Quotient.sound + exact QuotientGroup.leftRel_apply.mpr (QuotientGroup.leftRel_apply.mp hgh).1) q + | ⟨Sum.inr j,q⟩ => Quotient.lift (fun g : G × K => Sum.inr (vertex L g.2 j)) (by + intro g h hgh + apply congrArg Sum.inr + refine Sigma.ext (by rfl) (heq_of_eq ?_) + apply Quotient.sound + exact QuotientGroup.leftRel_apply.mpr (QuotientGroup.leftRel_apply.mp hgh).2) q + +omit [DecidableEq I] [DecidableEq J] in +@[simp] lemma productVertex_left (g : G × K) (i : I) : + productVertex H L (vertex (productGroups H L) g (Sum.inl i)) = Sum.inl (vertex H g.1 i) := rfl +omit [DecidableEq I] [DecidableEq J] in +@[simp] lemma productVertex_right (g : G × K) (j : J) : + productVertex H L (vertex (productGroups H L) g (Sum.inr j)) = Sum.inr (vertex L g.2 j) := rfl + +def embedLeft : Vertex H → Vertex (productGroups H L) + | ⟨i,q⟩ => Quotient.lift (fun g : G => vertex (productGroups H L) (g,1) (Sum.inl i)) (by + intro g h hgh + refine Sigma.ext (by rfl) (heq_of_eq ?_) + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + exact ⟨QuotientGroup.leftRel_apply.mp hgh,Subgroup.mem_top _⟩) q + +def embedRight : Vertex L → Vertex (productGroups H L) + | ⟨j,q⟩ => Quotient.lift (fun g : K => vertex (productGroups H L) (1,g) (Sum.inr j)) (by + intro g h hgh + refine Sigma.ext (by rfl) (heq_of_eq ?_) + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + exact ⟨Subgroup.mem_top _,QuotientGroup.leftRel_apply.mp hgh⟩) q + +def productVertexEquiv : Vertex (productGroups H L) ≃ Vertex H ⊕ Vertex L where + toFun := productVertex H L + invFun := Sum.elim (embedLeft H L) (embedRight H L) + left_inv := by + rintro ⟨i,q⟩ + cases i with + | inl i => + induction q using Quotient.inductionOn with | h g => + refine Sigma.ext (by rfl) (heq_of_eq ?_) + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + change g.1⁻¹*g.1 ∈ H i ∧ _ + simp + | inr j => + induction q using Quotient.inductionOn with | h g => + refine Sigma.ext (by rfl) (heq_of_eq ?_) + apply Quotient.sound + apply QuotientGroup.leftRel_apply.mpr + change _ ∧ g.2⁻¹*g.2 ∈ L j + simp + right_inv := by + intro x + cases x with + | inl x => + rcases x with ⟨i,q⟩ + induction q using Quotient.inductionOn with | h g => rfl + | inr x => + rcases x with ⟨j,q⟩ + induction q using Quotient.inductionOn with | h g => rfl + +lemma productFace_image (g : G) (k : K) (A : Finset I) (B : Finset J) : + (face (productGroups H L) (g,k) (A.image Sum.inl ∪ B.image Sum.inr)).image + (productVertex H L) = (face H g A).image Sum.inl ∪ (face L k B).image Sum.inr := by + simp only [face,Finset.image_union,Finset.image_image,Function.comp_def, + productVertex_left,productVertex_right] + +lemma productFace_image_general (g : G × K) (A : Finset (I ⊕ J)) : + ∃ (B : Finset I) (C : Finset J), + (face (productGroups H L) g A).image (productVertex H L) = + (face H g.1 B).image Sum.inl ∪ (face L g.2 C).image Sum.inr := by + refine ⟨A.toLeft,A.toRight,?_⟩ + have he : A.toLeft.image Sum.inl ∪ A.toRight.image Sum.inr = A := by ext x; cases x <;> simp + calc + _ = (face (productGroups H L) g (A.toLeft.image Sum.inl ∪ A.toRight.image Sum.inr)).image (productVertex H L) := by rw [he] + _ = _ := productFace_image H L g.1 g.2 A.toLeft A.toRight + +theorem productFace_iff (s : Finset (Vertex (productGroups H L))) : + IsFace (productGroups H L) s ↔ ∃ (sL : Finset (Vertex H)) (sR : Finset (Vertex L)), + IsFace H sL ∧ IsFace L sR ∧ + s.image (productVertex H L) = sL.image Sum.inl ∪ sR.image Sum.inr := by + constructor + · rintro ⟨g,A,rfl⟩ + obtain ⟨B,C,h⟩ := productFace_image_general H L g A + exact ⟨face H g.1 B,face L g.2 C,⟨_,_,rfl⟩,⟨_,_,rfl⟩,h⟩ + · rintro ⟨sL,sR,⟨g,A,rfl⟩,⟨k,B,rfl⟩,he⟩ + refine ⟨(g,k),A.image Sum.inl ∪ B.image Sum.inr,?_⟩ + apply Finset.image_injective (productVertexEquiv H L).injective + exact (productFace_image H L g k A B).trans he.symm + +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.InfiniteChains.Cone.FaceModel +variable {V W Z : Type} [DecidableEq V] [DecidableEq W] [DecidableEq Z] +variable {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} {T : CoboundaryExpanders.InfiniteChains.Complex Z} +def trans (M : FaceModel X Y) (L : FaceModel Y T) : FaceModel X T where + vertex := L.vertex ∘ M.vertex + injective := L.injective.comp M.injective + face_iff := by intro s; rw [←Finset.image_image,L.face_iff,M.face_iff] + cover := by + intro t ht + obtain ⟨b,hb,he⟩ := L.cover t ht + obtain ⟨a,ha,hf⟩ := M.cover b hb + exact ⟨a,ha,by rw [←Finset.image_image,hf,he]⟩ +end CoboundaryExpanders.InfiniteChains.Cone.FaceModel + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains Cone +variable {G G' I I' : Type} [Group G] [Group G'] [DecidableEq I] [DecidableEq I'] +variable (H : I → Subgroup G) (H' : I' → Subgroup G') +variable (e : G ≃* G') (r : I ≃ I') (he : ∀ i g, g ∈ H i ↔ e g ∈ H' (r i)) + +def isoModel : FaceModel (complex H) (complex H') where + vertex := isoVertex H H' e r he + injective := isoVertex_injective H H' e r he + face_iff := isoFace_iff H H' e r he + cover := by + intro t ht + let a := t.image (vertexEquiv H H' e r he).symm + have ha : a.image (isoVertex H H' e r he) = t := by + change a.image (vertexEquiv H H' e r he) = t + simp only [a,Finset.image_image,Function.comp_def,Equiv.apply_symm_apply,Finset.image_id'] + exact ⟨a,(isoFace_iff H H' e r he a).mp (by rwa [ha]),ha⟩ + +variable {K J : Type} [Group K] [DecidableEq J] (L : J → Subgroup K) +def productModel : FaceModel (complex (productGroups H L)) (Join.complex (complex H) (complex L)) where + vertex := productVertex H L + injective := (productVertexEquiv H L).injective + face_iff := by + intro s + change IsFace H (s.image (productVertex H L)).toLeft ∧ + IsFace L (s.image (productVertex H L)).toRight ↔ IsFace (productGroups H L) s + rw [productFace_iff] + constructor + · rintro ⟨hL,hR⟩ + refine ⟨_,_,hL,hR,?_⟩ + ext v + cases v <;> simp + · rintro ⟨a,b,ha,hb,he⟩ + rw [he] + have hL : (a.image (Sum.inl : Vertex H → Vertex H ⊕ Vertex L) ∪ b.image Sum.inr).toLeft = a := by ext v; simp + have hR : (a.image (Sum.inl : Vertex H → Vertex H ⊕ Vertex L) ∪ b.image Sum.inr).toRight = b := by ext v; simp + exact ⟨by rwa [hL],by rwa [hR]⟩ + cover := by + intro t ht + let s := t.image (productVertexEquiv H L).symm + have he : s.image (productVertex H L) = t := by + change s.image (productVertexEquiv H L) = t + simp only [s,Finset.image_image,Function.comp_def,Equiv.apply_symm_apply,Finset.image_id'] + refine ⟨s,(productFace_iff H L s).mpr ⟨t.toLeft,t.toRight,ht.1,ht.2,?_⟩,he⟩ + rw [he] + ext v + cases v <;> simp +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.MatrixOpposition +open SphericalOpposition SphericalOpposition.CompleteFlag TypedCosetFaces InfiniteChains Cone +open scoped Pointwise +variable {K : Type} [Field K] {N : ℕ} + +instance cutDecidableEq : DecidableEq (Cut N) := Classical.decEq _ +instance cutFinite : Finite (Cut N) := Finite.of_injective (fun c : Cut N => (⟨c.val,c.property.2⟩ : Fin N)) + (fun _ _ h => Subtype.ext (congrArg Fin.val h)) +noncomputable instance cutFintype : Fintype (Cut N) := Fintype.ofFinite _ + +def cutTypeEquiv : Cut N ≃ Fin (N-1) where + toFun c := ⟨N-c.val-1,by have h:=c.property; omega⟩ + invFun i := ⟨N-i.val-1,by have h:=i.isLt; omega⟩ + left_inv c := by apply Subtype.ext; have h:=c.property; dsimp; omega + right_inv i := by apply Fin.ext; have h:=i.isLt; dsimp; omega + +lemma cutGroups_correspond (c : Cut N) (g : upperGroup K N) : + upperFlagEquiv g ∈ (stdFlag K N).vertexStabilizers (oppFlag K N) (cutTypeEquiv c) ↔ + g ∈ cutGroups K N c := by + change upperFlagEquiv g • (oppFlag K N).baseSpace (cutTypeEquiv c) = _ ↔ _ + have he : properIndex (N:=N) (cutTypeEquiv c) = (⟨N-c.val,by have h:=c.property; omega⟩:Fin (N+1)) := by + apply Fin.ext + have h:=c.property + dsimp [properIndex,cutTypeEquiv] + omega + unfold baseSpace + rw [he] + rfl + +def cutSphericalModel : FaceModel (TypedCosetFaces.complex (cutGroups K N)) (stdFlag K N).complex := + (isoModel (cutGroups K N) ((stdFlag K N).vertexStabilizers (oppFlag K N)) + upperFlagEquiv cutTypeEquiv (fun c g => (cutGroups_correspond c g).symm)).trans + { vertex := (stdFlag K N).cosetVertexMap (oppFlag K N) + injective := (stdFlag K N).cosetVertexMap_injective (oppFlag K N) + face_iff := fun s => (cosetFace_iff stdFlags_opposite s).symm + cover := fun s hs => by + obtain ⟨g,A,he⟩ := opposedFace_coset stdFlags_opposite s hs + exact ⟨_,⟨g,A,rfl⟩,he⟩ } + +end CoboundaryExpanders.MatrixOpposition + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains Cone +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +lemma standard_face_mem (A : Finset I) : face H 1 A ∈ (complex H).faces := ⟨1,A,rfl⟩ +lemma linkComplex_eq (A : Finset I) : linkComplex H A = + (complex H).faceLink (face H 1 A) (standard_face_mem H A) := by + apply InfiniteChains.complex_eq + ext t + change Disjoint t (face H 1 A) ∧ IsFace H (t ∪ face H 1 A) ↔ + Disjoint (face H 1 A) t ∧ IsFace H (face H 1 A ∪ t) + rw [disjoint_comm,Finset.union_comm] + +def singleLinkModel (i : I) : + FaceModel (complex (vertexLinkGroups H i)) (linkComplex H {i}) where + vertex := vertexLinkEmbedding H i + injective := vertexLinkEmbedding_injective H i + face_iff := fun s => (vertexLinkFace_iff H i s).symm + cover := fun t ht => vertexLinkFace_surjective H i t ht +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.MatrixOpposition +open SphericalOpposition SphericalOpposition.CompleteFlag TypedCosetFaces InfiniteChains Cone +variable {K : Type} [Field K] {a b : ℕ} + +def middleCut (ha : 0 < a) (hb : 0 < b) : Cut (a+b) := ⟨a,ha,by omega⟩ +def cutLinkTypes (ha : 0 < a) (hb : 0 < b) : Cut a ⊕ Cut b ≃ + {c : Cut (a+b) // c ≠ middleCut ha hb} := cutSplitEquiv.trans + { toFun := fun c => ⟨c.val,fun h => c.property (congrArg Subtype.val h)⟩ + invFun := fun c => ⟨c.val,fun h => c.property (Subtype.ext h)⟩ + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + +lemma cutLinkGroups_correspond (ha : 0 < a) (hb : 0 < b) (c : Cut a ⊕ Cut b) + (g : upperGroup K a × upperGroup K b) : + g ∈ productGroups (cutGroups K a) (cutGroups K b) c ↔ + blockSuffixEquiv g ∈ vertexLinkGroups (cutGroups K (a+b)) (middleCut ha hb) (cutLinkTypes ha hb c) := by + have h := (blockSuffix_system g c).symm + cases c with + | inl c => + change (g.1 ∈ cutGroups K a c ∧ True) ↔ + (blockSuffixEquiv g).val ∈ cutGroups K (a+b) (cutSplitEquiv (Sum.inl c)).val + rw [and_true] + exact h + | inr c => + change (True ∧ g.2 ∈ cutGroups K b c) ↔ + (blockSuffixEquiv g).val ∈ cutGroups K (a+b) (cutSplitEquiv (Sum.inr c)).val + rw [true_and] + exact h + +def cutProductLinkModel (ha : 0 < a) (hb : 0 < b) : + FaceModel (TypedCosetFaces.complex (productGroups (cutGroups K a) (cutGroups K b))) + (TypedCosetFaces.complex (vertexLinkGroups (cutGroups K (a+b)) (middleCut ha hb))) := + isoModel _ _ blockSuffixEquiv (cutLinkTypes ha hb) (cutLinkGroups_correspond ha hb) + +end CoboundaryExpanders.MatrixOpposition + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains Cone +open scoped Pointwise +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +instance vertexAction : MulAction G (Vertex H) where + smul g v := ⟨v.1,g • v.2⟩ + one_smul v := by rcases v with ⟨i,v⟩; exact congrArg (Sigma.mk i) (one_smul G v) + mul_smul g h v := by rcases v with ⟨i,v⟩; exact congrArg (Sigma.mk i) (mul_smul g h v) + +omit [DecidableEq I] in +@[simp] lemma smul_vertex (g h : G) (i : I) : g • vertex H h i = vertex H (g*h) i := rfl + +omit [DecidableEq I] in +@[simp] lemma smul_face (g h : G) (A : Finset I) : g • face H h A = face H (g*h) A := by + simp only [Finset.smul_finset_def,face,Finset.image_image,Function.comp_def,smul_vertex] + +omit [DecidableEq I] in +lemma IsFace.smul {s : Finset (Vertex H)} (hs : IsFace H s) (g : G) : IsFace H (g • s) := by + obtain ⟨h,A,rfl⟩ := hs + rw [smul_face] + exact ⟨g*h,A,rfl⟩ + +lemma IsFace.type_card {s : Finset (Vertex H)} (hs : IsFace H s) : (types H s).card = s.card := by + obtain ⟨g,A,rfl⟩ := hs + rw [types_face,face_card] + +omit [DecidableEq I] in +lemma coset_pure [Fintype I] : + (∃ t, IsFace H t ∧ t.card = Fintype.card I) ∧ + ∀ s, IsFace H s → ∃ t, IsFace H t ∧ t.card = Fintype.card I ∧ s ⊆ t := by + constructor + · exact ⟨face H 1 Finset.univ,⟨1,_,rfl⟩,by simp⟩ + · rintro s ⟨g,A,rfl⟩ + exact ⟨face H g Finset.univ,⟨g,_,rfl⟩,by simp,Finset.image_mono _ (Finset.subset_univ _)⟩ + +omit [DecidableEq I] in +lemma chamber_transitive [Fintype I] {s t : Finset (Vertex H)} + (hs : IsFace H s) (ht : IsFace H t) (hsc : s.card = Fintype.card I) (htc : t.card = Fintype.card I) : + ∃ g : G, g • s = t := by + obtain ⟨g,A,rfl⟩ := hs + obtain ⟨h,B,rfl⟩ := ht + have ha : A = Finset.univ := Finset.eq_univ_of_card A (by simpa using hsc) + have hb : B = Finset.univ := Finset.eq_univ_of_card B (by simpa using htc) + subst A; subst B + exact ⟨h*g⁻¹,by simp [mul_assoc]⟩ + +omit [DecidableEq I] in +lemma stabilizer_fixes (A : Finset I) (g : stabilizer H A) : + (g.val : G) • face H 1 A = face H 1 A := by + rw [smul_face,mul_one] + apply (face_eq_iff H _ _ _).mpr + simp + +lemma remaining_card [Fintype I] (A : Finset I) : + Fintype.card (Remaining A) = Fintype.card I - A.card := by + simpa only [Remaining,Fintype.card_coe] using Fintype.card_subtype_compl (fun i : I => i ∈ A) + +omit [DecidableEq I] in +lemma linkFace_smul (A : Finset I) {s : Finset (Vertex H)} (hs : IsLinkFace H A s) + (g : stabilizer H A) : IsLinkFace H A (g.val • s) := by + constructor + · rw [←stabilizer_fixes H A g] + simp only [Finset.smul_finset_def] + exact (Finset.disjoint_image (f:=fun v : Vertex H => (g.val:G) • v) + (MulAction.injective (β:=Vertex H) (g.val:G))).mpr hs.1 + · have hh := hs.2.smul H g.val + simpa only [Finset.smul_finset_union,stabilizer_fixes H A g] using hh + +lemma link_chamber_transitive [Fintype I] (A : Finset I) {s t : Finset (Vertex H)} + (hs : IsLinkFace H A s) (ht : IsLinkFace H A t) + (hsc : s.card = Fintype.card I - A.card) (htc : t.card = Fintype.card I - A.card) : + ∃ g : stabilizer H A, g.val • s = t := by + obtain ⟨g,B,hg⟩ := (isLinkFace_iff H A s).mp hs + obtain ⟨h,C,hh⟩ := (isLinkFace_iff H A t).mp ht + have hB : B = Finset.univ := by + apply Finset.eq_univ_of_card + rw [remaining_card] + rw [←hg,Finset.card_image_of_injective _ (linkVertex_injective H A),face_card] at hsc + exact hsc + have hC : C = Finset.univ := by + apply Finset.eq_univ_of_card + rw [remaining_card] + rw [←hh,Finset.card_image_of_injective _ (linkVertex_injective H A),face_card] at htc + exact htc + subst B; subst C + refine ⟨h*g⁻¹,?_⟩ + rw [←hg,←hh,linkFace_image,linkFace_image,smul_face] + congr 1 + simp + +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.InfiniteChains + +section +open Cone +variable {V W : Type} [DecidableEq V] [DecidableEq W] + +namespace Cone.BoundedCone +variable {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R : ℕ} +def weaken (H : BoundedCone X n R) {m S : ℕ} (hm : m ≤ n) (hS : R ≤ S) : BoundedCone X m S where + hom := H.hom + support := fun s hs hn => H.support s hs (hn.trans hm) + contraction := fun s hs hn => H.contraction s hs (hn.trans hm) + bound := fun s hs hn => (H.bound s hs (hn.trans hm)).trans hS +end Cone.BoundedCone + +def RankBound (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) : Prop := ∀ s ∈ X.faces, s.card ≤ N + +def AllLinkCones (X : CoboundaryExpanders.InfiniteChains.Complex V) (N R : ℕ) : Prop := + ∀ s : Finset V, ∀ hs : s ∈ X.faces, s.card < N → + Nonempty (BoundedCone (X.faceLink s hs) (N-s.card-1) R) + +lemma RankBound.link {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} (hX : RankBound X N) + {s : Finset V} (hs : s ∈ X.faces) : RankBound (X.faceLink s hs) (N-s.card) := by + intro a ha + have h := hX (s∪a) ha.2 + rw [Finset.card_union_of_disjoint ha.1] at h + omega + +lemma RankBound.terminal {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} (hX : RankBound X N) + {s : Finset V} (hs : s ∈ X.faces) (hN : s.card = N) : + ∀ a ∈ (X.faceLink s hs).faces, a = ∅ := by + intro a ha + have h := hX.link hs a ha + rw [hN,Nat.sub_self] at h + exact Finset.card_eq_zero.mp (Nat.eq_zero_of_le_zero h) + +lemma AllLinkCones.weaken {X : CoboundaryExpanders.InfiniteChains.Complex V} {N R S : ℕ} (h : AllLinkCones X N R) (hS : R ≤ S) : + AllLinkCones X N S := by + intro s hs hn + exact ⟨(h s hs hn).some.weaken le_rfl hS⟩ + +lemma Cone.FaceModel.pushAllLinks {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + {N R : ℕ} (h : AllLinkCones X N R) : AllLinkCones Y N R := by + intro t ht hn + obtain ⟨s,hs,rfl⟩ := M.cover t ht + rw [Finset.card_image_of_injective _ M.injective] at hn ⊢ + exact ⟨(M.linkModel s hs).pushCone (h s hs hn).some⟩ + +lemma Cone.FaceModel.pullAllLinks {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + {N R : ℕ} (h : AllLinkCones Y N R) : AllLinkCones X N R := by + intro s hs hn + have hc : (s.image M.vertex).card < N := by rwa [Finset.card_image_of_injective _ M.injective] + have H := h (s.image M.vertex) ((M.face_iff s).mpr hs) hc + rw [Finset.card_image_of_injective _ M.injective] at H + exact ⟨(M.linkModel s hs).pullCone H.some⟩ + +omit [DecidableEq V] in +lemma Cone.FaceModel.rankBound {X : CoboundaryExpanders.InfiniteChains.Complex V} {Y : CoboundaryExpanders.InfiniteChains.Complex W} (M : FaceModel X Y) + {N : ℕ} (h : RankBound X N) : RankBound Y N := by + intro t ht + obtain ⟨s,hs,rfl⟩ := M.cover t ht + rw [Finset.card_image_of_injective _ M.injective] + exact h s hs + +namespace Join + +def emptyRightModel {X : CoboundaryExpanders.InfiniteChains.Complex W} {Y : CoboundaryExpanders.InfiniteChains.Complex V} + (hY : ∀ s ∈ Y.faces, s = ∅) : FaceModel X (complex X Y) where + vertex := Sum.inl + injective := Sum.inl_injective + face_iff := by + intro s + change (s.image Sum.inl).toLeft ∈ X.faces ∧ (s.image Sum.inl).toRight ∈ Y.faces ↔ _ + have hL : (s.image (Sum.inl : W → W ⊕ V)).toLeft = s := by ext a; simp + have hR : (s.image (Sum.inl : W → W ⊕ V)).toRight = ∅ := by ext a; simp + rw [hL,hR] + simp only [Y.empty_mem,and_true] + cover := by + intro t ht + refine ⟨t.toLeft,ht.1,?_⟩ + have he := Finset.toLeft_disjSum_toRight (u:=t) + rw [hY t.toRight ht.2,Finset.disjSum_empty,Finset.map_eq_image] at he + exact he + +omit [DecidableEq V] [DecidableEq W] in +lemma rankBound {X : CoboundaryExpanders.InfiniteChains.Complex W} {Y : CoboundaryExpanders.InfiniteChains.Complex V} {A B : ℕ} + (hX : RankBound X A) (hY : RankBound Y B) : RankBound (complex X Y) (A+B) := by + intro s hs + have hL := hX s.toLeft hs.1 + have hR := hY s.toRight hs.2 + have hC := Finset.card_toLeft_add_card_toRight (u:=s) + omega + +theorem allLinkCones {X : CoboundaryExpanders.InfiniteChains.Complex W} {Y : CoboundaryExpanders.InfiniteChains.Complex V} {A B R S : ℕ} + (hX : RankBound X A) (hY : RankBound Y B) + (hCX : AllLinkCones X A R) (hCY : AllLinkCones Y B S) : + AllLinkCones (complex X Y) (A+B) (R+S+(1+R*(A+1))*S) := by + intro s hs hn + have hL := hX s.toLeft hs.1 + have hR := hY s.toRight hs.2 + have hC := Finset.card_toLeft_add_card_toRight (u:=s) + rw [link_eq hs] + by_cases hA : s.toLeft.card = A + · have hB : s.toRight.card < B := by omega + have he : A+B-s.card-1 = B-s.toRight.card-1 := by omega + rw [he] + exact ⟨((emptyLeftModel (hX.terminal hs.1 hA)).pushCone (hCY _ hs.2 hB).some).weaken le_rfl (by omega)⟩ + by_cases hB : s.toRight.card = B + · have hAl : s.toLeft.card < A := by omega + have he : A+B-s.card-1 = A-s.toLeft.card-1 := by omega + rw [he] + exact ⟨((emptyRightModel (hY.terminal hs.2 hB)).pushCone (hCX _ hs.1 hAl).some).weaken le_rfl (by omega)⟩ + have hAl : s.toLeft.card < A := by omega + have hBl : s.toRight.card < B := by omega + have he : A+B-s.card-1 = (A-s.toLeft.card-1)+(B-s.toRight.card-1)+1 := by omega + rw [he] + refine ⟨(boundedCone (hCX _ hs.1 hAl).some (hCY _ hs.2 hBl).some).weaken le_rfl ?_⟩ + apply max_le + · omega + · have hh := Nat.mul_le_mul_right S (Nat.add_le_add_left + (Nat.mul_le_mul_left R (show A-s.toLeft.card-1+1 ≤ A+1 by omega)) 1) + omega + +end Join +end + +open Cone +variable {V : Type} [DecidableEq V] + +omit [DecidableEq V] in +lemma singleton_mem_of_mem_face {X : CoboundaryExpanders.InfiniteChains.Complex V} {s : Finset V} (hs : s ∈ X.faces) + {v : V} (hv : v ∈ s) : {v} ∈ X.faces := X.downward hs (Finset.singleton_subset_iff.mpr hv) + +lemma faceLink_congr {X : CoboundaryExpanders.InfiniteChains.Complex V} {s t : Finset V} (hs : s ∈ X.faces) (ht : t ∈ X.faces) + (h : s = t) : X.faceLink s hs = X.faceLink t ht := by subst t; rfl + +lemma AllLinkCones.vertexCriterion {X : CoboundaryExpanders.InfiniteChains.Complex V} {N R : ℕ} (hN : 0 < N) + (hBase : Nonempty (BoundedCone X (N-1) R)) + (hVertex : ∀ v : V, ∀ hv : {v} ∈ X.faces, + AllLinkCones (X.faceLink {v} hv) (N-1) R) : AllLinkCones X N R := by + intro s hs hn + by_cases he : s = ∅ + · subst s + simpa only [faceLink_empty,Finset.card_empty,Nat.sub_zero] using hBase + obtain ⟨v,hv⟩ := Finset.nonempty_iff_ne_empty.mpr he + have hvx := singleton_mem_of_mem_face hs hv + have hu : {v} ∪ s.erase v = s := by simp [Finset.insert_erase hv] + have ht : s.erase v ∈ (X.faceLink {v} hvx).faces := by + constructor + · simp + · rwa [hu] + have hc : (s.erase v).card = s.card-1 := Finset.card_erase_of_mem hv + have hlt : (s.erase v).card < N-1 := by have hp := Finset.card_pos.mpr ⟨v,hv⟩; omega + have H := hVertex v hvx (s.erase v) ht hlt + rw [faceLink_iterated,faceLink_congr ht.2 hs hu] at H + have hp := Finset.card_pos.mpr ⟨v,hv⟩ + have he : (N-1)-(s.erase v).card-1 = N-s.card-1 := by omega + rwa [he] at H + +end CoboundaryExpanders.InfiniteChains + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains Cone +open scoped Pointwise +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +def actionModel (g : G) : FaceModel (complex H) (complex H) where + vertex := fun v => g • v + injective := MulAction.injective g + face_iff := by + intro s + change IsFace H (g • s) ↔ IsFace H s + constructor + · intro h + have hh := h.smul H g⁻¹ + have he : g⁻¹ • (g • s) = s := inv_smul_smul g s + rw [he] at hh + exact hh + · exact fun h => h.smul H g + cover := by + intro t ht + refine ⟨g⁻¹ • t,ht.smul H g⁻¹,?_⟩ + change g • (g⁻¹ • t) = t + exact smul_inv_smul g t + +lemma rankBound [Fintype I] : InfiniteChains.RankBound (complex H) (Fintype.card I) := by + rintro s ⟨g,A,rfl⟩ + rw [face_card] + exact Finset.card_le_univ _ + +lemma standard_singleton_face (i : I) : {vertex H 1 i} ∈ (complex H).faces := by + exact ⟨1,{i},by simp [face]⟩ +lemma standard_link_eq (i : I) : linkComplex H {i} = + (complex H).faceLink {vertex H 1 i} (standard_singleton_face H i) := by + simpa only [face,Finset.image_singleton] using linkComplex_eq H {i} + +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.MatrixOpposition +open SphericalOpposition SphericalOpposition.CompleteFlag TypedCosetFaces InfiniteChains Cone +open scoped Pointwise +variable {K : Type} [Field K] {N : ℕ} + +lemma card_cut (N : ℕ) : Fintype.card (Cut N) = N-1 := by + rw [Fintype.card_congr (cutTypeEquiv (N:=N)),Fintype.card_fin] +lemma cut_rankBound : RankBound (TypedCosetFaces.complex (cutGroups K N)) (N-1) := by + simpa only [card_cut] using TypedCosetFaces.rankBound (cutGroups K N) + +lemma cut_middle_link_cones {a b R S : ℕ} (ha : 0 < a) (hb : 0 < b) + (hA : AllLinkCones (TypedCosetFaces.complex (cutGroups K a)) (a-1) R) + (hB : AllLinkCones (TypedCosetFaces.complex (cutGroups K b)) (b-1) S) : + AllLinkCones (linkComplex (cutGroups K (a+b)) {middleCut ha hb}) + ((a-1)+(b-1)) (R+S+(1+R*((a-1)+1))*S) := by + have hj := Join.allLinkCones cut_rankBound cut_rankBound hA hB + exact (singleLinkModel _ _).pushAllLinks + ((cutProductLinkModel ha hb).pushAllLinks + ((productModel (cutGroups K a) (cutGroups K b)).pullAllLinks hj)) + +theorem uniform_cut_allLinkCones (N : ℕ) : + ∃ Q R : ℕ, ∀ (K : Type) [Field K] [Fintype K], Q < Fintype.card K → + AllLinkCones (TypedCosetFaces.complex (cutGroups K N)) (N-1) R := by + classical + induction N using Nat.strong_induction_on with | h N ih => + by_cases hN : N ≤ 1 + · exact ⟨0,0,fun _ _ _ _ s _ hs => by omega⟩ + have hN2 : 2 ≤ N := by omega + obtain ⟨Q0,R0,h0⟩ := exists_uniform_cones (N-2) + choose q r hr using fun i : Fin N => ih i.val i.isLt + let QL := ∑ i : Fin N, q i + let L := ∑ i : Fin N, r i + let B := L+L+(1+L*(N+1))*L + refine ⟨max Q0 QL,max R0 B,?_⟩ + intro K _ _ hQ + have hsmall (a : ℕ) (ha : a < N) : + AllLinkCones (TypedCosetFaces.complex (cutGroups K a)) (a-1) L := by + have hq : q ⟨a,ha⟩ ≤ QL := Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ _) + have hr' : r ⟨a,ha⟩ ≤ L := Finset.single_le_sum (fun _ _ => Nat.zero_le _) (Finset.mem_univ _) + exact (hr ⟨a,ha⟩ K (lt_of_le_of_lt (hq.trans (le_max_right _ _)) hQ)).weaken hr' + apply AllLinkCones.vertexCriterion (by omega : 0 < N-1) + · have H := h0 K (Fin N → K) N (stdFlag K N) (by omega) + (lt_of_le_of_lt (le_max_left _ _) hQ) + have hh := cutSphericalModel (K:=K) (N:=N) |>.pullCone H.some + have he : N-1-1 = N-2 := by omega + rw [he] + exact ⟨hh.weaken le_rfl (le_max_left _ _)⟩ + intro v hv + rcases v with ⟨c,v⟩ + induction v using Quotient.inductionOn with | h g => + have hstandard : AllLinkCones (linkComplex (cutGroups K N) {c}) (N-1-1) (max R0 B) := by + rcases c with ⟨a,ha,haN⟩ + obtain ⟨b,hNb⟩ := Nat.exists_eq_add_of_le (Nat.le_of_lt haN) + subst N + have hb : 0 < b := by omega + have hbN : b < a+b := by omega + have hc := cut_middle_link_cones ha hb (hsmall a haN) (hsmall b hbN) + have he : (a-1)+(b-1) = a+b-1-1 := by omega + rw [he] at hc + refine hc.weaken ?_ + apply le_trans _ (le_max_right _ _) + dsimp [B] + gcongr + omega + rw [standard_link_eq] at hstandard + have hm := (actionModel (cutGroups K N) g).linkModel {vertex (cutGroups K N) 1 c} + (standard_singleton_face _ _) + have hh := hm.pushAllLinks hstandard + have he : (actionModel (cutGroups K N) g).vertex (vertex (cutGroups K N) 1 c) = + vertex (cutGroups K N) g c := by + change g • vertex (cutGroups K N) 1 c = _ + rw [smul_vertex,mul_one] + have hi : ({vertex (cutGroups K N) 1 c} : Finset _).image + (actionModel (cutGroups K N) g).vertex = {vertex (cutGroups K N) g c} := by + rw [Finset.image_singleton,he] + rw [faceLink_congr _ hv hi] at hh + exact hh + +end CoboundaryExpanders.MatrixOpposition + +namespace CoboundaryExpanders.InfiniteChains +open Cone +variable {V : Type} [DecidableEq V] + +def ProperLinkCones (X : CoboundaryExpanders.InfiniteChains.Complex V) (N R : ℕ) : Prop := + ∀ s : Finset V, s.Nonempty → ∀ hs : s ∈ X.faces, s.card < N → + Nonempty (BoundedCone (X.faceLink s hs) (N-s.card-1) R) + +lemma ProperLinkCones.vertexCriterion {X : CoboundaryExpanders.InfiniteChains.Complex V} {N R : ℕ} + (hVertex : ∀ v : V, ∀ hv : {v} ∈ X.faces, + AllLinkCones (X.faceLink {v} hv) (N-1) R) : ProperLinkCones X N R := by + intro s hne hs hn + obtain ⟨v,hv⟩ := hne + have hvx := singleton_mem_of_mem_face hs hv + have hu : {v} ∪ s.erase v = s := by simp [Finset.insert_erase hv] + have ht : s.erase v ∈ (X.faceLink {v} hvx).faces := by + constructor + · simp + · rwa [hu] + have hc : (s.erase v).card = s.card-1 := Finset.card_erase_of_mem hv + have hp := Finset.card_pos.mpr ⟨v,hv⟩ + have hlt : (s.erase v).card < N-1 := by omega + have H := hVertex v hvx (s.erase v) ht hlt + rw [faceLink_iterated,faceLink_congr ht.2 hs hu] at H + have he : (N-1)-(s.erase v).card-1 = N-s.card-1 := by omega + rwa [he] at H +end CoboundaryExpanders.InfiniteChains + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains Cone +open scoped Pointwise +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +lemma allVertexLinks_of_standard {N R : ℕ} + (hs : ∀ i : I, AllLinkCones (linkComplex H {i}) N R) : + ∀ v : Vertex H, ∀ hv : {v} ∈ (complex H).faces, + AllLinkCones ((complex H).faceLink {v} hv) N R := by + rintro ⟨i,v⟩ hv + induction v using Quotient.inductionOn with | h g => + have hh := hs i + rw [standard_link_eq] at hh + have hh' := ((actionModel H g).linkModel {vertex H 1 i} (standard_singleton_face H i)).pushAllLinks hh + have he : (actionModel H g).vertex (vertex H 1 i) = vertex H g i := by + change g • vertex H 1 i = _ + rw [smul_vertex,mul_one] + have hi : ({vertex H 1 i} : Finset _).image (actionModel H g).vertex = {vertex H g i} := by + rw [Finset.image_singleton,he] + rw [faceLink_congr _ hv hi] at hh' + exact hh' +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.Construction +open InfiniteChains Cone TypedCosetFaces SphericalOpposition.CompleteFlag MatrixOpposition + +theorem uniform_actual_proper_link_cones (n : ℕ) (hn : 1 ≤ n) : + ∃ Q R : ℕ, ∀ p : ℕ, ∀ _ : Fact p.Prime, Q < p → + ∀ m : ℕ, 2 ≤ m → + ProperLinkCones (TypedCosetFaces.complex (reducedLocalGroup p n hn m)) (n+1) R := by + obtain ⟨Q,R,h⟩ := uniform_cut_allLinkCones (n+1) + refine ⟨Q,R,?_⟩ + intro p hp hq m hm + have hspherical := (cutSphericalModel (K:=ZMod p) (N:=n+1)).pushAllLinks + (h (ZMod p) (by simpa only [ZMod.card] using hq)) + have hspherical' : AllLinkCones (stdFlag (ZMod p) (n+1)).complex n R := by + simpa only [Nat.add_sub_cancel] using hspherical + apply ProperLinkCones.vertexCriterion + apply allVertexLinks_of_standard + intro cut + have hc := (sphericalLinkModel p n hn hm cut).pullAllLinks hspherical' + have ha := (actualVertexLinkModel p n hn m cut).pushAllLinks hc + simpa only [Nat.add_sub_cancel] using ha + +end CoboundaryExpanders.Construction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Main.lean b/lean/OAI/Combinatorics/Coboundary/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa8b80133afd6060aa0d1d28934855dfff6f2e03 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Main.lean @@ -0,0 +1,118 @@ +import OAI.Geometry.Coboundary.LatticeCones +import OAI.Combinatorics.Coboundary.Skeleton +import OAI.GroupTheory.Congruence.FrameHomology + +namespace OAI + +/-! +Uniform congruence homology vanishing and the complete bounded-degree coboundary-expander theorem. +-/ + +noncomputable section +open CategoryTheory CategoryTheory.Limits + +namespace CoboundaryExpanders +open Construction + +/-- A single prime threshold supplies all the finitely many ambient U-ranks +needed in an inductive homology argument. -/ +theorem uniform_u_homology (N : ℕ) : + ∃ Q : ℕ, ∀ (p : ℕ) [Fact p.Prime], Odd p → Q < p → + ∀ a : ℕ, 4 ≤ a → a ≤ N → ∀ j : ℕ, 0 < j → j < a-2 → + IsZero (groupHomology (Rep.trivial (ZMod 2) (U p a) (ZMod 2)) j) := by + induction N with + | zero => exact ⟨0,fun _ _ _ _ a ha hN => by omega⟩ + | succ N ih => + by_cases hN : 4 ≤ N+1 + · obtain ⟨Q₁,hQ₁⟩ := ih + obtain ⟨Q₂,hQ₂⟩ := uniform_infinite_coset_positive N (by omega) + refine ⟨max Q₁ Q₂,?_⟩ + intro p inst hp hQ a ha haN j hj hja + rcases lt_or_eq_of_le haN with hlt | rfl + · exact hQ₁ p hp (lt_of_le_of_lt (le_max_left _ _) hQ) a ha (by omega) j hj hja + · apply u_homology_isZero_of_opposition p N (by omega) hp + ((oppositionAcyclic_iff_positive p N (by omega)).mpr + (hQ₂ p (lt_of_le_of_lt (le_max_right _ _) hQ))) j hj + omega + · exact ⟨0,fun _ _ _ _ a ha haN => by omega⟩ + +/-- The actual congruence-group vanishing follows by induction on homological +degree, using the ordinary partial-basis edge argument and odd-index transfer. +This does not assume integral pro-stability or a stability theorem. -/ +theorem gamma_vanishing_of_u (p N : ℕ) [Fact p.Prime] (hp : Odd p) + (hU : ∀ a : ℕ, 4 ≤ a → a ≤ N → ∀ j : ℕ, 0 < j → j < a-2 → + IsZero (groupHomology (Rep.trivial (ZMod 2) (U p a) (ZMod 2)) j)) : + ∀ j : ℕ, 0 < j → ∀ a : ℕ, 2*j+2 ≤ a → a ≤ N → + ∀ m : ℕ, 1 ≤ m → + IsZero (groupHomology (Rep.trivial (ZMod 2) (Gamma p a m) (ZMod 2)) j) := by + intro j + induction j using Nat.strong_induction_on with + | h j ih => + intro hj a ha haN m hm + obtain ⟨q,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : j ≠ 0) + obtain ⟨a,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : a ≠ 0) + apply QuotientVanishing.gamma_isZero_of_U_and_action p (a+1) m Fact.out hp hm (q+1) + · exact hU (a+1) (by omega) haN (q+1) (by omega) (by omega) + · intro g + exact CongruenceFrames.conjugation_trivial p a m hm hp q ha (by + intro t ht htq + exact ih (q+1-t) (by omega) (by omega) (a+1-(t+1)) (by omega) (by omega) m hm) g + +/-- Consequently, for sufficiently large odd primes the literal congruence +homology vanishes simultaneously in the finite rank window required by d. -/ +theorem uniform_gamma_vanishing (N : ℕ) : + ∃ Q : ℕ, ∀ (p : ℕ) [Fact p.Prime], Odd p → Q < p → + ∀ j : ℕ, 0 < j → ∀ a : ℕ, 2*j+2 ≤ a → a ≤ N → + ∀ m : ℕ, 1 ≤ m → + IsZero (groupHomology (Rep.trivial (ZMod 2) (Gamma p a m) (ZMod 2)) j) := by + obtain ⟨Q,hQ⟩ := uniform_u_homology N + exact ⟨Q,fun p _ hp hQp => gamma_vanishing_of_u p N hp (hQ p hp hQp)⟩ + +/-- Zero target homology makes every actual stabilization cokernel zero, +including its literal transition map. -/ +theorem proZero_of_target_vanishing (p a j : ℕ) + (hz : ∀ m : ℕ, 1 ≤ m → + IsZero (groupHomology (Rep.trivial (ZMod 2) (Gamma p (a+1) m) (ZMod 2)) j)) : + CongruenceCokernels.ProZero p a j := by + intro m hm + have : Subsingleton (CongruenceCokernels.H p (a+1) m j) := + ModuleCat.subsingleton_of_isZero (hz m hm) + have hs : Function.Surjective (CongruenceCokernels.stabilization p a m j) := + fun x => ⟨0,Subsingleton.elim _ _⟩ + have : Subsingleton (CongruenceCokernels.C p a m j) := + (Cokernel.surjective_iff_coker_subsingleton _).mp hs + exact ⟨m,le_refl m,Subsingleton.elim _ _⟩ + +/-- The manuscript's full theorem, with one positive weighted coboundary +expansion constant in ALL degrees below d and all members of the family. -/ +theorem main : MainStatement := by + apply reduction_to_positive_open_inputs + intro d hd + obtain ⟨Q₁,hQ₁⟩ := uniform_infinite_coset_positive (2*d) (by omega) + obtain ⟨Q₂,hQ₂⟩ := actual_uniform_cosystolic (2*d) (by omega) + obtain ⟨Q₃,hQ₃⟩ := uniform_gamma_vanishing (2*d+1) + obtain ⟨p,hbound,hp⟩ := Nat.exists_infinite_primes (max 3 (max Q₁ (max Q₂ Q₃))+1) + have hQ : max 3 (max Q₁ (max Q₂ Q₃)) < p := by omega + have hp2 : p ≠ 2 := by have := le_max_left 3 (max Q₁ (max Q₂ Q₃)); omega + have ho : Odd p := hp.odd_of_ne_two hp2 + let : Fact p.Prime := ⟨hp⟩ + have h₁ : Q₁ < p := lt_of_le_of_lt ((le_max_left _ _).trans (le_max_right _ _)) hQ + have h₂ : Q₂ < p := lt_of_le_of_lt + ((le_max_left _ _).trans ((le_max_right _ _).trans (le_max_right _ _))) hQ + have h₃ : Q₃ < p := lt_of_le_of_lt + ((le_max_right _ _).trans ((le_max_right _ _).trans (le_max_right _ _))) hQ + refine ⟨p,hp,ho,hQ₁ p h₁,?_,hQ₂ p inferInstance h₂⟩ + intro j hj hjd + constructor + · apply proZero_of_target_vanishing + intro m hm + exact hQ₃ p ho h₃ j hj (2*d-1+1) (by omega) (by omega) m hm + · apply proZero_of_target_vanishing + intro m hm + exact hQ₃ p ho h₃ j hj (2*d+1) (by omega) (by omega) m hm + +end CoboundaryExpanders + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Mixing.lean b/lean/OAI/Combinatorics/Coboundary/Mixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc7ac306c8d5bedc1a3eff39b09a5fe4573ce924 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Mixing.lean @@ -0,0 +1,1133 @@ +import OAI.Combinatorics.Coboundary.LinkSpectrum +import OAI.Combinatorics.Coboundary.FatLadders +import OAI.Combinatorics.Coboundary.Spectral +import OAI.GroupTheory.Congruence.Elementary + +namespace OAI + +noncomputable section + +/-! +Small-set expansion, local spectral descent, connectedness, and uniform coset mixing. +-/ + +section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix + +namespace CoboundaryExpanders.EdgeMixing +variable {V : Type*} [Fintype V] +attribute [local instance] Classical.propDecidable + +def volume (e : V → V → ℝ) : ℝ := ∑ x, mass e x +def selected (e : V → V → ℝ) (P : V → Prop) : ℝ := ∑ x, if P x then mass e x else 0 +def chi (P : V → Prop) (x : V) : ℝ := if P x then 1 else 0 + +lemma mean_chi (e : V → V → ℝ) (P : V → Prop) : + (∑ x, mass e x * chi P x) = selected e P := by + apply Finset.sum_congr rfl + intro x _ + by_cases h : P x <;> simp [chi,h] + +omit [Fintype V] in +lemma chi_sq (P : V → Prop) (x : V) : (chi P x)^2 = chi P x := by + by_cases h : P x <;> simp [chi,h] + +lemma sum_right (e : V → V → ℝ) (hs : ∀ x y, e x y = e y x) (f : V → ℝ) : + (∑ x, ∑ y, e x y * f y) = ∑ x, mass e x * f x := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + simp only [mass,Finset.sum_mul] + apply Finset.sum_congr rfl + intro y _ + rw [hs] + +lemma centered_mean (e : V → V → ℝ) (P : V → Prop) : + (∑ x, mass e x * (volume e * chi P x - selected e P)) = 0 := by + simp only [mul_sub,Finset.sum_sub_distrib] + have h : (∑ x, mass e x * (volume e * chi P x)) = volume e * selected e P := by + rw [← mean_chi,Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + ring + rw [h,← Finset.sum_mul] + change volume e * selected e P - volume e * selected e P = 0 + ring + +lemma centered_energy (e : V → V → ℝ) (P : V → Prop) : + energy e (fun x => volume e * chi P x - selected e P) = + (volume e)^2*selected e P-volume e*(selected e P)^2 := by + have he : energy e (fun x => volume e * chi P x - selected e P) = + (volume e)^2*(∑ x, mass e x * chi P x) - + 2*volume e*selected e P*(∑ x, mass e x * chi P x) + + (selected e P)^2*(∑ x, mass e x) := by + simp only [energy,Finset.mul_sum,← Finset.sum_sub_distrib,← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + by_cases h : P x <;> simp [chi, h] <;> ring + rw [he,mean_chi] + change (volume e)^2*selected e P - 2*volume e*selected e P*selected e P + + (selected e P)^2*volume e = _ + ring + +lemma centered_pairing (e : V → V → ℝ) (hs : ∀ x y, e x y = e y x) (P : V → Prop) : + pairing e (fun x => volume e * chi P x - selected e P) + (fun x => volume e * chi P x - selected e P) = + (volume e)^2*pairing e (chi P) (chi P)-volume e*(selected e P)^2 := by + have he : pairing e (fun x => volume e * chi P x - selected e P) + (fun x => volume e * chi P x - selected e P) = + (volume e)^2*pairing e (chi P) (chi P) - + volume e*selected e P*(∑ x, ∑ y, e x y * chi P x) - + volume e*selected e P*(∑ x, ∑ y, e x y * chi P y) + + (selected e P)^2*volume e := by + simp only [pairing,volume,mass,Finset.mul_sum,← Finset.sum_sub_distrib, + ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + ring + have hl : (∑ x, ∑ y, e x y * chi P x) = selected e P := by + simp only [← Finset.sum_mul] + exact mean_chi e P + rw [he,hl,sum_right e hs,mean_chi] + ring + +theorem small_set (e : V → V → ℝ) (he : ∀ x y, 0 ≤ e x y) + (hs : ∀ x y, e x y = e y x) (hvol : 0 < volume e) + {lam t : ℝ} (hlam : 0 ≤ lam) (hray : Rayleigh e lam) + (P : V → Prop) (hP : selected e P ≤ t*volume e) : + pairing e (chi P) (chi P) ≤ (t+lam)*selected e P := by + have ha : 0 ≤ selected e P := Finset.sum_nonneg (fun x _ => by + split_ifs + · exact Finset.sum_nonneg (fun y _ => he x y) + · rfl) + have hh := hray (fun x => volume e * chi P x - selected e P) (centered_mean e P) + rw [centered_pairing e hs,centered_energy] at hh + have hb : volume e*(selected e P)^2 ≤ t*(volume e)^2*selected e P := by + nlinarith [mul_le_mul_of_nonneg_right hP (mul_nonneg hvol.le ha)] + have hn : 0 ≤ lam*volume e*(selected e P)^2 := by positivity + have hv : 0 < (volume e)^2 := sq_pos_of_pos hvol + nlinarith + +end CoboundaryExpanders.EdgeMixing + +namespace CoboundaryExpanders.FatLadders +variable {V : Type*} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +omit [Fintype V] in +lemma coface_eq_insert {s a : Finset V} (hsub : s ⊆ a) (hc : a.card = s.card+1) : + ∃ x, x ∉ s ∧ insert x s = a := by + obtain ⟨x,hxa,hxs⟩ := Finset.exists_mem_notMem_of_card_lt_card (by omega : s.card < a.card) + refine ⟨x,hxs,Finset.eq_of_subset_of_card_le (Finset.insert_subset hxa hsub) ?_⟩ + rw [Finset.card_insert_of_notMem hxs,hc] + +lemma sum_insert_star (s : Finset V) (g : Finset V → ℝ) : + (∑ x : V, if x ∉ s then g (insert x s) else 0) = starSum (s.card+1) s g := by + unfold starSum + rw [← Finset.sum_filter,← Finset.sum_filter] + apply Finset.sum_bij (fun x _ => insert x s) + · intro x hx + have hn := (Finset.mem_filter.mp hx).2 + exact Finset.mem_filter.mpr ⟨mem_level.mpr (Finset.card_insert_of_notMem hn), + Finset.subset_insert _ _⟩ + · intro x hx y hy he + have hxs := (Finset.mem_filter.mp hx).2 + have hys := (Finset.mem_filter.mp hy).2 + have hm : x ∈ insert y s := he ▸ Finset.mem_insert_self x s + exact (Finset.mem_insert.mp hm).resolve_right hxs + · intro a ha + obtain ⟨ha,hsub⟩ := Finset.mem_filter.mp ha + obtain ⟨x,hx,he⟩ := coface_eq_insert hsub (mem_level.mp ha) + exact ⟨x,Finset.mem_filter.mpr ⟨Finset.mem_univ _,hx⟩,he⟩ + · intro x hx + rfl + +def linkEdge (w : Finset V → ℝ) (s : Finset V) (x y : V) : ℝ := + if x ∉ s ∧ y ∉ s ∧ x ≠ y then w (insert x (insert y s)) else 0 + +omit [Fintype V] in +lemma linkEdge_nonneg {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) (s x y) : + 0 ≤ linkEdge w s x y := by unfold linkEdge; split_ifs; exact hw _; rfl +omit [Fintype V] in +lemma linkEdge_symm (w : Finset V → ℝ) (s : Finset V) (x y : V) : + linkEdge w s x y = linkEdge w s y x := by + simp only [linkEdge,Finset.insert_comm,ne_comm,and_comm,and_left_comm,and_assoc] + +lemma linkEdge_mass {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (s : Finset V) (x : V) : + EdgeMixing.mass (linkEdge w s) x = + if x ∉ s then (N-s.card-1:ℕ)*w (insert x s) else 0 := by + by_cases hx : x ∈ s + · simp [EdgeMixing.mass,linkEdge,hx] + · rw [ite_eq_left hx] + have he : EdgeMixing.mass (linkEdge w s) x = + ∑ y : V, if y ∉ insert x s then w (insert y (insert x s)) else 0 := by + apply Finset.sum_congr rfl + intro y _ + by_cases hy : y ∈ s + · simp [linkEdge,hy] + · by_cases hxy : x = y + · subst y; simp [linkEdge] + · simp [linkEdge,hx,hy,hxy,Ne.symm hxy,Finset.insert_comm] + rw [he,sum_insert_star,hw.balance _ _ (by omega)] + simp [Finset.card_insert_of_notMem hx,Nat.sub_add_eq] + +lemma linkEdge_selected {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (F : Finset V → Prop) (s : Finset V) : + EdgeMixing.selected (linkEdge w s) (fun x => F (insert x s)) = + (N-s.card-1:ℕ)*starNorm w (s.card+1) s (indicator F) := by + have he : EdgeMixing.selected (linkEdge w s) (fun x => F (insert x s)) = + (N-s.card-1:ℕ)*(∑ x : V, if x ∉ s then atom w (indicator F) (insert x s) else 0) := by + simp only [EdgeMixing.selected,linkEdge_mass hw,Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + rw [atom_indicator] + split_ifs <;> ring + rw [he,sum_insert_star] + rfl + +lemma linkEdge_volume {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (s : Finset V) : + EdgeMixing.volume (linkEdge w s) = + (N-s.card-1:ℕ)*(N-s.card:ℕ)*w s := by + have he : EdgeMixing.volume (linkEdge w s) = + (N-s.card-1:ℕ)*(∑ x : V, if x ∉ s then w (insert x s) else 0) := by + simp only [EdgeMixing.volume,linkEdge_mass hw,Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + split_ifs <;> ring + rw [he,sum_insert_star,hw.balance _ _ (by omega)] + simp [mul_assoc] + +omit [Fintype V] in +lemma Collision.reconstruct {F : Finset V → Prop} {s a : Finset V} + (hc : Collision F s a) : ∃ x y, x ∉ s ∧ y ∉ s ∧ x ≠ y ∧ + a = insert x (insert y s) ∧ F (insert x s) ∧ F (insert y s) := by + obtain ⟨x,hx,y,hy,hxy,he,hfx,hfy⟩ := hc + have hye : y ∈ a.erase x := Finset.mem_erase.mpr ⟨Ne.symm hxy,hy⟩ + have hey : insert y s = a.erase x := by rw [←he,Finset.insert_erase hye] + have hrep : insert x (insert y s) = a := by rw [hey,Finset.insert_erase hx] + have hex : insert x s = a.erase y := by + rw [←he,Finset.erase_right_comm,Finset.insert_erase] + exact Finset.mem_erase.mpr ⟨hxy,hx⟩ + refine ⟨x,y,?_,?_,hxy,hrep.symm,hex ▸ hfy,hey ▸ hfx⟩ + · rw [←he]; simp + · rw [←he]; simp + +lemma collision_le_pairing {w : Finset V → ℝ} (hw : ∀ s, 0 ≤ w s) + (F : Finset V → Prop) (s : Finset V) : + collisionMass w F s ≤ EdgeMixing.pairing (linkEdge w s) + (EdgeMixing.chi (fun x => F (insert x s))) (EdgeMixing.chi (fun x => F (insert x s))) := by + let term := fun x y => linkEdge w s x y * EdgeMixing.chi (fun x => F (insert x s)) x * + EdgeMixing.chi (fun x => F (insert x s)) y + have ht : ∀ x y, 0 ≤ term x y := by + intro x y + dsimp [term,EdgeMixing.chi] + split_ifs <;> simp_all [linkEdge_nonneg hw] + have hpoint (a : Finset V) : (if Collision F s a then w a else 0) ≤ + ∑ x : V, ∑ y : V, if a = insert x (insert y s) then term x y else 0 := by + by_cases hc : Collision F s a + · rw [ite_eq_left hc] + obtain ⟨x,y,hx,hy,hxy,hrep,hFx,hFy⟩ := hc.reconstruct + have hv : (if a = insert x (insert y s) then term x y else 0) = w a := by + simp [hrep,term,EdgeMixing.chi,hFx,hFy,linkEdge,hx,hy,hxy] + rw [←hv] + apply (Finset.single_le_sum (fun y _ => by split_ifs; exact ht x y; rfl) + (Finset.mem_univ y)).trans + apply Finset.single_le_sum _ (Finset.mem_univ x) + intro u _ + exact Finset.sum_nonneg (fun v _ => by split_ifs; exact ht u v; rfl) + · rw [ite_eq_right hc] + exact Finset.sum_nonneg (fun x _ => Finset.sum_nonneg (fun y _ => by + split_ifs; exact ht x y; rfl)) + calc + collisionMass w F s ≤ ∑ a ∈ level (s.card+2), + ∑ x : V, ∑ y : V, if a = insert x (insert y s) then term x y else 0 := + Finset.sum_le_sum (fun a _ => hpoint a) + _ = ∑ x : V, ∑ y : V, ∑ a ∈ level (s.card+2), + if a = insert x (insert y s) then term x y else 0 := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.sum_comm] + _ ≤ ∑ x : V, ∑ y : V, term x y := by + apply Finset.sum_le_sum + intro x _ + apply Finset.sum_le_sum + intro y _ + simp only [Finset.sum_ite_eq'] + split_ifs + · rfl + · exact ht x y + _ = _ := rfl + +theorem localMixing_of_rayleigh {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + {lam : ℝ} (hlam : 0 ≤ lam) + (hray : ∀ s : Finset V, s.card+2 ≤ N → 0 < w s → EdgeMixing.Rayleigh (linkEdge w s) lam) : + LocalMixing w N lam := by + intro F s hs t ht hsmall + have hnon : 0 ≤ (t+lam)*(N:ℝ)*starNorm w (s.card+1) s (indicator F) := + mul_nonneg (mul_nonneg (add_nonneg ht hlam) (Nat.cast_nonneg _)) + (starNorm_nonneg hw.nonneg _ _ _) + by_cases hr : s.card+2 ≤ N + · by_cases hpos : 0 < w s + · have hcpos : (0:ℝ) < (N-s.card-1:ℕ) := by exact_mod_cast (show 0 < N-s.card-1 by omega) + have hvpos : 0 < EdgeMixing.volume (linkEdge w s) := by + rw [linkEdge_volume hw] + exact mul_pos (mul_pos hcpos (by exact_mod_cast (show 0 < N-s.card by omega))) hpos + have hm : EdgeMixing.selected (linkEdge w s) (fun x => F (insert x s)) ≤ + t*EdgeMixing.volume (linkEdge w s) := by + rw [linkEdge_selected hw,linkEdge_volume hw] + nlinarith [mul_le_mul_of_nonneg_left hsmall hcpos.le] + have hh := EdgeMixing.small_set (linkEdge w s) (linkEdge_nonneg hw.nonneg s) + (linkEdge_symm w s) hvpos hlam (hray s hr hpos) (fun x => F (insert x s)) hm + apply (collision_le_pairing hw.nonneg F s).trans + apply hh.trans + rw [linkEdge_selected hw] + have hcN : (N-s.card-1:ℕ) ≤ N := by omega + have hcr : ((N-s.card-1:ℕ):ℝ) ≤ N := by exact_mod_cast hcN + have hn := starNorm_nonneg hw.nonneg (s.card+1) s (indicator F) + nlinarith [mul_le_mul_of_nonneg_right hcr (mul_nonneg (add_nonneg ht hlam) hn)] + · have hz : w s = 0 := le_antisymm (le_of_not_gt hpos) (hw.nonneg s) + have hzero : collisionMass w F s = 0 := by + apply Finset.sum_eq_zero + intro a ha + split_ifs with hc + · obtain ⟨x,y,hx,hy,hxy,hrep,hFx,hFy⟩ := hc.reconstruct + exact hw.weight_eq_zero_of_base (hrep ▸ + (Finset.subset_insert y s).trans (Finset.subset_insert x (insert y s))) hz + · rfl + rw [hzero] + exact hnon + · have hzero : collisionMass w F s = 0 := by + apply Finset.sum_eq_zero + intro a ha + have hah := mem_level.mp ha + split_ifs + · exact hw.vanish a (by omega) + · rfl + rw [hzero] + exact hnon + +end CoboundaryExpanders.FatLadders + +end + +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix +open scoped BigOperators InnerProductSpace + +namespace CoboundaryExpanders.EdgeMixing + +section +variable {V W : Type} [Fintype V] [Fintype W] +attribute [local instance] Classical.propDecidable + +def action (e : V → V → ℝ) (f : V → ℝ) (x : V) : ℝ := (∑ y,e x y*f y)/mass e x +abbrev Active (e : V → V → ℝ) := {x : V // 0 < mass e x} +def Connected (e : V → V → ℝ) : Prop := + ∀ x y : Active e, Relation.ReflTransGen (fun a b : Active e => 0 < e a.val b.val) x y + +lemma edge_le_mass {e : V → V → ℝ} (he : ∀ x y,0 ≤ e x y) (x y : V) : e x y ≤ mass e x := by + exact Finset.single_le_sum (fun z _ => he x z) (Finset.mem_univ y) +lemma edge_zero_of_nonactive {e : V → V → ℝ} (he : ∀ x y,0 ≤ e x y) {x : V} + (hx : ¬0 < mass e x) (y : V) : e x y = 0 := + le_antisymm ((edge_le_mass he x y).trans (not_lt.mp hx)) (he x y) + +def activeEmbedding (e : V → V → ℝ) (he : ∀ x y,0 ≤ e x y) : + Embedding (fun x y : Active e => e x.val y.val) e where + vertex := Subtype.val + injective := Subtype.val_injective + edge_eq := fun _ _ => rfl + outside_zero := by + intro x hx y + exact edge_zero_of_nonactive he (fun h => hx ⟨⟨x,h⟩,rfl⟩) y + +def activeGraph (e : V → V → ℝ) (he : ∀ x y,0 ≤ e x y) + (hs : ∀ x y,e x y = e y x) : Spectral.WeightedGraph (Active e) where + edge := fun x y => e x.val y.val + nonneg := fun x y => he x.val y.val + symm := fun x y => hs x.val y.val + row_pos := by + intro x + have hm := (activeEmbedding e he).mass_map hs x + change mass (fun x y : Active e => e x.val y.val) x > 0 + rw [←hm] + exact x.property + +lemma active_action (e : V → V → ℝ) (he : ∀ x y,0 ≤ e x y) + (hs : ∀ x y,e x y = e y x) (f : Active e → ℝ) (x : Active e) : + action e ((activeEmbedding e he).extend f) x.val = (activeGraph e he hs).action f x := by + let M := activeEmbedding e he + change (∑ y,e x.val y*M.extend f y)/mass e x.val = + (∑ y : Active e,e x.val y.val*f y)/(activeGraph e he hs).mass x + have hz (y : V) (hy : y ∉ Set.range M.vertex) : e x.val y*M.extend f y = 0 := by + rw [hs,M.outside_zero y hy,zero_mul] + rw [sum_embedding M.vertex M.injective _ hz] + have hm := M.mass_map hs x + change mass e x.val = (activeGraph e he hs).mass x at hm + rw [hm] + congr 1 + apply Finset.sum_congr rfl + intro y _ + rw [M.extend_map] + rfl + +theorem trickle {e : V → V → ℝ} (he : ∀ x y,0 ≤ e x y) (hs : ∀ x y,e x y = e y x) + (hc : Connected e) {lam : ℝ} (hlam : lam < 1) + (hloc : ∀ f : V → ℝ, pairing e f f ≤ lam*energy e f+(1-lam)*energy e (action e f)) : + Rayleigh e (lam/(1-lam)) := by + let M := activeEmbedding e he + by_cases hne : Nonempty (Active e) + · let := hne + let G := activeGraph e he hs + apply M.push hs + intro f hf + change G.pairing f f ≤ (lam/(1-lam))*G.energy f + apply G.trickle hc hlam _ f hf + intro g + have h := hloc (M.extend g) + rw [M.pairing_pull hs,M.energy_pull hs,M.extend_comp,M.energy_pull hs] at h + have hg : action e (M.extend g) ∘ M.vertex = G.action g := by + funext x + exact active_action e he hs g x + rw [hg] at h + exact h + · have hzero (x y : V) : e x y = 0 := + M.outside_zero x (by rintro ⟨z,hz⟩; exact hne ⟨z⟩) y + intro f hf + simp only [pairing,energy,mass,hzero,zero_mul,Finset.sum_const_zero,mul_zero,le_refl] + +end + +variable {V : Type} [Fintype V] +lemma energy_sub_const (e : V → V → ℝ) (f : V → ℝ) (a : ℝ) : + energy e (fun x => f x-a) = energy e f - 2*a*(∑ x,mass e x*f x)+a^2*(∑ x,mass e x) := by + simp only [energy,Finset.mul_sum,←Finset.sum_sub_distrib,←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + ring +lemma pairing_sub_const (e : V → V → ℝ) (hs : ∀ x y,e x y = e y x) + (f : V → ℝ) (a : ℝ) : + pairing e (fun x => f x-a) (fun x => f x-a) = + pairing e f f - 2*a*(∑ x,mass e x*f x)+a^2*(∑ x,mass e x) := by + have he : pairing e (fun x => f x-a) (fun x => f x-a) = pairing e f f - + a*(∑ x,∑ y,e x y*f x)-a*(∑ x,∑ y,e x y*f y)+a^2*(∑ x,mass e x) := by + simp only [pairing,mass,Finset.mul_sum,←Finset.sum_sub_distrib,←Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + ring + have hr : (∑ x,∑ y,e x y*f y) = ∑ x,mass e x*f x := by + rw [Finset.sum_comm] + simp only [mass,Finset.sum_mul] + apply Finset.sum_congr rfl + intro x _ + apply Finset.sum_congr rfl + intro y _ + rw [hs] + rw [he,hr] + simp only [←Finset.sum_mul] + change pairing e f f-a*(∑x,mass e x*f x)-a*(∑x,mass e x*f x)+_ = _ + ring + +lemma centered_bound {e : V → V → ℝ} (hs : ∀ x y,e x y = e y x) + {lam : ℝ} (h : Rayleigh e lam) (f : V → ℝ) (a : ℝ) + (ha : (∑ x,mass e x*f x) = (∑ x,mass e x)*a) : + pairing e f f ≤ lam*energy e f+(1-lam)*(∑ x,mass e x)*a^2 := by + have hz : (∑ x,mass e x*(f x-a)) = 0 := by + simp only [mul_sub,Finset.sum_sub_distrib,←Finset.sum_mul] + rw [ha]; ring + have hh := h (fun x => f x-a) hz + rw [energy_sub_const,pairing_sub_const e hs,ha] at hh + nlinarith [hh] + +lemma mass_mul_action {e : V → V → ℝ} (he : ∀ x y,0 ≤ e x y) (f : V → ℝ) (x : V) : + mass e x * action e f x = ∑y,e x y*f y := by + by_cases hx : mass e x = 0 + · have hz (y : V) : e x y = 0 := edge_zero_of_nonactive he (by rw [hx]; exact lt_irrefl _) y + simp [hx,hz] + · exact mul_div_cancel₀ _ hx + +theorem triangle_moment {e : V → V → ℝ} (he : ∀ x y,0 ≤ e x y) + (hs : ∀ x y,e x y = e y x) (d : V → V → V → ℝ) + (hd : ∀ x y z,d x y z = d x z y) {c : ℝ} (hc : 0 < c) + (hm : ∀ x y,mass (d x) y = c*e x y) + (ht : ∀ y z,(∑ x,d x y z) = c*e y z) + {lam : ℝ} (hr : ∀ x,Rayleigh (d x) lam) (f : V → ℝ) : + pairing e f f ≤ lam*energy e f+(1-lam)*energy e (action e f) := by + have hl (x : V) : pairing (d x) f f ≤ lam*energy (d x) f+ + (1-lam)*c*mass e x*(action e f x)^2 := by + have hv : (∑y,mass (d x) y) = c*mass e x := by + simp only [hm] + rw [←Finset.mul_sum] + rfl + have hmean : (∑y,mass (d x) y*f y) = (∑y,mass (d x) y)*action e f x := by + rw [hv] + simp only [hm,mul_assoc,←Finset.mul_sum,mass_mul_action he] + have h := centered_bound (hd x) (hr x) f (action e f x) hmean + simpa only [hv,mul_assoc] using h + have hp : (∑x,pairing (d x) f f) = c*pairing e f f := by + simp only [pairing] + rw [Finset.sum_comm] + simp_rw [Finset.sum_comm (s:=Finset.univ) (t:=Finset.univ) (f:=fun x z => d x _ z*f _*f z)] + simp only [←Finset.sum_mul,ht,Finset.mul_sum,mul_assoc] + have hen : (∑x,energy (d x) f) = c*energy e f := by + simp only [energy,hm] + rw [Finset.sum_comm] + simp only [←Finset.sum_mul,←Finset.mul_sum] + unfold mass + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + rw [show (∑x,e x y) = ∑x,e y x by apply Finset.sum_congr rfl; intro x _; rw [hs]] + ring + have ha : (∑x,(1-lam)*c*mass e x*(action e f x)^2) = + c*(1-lam)*energy e (action e f) := by + simp only [energy,Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + ring + have h := Finset.sum_le_sum (s:=Finset.univ) (fun x _ => hl x) + rw [hp,Finset.sum_add_distrib,←Finset.mul_sum,hen,ha] at h + apply (mul_le_mul_iff_right₀ hc).mp + nlinarith [h] + +theorem triangle_trickle {e : V → V → ℝ} (he : ∀ x y,0 ≤ e x y) + (hs : ∀ x y,e x y = e y x) (hconn : Connected e) (d : V → V → V → ℝ) + (hd : ∀ x y z,d x y z = d x z y) {c : ℝ} (hc : 0 < c) + (hm : ∀ x y,mass (d x) y = c*e x y) + (ht : ∀ y z,(∑ x,d x y z) = c*e y z) + {lam : ℝ} (hlam : lam < 1) (hr : ∀ x,Rayleigh (d x) lam) : + Rayleigh e (lam/(1-lam)) := + trickle he hs hconn hlam (triangle_moment he hs d hd hc hm ht hr) +end CoboundaryExpanders.EdgeMixing + +namespace CoboundaryExpanders.FatLadders + +section +variable {V : Type} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable + +def triangle (w : Finset V → ℝ) (s : Finset V) (x y z : V) : ℝ := + if x ∉ s then linkEdge w (insert x s) y z else 0 +omit [Fintype V] in +lemma triangle_cycle (w : Finset V → ℝ) (s : Finset V) (x y z : V) : + triangle w s x y z = triangle w s y z x := by + unfold triangle linkEdge + simp only [Finset.mem_insert] + split_ifs <;> simp_all [Finset.insert_comm,ne_comm] +omit [Fintype V] in +lemma triangle_symm (w : Finset V → ℝ) (s : Finset V) (x y z : V) : + triangle w s x y z = triangle w s x z y := by + unfold triangle + rw [linkEdge_symm] +lemma triangle_mass {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (s : Finset V) (x y : V) : + EdgeMixing.mass (triangle w s x) y = (N-s.card-2:ℕ)*linkEdge w s x y := by + by_cases hx : x ∈ s + · simp [EdgeMixing.mass,triangle,linkEdge,hx] + · have he : triangle w s x = linkEdge w (insert x s) := by funext a b; simp [triangle,hx] + rw [he,linkEdge_mass hw,Finset.card_insert_of_notMem hx] + have hnat : N-(s.card+1)-1 = N-s.card-2 := by omega + rw [hnat] + by_cases hy : y ∈ s + · simp [linkEdge,hy] + · by_cases hxy : x = y + · subst y; simp [linkEdge] + · simp [linkEdge,hx,hy,hxy,Ne.symm hxy,Finset.insert_comm] +lemma triangle_sum {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (s : Finset V) (y z : V) : + (∑x,triangle w s x y z) = (N-s.card-2:ℕ)*linkEdge w s y z := by + simp_rw [triangle_cycle w s _ y z] + exact triangle_mass hw s y z +lemma linkEdge_zero {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + {s : Finset V} (hz : w s = 0) : linkEdge w s = 0 := by + funext x y + unfold linkEdge + split_ifs + · exact hw.weight_eq_zero_of_base ((Finset.subset_insert y s).trans (Finset.subset_insert x _)) hz + · rfl + +theorem link_trickle {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (s : Finset V) (hrank : s.card+3 ≤ N) + (hc : EdgeMixing.Connected (linkEdge w s)) {lam : ℝ} (hlam : lam < 1) + (hray : ∀ x, x ∉ s → 0 < w (insert x s) → + EdgeMixing.Rayleigh (linkEdge w (insert x s)) lam) : + EdgeMixing.Rayleigh (linkEdge w s) (lam/(1-lam)) := by + apply EdgeMixing.triangle_trickle (linkEdge_nonneg hw.nonneg s) (linkEdge_symm w s) hc + (triangle w s) (triangle_symm w s) (by exact_mod_cast (show 0 < N-s.card-2 by omega)) + (triangle_mass hw s) (triangle_sum hw s) hlam + intro x + by_cases hx : x ∈ s + · intro f hf + simp [EdgeMixing.pairing,EdgeMixing.energy,EdgeMixing.mass,triangle,hx] + · have he : triangle w s x = linkEdge w (insert x s) := by funext a b; simp [triangle,hx] + rw [he] + by_cases hp : 0 < w (insert x s) + · exact hray x hx hp + · have hz : w (insert x s) = 0 := le_antisymm (not_lt.mp hp) (hw.nonneg _) + rw [linkEdge_zero hw hz] + intro f hf + simp [EdgeMixing.pairing,EdgeMixing.energy,EdgeMixing.mass] +end + +variable {V : Type} [Fintype V] [DecidableEq V] +theorem link_trickle_double {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + (s : Finset V) (hrank : s.card+3 ≤ N) + (hc : EdgeMixing.Connected (linkEdge w s)) {lam : ℝ} (h0 : 0 ≤ lam) (h1 : lam ≤ 1) + (hray : ∀ x, x ∉ s → 0 < w (insert x s) → + EdgeMixing.Rayleigh (linkEdge w (insert x s)) (lam/2)) : + EdgeMixing.Rayleigh (linkEdge w s) lam := by + apply EdgeMixing.rayleigh_mono (linkEdge_nonneg hw.nonneg s) (link_trickle hw s hrank hc (by linarith) hray) + apply (div_le_iff₀ (by linarith : 0 < 1-lam/2)).mpr + nlinarith [mul_nonneg h0 (sub_nonneg.mpr h1)] + +theorem all_link_rayleigh {w : Finset V → ℝ} {N : ℕ} (hw : Balanced w N) + {eps : ℝ} (h0 : 0 ≤ eps) (h1 : eps ≤ 1) + (hc : ∀ s : Finset V, s.card+3 ≤ N → 0 < w s → EdgeMixing.Connected (linkEdge w s)) + (htop : ∀ s : Finset V, s.card+2 = N → 0 < w s → + EdgeMixing.Rayleigh (linkEdge w s) (eps / 2^(N-2))) : + ∀ s : Finset V, s.card+2 ≤ N → 0 < w s → EdgeMixing.Rayleigh (linkEdge w s) eps := by + have main : ∀ r : ℕ, ∀ s : Finset V, N-s.card = r → s.card+2 ≤ N → 0 < w s → + EdgeMixing.Rayleigh (linkEdge w s) (eps / 2^s.card) := by + intro r + induction r using Nat.strong_induction_on with + | h r ih => + intro s heq hr hs + by_cases ht : s.card+2 = N + · have hcard : s.card = N-2 := by omega + simpa only [hcard] using htop s ht hs + · have hr3 : s.card+3 ≤ N := by omega + have hp : (1:ℝ) ≤ 2^s.card := one_le_pow₀ (by norm_num) + apply link_trickle_double hw s hr3 (hc s hr3 hs) (div_nonneg h0 (by positivity)) + ((div_le_self h0 hp).trans h1) + intro x hx hxp + have hc' : (insert x s).card = s.card+1 := Finset.card_insert_of_notMem hx + have hi : N-(insert x s).card < r := by rw [hc']; omega + have hh := ih (N-(insert x s).card) hi (insert x s) rfl (by rw [hc']; omega) hxp + simpa only [hc',pow_succ,div_mul_eq_div_div] using hh + intro s hr hs + apply EdgeMixing.rayleigh_mono (linkEdge_nonneg hw.nonneg s) (main _ s rfl hr hs) + exact div_le_self h0 (one_le_pow₀ (by norm_num)) +end CoboundaryExpanders.FatLadders + +namespace CoboundaryExpanders.InfiniteChains.FiniteWeights +variable {V : Type} [Fintype V] [DecidableEq V] +attribute [local instance] Classical.propDecidable +lemma cofaces_chamberWeight (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) : + FatLadders.chamberWeight (fun t : ↥(level X N) => t.val) (fun _ => (1:ℝ)) = + fun s => (cofaces X N s : ℝ) := by + funext s + unfold FatLadders.chamberWeight cofaces + dsimp only + calc + _ = ∑ t ∈ level X N, if s ⊆ t then (1:ℝ) else 0 := + Finset.sum_coe_sort (level X N) (fun t => if s ⊆ t then (1:ℝ) else 0) + _ = _ := Finset.sum_boole _ _ + +lemma cofaces_balanced (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) : + FatLadders.Balanced (fun s => (cofaces X N s : ℝ)) N := by + rw [←cofaces_chamberWeight X N] + exact FatLadders.chamberWeight_balanced _ _ N + (fun t => ((mem_level X N t.val).mp t.property).2) (fun _ => by norm_num) + +lemma linkEdge_eq (X : CoboundaryExpanders.InfiniteChains.Complex V) {N : ℕ} {s : Finset V} (hs : s ∈ X.faces) + (hN : s.card ≤ N) : + FatLadders.linkEdge (fun t => (cofaces X N t : ℝ)) s = edge (X.faceLink s hs) (N-s.card) := by + funext x y + by_cases hx : x ∈ s + · have hf : ({x}:Finset V) ∉ (X.faceLink s hs).faces := by + intro h + exact Finset.disjoint_left.mp h.1 hx (Finset.mem_singleton_self x) + simp [FatLadders.linkEdge,hx,edge_zero_of_not_face _ _ hf] + by_cases hy : y ∈ s + · have hf : ({y}:Finset V) ∉ (X.faceLink s hs).faces := by + intro h + exact Finset.disjoint_left.mp h.1 hy (Finset.mem_singleton_self y) + rw [edge_symm _ _ x y,edge_zero_of_not_face _ _ hf] + simp [FatLadders.linkEdge,hy] + have hd : Disjoint s {x,y} := by simp [hx,hy] + simp only [FatLadders.linkEdge,hx,hy,not_false_eq_true,true_and,edge] + split_ifs + · rw [cofaces_link X hs hN hd] + congr 2 + ext z + simp only [Finset.mem_union,Finset.mem_insert,Finset.mem_singleton] + tauto + · rfl +end CoboundaryExpanders.InfiniteChains.FiniteWeights + +namespace CoboundaryExpanders.InfiniteChains +open Cone FiniteWeights +variable {V : Type} [Fintype V] [DecidableEq V] +lemma FiniteWeights.active_face (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) (x : V) + (hx : 0 < EdgeMixing.mass (edge X N) x) : ({x}:Finset V) ∈ X.faces := by + by_contra h + have hz : EdgeMixing.mass (edge X N) x = 0 := by + simp only [EdgeMixing.mass,edge_zero_of_not_face X N h,Finset.sum_const_zero] + rw [hz] at hx + exact (lt_irrefl _) hx +lemma FiniteWeights.edge_pos {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} (hP : Pure X N) {x y : V} + (hxy : x ≠ y) (hface : ({x,y}:Finset V) ∈ X.faces) : 0 < edge X N x y := by + rw [edge,ite_eq_left hxy] + exact_mod_cast cofaces_pos hP hface + +lemma Cone.VertexPath.toActive {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} (hP : Pure X N) {x y : V} + (hpath : VertexPath X x y) (hx : 0 < EdgeMixing.mass (edge X N) x) + (hy : 0 < EdgeMixing.mass (edge X N) y) : + Relation.ReflTransGen (fun a b : EdgeMixing.Active (edge X N) => 0 < edge X N a.val b.val) + ⟨x,hx⟩ ⟨y,hy⟩ := by + induction hpath with + | refl => exact Relation.ReflTransGen.refl + | @tail b c hpath hbc ih => + by_cases he : b = c + · subst c + exact ih hy + · have hp := edge_pos hP he hbc + have hb : 0 < EdgeMixing.mass (edge X N) b := hp.trans_le (EdgeMixing.edge_le_mass (edge_nonneg X N) b c) + exact (ih hb).tail hp + +theorem Cone.BoundedCone.spectralConnected {X : CoboundaryExpanders.InfiniteChains.Complex V} {n R N : ℕ} + (H : BoundedCone X n R) (hn : 1 ≤ n) (hP : Pure X N) : + EdgeMixing.Connected (edge X N) := by + intro x y + exact (H.vertexPath hn x.val y.val (active_face X N x.val x.property) + (active_face X N y.val y.property)).toActive hP x.property y.property +end CoboundaryExpanders.InfiniteChains + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains InfiniteChains.Cone InfiniteChains.FiniteWeights +variable {G I : Type} [Group G] [DecidableEq I] (H : I → Subgroup G) + +lemma spectralConnected_of_generate [Fintype (Vertex H)] {N : ℕ} (hp : Pure (complex H) N) + (hgen : Subgroup.closure (⋃ i, (H i : Set G)) = ⊤) (base : I) : + EdgeMixing.Connected (edge (complex H) N) := by + intro x y + exact (vertexPath_of_generate H hgen base x.val y.val).toActive hp x.property y.property +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.Construction + +section +open Elementary +variable (p n : ℕ) [Fact p.Prime] + +def cycleGenerated (hn : 1 ≤ n) : Subgroup (Matrix.SpecialLinearGroup (Fin (n + 1)) (R p)) := + Subgroup.closure (Set.range (cycleRoot p n hn)) + +omit [Fact p.Prime] in +theorem cycleRoot_mem_generated (hn : 1 ≤ n) (j : Fin (n + 1)) : + cycleRoot p n hn j ∈ cycleGenerated p n hn := + Subgroup.subset_closure ⟨j, rfl⟩ + +theorem cycleGenerated_le_U (hn : 1 ≤ n) : cycleGenerated p n hn ≤ U p (n + 1) := by + apply (Subgroup.closure_le _).mpr + rintro _ ⟨j, rfl⟩ + exact cycleRoot_mem_U p n hn j + +omit [Fact p.Prime] in +theorem upper_adjacent_mem_generated (hn : 1 ≤ n) (i j : Fin (n + 1)) + (hij : i.val + 1 = j.val) : + E (show i ≠ j by intro he; subst j; omega) (1 : R p) ∈ cycleGenerated p n hn := by + have hj : j ≠ 0 := by intro he; subst j; simp at hij + have hs : edgeSource n j = i := by + apply Fin.ext + simp only [edgeSource, dite_eq_right hj, Fin.val_mk] + omega + simpa only [cycleRoot, ite_eq_right hj, hs] using cycleRoot_mem_generated p n hn j + +omit [Fact p.Prime] in +theorem upper_one_mem_generated (hn : 1 ≤ n) {i j : Fin (n + 1)} (hij : i < j) : + E hij.ne (1 : R p) ∈ cycleGenerated p n hn := + E_upper_one_mem _ (upper_adjacent_mem_generated p n hn) hij + +omit [Fact p.Prime] in +theorem lower_X_mem_generated (hn : 1 ≤ n) {i j : Fin (n + 1)} (hij : j < i) : + E hij.ne.symm (Polynomial.X : R p) ∈ cycleGenerated p n hn := by + have hlast0 : (Fin.last n : Fin (n + 1)) ≠ 0 := by + intro he + have := congrArg Fin.val he + simp only [Fin.val_last, Fin.val_zero] at this + omega + have hbase : E hlast0 (Polynomial.X : R p) ∈ cycleGenerated p n hn := by + simpa [cycleRoot, edgeSource, E] using + cycleRoot_mem_generated p n hn 0 + have hlastj : j < Fin.last n := by change j.val < n; have := i.isLt; omega + have hlast : E hlastj.ne.symm (Polynomial.X : R p) ∈ cycleGenerated p n hn := by + by_cases hj : j = 0 + · subst j; exact hbase + · have h0j : (0 : Fin (n + 1)) < j := Fin.pos_iff_ne_zero.mpr hj + simpa only [mul_one] using E_path_mem (cycleGenerated p n hn) + hlast0 h0j.ne hlastj.ne.symm hbase (upper_one_mem_generated p n hn h0j) + by_cases hi : i = Fin.last n + · subst i; exact hlast + · have hilast : i < Fin.last n := by change i.val < n; have := i.isLt; have := Fin.ext_iff.not.mp hi; simp only [Fin.val_last] at this; omega + simpa only [one_mul] using E_path_mem (cycleGenerated p n hn) + hilast.ne hlastj.ne.symm hij.ne.symm (upper_one_mem_generated p n hn hilast) hlast + +omit [Fact p.Prime] in +theorem X_mem_generated (hn : 2 ≤ n) {i j : Fin (n + 1)} (hij : i ≠ j) : + E hij (Polynomial.X : R p) ∈ cycleGenerated p n (by omega) := by + have hn1 : 1 ≤ n := by omega + by_cases hji : j < i + · exact lower_X_mem_generated p n hn1 hji + have hij' : i < j := lt_of_le_of_ne (le_of_not_gt hji) hij + by_cases hi : i = 0 + · subst i + by_cases hj : j = Fin.last n + · subst j + let k : Fin (n + 1) := ⟨1, by omega⟩ + have h0k : (0 : Fin (n + 1)) < k := by change (0 : ℕ) < 1; omega + have hklast : k < Fin.last n := by change 1 < n; omega + have hk0 := lower_X_mem_generated p n hn1 h0k + have h0last := upper_one_mem_generated p n hn1 hij' + have hklastX : E hklast.ne (Polynomial.X : R p) ∈ cycleGenerated p n hn1 := by + simpa only [mul_one] using E_path_mem (cycleGenerated p n hn1) + h0k.ne.symm hij'.ne hklast.ne hk0 h0last + simpa only [one_mul] using E_path_mem (cycleGenerated p n hn1) + h0k.ne hklast.ne hij (upper_one_mem_generated p n hn1 h0k) hklastX + · have hjlast : j < Fin.last n := by + change j.val < n + have := j.isLt + have := Fin.ext_iff.not.mp hj + simp only [Fin.val_last] at this + omega + have h0last : (0 : Fin (n + 1)) < Fin.last n := by change 0 < n; omega + simpa only [one_mul] using E_path_mem (cycleGenerated p n hn1) + h0last.ne hjlast.ne.symm hij (upper_one_mem_generated p n hn1 h0last) + (lower_X_mem_generated p n hn1 hjlast) + · have h0i : (0 : Fin (n + 1)) < i := Fin.pos_iff_ne_zero.mpr hi + have h0j : (0 : Fin (n + 1)) < j := h0i.trans hij' + simpa only [mul_one] using E_path_mem (cycleGenerated p n hn1) + h0i.ne.symm h0j.ne hij (lower_X_mem_generated p n hn1 h0i) + (upper_one_mem_generated p n hn1 h0j) + +omit [Fact p.Prime] in +theorem X_pow_mem_generated (hn : 2 ≤ n) {i j : Fin (n + 1)} (hij : i ≠ j) (r : ℕ) : + E hij (Polynomial.X ^ (r + 1) : R p) ∈ cycleGenerated p n (by omega) := by + induction r generalizing i j with + | zero => simpa only [zero_add, pow_one] using X_mem_generated p n hn hij + | succ r ih => + obtain ⟨k, hki, hkj⟩ := Fin.exists_ne_and_ne_of_two_lt i j (by omega) + simpa only [pow_succ] using E_path_mem (cycleGenerated p n (by omega)) + hki.symm hkj hij (ih hki.symm) (X_mem_generated p n hn hkj) + +theorem scalar_root_mem (hn : 1 ≤ n) {i j : Fin (n + 1)} (hij : i ≠ j) + {f : R p} (hf : E hij f ∈ cycleGenerated p n hn) (c : ZMod p) : + E hij (Polynomial.C c * f) ∈ cycleGenerated p n hn := by + have hc : Polynomial.C c = (c.val : R p) := by + calc Polynomial.C c = Polynomial.C (c.val : ZMod p) := + congrArg Polynomial.C (ZMod.natCast_zmod_val c).symm + _ = _ := map_natCast Polynomial.C _ + rw [hc, E_natCast_mul] + exact (cycleGenerated p n hn).pow_mem hf _ + +theorem upper_polynomial_mem_generated (hn : 2 ≤ n) {i j : Fin (n + 1)} + (hij : i < j) (f : R p) : E hij.ne f ∈ cycleGenerated p n (by omega) := by + induction f using Polynomial.induction_on' with + | add f g hf hg => + change Matrix.SpecialLinearGroup.transvection hij.ne (f + g) ∈ _ + rw [Matrix.SpecialLinearGroup.transvection_add] + exact (cycleGenerated p n (by omega)).mul_mem hf hg + | monomial r c => + rw [← Polynomial.C_mul_X_pow_eq_monomial] + apply scalar_root_mem + cases r with + | zero => simpa using upper_one_mem_generated p n (by omega) hij + | succ r => exact X_pow_mem_generated p n hn hij.ne r + +theorem X_polynomial_mem_generated (hn : 2 ≤ n) {i j : Fin (n + 1)} + (hij : i ≠ j) (f : R p) : + E hij (Polynomial.X * f) ∈ cycleGenerated p n (by omega) := by + induction f using Polynomial.induction_on' with + | add f g hf hg => + rw [mul_add] + change Matrix.SpecialLinearGroup.transvection hij (_ + _) ∈ _ + rw [Matrix.SpecialLinearGroup.transvection_add] + exact (cycleGenerated p n (by omega)).mul_mem hf hg + | monomial r c => + rw [← Polynomial.C_mul_X_pow_eq_monomial] + rw [mul_left_comm, ← pow_succ'] + exact scalar_root_mem p n (by omega) hij (X_pow_mem_generated p n hn hij r) c + +end + +open Elementary +variable (p n m : ℕ) [Fact p.Prime] + +def residue (hm : 1 ≤ m) : Trunc p m →+* ZMod p := + Ideal.Quotient.lift (powerIdeal p m) (Polynomial.evalRingHom 0) (by + change powerIdeal p m ≤ RingHom.ker (Polynomial.evalRingHom (R := ZMod p) 0) + apply Ideal.span_le.mpr + intro f hf + have hf' : f = Polynomial.X ^ m := by simpa using hf + subst f + simp [show m ≠ 0 by omega]) + +@[simp] theorem residue_mk (hm : 1 ≤ m) (f : R p) : + residue p m hm (Ideal.Quotient.mk (powerIdeal p m) f) = f.eval 0 := rfl + +theorem residue_one_isUnit (hm : 1 ≤ m) (a : Trunc p m) + (ha : residue p m hm a = 1) : IsUnit a := by + obtain ⟨f, rfl⟩ := Ideal.Quotient.mk_surjective a + have hf : (f - 1).eval 0 = 0 := by simpa using sub_eq_zero.mpr ha + have hdiv : Polynomial.X ∣ f - 1 := Polynomial.X_dvd_iff.mpr (by simpa [Polynomial.coeff_zero_eq_eval_zero] using hf) + obtain ⟨b, hb⟩ := hdiv + have he : Ideal.Quotient.mk (powerIdeal p m) f - 1 = + tbar p m * Ideal.Quotient.mk (powerIdeal p m) b := by + simpa only [map_sub, map_one, map_mul, tbar] using congrArg (Ideal.Quotient.mk (powerIdeal p m)) hb + have hn : IsNilpotent (Ideal.Quotient.mk (powerIdeal p m) f - 1) := by + rw [he] + refine ⟨m, ?_⟩ + rw [mul_pow, tbar_pow, zero_mul] + simpa only [sub_add_cancel] using hn.isUnit_add_one + +theorem map_E {A B : Type*} [CommRing A] [CommRing B] {a : ℕ} + (φ : A →+* B) {i j : Fin a} (hij : i ≠ j) (c : A) : + Matrix.SpecialLinearGroup.map φ (E hij c) = E hij (φ c) := by + exact map_transvection φ hij c + +def truncatedIwahori (hm : 1 ≤ m) : + Subgroup (Matrix.SpecialLinearGroup (Fin (n + 1)) (Trunc p m)) := + (upperUnitriangular p (n + 1)).comap (Matrix.SpecialLinearGroup.map (residue p m hm)) + +theorem truncatedIwahori_entries (hm : 1 ≤ m) + (g : Matrix.SpecialLinearGroup (Fin (n + 1)) (Trunc p m)) + (hg : g ∈ truncatedIwahori p n m hm) (i j : Fin (n + 1)) (hji : j ≤ i) : + residue p m hm (g i j) = if i = j then 1 else 0 := by + have := hg i j hji + simpa [Matrix.SpecialLinearGroup.map_apply_coe, RingHom.mapMatrix_apply, + Matrix.map_apply, Matrix.one_apply] using this + +theorem reduction_mem_truncatedIwahori (hm : 1 ≤ m) + {g : Matrix.SpecialLinearGroup (Fin (n + 1)) (R p)} (hg : g ∈ U p (n + 1)) : + Matrix.SpecialLinearGroup.map (Ideal.Quotient.mk (powerIdeal p m)) g ∈ + truncatedIwahori p n m hm := by + intro i j hji + have := hg i j hji + simpa [evalZero, Matrix.SpecialLinearGroup.map_apply_coe, RingHom.mapMatrix_apply, + Matrix.map_apply] using this + +def reducedGenerated (hn : 1 ≤ n) := + (cycleGenerated p n hn).map (Matrix.SpecialLinearGroup.map (Ideal.Quotient.mk (powerIdeal p m))) + +theorem reducedGenerated_le (hn : 1 ≤ n) (hm : 1 ≤ m) : + reducedGenerated p n m hn ≤ truncatedIwahori p n m hm := by + rintro _ ⟨g, hg, rfl⟩ + exact reduction_mem_truncatedIwahori p n m hm (cycleGenerated_le_U p n hn hg) + +theorem reducedGenerated_roots (hn : 2 ≤ n) (hm : 1 ≤ m) + (i j : Fin (n + 1)) (hij : i ≠ j) (c : Trunc p m) + (hc : j < i → residue p m hm c = 0) : + E hij c ∈ reducedGenerated p n m (by omega) := by + obtain ⟨f, rfl⟩ := Ideal.Quotient.mk_surjective c + refine ⟨E hij f, ?_, map_E _ hij f⟩ + by_cases hji : j < i + · have hf : Polynomial.X ∣ f := Polynomial.X_dvd_iff.mpr (by + have := hc hji + simpa [Polynomial.coeff_zero_eq_eval_zero] using this) + obtain ⟨b, rfl⟩ := hf + exact X_polynomial_mem_generated p n hn hij b + · exact upper_polynomial_mem_generated p n hn (lt_of_le_of_ne (le_of_not_gt hji) hij) f + +theorem truncatedIwahori_eq_generated (hn : 2 ≤ n) (hm : 1 ≤ m) : + truncatedIwahori p n m hm = reducedGenerated p n m (by omega) := by + apply le_antisymm + · exact iwahori_mem_of_roots (residue p m hm) _ _ + (reducedGenerated_le p n m (by omega) hm) + (truncatedIwahori_entries p n m hm) (residue_one_isUnit p m hm) + (reducedGenerated_roots p n m hn hm) + · exact reducedGenerated_le p n m (by omega) hm + +theorem quotient_locals_generate (hn : 2 ≤ n) (hm : 1 ≤ m) : + Subgroup.closure (⋃ i, (reducedLocalGroup p n (by omega) m i : Set (Gquot p (n + 1) m))) = ⊤ := by + let K : Subgroup (Gquot p (n + 1) m) := + Subgroup.closure (⋃ i, (reducedLocalGroup p n (by omega) m i : Set (Gquot p (n + 1) m))) + let e : Gquot p (n + 1) m →* Matrix.SpecialLinearGroup (Fin (n + 1)) (Trunc p m) := + QuotientGroup.kerLift (uReduction p (n + 1) m) + have he : Function.Injective e := QuotientGroup.kerLift_injective _ + have hgen : reducedGenerated p n m (by omega) ≤ K.map e := by + apply (Subgroup.map_le_iff_le_comap).mpr + apply (Subgroup.closure_le _).mpr + rintro _ ⟨j, rfl⟩ + obtain ⟨cut, hcut⟩ : ∃ cut : Fin (n + 1), cut ≠ j := by + by_cases hj : j = 0 + · refine ⟨Fin.last n, ?_⟩ + rw [hj] + intro h + have := congrArg Fin.val h + simp only [Fin.val_last, Fin.val_zero] at this + omega + · exact ⟨0, fun h => hj h.symm⟩ + let u : U p (n + 1) := ⟨cycleRoot p n (by omega) j, cycleRoot_mem_U p n (by omega) j⟩ + have hu : u ∈ uLocalGroup p n (by omega) cut := + Subgroup.subset_closure ⟨j, hcut.symm, rfl⟩ + have hq : QuotientGroup.mk' (uReduction p (n + 1) m).ker u ∈ K := + Subgroup.subset_closure (Set.mem_iUnion.mpr ⟨cut, ⟨u, hu, rfl⟩⟩) + exact ⟨_, hq, rfl⟩ + apply top_le_iff.mp + intro q _ + induction q using QuotientGroup.induction_on with + | H u => + have hu := reduction_mem_truncatedIwahori p n m hm u.property + rw [truncatedIwahori_eq_generated p n m hn hm] at hu + obtain ⟨v, hv, hev⟩ := hgen hu + have hveq : v = QuotientGroup.mk u := he hev + exact hveq ▸ hv + +end CoboundaryExpanders.Construction + +namespace CoboundaryExpanders +lemma sqrt_div_le_of_sq {p t : ℝ} (hp : 0 < p) (ht : 0 < t) (h : 1 ≤ t^2*p) : + Real.sqrt p/p ≤ t := by + have hs := Real.sqrt_nonneg p + have he := Real.sq_sqrt hp.le + have hsq : 1 ≤ (t*Real.sqrt p)^2 := by simpa only [mul_pow,he] using h + have hpos : 0 ≤ t*Real.sqrt p := mul_nonneg ht.le hs + have hb : 1 ≤ t*Real.sqrt p := by nlinarith + apply (div_le_iff₀ hp).mpr + calc + Real.sqrt p = 1*Real.sqrt p := by ring + _ ≤ (t*Real.sqrt p)*Real.sqrt p := mul_le_mul_of_nonneg_right hb hs + _ = t*p := by nlinarith [mul_assoc t (Real.sqrt p) (Real.sqrt p)] + +theorem exists_spectral_threshold (r : ℕ) {eps : ℝ} (heps : 0 < eps) : + ∃ Q : ℕ, ∀ p : ℕ, Q < p → Real.sqrt (p:ℝ)/(p:ℝ) ≤ eps/(2:ℝ)^r := by + let t := eps/(2:ℝ)^r + have ht : 0 < t := by dsimp [t]; positivity + obtain ⟨Q,hQ⟩ := exists_nat_gt (1/t^2) + refine ⟨Q,?_⟩ + intro p hp + have hp' : 0 < (p:ℝ) := by exact_mod_cast (show 0 < p by omega) + have hb : 1/t^2 ≤ (p:ℝ) := hQ.le.trans (by exact_mod_cast hp.le) + have hc : 1 ≤ t^2*(p:ℝ) := by + have h := (div_le_iff₀ (sq_pos_of_pos ht)).mp hb + simpa only [mul_comm] using h + exact sqrt_div_le_of_sq hp' ht hc +end CoboundaryExpanders + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains FiniteWeights Cone +open scoped Pointwise +variable {G I : Type} [Group G] [Fintype G] [DecidableEq I] [Fintype I] (H : I → Subgroup G) +noncomputable instance vertexFintype : Fintype (Vertex H) := Fintype.ofFinite _ + +lemma finite_pure : Pure (complex H) (Fintype.card I) := by + obtain ⟨hne,h⟩ := coset_pure H + constructor + · obtain ⟨t,ht,he⟩ := hne + exact ⟨t,(mem_level _ _ _).mpr ⟨ht,he⟩⟩ + · intro s hs + obtain ⟨t,ht,he,hst⟩ := h s hs + exact ⟨t,(mem_level _ _ _).mpr ⟨ht,he⟩,hst⟩ + +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.InfiniteChains +open Cone FiniteWeights +variable {V : Type} [Fintype V] [DecidableEq V] + +lemma FiniteWeights.linkEdge_empty (X : CoboundaryExpanders.InfiniteChains.Complex V) (N : ℕ) : + FatLadders.linkEdge (fun t => (cofaces X N t : ℝ)) ∅ = edge X N := by + funext x y + simp [FatLadders.linkEdge,edge] + +lemma TopSpectral.changeFintype {V : Type} [DecidableEq V] {fa : Fintype V} + (fb : Fintype V) {X : CoboundaryExpanders.InfiniteChains.Complex V} {N : ℕ} {lam : ℝ} + (ht : @TopSpectral V fa _ X N lam) : @TopSpectral V fb _ X N lam := by + cases Subsingleton.elim fa fb + exact ht + +theorem mixing_of_top_cones {X : CoboundaryExpanders.InfiniteChains.Complex V} {N R : ℕ} (hp : Pure X N) + (hc : EdgeMixing.Connected (edge X N)) (hcones : ProperLinkCones X N R) + {eps lam : ℝ} (h0 : 0 ≤ eps) (h1 : eps ≤ 1) + (htop : TopSpectral X N lam) (hlam : lam ≤ eps/2^(N-2)) : + FatLadders.LocalMixing (fun t => (cofaces X N t : ℝ)) N eps := by + apply FatLadders.localMixing_of_rayleigh (cofaces_balanced X N) h0 + apply FatLadders.all_link_rayleigh (cofaces_balanced X N) h0 h1 + · intro s hr hs + have hs' : s ∈ X.faces := (cofaces_pos_iff hp s).mp (by exact_mod_cast hs) + by_cases he : s.Nonempty + · rw [linkEdge_eq X hs' (by omega)] + exact (hcones s he hs' (by omega)).some.spectralConnected (by omega) (pure_link hp hs') + · have he' : s = ∅ := Finset.not_nonempty_iff_eq_empty.mp he + subst s + rwa [linkEdge_empty X N] + · intro s hr hs + have hs' : s ∈ X.faces := (cofaces_pos_iff hp s).mp (by exact_mod_cast hs) + rw [linkEdge_eq X hs' (by omega)] + have he : N-s.card = 2 := by omega + rw [he] + exact EdgeMixing.rayleigh_mono (edge_nonneg _ _) (htop s hs' hr) hlam +end CoboundaryExpanders.InfiniteChains + +namespace CoboundaryExpanders.TypedCosetFaces +open InfiniteChains Cone FiniteWeights +variable {G I : Type} [Group G] [Fintype G] [DecidableEq I] [Fintype I] +lemma coset_mixing (H : I → Subgroup G) {N R : ℕ} (hN : Fintype.card I = N) + (hgen : Subgroup.closure (⋃ i, (H i : Set G)) = ⊤) (base : I) + {eps lam : ℝ} (h0 : 0 ≤ eps) (h1 : eps ≤ 1) + (hcones : ProperLinkCones (complex H) N R) (ht : TopSpectral (complex H) N lam) + (hlam : lam ≤ eps / 2^(N-2)) : + FatLadders.LocalMixing (fun t => (cofaces (complex H) N t : ℝ)) N eps := by + have hP : Pure (complex H) N := hN ▸ finite_pure H + exact mixing_of_top_cones hP (spectralConnected_of_generate H hP hgen base) + hcones h0 h1 ht hlam +end CoboundaryExpanders.TypedCosetFaces + +namespace CoboundaryExpanders.Construction +open InfiniteChains Cone FiniteWeights TypedCosetFaces + +lemma actual_mixing_level (n : ℕ) (hn : 2 ≤ n) (p : ℕ) [Fact p.Prime] + (m : ℕ) (hm : 2 ≤ m) {R : ℕ} {eps : ℝ} (h0 : 0 ≤ eps) (h1 : eps ≤ 1) + (hcones : ProperLinkCones (TypedCosetFaces.complex (reducedLocalGroup p n (by omega) m)) (n+1) R) + (hlam : Real.sqrt p / p ≤ eps / 2^(n+1-2)) : + letI : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + FatLadders.LocalMixing + (fun t => (cofaces (TypedCosetFaces.complex (reducedLocalGroup p n (by omega) m)) (n+1) t : ℝ)) (n+1) eps := by + let : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + have htop := actual_topSpectral n hn p m hm + have ht := TopSpectral.changeFintype (vertexFintype (reducedLocalGroup p n (by omega) m)) htop + exact coset_mixing (reducedLocalGroup p n (by omega) m) (Fintype.card_fin _) + (quotient_locals_generate p n m hn (by omega)) 0 h0 h1 hcones + ht hlam + +lemma actual_mixing_mono (n : ℕ) (hn : 1 ≤ n) (p : ℕ) [Fact p.Prime] (m : ℕ) + {eps mu : ℝ} (h : eps ≤ mu) : + letI : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + FatLadders.LocalMixing + (fun t => (cofaces (TypedCosetFaces.complex (reducedLocalGroup p n hn m)) (n+1) t : ℝ)) (n+1) eps → + FatLadders.LocalMixing + (fun t => (cofaces (TypedCosetFaces.complex (reducedLocalGroup p n hn m)) (n+1) t : ℝ)) (n+1) mu := by + let : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + intro hmix F s hs t ht hb + apply (hmix F s hs t ht hb).trans + apply mul_le_mul_of_nonneg_right _ (FatLadders.starNorm_nonneg (fun s => Nat.cast_nonneg _) _ _ _) + exact mul_le_mul_of_nonneg_right (add_le_add_right h t) (Nat.cast_nonneg _) + +theorem uniform_actual_mixing (n : ℕ) (hn : 2 ≤ n) {eps : ℝ} (heps : 0 < eps) : + ∃ Q : ℕ, ∀ p : ℕ, ∀ _ : Fact p.Prime, Q < p → ∀ m : ℕ, 2 ≤ m → + letI : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + FatLadders.LocalMixing + (fun t => (cofaces (TypedCosetFaces.complex (reducedLocalGroup p n (by omega) m)) (n+1) t : ℝ)) + (n+1) eps := by + obtain ⟨Q₀,R,hcones⟩ := uniform_actual_proper_link_cones n (by omega) + obtain ⟨Q₁,hspectral⟩ := exists_spectral_threshold (n+1-2) (lt_min heps zero_lt_one) + refine ⟨max Q₀ Q₁,?_⟩ + intro p hp hq m hm + exact actual_mixing_mono n (by omega) p m (min_le_left eps 1) + (actual_mixing_level n hn p m hm (le_of_lt (lt_min heps zero_lt_one)) + (min_le_right eps 1) (hcones p hp ((le_max_left _ _).trans_lt hq) m hm) + (hspectral p ((le_max_right _ _).trans_lt hq))) +end CoboundaryExpanders.Construction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Realization.lean b/lean/OAI/Combinatorics/Coboundary/Realization.lean new file mode 100644 index 0000000000000000000000000000000000000000..666c79db7585d5ecceea2192e68eaa21d9224895 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Realization.lean @@ -0,0 +1,735 @@ +import OAI.Combinatorics.Coboundary.Complex +import OAI.Combinatorics.Coboundary.Expansion +import OAI.GroupTheory.Congruence.Resolution + +namespace OAI + +/-! +Finite labeled coset complexes, purity, growth, incidence bounds, and weighted expansion reduction. +-/ + +noncomputable section +open CategoryTheory +open scoped BigOperators +open CategoryTheory Finsupp +open CategoryTheory Finsupp MonoidalCategory +open scoped BigOperators Matrix +open scoped Matrix +open scoped MonoidAlgebra +open CategoryTheory CategoryTheory.Limits +open Filter + +namespace CoboundaryExpanders.CosetConstruction + +section + +open CoboundaryExpanders.Complex + +variable {G : Type*} [Group G] [Fintype G] {n : ℕ} + +abbrev Vertex (H : Fin (n + 1) → Subgroup G) := (i : Fin (n + 1)) × (G ⧸ H i) + +noncomputable instance vertexFintype (H : Fin (n + 1) → Subgroup G) : + Fintype (Vertex H) := Fintype.ofFinite _ + +def labelEquiv (H : Fin (n + 1) → Subgroup G) : + Vertex H ≃ Fin (Fintype.card (Vertex H)) := Fintype.equivFin _ + +def vertex (H : Fin (n + 1) → Subgroup G) (g : G) (i : Fin (n + 1)) : + Fin (Fintype.card (Vertex H)) := labelEquiv H ⟨i, QuotientGroup.mk g⟩ + +theorem vertex_surjective (H : Fin (n + 1) → Subgroup G) + (v : Fin (Fintype.card (Vertex H))) : ∃ i g, vertex H g i = v := by + obtain ⟨⟨i, c⟩, rfl⟩ := (labelEquiv H).surjective v + induction c using QuotientGroup.induction_on with + | H g => exact ⟨i, g, rfl⟩ + +theorem vertex_type_eq {H : Fin (n + 1) → Subgroup G} {g h : G} {i j : Fin (n + 1)} + (heq : vertex H g i = vertex H h j) : i = j := + congrArg Sigma.fst ((labelEquiv H).injective heq) + +theorem vertex_injective (H : Fin (n + 1) → Subgroup G) (g : G) : + Function.Injective (vertex H g) := fun _ _ heq => vertex_type_eq heq + +theorem vertex_eq_iff (H : Fin (n + 1) → Subgroup G) (g h : G) (i : Fin (n + 1)) : + vertex H g i = vertex H h i ↔ g⁻¹ * h ∈ H i := by + change labelEquiv H ⟨i, (g : G ⧸ H i)⟩ = labelEquiv H ⟨i, (h : G ⧸ H i)⟩ ↔ _ + rw [Equiv.apply_eq_iff_eq] + simpa using (QuotientGroup.eq (s := H i) (a := g) (b := h)) + +def chamber (H : Fin (n + 1) → Subgroup G) (g : G) : + Finset (Fin (Fintype.card (Vertex H))) := Finset.univ.image (vertex H g) + +@[simp] theorem mem_chamber {H : Fin (n + 1) → Subgroup G} {g : G} {v} : + v ∈ chamber H g ↔ ∃ i, vertex H g i = v := by + simp [chamber] + +@[simp] theorem vertex_mem_chamber (H : Fin (n + 1) → Subgroup G) (g : G) (i) : + vertex H g i ∈ chamber H g := mem_chamber.mpr ⟨i, rfl⟩ + +@[simp] theorem card_chamber (H : Fin (n + 1) → Subgroup G) (g : G) : + (chamber H g).card = n + 1 := by + rw [chamber, Finset.card_image_of_injective _ (vertex_injective H g)] + simp + +@[reducible] def complex (H : Fin (n + 1) → Subgroup G) : Complex where + vertexCount := Fintype.card (Vertex H) + faces := Finset.univ.biUnion (fun g : G => (chamber H g).powerset) + empty_mem := Finset.mem_biUnion.mpr ⟨1, Finset.mem_univ _, + Finset.mem_powerset.mpr (Finset.empty_subset _)⟩ + downward := by + intro σ τ hσ hτ + obtain ⟨g, _, hg⟩ := Finset.mem_biUnion.mp hσ + exact Finset.mem_biUnion.mpr ⟨g, Finset.mem_univ _, + Finset.mem_powerset.mpr (hτ.trans (Finset.mem_powerset.mp hg))⟩ + vertex_mem := by + intro v + obtain ⟨i, g, rfl⟩ := vertex_surjective H v + exact Finset.mem_biUnion.mpr ⟨g, Finset.mem_univ _, + Finset.mem_powerset.mpr (Finset.singleton_subset_iff.mpr (vertex_mem_chamber H g i))⟩ + +@[simp] theorem mem_faces {H : Fin (n + 1) → Subgroup G} {σ} : + σ ∈ (complex H).faces ↔ ∃ g, σ ⊆ chamber H g := by + simp [complex] + +@[simp] theorem chamber_mem_facesOf (H : Fin (n + 1) → Subgroup G) (g : G) : + chamber H g ∈ (complex H).facesOf n := by + exact (mem_facesOf _ _ _).mpr ⟨mem_faces.mpr ⟨g, Finset.Subset.refl _⟩, + card_chamber H g⟩ + +theorem pure (H : Fin (n + 1) → Subgroup G) : (complex H).Pure n := by + refine ⟨⟨chamber H 1, chamber_mem_facesOf H 1⟩, ?_⟩ + intro σ hσ + obtain ⟨g, hg⟩ := mem_faces.mp hσ + exact ⟨chamber H g, chamber_mem_facesOf H g, hg⟩ + +abbrev Walk (H : Fin (n + 1) → Subgroup G) + (v w : Fin (Fintype.card (Vertex H))) : Prop := + Relation.ReflTransGen (fun a b => a ≠ b ∧ {a, b} ∈ (complex H).faces) v w + +theorem walk_of_common_chamber {H : Fin (n + 1) → Subgroup G} {g : G} + {v w : Fin (Fintype.card (Vertex H))} (hv : v ∈ chamber H g) (hw : w ∈ chamber H g) : + Walk H v w := by + by_cases heq : v = w + · subst w + exact Relation.ReflTransGen.refl + · exact Relation.ReflTransGen.single ⟨heq, + mem_faces.mpr ⟨g, by simpa only [Finset.insert_subset_iff, Finset.singleton_subset_iff] using And.intro hv hw⟩⟩ + +theorem walk_symm {H : Fin (n + 1) → Subgroup G} {v w} + (h : Walk H v w) : Walk H w v := by + induction h with + | refl => exact Relation.ReflTransGen.refl + | tail _ hab ih => + exact (Relation.ReflTransGen.single ⟨hab.1.symm, + by simpa only [Finset.pair_comm] using hab.2⟩).trans ih + +theorem walk_vertex_mul (H : Fin (n + 1) → Subgroup G) + (hgen : Subgroup.closure (⋃ i, (H i : Set G)) = ⊤) (x : G) : + ∀ g : G, Walk H (vertex H g 0) (vertex H (g * x) 0) := by + have hx : x ∈ Subgroup.closure (⋃ i, (H i : Set G)) := by + rw [hgen] + exact Subgroup.mem_top x + induction hx using Subgroup.closure_induction with + | mem x hx => + obtain ⟨i, hxi⟩ := Set.mem_iUnion.mp hx + intro g + have hcommon : vertex H g i = vertex H (g * x) i := + (vertex_eq_iff H g (g * x) i).mpr (by simpa using hxi) + have hleft := walk_of_common_chamber (vertex_mem_chamber H g 0) + (vertex_mem_chamber H g i) + have hright := walk_of_common_chamber (vertex_mem_chamber H (g * x) i) + (vertex_mem_chamber H (g * x) 0) + rw [← hcommon] at hright + exact hleft.trans hright + | one => + intro g + simpa only [mul_one] using + (Relation.ReflTransGen.refl : Walk H (vertex H g 0) (vertex H g 0)) + | mul x y hx hy ihx ihy => + intro g + simpa only [mul_assoc] using (ihx g).trans (ihy (g * x)) + | inv x hx ih => + intro g + simpa only [mul_assoc, inv_mul_cancel, mul_one] using walk_symm (ih (g * x⁻¹)) + +theorem connected (H : Fin (n + 1) → Subgroup G) + (hgen : Subgroup.closure (⋃ i, (H i : Set G)) = ⊤) : + (complex H).Connected := by + refine ⟨⟨vertex H 1 0⟩, ?_⟩ + intro v w + obtain ⟨i, g, rfl⟩ := vertex_surjective H v + obtain ⟨j, h, rfl⟩ := vertex_surjective H w + have hleft := walk_of_common_chamber (vertex_mem_chamber H g i) + (vertex_mem_chamber H g 0) + have hright := walk_of_common_chamber (vertex_mem_chamber H h 0) + (vertex_mem_chamber H h j) + have hmid := walk_vertex_mul H hgen (g⁻¹ * h) g + simp only [← mul_assoc, mul_inv_cancel, one_mul] at hmid + exact hleft.trans (hmid.trans hright) + +noncomputable local instance subgroupFintype (K : Subgroup G) : Fintype K := + Fintype.ofFinite K + +def incidentInChamber (H : Fin (n + 1) → Subgroup G) (g : G) + (v : Fin (Fintype.card (Vertex H))) (d : ℕ) := + ((chamber H g).powersetCard (d + 1)).filter (v ∈ ·) + +@[simp] theorem mem_incidentInChamber {H : Fin (n + 1) → Subgroup G} {g v d σ} : + σ ∈ incidentInChamber H g v d ↔ σ ⊆ chamber H g ∧ σ.card = d + 1 ∧ v ∈ σ := by + simp [incidentInChamber, Finset.mem_powersetCard, and_assoc] + +theorem card_incidentInChamber (H : Fin (n + 1) → Subgroup G) (g : G) + (v : Fin (Fintype.card (Vertex H))) (d : ℕ) (hv : v ∈ chamber H g) : + (incidentInChamber H g v d).card = Nat.choose n d := by + have h := Finset.card_filter_powersetCard_subset {v} (chamber H g) (d + 1) + (Finset.singleton_subset_iff.mpr hv) (by simp) + simpa [incidentInChamber] using h + +theorem incident_faces_subset (H : Fin (n + 1) → Subgroup G) (g : G) + (i : Fin (n + 1)) (d : ℕ) : + ((complex H).facesOf d).filter (vertex H g i ∈ ·) ⊆ + Finset.univ.biUnion (fun h : H i => + incidentInChamber H (g * h) (vertex H g i) d) := by + intro σ hσ + obtain ⟨hσ, hv⟩ := Finset.mem_filter.mp hσ + obtain ⟨hface, hcard⟩ := (mem_facesOf _ _ _).mp hσ + obtain ⟨k, hk⟩ := mem_faces.mp hface + obtain ⟨j, hj⟩ := mem_chamber.mp (hk hv) + have hji : j = i := vertex_type_eq hj + subst j + have hmem : g⁻¹ * k ∈ H i := (vertex_eq_iff H g k i).mp hj.symm + refine Finset.mem_biUnion.mpr ⟨⟨g⁻¹ * k, hmem⟩, Finset.mem_univ _, ?_⟩ + apply mem_incidentInChamber.mpr + simpa only [mul_inv_cancel_left] using And.intro hk (And.intro hcard hv) + +theorem topDegree_le (H : Fin (n + 1) → Subgroup G) (g : G) + (i : Fin (n + 1)) (d : ℕ) : + (complex H).topDegree d (vertex H g i) ≤ Nat.card (H i) * Nat.choose n d := by + calc + _ ≤ (Finset.univ.biUnion (fun h : H i => + incidentInChamber H (g * h) (vertex H g i) d)).card := + Finset.card_le_card (incident_faces_subset H g i d) + _ ≤ ∑ h : H i, (incidentInChamber H (g * h) (vertex H g i) d).card := + Finset.card_biUnion_le + _ = Nat.card (H i) * Nat.choose n d := by + have hc (h : H i) : vertex H g i ∈ chamber H (g * h) := by + rw [(vertex_eq_iff H g (g * h) i).mpr (by simp)] + exact vertex_mem_chamber _ _ _ + simp_rw [card_incidentInChamber H _ _ d (hc _)] + simp [Nat.card_eq_fintype_card] + +theorem vertexCount_eq_sum_index (H : Fin (n + 1) → Subgroup G) : + (complex H).vertexCount = ∑ i, (H i).index := by + change Fintype.card (Vertex H) = _ + rw [← Nat.card_eq_fintype_card, Nat.card_sigma] + simp only [Subgroup.index_eq_card] + +theorem vertexCount_mul (H : Fin (n + 1) → Subgroup G) (M : ℕ) + (hM : ∀ i, Nat.card (H i) = M) : + (complex H).vertexCount * M = (n + 1) * Nat.card G := by + rw [vertexCount_eq_sum_index, Finset.sum_mul] + have heq (i : Fin (n + 1)) : (H i).index * M = Nat.card G := by + rw [← hM i, mul_comm] + exact (H i).card_mul_index + simp_rw [heq] + simp + +end + +variable {G : Type} [Group G] [Fintype G] {n : ℕ} + +theorem vertexCount_mul_lower (H : Fin (n + 1) → Subgroup G) (M : ℕ) + (hM : ∀ i, Nat.card (H i) ≤ M) : + (n + 1) * Nat.card G ≤ (complex H).vertexCount * M := by + rw [vertexCount_eq_sum_index, Finset.sum_mul] + calc + _ = ∑ i : Fin (n + 1), (H i).index * Nat.card (H i) := by + simp only [mul_comm (H _).index, Subgroup.card_mul_index] + simp + _ ≤ _ := Finset.sum_le_sum (fun i _ => Nat.mul_le_mul_left _ (hM i)) + +end CoboundaryExpanders.CosetConstruction + +namespace CoboundaryExpanders.Construction + +section +open Filter CosetConstruction _root_.OAI.CoboundaryExpanders.Complex +variable (p n : ℕ) [Fact p.Prime] + +def localBound : ℕ := Nat.card (Matrix.GeneralLinearGroup (Fin (n + 1)) (ZMod p)) + +theorem localBound_pos : 0 < localBound p n := Nat.card_pos + +def finiteCosetComplex (hn : 1 ≤ n) (m : ℕ) : Complex := + letI : Fintype (Gquot p (n + 1) m) := Fintype.ofFinite _ + CosetConstruction.complex (reducedLocalGroup p n hn m) + +def finiteSkeleton (hn : 1 ≤ n) (d m : ℕ) : Complex := + (finiteCosetComplex p n hn (m + 2)).skeleton d + +theorem finiteCosetComplex_pure (hn : 1 ≤ n) (m : ℕ) : + (finiteCosetComplex p n hn m).Pure n := by + let : Fintype (Gquot p (n + 1) m) := Fintype.ofFinite _ + exact CosetConstruction.pure _ + +theorem finiteSkeleton_pure (hn : 1 ≤ n) {d : ℕ} (hd : d ≤ n) (m : ℕ) : + (finiteSkeleton p n hn d m).Pure d := by + exact skeleton_pure (finiteCosetComplex_pure p n hn (m + 2)) hd + +theorem finiteCosetComplex_degree (hn : 1 ≤ n) (m d : ℕ) + (v : Fin (finiteCosetComplex p n hn m).vertexCount) : + (finiteCosetComplex p n hn m).topDegree d v ≤ localBound p n * Nat.choose n d := by + let : Fintype (Gquot p (n + 1) m) := Fintype.ofFinite _ + obtain ⟨i, g, rfl⟩ := vertex_surjective (reducedLocalGroup p n hn m) v + exact (topDegree_le _ _ _ _).trans + (Nat.mul_le_mul_right _ (reducedLocalGroup_card_le p n hn m i)) + +theorem finiteSkeleton_degree (hn : 1 ≤ n) (d m : ℕ) + (v : Fin (finiteSkeleton p n hn d m).vertexCount) : + (finiteSkeleton p n hn d m).topDegree d v ≤ localBound p n * Nat.choose n d := by + classical + change ((finiteCosetComplex p n hn (m + 2)).skeleton d).topDegree d v ≤ _ + unfold Complex.topDegree + rw [skeleton_facesOf le_rfl] + exact finiteCosetComplex_degree p n hn (m + 2) d v + +theorem finiteCosetComplex_growth_bound (hn : 1 ≤ n) (m : ℕ) : + p ^ m ≤ (finiteCosetComplex p n hn m).vertexCount * localBound p n := by + let : Fintype (Gquot p (n + 1) m) := Fintype.ofFinite _ + exact (gquot_card_lower p n hn m).trans + ((Nat.le_mul_of_pos_left _ (Nat.succ_pos n)).trans + (vertexCount_mul_lower _ (localBound p n) (reducedLocalGroup_card_le p n hn m))) + +theorem finiteSkeleton_growth (hn : 1 ≤ n) (d : ℕ) : + Tendsto (fun m => (finiteSkeleton p n hn d m).vertexCount) atTop atTop := by + apply tendsto_atTop.mpr + intro b + apply eventually_atTop.mpr + refine ⟨b * localBound p n, fun m hm => ?_⟩ + apply (Nat.mul_le_mul_right_iff (localBound_pos p n)).mp + exact hm.trans ((Nat.le_add_right m 2).trans + ((Nat.le_of_lt (Nat.lt_pow_self (Fact.out : p.Prime).one_lt)).trans + (finiteCosetComplex_growth_bound p n hn (m + 2)))) + +theorem finiteSkeleton_vertex_faces_growth (hn : 1 ≤ n) (d : ℕ) : + Tendsto (fun m => ((finiteSkeleton p n hn d m).facesOf 0).card) atTop atTop := by + simpa only [Complex.card_facesOf_zero] using finiteSkeleton_growth p n hn d + +theorem constructed_pure_bounded_growing (d : ℕ) (hd : 3 ≤ d) : + ∃ D : ℕ, (∀ m, (finiteSkeleton p (2 * d) (by omega) d m).Pure d) ∧ + Tendsto (fun m => ((finiteSkeleton p (2 * d) (by omega) d m).facesOf 0).card) + atTop atTop ∧ + ∀ m (v : Fin (finiteSkeleton p (2 * d) (by omega) d m).vertexCount), + (finiteSkeleton p (2 * d) (by omega) d m).topDegree d v ≤ D := by + refine ⟨localBound p (2 * d) * Nat.choose (2 * d) d, ?_, ?_, ?_⟩ + · exact fun m => finiteSkeleton_pure p (2 * d) (by omega) (by omega) m + · exact finiteSkeleton_vertex_faces_growth p (2 * d) (by omega) d + · exact fun m v => finiteSkeleton_degree p (2 * d) (by omega) d m v + +end + +open Filter _root_.OAI.CoboundaryExpanders.Complex +variable (p n : ℕ) [Fact p.Prime] + +theorem finiteCosetComplex_connected (hn : 2 ≤ n) (m : ℕ) (hm : 1 ≤ m) : + (finiteCosetComplex p n (by omega) m).Connected := by + let : Fintype (Gquot p (n + 1) m) := Fintype.ofFinite _ + exact CosetConstruction.connected _ (quotient_locals_generate p n m hn hm) + +theorem finiteSkeleton_connected (hn : 2 ≤ n) (d m : ℕ) (hd : 1 ≤ d) : + (finiteSkeleton p n (by omega) d m).Connected := by + exact skeleton_connected (finiteCosetComplex_connected p n hn (m + 2) (by omega)) hd + +theorem constructed_connected_pure_bounded_growing (d : ℕ) (hd : 3 ≤ d) : + ∃ D : ℕ, + (∀ m, (finiteSkeleton p (2 * d) (by omega) d m).Pure d ∧ + (finiteSkeleton p (2 * d) (by omega) d m).Connected) ∧ + Tendsto (fun m => ((finiteSkeleton p (2 * d) (by omega) d m).facesOf 0).card) + atTop atTop ∧ + ∀ m (v : Fin (finiteSkeleton p (2 * d) (by omega) d m).vertexCount), + (finiteSkeleton p (2 * d) (by omega) d m).topDegree d v ≤ D := by + obtain ⟨D, hpure, hgrowth, hdegree⟩ := constructed_pure_bounded_growing p d hd + exact ⟨D, fun m => ⟨hpure m, finiteSkeleton_connected p (2 * d) (by omega) d m (by omega)⟩, + hgrowth, hdegree⟩ + +theorem finiteSkeleton_zero_cohomology (hn : 2 ≤ n) (d m : ℕ) (hd : 1 ≤ d) : + (finiteSkeleton p n (by omega) d m).cocycles 0 = + (finiteSkeleton p n (by omega) d m).coboundaries 0 := + cocycles_zero_eq_coboundaries_of_connected (finiteSkeleton_connected p n hn d m hd) + +end CoboundaryExpanders.Construction + +namespace CoboundaryExpanders.Complex +local instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i + +abbrev Chain (X : Complex) (i : ℕ) := Module.Dual (ZMod 2) (X.Cochain i) + +def chainBasis (X : Complex) (i : ℕ) : + Module.Basis (X.Face i) (ZMod 2) (X.Chain i) := + (Pi.basisFun (ZMod 2) (X.Face i)).dualBasis + +@[simp] theorem chainBasis_apply (X : Complex) (i : ℕ) (σ : X.Face i) + (f : X.Cochain i) : X.chainBasis i σ f = f σ := by + exact (Pi.basisFun (ZMod 2) (X.Face i)).dualBasis_apply σ f + +def boundaryLinear (X : Complex) (i : ℕ) : X.Chain (i + 1) →ₗ[ZMod 2] X.Chain i := + (X.coboundaryLinear i).dualMap + +@[simp] theorem boundary_on_face (X : Complex) (i : ℕ) (τ : X.Face (i + 1)) : + X.boundaryLinear i (X.chainBasis (i + 1) τ) = + ∑ σ : X.Face i, if σ.val ⊆ τ.val then X.chainBasis i σ else 0 := by + apply LinearMap.ext + intro f + change X.chainBasis (i + 1) τ (X.coboundary i f) = _ + rw [chainBasis_apply] + simp only [coboundary, LinearMap.sum_apply] + apply Finset.sum_congr rfl + intro σ _ + split_ifs <;> simp + +@[simp] theorem boundary_boundary (X : Complex) (i : ℕ) : + (X.boundaryLinear i).comp (X.boundaryLinear (i + 1)) = 0 := by + apply LinearMap.ext + intro c + apply LinearMap.ext + intro f + change c (X.coboundary (i + 1) (X.coboundary i f)) = 0 + rw [coboundary_coboundary, map_zero] + +open CategoryTheory + +def chainComplex (X : Complex) : ChainComplex (ModuleCat (ZMod 2)) ℕ := + ChainComplex.of (fun i => ModuleCat.of (ZMod 2) (X.Chain i)) + (fun i => ModuleCat.ofHom (X.boundaryLinear i)) + (fun i => ModuleCat.hom_ext (X.boundary_boundary i)) + +@[simp] theorem chainComplex_d (X : Complex) (i : ℕ) : + X.chainComplex.d (i + 1) i = ModuleCat.ofHom (X.boundaryLinear i) := + by simp only [chainComplex, ChainComplex.of_d] + +theorem cocycles_eq_coboundaries_of_homology_isZero (X : Complex) (i : ℕ) + (homologyZero : Limits.IsZero (X.chainComplex.homology (i + 1))) : + X.cocycles (i + 1) = X.coboundaries (i + 1) := by + have he := (HomologicalComplex.exactAt_iff_isZero_homology _ _).mpr homologyZero + rw [HomologicalComplex.exactAt_iff' _ (i + 2) (i + 1) i (by simp) (by simp)] at he + have hr := he.moduleCat_range_eq_ker + change LinearMap.range (X.chainComplex.d (i + 2) (i + 1)).hom = + LinearMap.ker (X.chainComplex.d (i + 1) i).hom at hr + rw [chainComplex_d, chainComplex_d] at hr + change LinearMap.range (X.boundaryLinear (i + 1)) = LinearMap.ker (X.boundaryLinear i) at hr + unfold boundaryLinear at hr + rw [LinearMap.range_dualMap_eq_dualAnnihilator_ker, + LinearMap.ker_dualMap_eq_dualAnnihilator_range] at hr + have hh := Subspace.dualAnnihilator_inj.mp hr + change LinearMap.ker (X.coboundaryLinear (i + 1)) = + LinearMap.range (X.coboundaryLinear i) at hh + ext f + change (X.coboundaryLinear (i + 1) f = 0) ↔ ∃ g, X.coboundary i g = f + exact Set.ext_iff.mp (congrArg (fun W : Submodule (ZMod 2) (X.Cochain (i + 1)) => W.carrier) hh) f + +end CoboundaryExpanders.Complex + +namespace CoboundaryExpanders.InfiniteChains.Complex +variable {V : Type} [DecidableEq V] [Finite V] (X : InfiniteChains.Complex V) + +instance finiteFaceFintype (n : ℕ) : Fintype (X.Face n) := Fintype.ofFinite _ + +lemma boundary_single_subfaces (n : ℕ) (s : X.Face (n+1)) (r : k) : + X.boundary n (Finsupp.single s r) = + ∑ t : X.Face n, if t.val ⊆ s.val then Finsupp.single t r else 0 := by + classical + rw [boundary_single, ← Finset.sum_filter] + apply Finset.sum_bij (fun (v : ↥s.val) _ => X.erase n s v) + · intro v _ + simp only [Finset.mem_filter, Finset.mem_univ, true_and] + exact Finset.erase_subset _ _ + · intro a _ b _ he + apply Subtype.ext + exact (Finset.erase_inj s.val a.property).mp (congrArg Subtype.val he) + · intro t ht + have hsub : t.val ⊆ s.val := (Finset.mem_filter.mp ht).2 + have hcard : (s.val \ t.val).card = 1 := by + rw [Finset.card_sdiff_of_subset hsub, s.property.2,t.property.2] + omega + obtain ⟨v,hv,he⟩ := (Finset.covBy_iff_card_sdiff_eq_one.mpr ⟨hsub,hcard⟩).exists_finset_erase + exact ⟨⟨v,hv⟩,Finset.mem_univ _,Subtype.ext he⟩ + · intro _ _ + rfl +end CoboundaryExpanders.InfiniteChains.Complex + +namespace CoboundaryExpanders.CosetConstruction +open CategoryTheory +local instance (X : CoboundaryExpanders.Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : CoboundaryExpanders.Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i +variable {G : Type} [Group G] [Fintype G] {n : ℕ} +variable (H : Fin (n+1) → Subgroup G) + +lemma labelled_face_image (g : G) (A : Finset (Fin (n+1))) : + (TypedCosetFaces.face H g A).image (labelEquiv H) = A.image (vertex H g) := by + simp only [TypedCosetFaces.face, Finset.image_image] + rfl + +lemma labelled_mem_faces (s : Finset (Vertex H)) : + s.image (labelEquiv H) ∈ (complex H).faces ↔ TypedCosetFaces.IsFace H s := by + classical + constructor + · intro hs + obtain ⟨g,hg⟩ := mem_faces.mp hs + apply (TypedCosetFaces.complex H).downward (σ := TypedCosetFaces.face H g Finset.univ) + ⟨g,Finset.univ,rfl⟩ + intro x hx + have hh := hg (Finset.mem_image.mpr ⟨x,hx,rfl⟩) + obtain ⟨i,hi⟩ := mem_chamber.mp hh + apply Finset.mem_image.mpr + exact ⟨i,Finset.mem_univ _,(labelEquiv H).injective hi⟩ + · rintro ⟨g,A,rfl⟩ + rw [labelled_face_image] + exact mem_faces.mpr ⟨g,Finset.image_subset_image (Finset.subset_univ A)⟩ + +def typedFaceEquiv (i : ℕ) : + (TypedCosetFaces.complex H).Face (i+1) ≃ (complex H).Face i where + toFun s := ⟨s.val.image (labelEquiv H), (Complex.mem_facesOf _ _ _).mpr + ⟨(labelled_mem_faces H s.val).mpr s.property.1, + (Finset.card_image_of_injective _ (labelEquiv H).injective).trans s.property.2⟩⟩ + invFun s := ⟨s.val.image (labelEquiv H).symm, by + constructor + · apply (labelled_mem_faces H _).mp + simpa only [Finset.image_image, Function.comp_def, Equiv.apply_symm_apply, Finset.image_id'] + using Complex.face_mem s + · exact (Finset.card_image_of_injective _ (labelEquiv H).symm.injective).trans (Complex.face_card s)⟩ + left_inv s := by + apply Subtype.ext + simp only [Finset.image_image, Function.comp_def, Equiv.symm_apply_apply, Finset.image_id'] + right_inv s := by + apply Subtype.ext + simp only [Finset.image_image, Function.comp_def, Equiv.apply_symm_apply, Finset.image_id'] + +lemma typedFaceEquiv_subset (i j : ℕ) + (s : (TypedCosetFaces.complex H).Face (i+1)) + (t : (TypedCosetFaces.complex H).Face (j+1)) : + (typedFaceEquiv H i s).val ⊆ (typedFaceEquiv H j t).val ↔ s.val ⊆ t.val := by + change s.val.image (labelEquiv H) ⊆ t.val.image (labelEquiv H) ↔ _ + exact Finset.image_subset_image_iff (labelEquiv H).injective + +def typedChainEquiv (i : ℕ) : + (TypedCosetFaces.complex H).Chains (i+1) ≃ₗ[ZMod 2] (complex H).Chain i := + (Finsupp.domLCongr (typedFaceEquiv H i)).trans ((complex H).chainBasis i).repr.symm + +@[simp] lemma typedChainEquiv_single (i : ℕ) + (s : (TypedCosetFaces.complex H).Face (i+1)) (r : ZMod 2) : + typedChainEquiv H i (Finsupp.single s r) = r • (complex H).chainBasis i (typedFaceEquiv H i s) := by + simp [typedChainEquiv, Module.Basis.repr_symm_apply] + +lemma typedChainEquiv_boundary (i : ℕ) : + (typedChainEquiv H i).toLinearMap.comp ((TypedCosetFaces.complex H).boundary (i+1)) = + ((complex H).boundaryLinear i).comp (typedChainEquiv H (i+1)).toLinearMap := by + classical + apply Finsupp.lhom_ext' + intro s + apply LinearMap.ext + intro r + simp only [LinearMap.comp_apply, Finsupp.lsingle_apply, + InfiniteChains.Complex.boundary_single_subfaces, map_sum, + LinearEquiv.coe_coe, typedChainEquiv_single, map_smul, + Complex.boundary_on_face, Finset.smul_sum] + apply @Fintype.sum_equiv _ _ _ _ ((complex H).instFintypeFace_2 i) _ (typedFaceEquiv H i) + intro t + by_cases ht : t.val ⊆ s.val + · have hlt := (typedFaceEquiv_subset H i (i+1) t s).mpr ht + simp only [ite_eq_left ht,ite_eq_left hlt,typedChainEquiv_single] + · have hlt := mt (typedFaceEquiv_subset H i (i+1) t s).mp ht + simp only [ite_eq_right ht,ite_eq_right hlt,map_zero,smul_zero] + +def typedChainIso : (TypedCosetFaces.complex H).chainComplex ≅ (complex H).chainComplex := + HomologicalComplex.Hom.isoOfComponents + (fun i => (typedChainEquiv H i).toModuleIso) + (by + intro i j hij + have hij' : j+1 = i := by simpa using hij + subst i + rw [InfiniteChains.Complex.chainComplex_d, CoboundaryExpanders.Complex.chainComplex_d] + apply ModuleCat.hom_ext + exact (typedChainEquiv_boundary H j).symm) + +theorem cocycles_eq_coboundaries_of_typed_homology (i : ℕ) + (hz : Limits.IsZero ((TypedCosetFaces.complex H).chainComplex.homology (i+1))) : + (complex H).cocycles (i+1) = (complex H).coboundaries (i+1) := by + apply Complex.cocycles_eq_coboundaries_of_homology_isZero + exact hz.of_iso ((HomologicalComplex.homologyFunctor _ _ (i+1)).mapIso (typedChainIso H)).symm + +end CoboundaryExpanders.CosetConstruction + +namespace CoboundaryExpanders.Construction +open CategoryTheory _root_.OAI.CoboundaryExpanders.Complex +variable (p n : ℕ) [Fact p.Prime] + +theorem finiteCosetComplex_positive_cohomology (hn : 2 ≤ n) (hp : Odd p) + (hL : OppositionAcyclic p n (by omega)) (m i : ℕ) + (hm : 2 ≤ m) (hi : 0 < i) (hin : i < n-1) + (hz : CongruenceCokernels.ProZero p (n-1) i) + (hz' : CongruenceCokernels.ProZero p n i) : + (finiteCosetComplex p n (by omega) m).cocycles i = + (finiteCosetComplex p n (by omega) m).coboundaries i := by + classical + let : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + obtain ⟨j,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (by omega : i ≠ 0) + exact CosetConstruction.cocycles_eq_coboundaries_of_typed_homology + (reducedLocalGroup p n (by omega) m) j + (quotientTyped_homology_isZero p n hn hp hL m (j+1) hm hi hin hz hz') + +end CoboundaryExpanders.Construction + +namespace CoboundaryExpanders.Complex + +theorem cofaceCount_le_topDegree {X : Complex} {i : ℕ} (σ : X.Face i) + (n : ℕ) (v : Fin X.vertexCount) (hv : v ∈ σ.val) : + X.cofaceCount n σ.val ≤ X.topDegree n v := by + apply Finset.card_le_card + intro τ hτ + obtain ⟨hτ, hστ⟩ := Finset.mem_filter.mp hτ + exact Finset.mem_filter.mpr ⟨hτ, hστ hv⟩ + +theorem cofaceCount_pos_of_pure {X : Complex} {n i : ℕ} (hX : X.Pure n) + (σ : X.Face i) : 0 < X.cofaceCount n σ.val := by + obtain ⟨τ,hτ,hστ⟩ := hX.2 σ.val (face_mem σ) + exact Finset.card_pos.mpr ⟨τ,Finset.mem_filter.mpr ⟨hτ,hστ⟩⟩ + +theorem skeleton_cocycles {X : Complex} {s i : ℕ} (hi : i < s) : + (X.skeletonCochainEquiv hi.le) '' X.cocycles i = (X.skeleton s).cocycles i := by + ext f + obtain ⟨f₀,rfl⟩ := (X.skeletonCochainEquiv hi.le).surjective f + simp only [Set.mem_image, Set.mem_ofPred_eq, cocycles] + constructor + · rintro ⟨g,hg,he⟩ + have hg₀ : g = f₀ := (X.skeletonCochainEquiv hi.le).injective he + subst g + rw [X.skeleton_coboundary hi, hg, map_zero] + · intro hf + rw [X.skeleton_coboundary hi] at hf + exact ⟨f₀, (X.skeletonCochainEquiv hi).injective (by simpa using hf), rfl⟩ + +theorem skeleton_cosystolic_iff {X : Complex} {s i : ℕ} (hi : i < s) (η : ℝ) : + (∀ f : (X.skeleton s).Cochain i, + η * (X.skeleton s).distance s i f ((X.skeleton s).cocycles i) ≤ + (X.skeleton s).norm s (i+1) ((X.skeleton s).coboundary i f)) ↔ + (∀ f : X.Cochain i, + η * X.distance s i f (X.cocycles i) ≤ X.norm s (i+1) (X.coboundary i f)) := by + constructor + · intro h f + have hh := h (X.skeletonCochainEquiv hi.le f) + rw [← skeleton_cocycles hi, skeleton_distance_image, + skeleton_coboundary X hi, skeleton_norm] at hh + exact hh + · intro h f + obtain ⟨f₀,rfl⟩ := (X.skeletonCochainEquiv hi.le).surjective f + rw [← skeleton_cocycles hi, skeleton_distance_image, + skeleton_coboundary X hi, skeleton_norm] + exact h f₀ + +theorem ambient_cosystolic_of_skeleton {X : Complex} {i s n : ℕ} + (hX : X.Pure n) (hi : i < s) (hs : s ≤ n) {M η : ℝ} + (_hM : 0 < M) (hη : 0 ≤ η) + (hc : ∀ ρ : X.Face s, 1 ≤ (X.cofaceCount n ρ.val : ℝ) ∧ + (X.cofaceCount n ρ.val : ℝ) ≤ M) + (hquant : ∀ f : X.Cochain i, + η * X.distance s i f (X.cocycles i) ≤ X.norm s (i+1) (X.coboundary i f)) + (f : X.Cochain i) : + (η/M) * X.distance n i f (X.cocycles i) ≤ X.norm n (i+1) (X.coboundary i f) := by + have hZ : (X.cocycles i).Nonempty := ⟨0, by simp [cocycles]⟩ + have hdist := (skeleton_distance_comparison hX hi.le hs zero_lt_one hc f hZ).1 + have hnorm := (skeleton_norm_comparison hX hi hs zero_lt_one hc (X.coboundary i f)).2 + simp only [div_one] at hnorm + apply (mul_le_mul_iff_right₀ (skeletonScale_pos hX hs)).mp + calc + X.skeletonScale n s * ((η / M) * X.distance n i f (X.cocycles i)) = + η * ((X.skeletonScale n s / M) * X.distance n i f (X.cocycles i)) := by ring + _ ≤ η * X.distance s i f (X.cocycles i) := mul_le_mul_of_nonneg_left hdist hη + _ ≤ X.norm s (i+1) (X.coboundary i f) := hquant f + _ ≤ X.skeletonScale n s * X.norm n (i+1) (X.coboundary i f) := hnorm + +end CoboundaryExpanders.Complex + +namespace CoboundaryExpanders.Construction +open _root_.OAI.CoboundaryExpanders.Complex Filter +variable (p n : ℕ) [Fact p.Prime] + +def UniformCosystolic (hn : 1 ≤ n) : Prop := + ∃ η : ℝ, 0 < η ∧ ∀ m : ℕ, 2 ≤ m → ∀ i : ℕ, i < n-1 → + ∀ f : ((finiteCosetComplex p n hn m).skeleton (n-1)).Cochain i, + η * ((finiteCosetComplex p n hn m).skeleton (n-1)).distance (n-1) i f + (((finiteCosetComplex p n hn m).skeleton (n-1)).cocycles i) ≤ + ((finiteCosetComplex p n hn m).skeleton (n-1)).norm (n-1) (i+1) + (((finiteCosetComplex p n hn m).skeleton (n-1)).coboundary i f) + +theorem finiteCosetComplex_coface_bounds (hn : 1 ≤ n) (m i : ℕ) + (σ : (finiteCosetComplex p n hn m).Face i) : + 1 ≤ ((finiteCosetComplex p n hn m).cofaceCount n σ.val : ℝ) ∧ + ((finiteCosetComplex p n hn m).cofaceCount n σ.val : ℝ) ≤ localBound p n := by + constructor + · exact_mod_cast cofaceCount_pos_of_pure (finiteCosetComplex_pure p n hn m) σ + · have hp : σ.val.Nonempty := Finset.card_pos.mp (by rw [face_card σ]; omega) + obtain ⟨v,hv⟩ := hp + have h := (cofaceCount_le_topDegree σ n v hv).trans + (finiteCosetComplex_degree p n hn m n v) + simpa only [Nat.choose_self, Nat.mul_one] using (show + ((finiteCosetComplex p n hn m).cofaceCount n σ.val : ℝ) ≤ + (localBound p n * Nat.choose n n : ℕ) from by exact_mod_cast h) + +theorem constructed_expansion_of_open_inputs (d : ℕ) (hd : 3 ≤ d) (hp : Odd p) + (hL : OppositionAcyclic p (2*d) (by omega)) + (hz : ∀ i : ℕ, 0 < i → i < d → + CongruenceCokernels.ProZero p (2*d-1) i ∧ CongruenceCokernels.ProZero p (2*d) i) + (hq : UniformCosystolic p (2*d) (by omega)) : + ∃ ε : ℝ, 0 < ε ∧ ∀ m i, i < d → + ∀ f : (finiteSkeleton p (2*d) (by omega) d m).Cochain i, + ε * (finiteSkeleton p (2*d) (by omega) d m).distance d i f + ((finiteSkeleton p (2*d) (by omega) d m).coboundaries i) ≤ + (finiteSkeleton p (2*d) (by omega) d m).norm d (i+1) + ((finiteSkeleton p (2*d) (by omega) d m).coboundary i f) := by + obtain ⟨η,hη,hq⟩ := hq + have hM : 0 < (localBound p (2*d) : ℝ) := by exact_mod_cast localBound_pos p (2*d) + refine ⟨(η / localBound p (2*d)) / localBound p (2*d), div_pos (div_pos hη hM) hM, ?_⟩ + intro m i hi f + have hvanish : (finiteCosetComplex p (2*d) (by omega) (m+2)).cocycles i = + (finiteCosetComplex p (2*d) (by omega) (m+2)).coboundaries i := by + by_cases hi0 : i = 0 + · subst i + exact cocycles_zero_eq_coboundaries_of_connected + (finiteCosetComplex_connected p (2*d) (by omega) (m+2) (by omega)) + · exact finiteCosetComplex_positive_cohomology p (2*d) (by omega) hp hL + (m+2) i (by omega) (by omega) (by omega) (hz i (by omega) hi).1 (hz i (by omega) hi).2 + apply skeleton_expansion (finiteCosetComplex_pure p (2*d) (by omega) (m+2)) hi (by omega) + (div_nonneg hη.le hM.le) (finiteCosetComplex_coface_bounds p (2*d) (by omega) (m+2) d) + hvanish _ f + intro g + exact ambient_cosystolic_of_skeleton + (finiteCosetComplex_pure p (2*d) (by omega) (m+2)) (by omega : i < 2*d-1) + (by omega) hM hη.le (finiteCosetComplex_coface_bounds p (2*d) (by omega) (m+2) (2*d-1)) + ((skeleton_cosystolic_iff (by omega : i < 2*d-1) η).mp (hq (m+2) (by omega) i (by omega))) g + +end CoboundaryExpanders.Construction + +namespace CoboundaryExpanders +open Construction + +theorem reduction_to_three_open_inputs + (hinputs : ∀ d : ℕ, ∀ hd : 3 ≤ d, ∃ p : ℕ, ∃ hp : p.Prime, Odd p ∧ + letI : Fact p.Prime := ⟨hp⟩ + OppositionAcyclic p (2*d) (by omega) ∧ + (∀ i : ℕ, 0 < i → i < d → + CongruenceCokernels.ProZero p (2*d-1) i ∧ CongruenceCokernels.ProZero p (2*d) i) ∧ + UniformCosystolic p (2*d) (by omega)) : MainStatement := by + intro d hd + obtain ⟨p,hp,ho,hL,hz,hq⟩ := hinputs d hd + let : Fact p.Prime := ⟨hp⟩ + obtain ⟨D,hPC,hgrowth,hdegree⟩ := constructed_connected_pure_bounded_growing p d hd + obtain ⟨ε,hε,hexp⟩ := constructed_expansion_of_open_inputs p d hd ho hL hz hq + exact ⟨D,ε,hε,finiteSkeleton p (2*d) (by omega) d,hPC,hgrowth,hdegree,hexp⟩ + +end CoboundaryExpanders + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Skeleton.lean b/lean/OAI/Combinatorics/Coboundary/Skeleton.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b0284de6bb3b3144d0817bb5cfbebce7d12738a --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Skeleton.lean @@ -0,0 +1,344 @@ +import OAI.Combinatorics.Coboundary.Realization + +namespace OAI + +noncomputable section + +/-! +Skeleton-weight identities and conversion of raw cosystolic estimates to the finite weighted norms. +-/ + +section +open scoped BigOperators +open Filter + +namespace CoboundaryExpanders.Complex + +local instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i + +end CoboundaryExpanders.Complex + +namespace CoboundaryExpanders.FatLadders +variable {V W : Type} [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] +omit [Fintype V] [Fintype W] in +lemma delta_image (e : V ≃ W) (f : Finset W → k) (s : Finset V) : + delta (fun t => f (t.image e)) s = delta f (s.image e) := by + unfold delta + rw [Finset.sum_image] + · apply Finset.sum_congr rfl + intro x hx + change f ((s.erase x).image e) = _ + rw [Finset.image_erase e.injective] + · exact fun _ _ _ _ h => e.injective h + +lemma norm_image (e : V ≃ W) (w : Finset W → ℝ) (f : Finset W → k) (r : ℕ) : + norm (fun t => w (t.image e)) r (fun t => f (t.image e)) = norm w r f := by + unfold norm + apply Finset.sum_bij (fun s _ => s.image e) + · intro s hs + simpa only [mem_level,Finset.card_image_of_injective _ e.injective] using hs + · intro s hs t ht h + exact Finset.image_injective e.injective h + · intro s hs + refine ⟨s.image e.symm,?_,?_⟩ + · simpa only [mem_level,Finset.card_image_of_injective _ e.symm.injective] using hs + · simp only [Finset.image_image,Function.comp_def,Equiv.apply_symm_apply,Finset.image_id'] + · intro s hs + rfl +end CoboundaryExpanders.FatLadders + +namespace CoboundaryExpanders.Complex + +section +local instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i +variable (X : Complex) + +def rawCochain (i : ℕ) (f : X.Cochain i) (s : Finset (Fin X.vertexCount)) : ZMod 2 := + if h : s ∈ X.facesOf i then f ⟨s,h⟩ else 0 + +def ofRaw (i : ℕ) (f : Finset (Fin X.vertexCount) → ZMod 2) : X.Cochain i := fun s => f s.val + +@[simp] lemma ofRaw_rawCochain (i : ℕ) (f : X.Cochain i) : + X.ofRaw i (X.rawCochain i f) = f := by + ext s + simp only [ofRaw,rawCochain,dite_eq_left s.property] + +@[simp] lemma ofRaw_add (i : ℕ) (f g : Finset (Fin X.vertexCount) → ZMod 2) : + X.ofRaw i (f+g) = X.ofRaw i f + X.ofRaw i g := rfl + +lemma coboundary_ofRaw (i : ℕ) (f : Finset (Fin X.vertexCount) → ZMod 2) : + X.coboundary i (X.ofRaw i f) = X.ofRaw (i+1) (FatLadders.delta f) := by + ext t + change (∑ s : X.Face i, if s.val ⊆ t.val then f s.val else 0) = ∑ x ∈ t.val, f (t.val.erase x) + rw [←Finset.sum_filter] + symm + apply Finset.sum_bij (fun x hx => (⟨t.val.erase x,(mem_facesOf X i _).mpr + ⟨X.downward (face_mem t) (Finset.erase_subset _ _),by rw [Finset.card_erase_of_mem hx,face_card t]; omega⟩⟩ : X.Face i)) + · intro x hx + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + exact Finset.erase_subset _ _ + · intro x hx y hy hxy + exact (Finset.erase_inj t.val hx).mp (congrArg Subtype.val hxy) + · intro s hs + have hst : s.val ⊆ t.val := (Finset.mem_filter.mp hs).2 + have hcard : (t.val \ s.val).card = 1 := by + rw [Finset.card_sdiff_of_subset hst,face_card t,face_card s]; omega + obtain ⟨x,hx,he⟩ := (Finset.covBy_iff_card_sdiff_eq_one.mpr ⟨hst,hcard⟩).exists_finset_erase + exact ⟨x,hx,Subtype.ext he⟩ + · intro x hx + rfl + +lemma cofaceCount_zero_of_not_mem (n : ℕ) {s : Finset (Fin X.vertexCount)} + (hs : s ∉ X.faces) : X.cofaceCount n s = 0 := by + apply Finset.card_eq_zero.mpr + apply Finset.eq_empty_iff_forall_notMem.mpr + intro t ht + obtain ⟨ht,hst⟩ := Finset.mem_filter.mp ht + exact hs (X.downward ((mem_facesOf X n t).mp ht).1 hst) + +lemma norm_ofRaw (n i : ℕ) (f : Finset (Fin X.vertexCount) → ZMod 2) : + X.norm n i (X.ofRaw i f) = + FatLadders.norm (fun s => (X.cofaceCount n s : ℝ)) (i+1) f / + ((Nat.choose (n+1) (i+1) : ℝ)*(X.facesOf n).card) := by + rw [norm] + have he : (∑ s : X.Face i, if f s.val = 0 then (0:ℝ) else X.cofaceCount n s.val) = + FatLadders.norm (fun s => (X.cofaceCount n s : ℝ)) (i+1) f := by + rw [sum_face_eq X i (fun s => if f s = 0 then (0:ℝ) else X.cofaceCount n s)] + unfold FatLadders.norm FatLadders.atom + apply Finset.sum_subset + · intro s hs + exact FatLadders.mem_level.mpr ((mem_facesOf X i s).mp hs).2 + · intro s hs hnot + have hsm : s ∉ X.faces := by + intro hm + exact hnot ((mem_facesOf X i s).mpr ⟨hm,FatLadders.mem_level.mp hs⟩) + rw [X.cofaceCount_zero_of_not_mem n hsm] + simp + rw [←he,Finset.sum_div] + apply Finset.sum_congr rfl + intro s hs + change (if f s.val ≠ 0 then X.weight n i s else 0) = _ + rw [weight_eq_cofaceCount] + by_cases hf : f s.val = 0 <;> simp [hf] + +lemma normalizer_pos {n i : ℕ} (hX : X.Pure n) (hi : i ≤ n) : + 0 < (Nat.choose (n+1) (i+1) : ℝ)*(X.facesOf n).card := by + exact mul_pos (Nat.cast_pos.mpr (Nat.choose_pos (by omega))) (Nat.cast_pos.mpr hX.1.card_pos) + +end + +local instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i +variable {X : Complex} +lemma raw_norm_eq_mul {n i : ℕ} (hX : X.Pure n) (hi : i ≤ n) + (f : Finset (Fin X.vertexCount) → ZMod 2) : + FatLadders.norm (fun s => (X.cofaceCount n s : ℝ)) (i+1) f = + ((Nat.choose (n+1) (i+1) : ℝ)*(X.facesOf n).card)*X.norm n i (X.ofRaw i f) := by + rw [X.norm_ofRaw] + exact (mul_div_cancel₀ _ (X.normalizer_pos hX hi).ne').symm + +theorem cosystolic_of_raw {n i : ℕ} (hX : X.Pure n) (hi : i < n) {K : ℝ} (hK : 0 < K) + (hraw : ∀ f : Finset (Fin X.vertexCount) → ZMod 2, ∃ h, + FatLadders.norm (fun s => (X.cofaceCount n s : ℝ)) (i+2) (FatLadders.delta (f+h)) = 0 ∧ + FatLadders.norm (fun s => (X.cofaceCount n s : ℝ)) (i+1) h ≤ + K*FatLadders.norm (fun s => (X.cofaceCount n s : ℝ)) (i+2) (FatLadders.delta f)) + (f : X.Cochain i) : + (1/(K*2^(n+1))) * X.distance n i f (X.cocycles i) ≤ X.norm n (i+1) (X.coboundary i f) := by + obtain ⟨h,hz,hb⟩ := hraw (X.rawCochain i f) + have hdelta : X.coboundary i f = X.ofRaw (i+1) (FatLadders.delta (X.rawCochain i f)) := by + simpa only [ofRaw_rawCochain] using X.coboundary_ofRaw i (X.rawCochain i f) + have hz' : X.coboundary i (f+X.ofRaw i h) = 0 := by + apply (norm_eq_zero_iff hX (by omega) _).mp + rw [←X.ofRaw_rawCochain i f,←X.ofRaw_add,X.coboundary_ofRaw,X.norm_ofRaw] + simp only [Nat.add_assoc,show 1+1=2 by rfl,hz,zero_div] + have hn : X.norm n i (X.ofRaw i h) ≤ K*2^(n+1)*X.norm n (i+1) (X.coboundary i f) := by + rw [raw_norm_eq_mul hX (by omega),raw_norm_eq_mul hX (by omega),←hdelta] at hb + have hc0 : 1 ≤ (Nat.choose (n+1) (i+1) : ℝ) := by + exact_mod_cast Nat.choose_pos (show i+1 ≤ n+1 by omega) + have hc1 : (Nat.choose (n+1) (i+1+1) : ℝ) ≤ 2^(n+1) := by + exact_mod_cast Nat.choose_le_two_pow (n+1) (i+1+1) + have hbound : (Nat.choose (n+1) (i+1+1) : ℝ) ≤ 2^(n+1)*(Nat.choose (n+1) (i+1) : ℝ) := + hc1.trans (by nlinarith [show (0:ℝ) ≤ 2^(n+1) by positivity]) + apply (mul_le_mul_iff_right₀ (X.normalizer_pos (i:=i) hX (by omega))).mp + apply hb.trans + have hcnt : (0:ℝ) ≤ (X.facesOf n).card := Nat.cast_nonneg _ + have hx := mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left + (mul_le_mul_of_nonneg_right hbound hcnt) hK.le) (X.norm_nonneg n (i+1) (X.coboundary i f)) + nlinarith only [hx] + have hd : X.distance n i f (X.cocycles i) ≤ X.norm n i (X.ofRaw i h) := by + have hmem : f+X.ofRaw i h ∈ X.cocycles i := hz' + have hh := X.distance_le_norm n i f hmem + have he : f-(f+X.ofRaw i h) = X.ofRaw i h := by + ext s + simp only [Pi.sub_apply,Pi.add_apply,sub_add_cancel_left,CharTwo.neg_eq] + rwa [he] at hh + have hpos : 0 < K*2^(n+1) := mul_pos hK (by positivity) + have hh := hd.trans hn + apply (mul_le_mul_iff_right₀ hpos).mp + convert hh using 1 + field_simp +end CoboundaryExpanders.Complex + +namespace CoboundaryExpanders.FatLadders +variable {V W : Type} [Fintype V] [Fintype W] [DecidableEq V] [DecidableEq W] +lemma correction_image (e : V ≃ W) (wV : Finset V → ℝ) (wW : Finset W → ℝ) + (hw : ∀ s,wW (s.image e) = wV s) (r : ℕ) (K : ℝ) + (hh : ∀ f : Finset V → k, ∃ h, + norm wV r (delta (f+h)) = 0 ∧ norm wV (r-1) h ≤ K*norm wV r (delta f)) : + ∀ f : Finset W → k, ∃ h, + norm wW r (delta (f+h)) = 0 ∧ norm wW (r-1) h ≤ K*norm wW r (delta f) := by + intro f + obtain ⟨h,hz,hb⟩ := hh (fun s => f (s.image e)) + let g : Finset W → k := fun s => h (s.image e.symm) + have hg : (fun s => g (s.image e)) = h := by + funext s + simp only [g,Finset.image_image,Function.comp_def,Equiv.symm_apply_apply,Finset.image_id'] + have norm_transfer : ∀ r (F : Finset W → k), + norm wV r (fun s => F (s.image e)) = norm wW r F := by + intro r F + have he : wV = fun s => wW (s.image e) := (funext hw).symm + rw [he] + exact norm_image e wW F r + have hz' := norm_transfer r (delta (f+g)) + have hd : (fun s => delta (f+g) (s.image e)) = delta ((fun s => f (s.image e))+h) := by + funext s + rw [←delta_image e] + congr 1 + funext t + change f (t.image e)+g (t.image e) = f (t.image e)+h t + rw [congrFun hg t] + refine ⟨g,?_,?_⟩ + · rwa [←hz',hd] + · rw [←norm_transfer (r-1) g,←norm_transfer r (delta f),hg] + have hd' : (fun s => delta f (s.image e)) = delta (fun s => f (s.image e)) := + funext (fun s => (delta_image e f s).symm) + rwa [hd'] +end CoboundaryExpanders.FatLadders + +namespace CoboundaryExpanders.Complex + +section + +local instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i + +end + +local instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i + +open CategoryTheory + +end CoboundaryExpanders.Complex + +namespace CoboundaryExpanders.CosetConstruction + +section +open CategoryTheory +local instance (X : CoboundaryExpanders.Complex) (i : ℕ) : Fintype (X.Face i) := X.instFintypeFace i +local instance (X : CoboundaryExpanders.Complex) (i : ℕ) : DecidableEq (X.Face i) := X.instDecidableEqFace i +variable {G : Type} [Group G] [Fintype G] {n : ℕ} +variable (H : Fin (n+1) → Subgroup G) + +end + +open InfiniteChains.FiniteWeights +variable {G : Type} [Group G] [Fintype G] {n : ℕ} +variable (H : Fin (n+1) → Subgroup G) + +lemma labelled_cofaces (r : ℕ) (s : Finset (Vertex H)) : + (complex H).cofaceCount r (s.image (labelEquiv H)) = + cofaces (TypedCosetFaces.complex H) (r+1) s := by + unfold Complex.cofaceCount cofaces + symm + apply Finset.card_bij (fun t _ => t.image (labelEquiv H)) + · intro t ht + obtain ⟨ht,hst⟩ := Finset.mem_filter.mp ht + obtain ⟨ht,hcard⟩ := (mem_level _ _ _).mp ht + exact Finset.mem_filter.mpr ⟨(Complex.mem_facesOf _ _ _).mpr + ⟨(labelled_mem_faces H t).mpr ht,by rwa [Finset.card_image_of_injective _ (labelEquiv H).injective]⟩, + Finset.image_subset_image hst⟩ + · intro t ht u hu he + exact Finset.image_injective (labelEquiv H).injective he + · intro t ht + obtain ⟨ht,hst⟩ := Finset.mem_filter.mp ht + obtain ⟨ht,hcard⟩ := (Complex.mem_facesOf _ _ _).mp ht + have he : (t.image (labelEquiv H).symm).image (labelEquiv H) = t := by + simp only [Finset.image_image,Function.comp_def,Equiv.apply_symm_apply,Finset.image_id'] + refine ⟨t.image (labelEquiv H).symm,Finset.mem_filter.mpr ⟨(mem_level _ _ _).mpr ⟨?_,?_⟩,?_⟩,he⟩ + · apply (labelled_mem_faces H _).mp + rwa [he] + · rwa [Finset.card_image_of_injective _ (labelEquiv H).symm.injective] + · apply (Finset.image_subset_image_iff (labelEquiv H).injective).mp + rwa [he] + +theorem cosystolic_of_typed_raw (i : ℕ) (hi : i < n) {K : ℝ} (hK : 0 < K) + (hh : ∀ f : Finset (Vertex H) → ZMod 2, ∃ h, + FatLadders.norm (fun s => (cofaces (TypedCosetFaces.complex H) (n+1) s : ℝ)) (i+2) + (FatLadders.delta (f+h)) = 0 ∧ + FatLadders.norm (fun s => (cofaces (TypedCosetFaces.complex H) (n+1) s : ℝ)) (i+1) h ≤ + K*FatLadders.norm (fun s => (cofaces (TypedCosetFaces.complex H) (n+1) s : ℝ)) (i+2) + (FatLadders.delta f)) : + ∀ f : (complex H).Cochain i, + (1/(K*2^(n+1))) * (complex H).distance n i f ((complex H).cocycles i) ≤ + (complex H).norm n (i+1) ((complex H).coboundary i f) := by + apply Complex.cosystolic_of_raw (pure H) hi hK + have he := FatLadders.correction_image (labelEquiv H) + (fun s => (cofaces (TypedCosetFaces.complex H) (n+1) s : ℝ)) + (fun s => ((complex H).cofaceCount n s : ℝ)) + (fun s => by rw [labelled_cofaces]) (i+2) K + simpa only [show i+2-1=i+1 by omega] using he hh +end CoboundaryExpanders.CosetConstruction + +end + +namespace CoboundaryExpanders.Complex + +theorem skeleton_cosystolic_of_ambient {X : Complex} {i s n : ℕ} + (hX : X.Pure n) (hi : i < s) (hs : s ≤ n) {M η : ℝ} + (hM : 0 < M) (hη : 0 ≤ η) + (hc : ∀ ρ : X.Face s, 1 ≤ (X.cofaceCount n ρ.val : ℝ) ∧ + (X.cofaceCount n ρ.val : ℝ) ≤ M) + (hquant : ∀ f : X.Cochain i, + η * X.distance n i f (X.cocycles i) ≤ X.norm n (i+1) (X.coboundary i f)) + (f : X.Cochain i) : + (η/M) * X.distance s i f (X.cocycles i) ≤ X.norm s (i+1) (X.coboundary i f) := by + have hZ : (X.cocycles i).Nonempty := ⟨0, by simp [cocycles]⟩ + have hdist := (skeleton_distance_comparison hX hi.le hs zero_lt_one hc f hZ).2 + have hnorm := (skeleton_norm_comparison hX hi hs zero_lt_one hc (X.coboundary i f)).1 + simp only [div_one] at hdist + calc + (η/M) * X.distance s i f (X.cocycles i) ≤ + (η/M) * (X.skeletonScale n s * X.distance n i f (X.cocycles i)) := + mul_le_mul_of_nonneg_left hdist (div_nonneg hη hM.le) + _ = (X.skeletonScale n s/M) * (η * X.distance n i f (X.cocycles i)) := by ring + _ ≤ (X.skeletonScale n s/M) * X.norm n (i+1) (X.coboundary i f) := + mul_le_mul_of_nonneg_left (hquant f) (div_nonneg (skeletonScale_pos hX hs).le hM.le) + _ ≤ _ := hnorm +end CoboundaryExpanders.Complex + +namespace CoboundaryExpanders.Construction +open InfiniteChains.FiniteWeights + +theorem actual_uniform_cosystolic (n : ℕ) (hn : 2 ≤ n) : + ∃ Q : ℕ, ∀ p : ℕ, ∀ _ : Fact p.Prime, Q < p → UniformCosystolic p n (by omega) := by + obtain ⟨Q,K,hK,hraw⟩ := uniform_actual_raw_cosystolic n hn + refine ⟨Q,?_⟩ + intro p hp hqp + have hM : 0 < (localBound p n : ℝ) := by exact_mod_cast localBound_pos p n + have heta : 0 < (1/(K*2^(n+1)) : ℝ) := by positivity + refine ⟨(1/(K*2^(n+1)))/(localBound p n),div_pos heta hM,?_⟩ + intro m hm i hi + apply (Complex.skeleton_cosystolic_iff hi _).mpr + apply Complex.skeleton_cosystolic_of_ambient (finiteCosetComplex_pure p n (by omega) m) hi + (by omega) hM heta.le (finiteCosetComplex_coface_bounds p n (by omega) m (n-1)) + let : Fintype (Gquot p (n+1) m) := Fintype.ofFinite _ + apply CosetConstruction.cosystolic_of_typed_raw (reducedLocalGroup p n (by omega) m) i (by omega) hK + exact hraw p hp hqp m hm (i+2) (by omega) +end CoboundaryExpanders.Construction + +end + +end OAI diff --git a/lean/OAI/Combinatorics/Coboundary/Spectral.lean b/lean/OAI/Combinatorics/Coboundary/Spectral.lean new file mode 100644 index 0000000000000000000000000000000000000000..4db9c40aaab24942db01d2e8c55c67e1db192444 --- /dev/null +++ b/lean/OAI/Combinatorics/Coboundary/Spectral.lean @@ -0,0 +1,244 @@ +import Mathlib + +namespace OAI + +/-! +Self-adjoint operator estimates and the weighted-graph spectral trickling argument. +-/ + +noncomputable section +open scoped BigOperators +open scoped BigOperators Matrix +open scoped Matrix +open scoped BigOperators InnerProductSpace + +namespace CoboundaryExpanders.Spectral + +section + +lemma eigenvalue_trickle {lam μ : ℝ} (hlam : lam < 1) (hμ : μ < 1) + (h : μ ≤ lam + (1-lam)*μ^2) : μ ≤ lam/(1-lam) := by + apply (le_div_iff₀ (by linarith : 0 < 1-lam)).mpr + have hp : 0 < 1-μ := by linarith + nlinarith [mul_pos hp (by linarith : 0 < 1-lam)] + +variable {E : Type} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + +theorem operator_trickle (A : E →ₗ[ℝ] E) (hA : A.IsSymmetric) + (c : E) (hfix : ∀ v, A v = v → ∃ t : ℝ, v = t • c) + {lam : ℝ} (hlam : lam < 1) + (hupper : ∀ v, ⟪A v,v⟫_ℝ ≤ ⟪v,v⟫_ℝ) + (hlocal : ∀ v, ⟪A v,v⟫_ℝ ≤ lam*⟪v,v⟫_ℝ + (1-lam)*⟪A v,A v⟫_ℝ) + (v : E) (hv : ⟪c,v⟫_ℝ = 0) : + ⟪A v,v⟫_ℝ ≤ lam/(1-lam) * ⟪v,v⟫_ℝ := by + classical + let b := hA.eigenvectorBasis (n := Module.finrank ℝ E) rfl + let ev := hA.eigenvalues (n := Module.finrank ℝ E) rfl + have he (i) : A (b i) = ev i • b i := hA.apply_eigenvectorBasis rfl i + have hn (i) : ⟪b i,b i⟫_ℝ = 1 := by + simp + have hi (i) : ev i ≤ 1 := by + have h := hupper (b i) + rw [he,real_inner_smul_left,hn,mul_one] at h + exact h + have hbound (i) : ev i * (b.repr v i)^2 ≤ lam/(1-lam) * (b.repr v i)^2 := by + by_cases h : ev i = 1 + · have hh : A (b i) = b i := by rw [he,h,one_smul] + obtain ⟨t,ht⟩ := hfix (b i) hh + have hvi : b.repr v i = 0 := by + rw [OrthonormalBasis.repr_apply_apply,ht,real_inner_smul_left,hv,mul_zero] + simp [hvi] + · apply mul_le_mul_of_nonneg_right _ (sq_nonneg _) + apply eigenvalue_trickle hlam (lt_of_le_of_ne (hi i) h) + have hl := hlocal (b i) + rw [he,real_inner_smul_left,real_inner_smul_right,real_inner_smul_left,hn] at hl + nlinarith + have hrepr : ∀ i, b.repr (A v) i = ev i * b.repr v i := + hA.eigenvectorBasis_apply_self_apply rfl v + rw [← b.repr.inner_map_map (A v) v, ← b.repr.inner_map_map v v] + simp only [EuclideanSpace.inner_eq_star_dotProduct, dotProduct, star_trivial] + rw [Finset.mul_sum] + apply Finset.sum_le_sum + intro i _ + rw [hrepr] + nlinarith [hbound i] + +end + +open scoped BigOperators InnerProductSpace +variable {V : Type} [Fintype V] + +structure WeightedGraph (V : Type) [Fintype V] where + edge : V → V → ℝ + nonneg : ∀ u v, 0 ≤ edge u v + symm : ∀ u v, edge u v = edge v u + row_pos : ∀ u, 0 < ∑ v, edge u v + +namespace WeightedGraph +open WithLp +local instance : DecidableEq V := Classical.decEq _ +variable (G : WeightedGraph V) +def mass (u : V) : ℝ := ∑ v, G.edge u v +def energy (f : V → ℝ) : ℝ := ∑ u, G.mass u * (f u)^2 +def pairing (f g : V → ℝ) : ℝ := ∑ u, ∑ v, G.edge u v * f u * g v +def action (f : V → ℝ) (u : V) : ℝ := (∑ v, G.edge u v * f v) / G.mass u +def Connected : Prop := ∀ u v : V, Relation.ReflTransGen (fun u v => 0 < G.edge u v) u v + +lemma mass_pos (u : V) : 0 < G.mass u := G.row_pos u +lemma mass_ne (u : V) : G.mass u ≠ 0 := ne_of_gt (G.mass_pos u) +lemma energy_nonneg (f : V → ℝ) : 0 ≤ G.energy f := + Finset.sum_nonneg (fun u _ => mul_nonneg (G.mass_pos u).le (sq_nonneg _)) + +lemma swapped_energy (f : V → ℝ) : + (∑ u, ∑ v, G.edge u v * (f v)^2) = G.energy f := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro u _ + simp only [mass,Finset.sum_mul] + apply Finset.sum_congr rfl + intro v _ + rw [G.symm] + +lemma energy_difference (f : V → ℝ) : + G.energy f - G.pairing f f = (1/2:ℝ) * ∑ u, ∑ v, G.edge u v * (f u-f v)^2 := by + have hswap := G.swapped_energy f + have hself : (∑ u, ∑ v, G.edge u v * (f u)^2) = G.energy f := by + simp only [energy,mass,Finset.sum_mul] + have he : (∑ u, ∑ v, G.edge u v * (f u-f v)^2) = + (∑ u, ∑ v, G.edge u v * (f u)^2) + (∑ u, ∑ v, G.edge u v * (f v)^2) - + 2 * G.pairing f f := by + simp only [pairing,Finset.mul_sum,← Finset.sum_add_distrib,← Finset.sum_sub_distrib] + apply Finset.sum_congr rfl + intro u _ + apply Finset.sum_congr rfl + intro v _ + ring + rw [he,hself,hswap] + ring + +lemma pairing_le_energy (f : V → ℝ) : G.pairing f f ≤ G.energy f := by + have hn : 0 ≤ ∑ u, ∑ v, G.edge u v * (f u-f v)^2 := + Finset.sum_nonneg (fun u _ => Finset.sum_nonneg (fun v _ => + mul_nonneg (G.nonneg u v) (sq_nonneg _))) + have hh := G.energy_difference f + linarith + +lemma action_pairing (f g : V → ℝ) : + (∑ u, G.mass u * f u * G.action g u) = G.pairing f g := by + unfold pairing action + apply Finset.sum_congr rfl + intro u _ + calc + G.mass u * f u * ((∑ v, G.edge u v * g v)/G.mass u) = + f u * (∑ v, G.edge u v * g v) := by field_simp [G.mass_ne u] + _ = _ := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro v _ + ring + +lemma fixed_constant (hG : G.Connected) (f : V → ℝ) (hf : G.action f = f) : + ∀ u v, f u = f v := by + have he : G.energy f = G.pairing f f := by + rw [← G.action_pairing, hf] + simp only [energy,pow_two,mul_assoc] + have hz : ∑ u, ∑ v, G.edge u v * (f u-f v)^2 = 0 := by + have h := G.energy_difference f + rw [he,sub_self] at h + linarith + have hn (u v) : 0 ≤ G.edge u v * (f u-f v)^2 := + mul_nonneg (G.nonneg u v) (sq_nonneg _) + have hedge (u v) (huv : 0 < G.edge u v) : f u = f v := by + have hrow : ∑ v, G.edge u v * (f u-f v)^2 = 0 := + (Finset.sum_eq_zero_iff_of_nonneg (fun u _ => Finset.sum_nonneg (fun v _ => hn u v))).mp hz + u (Finset.mem_univ u) + have hs : G.edge u v * (f u-f v)^2 = 0 := + (Finset.sum_eq_zero_iff_of_nonneg (fun v _ => hn u v)).mp hrow v (Finset.mem_univ v) + have hsq := (mul_eq_zero.mp hs).resolve_left (ne_of_gt huv) + nlinarith [sq_nonneg (f u-f v)] + intro u v + induction hG u v with + | refl => rfl + | @tail b c _ hbc ih => exact ih.trans (hedge b c hbc) + +def coord (f : V → ℝ) : EuclideanSpace ℝ V := toLp 2 (fun u => Real.sqrt (G.mass u) * f u) +def uncoord (v : EuclideanSpace ℝ V) : V → ℝ := fun u => v u / Real.sqrt (G.mass u) +def matrix : Matrix V V ℝ := fun u v => G.edge u v / (Real.sqrt (G.mass u)*Real.sqrt (G.mass v)) +def operator : EuclideanSpace ℝ V →ₗ[ℝ] EuclideanSpace ℝ V := G.matrix.toEuclideanLin + +lemma sqrt_ne (u : V) : Real.sqrt (G.mass u) ≠ 0 := ne_of_gt (Real.sqrt_pos.mpr (G.mass_pos u)) +@[simp] lemma coord_uncoord (v : EuclideanSpace ℝ V) : G.coord (G.uncoord v) = v := by + ext u + simp only [coord,uncoord,PiLp.toLp_apply,mul_div_cancel₀ _ (G.sqrt_ne u)] +@[simp] lemma uncoord_coord (f : V → ℝ) : G.uncoord (G.coord f) = f := by + funext u + simp only [coord,uncoord,PiLp.toLp_apply,mul_div_cancel_left₀ _ (G.sqrt_ne u)] + +lemma coord_inner (f g : V → ℝ) : + ⟪G.coord f,G.coord g⟫_ℝ = ∑ u, G.mass u * f u * g u := by + simp only [coord,EuclideanSpace.inner_eq_star_dotProduct,dotProduct,star_trivial] + apply Finset.sum_congr rfl + intro u _ + calc + _ = (Real.sqrt (G.mass u))^2 * f u * g u := by ring + _ = _ := by rw [Real.sq_sqrt (G.mass_pos u).le] + +lemma operator_coord (f : V → ℝ) : G.operator (G.coord f) = G.coord (G.action f) := by + ext u + change (∑ v, G.edge u v / (Real.sqrt (G.mass u)*Real.sqrt (G.mass v)) * + (Real.sqrt (G.mass v)*f v)) = Real.sqrt (G.mass u)*((∑ v,G.edge u v*f v)/G.mass u) + rw [Finset.sum_div,Finset.mul_sum] + apply Finset.sum_congr rfl + intro v _ + have hs := Real.sq_sqrt (G.mass_pos u).le + field_simp [G.sqrt_ne u,G.sqrt_ne v,G.mass_ne u] + rw [hs] + ring + +lemma operator_symmetric : G.operator.IsSymmetric := by + apply Matrix.isSymmetric_toEuclideanLin_iff.mpr + ext u v + simp only [Matrix.conjTranspose_apply,star_trivial,matrix] + rw [G.symm v u,mul_comm] + +theorem trickle [Nonempty V] (hG : G.Connected) {lam : ℝ} (hlam : lam < 1) + (hloc : ∀ f : V → ℝ, G.pairing f f ≤ lam*G.energy f + (1-lam)*G.energy (G.action f)) + (f : V → ℝ) (hf : ∑ u, G.mass u * f u = 0) : + G.pairing f f ≤ (lam/(1-lam))*G.energy f := by + let c := G.coord (fun _ => 1) + have hfix (v : EuclideanSpace ℝ V) (hv : G.operator v = v) : ∃ t : ℝ, v = t • c := by + have hh : G.action (G.uncoord v) = G.uncoord v := by + have h := congrArg G.uncoord hv + rw [← G.coord_uncoord v,G.operator_coord,G.uncoord_coord] at h + simpa using h + let u : V := Classical.choice inferInstance + refine ⟨G.uncoord v u,?_⟩ + conv_lhs => rw [← G.coord_uncoord v] + ext w + change Real.sqrt (G.mass w)*G.uncoord v w = G.uncoord v u * (Real.sqrt (G.mass w)*1) + rw [G.fixed_constant hG _ hh w u] + ring + have hup (v : EuclideanSpace ℝ V) : ⟪G.operator v,v⟫_ℝ ≤ ⟪v,v⟫_ℝ := by + rw [← G.coord_uncoord v,G.operator_coord,G.coord_inner,G.coord_inner] + have h := G.pairing_le_energy (G.uncoord v) + rw [← G.action_pairing] at h + simpa only [energy,pow_two,mul_assoc,mul_left_comm,mul_comm] using h + have hlo (v : EuclideanSpace ℝ V) : ⟪G.operator v,v⟫_ℝ ≤ + lam*⟪v,v⟫_ℝ + (1-lam)*⟪G.operator v,G.operator v⟫_ℝ := by + rw [← G.coord_uncoord v,G.operator_coord,G.coord_inner,G.coord_inner,G.coord_inner] + have h := hloc (G.uncoord v) + rw [← G.action_pairing] at h + simpa only [energy,pow_two,mul_assoc,mul_left_comm,mul_comm] using h + have hmean : ⟪c,G.coord f⟫_ℝ = 0 := by simpa [c,G.coord_inner] using hf + have h := operator_trickle G.operator G.operator_symmetric c hfix hlam hup hlo (G.coord f) hmean + rw [G.operator_coord,G.coord_inner,G.coord_inner] at h + rw [← G.action_pairing] + simpa only [energy,pow_two,mul_assoc,mul_left_comm,mul_comm] using h + +end WeightedGraph +end CoboundaryExpanders.Spectral + +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/AdjacentSurgery.lean b/lean/OAI/Combinatorics/CompleteCrossing/AdjacentSurgery.lean new file mode 100644 index 0000000000000000000000000000000000000000..400cd5570da31a6e7cb0208c6ccc5beb8ab637c0 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/AdjacentSurgery.lean @@ -0,0 +1,621 @@ +import OAI.Combinatorics.CompleteCrossing.CrossingCuts +import OAI.Combinatorics.Crossing.PolygonalParametrizationCover + +namespace OAI + +/-! Reconnected paths and point-removing surgery on adjacent edges. -/ + +section + +/-! The two actual switched walks, before loop deletion. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +theorem surgery_forward_adj : (crossingSurgeryGraph C P p q).Adj + (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q)) := + crossingSurgeryGraph_reconnection_adj C P p q true + +theorem surgery_backward_adj : (crossingSurgeryGraph C P p q).Adj + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p)) := + crossingSurgeryGraph_reconnection_adj C P p q false + +def reconnectedForwardWalk (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + (crossingSurgeryGraph C P p q).Walk (D'.vertex ((graph.src p.1))) (D'.vertex ((graph.dst q.1))) := + walkThroughChord (Kp.prefixInSurgery p q rfl) + surgery_forward_adj (Kq.suffixInSurgery p q hm.symm) + +def reconnectedBackwardWalk (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + (crossingSurgeryGraph C P p q).Walk (D'.vertex ((graph.src q.1))) (D'.vertex ((graph.dst p.1))) := + walkThroughChord (Kq.prefixInSurgery p q hm.symm) + surgery_backward_adj (Kp.suffixInSurgery p q rfl) + +theorem reconnectedForwardWalk_trace (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + Set.range (graphWalkPath id (reconnectedForwardWalk Kp Kq hm))= + (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take Kp.first.val)) ∪ + segment ℝ (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q))) ∪ + Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).drop Kq.last.val)) := by + rw [reconnectedForwardWalk,walkThroughChord_range, + ExteriorCrossingCut.prefixInSurgery_trace,ExteriorCrossingCut.suffixInSurgery_trace] + +theorem reconnectedBackwardWalk_trace (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + Set.range (graphWalkPath id (reconnectedBackwardWalk Kp Kq hm))= + (Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).take Kq.first.val)) ∪ + segment ℝ (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p))) ∪ + Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop Kp.last.val)) := by + rw [reconnectedBackwardWalk,walkThroughChord_range, + ExteriorCrossingCut.prefixInSurgery_trace,ExteriorCrossingCut.suffixInSurgery_trace] + +end Paper170Geometry + +end +end + +section + +/-! Actual simple polygonal paths extracted from the two switched walks. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +def reconnectedForwardPath (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : Path (D'.vertex ((graph.src p.1))) (D'.vertex ((graph.dst q.1))) := by + classical + exact graphWalkPath id (reconnectedForwardWalk Kp Kq hm).bypass + +def reconnectedBackwardPath (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : Path (D'.vertex ((graph.src q.1))) (D'.vertex ((graph.dst p.1))) := by + classical + exact graphWalkPath id (reconnectedBackwardWalk Kp Kq hm).bypass + +theorem reconnectedForwardPath_injective (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hadj : graph.src p.1 = graph.src q.1 ∨ graph.dst p.1 = graph.dst q.1) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Function.Injective (reconnectedForwardPath Kp Kq hm) := by + classical + exact graphWalkPath_injective id hemb (surgery_mixed_endpoints_ne C p q hadj) + _ (reconnectedForwardWalk Kp Kq hm).bypass_isPath + +theorem reconnectedBackwardPath_injective (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hadj : graph.src p.1 = graph.src q.1 ∨ graph.dst p.1 = graph.dst q.1) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Function.Injective (reconnectedBackwardPath Kp Kq hm) := by + classical + exact graphWalkPath_injective id hemb (surgery_mixed_endpoints_ne C q p (hadj.imp Eq.symm Eq.symm)) + _ (reconnectedBackwardWalk Kp Kq hm).bypass_isPath + +theorem reconnectedForwardPath_hasFiniteAffineCover (Kp : ExteriorCrossingCut C P p) + (Kq : ExteriorCrossingCut C P q) (hm : C.innerMark p=C.innerMark q) : + HasFiniteAffineCover (reconnectedForwardPath Kp Kq hm) := by + classical + exact graphWalkPath_hasFiniteAffineCover id _ + +theorem reconnectedBackwardPath_hasFiniteAffineCover (Kp : ExteriorCrossingCut C P p) + (Kq : ExteriorCrossingCut C P q) (hm : C.innerMark p=C.innerMark q) : + HasFiniteAffineCover (reconnectedBackwardPath Kp Kq hm) := by + classical + exact graphWalkPath_hasFiniteAffineCover id _ + +theorem reconnectedForwardPath_trace (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + Set.range (reconnectedForwardPath Kp Kq hm) ⊆ + (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take Kp.first.val)) ∪ + segment ℝ (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q))) ∪ + Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).drop Kq.last.val)) := by + classical + exact (graphWalkPath_bypass_range_subset id (reconnectedForwardWalk Kp Kq hm)).trans + (by rw [reconnectedForwardWalk_trace]) + +theorem reconnectedBackwardPath_trace (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) : + Set.range (reconnectedBackwardPath Kp Kq hm) ⊆ + (Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).take Kq.first.val)) ∪ + segment ℝ (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p))) ∪ + Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop Kp.last.val)) := by + classical + exact (graphWalkPath_bypass_range_subset id (reconnectedBackwardWalk Kp Kq hm)).trans + (by rw [reconnectedBackwardWalk_trace]) + +end Paper170Geometry + +end +end + +section + +/-! The selected spatial crossing point is absent from both actual bypassed paths. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +theorem reconnected_paths_avoid_crossing (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (x : Plane) + (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∉ Set.range (reconnectedForwardPath Kp Kq hm) ∧ + x ∉ Set.range (reconnectedBackwardPath Kp Kq hm) := by + obtain ⟨hxin,havoid⟩ := C.reconnection_avoids_chord_meeting p q hpq x hxp hxq + have hxinq : x ∈ C.crossingDisk q := by + simpa only [DrawingPassages.crossingDisk,hm] using hxin + constructor + · intro hx + rcases reconnectedForwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · exact Set.disjoint_left.mp Kp.prefix_outside hx hxin + · exact havoid true hx + · exact Set.disjoint_left.mp Kq.suffix_outside hx hxinq + · intro hx + rcases reconnectedBackwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · exact Set.disjoint_left.mp Kq.prefix_outside hx hxinq + · exact havoid false hx + · exact Set.disjoint_left.mp Kp.suffix_outside hx hxin + +end Paper170Geometry + +end +end + +section + +/-! The actual rerouted simple paths have vertex-avoiding interiors. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +theorem path_interior_avoids_vertices_of_range {V : Type*} (vertex : V → Plane) (a b : V) + (γ : Path (vertex a) (vertex b)) (hinj : Function.Injective γ) + (hrange : ∀ v, vertex v ∈ Set.range γ → v=a ∨ v=b) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (v : V) : γ t ≠ vertex v := by + intro he + rcases hrange v ⟨t,he⟩ with rfl | rfl + · exact ht.1.ne (hinj (he.trans γ.source.symm)).symm + · exact ht.2.ne (hinj (he.trans γ.target.symm)) + +theorem reconnectedForwardPath_vertex_eq (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (j : Vertex) (hj : D'.vertex j ∈ Set.range (reconnectedForwardPath Kp Kq hm)) : + j=(graph.src p.1) ∨ j=(graph.dst q.1) := by + rcases reconnectedForwardPath_trace Kp Kq hm hj with (hj | hj) | hj + · exact Or.inl (Kp.prefix_vertex_eq j hj) + · exact False.elim (C.reconnection_segment_avoids_vertices p q hm D'.vertex hv true j hj) + · exact Or.inr (Kq.suffix_vertex_eq j hj) + +theorem reconnectedBackwardPath_vertex_eq (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (j : Vertex) (hj : D'.vertex j ∈ Set.range (reconnectedBackwardPath Kp Kq hm)) : + j=(graph.src q.1) ∨ j=(graph.dst p.1) := by + rcases reconnectedBackwardPath_trace Kp Kq hm hj with (hj | hj) | hj + · exact Or.inl (Kq.prefix_vertex_eq j hj) + · exact False.elim (C.reconnection_segment_avoids_vertices p q hm D'.vertex hv false j hj) + · exact Or.inr (Kp.suffix_vertex_eq j hj) + +theorem reconnectedForwardPath_interior_avoids_vertices + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hadj : graph.src p.1 = graph.src q.1 ∨ graph.dst p.1 = graph.dst q.1) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (j : Vertex) : + reconnectedForwardPath Kp Kq hm t ≠ D'.vertex j := + path_interior_avoids_vertices_of_range D'.vertex _ _ _ + (reconnectedForwardPath_injective Kp Kq hm hadj hemb) + (reconnectedForwardPath_vertex_eq Kp Kq hm hv) t ht j + +theorem reconnectedBackwardPath_interior_avoids_vertices + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hadj : graph.src p.1 = graph.src q.1 ∨ graph.dst p.1 = graph.dst q.1) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (j : Vertex) : + reconnectedBackwardPath Kp Kq hm t ≠ D'.vertex j := + path_interior_avoids_vertices_of_range D'.vertex _ _ _ + (reconnectedBackwardPath_injective Kp Kq hm hadj hemb) + (reconnectedBackwardPath_vertex_eq Kp Kq hm hv) t ht j + +end Paper170Geometry + +end +end + +section + +/-! Replacement of two actual drawing routes with proved simple, vertex-avoiding paths. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170.ContinuousDrawing +def replaceTwoRoutes (D : Paper170.ContinuousDrawing graph) (e f : Edge) + (γ : Path (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (δ : Path (D.vertex ((graph.src f))) (D.vertex ((graph.dst f)))) + (g : Edge) : Path (D.vertex ((graph.src g))) (D.vertex ((graph.dst g))) := by + classical + exact if h : g=e then γ.cast (congrArg (fun k : Edge => D.vertex ((graph.src k))) h) + (congrArg (fun k : Edge => D.vertex ((graph.dst k))) h) + else if h : g=f then δ.cast (congrArg (fun k : Edge => D.vertex ((graph.src k))) h) + (congrArg (fun k : Edge => D.vertex ((graph.dst k))) h) + else D.edge g + +theorem replaceTwoRoutes_first (D : Paper170.ContinuousDrawing graph) (e f : Edge) + (γ : Path (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (δ : Path (D.vertex ((graph.src f))) (D.vertex ((graph.dst f)))) : + D.replaceTwoRoutes e f γ δ e=γ := by + simp only [replaceTwoRoutes,dite_eq_left rfl,Path.cast_rfl_rfl] + +theorem replaceTwoRoutes_second (D : Paper170.ContinuousDrawing graph) (e f : Edge) (hef : e ≠ f) + (γ : Path (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (δ : Path (D.vertex ((graph.src f))) (D.vertex ((graph.dst f)))) : + D.replaceTwoRoutes e f γ δ f=δ := by + simp only [replaceTwoRoutes,dite_eq_right (Ne.symm hef),dite_eq_left rfl,Path.cast_rfl_rfl] + +theorem replaceTwoRoutes_other (D : Paper170.ContinuousDrawing graph) (e f : Edge) + (γ : Path (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (δ : Path (D.vertex ((graph.src f))) (D.vertex ((graph.dst f)))) + (g : Edge) (hge : g ≠ e) (hgf : g ≠ f) : + D.replaceTwoRoutes e f γ δ g=D.edge g := by + simp only [replaceTwoRoutes,dite_eq_right hge,dite_eq_right hgf] + +def replaceTwoEdges (D : Paper170.ContinuousDrawing graph) (e f : Edge) + (γ : Path (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (δ : Path (D.vertex ((graph.src f))) (D.vertex ((graph.dst f)))) + (hγ : Function.Injective γ) (hδ : Function.Injective δ) + (hvγ : ∀ t, t ∈ Set.Ioo (0 : unitInterval) 1 → ∀ j, γ t ≠ D.vertex j) + (hvδ : ∀ t, t ∈ Set.Ioo (0 : unitInterval) 1 → ∀ j, δ t ≠ D.vertex j) : + Paper170.ContinuousDrawing graph where + vertex := D.vertex + vertex_injective := D.vertex_injective + edge := D.replaceTwoRoutes e f γ δ + edge_injective := by + intro g + classical + by_cases hge : g=e + · subst g + rw [replaceTwoRoutes_first] + exact hγ + by_cases hgf : g=f + · subst g + rw [replaceTwoRoutes_second _ _ _ (Ne.symm hge)] + exact hδ + · rw [replaceTwoRoutes_other _ _ _ _ _ _ hge hgf] + exact D.edge_injective g + interior_avoids_vertices := by + intro g t ht j + classical + by_cases hge : g=e + · subst g + rw [replaceTwoRoutes_first] + exact hvγ t ht j + by_cases hgf : g=f + · subst g + rw [replaceTwoRoutes_second _ _ _ (Ne.symm hge)] + exact hvδ t ht j + · rw [replaceTwoRoutes_other _ _ _ _ _ _ hge hgf] + exact D.interior_avoids_vertices g t ht j + +end Paper170.ContinuousDrawing + +end +end + +section + +/-! Trace case analysis for the actual two-route replacement. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170.ContinuousDrawing +theorem replaceTwoRoutes_range_cases (D : Paper170.ContinuousDrawing graph) (e f : Edge) + (γ : Path (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (δ : Path (D.vertex ((graph.src f))) (D.vertex ((graph.dst f)))) + (g : Edge) (x : Plane) (hx : x ∈ Set.range (D.replaceTwoRoutes e f γ δ g)) : + (g=e ∧ x ∈ Set.range γ) ∨ (g=f ∧ x ∈ Set.range δ) ∨ + (g ≠ e ∧ g ≠ f ∧ x ∈ Set.range (D.edge g)) := by + classical + by_cases hge : g=e + · subst g + exact Or.inl ⟨rfl,by simpa only [replaceTwoRoutes_first] using hx⟩ + by_cases hgf : g=f + · subst g + exact Or.inr (Or.inl ⟨rfl,by simpa only [replaceTwoRoutes_second D e f (Ne.symm hge)] using hx⟩) + · exact Or.inr (Or.inr ⟨hge,hgf,by simpa only [replaceTwoRoutes_other D e f γ δ g hge hgf] using hx⟩) + +end Paper170.ContinuousDrawing + +end +end + +section + +/-! Assigning the two switched paths to the original edges for either shared endpoint. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +def adjacentSurgeryRouteP (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) : + Path (D'.vertex ((graph.src p.1))) (D'.vertex ((graph.dst p.1))) := by + classical + exact if h : (graph.src p.1)=(graph.src q.1) then (reconnectedBackwardPath Kp Kq hm).cast + (congrArg (fun i => D'.vertex (i)) h) rfl + else (reconnectedForwardPath Kp Kq hm).cast rfl + (congrArg (fun j => D'.vertex (j)) (hadj.resolve_left h)) + +def adjacentSurgeryRouteQ (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) : + Path (D'.vertex ((graph.src q.1))) (D'.vertex ((graph.dst q.1))) := by + classical + exact if h : (graph.src p.1)=(graph.src q.1) then (reconnectedForwardPath Kp Kq hm).cast + (congrArg (fun i => D'.vertex (i)) h.symm) rfl + else (reconnectedBackwardPath Kp Kq hm).cast rfl + (congrArg (fun j => D'.vertex (j)) (hadj.resolve_left h).symm) + +theorem adjacentSurgeryRouteP_injective (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Function.Injective (adjacentSurgeryRouteP Kp Kq hm hadj) := by + unfold adjacentSurgeryRouteP + split + · exact reconnectedBackwardPath_injective Kp Kq hm hadj hemb + · exact reconnectedForwardPath_injective Kp Kq hm hadj hemb + +theorem adjacentSurgeryRouteQ_injective (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Function.Injective (adjacentSurgeryRouteQ Kp Kq hm hadj) := by + unfold adjacentSurgeryRouteQ + split + · exact reconnectedForwardPath_injective Kp Kq hm hadj hemb + · exact reconnectedBackwardPath_injective Kp Kq hm hadj hemb + +theorem adjacentSurgeryRouteP_avoids_vertices + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (j : Vertex) : + adjacentSurgeryRouteP Kp Kq hm hadj t ≠ D'.vertex j := by + unfold adjacentSurgeryRouteP + split + · exact reconnectedBackwardPath_interior_avoids_vertices Kp Kq hm hv hadj hemb t ht j + · exact reconnectedForwardPath_interior_avoids_vertices Kp Kq hm hv hadj hemb t ht j + +theorem adjacentSurgeryRouteQ_avoids_vertices + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) (j : Vertex) : + adjacentSurgeryRouteQ Kp Kq hm hadj t ≠ D'.vertex j := by + unfold adjacentSurgeryRouteQ + split + · exact reconnectedForwardPath_interior_avoids_vertices Kp Kq hm hv hadj hemb t ht j + · exact reconnectedBackwardPath_interior_avoids_vertices Kp Kq hm hv hadj hemb t ht j + +end Paper170Geometry + +end +end + +section + +/-! An actual continuous drawing with the two adjacent routes replaced. Admissibility is a later theorem. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +def adjacentSurgeryDrawing (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : Paper170.ContinuousDrawing graph := + D'.toContinuousDrawing.replaceTwoEdges p.1 q.1 + (adjacentSurgeryRouteP Kp Kq hm hadj) (adjacentSurgeryRouteQ Kp Kq hm hadj) + (adjacentSurgeryRouteP_injective Kp Kq hm hadj hemb) + (adjacentSurgeryRouteQ_injective Kp Kq hm hadj hemb) + (adjacentSurgeryRouteP_avoids_vertices Kp Kq hm hadj hv hemb) + (adjacentSurgeryRouteQ_avoids_vertices Kp Kq hm hadj hv hemb) + +theorem adjacentSurgeryDrawing_vertex (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).vertex=D'.vertex := rfl + +theorem adjacentSurgeryDrawing_first (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge p.1=adjacentSurgeryRouteP Kp Kq hm hadj := + Paper170.ContinuousDrawing.replaceTwoRoutes_first _ _ _ _ _ + +theorem adjacentSurgeryDrawing_second (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge q.1=adjacentSurgeryRouteQ Kp Kq hm hadj := + Paper170.ContinuousDrawing.replaceTwoRoutes_second _ _ _ (fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm)) _ _ + +theorem adjacentSurgeryDrawing_other (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (e : Edge) (hep : e ≠ p.1) (heq : e ≠ q.1) : + (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge e=D'.edge e := + Paper170.ContinuousDrawing.replaceTwoRoutes_other _ _ _ _ _ _ hep heq + +theorem adjacentSurgeryRouteP_hasFiniteAffineCover + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) : + HasFiniteAffineCover (adjacentSurgeryRouteP Kp Kq hm hadj) := by + unfold adjacentSurgeryRouteP + split + · exact (reconnectedBackwardPath_hasFiniteAffineCover Kp Kq hm).cast _ _ + · exact (reconnectedForwardPath_hasFiniteAffineCover Kp Kq hm).cast _ _ + +theorem adjacentSurgeryRouteQ_hasFiniteAffineCover + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) : + HasFiniteAffineCover (adjacentSurgeryRouteQ Kp Kq hm hadj) := by + unfold adjacentSurgeryRouteQ + split + · exact (reconnectedForwardPath_hasFiniteAffineCover Kp Kq hm).cast _ _ + · exact (reconnectedBackwardPath_hasFiniteAffineCover Kp Kq hm).cast _ _ + +end Paper170Geometry + +end +end + +section + +/-! Polygonality and actual removal of the selected point from every new drawing route. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q : C.InnerIndex} + +theorem adjacentSurgeryDrawing_hasFiniteAffineCover + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (e : Edge) : HasFiniteAffineCover ((adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge e) := by + classical + by_cases hep : e=p.1 + · subst e + rw [adjacentSurgeryDrawing_first] + exact adjacentSurgeryRouteP_hasFiniteAffineCover Kp Kq hm hadj + by_cases heq : e=q.1 + · subst e + rw [adjacentSurgeryDrawing_second Kp Kq hm hpq] + exact adjacentSurgeryRouteQ_hasFiniteAffineCover Kp Kq hm hadj + · rw [adjacentSurgeryDrawing_other Kp Kq hm hadj hv hemb e hep heq] + exact (P e).hasFiniteAffineCover + +theorem adjacentSurgeryRoutes_avoid_crossing + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∉ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj) ∧ + x ∉ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj) := by + have ha := reconnected_paths_avoid_crossing Kp Kq hm hpq x hxp hxq + constructor + · unfold adjacentSurgeryRouteP + split + · exact ha.2 + · exact ha.1 + · unfold adjacentSurgeryRouteQ + split + · exact ha.1 + · exact ha.2 + +theorem adjacentSurgeryDrawing_avoids_crossing + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hm : C.innerMark p=C.innerMark q) (hpq : p ≠ q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hv : ∀ j, squaredLength (D'.vertex j-D.vertex j) < C.radius^2) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) + (hother : ∀ e, e ≠ p.1 → e ≠ q.1 → x ∉ Set.range (D'.edge e)) : + ∀ e, x ∉ Set.range ((adjacentSurgeryDrawing Kp Kq hm hadj hv hemb).edge e) := by + have ha := adjacentSurgeryRoutes_avoid_crossing Kp Kq hm hpq hadj x hxp hxq + intro e + classical + by_cases hep : e=p.1 + · subst e + rw [adjacentSurgeryDrawing_first] + exact ha.1 + by_cases heq : e=q.1 + · subst e + rw [adjacentSurgeryDrawing_second Kp Kq hm hpq] + exact ha.2 + · rw [adjacentSurgeryDrawing_other Kp Kq hm hadj hv hemb e hep heq] + exact hother e hep heq + +end Paper170Geometry + +end +end + +section + +/-! All cut and embedding data are constructed for the actual normalized drawing. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem exists_adjacentSurgery_continuousDrawing [Fintype Vertex] [Fintype Edge] (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (p q : C.InnerIndex) (hpq : p ≠ q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + ∃ A : Paper170.ContinuousDrawing graph, A.vertex=v ∧ + (∀ e, HasFiniteAffineCover (A.edge e)) ∧ + (∀ e, x ∉ Set.range (A.edge e)) ∧ + (∀ e, e ≠ p.1 → e ≠ q.1 → ∀ t, A.edge e t=E.assembledEdge v e t) := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + have hcross := C.crossingChord_meeting_segmentsCrossProperly p q hpq x hxp hxq + obtain ⟨P,hmark,hport⟩ := E.exists_assembled_port_subdivision v hvinj hv hdet + obtain ⟨Kp⟩ := E.nonempty_exteriorCrossingCut v hvinj hv hdet P hport p + obtain ⟨Kq⟩ := E.nonempty_exteriorCrossingCut v hvinj hv hdet P hport q + have hemb := crossingSurgeryGraph_embedding C P hmark hport p q hm hcross + let A := adjacentSurgeryDrawing Kp Kq hm hadj hv hemb + refine ⟨A,rfl,adjacentSurgeryDrawing_hasFiniteAffineCover Kp Kq hm hpq hadj hv hemb,?_,?_⟩ + · apply adjacentSurgeryDrawing_avoids_crossing Kp Kq hm hpq hadj hv hemb x hxp hxq + intro e hep heq hx + exact Set.disjoint_left.mp (E.assembled_other_edge_avoids_crossingDisk v hv p q hpq hm e hep heq) + hx (C.reconnection_avoids_chord_meeting p q hpq x hxp hxq).1 + · intro e hep heq t + exact congrArg (fun γ => γ t) (adjacentSurgeryDrawing_other Kp Kq hm hadj hv hemb e hep heq) + +end Paper170Geometry.PolygonalExterior + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/AlgebraDefs.lean b/lean/OAI/Combinatorics/CompleteCrossing/AlgebraDefs.lean new file mode 100644 index 0000000000000000000000000000000000000000..5091e039f33649805aec9f7bc28fe430fdf1c136 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/AlgebraDefs.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.Crossing.NodeMoments +import Mathlib.Algebra.MvPolynomial.Degrees +import Mathlib.Algebra.MvPolynomial.Rename +import Mathlib.Algebra.Polynomial.Derivative +import Mathlib.Data.Fin.VecNotation +import Mathlib.Basic.Real.Basic +import Mathlib.LinearAlgebra.Matrix.BilinearForm + +namespace OAI + +/-! Polynomial spaces, interpolation weights, crossing tensors, and support evaluation. -/ + +section + +/-! Polynomial spaces and crossing tensors for complete graphs. + +These definitions contain no mathematical theorem assumptions. -/ + +open scoped BigOperators Classical + +noncomputable section + +namespace Paper170 + +abbrev Poly2 := MvPolynomial (Fin 2) ℝ +abbrev Poly4 := MvPolynomial (Fin 4) ℝ + +def nodeWeight {ι : Type*} [Fintype ι] (node : ι → ℝ) (i : ι) : ℝ := + (Zarankiewicz.derivativeAtNode node i)⁻¹ + +def omittedNodePolynomial {ι : Type*} [Fintype ι] [DecidableEq ι] + (node : ι → ℝ) (i : ι) : Polynomial ℝ := + ∏ j ∈ Finset.univ.erase i, (Polynomial.X - Polynomial.C (node j)) + +def rectangle (a b : ℕ) : Submodule ℝ Poly2 := + MvPolynomial.degreesLE ℝ (Fin 2) + (Multiset.replicate a 0 + Multiset.replicate b 1) + +def box4 (d : ℕ) : Submodule ℝ Poly4 := + MvPolynomial.degreesLE ℝ (Fin 4) (d • (Finset.univ : Finset (Fin 4)).val) + +def swapFirstPair : Poly4 →ₗ[ℝ] Poly4 := + (MvPolynomial.rename (Equiv.swap (0 : Fin 4) 1)).toLinearMap + +def swapSecondPair : Poly4 →ₗ[ℝ] Poly4 := + (MvPolynomial.rename (Equiv.swap (2 : Fin 4) 3)).toLinearMap + +def endpointSymmetricSpace (s : ℕ) : Submodule ℝ Poly4 := + box4 (s - 2) ⊓ LinearMap.ker (swapFirstPair - LinearMap.id) ⊓ + LinearMap.ker (swapSecondPair - LinearMap.id) + +def evalTwo (u v : ℝ) : Poly2 →ₗ[ℝ] ℝ := + (MvPolynomial.aeval ![u, v]).toLinearMap + +def evalFour (x u y v : ℝ) : Poly4 →ₗ[ℝ] ℝ := + (MvPolynomial.aeval ![x, u, y, v]).toLinearMap + +/-- The manuscript's one-based L_s, translated to zero-based Fin indices. -/ +def evenTriangle (s : ℕ) : Finset (Fin (2 * s) × Fin (2 * s)) := + Finset.univ.filter fun pq => + (pq.1.val < s ∧ pq.2 < pq.1) ∨ (s ≤ pq.1.val ∧ pq.1 < pq.2) + +abbrev EvenTriangleCoord (s : ℕ) := ↥(evenTriangle s) + +def triangleEvaluation (s a b : ℕ) (node : Fin (2 * s) → ℝ) : + rectangle a b →ₗ[ℝ] (EvenTriangleCoord s → ℝ) := + LinearMap.pi fun pq => + (evalTwo (node pq.val.1) (node pq.val.2)).comp (rectangle a b).subtype + +def halfOrder {ι : Type*} (order : LinearOrder ι) (p q : ι) : ℝ := + letI := order + if p < q then 1 / 2 else if q < p then -(1 / 2) else 0 + +def weightedPairing {ι : Type*} [Fintype ι] + (node : ι → ℝ) (K : ι → ι → ℝ) (A B : Poly2) : ℝ := + ∑ p, ∑ q, K p q * (node p - node q) / + (Zarankiewicz.derivativeAtNode node p * Zarankiewicz.derivativeAtNode node q) * + evalTwo (node p) (node q) A * evalTwo (node p) (node q) B + +def orderPairing {ι : Type*} [Fintype ι] + (node : ι → ℝ) (order : LinearOrder ι) (A B : Poly2) : ℝ := + weightedPairing node (halfOrder order) A B + +abbrev CrossingTensor (n : ℕ) := Fin n → Fin n → Fin n → Fin n → ℝ + +def chainBoundary {n : ℕ} (z : Fin n → Fin n → ℝ) (v : Fin n) : ℝ := + (∑ i, z i v) - ∑ p, z v p + +def chainPairing {n : ℕ} (J : CrossingTensor n) + (z z' : Fin n → Fin n → ℝ) : ℝ := + ∑ i, ∑ p, ∑ k, ∑ q, J i p k q * z i p * z' k q + +def polynomialTest {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (H : Poly4) : ℝ := + ∑ i, ∑ p, ∑ k, ∑ q, J i p k q * nodeWeight node i * nodeWeight node p * + nodeWeight node k * nodeWeight node q * evalFour (node i) (node p) (node k) (node q) H + +/-- Canonical orientation within each edge; the two edges remain ordered. -/ +def supportedPairs {n : ℕ} (J : CrossingTensor n) : + Finset ((Fin n × Fin n) × (Fin n × Fin n)) := + Finset.univ.filter fun a => + a.1.1 < a.1.2 ∧ a.2.1 < a.2.2 ∧ + a.1.1 ≠ a.2.1 ∧ a.1.1 ≠ a.2.2 ∧ + a.1.2 ≠ a.2.1 ∧ a.1.2 ≠ a.2.2 ∧ + J a.1.1 a.1.2 a.2.1 a.2.2 ≠ 0 + +abbrev SupportCoord {n : ℕ} (J : CrossingTensor n) := ↥(supportedPairs J) + +def supportEvaluation {n : ℕ} (s : ℕ) (node : Fin n → ℝ) (J : CrossingTensor n) : + endpointSymmetricSpace s →ₗ[ℝ] (SupportCoord J → ℝ) := + LinearMap.pi fun a => (evalFour (node a.val.1.1) (node a.val.1.2) + (node a.val.2.1) (node a.val.2.2)).comp (endpointSymmetricSpace s).subtype + +/-- C=(x-y)(x-v)(u-y)(u-v), with coordinates x,u,y,v. -/ +def collisionFactor : Poly4 := + (MvPolynomial.X 0 - MvPolynomial.X 2) * + (MvPolynomial.X 0 - MvPolynomial.X 3) * + (MvPolynomial.X 1 - MvPolynomial.X 2) * + (MvPolynomial.X 1 - MvPolynomial.X 3) + +/-- The complete six-difference product in the source's stated order. -/ +def fullDifference : Poly4 := + (MvPolynomial.X 0 - MvPolynomial.X 1) * + (MvPolynomial.X 2 - MvPolynomial.X 3) * collisionFactor + +/-- Substitute x=y=t, leaving u,v as the two variables. -/ +def vertexSpecialization (t : ℝ) : Poly4 →ₐ[ℝ] Poly2 := + MvPolynomial.aeval ![MvPolynomial.C t, MvPolynomial.X 0, + MvPolynomial.C t, MvPolynomial.X 1] + +/-- Substitute y=x, leaving x,u,v as three variables. -/ +def diagonalSpecialization : Poly4 →ₐ[ℝ] MvPolynomial (Fin 3) ℝ := + MvPolynomial.aeval ![MvPolynomial.X 0, MvPolynomial.X 1, + MvPolynomial.X 0, MvPolynomial.X 2] + +def supportDiagonal {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (a : SupportCoord J) : ℝ := + J a.val.1.1 a.val.1.2 a.val.2.1 a.val.2.2 * + nodeWeight node a.val.1.1 * nodeWeight node a.val.1.2 * + nodeWeight node a.val.2.1 * nodeWeight node a.val.2.2 * + evalFour (node a.val.1.1) (node a.val.1.2) (node a.val.2.1) (node a.val.2.2) + fullDifference + +def supportBilinear {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) : + LinearMap.BilinForm ℝ (SupportCoord J → ℝ) := + Matrix.toBilin' (Matrix.diagonal (supportDiagonal node J)) + +def weightedChain {n : ℕ} (node : Fin n → ℝ) (a b : ℕ) (i p : Fin n) : ℝ := + nodeWeight node i * nodeWeight node p * node i ^ a * node p ^ b + +def collisionFactors : Fin 4 → Poly4 := + ![MvPolynomial.X 0 - MvPolynomial.X 2, + MvPolynomial.X 0 - MvPolynomial.X 3, + MvPolynomial.X 1 - MvPolynomial.X 2, + MvPolynomial.X 1 - MvPolynomial.X 3] + +def liftUnivariate (i : Fin 4) (U : Polynomial ℝ) : Poly4 := + Polynomial.aeval (MvPolynomial.X i) U + +def liftBivariate (i j : Fin 4) (B : Poly2) : Poly4 := + MvPolynomial.aeval ![MvPolynomial.X i, MvPolynomial.X j] B + +def localTestPolynomial (P : Poly4) (U V : Polynomial ℝ) (B : Poly2) : Poly4 := + P * (MvPolynomial.X 1 - MvPolynomial.X 3) * + (MvPolynomial.X 1 - MvPolynomial.X 2) * (MvPolynomial.X 3 - MvPolynomial.X 0) * + liftUnivariate 0 U * liftUnivariate 2 V * liftBivariate 1 3 B + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Angles.lean b/lean/OAI/Combinatorics/CompleteCrossing/Angles.lean new file mode 100644 index 0000000000000000000000000000000000000000..21e2bf056a4d88e0eddfd577e1b46095c8eff852 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Angles.lean @@ -0,0 +1,376 @@ +import OAI.Combinatorics.CompleteCrossing.Plane +import OAI.Combinatorics.Crossing.ChordOrientations +import OAI.Combinatorics.Crossing.RadialBoundaryPorts +import OAI.Combinatorics.Crossing.SimilarityCoordinates +import Mathlib.Analysis.Complex.Arg +import Mathlib.Analysis.SpecialFunctions.Trigonometric.Arctan +import Mathlib.Tactic + +namespace OAI + +/-! Spoke angles, circle angles, scaling, and coordinate frames. -/ + +section + +noncomputable section +open scoped Classical +namespace Paper170 + +def complexPoint (a : Plane) : ℂ := ⟨a.1, a.2⟩ + +lemma complexPoint_injective : Function.Injective complexPoint := by + intro a b h + exact Prod.ext (congrArg Complex.re h) (congrArg Complex.im h) + +@[simp] lemma complexPoint_zero : complexPoint 0 = 0 := rfl + +@[simp] lemma complexPoint_smul (r : ℝ) (a : Plane) : + complexPoint (r • a) = (r : ℂ) * complexPoint a := by + apply Complex.ext <;> simp [complexPoint] + +lemma complexPoint_ne_zero {a : Plane} (ha : a ≠ 0) : complexPoint a ≠ 0 := by + exact fun h => ha (complexPoint_injective h) + +lemma spokeAngle_coe (cut : ℝ) (a : Plane) (ha : a ≠ 0) : + (spokeAngle cut a : Real.Angle) = (Complex.arg (complexPoint a) : Real.Angle) - cut := by + change (Complex.arg (Complex.exp (-(cut : ℂ) * Complex.I) * complexPoint a) : Real.Angle) = _ + rw [Complex.arg_mul_coe_angle (Complex.exp_ne_zero _) (complexPoint_ne_zero ha)] + simp [Complex.arg_exp, sub_eq_add_neg, add_comm] + +lemma finite_spoke_cut {ι : Type*} [Fintype ι] (a : ι → Plane) (ha : ∀ i, a i ≠ 0) : + ∃ cut : ℝ, ∀ i, spokeAngle cut (a i) ≠ Real.pi := by + have hreal (t : ℝ) : (Real.arctan t : Real.Angle).toReal = Real.arctan t := by + apply Real.Angle.toReal_coe_eq_self_iff.mpr + rcases Real.arctan_mem_Ioo t with ⟨hl, hu⟩ + constructor <;> linarith [Real.pi_pos] + have hinj : Function.Injective (fun t : ℝ => (Real.arctan t : Real.Angle)) := by + intro t u h + apply Real.arctan_injective + simpa only [hreal] using congrArg Real.Angle.toReal h + let := Infinite.of_injective _ hinj + let bad : ι → Real.Angle := fun i => (Complex.arg (complexPoint (a i)) : Real.Angle) - Real.pi + obtain ⟨θ, hθ⟩ := (Set.finite_range bad).exists_notMem + refine ⟨θ.toReal, ?_⟩ + intro i hi + have h := spokeAngle_coe θ.toReal (a i) (ha i) + rw [hi, Real.Angle.coe_toReal] at h + apply hθ + refine ⟨i, ?_⟩ + apply sub_eq_iff_eq_add.mpr + simpa [add_comm] using (eq_sub_iff_add_eq.mp h).symm + +lemma spokeAngle_eq_smul (cut : ℝ) (a b : Plane) (ha : a ≠ 0) (hb : b ≠ 0) + (h : spokeAngle cut a = spokeAngle cut b) : ∃ r : ℝ, 0 < r ∧ r • a = b := by + let q := Complex.exp (-(cut : ℂ) * Complex.I) + have hq : q ≠ 0 := Complex.exp_ne_zero _ + have ha' : q * complexPoint a ≠ 0 := mul_ne_zero hq (complexPoint_ne_zero ha) + have hb' : q * complexPoint b ≠ 0 := mul_ne_zero hq (complexPoint_ne_zero hb) + let r : ℝ := ‖q * complexPoint b‖ / ‖q * complexPoint a‖ + have hr : 0 < r := div_pos (norm_pos_iff.mpr hb') (norm_pos_iff.mpr ha') + refine ⟨r, hr, complexPoint_injective ?_⟩ + rw [complexPoint_smul] + apply mul_left_cancel₀ hq + have heq := (Complex.arg_eq_arg_iff ha' hb').mp h + rw [← Complex.ofReal_div] at heq + change ((r : ℂ) * (q * complexPoint a)) = q * complexPoint b at heq + calc + q * ((r : ℂ) * complexPoint a) = (r : ℂ) * (q * complexPoint a) := by ring + _ = q * complexPoint b := heq + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +lemma spokeAngle_smul (cut r : ℝ) (hr : 0 < r) (a : Plane) : + spokeAngle cut (r • a) = spokeAngle cut a := by + change Complex.arg (Complex.exp (-(cut : ℂ) * Complex.I) * complexPoint (r • a)) = _ + rw [complexPoint_smul, mul_left_comm, Complex.arg_real_mul _ hr] + rfl + +end Paper170 + +end +end + +section + +noncomputable section +open scoped Classical +namespace Paper170 + +lemma circlePoint_complex (t : ℝ) : + complexPoint (Zarankiewicz.circlePoint t) = + (Real.cos (2 * Real.arctan t) : ℂ) + (Real.sin (2 * Real.arctan t) : ℂ) * Complex.I := by + have hden := Zarankiewicz.circle_denominator_pos t + have hsqrt := Real.sq_sqrt hden.le + have hsqrt0 : Real.sqrt (1 + t ^ 2) ≠ 0 := ne_of_gt (Real.sqrt_pos.mpr hden) + apply Complex.ext + · simp only [Complex.add_re, Complex.mul_re, Complex.ofReal_re, Complex.ofReal_im, + Complex.I_re, Complex.I_im, mul_zero, zero_mul, sub_zero, add_zero] + rw [Real.cos_two_mul, Real.cos_sq_arctan] + dsimp [complexPoint, Zarankiewicz.circlePoint] + field_simp + ring + · simp only [Complex.add_im, Complex.mul_im, Complex.ofReal_re, Complex.ofReal_im, + Complex.I_re, Complex.I_im, mul_zero, mul_one, zero_add, add_zero] + rw [Real.sin_two_mul, Real.sin_arctan, Real.cos_arctan] + dsimp [complexPoint, Zarankiewicz.circlePoint] + field_simp + rw [hsqrt] + +lemma circlePoint_arg (t : ℝ) : + Complex.arg (complexPoint (Zarankiewicz.circlePoint t)) = 2 * Real.arctan t := by + rw [circlePoint_complex] + rw [Complex.ofReal_cos, Complex.ofReal_sin] + apply Complex.arg_cos_add_sin_mul_I + rcases Real.arctan_mem_Ioo t with ⟨hl, hu⟩ + constructor <;> linarith + +lemma circlePoint_arg_lt (a b : ℝ) : + Complex.arg (complexPoint (Zarankiewicz.circlePoint a)) < + Complex.arg (complexPoint (Zarankiewicz.circlePoint b)) ↔ a < b := by + rw [circlePoint_arg, circlePoint_arg, mul_lt_mul_iff_right₀ (by norm_num : (0 : ℝ) < 2)] + exact Real.arctan_strictMono.lt_iff_lt + +def angleRotation (cut : ℝ) (a : Plane) : Plane := + Zarankiewicz.similarityPoint 0 + ((Complex.exp (-(cut : ℂ) * Complex.I)).re, (Complex.exp (-(cut : ℂ) * Complex.I)).im) a + +lemma angleRotation_complex (cut : ℝ) (a : Plane) : + complexPoint (angleRotation cut a) = + Complex.exp (-(cut : ℂ) * Complex.I) * complexPoint a := by + apply Complex.ext <;> simp [complexPoint, angleRotation, Zarankiewicz.similarityPoint, add_comm] + +lemma angleRotation_unit (cut : ℝ) (a : Plane) (ha : squaredLength a = 1) : + squaredLength (angleRotation cut a) = 1 := by + have he : Complex.normSq (Complex.exp (-(cut : ℂ) * Complex.I)) = 1 := by + rw [← Complex.sq_norm] + simp [Complex.norm_exp] + have hform (p : Plane) : Complex.normSq (complexPoint p) = squaredLength p := by + simp [Complex.normSq_apply, complexPoint, squaredLength, pow_two] + have h : Complex.normSq (complexPoint a) = 1 := by rw [hform, ha] + rw [← hform] + rw [angleRotation_complex, map_mul, he, h, mul_one] + +lemma angleRotation_injective (cut : ℝ) : Function.Injective (angleRotation cut) := by + intro a b h + apply complexPoint_injective + apply mul_left_cancel₀ (Complex.exp_ne_zero (-(cut : ℂ) * Complex.I)) + simpa only [angleRotation_complex] using congrArg complexPoint h + +lemma angleRotation_sign (cut : ℝ) (a b c d : Plane) : + segmentIntersection (angleRotation cut a) (angleRotation cut b) + (angleRotation cut c) (angleRotation cut d) = segmentIntersection a b c d := by + simp only [segmentIntersection_eq_segmentCrossingSign] + apply Zarankiewicz.segmentCrossingSign_similarity + intro h + apply Complex.exp_ne_zero (-(cut : ℂ) * Complex.I) + exact Complex.ext (congrArg Prod.fst h) (congrArg Prod.snd h) + +lemma angleRotation_parameter (cut : ℝ) (a : Plane) (ha : squaredLength a = 1) + (hc : spokeAngle cut a ≠ Real.pi) : + ∃ t, Zarankiewicz.circlePoint t = angleRotation cut a := by + have hu := angleRotation_unit cut a ha + have hx : (angleRotation cut a).1 ≠ -1 := by + intro h + have hy : (angleRotation cut a).2 = 0 := by + dsimp [squaredLength] at hu + rw [h] at hu + nlinarith [sq_nonneg (angleRotation cut a).2] + apply hc + change Complex.arg (Complex.exp (-(cut : ℂ) * Complex.I) * complexPoint a) = _ + rw [← angleRotation_complex] + exact Complex.arg_eq_pi_iff.mpr ⟨by simpa only [complexPoint, h] using (by norm_num : (-1:ℝ)<0), hy⟩ + exact ⟨(angleRotation cut a).2 / (1 + (angleRotation cut a).1), + Zarankiewicz.circlePoint_surjective_away_cut _ hu hx⟩ + +theorem signed_chord_formula (p : Fin 4 → Plane) (hp : Function.Injective p) + (hc : ∀ i, squaredLength (p i) = 1) (cut : ℝ) + (hcut : ∀ i, spokeAngle cut (p i) ≠ Real.pi) : + segmentIntersection (p 0) (p 1) (p 2) (p 3) = (1 / 2 : ℝ) * + (circleComparison cut (p 0) (p 2) - circleComparison cut (p 0) (p 3) - + circleComparison cut (p 1) (p 2) + circleComparison cut (p 1) (p 3)) := by + choose t ht using fun i => angleRotation_parameter cut (p i) (hc i) (hcut i) + have hi : Function.Injective t := by + intro i j hij + apply hp + apply angleRotation_injective cut + rw [← ht i, ← ht j, hij] + have hs (i j : Fin 4) : circleComparison cut (p i) (p j) = Zarankiewicz.orderSign (t i) (t j) := by + have he (k : Fin 4) : spokeAngle cut (p k) = Complex.arg (complexPoint (Zarankiewicz.circlePoint (t k))) := by + rw [ht, angleRotation_complex] + rfl + simp only [circleComparison, he, circlePoint_arg_lt, Zarankiewicz.orderSign] + rw [← angleRotation_sign cut, ← ht 0, ← ht 1, ← ht 2, ← ht 3, + segmentIntersection_eq_segmentCrossingSign, + Zarankiewicz.circle_chord_pairing _ _ _ _ (hi.ne (by decide)) (hi.ne (by decide)) + (hi.ne (by decide)) (hi.ne (by decide)) (hi.ne (by decide)) (hi.ne (by decide))] + simp only [hs] + ring + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +variable {V E : Type} {G : Graph V E} + +lemma outwardSpoke_ne_zero (N : NormalizedDrawing G) (v : V) (e : E) : + outwardSpoke N v e ≠ 0 := by + unfold outwardSpoke + split_ifs + · exact (N.polygonal e).direction_ne_zero (N.edge_injective e) 0 (N.polygonal e).positive + · have h := (N.polygonal e).direction_ne_zero (N.edge_injective e) + ((N.polygonal e).pieces - 1) (by have := (N.polygonal e).positive; omega) + have hi : (N.polygonal e).pieces - 1 + 1 = (N.polygonal e).pieces := by + have := (N.polygonal e).positive + omega + rw [hi] at h + exact sub_ne_zero.mpr (Ne.symm (sub_ne_zero.mp h)) + +lemma outwardSpoke_interior (N : NormalizedDrawing G) (v : V) (e : G.IncidentEdge v) + (t : ℝ) (ht : 0 < t ∧ t < 1) : + N.vertex v + t • outwardSpoke N v e.val ∈ edgeInterior N.toContinuousDrawing e.val := by + by_cases hs : G.src e.val = v + · have h := (N.polygonal e.val).segment_mem_interior N.toContinuousDrawing e.val + ⟨0, (N.polygonal e.val).positive⟩ t ht + have hp : (N.polygonal e.val).vertices 0 = N.vertex v := by + simpa [hs] using (N.polygonal e.val).vertices_first + convert h using 1 + rw [outwardSpoke, ite_eq_left hs, hp] + simp only [segmentPoint] + module + · have hd : G.dst e.val = v := e.property.resolve_left hs + have hi : (N.polygonal e.val).pieces - 1 + 1 = (N.polygonal e.val).pieces := by + have := (N.polygonal e.val).positive + omega + have h := (N.polygonal e.val).segment_mem_interior N.toContinuousDrawing e.val + ⟨(N.polygonal e.val).pieces - 1, by have := (N.polygonal e.val).positive; omega⟩ + (1-t) ⟨by linarith, by linarith⟩ + have hp : (N.polygonal e.val).vertices (N.polygonal e.val).pieces = N.vertex v := by + simpa [hd] using (N.polygonal e.val).vertices_last + simp only [hi, hp] at h + convert h using 1 + rw [outwardSpoke, ite_eq_right hs, hp] + simp only [segmentPoint] + module + +lemma spokeAngle_injective (N : NormalizedDrawing G) (v : V) (cut : ℝ) : + Function.Injective (fun e : G.IncidentEdge v => spokeAngle cut (outwardSpoke N v e.val)) := by + intro e f h + by_contra hne + have hef : e.val ≠ f.val := fun h => hne (Subtype.ext h) + have hadj : G.src e.val = G.src f.val ∨ G.src e.val = G.dst f.val ∨ + G.dst e.val = G.src f.val ∨ G.dst e.val = G.dst f.val := by + rcases e.property with he | he <;> rcases f.property with hf | hf <;> grind + obtain ⟨r, hr, heq⟩ := spokeAngle_eq_smul cut (outwardSpoke N v e.val) + (outwardSpoke N v f.val) (outwardSpoke_ne_zero N v e.val) (outwardSpoke_ne_zero N v f.val) h + have hden : 0 < 1+r := by linarith + have ht : 0 < 1/(1+r) ∧ 1/(1+r) < 1 := by + constructor + · exact div_pos zero_lt_one hden + · exact (div_lt_one hden).mpr (by linarith) + have hu : 0 < r/(1+r) ∧ r/(1+r) < 1 := by + constructor + · exact div_pos hr hden + · exact (div_lt_one hden).mpr (by linarith) + have hx := outwardSpoke_interior N v e (r/(1+r)) hu + have hy := outwardSpoke_interior N v f (1/(1+r)) ht + have hxy : N.vertex v + (1/(1+r)) • outwardSpoke N v f.val = + N.vertex v + (r/(1+r)) • outwardSpoke N v e.val := by + rw [← heq, smul_smul] + congr 2 + ring + rw [hxy] at hy + exact Set.disjoint_left.mp (N.no_adjacent e.val f.val hef hadj) hx hy + +theorem spoke_orders_exist [Fintype V] [Fintype E] (G : Graph V E) + (N : NormalizedDrawing G) : Nonempty (SpokeOrders N) := by + have hc (v : V) : ∃ cut : ℝ, ∀ e : G.IncidentEdge v, + spokeAngle cut (outwardSpoke N v e.val) ≠ Real.pi := + finite_spoke_cut _ (fun e => outwardSpoke_ne_zero N v e.val) + choose cut hcut using hc + exact ⟨{ + cut := cut + order := fun v => LinearOrder.lift' _ (spokeAngle_injective N v (cut v)) + cut_avoids := hcut + compatible := fun _ _ _ => Iff.rfl + }⟩ + +end Paper170 + +end +end + +section + +noncomputable section +open Zarankiewicz +namespace Paper170 + +theorem complexPoint_similarity (o u x : Plane) : + complexPoint (similarityPoint o u x)=complexPoint o+complexPoint u*complexPoint x := by + apply Complex.ext <;> simp [complexPoint,similarityPoint,add_comm] + +def angleCoordinateFrame (cut radius : ℝ) : Plane := + radius • (((Complex.exp (-(cut:ℂ)*Complex.I))⁻¹).re, + ((Complex.exp (-(cut:ℂ)*Complex.I))⁻¹).im) + +theorem complexPoint_angleCoordinateFrame (cut radius : ℝ) : + complexPoint (angleCoordinateFrame cut radius)= + (radius:ℂ)*(Complex.exp (-(cut:ℂ)*Complex.I))⁻¹ := by + rw [angleCoordinateFrame,complexPoint_smul] + rfl + +theorem angleCoordinateFrame_length (cut radius : ℝ) : + squaredLength (angleCoordinateFrame cut radius)=radius^2 := by + have hq : Complex.normSq (Complex.exp (-(cut:ℂ)*Complex.I))=1 := by + rw [← Complex.sq_norm] + simp [Complex.norm_exp] + have hnorm (p : Plane) : squaredLength p=Complex.normSq (complexPoint p) := by + simp [complexPoint,squaredLength,Complex.normSq_apply,pow_two] + rw [hnorm,complexPoint_angleCoordinateFrame,map_mul,map_inv₀,hq,inv_one,mul_one] + simp [Complex.normSq_apply,pow_two] + +theorem angleCoordinateFrame_ne_zero (cut radius : ℝ) (hr : 0 r.1.1) he) + · exact hi.symm.trans (congrArg (fun r : C.Port => r.1.1) he) + · exact False.elim (Set.disjoint_left.mp (C.crossingChord_avoids_vertex_disks q j) + hx (C.vertex_spoke_range_in_disk v hv j p hy)) + +theorem middle_middle_meeting_chords (E : PolygonalExterior C) (e f : Edge) + (hef : e ≠ f) (x : Plane) (hx : x ∈ Set.range (E.middlePath e)) + (hy : x ∈ Set.range (E.middlePath f)) : + ∃ p q : C.InnerIndex, p.1=e ∧ q.1=f ∧ + x ∈ Set.range (C.crossingChord p) ∧ x ∈ Set.range (C.crossingChord q) := by + have he : ∃ p : C.InnerIndex, p.1=e ∧ x ∈ Set.range (C.crossingChord p) := by + rcases (E.middlePath_range_iff e x).mp hx with ⟨i,hi,hh⟩ | hh + · exact False.elim (hef ((E.middle_exterior_edge_eq f i x hy hh).trans hi).symm) + · exact hh + have hf : ∃ q : C.InnerIndex, q.1=f ∧ x ∈ Set.range (C.crossingChord q) := by + rcases (E.middlePath_range_iff f x).mp hy with ⟨i,hi,hh⟩ | hh + · exact False.elim (hef ((E.middle_exterior_edge_eq e i x hx hh).trans hi)) + · exact hh + obtain ⟨p,hp,hxp⟩ := he + obtain ⟨q,hq,hxq⟩ := hf + exact ⟨p,q,hp,hq,hxp,hxq⟩ + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Every nonvertex intersection of assembled edges is an actual crossing-disk chord intersection. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +theorem vertex_spokes_meeting (C : DrawingPassages D) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (j k : Vertex) (p : C.PortsAt (C.vertexMark j)) (q : C.PortsAt (C.vertexMark k)) + (hpq : p.val ≠ q.val) (x : Plane) + (hx : x ∈ Set.range (Path.segment (v j) (C.portPoint p.val))) + (hy : x ∈ Set.range (Path.segment (v k) (C.portPoint q.val))) : x=v j := by + by_cases hjk : j=k + · subst k + exact spokes_meet_only_at_center _ _ _ (hdet j p q (fun he => hpq (congrArg Subtype.val he))) + (by simpa only [Path.range_segment] using hx) (by simpa only [Path.range_segment] using hy) + · exact False.elim (Set.disjoint_left.mp (C.vertex_spokes_disjoint_of_vertices_ne v hv j k hjk p q) hx hy) + +end DrawingPassages +namespace PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem assembled_spoke_meeting (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e : Edge) (j : Vertex) (p : C.PortsAt (C.vertexMark j)) + (hep : e ≠ p.val.1.1) (x : Plane) (hx : x ∈ Set.range (E.assembledEdge v e)) + (hy : x ∈ Set.range (Path.segment (v j) (C.portPoint p.val))) : x=v j := by + rw [assembledEdge,Path.trans_range,Path.trans_range] at hx + rcases hx with (hx | hx) | hx + · exact C.vertex_spokes_meeting v hv hdet j _ p (C.startPortAt e) + (fun he => hep (congrArg (fun r : C.Port => r.1.1) he).symm) x hy hx + · exact False.elim (hep (E.middle_spoke_edge_eq v hv e j p x hx hy)) + · rw [endSpoke_range] at hx + exact C.vertex_spokes_meeting v hv hdet j _ p (C.endPortAt e) + (fun he => hep (congrArg (fun r : C.Port => r.1.1) he).symm) x hy hx + +theorem assembled_meeting_chords (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e f : Edge) (hef : e ≠ f) (x : Plane) + (havoid : ∀ j, x ≠ v j) (hx : x ∈ Set.range (E.assembledEdge v e)) + (hy : x ∈ Set.range (E.assembledEdge v f)) : + ∃ p q : C.InnerIndex, p.1=e ∧ q.1=f ∧ + x ∈ Set.range (C.crossingChord p) ∧ x ∈ Set.range (C.crossingChord q) := by + have hm (a b : Edge) (hab : a ≠ b) + (ha : x ∈ Set.range (E.assembledEdge v a)) (hb : x ∈ Set.range (E.assembledEdge v b)) : + x ∈ Set.range (E.middlePath a) := by + rw [assembledEdge,Path.trans_range,Path.trans_range] at ha + rcases ha with (ha | ha) | ha + · exact False.elim (havoid _ (E.assembled_spoke_meeting v hv hdet b _ (C.startPortAt a) + (Ne.symm hab) x hb ha)) + · exact ha + · rw [endSpoke_range] at ha + exact False.elim (havoid _ (E.assembled_spoke_meeting v hv hdet b _ (C.endPortAt a) + (Ne.symm hab) x hb ha)) + exact E.middle_middle_meeting_chords e f hef x (hm e f hef hx hy) (hm f e (Ne.symm hef) hy hx) + +theorem assembled_crossings_subset (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + Paper170.crossingPoints (E.assembledDrawing v hvinj hv) ⊆ C.chordCrossings := by + rintro x ⟨e,f,hef,⟨s,hs,he⟩,⟨t,ht,hf⟩⟩ + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x + (fun j heq => E.assembledEdge_interior_avoids_vertices v hv e s hs j (he.trans heq)) + ⟨s,he⟩ ⟨t,hf⟩ + exact ⟨p,q,(fun heq => hef (hp.symm.trans ((congrArg Sigma.fst heq).trans hq))),hxp,hxq⟩ + +theorem assembled_crossings_finite (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + (Paper170.crossingPoints (E.assembledDrawing v hvinj hv)).Finite := + C.chordCrossings_finite.subset (E.assembled_crossings_subset v hvinj hv hdet) + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! No triple intersection is introduced by the actual replacement drawing. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem assembled_no_triples (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e f g : Edge) (hef : e ≠ f) (heg : e ≠ g) (hfg : f ≠ g) : + Paper170.edgeInterior (E.assembledDrawing v hvinj hv) e ∩ + Paper170.edgeInterior (E.assembledDrawing v hvinj hv) f ∩ + Paper170.edgeInterior (E.assembledDrawing v hvinj hv) g=∅ := by + apply Set.eq_empty_iff_forall_notMem.mpr + rintro x ⟨⟨⟨s,hs,he⟩,⟨t,ht,hf⟩⟩,⟨u,hu,hg⟩⟩ + have ha : ∀ j, x ≠ v j := fun j heq => + E.assembledEdge_interior_avoids_vertices v hv e s hs j (he.trans heq) + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x ha ⟨s,he⟩ ⟨t,hf⟩ + obtain ⟨r,z,hr,hz,hxr,hxz⟩ := E.assembled_meeting_chords v hv hdet e g heg x ha ⟨s,he⟩ ⟨u,hg⟩ + apply C.innerMark_no_triples p q z + · intro heq + exact hef (hp.symm.trans ((congrArg Sigma.fst heq).trans hq)) + · intro heq + exact heg (hp.symm.trans ((congrArg Sigma.fst heq).trans hz)) + · intro heq + exact hfg (hq.symm.trans ((congrArg Sigma.fst heq).trans hz)) + · exact C.chord_meeting_marks_eq p q hxp hxq + · exact C.chord_meeting_marks_eq p z hxp hxz + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Each actual boundary port belongs to exactly its assigned assembled edge. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem portPoint_mem_exterior (E : PolygonalExterior C) (p : C.Port) : + C.portPoint p ∈ Set.range (E.chain p.1).path := by + rcases p with ⟨i,b⟩ + cases b + · exact ⟨0,(E.chain i).path.source⟩ + · exact ⟨1,(E.chain i).path.target⟩ + +theorem assembled_port_mem_range (E : PolygonalExterior C) (v : Vertex → Plane) + (p : C.Port) : C.portPoint p ∈ Set.range (E.assembledEdge v p.1.1) := by + apply (E.assembledEdge_range_iff v p.1.1 (C.portPoint p)).mpr + exact Or.inl (Or.inr (Or.inl ⟨p.1,rfl,E.portPoint_mem_exterior p⟩)) + +theorem assembled_exterior_edge_eq (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : Edge) (i : C.ArcIndex) (x : Plane) + (hx : x ∈ Set.range (E.assembledEdge v e)) (hy : x ∈ Set.range (E.chain i).path) : e=i.1 := by + rw [assembledEdge,Path.trans_range,Path.trans_range] at hx + rcases hx with (hx | hx) | hx + · obtain ⟨s,hs⟩ := hy + obtain ⟨t,ht⟩ := hx + have hh := E.exterior_spoke_meeting_parameters v hv i _ (C.startPortAt e) s t (hs.trans ht.symm) + rcases hh.2 with ⟨_,he⟩ | ⟨_,he⟩ + · exact (congrArg (fun p : C.Port => p.1.1) he).symm + · exact (congrArg (fun p : C.Port => p.1.1) he).symm + · exact E.middle_exterior_edge_eq e i x hx hy + · rw [endSpoke_range] at hx + obtain ⟨s,hs⟩ := hy + obtain ⟨t,ht⟩ := hx + have hh := E.exterior_spoke_meeting_parameters v hv i _ (C.endPortAt e) s t (hs.trans ht.symm) + rcases hh.2 with ⟨_,he⟩ | ⟨_,he⟩ + · exact (congrArg (fun p : C.Port => p.1.1) he).symm + · exact (congrArg (fun p : C.Port => p.1.1) he).symm + +theorem assembled_port_unique_edge (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : Edge) (p : C.Port) + (hp : C.portPoint p ∈ Set.range (E.assembledEdge v e)) : e=p.1.1 := + E.assembled_exterior_edge_eq v hv e p.1 (C.portPoint p) hp (E.portPoint_mem_exterior p) + +end Paper170Geometry.PolygonalExterior + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/CircleArcs.lean b/lean/OAI/Combinatorics/CompleteCrossing/CircleArcs.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ea048ee0f90a813957bf7f9e6f42a0e1c69e1ac --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/CircleArcs.lean @@ -0,0 +1,655 @@ +import OAI.Combinatorics.CompleteCrossing.Hill +import OAI.Combinatorics.CompleteCrossing.Plane +import OAI.Combinatorics.Crossing.CircleChords +import OAI.Combinatorics.Crossing.ProperCrossingLocality +import OAI.Combinatorics.Crossing.ProperSegmentCrossing +import OAI.Combinatorics.Crossing.RoundCircleChords +import Mathlib.Data.Set.Finite.Lattice +import Mathlib.LinearAlgebra.AffineSpace.AffineMap +import Mathlib.Topology.OpenPartialHomeomorph.Composition + +namespace OAI + +/-! Circle segments, inversion, continuous paths, and admissibility of two-page arcs. -/ + +section + +/-! Exact circle and inversion routes for the source's two-page drawing. + + -/ + +noncomputable section +open Set +open scoped Classical + +namespace Paper170 + +def chordInterior {n : ℕ} (p : Fin n → Plane) (e : CompleteEdge n) : Set Plane := + (segmentPoint (p e.val.1) (p e.val.2)) '' Ioo (0 : ℝ) 1 + +/-- The source's generic circle placement, stated only in geometric terms. -/ +structure CircleConfiguration (n : ℕ) where + point : Fin n → Plane + injective : Function.Injective point + on_circle : ∀ i, squaredLength (point i) = 1 + cyclic_order : ∀ i j k, i < j → j < k → + 0 < det2 (point j - point i) (point k - point i) + no_antipodal : ∀ i j, i ≠ j → point i + point j ≠ 0 + no_triple_chords : ∀ e f g : CompleteEdge n, e ≠ f → e ≠ g → f ≠ g → + chordInterior point e ∩ chordInterior point f ∩ chordInterior point g = ∅ + +def twoPageRoute {n : ℕ} (C : CircleConfiguration n) (e : CompleteEdge n) + (t : unitInterval) : Plane := + let x := segmentPoint (C.point e.val.1) (C.point e.val.2) t.val + if residueColor n (e.val.1.val + e.val.2.val) then x else inversion x + +/-- Equality with the actual circle/chord/inversion construction. -/ +structure TwoPageDrawing {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) : Prop where + vertex_eq : D.vertex = C.point + edge_eq : ∀ e t, D.edge e t = twoPageRoute C e t + +def lineIntersectionPoint (a b c d : Plane) : Plane := + a + (det2 (c - a) (d - c) / det2 (b - a) (d - c)) • (b - a) + +def crossingTuplePoint {n : ℕ} (C : CircleConfiguration n) (v : Fin 4 → Fin n) : Plane := + let x := lineIntersectionPoint (C.point (v 0)) (C.point (v 2)) + (C.point (v 1)) (C.point (v 3)) + if residueColor n ((v 0).val + (v 2).val) then x else inversion x + +end Paper170 + +end +end + +section + +noncomputable section +open Set +namespace Paper170 + +theorem chordInterior_eq_unitIntervalImage {n : ℕ} (p : Fin n → Plane) (e : CompleteEdge n) : + chordInterior p e = + (fun t : unitInterval => segmentPoint (p e.val.1) (p e.val.2) t.val) '' + Ioo (0 : unitInterval) 1 := by + ext x + constructor + · rintro ⟨t, ht, rfl⟩ + exact ⟨⟨t, ht.1.le, ht.2.le⟩, ht, rfl⟩ + · rintro ⟨t, ht, rfl⟩ + exact ⟨t.val, ht, rfl⟩ + +theorem twoPageRoute_image {n : ℕ} (C : CircleConfiguration n) (e : CompleteEdge n) : + twoPageRoute C e '' Ioo (0 : unitInterval) 1 = + if residueColor n (e.val.1.val + e.val.2.val) then chordInterior C.point e + else inversion '' chordInterior C.point e := by + change (fun t => twoPageRoute C e t) '' _ = _ + cases hc : residueColor n (e.val.1.val + e.val.2.val) <;> + simp [twoPageRoute, hc, chordInterior_eq_unitIntervalImage, Set.image_image] + +theorem twoPage_edgeInterior {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) + (e : CompleteEdge n) : + edgeInterior D.toContinuousDrawing e = + if residueColor n (e.val.1.val + e.val.2.val) then chordInterior C.point e + else inversion '' chordInterior C.point e := by + change (D.edge e : unitInterval → Plane) '' _ = _ + rw [show (D.edge e : unitInterval → Plane) = twoPageRoute C e from funext (hD.edge_eq e)] + exact twoPageRoute_image C e + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +theorem circle_points_noncollinear {n : ℕ} (p : Fin n → Plane) + (hp : Function.Injective p) (hc : ∀ i, squaredLength (p i) = 1) + {i j k : Fin n} (hij : i ≠ j) (hik : i ≠ k) (hjk : j ≠ k) : + Zarankiewicz.orient2 (p i) (p j) (p k) ≠ 0 := by + apply Zarankiewicz.round_circle_orient_ne_zero 0 (p i) (p j) (p k) 1 + · simpa only [sub_zero, one_pow, squaredLength, Zarankiewicz.squaredLength] using hc i + · simpa only [sub_zero, one_pow, squaredLength, Zarankiewicz.squaredLength] using hc j + · simpa only [sub_zero, one_pow, squaredLength, Zarankiewicz.squaredLength] using hc k + · exact hp.ne hij + · exact hp.ne hik + · exact hp.ne hjk + +theorem open_chord_reverse {a b x : Plane} (hx : x ∈ Zarankiewicz.openSegmentTrace a b) : + x ∈ Zarankiewicz.openSegmentTrace b a := by + obtain ⟨t, ht, rfl⟩ := hx + exact ⟨1 - t, ⟨by linarith [ht.2], by linarith [ht.1]⟩, + Zarankiewicz.segmentPoint_reverse a b t⟩ + +theorem open_chords_common_start {a b c x : Plane} + (hn : Zarankiewicz.orient2 a b c ≠ 0) + (hx : x ∈ Zarankiewicz.openSegmentTrace a b) + (hy : x ∈ Zarankiewicz.openSegmentTrace a c) : False := by + obtain ⟨t, ht, he⟩ := hx + obtain ⟨u, hu, hf⟩ := hy + have hz := congrArg (Zarankiewicz.orient2 a b) (he.trans hf.symm) + rw [Zarankiewicz.orient2_self_segment, Zarankiewicz.orient2_segment] at hz + have ha : Zarankiewicz.orient2 a b a = 0 := by simp [Zarankiewicz.orient2, Zarankiewicz.det2] + rw [ha, mul_zero, zero_add] at hz + exact hn ((mul_eq_zero.mp hz.symm).resolve_left (ne_of_gt hu.1)) + +theorem circle_chord_endpoints_distinct {n : ℕ} (p : Fin n → Plane) + (hp : Function.Injective p) (hc : ∀ i, squaredLength (p i) = 1) + (e f : CompleteEdge n) (hef : e ≠ f) (x : Plane) + (he : x ∈ chordInterior p e) (hf : x ∈ chordInterior p f) : + e.val.1 ≠ f.val.1 ∧ e.val.1 ≠ f.val.2 ∧ e.val.2 ≠ f.val.1 ∧ e.val.2 ≠ f.val.2 := by + have he' : x ∈ Zarankiewicz.openSegmentTrace (p e.val.1) (p e.val.2) := he + have hf' : x ∈ Zarankiewicz.openSegmentTrace (p f.val.1) (p f.val.2) := hf + have hei : e.val.1 < e.val.2 := e.property + have hfi : f.val.1 < f.val.2 := f.property + refine ⟨?_, ?_, ?_, ?_⟩ + · intro h + have hother : e.val.2 ≠ f.val.2 := by + intro hh + exact hef (Subtype.ext (Prod.ext h hh)) + have hn := circle_points_noncollinear p hp hc (ne_of_lt hei) + (show e.val.1 ≠ f.val.2 by rw [h]; exact ne_of_lt hfi) hother + rw [← h] at hf' + exact open_chords_common_start hn he' hf' + · intro h + have hn := circle_points_noncollinear p hp hc (ne_of_lt hei) + (show e.val.1 ≠ f.val.1 by rw [h]; exact ne_of_gt hfi) (by omega) + have hf'' := open_chord_reverse hf' + rw [← h] at hf'' + exact open_chords_common_start hn he' hf'' + · intro h + have hn := circle_points_noncollinear p hp hc (ne_of_gt hei) + (show e.val.2 ≠ f.val.2 by rw [h]; exact ne_of_lt hfi) (by omega) + have he'' := open_chord_reverse he' + rw [← h] at hf' + exact open_chords_common_start hn he'' hf' + · intro h + have hother : e.val.1 ≠ f.val.1 := by + intro hh + exact hef (Subtype.ext (Prod.ext hh h)) + have hn := circle_points_noncollinear p hp hc (ne_of_gt hei) + (show e.val.2 ≠ f.val.1 by rw [h]; exact ne_of_gt hfi) hother + have he'' := open_chord_reverse he' + have hf'' := open_chord_reverse hf' + rw [← h] at hf'' + exact open_chords_common_start hn he'' hf'' + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +theorem CircleConfiguration.orient_inside {n : ℕ} (C : CircleConfiguration n) + {i j k : Fin n} (hik : i < k) (hkj : k < j) : + Zarankiewicz.orient2 (C.point i) (C.point j) (C.point k) < 0 := by + rw [Zarankiewicz.orient2_swap_ends] + exact neg_neg_of_pos (C.cyclic_order i k j hik hkj) + +theorem CircleConfiguration.orient_outside {n : ℕ} (C : CircleConfiguration n) + {i j k : Fin n} (hij : i < j) (hk : k < i ∨ j < k) : + 0 < Zarankiewicz.orient2 (C.point i) (C.point j) (C.point k) := by + rcases hk with hk | hk + · rw [Zarankiewicz.orient2_cycle (C.point k) (C.point i) (C.point j)] + exact C.cyclic_order k i j hk hij + · exact C.cyclic_order i j k hij hk + +theorem CircleConfiguration.alternating_cross {n : ℕ} (C : CircleConfiguration n) + {i k j l : Fin n} (hik : i < k) (hkj : k < j) (hjl : j < l) : + Zarankiewicz.SegmentsCrossProperly (C.point i) (C.point j) (C.point k) (C.point l) := by + have hsign := Zarankiewicz.segmentCrossingSign_of_positive_sides + (C.point i) (C.point j) (C.point k) (C.point l) + (C.orient_inside hik hkj) (C.orient_outside (hik.trans hkj) (Or.inr hjl)) + (C.orient_outside (hkj.trans hjl) (Or.inl hik)) (C.orient_inside hkj hjl) + by_contra h + simp [Zarankiewicz.segmentCrossingSign, h] at hsign + +theorem lineIntersectionPoint_eq_parameter (a b c d : Plane) : + lineIntersectionPoint a b c d = + Zarankiewicz.segmentPoint a b (Zarankiewicz.firstIntersectionParameter a b c d) := by + have hnum : det2 (c - a) (d - c) = Zarankiewicz.det2 (d - c) (a - c) := by + dsimp [det2, Zarankiewicz.det2] + ring + unfold lineIntersectionPoint + rw [hnum] + change a + Zarankiewicz.firstIntersectionParameter a b c d • (b - a) = _ + ext <;> simp [Zarankiewicz.segmentPoint] <;> ring + +theorem open_chords_intersection_singleton (a b c d : Plane) + (h : Zarankiewicz.SegmentsCrossProperly a b c d) : + Zarankiewicz.openSegmentTrace a b ∩ Zarankiewicz.openSegmentTrace c d = + {lineIntersectionPoint a b c d} := by + have ht := (Zarankiewicz.segmentsCrossProperly_iff_parameters a b c d h.1).mp h + have hp : lineIntersectionPoint a b c d ∈ + Zarankiewicz.openSegmentTrace a b ∩ Zarankiewicz.openSegmentTrace c d := by + rw [lineIntersectionPoint_eq_parameter] + exact ⟨⟨_, ht.1, rfl⟩, ⟨_, ht.2, (Zarankiewicz.intersection_parameters_eq a b c d h.1).symm⟩⟩ + ext x + constructor + · intro hx + exact (Zarankiewicz.openSegment_intersection_subsingleton a b c d h.1 hx hp) + · rintro rfl + exact hp + +theorem circle_chord_intersection {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) (hef : e ≠ f) : + chordInterior C.point e ∩ chordInterior C.point f = + if (e.val.1 < f.val.1 ∧ f.val.1 < e.val.2 ∧ e.val.2 < f.val.2) ∨ + (f.val.1 < e.val.1 ∧ e.val.1 < f.val.2 ∧ f.val.2 < e.val.2) then + {lineIntersectionPoint (C.point e.val.1) (C.point e.val.2) + (C.point f.val.1) (C.point f.val.2)} + else ∅ := by + by_cases halt : (e.val.1 < f.val.1 ∧ f.val.1 < e.val.2 ∧ e.val.2 < f.val.2) ∨ + (f.val.1 < e.val.1 ∧ e.val.1 < f.val.2 ∧ f.val.2 < e.val.2) + · rw [ite_eq_left halt] + apply open_chords_intersection_singleton + rcases halt with ⟨h₁, h₂, h₃⟩ | ⟨h₁, h₂, h₃⟩ + · exact C.alternating_cross h₁ h₂ h₃ + · exact (Zarankiewicz.segmentsCrossProperly_swap _ _ _ _).mp + (C.alternating_cross h₁ h₂ h₃) + · rw [ite_eq_right halt] + apply Set.eq_empty_iff_forall_notMem.mpr + intro x hx + obtain ⟨h02, h03, h12, h13⟩ := circle_chord_endpoints_distinct C.point C.injective + C.on_circle e f hef x hx.1 hx.2 + have hei := e.property + have hfi := f.property + have htrans := Zarankiewicz.round_circle_chords_transverse 0 + (C.point e.val.1) (C.point e.val.2) (C.point f.val.1) (C.point f.val.2) 1 + (by simpa only [sub_zero, one_pow, squaredLength, Zarankiewicz.squaredLength] using C.on_circle e.val.1) + (by simpa only [sub_zero, one_pow, squaredLength, Zarankiewicz.squaredLength] using C.on_circle e.val.2) + (by simpa only [sub_zero, one_pow, squaredLength, Zarankiewicz.squaredLength] using C.on_circle f.val.1) + (by simpa only [sub_zero, one_pow, squaredLength, Zarankiewicz.squaredLength] using C.on_circle f.val.2) + (C.injective.ne (ne_of_lt hei)) (C.injective.ne (ne_of_lt hfi)) + (C.injective.ne h02) (C.injective.ne h03) (C.injective.ne h12) (C.injective.ne h13) + obtain ⟨t, ht, he⟩ := hx.1 + obtain ⟨u, hu, hf⟩ := hx.2 + have heq := he.trans hf.symm + have hcross : Zarankiewicz.SegmentsCrossProperly (C.point e.val.1) (C.point e.val.2) + (C.point f.val.1) (C.point f.val.2) := + ⟨(htrans t ⟨ht.1.le, ht.2.le⟩ u ⟨hu.1.le, hu.2.le⟩ heq).1, t, ht, u, hu, heq⟩ + apply Zarankiewicz.not_segmentsCrossProperly_of_same_side _ _ _ _ _ hcross + by_cases hinside : e.val.1 < f.val.1 ∧ f.val.1 < e.val.2 + · exact Or.inr ⟨C.orient_inside hinside.1 hinside.2, + C.orient_inside (by omega) (by omega)⟩ + · exact Or.inl ⟨C.orient_outside hei (by omega), C.orient_outside hei (by omega)⟩ + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +@[simp] theorem inversion_zero : inversion 0 = 0 := by + simp [inversion, squaredLength] + +theorem inversion_ne_zero {x : Plane} (hx : x ≠ 0) : inversion x ≠ 0 := by + intro h + exact hx ((inversion_involutive x).symm.trans ((congrArg inversion h).trans inversion_zero)) + +theorem continuous_squaredLength : Continuous squaredLength := by + unfold squaredLength + fun_prop + +theorem continuousAt_inversion {x : Plane} (hx : x ≠ 0) : ContinuousAt inversion x := by + have hq := ne_of_gt (squaredLength_pos hx) + exact (continuous_fst.continuousAt.div continuous_squaredLength.continuousAt hq).prodMk + (continuous_snd.continuousAt.div continuous_squaredLength.continuousAt hq) + +def inversionChart : OpenPartialHomeomorph Plane Plane where + toFun := inversion + invFun := inversion + source := {x | x ≠ 0} + target := {x | x ≠ 0} + map_source' := fun _ hx => inversion_ne_zero hx + map_target' := fun _ hx => inversion_ne_zero hx + left_inv' := fun x _ => inversion_involutive x + right_inv' := fun x _ => inversion_involutive x + continuousOn_toFun := fun _ hx => (continuousAt_inversion hx).continuousWithinAt + continuousOn_invFun := fun _ hx => (continuousAt_inversion hx).continuousWithinAt + open_source := isClosed_singleton.isOpen_compl + open_target := isClosed_singleton.isOpen_compl + +theorem inversion_chart_image (c : OpenPartialHomeomorph Plane Plane) (A L : Set Plane) + (h : c '' (c.source ∩ A) = c.target ∩ L) : + (inversionChart.trans c) '' ((inversionChart.trans c).source ∩ inversion '' A) = + (inversionChart.trans c).target ∩ L := by + let e := inversionChart.trans c + apply Set.Subset.antisymm + · rintro y ⟨z, hz, rfl⟩ + have hs : z ≠ 0 ∧ inversion z ∈ c.source := hz.1 + obtain ⟨a, ha, rfl⟩ := hz.2 + have hi : inversion (inversion a) ∈ A := (inversion_involutive a).symm ▸ ha + exact ⟨e.map_source hz.1, + (Zarankiewicz.chart_image_mem_iff c A L h _ hs.2).mp hi⟩ + · rintro y ⟨hy, hL⟩ + have hz := e.map_target hy + have hs : e.symm y ≠ 0 ∧ inversion (e.symm y) ∈ c.source := hz + have he : c (inversion (e.symm y)) = y := e.right_inv hy + have ha : inversion (e.symm y) ∈ A := + (Zarankiewicz.chart_image_mem_iff c A L h _ hs.2).mpr (he.symm ▸ hL) + exact ⟨e.symm y, ⟨hz, ⟨inversion (e.symm y), ha, inversion_involutive _⟩⟩, + e.right_inv hy⟩ + +theorem ProperCrossing.inverted {A B : Set Plane} {x : Plane} + (h : ProperCrossing A B x) (hx : x ≠ 0) : + ProperCrossing (inversion '' A) (inversion '' B) (inversion x) := by + obtain ⟨c, hs, he, hA, hB⟩ := h.chart_exists + refine ⟨inversionChart.trans c, ⟨inversion_ne_zero hx, ?_⟩, ?_, + inversion_chart_image c A _ hA, inversion_chart_image c B _ hB⟩ + · change inversion (inversion x) ∈ c.source + rwa [inversion_involutive] + · change c (inversion (inversion x)) = (0, 0) + rwa [inversion_involutive] + +theorem squaredLength_inversion {x : Plane} (hx : x ≠ 0) : + squaredLength (inversion x) = (squaredLength x)⁻¹ := by + have hq := ne_of_gt (squaredLength_pos hx) + change (x.1 / squaredLength x)^2 + (x.2 / squaredLength x)^2 = _ + rw [div_pow, div_pow, ← add_div] + change squaredLength x / squaredLength x ^ 2 = _ + field_simp + +theorem chord_ne_zero {a b : Plane} (ha : squaredLength a = 1) + (hb : squaredLength b = 1) (hab : a + b ≠ 0) (t : ℝ) : + segmentPoint a b t ≠ 0 := by + intro h + have h0 := congrArg Prod.fst h + have h1 := congrArg Prod.snd h + change (1-t)*a.1+t*b.1=0 at h0 + change (1-t)*a.2+t*b.2=0 at h1 + have ht : t = 1/2 := by + have he : (1-t)^2 * squaredLength a = t^2 * squaredLength b := by + unfold squaredLength + linear_combination ((1-t)*a.1-t*b.1)*h0 + ((1-t)*a.2-t*b.2)*h1 + rw [ha, hb] at he + nlinarith + apply hab + ext <;> dsimp <;> rw [ht] at h0 h1 <;> linarith + +theorem CircleConfiguration.chord_ne_zero {n : ℕ} (C : CircleConfiguration n) + (e : CompleteEdge n) (t : ℝ) : + segmentPoint (C.point e.val.1) (C.point e.val.2) t ≠ 0 := + Paper170.chord_ne_zero (C.on_circle _) (C.on_circle _) + (C.no_antipodal _ _ (ne_of_lt e.property)) t + +theorem CircleConfiguration.chord_inside {n : ℕ} (C : CircleConfiguration n) + (e : CompleteEdge n) {x : Plane} (hx : x ∈ chordInterior C.point e) : + squaredLength x < 1 := by + obtain ⟨t, ht, rfl⟩ := hx + simpa only [squaredLength, Zarankiewicz.squaredLength, sub_zero, one_pow, segmentPoint_eq] using + Zarankiewicz.round_chord_in_open_disk 0 (C.point e.val.1) (C.point e.val.2) 1 + (by simpa only [squaredLength, Zarankiewicz.squaredLength, sub_zero, one_pow] using C.on_circle e.val.1) + (by simpa only [squaredLength, Zarankiewicz.squaredLength, sub_zero, one_pow] using C.on_circle e.val.2) + (C.injective.ne (ne_of_lt e.property)) t ht + +theorem CircleConfiguration.chord_mem_ne_zero {n : ℕ} (C : CircleConfiguration n) + (e : CompleteEdge n) {x : Plane} (hx : x ∈ chordInterior C.point e) : x ≠ 0 := by + obtain ⟨t, _, rfl⟩ := hx + exact C.chord_ne_zero e t + +theorem CircleConfiguration.inverted_chord_outside {n : ℕ} (C : CircleConfiguration n) + (e : CompleteEdge n) {x : Plane} (hx : x ∈ inversion '' chordInterior C.point e) : + 1 < squaredLength x := by + obtain ⟨y, hy, rfl⟩ := hx + rw [squaredLength_inversion (C.chord_mem_ne_zero e hy)] + exact (one_lt_inv₀ (squaredLength_pos (C.chord_mem_ne_zero e hy))).mpr (C.chord_inside e hy) + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +theorem segmentPoint_injective {a b : Plane} (hab : a ≠ b) : + Function.Injective (segmentPoint a b) := by + intro s t h + apply AffineMap.lineMap_injective ℝ hab + simpa only [AffineMap.lineMap_apply_module, segmentPoint] using h + +theorem continuous_segmentPoint (a b : Plane) : Continuous (segmentPoint a b) := by + unfold segmentPoint + fun_prop + +theorem continuous_twoPageRoute {n : ℕ} (C : CircleConfiguration n) (e : CompleteEdge n) : + Continuous (twoPageRoute C e) := by + have hseg : Continuous (fun t : unitInterval => segmentPoint (C.point e.val.1) (C.point e.val.2) t.val) := + (continuous_segmentPoint _ _).comp continuous_subtype_val + change Continuous (fun t => twoPageRoute C e t) + cases hc : residueColor n (e.val.1.val + e.val.2.val) + · + simp only [twoPageRoute, hc, Bool.false_eq_true, ↓reduceIte] + exact continuous_iff_continuousAt.mpr (fun t => + (continuousAt_inversion (C.chord_ne_zero e t.val)).comp + (f := fun u : unitInterval => segmentPoint (C.point e.val.1) (C.point e.val.2) u.val) + hseg.continuousAt) + · simpa only [twoPageRoute, hc, ↓reduceIte] using hseg + +def twoPagePath {n : ℕ} (C : CircleConfiguration n) (e : CompleteEdge n) : + Path (C.point e.val.1) (C.point e.val.2) where + toFun := twoPageRoute C e + continuous_toFun := continuous_twoPageRoute C e + source' := by + simp [twoPageRoute, segmentPoint, inversion_fixes_circle _ (C.on_circle _)] + target' := by + simp [twoPageRoute, segmentPoint, inversion_fixes_circle _ (C.on_circle _)] + +theorem twoPageRoute_injective {n : ℕ} (C : CircleConfiguration n) (e : CompleteEdge n) : + Function.Injective (twoPageRoute C e) := by + have hseg := (segmentPoint_injective (C.injective.ne (ne_of_lt e.property))).comp + (show Function.Injective (fun t : unitInterval => t.val) from Subtype.val_injective) + cases hc : residueColor n (e.val.1.val + e.val.2.val) + · intro s t h + apply hseg + change segmentPoint (C.point e.val.1) (C.point e.val.2) s.val = + segmentPoint (C.point e.val.1) (C.point e.val.2) t.val + exact inversion_involutive.injective (by simpa only [twoPageRoute, hc, Bool.false_eq_true, ↓reduceIte] using h) + · intro s t h + apply hseg + change segmentPoint (C.point e.val.1) (C.point e.val.2) s.val = + segmentPoint (C.point e.val.1) (C.point e.val.2) t.val + simpa only [twoPageRoute, hc, ↓reduceIte] using h + +theorem twoPageRoute_avoids_vertices {n : ℕ} (C : CircleConfiguration n) + (e : CompleteEdge n) (t : unitInterval) (ht : t ∈ Ioo (0 : unitInterval) 1) (v : Fin n) : + twoPageRoute C e t ≠ C.point v := by + have hmem : twoPageRoute C e t ∈ twoPageRoute C e '' Ioo (0 : unitInterval) 1 := ⟨t, ht, rfl⟩ + rw [twoPageRoute_image] at hmem + intro he + rw [he] at hmem + cases hc : residueColor n (e.val.1.val + e.val.2.val) + · simp only [hc, Bool.false_eq_true, ↓reduceIte] at hmem + have h := C.inverted_chord_outside e hmem + rw [C.on_circle] at h + exact (lt_irrefl _ h) + · simp only [hc, ↓reduceIte] at hmem + have h := C.chord_inside e hmem + rw [C.on_circle] at h + exact (lt_irrefl _ h) + +def twoPageContinuous {n : ℕ} (C : CircleConfiguration n) : + ContinuousDrawing (completeGraph n) where + vertex := C.point + vertex_injective := C.injective + edge := twoPagePath C + edge_injective := twoPageRoute_injective C + interior_avoids_vertices := twoPageRoute_avoids_vertices C + +theorem twoPageContinuous_edgeInterior {n : ℕ} (C : CircleConfiguration n) (e : CompleteEdge n) : + edgeInterior (twoPageContinuous C) e = + if residueColor n (e.val.1.val + e.val.2.val) then chordInterior C.point e + else inversion '' chordInterior C.point e := + twoPageRoute_image C e + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +theorem CircleConfiguration.chord_proper {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) (hef : e ≠ f) {x : Plane} + (hx : x ∈ chordInterior C.point e) (hy : x ∈ chordInterior C.point f) : + ProperCrossing (chordInterior C.point e) (chordInterior C.point f) x := by + have hp : x ∈ chordInterior C.point e ∩ chordInterior C.point f := ⟨hx, hy⟩ + rw [circle_chord_intersection C e f hef] at hp + split_ifs at hp with halt + · have hcross : Zarankiewicz.SegmentsCrossProperly (C.point e.val.1) (C.point e.val.2) + (C.point f.val.1) (C.point f.val.2) := by + rcases halt with ⟨h₁, h₂, h₃⟩ | ⟨h₁, h₂, h₃⟩ + · exact C.alternating_cross h₁ h₂ h₃ + · exact (Zarankiewicz.segmentsCrossProperly_swap _ _ _ _).mp (C.alternating_cross h₁ h₂ h₃) + exact ⟨Zarankiewicz.properCrossing_openSegments _ _ _ _ x hcross.1 hx hy⟩ + · exact hp.elim + +theorem CircleConfiguration.chord_inter_finite {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) (hef : e ≠ f) : + (chordInterior C.point e ∩ chordInterior C.point f).Finite := by + rw [circle_chord_intersection C e f hef] + split_ifs <;> simp + +theorem CircleConfiguration.chord_inverted_disjoint {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) : + Disjoint (chordInterior C.point e) (inversion '' chordInterior C.point f) := by + apply Set.disjoint_left.mpr + intro x hx hy + exact lt_asymm (C.chord_inside e hx) (C.inverted_chord_outside f hy) + +theorem twoPageContinuous_same_color {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) {x : Plane} + (hx : x ∈ edgeInterior (twoPageContinuous C) e) + (hy : x ∈ edgeInterior (twoPageContinuous C) f) : + residueColor n (e.val.1.val + e.val.2.val) = + residueColor n (f.val.1.val + f.val.2.val) := by + rw [twoPageContinuous_edgeInterior] at hx hy + cases he : residueColor n (e.val.1.val + e.val.2.val) <;> + cases hf : residueColor n (f.val.1.val + f.val.2.val) <;> + simp only [he, hf, Bool.false_eq_true, ↓reduceIte] at hx hy ⊢ + · exact (lt_asymm (C.inverted_chord_outside e hx) (C.chord_inside f hy)).elim + · exact (lt_asymm (C.chord_inside e hx) (C.inverted_chord_outside f hy)).elim + +theorem twoPageContinuous_inter_finite {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) (hef : e ≠ f) : + (edgeInterior (twoPageContinuous C) e ∩ edgeInterior (twoPageContinuous C) f).Finite := by + rw [twoPageContinuous_edgeInterior, twoPageContinuous_edgeInterior] + cases he : residueColor n (e.val.1.val + e.val.2.val) <;> + cases hf : residueColor n (f.val.1.val + f.val.2.val) <;> + simp only [Bool.false_eq_true, ↓reduceIte] + · rw [← Set.image_inter inversion_involutive.injective] + exact (C.chord_inter_finite e f hef).image _ + · rw [(C.chord_inverted_disjoint f e).symm.inter_eq] + exact Set.finite_empty + · rw [(C.chord_inverted_disjoint e f).inter_eq] + exact Set.finite_empty + · exact C.chord_inter_finite e f hef + +theorem twoPageContinuous_crossings_finite {n : ℕ} (C : CircleConfiguration n) : + (crossingPoints (twoPageContinuous C)).Finite := by + have heq : crossingPoints (twoPageContinuous C) = + ⋃ e : CompleteEdge n, ⋃ f : CompleteEdge n, + if e = f then ∅ else edgeInterior (twoPageContinuous C) e ∩ + edgeInterior (twoPageContinuous C) f := by + ext x + simp only [crossingPoints, mem_ofPred_eq, mem_iUnion] + constructor + · rintro ⟨e, f, hef, hx, hy⟩ + exact ⟨e, f, by rw [ite_eq_right hef]; exact ⟨hx, hy⟩⟩ + · rintro ⟨e, f, hx⟩ + split_ifs at hx with hef + · exact hx.elim + · exact ⟨e, f, hef, hx.1, hx.2⟩ + rw [heq] + apply Set.finite_iUnion + intro e + apply Set.finite_iUnion + intro f + split_ifs with hef + · exact Set.finite_empty + · exact twoPageContinuous_inter_finite C e f hef + +theorem twoPageContinuous_proper {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) (hef : e ≠ f) (x : Plane) + (hx : x ∈ edgeInterior (twoPageContinuous C) e) + (hy : x ∈ edgeInterior (twoPageContinuous C) f) : + ProperCrossing (edgeInterior (twoPageContinuous C) e) + (edgeInterior (twoPageContinuous C) f) x := by + have hc := twoPageContinuous_same_color C e f hx hy + simp only [twoPageContinuous_edgeInterior] at hx hy ⊢ + rw [hc] at hx ⊢ + cases hf : residueColor n (f.val.1.val + f.val.2.val) <;> + simp only [hf, Bool.false_eq_true, ↓reduceIte] at hx hy ⊢ + · obtain ⟨a, ha, rfl⟩ := hx + obtain ⟨b, hb, he⟩ := hy + have hba : b = a := inversion_involutive.injective he + subst b + exact (C.chord_proper e f hef ha hb).inverted (C.chord_mem_ne_zero e ha) + · exact C.chord_proper e f hef hx hy + +theorem twoPageContinuous_no_triples {n : ℕ} (C : CircleConfiguration n) + (e f g : CompleteEdge n) (hef : e ≠ f) (heg : e ≠ g) (hfg : f ≠ g) : + edgeInterior (twoPageContinuous C) e ∩ edgeInterior (twoPageContinuous C) f ∩ + edgeInterior (twoPageContinuous C) g = ∅ := by + apply Set.eq_empty_iff_forall_notMem.mpr + intro x hx + have hcf := twoPageContinuous_same_color C e f hx.1.1 hx.1.2 + have hcg := twoPageContinuous_same_color C e g hx.1.1 hx.2 + simp only [twoPageContinuous_edgeInterior, ← hcf, ← hcg] at hx + cases he : residueColor n (e.val.1.val + e.val.2.val) <;> + simp only [he, Bool.false_eq_true, ↓reduceIte] at hx + · have hm : x ∈ inversion '' + (chordInterior C.point e ∩ chordInterior C.point f ∩ chordInterior C.point g) := by + rw [Set.image_inter inversion_involutive.injective, + Set.image_inter inversion_involutive.injective] + exact hx + rw [C.no_triple_chords e f g hef heg hfg, Set.image_empty] at hm + exact hm.elim + · rw [C.no_triple_chords e f g hef heg hfg] at hx + exact hx.elim + +def twoPageAdmissible {n : ℕ} (C : CircleConfiguration n) : + AdmissibleDrawing (completeGraph n) where + toContinuousDrawing := twoPageContinuous C + crossings_finite := twoPageContinuous_crossings_finite C + crossings_proper := twoPageContinuous_proper C + no_triples := twoPageContinuous_no_triples C + +theorem two_page_drawing_exists {n : ℕ} (C : CircleConfiguration n) : + ∃ D : AdmissibleDrawing (completeGraph n), TwoPageDrawing C D := + ⟨twoPageAdmissible C, rfl, fun _ _ => rfl⟩ + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/CirclePlacement.lean b/lean/OAI/Combinatorics/CompleteCrossing/CirclePlacement.lean new file mode 100644 index 0000000000000000000000000000000000000000..8423b088ca8f0009f71f8d7b5468a0fa3be08d67 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/CirclePlacement.lean @@ -0,0 +1,629 @@ +import OAI.Combinatorics.CompleteCrossing.CircleArcs +import OAI.Combinatorics.Crossing.FiniteCircleCoordinates +import OAI.Combinatorics.Crossing.GenericPolynomialBox +import OAI.Combinatorics.Crossing.TangentTrackIdentity +import Mathlib.Data.Fintype.EquivFin +import Mathlib.Tactic.FunProp +import Mathlib.Topology.Order.Basic + +namespace OAI + +/-! Generic circular placement, prescribed arcs, restrictions, and existence of drawings. -/ + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +variable {V E : Type} {m : ℕ} + +def completeEdgeOf (G : Graph V E) (ι : V ↪ Fin m) (e : E) : CompleteEdge m := + if h : ι (G.src e) < ι (G.dst e) then ⟨(ι (G.src e), ι (G.dst e)), h⟩ + else ⟨(ι (G.dst e), ι (G.src e)), by change ι (G.dst e) < ι (G.src e); have := ι.injective.ne (G.loopless e); omega⟩ + +theorem completeEdgeOf_endpoints (G : Graph V E) (ι : V ↪ Fin m) (e : E) : + ((completeEdgeOf G ι e).val.1 = ι (G.src e) ∧ + (completeEdgeOf G ι e).val.2 = ι (G.dst e)) ∨ + ((completeEdgeOf G ι e).val.1 = ι (G.dst e) ∧ + (completeEdgeOf G ι e).val.2 = ι (G.src e)) := by + unfold completeEdgeOf + split_ifs <;> simp + +theorem completeEdgeOf_injective (G : Graph V E) (ι : V ↪ Fin m) : + Function.Injective (completeEdgeOf G ι) := by + intro e f h + have h₁ := congrArg (fun a : CompleteEdge m => a.val.1) h + have h₂ := congrArg (fun a : CompleteEdge m => a.val.2) h + rcases completeEdgeOf_endpoints G ι e with he | he <;> + rcases completeEdgeOf_endpoints G ι f with hf | hf + · exact G.simple e f (Or.inl ⟨ι.injective (he.1.symm.trans (h₁.trans hf.1)), + ι.injective (he.2.symm.trans (h₂.trans hf.2))⟩) + · exact G.simple e f (Or.inr ⟨ι.injective (he.1.symm.trans (h₁.trans hf.1)), + ι.injective (he.2.symm.trans (h₂.trans hf.2))⟩) + · exact G.simple e f (Or.inr ⟨ι.injective (he.2.symm.trans (h₂.trans hf.2)), + ι.injective (he.1.symm.trans (h₁.trans hf.1))⟩) + · exact G.simple e f (Or.inl ⟨ι.injective (he.2.symm.trans (h₂.trans hf.2)), + ι.injective (he.1.symm.trans (h₁.trans hf.1))⟩) + +theorem unitInterval_symm_mem_open {t : unitInterval} (ht : t ∈ Ioo (0 : unitInterval) 1) : + unitInterval.symm t ∈ Ioo (0 : unitInterval) 1 := by + have h0 : (0 : ℝ) < t.val := ht.1 + have h1 : t.val < (1 : ℝ) := ht.2 + change 0 < 1 - t.val ∧ 1 - t.val < 1 + constructor <;> linarith + +theorem path_symm_open_image {a b : Plane} (γ : Path a b) : + γ.symm '' Ioo (0 : unitInterval) 1 = γ '' Ioo (0 : unitInterval) 1 := by + ext x + constructor + · rintro ⟨t, ht, rfl⟩ + exact ⟨unitInterval.symm t, unitInterval_symm_mem_open ht, rfl⟩ + · rintro ⟨t, ht, rfl⟩ + refine ⟨unitInterval.symm t, unitInterval_symm_mem_open ht, ?_⟩ + change γ (unitInterval.symm (unitInterval.symm t)) = γ t + rw [unitInterval.symm_involutive t] + +def restrictedCompletePath (G : Graph V E) (ι : V ↪ Fin m) + (D : AdmissibleDrawing (completeGraph m)) (e : E) : + Path (D.vertex (ι (G.src e))) (D.vertex (ι (G.dst e))) where + toFun t := if h : ι (G.src e) < ι (G.dst e) then + D.edge ⟨(ι (G.src e), ι (G.dst e)), h⟩ t + else D.edge ⟨(ι (G.dst e), ι (G.src e)), + by change ι (G.dst e) < ι (G.src e); have := ι.injective.ne (G.loopless e); omega⟩ + (unitInterval.symm t) + continuous_toFun := by + split_ifs with h + · exact (D.edge _).continuous + · exact (D.edge _).continuous.comp unitInterval.continuous_symm + source' := by + split_ifs + · exact (D.edge _).source + · rw [unitInterval.symm_zero] + exact (D.edge _).target + target' := by + split_ifs + · exact (D.edge _).target + · rw [unitInterval.symm_one] + exact (D.edge _).source + +theorem restrictedCompletePath_injective (G : Graph V E) (ι : V ↪ Fin m) + (D : AdmissibleDrawing (completeGraph m)) (e : E) : + Function.Injective (restrictedCompletePath G ι D e) := by + intro s t he + by_cases h : ι (G.src e) < ι (G.dst e) + · let f : CompleteEdge m := ⟨(ι (G.src e), ι (G.dst e)), h⟩ + have hpath : (restrictedCompletePath G ι D e : unitInterval → Plane) = D.edge f := by + funext t + exact dite_eq_left h + exact D.edge_injective f ((congrFun hpath s).symm.trans (he.trans (congrFun hpath t))) + · let f : CompleteEdge m := ⟨(ι (G.dst e), ι (G.src e)), + by change ι (G.dst e) < ι (G.src e); have := ι.injective.ne (G.loopless e); omega⟩ + have hpath : (restrictedCompletePath G ι D e : unitInterval → Plane) = (D.edge f).symm := by + funext t + exact dite_eq_right h + have he' := (congrFun hpath s).symm.trans (he.trans (congrFun hpath t)) + exact unitInterval.symm_involutive.injective (D.edge_injective _ he') + +theorem restrictedCompletePath_interior (G : Graph V E) (ι : V ↪ Fin m) + (D : AdmissibleDrawing (completeGraph m)) (e : E) : + restrictedCompletePath G ι D e '' Ioo (0 : unitInterval) 1 = + edgeInterior D.toContinuousDrawing (completeEdgeOf G ι e) := by + by_cases h : ι (G.src e) < ι (G.dst e) + · let f : CompleteEdge m := ⟨(ι (G.src e), ι (G.dst e)), h⟩ + have hedge : completeEdgeOf G ι e = f := dite_eq_left h + have hpath : (restrictedCompletePath G ι D e : unitInterval → Plane) = D.edge f := by + funext t + exact dite_eq_left h + rw [hpath, hedge] + rfl + · let f : CompleteEdge m := ⟨(ι (G.dst e), ι (G.src e)), + by change ι (G.dst e) < ι (G.src e); have := ι.injective.ne (G.loopless e); omega⟩ + have hedge : completeEdgeOf G ι e = f := dite_eq_right h + have hpath : (restrictedCompletePath G ι D e : unitInterval → Plane) = (D.edge f).symm := by + funext t + exact dite_eq_right h + rw [hpath, hedge] + exact path_symm_open_image (D.edge f) + +theorem restrictedCompletePath_avoids (G : Graph V E) (ι : V ↪ Fin m) + (D : AdmissibleDrawing (completeGraph m)) (e : E) (t : unitInterval) + (ht : t ∈ Ioo (0 : unitInterval) 1) (v : V) : + restrictedCompletePath G ι D e t ≠ D.vertex (ι v) := by + have hm : restrictedCompletePath G ι D e t ∈ + restrictedCompletePath G ι D e '' Ioo (0 : unitInterval) 1 := ⟨t, ht, rfl⟩ + rw [restrictedCompletePath_interior] at hm + obtain ⟨u, hu, he⟩ := hm + rw [← he] + exact D.interior_avoids_vertices _ u hu _ + +def restrictedCompleteContinuous (G : Graph V E) (ι : V ↪ Fin m) + (D : AdmissibleDrawing (completeGraph m)) : ContinuousDrawing G where + vertex := D.vertex ∘ ι + vertex_injective := D.vertex_injective.comp ι.injective + edge := restrictedCompletePath G ι D + edge_injective := restrictedCompletePath_injective G ι D + interior_avoids_vertices := restrictedCompletePath_avoids G ι D + +theorem restrictedComplete_edgeInterior (G : Graph V E) (ι : V ↪ Fin m) + (D : AdmissibleDrawing (completeGraph m)) (e : E) : + edgeInterior (restrictedCompleteContinuous G ι D) e = + edgeInterior D.toContinuousDrawing (completeEdgeOf G ι e) := + restrictedCompletePath_interior G ι D e + +theorem restrictedComplete_crossings_subset (G : Graph V E) (ι : V ↪ Fin m) + (D : AdmissibleDrawing (completeGraph m)) : + crossingPoints (restrictedCompleteContinuous G ι D) ⊆ crossingPoints D.toContinuousDrawing := by + rintro x ⟨e, f, hef, hx, hy⟩ + rw [restrictedComplete_edgeInterior] at hx hy + exact ⟨_, _, (completeEdgeOf_injective G ι).ne hef, hx, hy⟩ + +def restrictedCompleteAdmissible (G : Graph V E) (ι : V ↪ Fin m) + (D : AdmissibleDrawing (completeGraph m)) : AdmissibleDrawing G where + toContinuousDrawing := restrictedCompleteContinuous G ι D + crossings_finite := D.crossings_finite.subset (restrictedComplete_crossings_subset G ι D) + crossings_proper := by + intro e f hef x hx hy + simp only [restrictedComplete_edgeInterior] at hx hy ⊢ + exact D.crossings_proper _ _ ((completeEdgeOf_injective G ι).ne hef) x hx hy + no_triples := by + intro e f g hef heg hfg + simp only [restrictedComplete_edgeInterior] + exact D.no_triples _ _ _ ((completeEdgeOf_injective G ι).ne hef) + ((completeEdgeOf_injective G ι).ne heg) ((completeEdgeOf_injective G ι).ne hfg) + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +def circleConcurrency {R : Type*} [CommRing R] (a b c d e f : R) : R := + (c + d) * e * f - c * d * (e + f) - (a + b) * (e * f - c * d) + + a * b * (e + f - c - d) + +def circleLine (a b : ℝ) (z : Plane) : ℝ := + (1 - a * b) * z.1 + (a + b) * z.2 - (1 + a * b) + +theorem circleLine_param (a b : ℝ) : circleLine a b (Zarankiewicz.circlePoint a) = 0 := by + have ha := ne_of_gt (Zarankiewicz.circle_denominator_pos a) + unfold circleLine Zarankiewicz.circlePoint + field_simp + ring + +theorem circleLine_chord (a b t : ℝ) : + circleLine a b (segmentPoint (Zarankiewicz.circlePoint a) (Zarankiewicz.circlePoint b) t) = 0 := by + have ha := circleLine_param a b + have hb := circleLine_param b a + unfold circleLine at * + change (1 - a * b) * ((1 - t) * (Zarankiewicz.circlePoint a).1 + t * (Zarankiewicz.circlePoint b).1) + + (a + b) * ((1 - t) * (Zarankiewicz.circlePoint a).2 + t * (Zarankiewicz.circlePoint b).2) - + (1 + a * b) = 0 + linear_combination (1 - t) * ha + t * hb + +theorem circleConcurrency_of_lines (a b c d e f : ℝ) (z : Plane) + (h₁ : circleLine a b z = 0) (h₂ : circleLine c d z = 0) (h₃ : circleLine e f z = 0) : + circleConcurrency a b c d e f = 0 := by + have he : 2 * circleConcurrency a b c d e f = 0 := by + unfold circleConcurrency circleLine at * + linear_combination + -((1 - c * d) * (e + f) - (1 - e * f) * (c + d)) * h₁ - + ((1 - e * f) * (a + b) - (1 - a * b) * (e + f)) * h₂ - + ((1 - a * b) * (c + d) - (1 - c * d) * (a + b)) * h₃ + linarith + +def circleConcurrencyPolynomial {n : ℕ} (v : Fin 6 → Fin n) : MvPolynomial (Fin n) ℝ := + circleConcurrency (MvPolynomial.X (v 0)) (MvPolynomial.X (v 1)) + (MvPolynomial.X (v 2)) (MvPolynomial.X (v 3)) + (MvPolynomial.X (v 4)) (MvPolynomial.X (v 5)) + +theorem circleConcurrencyPolynomial_eval {n : ℕ} (v : Fin 6 → Fin n) (t : Fin n → ℝ) : + MvPolynomial.eval t (circleConcurrencyPolynomial v) = + circleConcurrency (t (v 0)) (t (v 1)) (t (v 2)) (t (v 3)) (t (v 4)) (t (v 5)) := by + simp [circleConcurrencyPolynomial, circleConcurrency] + +theorem circleConcurrencyPolynomial_ne_zero {n : ℕ} (v : Fin 6 → Fin n) + (hv : Function.Injective v) : circleConcurrencyPolynomial v ≠ 0 := by + let t : Fin n → ℝ := fun i => if i = v 2 ∨ i = v 4 ∨ i = v 5 then 1 else 0 + have he : MvPolynomial.eval t (circleConcurrencyPolynomial v) = 1 := by + rw [circleConcurrencyPolynomial_eval] + simp only [t, hv.eq_iff] + norm_num [circleConcurrency, Fin.ext_iff] + intro hz + rw [hz, map_zero] at he + exact zero_ne_one he + +theorem circle_configuration_exists (n : ℕ) : Nonempty (CircleConfiguration n) := by + let I := {v : Fin 6 → Fin n // Function.Injective v} + let : Fintype I := Fintype.ofFinite I + obtain ⟨t, ht, havoid⟩ := Zarankiewicz.exists_box_avoiding_polynomials + (fun v : I => circleConcurrencyPolynomial v.val) + (fun v => circleConcurrencyPolynomial_ne_zero v.val v.property) + (fun i : Fin n => 2 * (i.val : ℝ) + 1) (fun i : Fin n => 2 * (i.val : ℝ) + 2) + (by intro i; linarith) + have htmono : StrictMono t := by + intro i j hij + have hij' : (i.val : ℝ) + 1 ≤ j.val := by exact_mod_cast hij + linarith [(ht i).2, (ht j).1] + have htpos (i : Fin n) : 0 < t i := by + have hnonneg : (0 : ℝ) ≤ i.val := Nat.cast_nonneg _ + linarith [(ht i).1] + let p := Zarankiewicz.circlePoint ∘ t + have hp : Function.Injective p := Zarankiewicz.circlePoint_injective.comp htmono.injective + have hcircle (i : Fin n) : squaredLength (p i) = 1 := Zarankiewicz.circlePoint_on_unit_circle (t i) + refine ⟨{ + point := p + injective := hp + on_circle := hcircle + cyclic_order := ?_ + no_antipodal := ?_ + no_triple_chords := ?_ }⟩ + · intro i j k hij hjk + exact Zarankiewicz.circle_orient_pos (t i) (t j) (t k) (htmono hij) (htmono hjk) + · intro i j _ he + have hi : 0 < (p i).2 := div_pos (by linarith [htpos i]) (Zarankiewicz.circle_denominator_pos _) + have hj : 0 < (p j).2 := div_pos (by linarith [htpos j]) (Zarankiewicz.circle_denominator_pos _) + have hz := congrArg Prod.snd he + change (p i).2 + (p j).2 = 0 at hz + linarith + · intro e f g hef heg hfg + apply Set.eq_empty_iff_forall_notMem.mpr + intro z hz + have hEF := circle_chord_endpoints_distinct p hp hcircle e f hef z hz.1.1 hz.1.2 + have hEG := circle_chord_endpoints_distinct p hp hcircle e g heg z hz.1.1 hz.2 + have hFG := circle_chord_endpoints_distinct p hp hcircle f g hfg z hz.1.2 hz.2 + let v : Fin 6 → Fin n := ![e.val.1, e.val.2, f.val.1, f.val.2, g.val.1, g.val.2] + have hv : Function.Injective v := by + intro i j heq + have he' := e.property + have hf' := f.property + have hg' := g.property + fin_cases i <;> fin_cases j <;> norm_num [v, Fin.ext_iff] at heq ⊢ <;> omega + have hne := havoid (⟨v, hv⟩ : I) + rw [circleConcurrencyPolynomial_eval] at hne + have hline (a : CompleteEdge n) (ha : z ∈ chordInterior p a) : + circleLine (t a.val.1) (t a.val.2) z = 0 := by + obtain ⟨u, _, rfl⟩ := ha + exact circleLine_chord _ _ u + apply hne + exact circleConcurrency_of_lines _ _ _ _ _ _ z + (hline e hz.1.1) (hline f hz.1.2) (hline g hz.2) + +end Paper170 + +end +end + +section + +/-! Generic circle positions can be selected inside arbitrary prescribed open parameter intervals. -/ +noncomputable section +open Set MvPolynomial +open scoped Classical +namespace Paper170 + +lemma circle_differencePolynomial_ne_zero {n : ℕ} (e : CompleteEdge n) : + (X e.val.1-X e.val.2 : MvPolynomial (Fin n) ℝ) ≠ 0 := by + intro h + have hh := congrArg (MvPolynomial.eval (fun i => if i=e.val.1 then (1:ℝ) else 0)) h + simp [ne_of_gt e.property] at hh + +lemma circle_antipodalPolynomial_ne_zero {n : ℕ} (e : CompleteEdge n) : + (1+X e.val.1*X e.val.2 : MvPolynomial (Fin n) ℝ) ≠ 0 := by + intro h + have hh := congrArg (MvPolynomial.eval (fun _ => (0:ℝ))) h + simp at hh + +theorem exists_generic_circle_parameters (n : ℕ) (lo hi : Fin n → ℝ) + (hinterval : ∀i, lo i < hi i) : + ∃t : Fin n → ℝ, (∀i, t i ∈ Ioo (lo i) (hi i)) ∧ Function.Injective t ∧ + (∀i j, i≠j → 1+t i*t j≠0) ∧ + ∀v : Fin 6 → Fin n, Function.Injective v → + circleConcurrency (t (v 0)) (t (v 1)) (t (v 2)) (t (v 3)) (t (v 4)) (t (v 5)) ≠ 0 := by + let S := {v : Fin 6 → Fin n // Function.Injective v} + let : Fintype S := Fintype.ofFinite S + let I := CompleteEdge n ⊕ (CompleteEdge n ⊕ S) + let P : I → MvPolynomial (Fin n) ℝ := fun i => match i with + | .inl e => X e.val.1-X e.val.2 + | .inr (.inl e) => 1+X e.val.1*X e.val.2 + | .inr (.inr v) => circleConcurrencyPolynomial v.val + have hP (i : I) : P i ≠ 0 := by + rcases i with e | e | v + · exact circle_differencePolynomial_ne_zero e + · exact circle_antipodalPolynomial_ne_zero e + · exact circleConcurrencyPolynomial_ne_zero v.val v.property + obtain ⟨t,ht,ha⟩ := Zarankiewicz.exists_box_avoiding_polynomials P hP lo hi hinterval + have hdiff (i j : Fin n) (hij : i Zarankiewicz.circlePoint (t i)) e ∩ + chordInterior (fun i => Zarankiewicz.circlePoint (t i)) f ∩ + chordInterior (fun i => Zarankiewicz.circlePoint (t i)) g = ∅ := by + let p := fun i => Zarankiewicz.circlePoint (t i) + have hp : Function.Injective p := Zarankiewicz.circlePoint_injective.comp ht + have hcircle i : squaredLength (p i)=1 := Zarankiewicz.circlePoint_on_unit_circle (t i) + intro e f g hef heg hfg + apply Set.eq_empty_iff_forall_notMem.mpr + intro z hz + have hEF := circle_chord_endpoints_distinct p hp hcircle e f hef z hz.1.1 hz.1.2 + have hEG := circle_chord_endpoints_distinct p hp hcircle e g heg z hz.1.1 hz.2 + have hFG := circle_chord_endpoints_distinct p hp hcircle f g hfg z hz.1.2 hz.2 + let v : Fin 6 → Fin n := ![e.val.1,e.val.2,f.val.1,f.val.2,g.val.1,g.val.2] + have hv : Function.Injective v := by + intro i j heq + have he' := e.property + have hf' := f.property + have hg' := g.property + fin_cases i <;> fin_cases j <;> norm_num [v,Fin.ext_iff] at heq ⊢ <;> omega + have hline (a : CompleteEdge n) (ha : z ∈ chordInterior p a) : + circleLine (t a.val.1) (t a.val.2) z=0 := by + obtain ⟨u,_,rfl⟩ := ha + exact circleLine_chord _ _ u + exact havoid v hv (circleConcurrency_of_lines _ _ _ _ _ _ z + (hline e hz.1.1) (hline f hz.1.2) (hline g hz.2)) + +theorem exists_circle_points_in_parameter_intervals (n : ℕ) (lo hi : Fin n → ℝ) + (hinterval : ∀i, lo i < hi i) : + ∃t : Fin n → ℝ, (∀i, t i ∈ Ioo (lo i) (hi i)) ∧ + Function.Injective (fun i => Zarankiewicz.circlePoint (t i)) ∧ + (∀i, squaredLength (Zarankiewicz.circlePoint (t i))=1) ∧ + (∀i j, i≠j → Zarankiewicz.circlePoint (t i)+Zarankiewicz.circlePoint (t j)≠0) ∧ + ∀e f g : CompleteEdge n, e≠f → e≠g → f≠g → + chordInterior (fun i => Zarankiewicz.circlePoint (t i)) e ∩ + chordInterior (fun i => Zarankiewicz.circlePoint (t i)) f ∩ + chordInterior (fun i => Zarankiewicz.circlePoint (t i)) g = ∅ := by + obtain ⟨t,ht,hinj,hanti,havoid⟩ := exists_generic_circle_parameters n lo hi hinterval + exact ⟨t,ht,Zarankiewicz.circlePoint_injective.comp hinj, + fun i => Zarankiewicz.circlePoint_on_unit_circle (t i), + fun i j hij => circlePoint_add_ne_zero _ _ (hanti i j hij),circleParameters_no_triples t hinj havoid⟩ + +lemma continuous_circle_similarity (u : Plane) : + Continuous (fun t : ℝ => Zarankiewicz.similarityPoint 0 u (Zarankiewicz.circlePoint t)) := by + have hden : Continuous (fun t : ℝ => 1+t^2) := by fun_prop + have hn (t : ℝ) : 1+t^2≠0 := ne_of_gt (Zarankiewicz.circle_denominator_pos t) + have hx : Continuous (fun t : ℝ => (1-t^2)/(1+t^2)) := + (continuous_const.sub (continuous_id.pow 2)).div hden hn + have hy : Continuous (fun t : ℝ => 2*t/(1+t^2)) := + (continuous_const.mul continuous_id).div hden hn + change Continuous (fun t : ℝ => (0 : Plane)+ + (u.1*((1-t^2)/(1+t^2))-u.2*(2*t/(1+t^2)), + u.2*((1-t^2)/(1+t^2))+u.1*(2*t/(1+t^2)))) + exact continuous_const.add (((continuous_const.mul hx).sub (continuous_const.mul hy)).prodMk + ((continuous_const.mul hx).add (continuous_const.mul hy))) + +lemma circle_similarity_add (u a b : Plane) : + Zarankiewicz.similarityPoint 0 u (a+b) = + Zarankiewicz.similarityPoint 0 u a+Zarankiewicz.similarityPoint 0 u b := by + apply Prod.ext <;> dsimp [Zarankiewicz.similarityPoint] <;> ring + +lemma circle_similarity_zero (u : Plane) : Zarankiewicz.similarityPoint 0 u 0=0 := by + simp [Zarankiewicz.similarityPoint] + +lemma circle_similarity_no_triples {n : ℕ} (u : Plane) (hu : u≠0) (p : Fin n → Plane) + (htriple : ∀e f g : CompleteEdge n, e≠f → e≠g → f≠g → + chordInterior p e ∩ chordInterior p f ∩ chordInterior p g=∅) : + ∀e f g : CompleteEdge n, e≠f → e≠g → f≠g → + chordInterior (fun i => Zarankiewicz.similarityPoint 0 u (p i)) e ∩ + chordInterior (fun i => Zarankiewicz.similarityPoint 0 u (p i)) f ∩ + chordInterior (fun i => Zarankiewicz.similarityPoint 0 u (p i)) g=∅ := by + intro e f g hef heg hfg + apply Set.eq_empty_iff_forall_notMem.mpr + rintro z ⟨⟨⟨s,hs,hes⟩,hf⟩,hg⟩ + let y := segmentPoint (p e.val.1) (p e.val.2) s + have hsy : Zarankiewicz.similarityPoint 0 u y=z := by + change Zarankiewicz.similarityPoint 0 u (Zarankiewicz.segmentPoint _ _ s)=z + rw [Zarankiewicz.similarityPoint_segment] + exact hes + have hinj := Zarankiewicz.similarityPoint_injective 0 u hu + have transfer (a : CompleteEdge n) + (ha : z ∈ chordInterior (fun i => Zarankiewicz.similarityPoint 0 u (p i)) a) : + y ∈ chordInterior p a := by + obtain ⟨t,ht,het⟩ := ha + refine ⟨t,ht,hinj ?_⟩ + change Zarankiewicz.similarityPoint 0 u (Zarankiewicz.segmentPoint _ _ t)=_ + rw [Zarankiewicz.similarityPoint_segment,hsy] + exact het + have hm : y ∈ chordInterior p e ∩ chordInterior p f ∩ chordInterior p g := + ⟨⟨⟨s,hs,rfl⟩,transfer f hf⟩,transfer g hg⟩ + rw [htriple e f g hef heg hfg] at hm + exact hm + +theorem exists_generic_circle_points_in_neighborhoods (n : ℕ) (anchor : Fin n → Plane) + (hinj : Function.Injective anchor) (hcircle : ∀i, squaredLength (anchor i)=1) + (U : Fin n → Set Plane) (hU : ∀i, IsOpen (U i)) (hanchor : ∀i, anchor i ∈ U i) : + ∃p : Fin n → Plane, (∀i, p i∈U i) ∧ Function.Injective p ∧ + (∀i, squaredLength (p i)=1) ∧ (∀i j, i≠j → p i+p j≠0) ∧ + ∀e f g : CompleteEdge n, e≠f → e≠g → f≠g → + chordInterior p e ∩ chordInterior p f ∩ chordInterior p g=∅ := by + obtain ⟨u,hu,hlen,node,_,hpoint⟩ := Zarankiewicz.exists_finite_circle_coordinates + 0 1 (by norm_num) anchor hinj (by intro i; change squaredLength (anchor i-0)=1^2; simpa only [sub_zero,one_pow] using hcircle i) + have hlen' : Zarankiewicz.squaredLength u=1 := by simpa only [one_pow] using hlen + let f := fun t : ℝ => Zarankiewicz.similarityPoint 0 u (Zarankiewicz.circlePoint t) + have hc : Continuous f := continuous_circle_similarity u + have hex (i : Fin n) : ∃lo hi : ℝ, lo f (t i) + have hsim := Zarankiewicz.similarityPoint_injective 0 u hu + refine ⟨p,fun i => hsub i (ht i),hsim.comp hp,?_,?_,?_⟩ + · intro i + have hh := Zarankiewicz.similarityPoint_squaredLength 0 u (Zarankiewicz.circlePoint (t i)) + change Zarankiewicz.squaredLength + (Zarankiewicz.similarityPoint 0 u (Zarankiewicz.circlePoint (t i)))=1 + have hbase : Zarankiewicz.squaredLength (Zarankiewicz.circlePoint (t i))=1 := + Zarankiewicz.circlePoint_on_unit_circle (t i) + simpa only [sub_zero,hlen',hbase,one_mul] using hh + · intro i j hij he + apply hpa i j hij + apply hsim + rw [circle_similarity_add,circle_similarity_zero] + exact he + · exact circle_similarity_no_triples u hu _ hpt + +end Paper170 + +end +end + +section + +/-! Generic positions in prescribed circle arcs, including arbitrary choices of chart cut. -/ +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +theorem exists_generic_circle_points_in_disjoint_arcs (n : ℕ) (U : Fin n → Set Plane) + (hU : ∀i, IsOpen (U i)) + (hne : ∀i, (U i ∩ {x | squaredLength x=1}).Nonempty) + (hdisj : Pairwise (fun i j => Disjoint (U i ∩ {x | squaredLength x=1}) + (U j ∩ {x | squaredLength x=1}))) : + ∃p : Fin n → Plane, (∀i, p i∈U i) ∧ Function.Injective p ∧ + (∀i, squaredLength (p i)=1) ∧ (∀i j, i≠j → p i+p j≠0) ∧ + ∀e f g : CompleteEdge n, e≠f → e≠g → f≠g → + chordInterior p e ∩ chordInterior p f ∩ chordInterior p g=∅ := by + choose anchor hanchor using hne + have hinj : Function.Injective anchor := by + intro i j hij + by_contra h + apply Set.disjoint_left.mp (hdisj h) (hanchor i) + rw [hij] + exact hanchor j + exact exists_generic_circle_points_in_neighborhoods n anchor hinj (fun i => (hanchor i).2) + U hU (fun i => (hanchor i).1) + +theorem exists_circle_configuration_in_parameter_arcs (n : ℕ) (u : Plane) + (hu : squaredLength u=1) (lo hi : Fin n → ℝ) (hinterval : ∀i, lo i Zarankiewicz.similarityPoint 0 u (Zarankiewicz.circlePoint t)) '' + Ioo (lo i) (hi i) := by + obtain ⟨t,ht,hinj,hcircle,hanti,htriple⟩ := exists_circle_points_in_parameter_intervals n lo hi hinterval + have hmono : StrictMono t := fun i j hij => ((ht i).2.trans_le (hordered i j hij)).trans (ht j).1 + have hune : u≠0 := by + intro h + rw [h] at hu + norm_num [squaredLength] at hu + have hlen : Zarankiewicz.squaredLength u=1 := hu + let p := fun i => Zarankiewicz.similarityPoint 0 u (Zarankiewicz.circlePoint (t i)) + have hsim := Zarankiewicz.similarityPoint_injective 0 u hune + refine ⟨{ + point := p + injective := hsim.comp hinj + on_circle := ?_ + cyclic_order := ?_ + no_antipodal := ?_ + no_triple_chords := circle_similarity_no_triples u hune _ htriple },?_⟩ + · intro i + change Zarankiewicz.squaredLength (p i)=1 + have hh := Zarankiewicz.similarityPoint_squaredLength 0 u (Zarankiewicz.circlePoint (t i)) + have hb : Zarankiewicz.squaredLength (Zarankiewicz.circlePoint (t i))=1 := hcircle i + simpa only [sub_zero,hlen,hb,one_mul] using hh + · intro i j k hij hjk + have hh := Zarankiewicz.similarityPoint_det 0 u (Zarankiewicz.circlePoint (t i)) + (Zarankiewicz.circlePoint (t j)) (Zarankiewicz.circlePoint (t i)) (Zarankiewicz.circlePoint (t k)) + change 0 < Zarankiewicz.det2 (p j-p i) (p k-p i) + rw [hh,hlen,one_mul] + exact Zarankiewicz.circle_orient_pos _ _ _ (hmono hij) (hmono hjk) + · intro i j hij he + apply hanti i j hij + apply hsim + rw [circle_similarity_add,circle_similarity_zero] + exact he + · intro i + exact ⟨t i,ht i,rfl⟩ + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +variable {V E : Type} + +theorem admissible_drawing_exists [Fintype V] [Fintype E] (G : Graph V E) : Nonempty (AdmissibleDrawing G) := by + obtain ⟨C⟩ := circle_configuration_exists (Fintype.card V) + exact ⟨restrictedCompleteAdmissible G (Fintype.equivFin V).toEmbedding (twoPageAdmissible C)⟩ + +theorem minimum_drawing_exists [Fintype V] [Fintype E] (G : Graph V E) : + ∃ D : AdmissibleDrawing G, crossingCount D = ordinaryCrossingNumber G ∧ + ∀ A : AdmissibleDrawing G, crossingCount D ≤ crossingCount A := by + obtain ⟨D₀⟩ := admissible_drawing_exists G + obtain ⟨D, hD⟩ := Paper170Geometry.crossingCount_attainment D₀ + refine ⟨D, hD, fun A => ?_⟩ + rw [hD] + exact Paper170Geometry.ordinaryCrossingNumber_le_count A + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Counting.lean b/lean/OAI/Combinatorics/CompleteCrossing/Counting.lean new file mode 100644 index 0000000000000000000000000000000000000000..72305c5bd46776d2d9acd38e23bd9ca5a28917c5 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Counting.lean @@ -0,0 +1,365 @@ +import OAI.Combinatorics.CompleteCrossing.Residues +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Data.Fin.VecNotation +import Mathlib.Order.Fin.Basic +import Mathlib.Tactic.FinCases + +namespace OAI + +/-! Cyclic gap enumeration and the exact Harary–Hill crossing-tuple count. -/ + +section + +noncomputable section +open scoped BigOperators +namespace Paper170 + +def naturalCrossingTuples (n : ℕ) : Finset (Fin 4 → ℕ) := + (crossingTuples n).image (fun v i => (v i).val) + +theorem mem_naturalCrossingTuples {n : ℕ} {v : Fin 4 → ℕ} : + v ∈ naturalCrossingTuples n ↔ + v 0 < v 1 ∧ v 1 < v 2 ∧ v 2 < v 3 ∧ v 3 < n ∧ + residueColor n (v 0 + v 2) = residueColor n (v 1 + v 3) := by + constructor + · intro hv + obtain ⟨w, hw, rfl⟩ := Finset.mem_image.mp hv + obtain ⟨_, hw, hc⟩ := Finset.mem_filter.mp hw + exact ⟨hw (by decide : (0 : Fin 4) < 1), hw (by decide : (1 : Fin 4) < 2), + hw (by decide : (2 : Fin 4) < 3), (w 3).isLt, hc⟩ + · rintro ⟨h₀, h₁, h₂, h₃, hc⟩ + have hb (i : Fin 4) : v i < n := by fin_cases i <;> dsimp <;> omega + let w : Fin 4 → Fin n := fun i => ⟨v i, hb i⟩ + apply Finset.mem_image.mpr + refine ⟨w, Finset.mem_filter.mpr ⟨Finset.mem_univ _, ?_, hc⟩, rfl⟩ + apply Fin.strictMono_iff_lt_succ.mpr + intro i + fin_cases i <;> simp only [w, Fin.mk_lt_mk] <;> assumption + +theorem naturalCrossingTuples_card (n : ℕ) : + (naturalCrossingTuples n).card = (crossingTuples n).card := by + apply Finset.card_image_of_injective + intro v w h + funext i + exact Fin.ext (congrFun h i) + +abbrev CyclicRecord := Σ _ : ℕ, ℕ × ℕ × ℕ + +def cyclicRecords (n : ℕ) : Finset CyclicRecord := + (Finset.Icc 2 (n - 2)).sigma (fun k => sameColorGapTuples n k) + +theorem mem_cyclicRecords {n k a g h : ℕ} : + (⟨k, a, g, h⟩ : CyclicRecord) ∈ cyclicRecords n ↔ + 2 ≤ k ∧ k ≤ n - 2 ∧ a < n ∧ 1 ≤ g ∧ g ≤ k - 1 ∧ + 1 ≤ h ∧ h ≤ n - k - 1 ∧ + residueColor n (2 * a + g + h) = residueColor n (2 * a + g + h + k) := by + simp [cyclicRecords, sameColorGapTuples, and_assoc] + +def cyclicToOrdered (n : ℕ) (p : CyclicRecord) : Fin 4 × (Fin 4 → ℕ) := + let k := p.1 + let a := p.2.1 + let b := a + p.2.2.1 + let c := b + p.2.2.2 + let d := a + k + p.2.2.2 + if d < n then (0, ![a, b, c, d]) + else if c < n then (1, ![d - n, a, b, c]) + else if b < n then (2, ![c - n, d - n, a, b]) + else (3, ![b - n, c - n, d - n, a]) + +def orderedToCyclic (n : ℕ) (q : Fin 4 × (Fin 4 → ℕ)) : CyclicRecord := + let v := q.2 + match q.1.val with + | 0 => ⟨(v 1 - v 0) + (v 3 - v 2), v 0, v 1 - v 0, v 2 - v 1⟩ + | 1 => ⟨(v 2 - v 1) + (v 0 + n - v 3), v 1, v 2 - v 1, v 3 - v 2⟩ + | 2 => ⟨(v 3 - v 2) + (v 1 - v 0), v 2, v 3 - v 2, v 0 + n - v 3⟩ + | _ => ⟨(v 0 + n - v 3) + (v 2 - v 1), v 3, v 0 + n - v 3, v 1 - v 0⟩ + +theorem residueColor_shift_eq {n x y : ℕ} (t : ℕ) (h : x + t * n = y) : + residueColor n x = residueColor n y := by + rw [← h] + simp [residueColor, Nat.add_mod] + +theorem cyclicToOrdered_spec {n k a g h : ℕ} (hk : 2 ≤ k) (_hkn : k ≤ n - 2) + (ha : a < n) (hg : 1 ≤ g) (hgk : g ≤ k - 1) + (hh : 1 ≤ h) (hhn : h ≤ n - k - 1) : + let v := (cyclicToOrdered n ⟨k, a, g, h⟩).2 + v 0 < v 1 ∧ v 1 < v 2 ∧ v 2 < v 3 ∧ v 3 < n ∧ + (residueColor n (v 0 + v 2) = residueColor n (v 1 + v 3) ↔ + residueColor n (2 * a + g + h) = residueColor n (2 * a + g + h + k)) := by + by_cases hd : a + k + h < n + · simp only [cyclicToOrdered, hd, ↓reduceIte, Matrix.cons_val_zero, Matrix.cons_val_one, + Matrix.cons_val_two, Matrix.cons_val_three, Matrix.head_cons, Matrix.tail_cons] + refine ⟨by omega, by omega, by omega, by trivial, ?_⟩ + rw [show a + (a + g + h) = 2 * a + g + h by omega, + show a + g + (a + k + h) = 2 * a + g + h + k by omega] + · by_cases hc : a + g + h < n + · simp only [cyclicToOrdered, hd, hc, ↓reduceIte, Matrix.cons_val_zero, + Matrix.cons_val_one, Matrix.cons_val_two, Matrix.cons_val_three, Matrix.head_cons, Matrix.tail_cons] + refine ⟨by omega, by omega, by omega, by trivial, ?_⟩ + rw [residueColor_shift_eq 1 (show (a + k + h - n + (a + g)) + 1 * n = + 2 * a + g + h + k by omega)] + have he : a + (a + g + h) = 2 * a + g + h := by omega + rw [he, eq_comm] + · by_cases hb : a + g < n + · simp only [cyclicToOrdered, hd, hc, hb, ↓reduceIte, Matrix.cons_val_zero, + Matrix.cons_val_one, Matrix.cons_val_two, Matrix.cons_val_three, Matrix.head_cons, Matrix.tail_cons] + refine ⟨by omega, by omega, by omega, by trivial, ?_⟩ + rw [residueColor_shift_eq 1 (show (a + g + h - n + a) + 1 * n = + 2 * a + g + h by omega), + residueColor_shift_eq 1 (show (a + k + h - n + (a + g)) + 1 * n = + 2 * a + g + h + k by omega)] + · simp only [cyclicToOrdered, hd, hc, hb, ↓reduceIte, Matrix.cons_val_zero, + Matrix.cons_val_one, Matrix.cons_val_two, Matrix.cons_val_three, Matrix.head_cons, Matrix.tail_cons] + refine ⟨by omega, by omega, by omega, ha, ?_⟩ + rw [residueColor_shift_eq 2 (show (a + g - n + (a + k + h - n)) + 2 * n = + 2 * a + g + h + k by omega), + residueColor_shift_eq 1 (show (a + g + h - n + a) + 1 * n = + 2 * a + g + h by omega), eq_comm] + +theorem orderedToCyclic_bounds {n : ℕ} (j : Fin 4) (v : Fin 4 → ℕ) + (h₀ : v 0 < v 1) (h₁ : v 1 < v 2) (h₂ : v 2 < v 3) (h₃ : v 3 < n) : + let p := orderedToCyclic n (j, v) + 2 ≤ p.1 ∧ p.1 ≤ n - 2 ∧ p.2.1 < n ∧ 1 ≤ p.2.2.1 ∧ + p.2.2.1 ≤ p.1 - 1 ∧ 1 ≤ p.2.2.2 ∧ p.2.2.2 ≤ n - p.1 - 1 := by + fin_cases j <;> simp [orderedToCyclic] <;> omega + +theorem orderedToCyclic_inverse {n : ℕ} (j : Fin 4) (v : Fin 4 → ℕ) + (h₀ : v 0 < v 1) (h₁ : v 1 < v 2) (h₂ : v 2 < v 3) (h₃ : v 3 < n) : + cyclicToOrdered n (orderedToCyclic n (j, v)) = (j, v) := by + fin_cases j <;> simp (disch := omega) [orderedToCyclic, cyclicToOrdered] + all_goals split_ifs <;> try omega + all_goals + apply Prod.ext + · rfl + · funext i + fin_cases i <;> simp <;> omega + +theorem cyclicToOrdered_inverse {n k a g h : ℕ} (hk : 2 ≤ k) (_hkn : k ≤ n - 2) + (ha : a < n) (hg : 1 ≤ g) (hgk : g ≤ k - 1) + (hh : 1 ≤ h) (hhn : h ≤ n - k - 1) : + orderedToCyclic n (cyclicToOrdered n ⟨k, a, g, h⟩) = ⟨k, a, g, h⟩ := by + unfold cyclicToOrdered + dsimp only + split_ifs <;> simp [orderedToCyclic] <;> omega + +theorem cyclicToOrdered_mem {n : ℕ} {p : CyclicRecord} (hp : p ∈ cyclicRecords n) : + cyclicToOrdered n p ∈ (Finset.univ : Finset (Fin 4)) ×ˢ naturalCrossingTuples n := by + rcases p with ⟨k, a, g, h⟩ + obtain ⟨hk, hkn, ha, hg, hgk, hh, hhn, hc⟩ := mem_cyclicRecords.mp hp + obtain ⟨h₀, h₁, h₂, h₃, he⟩ := cyclicToOrdered_spec hk hkn ha hg hgk hh hhn + exact Finset.mem_product.mpr ⟨Finset.mem_univ _, + mem_naturalCrossingTuples.mpr ⟨h₀, h₁, h₂, h₃, he.mpr hc⟩⟩ + +theorem orderedToCyclic_mem {n : ℕ} {q : Fin 4 × (Fin 4 → ℕ)} + (hq : q ∈ (Finset.univ : Finset (Fin 4)) ×ˢ naturalCrossingTuples n) : + orderedToCyclic n q ∈ cyclicRecords n := by + rcases q with ⟨j, v⟩ + obtain ⟨h₀, h₁, h₂, h₃, hc⟩ := mem_naturalCrossingTuples.mp (Finset.mem_product.mp hq).2 + obtain ⟨hk, hkn, ha, hg, hgk, hh, hhn⟩ := orderedToCyclic_bounds j v h₀ h₁ h₂ h₃ + apply mem_cyclicRecords.mpr + refine ⟨hk, hkn, ha, hg, hgk, hh, hhn, ?_⟩ + have he := (cyclicToOrdered_spec hk hkn ha hg hgk hh hhn).2.2.2.2 + rw [show (⟨(orderedToCyclic n (j, v)).1, (orderedToCyclic n (j, v)).2.1, + (orderedToCyclic n (j, v)).2.2.1, (orderedToCyclic n (j, v)).2.2.2⟩ : CyclicRecord) = + orderedToCyclic n (j, v) from rfl, orderedToCyclic_inverse j v h₀ h₁ h₂ h₃] at he + exact he.mp hc + +theorem crossingTuples_cyclic_count {n : ℕ} (_hn : 3 ≤ n) : + 4 * (crossingTuples n).card = + ∑ k ∈ Finset.Icc 2 (n - 2), (sameColorGapTuples n k).card := by + have hcard : (cyclicRecords n).card = + ((Finset.univ : Finset (Fin 4)) ×ˢ naturalCrossingTuples n).card := by + apply Finset.card_nbij' (cyclicToOrdered n) (orderedToCyclic n) + · exact fun _ hp => cyclicToOrdered_mem hp + · exact fun _ hq => orderedToCyclic_mem hq + · rintro ⟨k, a, g, h⟩ hp + obtain ⟨hk, hkn, ha, hg, hgk, hh, hhn, _⟩ := mem_cyclicRecords.mp hp + exact cyclicToOrdered_inverse hk hkn ha hg hgk hh hhn + · rintro ⟨j, v⟩ hq + obtain ⟨h₀, h₁, h₂, h₃, _⟩ := mem_naturalCrossingTuples.mp (Finset.mem_product.mp hq).2 + exact orderedToCyclic_inverse j v h₀ h₁ h₂ h₃ + simpa only [cyclicRecords, Finset.card_sigma, Finset.card_product, + Finset.card_univ, Fintype.card_fin, naturalCrossingTuples_card] using hcard.symm + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators +namespace Paper170 + +def startingLabels (n k b : ℕ) : Finset ℕ := + (Finset.range n).filter (fun a => + residueColor n (2 * a + b) = residueColor n (2 * a + b + k)) + +theorem startingLabels_card_eq_sum {n : ℕ} (hn : 0 < n) (k b : ℕ) : + (startingLabels n k b).card = + ∑ r ∈ sameColorResidues n k, (residueFiber n b r).card := by + unfold residueFiber + rw [Finset.sum_card_fiberwise_eq_card_filter] + congr 1 + ext a + simp [startingLabels, sameColorResidues, residueColor, + Nat.mod_lt _ hn, Nat.add_mod] + +theorem startingLabels_card_odd {n : ℕ} (hn : Odd n) (k b : ℕ) : + (startingLabels n k b).card = (sameColorResidues n k).card := by + have hpos : 0 < n := by obtain ⟨t, ht⟩ := hn; omega + rw [startingLabels_card_eq_sum hpos] + calc + (∑ r ∈ sameColorResidues n k, (residueFiber n b r).card) = + ∑ _r ∈ sameColorResidues n k, 1 := by + apply Finset.sum_congr rfl + intro r hr + exact residueFiber_card_odd hn (Finset.mem_range.mp (Finset.mem_filter.mp hr).1) + _ = _ := by simp + +theorem startingLabels_card_even {m : ℕ} (hm : 0 < m) (k b : ℕ) : + (startingLabels (2 * m) k b).card = 2 * (sameColorResiduesParity (2 * m) k (b % 2)).card := by + rw [startingLabels_card_eq_sum (by omega)] + calc + (∑ r ∈ sameColorResidues (2 * m) k, (residueFiber (2 * m) b r).card) = + ∑ r ∈ sameColorResidues (2 * m) k, if r % 2 = b % 2 then 2 else 0 := by + apply Finset.sum_congr rfl + intro r hr + exact residueFiber_card_even hm (Finset.mem_range.mp (Finset.mem_filter.mp hr).1) + _ = _ := by rw [← Finset.sum_filter]; simp [sameColorResiduesParity, mul_comm] + +theorem parity_partition (s : Finset ℕ) (b : ℕ) : + (s.filter (fun r => (r + b) % 2 = 0)).card + + (s.filter (fun r => (r + b) % 2 = 1)).card = s.card := by + have he : s.filter (fun r => ¬(r + b) % 2 = 0) = s.filter (fun r => (r + b) % 2 = 1) := by + ext r + rcases Nat.mod_two_eq_zero_or_one (r + b) with h | h <;> simp [h] + rw [← he] + exact Finset.card_filter_add_card_filter_not (s := s) _ + +theorem startingLabels_card_even_balanced {m k : ℕ} (hm : 0 < m) + (hk : 2 ≤ k) (hkn : k ≤ 2 * m - 2) (hparity : Odd m ∨ Even k) (b : ℕ) : + (startingLabels (2 * m) k b).card = (sameColorResidues (2 * m) k).card := by + rw [startingLabels_card_even hm] + have hbal := sameColorResidues_parity_balance hm hk hkn hparity + have htotal := parity_partition (sameColorResidues (2 * m) k) 0 + simp only [Nat.add_zero] at htotal + change (sameColorResiduesParity (2 * m) k 0).card + + (sameColorResiduesParity (2 * m) k 1).card = _ at htotal + have hb : b % 2 = 0 ∨ b % 2 = 1 := Nat.mod_two_eq_zero_or_one b + rcases hb with hb | hb <;> rw [hb] <;> omega + +theorem sum_parity_weights (s : Finset ℕ) (b x y : ℕ) + (hbal : (s.filter (fun r => (r + b) % 2 = 0)).card = + (s.filter (fun r => (r + b) % 2 = 1)).card) : + (∑ r ∈ s, 2 * (if (r + b) % 2 = 0 then x else y)) = s.card * (x + y) := by + have he : s.filter (fun r => ¬(r + b) % 2 = 0) = s.filter (fun r => (r + b) % 2 = 1) := by + ext r + rcases Nat.mod_two_eq_zero_or_one (r + b) with h | h <;> simp [h] + rw [← Finset.mul_sum, Finset.sum_ite] + simp only [Finset.sum_const, smul_eq_mul, he] + rw [← parity_partition s b, hbal] + ring + +theorem startingLabels_sum_odd_gap {m k : ℕ} (hm : 0 < m) (hk : Odd k) (b : ℕ) : + (∑ g ∈ Finset.Icc 1 (k - 1), (startingLabels (2 * m) k (g + b)).card) = + (k - 1) * (sameColorResidues (2 * m) k).card := by + simp_rw [startingLabels_card_even hm] + have hfun (g : ℕ) : (sameColorResiduesParity (2 * m) k ((g + b) % 2)).card = + if (g + b) % 2 = 0 then (sameColorResiduesParity (2 * m) k 0).card + else (sameColorResiduesParity (2 * m) k 1).card := by + rcases Nat.mod_two_eq_zero_or_one (g + b) with h | h <;> simp [h] + simp_rw [hfun] + rw [sum_parity_weights _ _ _ _ (firstGapParity_balance hk b)] + have htotal := parity_partition (sameColorResidues (2 * m) k) 0 + simp only [Nat.add_zero] at htotal + change (sameColorResiduesParity (2 * m) k 0).card + + (sameColorResiduesParity (2 * m) k 1).card = _ at htotal + rw [htotal, Nat.card_Icc] + congr 1 + +theorem sameColorGapTuples_card_eq_sum (n k : ℕ) : + (sameColorGapTuples n k).card = + ∑ g₂ ∈ Finset.Icc 1 (n - k - 1), ∑ g₁ ∈ Finset.Icc 1 (k - 1), + (startingLabels n k (g₁ + g₂)).card := by + simp only [sameColorGapTuples, startingLabels, Finset.card_eq_sum_ones, + Finset.sum_filter, Finset.sum_product, Nat.add_assoc] + rw [Finset.sum_comm] + conv_lhs => arg 2; ext g₁; rw [Finset.sum_comm] + rw [Finset.sum_comm] + +theorem sameColorGapTuples_card {n k : ℕ} (hn : 3 ≤ n) (hk : 2 ≤ k) + (hkn : k ≤ n - 2) : + (sameColorGapTuples n k).card = (k - 1) * (n - k - 1) * + (sameColorResidues n k).card := by + rw [sameColorGapTuples_card_eq_sum] + rcases Nat.even_or_odd n with he | ho + · obtain ⟨m, hm⟩ := he + have heq : n = 2 * m := by omega + clear hm + subst n + have hmp : 0 < m := by omega + by_cases hpar : Odd m ∨ Even k + · simp_rw [startingLabels_card_even_balanced hmp hk hkn hpar] + simp only [Finset.sum_const, smul_eq_mul, Nat.card_Icc] + have h₁ : k - 1 + 1 - 1 = k - 1 := by omega + have h₂ : 2 * m - k - 1 + 1 - 1 = 2 * m - k - 1 := by omega + rw [h₁, h₂] + ring + · have hko : Odd k := Nat.not_even_iff_odd.mp (fun h => hpar (Or.inr h)) + simp_rw [startingLabels_sum_odd_gap hmp hko] + simp only [Finset.sum_const, smul_eq_mul, Nat.card_Icc] + have h₂ : 2 * m - k - 1 + 1 - 1 = 2 * m - k - 1 := by omega + rw [h₂] + ring + · simp_rw [startingLabels_card_odd ho] + simp only [Finset.sum_const, smul_eq_mul, Nat.card_Icc] + have h₁ : k - 1 + 1 - 1 = k - 1 := by omega + have h₂ : n - k - 1 + 1 - 1 = n - k - 1 := by omega + rw [h₁, h₂] + ring + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators +namespace Paper170 + +theorem crossingTuples_card {n : ℕ} (hn : 3 ≤ n) : + (crossingTuples n).card = hill n := by + have hcount : 4 * (crossingTuples n).card = + (n / 2) * (n / 2 - 1) * (n - n / 2 - 1) * (n - n / 2 - 2) := by + rw [crossingTuples_cyclic_count hn] + calc + (∑ k ∈ Finset.Icc 2 (n - 2), (sameColorGapTuples n k).card) = + ∑ k ∈ Finset.Icc 2 (n - 2), + (k - 1) * (n - k - 1) * (n - 2 * min k (n - k)) := by + apply Finset.sum_congr rfl + intro k hk + have hk₁ := (Finset.mem_Icc.mp hk).1 + have hk₂ := (Finset.mem_Icc.mp hk).2 + rw [sameColorGapTuples_card hn hk₁ hk₂, sameColorResidues_card hn hk₁ hk₂] + _ = _ := by rw [cyclic_count_pairing hn, crossing_sum_telescope hn] + have h₁ : n - n / 2 - 1 = (n - 1) / 2 := by omega + have h₂ : n / 2 - 1 = (n - 2) / 2 := by omega + have h₃ : n - n / 2 - 2 = (n - 3) / 2 := by omega + rw [h₁, h₂, h₃] at hcount + have hp : n / 2 * ((n - 1) / 2) * ((n - 2) / 2) * ((n - 3) / 2) = + 4 * (crossingTuples n).card := by rw [hcount]; ring + rw [hill, hp] + omega + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/CrossingCuts.lean b/lean/OAI/Combinatorics/CompleteCrossing/CrossingCuts.lean new file mode 100644 index 0000000000000000000000000000000000000000..c23eb12ba25e190971d1e912d094a582c7db4bc5 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/CrossingCuts.lean @@ -0,0 +1,595 @@ +import OAI.Combinatorics.CompleteCrossing.Reconnection +import OAI.Combinatorics.Crossing.ExteriorSegmentGraph +import OAI.Combinatorics.Crossing.GraphWalkRealizationLaws +import OAI.Combinatorics.Crossing.OrderedPathParts +import OAI.Combinatorics.Crossing.SegmentAugmentation + +namespace OAI + +/-! Ordered crossing ports, surgery cut walks, path witnesses, and cut separation. -/ + +section + +/-! The actual embedded surgery graph: exterior drawing tracks and two disjoint reconnection chords. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + +def crossingSurgeryGraph (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q : C.InnerIndex) : SimpleGraph Plane := + segmentAugmentedGraph (exteriorSegmentGraph (drawingSubdivisionGraph P) (C.crossingDisk p)) + (C.reconnectionStart p q) (C.reconnectionEnd p q) (C.reconnection_endpoints_ne p q) + +theorem crossingSurgeryGraph_embedding (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) + (hmark : ∀ e t, D'.edge e t ∈ drawingMarks D'.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) + (hport : ∀ e t, D'.edge e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) + (p q : C.InnerIndex) (hm : C.innerMark p=C.innerMark q) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) : + StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id := by + have hemb := drawingSubdivisionGraph_embedding P hmark + have houtEmb : StraightEdgeEmbedding + (exteriorSegmentGraph (drawingSubdivisionGraph P) (C.crossingDisk p)) id := by + refine ⟨hemb.1,?_⟩ + intro a b c d hab hcd x hx hy + exact hemb.2 a b c d hab.1 hcd.1 x hx hy + apply segmentAugmentedGraph_embedding _ _ _ _ houtEmb (C.crossingDisk p) + · intro x y hxy + exact hxy.2 + · exact C.reconnection_open_in_disk p q hm + · exact C.reconnection_chords_disjoint p q hcross + · intro i x y hxy + constructor + · apply drawingSubdivisionGraph_point_endpoint P _ ?_ x y hxy.1 + intro e t ht + apply hport e t + cases i + · exact ⟨C.incomingPort q,ht.symm⟩ + · exact ⟨C.incomingPort p,ht.symm⟩ + · apply drawingSubdivisionGraph_point_endpoint P _ ?_ x y hxy.1 + intro e t ht + apply hport e t + cases i + · exact ⟨C.outgoingPort p,ht.symm⟩ + · exact ⟨C.outgoingPort q,ht.symm⟩ + +theorem exterior_le_crossingSurgeryGraph (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q : C.InnerIndex) : + exteriorSegmentGraph (drawingSubdivisionGraph P) (C.crossingDisk p) ≤ crossingSurgeryGraph C P p q := + le_segmentAugmentedGraph _ _ _ _ + +theorem crossingSurgeryGraph_reconnection_adj (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q : C.InnerIndex) (i : Bool) : + (crossingSurgeryGraph C P p q).Adj (C.reconnectionStart p q i) (C.reconnectionEnd p q i) := + segmentAugmentedGraph_added_adj _ _ _ _ i + +end Paper170Geometry + +end +end + +section + +/-! The actual incoming and outgoing ports occur in the correct order on each edge. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem middlePath_contains_chord (E : PolygonalExterior C) (p : C.InnerIndex) : + OrderedPathPart (E.middlePath p.1) (C.crossingChord p) := by + rcases p with ⟨e,⟨i,hi⟩⟩ + have hj : i.val-1+1 < C.count e := by omega + have hinner : C.orderedInner e (i.val-1) hj=⟨e,⟨i,hi⟩⟩ := by + unfold DrawingPassages.orderedInner + congr 1 + apply Subtype.ext + apply Fin.ext + change i.val-1+1=i.val + omega + have hpart : OrderedPathPart (E.middlePath e) (orderedBridge C e (i.val-1)) := + alternatingPath_contains_bridge _ _ _ _ (C.count e-1) (i.val-1) (by omega) + apply hpart.congr_right + intro t + rw [orderedBridge_apply (C:=C) e (i.val-1) hj t,hinner] + +theorem assembledEdge_contains_chord (E : PolygonalExterior C) + (v : Vertex → Plane) (p : C.InnerIndex) : + OrderedPathPart (E.assembledEdge v p.1) (C.crossingChord p) := by + have h : OrderedPathPart (E.anchoredMiddle p.1) (C.crossingChord p) := E.middlePath_contains_chord p + exact (h.right (startSpoke C v p.1)).left (endSpoke C v p.1) + +theorem assembled_crossing_ports_ordered (E : PolygonalExterior C) + (v : Vertex → Plane) (p : C.InnerIndex) : + ∃ u w : unitInterval, u < w ∧ + E.assembledEdge v p.1 u=C.portPoint (C.incomingPort p) ∧ + E.assembledEdge v p.1 w=C.portPoint (C.outgoingPort p) := + (E.assembledEdge_contains_chord v p).endpoints_ordered + +theorem crossing_port_walk_indices (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (hport : ∀ e t, E.assembledEdge v e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) + (p : C.InnerIndex) : + ∃ i j : Fin ((P p.1).pieces+1), i < j ∧ + (drawingEdgeWalk P p.1).getVert i.val=C.portPoint (C.incomingPort p) ∧ + (drawingEdgeWalk P p.1).getVert j.val=C.portPoint (C.outgoingPort p) := by + obtain ⟨u,w,huw,hu,hw⟩ := E.assembled_crossing_ports_ordered v p + obtain ⟨i,hi⟩ := hport p.1 u ⟨C.incomingPort p,hu.symm⟩ + obtain ⟨j,hj⟩ := hport p.1 w ⟨C.outgoingPort p,hw.symm⟩ + have hij : i < j := by + by_contra hn + have hh := (P p.1).increasing.monotone (le_of_not_gt hn) + rw [hi,hj] at hh + exact huw.not_ge hh + refine ⟨i,j,hij,?_,?_⟩ + · rw [drawingEdgeWalk_getVert P p.1 i.val (by omega)] + have he := (P p.1).vertices_at i + change (P p.1).vertices i.val=E.assembledEdge v p.1 ((P p.1).knot i) at he + exact he.trans ((congrArg (E.assembledEdge v p.1) hi).trans hu) + · rw [drawingEdgeWalk_getVert P p.1 j.val (by omega)] + have he := (P p.1).vertices_at j + change (P p.1).vertices j.val=E.assembledEdge v p.1 ((P p.1).knot j) at he + exact he.trans ((congrArg (E.assembledEdge v p.1) hj).trans hw) + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Exactly the two incident assembled edges can enter a chosen crossing disk. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem assembled_in_crossingDisk_chord (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : Edge) (p : C.InnerIndex) (x : Plane) + (hx : x ∈ Set.range (E.assembledEdge v e)) (hxin : x ∈ C.crossingDisk p) : + ∃ r : C.InnerIndex, r.1=e ∧ C.innerMark r=C.innerMark p ∧ x ∈ Set.range (C.crossingChord r) := by + rcases (E.assembledEdge_range_iff v e x).mp hx with (hx | ⟨i,hi,hx⟩ | ⟨r,hr,hx⟩) | hx + · exact False.elim (Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p _) + hxin (C.vertex_spoke_range_in_disk v hv _ (C.startPortAt e) hx)) + · obtain ⟨t,rfl⟩ := hx + exact False.elim (hxin.not_ge (E.outside_open_disks i t (C.innerMark p))) + · refine ⟨r,hr,?_,hx⟩ + by_contra hn + exact Set.disjoint_left.mp (C.disks_disjoint _ _ hn) + (C.crossingChord_range_subset_disk r hx) (C.crossingDisk_subset_closed p hxin) + · rw [endSpoke_range] at hx + exact False.elim (Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p _) + hxin (C.vertex_spoke_range_in_disk v hv _ (C.endPortAt e) hx)) + +theorem assembled_crossingDisk_owner (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p q : C.InnerIndex) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (e : Edge) (x : Plane) + (hx : x ∈ Set.range (E.assembledEdge v e)) (hxin : x ∈ C.crossingDisk p) : e=p.1 ∨ e=q.1 := by + obtain ⟨r,hr,hrm,hxr⟩ := E.assembled_in_crossingDisk_chord v hv e p x hx hxin + rcases C.innerIndex_at_mark_pair p q r hpq hm hrm.symm with rfl | rfl + · exact Or.inl hr.symm + · exact Or.inr hr.symm + +theorem assembled_other_edge_avoids_crossingDisk (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p q : C.InnerIndex) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (e : Edge) (hep : e ≠ p.1) (heq : e ≠ q.1) : + Disjoint (Set.range (E.assembledEdge v e)) (C.crossingDisk p) := by + apply Set.disjoint_left.mpr + intro x hx hxin + rcases E.assembled_crossingDisk_owner v hv p q hpq hm e x hx hxin with h | h + · exact hep h + · exact heq h + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Before the incoming port and after the outgoing port, the actual edge avoids the open crossing disk. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : Paper170.AdmissibleDrawing graph} + +theorem crossingChord_parameter_interior (C : DrawingPassages D.toFiniteIntersectionDrawing) (p : C.InnerIndex) + (t : unitInterval) (ht : C.crossingChord p t ∈ C.crossingDisk p) : + t ∈ Set.Ioo (0 : unitInterval) 1 := by + have ht0 : t ≠ 0 := by + intro he + subst t + change squaredLength (C.crossingChord p 0-(C.innerMark p).val) < C.radius^2 at ht + rw [Path.source,C.incomingPoint_on_circle] at ht + exact lt_irrefl _ ht + have ht1 : t ≠ 1 := by + intro he + subst t + change squaredLength (C.crossingChord p 1-(C.innerMark p).val) < C.radius^2 at ht + rw [Path.target,C.outgoingPoint_on_circle] at ht + exact lt_irrefl _ ht + exact ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ + +end DrawingPassages +namespace PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem assembled_crossing_disk_parameter_between (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p : C.InnerIndex) (u w : unitInterval) + (hu : E.assembledEdge v p.1 u=C.portPoint (C.incomingPort p)) + (hw : E.assembledEdge v p.1 w=C.portPoint (C.outgoingPort p)) + (t : unitInterval) (ht : E.assembledEdge v p.1 t ∈ C.crossingDisk p) : u < t ∧ t < w := by + obtain ⟨f,hf,he⟩ := E.assembledEdge_contains_chord v p + have h0 : f 0=u := E.assembledEdge_injective v hv p.1 + (((he 0).trans (C.crossingChord p).source).trans hu.symm) + have h1 : f 1=w := E.assembledEdge_injective v hv p.1 + (((he 1).trans (C.crossingChord p).target).trans hw.symm) + have hmem : E.assembledEdge v p.1 t ∈ Set.range (C.crossingChord p) := + (E.assembled_range_in_crossingDisk v hv p _ ht).mp ⟨t,rfl⟩ + obtain ⟨s,hs⟩ := hmem + have hsint := C.crossingChord_parameter_interior p s (hs.symm ▸ ht) + have hst : f s=t := E.assembledEdge_injective v hv p.1 ((he s).trans hs) + exact ⟨by simpa only [h0,hst] using hf hsint.1,by simpa only [h1,hst] using hf hsint.2⟩ + +theorem assembled_crossing_port_clearance (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p : C.InnerIndex) (u w : unitInterval) + (hu : E.assembledEdge v p.1 u=C.portPoint (C.incomingPort p)) + (hw : E.assembledEdge v p.1 w=C.portPoint (C.outgoingPort p)) + (t : unitInterval) (ht : t ≤ u ∨ w ≤ t) : E.assembledEdge v p.1 t ∉ C.crossingDisk p := by + intro hmem + have hbetween := E.assembled_crossing_disk_parameter_between v hv p u w hu hw t hmem + rcases ht with ht | ht + · exact hbetween.1.not_ge ht + · exact hbetween.2.not_ge ht + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! Actual ordered prefix and suffix cuts lie in the exterior segment graph. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem crossing_cut_traces_disjoint (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (p : C.InnerIndex) (i j : Fin ((P p.1).pieces+1)) + (hi : (drawingEdgeWalk P p.1).getVert i.val=C.portPoint (C.incomingPort p)) + (hj : (drawingEdgeWalk P p.1).getVert j.val=C.portPoint (C.outgoingPort p)) : + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take i.val))) (C.crossingDisk p) ∧ + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop j.val))) (C.crossingDisk p) := by + have hki : (drawingEdgeWalk P p.1).getVert i.val=E.assembledEdge v p.1 ((P p.1).knot i) := + (drawingEdgeWalk_getVert P p.1 i.val (by omega)).trans ((P p.1).vertices_at i) + have hkj : (drawingEdgeWalk P p.1).getVert j.val=E.assembledEdge v p.1 ((P p.1).knot j) := + (drawingEdgeWalk_getVert P p.1 j.val (by omega)).trans ((P p.1).vertices_at j) + have hu := hki.symm.trans hi + have hw := hkj.symm.trans hj + constructor + · apply Set.disjoint_left.mpr + intro x hx hxin + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_take_trace P p.1 i hx + exact E.assembled_crossing_port_clearance v hv p _ _ hu hw t (Or.inl ht.2) (he.symm ▸ hxin) + · apply Set.disjoint_left.mpr + intro x hx hxin + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_drop_trace P p.1 j hx + exact E.assembled_crossing_port_clearance v hv p _ _ hu hw t (Or.inr ht.1) (he.symm ▸ hxin) + +theorem exists_exterior_crossing_cuts (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (hport : ∀ e t, E.assembledEdge v e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) + (p : C.InnerIndex) : + ∃ i j : Fin ((P p.1).pieces+1), i < j ∧ + (drawingEdgeWalk P p.1).getVert i.val=C.portPoint (C.incomingPort p) ∧ + (drawingEdgeWalk P p.1).getVert j.val=C.portPoint (C.outgoingPort p) ∧ + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take i.val))) (C.crossingDisk p) ∧ + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop j.val))) (C.crossingDisk p) := by + obtain ⟨i,j,hij,hi,hj⟩ := E.crossing_port_walk_indices v hvinj hv hdet P hport p + exact ⟨i,j,hij,hi,hj,E.crossing_cut_traces_disjoint v hvinj hv hdet P p i j hi hj⟩ + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Actual prefix and suffix walks transferred to the constructed surgery graph. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + +def surgeryPrefixWalk (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q r : C.InnerIndex) + (i : ℕ) (hi : (drawingEdgeWalk P r.1).getVert i=C.portPoint (C.incomingPort r)) + (hout : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take i))) (C.crossingDisk p)) : + (crossingSurgeryGraph C P p q).Walk (D'.vertex ((graph.src r.1))) (C.portPoint (C.incomingPort r)) := + ((exteriorGraphWalk ((drawingEdgeWalk P r.1).take i) (C.crossingDisk p) hout).mapLe + (exterior_le_crossingSurgeryGraph C P p q)).copy rfl hi + +def surgerySuffixWalk (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q r : C.InnerIndex) + (j : ℕ) (hj : (drawingEdgeWalk P r.1).getVert j=C.portPoint (C.outgoingPort r)) + (hout : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop j))) (C.crossingDisk p)) : + (crossingSurgeryGraph C P p q).Walk (C.portPoint (C.outgoingPort r)) (D'.vertex ((graph.dst r.1))) := + ((exteriorGraphWalk ((drawingEdgeWalk P r.1).drop j) (C.crossingDisk p) hout).mapLe + (exterior_le_crossingSurgeryGraph C P p q)).copy hj rfl + +theorem surgeryPrefixWalk_trace (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q r : C.InnerIndex) + (i : ℕ) (hi : (drawingEdgeWalk P r.1).getVert i=C.portPoint (C.incomingPort r)) + (hout : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take i))) (C.crossingDisk p)) : + Set.range (graphWalkPath id (surgeryPrefixWalk C P p q r i hi hout))= + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take i)) := by + rw [surgeryPrefixWalk,graphWalkPath_copy_range,graphWalkPath_mapLe_range,exteriorGraphWalk_trace] + +theorem surgerySuffixWalk_trace (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (p q r : C.InnerIndex) + (j : ℕ) (hj : (drawingEdgeWalk P r.1).getVert j=C.portPoint (C.outgoingPort r)) + (hout : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop j))) (C.crossingDisk p)) : + Set.range (graphWalkPath id (surgerySuffixWalk C P p q r j hj hout))= + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop j)) := by + rw [surgerySuffixWalk,graphWalkPath_copy_range,graphWalkPath_mapLe_range,exteriorGraphWalk_trace] + +end Paper170Geometry + +end +end + +section + +/-! Ordered actual cut data, whose existence is proved for the constructed normalization. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + +structure ExteriorCrossingCut (C : DrawingPassages D.toFiniteIntersectionDrawing) + (P : ∀ e, PolygonalParametrization (D'.edge e)) (r : C.InnerIndex) where + first : Fin ((P r.1).pieces+1) + last : Fin ((P r.1).pieces+1) + ordered : first < last + first_point : (drawingEdgeWalk P r.1).getVert first.val=C.portPoint (C.incomingPort r) + last_point : (drawingEdgeWalk P r.1).getVert last.val=C.portPoint (C.outgoingPort r) + prefix_outside : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take first.val))) (C.crossingDisk r) + suffix_outside : Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop last.val))) (C.crossingDisk r) + +theorem PolygonalExterior.nonempty_exteriorCrossingCut {C : DrawingPassages D.toFiniteIntersectionDrawing} (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (hport : ∀ e t, E.assembledEdge v e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) + (r : C.InnerIndex) : Nonempty (ExteriorCrossingCut C P r) := by + obtain ⟨i,j,hij,hi,hj,hout,hout'⟩ := E.exists_exterior_crossing_cuts v hvinj hv hdet P hport r + exact ⟨⟨i,j,hij,hi,hj,hout,hout'⟩⟩ + +namespace ExteriorCrossingCut +variable {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {p q r : C.InnerIndex} + +def prefixInSurgery (K : ExteriorCrossingCut C P r) (p q : C.InnerIndex) + (hr : C.innerMark r=C.innerMark p) : + (crossingSurgeryGraph C P p q).Walk (D'.vertex ((graph.src r.1))) (C.portPoint (C.incomingPort r)) := + surgeryPrefixWalk C P p q r K.first.val K.first_point (by + simpa only [DrawingPassages.crossingDisk,hr] using K.prefix_outside) + +def suffixInSurgery (K : ExteriorCrossingCut C P r) (p q : C.InnerIndex) + (hr : C.innerMark r=C.innerMark p) : + (crossingSurgeryGraph C P p q).Walk (C.portPoint (C.outgoingPort r)) (D'.vertex ((graph.dst r.1))) := + surgerySuffixWalk C P p q r K.last.val K.last_point (by + simpa only [DrawingPassages.crossingDisk,hr] using K.suffix_outside) + +theorem prefixInSurgery_trace (K : ExteriorCrossingCut C P r) (p q : C.InnerIndex) + (hr : C.innerMark r=C.innerMark p) : + Set.range (graphWalkPath id (K.prefixInSurgery p q hr))= + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val)) := + surgeryPrefixWalk_trace _ _ _ _ _ _ _ _ + +theorem suffixInSurgery_trace (K : ExteriorCrossingCut C P r) (p q : C.InnerIndex) + (hr : C.innerMark r=C.innerMark p) : + Set.range (graphWalkPath id (K.suffixInSurgery p q hr))= + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val)) := + surgerySuffixWalk_trace _ _ _ _ _ _ _ _ + +end ExteriorCrossingCut +end Paper170Geometry + +end +end + +section + +/-! Simple actual polygonal paths obtained from transferred tracks and one new chord. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +def walkThroughChord {G : SimpleGraph Plane} {a u v b : Plane} + (A : G.Walk a u) (h : G.Adj u v) (B : G.Walk v b) : G.Walk a b := + (A.append h.toWalk).append B + +theorem walkThroughChord_range {G : SimpleGraph Plane} {a u v b : Plane} + (A : G.Walk a u) (h : G.Adj u v) (B : G.Walk v b) : + Set.range (graphWalkPath id (walkThroughChord A h B))= + (Set.range (graphWalkPath id A) ∪ segment ℝ u v) ∪ Set.range (graphWalkPath id B) := by + rw [walkThroughChord,graphWalkPath_append_range,graphWalkPath_append_range,graphWalkPath_toWalk_range] + +theorem exists_simple_path_through_chord {G : SimpleGraph Plane} + (hemb : StraightEdgeEmbedding G id) {a u v b : Plane} (hab : a ≠ b) + (A : G.Walk a u) (h : G.Adj u v) (B : G.Walk v b) : + ∃ γ : Path a b, Function.Injective γ ∧ HasFiniteAffineCover γ ∧ + Set.range γ ⊆ (Set.range (graphWalkPath id A) ∪ segment ℝ u v) ∪ Set.range (graphWalkPath id B) := by + classical + let p := walkThroughChord A h B + refine ⟨graphWalkPath id p.bypass, + graphWalkPath_injective id hemb hab p.bypass p.bypass_isPath, + graphWalkPath_hasFiniteAffineCover id p.bypass,?_⟩ + exact (graphWalkPath_bypass_range_subset id p).trans (by rw [walkThroughChord_range]) + +variable {D D' : Paper170.AdmissibleDrawing graph} + +theorem surgery_mixed_endpoints_ne (C : DrawingPassages D.toFiniteIntersectionDrawing) + (p q : C.InnerIndex) (hadj : graph.src p.1 = graph.src q.1 ∨ graph.dst p.1 = graph.dst q.1) : + D'.vertex (graph.src p.1) ≠ D'.vertex (graph.dst q.1) := by + intro h + have he := D'.vertex_injective h + rcases hadj with hs | ht + · exact graph.loopless q.1 (hs.symm.trans he) + · exact graph.loopless p.1 (he.trans ht.symm) + +end Paper170Geometry + +end +end + +section + +/-! Actual drawing prefixes and suffixes meet vertices only at their retained endpoint. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D D' : Paper170.AdmissibleDrawing graph} + +namespace ExteriorCrossingCut +variable {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {r : C.InnerIndex} + +theorem first_parameter_lt_one (K : ExteriorCrossingCut C P r) : (P r.1).knot K.first < 1 := by + rw [← (P r.1).last] + exact (P r.1).increasing (K.ordered.trans_le (Fin.le_last _)) + +theorem last_parameter_pos (K : ExteriorCrossingCut C P r) : 0 < (P r.1).knot K.last := by + rw [← (P r.1).first] + exact (P r.1).increasing ((Fin.zero_le K.first).trans_lt K.ordered) + +theorem prefix_vertex_eq (K : ExteriorCrossingCut C P r) (v : Vertex) + (hv : D'.vertex v ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val))) : + v=(graph.src r.1) := by + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_take_trace P r.1 K.first hv + rcases drawing_edge_vertex_parameter D'.toContinuousDrawing r.1 t v he with ⟨_,hv⟩ | ⟨ht1,_⟩ + · exact hv + · exact False.elim ((ht1 ▸ ht.2).not_gt K.first_parameter_lt_one) + +theorem suffix_vertex_eq (K : ExteriorCrossingCut C P r) (v : Vertex) + (hv : D'.vertex v ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val))) : + v=(graph.dst r.1) := by + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_drop_trace P r.1 K.last hv + rcases drawing_edge_vertex_parameter D'.toContinuousDrawing r.1 t v he with ⟨ht0,_⟩ | ⟨_,hv⟩ + · exact False.elim ((ht0 ▸ ht.1).not_gt K.last_parameter_pos) + · exact hv + +end ExteriorCrossingCut +end Paper170Geometry + +end +end + +section + +/-! Actual retained cuts are disjoint and contain only their own boundary port. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.ExteriorCrossingCut +variable {D D' : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} {P : ∀ e, PolygonalParametrization (D'.edge e)} + {r : C.InnerIndex} + +theorem first_parameter_point (K : ExteriorCrossingCut C P r) : + D'.edge r.1 ((P r.1).knot K.first)=C.portPoint (C.incomingPort r) := + ((drawingEdgeWalk_getVert P r.1 K.first.val (by have h := K.first.isLt; omega)).trans + ((P r.1).vertices_at K.first)).symm.trans K.first_point + +theorem last_parameter_point (K : ExteriorCrossingCut C P r) : + D'.edge r.1 ((P r.1).knot K.last)=C.portPoint (C.outgoingPort r) := + ((drawingEdgeWalk_getVert P r.1 K.last.val (by have h := K.last.isLt; omega)).trans + ((P r.1).vertices_at K.last)).symm.trans K.last_point + +theorem prefix_subset_edge (K : ExteriorCrossingCut C P r) : + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val)) ⊆ Set.range (D'.edge r.1) := by + intro x hx + obtain ⟨t,_,he⟩ := drawingEdgeWalk_take_trace P r.1 K.first hx + exact ⟨t,he⟩ + +theorem suffix_subset_edge (K : ExteriorCrossingCut C P r) : + Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val)) ⊆ Set.range (D'.edge r.1) := by + intro x hx + obtain ⟨t,_,he⟩ := drawingEdgeWalk_drop_trace P r.1 K.last hx + exact ⟨t,he⟩ + +theorem incoming_not_suffix (K : ExteriorCrossingCut C P r) : + C.portPoint (C.incomingPort r) ∉ Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val)) := by + intro hx + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_drop_trace P r.1 K.last hx + have heq := D'.edge_injective r.1 (he.trans K.first_parameter_point.symm) + exact ((P r.1).increasing K.ordered).not_ge (heq ▸ ht.1) + +theorem outgoing_not_prefix (K : ExteriorCrossingCut C P r) : + C.portPoint (C.outgoingPort r) ∉ Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val)) := by + intro hx + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_take_trace P r.1 K.first hx + have heq := D'.edge_injective r.1 (he.trans K.last_parameter_point.symm) + exact ((P r.1).increasing K.ordered).not_ge (heq ▸ ht.2) + +theorem prefix_suffix_disjoint (K : ExteriorCrossingCut C P r) : + Disjoint (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).take K.first.val))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P r.1).drop K.last.val))) := by + apply Set.disjoint_left.mpr + intro x hx hy + obtain ⟨t,ht,he⟩ := drawingEdgeWalk_take_trace P r.1 K.first hx + obtain ⟨u,hu,hf⟩ := drawingEdgeWalk_drop_trace P r.1 K.last hy + have heq := D'.edge_injective r.1 (he.trans hf.symm) + exact ((P r.1).increasing K.ordered).not_ge (hu.1.trans (heq ▸ ht.2)) + +end Paper170Geometry.ExteriorCrossingCut + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/CycleIdentity.lean b/lean/OAI/Combinatorics/CompleteCrossing/CycleIdentity.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0a0bff766653088c46d66f42ad1f96b100a9d28 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/CycleIdentity.lean @@ -0,0 +1,154 @@ +import OAI.Combinatorics.CompleteCrossing.CycleIntersections +import OAI.Combinatorics.CompleteCrossing.Refinement +import OAI.Combinatorics.CompleteCrossing.Tensor + +namespace OAI + +/-! The geometric cycle identity deduced from endpoint and intersection coordinates. -/ + +section + +/-! Actual vertex-coordinate orders give the frozen signed endpoint contribution. -/ +noncomputable section +open scoped BigOperators Classical +namespace Paper170 +variable {Vertex Edge : Type} {graph : Graph Vertex Edge} + +theorem endpointSign_eq_sub_indicators (v : Vertex) (e : Edge) : + endpointSign graph v e = + (if graph.src e=v then 1 else 0) - (if graph.dst e=v then 1 else 0) := by + by_cases hs : graph.src e=v + · have ht : graph.dst e≠v := fun h => graph.loopless e (hs.trans h.symm) + simp [endpointSign,hs,ht] + · by_cases ht : graph.dst e=v <;> simp [endpointSign,hs,ht] + +theorem sum_endpointSign [Fintype Vertex] (e : Edge) (f : Vertex → ℝ) : + (∑v, endpointSign graph v e * f v) = f (graph.src e)-f (graph.dst e) := by + simp [endpointSign_eq_sub_indicators,sub_mul,ite_mul,Finset.sum_sub_distrib] + +end Paper170 + +namespace Paper170Geometry.TruncatedSpokeCoordinates +open Zarankiewicz +variable {Vertex Edge : Type} [Fintype Vertex] {graph : Paper170.Graph Vertex Edge} + {N : Paper170.NormalizedDrawing graph} {V : VertexTruncation N.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) (O : Paper170.SpokeOrders N) + +omit [Fintype Vertex] in +theorem flagPairing_eq_spokeComparison + (hnode : ∀v (e f : IncidentEdges graph v), + orderSign (C.node v e) (C.node v f) = Paper170.spokeComparison O v e.val f.val) + (a b : IncidentFlag graph) : C.flagPairing a b = + if b.1=a.1 then Paper170.spokeComparison O a.1 a.2.val b.2.val / 2 else 0 := by + unfold flagPairing + split_ifs with h + · rw [hnode] + rfl + · rfl + +theorem edgeEndpointPairing_eq_signed_sum + (hnode : ∀v (e f : IncidentEdges graph v), + orderSign (C.node v e) (C.node v f) = Paper170.spokeComparison O v e.val f.val) + (e f : Edge) : C.edgeEndpointPairing e f = + (1/2 : ℝ) * ∑v, Paper170.endpointSign graph v e * Paper170.endpointSign graph v f * + Paper170.spokeComparison O v e f := by + have hsum := Paper170.sum_endpointSign (graph := graph) e + (fun v => Paper170.endpointSign graph v f * Paper170.spokeComparison O v e f) + simp only [← mul_assoc] at hsum + rw [hsum] + unfold edgeEndpointPairing + rw [C.flagPairing_eq_spokeComparison O hnode,C.flagPairing_eq_spokeComparison O hnode, + C.flagPairing_eq_spokeComparison O hnode,C.flagPairing_eq_spokeComparison O hnode] + simp only [dartSourceFlag,dartTargetFlag,dartSourceIncident,dartTargetIncident, + forwardDart,OrientedDart.fst,OrientedDart.snd,Paper170.endpointSign_eq_sub_indicators] + split_ifs <;> ring + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! The geometric closed-polygon calculation annihilates the real graph cycle space. -/ +noncomputable section +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {Vertex Edge : Type} [Fintype Vertex] [Fintype Edge] + {graph : Paper170.Graph Vertex Edge} {D : Paper170.AdmissibleDrawing graph} + {V : VertexTruncation D.toContinuousDrawing} (C : TruncatedSpokeCoordinates V) + +theorem cycleMatrix_pairing_zero (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (z z' : Edge → ℝ) (hz : ∀v, Paper170.boundary graph z v = 0) + (hz' : ∀v, Paper170.boundary graph z' v = 0) : + Paper170.edgePairing C.cycleIntersectionMatrix z z' = 0 := by + apply Paper170.edgePairing_eq_zero_of_simple_cycles graph C.cycleIntersectionMatrix ?_ z z' hz hz' + intro P Q + rw [Paper170.edgePairing_simple_cycles_range] + exact C.closed_cycle_matrix_sum hnorm hstraight htrans P.cyclicDart Q.cyclicDart + P.cyclicDart_seam Q.cyclicDart_seam P.length Q.length P.cyclicDart_period Q.cyclicDart_period + (fun i _ => P.cyclicDart_next_edge_ne i) (fun j _ => Q.cyclicDart_next_edge_ne j) + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Reconstruction of the frozen cycle pairing from faithful local coordinates. -/ +noncomputable section +namespace Paper170 +open Paper170Geometry +variable {Vertex Edge : Type} [Fintype Vertex] [Fintype Edge] + {graph : Graph Vertex Edge} + +theorem cycle_pairing_of_coordinates (N : NormalizedDrawing graph) (O : SpokeOrders N) + (V : VertexTruncation N.toContinuousDrawing) (C : TruncatedSpokeCoordinates V) + (hnode : ∀v (e f : IncidentEdges graph v), + Zarankiewicz.orderSign (C.node v e) (C.node v f) = spokeComparison O v e.val f.val) + (z z' : Edge → ℝ) (hz : ∀v, boundary graph z v = 0) (hz' : ∀v, boundary graph z' v = 0) : + edgePairing (cycleIntersection O) z z' = 0 := by + have hmatrix : C.cycleIntersectionMatrix = cycleIntersection O := by + funext e f + unfold TruncatedSpokeCoordinates.cycleIntersectionMatrix cycleIntersection + rw [VertexTruncation.signedIntersection_eq_interiorIntersection N V, + C.edgeEndpointPairing_eq_signed_sum O hnode] + rw [← hmatrix] + exact C.cycleMatrix_pairing_zero (normalized_noAdjacent N) (normalized_locallyStraight N) + (normalized_locallyTransverse N) z z' hz hz' + +end Paper170 + +end +end + +section + +/-! The source cycle identity for every normalized ordinary drawing. -/ +noncomputable section +namespace Paper170 +open Paper170Geometry + +theorem cycle_pairing {Vertex Edge : Type} [Fintype Vertex] [Fintype Edge] + (G : Graph Vertex Edge) (N : NormalizedDrawing G) (O : SpokeOrders N) + (z z' : Edge → ℝ) (hz : ∀v, boundary G z v = 0) (hz' : ∀v, boundary G z' v = 0) : + edgePairing (cycleIntersection O) z z' = 0 := by + obtain ⟨V⟩ := normalized_vertexTruncation N + obtain ⟨C,hC⟩ := exists_truncatedSpokeCoordinates_compatible N V O + exact cycle_pairing_of_coordinates N O V C hC z z' hz hz' + +theorem raw_cycle_pairing {n : ℕ} (N : NormalizedDrawing (completeGraph n)) (O : SpokeOrders N) + (z z' : Fin n → Fin n → ℝ) (hz : ∀v, chainBoundary z v = 0) (hz' : ∀v, chainBoundary z' v = 0) : + chainPairing (rawCycleIntersection O) z z' = 0 := by + rw [chainPairing_rawCycleIntersection] + apply cycle_pairing (completeGraph n) N O (liftedChain z) (liftedChain z') + · simpa only [boundary_liftedChain] using hz + · simpa only [boundary_liftedChain] using hz' + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/CycleIntersections.lean b/lean/OAI/Combinatorics/CompleteCrossing/CycleIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e4bb9528a9cf86c75a70467774c36efe0fecfbf --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/CycleIntersections.lean @@ -0,0 +1,594 @@ +import OAI.Combinatorics.CompleteCrossing.DartPaths +import OAI.Combinatorics.CompleteCrossing.VertexChords +import OAI.Combinatorics.Crossing.CyclicSumArithmetic +import OAI.Combinatorics.Crossing.StraightChainIntersections +import OAI.Combinatorics.Crossing.StraightChainTransversality + +namespace OAI + +/-! Signed dart and cycle intersections, passage pairing, and endpoint averaging. -/ + +section + +/-! Complete shifted edge paths have exactly the original signed edge intersections; the two actual connectors contribute zero. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_complete_edge_intersection_radius [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ e f : Edge, + (V.trackChain e).Transverse (C.shiftedEdgeChain f ε) ∧ + polygonIntersection (V.trackChain e).vertices (C.shiftedEdgeChain f ε).vertices + (V.trackChain e).pieces (C.shiftedEdgeChain f ε).pieces=V.signedIntersection e f := by + obtain ⟨δ₀,hδ₀,hT⟩ := V.exists_all_edge_shift_radius hnorm hstraight htrans + obtain ⟨δ₁,hδ₁,hI⟩ := V.exists_uniform_track_intersections hnorm hstraight htrans + obtain ⟨δ₂,hδ₂,hC⟩ := C.exists_all_connector_track_radius hnorm + let δ := min δ₀ (min δ₁ δ₂) + have hδ : 0<δ := lt_min hδ₀ (lt_min hδ₁ hδ₂) + have hb₀ : δ≤δ₀ := min_le_left _ _ + have hb₁ : δ≤δ₁ := (min_le_right _ _).trans (min_le_left _ _) + have hb₂ : δ≤δ₂ := (min_le_right _ _).trans (min_le_right _ _) + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall e f + have hconn (j : Vertex) (g : IncidentEdges graph j) : + (V.trackChain e).Transverse (C.connectorChain j g ε) := by + apply PolygonalChain.transverse_single_right + intro i + exact segmentPairTransverse_of_not_meet _ _ _ _ (hC ε hε (hsmall.trans_le hb₂) j g e i) + have hmid : (V.trackChain e).Transverse (C.shiftedTrackChain f ε) := by + intro i j + exact (hT ε hε (hsmall.trans_le hb₀) e f i j).1 + have hzero (j : Vertex) (g : IncidentEdges graph j) : + polygonIntersection (V.trackChain e).vertices (C.connectorChain j g ε).vertices (V.trackChain e).pieces 1=0 := by + apply PolygonalChain.intersection_single_right_zero + intro i + exact hC ε hε (hsmall.trans_le hb₂) j g e i + constructor + · change (V.trackChain e).Transverse + (((C.connectorChain ((graph.src f)) (V.leftIncident f) ε).join (C.shiftedTrackChain f ε)).join + (C.connectorChain ((graph.dst f)) (V.rightIncident f) ε).reverse) + apply PolygonalChain.transverse_join_right + · exact PolygonalChain.transverse_join_right _ _ _ (hconn _ _) hmid + · exact (V.trackChain e).transverse_reverse_right _ (hconn _ _) + · rw [C.shiftedEdgeChain_intersection_right,hzero,hzero,zero_add,sub_zero] + exact hI ε hε (hsmall.trans_le hb₁) e f + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Complete edge paths and vertex chords have zero cross-type intersection sums, with all seams verified. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_chord_edge_radius [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → + (∀ j (a b : IncidentEdges graph j) e, + (V.chordChain j a b).Transverse (C.shiftedEdgeChain e ε) ∧ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedEdgeChain e ε).vertices + (V.chordChain j a b).pieces (C.shiftedEdgeChain e ε).pieces=0) ∧ + (∀ j (a b : IncidentEdges graph j) e, + (V.trackChain e).Transverse (C.shiftedChordChain j a b ε) ∧ + polygonIntersection (V.trackChain e).vertices (C.shiftedChordChain j a b ε).vertices + (V.trackChain e).pieces (C.shiftedChordChain j a b ε).pieces=0) := by + obtain ⟨δ,hδ,hh⟩ := C.exists_cross_type_radius hnorm + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall + obtain ⟨hTC,hTChord,hChordT,hChordC,hChordChord,hOther⟩ := hh ε hε hsmall + constructor + · intro j a b e + have hconn (k : Vertex) (f : IncidentEdges graph k) : + (V.chordChain j a b).Transverse (C.connectorChain k f ε) := by + apply PolygonalChain.transverse_single_single + exact segmentPairTransverse_of_not_meet _ _ _ _ (hChordC j k a b f) + have hmid : (V.chordChain j a b).Transverse (C.shiftedTrackChain e ε) := by + apply PolygonalChain.transverse_single_left + intro i + exact segmentPairTransverse_of_not_meet _ _ _ _ (hChordT j a b e i) + have hzconn (k : Vertex) (f : IncidentEdges graph k) : + polygonIntersection (V.chordChain j a b).vertices (C.connectorChain k f ε).vertices 1 1=0 := by + rw [VertexTruncation.chordChain,connectorChain,PolygonalChain.intersection_single_single] + exact segmentCrossingSign_eq_zero_of_not_meet _ _ _ _ (hChordC j k a b f) + have hzmid : polygonIntersection (V.chordChain j a b).vertices + (shiftedTrack (V.vertices e) (V.pieces e) ε) 1 (V.pieces e)=0 := by + apply (C.shiftedTrackChain e ε).intersection_single_left_zero + intro i + exact hChordT j a b e i + constructor + · change (V.chordChain j a b).Transverse + (((C.connectorChain ((graph.src e)) (V.leftIncident e) ε).join (C.shiftedTrackChain e ε)).join + (C.connectorChain ((graph.dst e)) (V.rightIncident e) ε).reverse) + apply PolygonalChain.transverse_join_right + · exact PolygonalChain.transverse_join_right _ _ _ (hconn _ _) hmid + · exact (V.chordChain j a b).transverse_reverse_right _ (hconn _ _) + · change polygonIntersection (V.chordChain j a b).vertices (C.shiftedEdgeChain e ε).vertices 1 _=0 + rw [C.shiftedEdgeChain_intersection_right,hzconn,hzconn,hzmid] + norm_num + · intro j a b e + constructor + · apply PolygonalChain.transverse_single_right + intro i + exact segmentPairTransverse_of_not_meet _ _ _ _ (hTChord j a b e i) + · apply PolygonalChain.intersection_single_right_zero + intro i + exact hTChord j a b e i + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Actual vertex-chord chains have precisely the local two-sided averaged endpoint pairing. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem chordChain_intersection (j k : Vertex) (a b : IncidentEdges graph j) + (c d : IncidentEdges graph k) (ε : ℝ) : + polygonIntersection (V.chordChain j a b).vertices (C.shiftedChordChain k c d ε).vertices 1 1= + segmentCrossingSign (V.spokePort j a) (V.spokePort j b) (C.shiftedPort k c ε) (C.shiftedPort k d ε) := by + rw [VertexTruncation.chordChain,shiftedChordChain,PolygonalChain.intersection_single_single] + +theorem exists_vertex_chord_chain_radius [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ + (∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j k (a b : IncidentEdges graph j) (c d : IncidentEdges graph k), + a ≠ b → c ≠ d → (V.chordChain j a b).Transverse (C.shiftedChordChain k c d ε)) ∧ + (∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j k, j ≠ k → ∀ (a b : IncidentEdges graph j) (c d : IncidentEdges graph k), + polygonIntersection (V.chordChain j a b).vertices (C.shiftedChordChain k c d ε).vertices 1 1=0) ∧ + (∀ t : ℝ, 0 + rcases orientedDart_cases b with ⟨f,rfl⟩ | ⟨f,rfl⟩ + · obtain ⟨hT,hI⟩ := h e f + refine ⟨hT,?_⟩ + change polygonIntersection (V.trackChain e).vertices (C.shiftedEdgeChain f ε).vertices + (V.trackChain e).pieces (C.shiftedEdgeChain f ε).pieces=1*1*V.signedIntersection e f + simpa only [one_mul] using hI + · obtain ⟨hT,hI⟩ := h e f + refine ⟨(V.trackChain e).transverse_reverse_right _ hT,?_⟩ + change polygonIntersection (V.trackChain e).vertices (C.shiftedEdgeChain f ε).reverse.vertices + (V.trackChain e).pieces (C.shiftedEdgeChain f ε).reverse.pieces=1*(-1)*V.signedIntersection e f + rw [PolygonalChain.intersection_reverse_right,hI] + ring + · obtain ⟨hT,hI⟩ := h e f + refine ⟨(V.trackChain e).transverse_reverse_left _ hT,?_⟩ + change polygonIntersection (V.trackChain e).reverse.vertices (C.shiftedEdgeChain f ε).vertices + (V.trackChain e).reverse.pieces (C.shiftedEdgeChain f ε).pieces=(-1)*1*V.signedIntersection e f + rw [PolygonalChain.intersection_reverse_left,hI] + ring + · obtain ⟨hT,hI⟩ := h e f + refine ⟨(V.trackChain e).reverse.transverse_reverse_right _ + ((V.trackChain e).transverse_reverse_left _ hT),?_⟩ + change polygonIntersection (V.trackChain e).reverse.vertices (C.shiftedEdgeChain f ε).reverse.vertices + (V.trackChain e).reverse.pieces (C.shiftedEdgeChain f ε).reverse.pieces=(-1)*(-1)*V.signedIntersection e f + rw [PolygonalChain.intersection_reverse_left,PolygonalChain.intersection_reverse_right,hI] + ring + +theorem chord_dart_intersection {ε : ℝ} (j : Vertex) (a b : IncidentEdges graph j) + (d : OrientedDart graph) + (h : ∀ e, (V.chordChain j a b).Transverse (C.shiftedEdgeChain e ε) ∧ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedEdgeChain e ε).vertices + (V.chordChain j a b).pieces (C.shiftedEdgeChain e ε).pieces=0) : + (V.chordChain j a b).Transverse (C.shiftedDartChain d ε) ∧ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedDartChain d ε).vertices + (V.chordChain j a b).pieces (C.shiftedDartChain d ε).pieces=0 := by + rcases orientedDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ + · exact h e + · obtain ⟨hT,hI⟩ := h e + refine ⟨(V.chordChain j a b).transverse_reverse_right _ hT,?_⟩ + change polygonIntersection (V.chordChain j a b).vertices (C.shiftedEdgeChain e ε).reverse.vertices + (V.chordChain j a b).pieces (C.shiftedEdgeChain e ε).reverse.pieces=0 + rw [PolygonalChain.intersection_reverse_right,hI,neg_zero] + +theorem dart_chord_intersection {ε : ℝ} (j : Vertex) (a b : IncidentEdges graph j) + (d : OrientedDart graph) + (h : ∀ e, (V.trackChain e).Transverse (C.shiftedChordChain j a b ε) ∧ + polygonIntersection (V.trackChain e).vertices (C.shiftedChordChain j a b ε).vertices + (V.trackChain e).pieces (C.shiftedChordChain j a b ε).pieces=0) : + (V.dartTrackChain d).Transverse (C.shiftedChordChain j a b ε) ∧ + polygonIntersection (V.dartTrackChain d).vertices (C.shiftedChordChain j a b ε).vertices + (V.dartTrackChain d).pieces (C.shiftedChordChain j a b ε).pieces=0 := by + rcases orientedDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ + · exact h e + · obtain ⟨hT,hI⟩ := h e + refine ⟨(V.trackChain e).transverse_reverse_left _ hT,?_⟩ + change polygonIntersection (V.trackChain e).reverse.vertices (C.shiftedChordChain j a b ε).vertices + (V.trackChain e).reverse.pieces (C.shiftedChordChain j a b ε).pieces=0 + rw [PolygonalChain.intersection_reverse_left,hI,neg_zero] + +theorem exists_dart_intersection_radius [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε| < δ → + (∀ a b : OrientedDart graph, + (V.dartTrackChain a).Transverse (C.shiftedDartChain b ε) ∧ + polygonIntersection (V.dartTrackChain a).vertices (C.shiftedDartChain b ε).vertices + (V.dartTrackChain a).pieces (C.shiftedDartChain b ε).pieces= + dartSign a*dartSign b*V.signedIntersection (OrientedDart.edge a) (OrientedDart.edge b)) ∧ + (∀ j (a b : IncidentEdges graph j) d, + (V.chordChain j a b).Transverse (C.shiftedDartChain d ε) ∧ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedDartChain d ε).vertices + (V.chordChain j a b).pieces (C.shiftedDartChain d ε).pieces=0) ∧ + (∀ j (a b : IncidentEdges graph j) d, + (V.dartTrackChain d).Transverse (C.shiftedChordChain j a b ε) ∧ + polygonIntersection (V.dartTrackChain d).vertices (C.shiftedChordChain j a b ε).vertices + (V.dartTrackChain d).pieces (C.shiftedChordChain j a b ε).pieces=0) := by + obtain ⟨δ₀,hδ₀,h₀⟩ := C.exists_complete_edge_intersection_radius hnorm hstraight htrans + obtain ⟨δ₁,hδ₁,h₁⟩ := C.exists_chord_edge_radius hnorm + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro ε hε hs + have he := h₀ ε hε (hs.trans_le (min_le_left _ _)) + obtain ⟨hcd,hdc⟩ := h₁ ε hε (hs.trans_le (min_le_right _ _)) + exact ⟨fun a b => C.dart_pair_intersection a b he, + fun j a b d => C.chord_dart_intersection j a b d (hcd j a b), + fun j a b d => C.dart_chord_intersection j a b d (hdc j a b)⟩ + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Every actual cycle-block intersection splits into its edge term and its vertex-chord term. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry + +namespace PolygonalChain +variable {O T : Set Plane} {a b c d e f : Plane} + +theorem intersection_join_join (P : PolygonalChain O a b) (Q : PolygonalChain O b c) + (R : PolygonalChain T d e) (S : PolygonalChain T e f) : + polygonIntersection (P.join Q).vertices (R.join S).vertices (P.join Q).pieces (R.join S).pieces= + polygonIntersection P.vertices R.vertices P.pieces R.pieces+ + polygonIntersection P.vertices S.vertices P.pieces S.pieces+ + polygonIntersection Q.vertices R.vertices Q.pieces R.pieces+ + polygonIntersection Q.vertices S.vertices Q.pieces S.pieces := by + rw [Zarankiewicz.PolygonalChain.intersection_join_left, + Zarankiewicz.PolygonalChain.intersection_join_right, + Zarankiewicz.PolygonalChain.intersection_join_right] + ring + +theorem transverse_join_join (P : PolygonalChain O a b) (Q : PolygonalChain O b c) + (R : PolygonalChain T d e) (S : PolygonalChain T e f) + (hPR : P.Transverse R) (hPS : P.Transverse S) (hQR : Q.Transverse R) (hQS : Q.Transverse S) : + (P.join Q).Transverse (R.join S) := + P.transverse_join_left Q (R.join S) + (R.transverse_join_right S P hPR hPS) (R.transverse_join_right S Q hQR hQS) + +end PolygonalChain +namespace TruncatedSpokeCoordinates +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +def passageIntersection (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (i j : ℕ) (ε : ℝ) : ℝ := + polygonIntersection (V.chordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i)).vertices + (C.shiftedChordChain (f j).snd (dartTargetIncident (f j)) (dartPassageNext f hf j) ε).vertices 1 1 + +theorem exists_cycle_block_radius [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε| < δ → + ∀ (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) (i j : ℕ), + OrientedDart.edge (d (i+1)) ≠ OrientedDart.edge (d i) → + OrientedDart.edge (f (j+1)) ≠ OrientedDart.edge (f j) → + (V.dartCycleBlock d hd i).Transverse (C.shiftedCycleBlock f hf ε j) ∧ + polygonIntersection (V.dartCycleBlock d hd i).vertices (C.shiftedCycleBlock f hf ε j).vertices + (V.dartCycleBlock d hd i).pieces (C.shiftedCycleBlock f hf ε j).pieces= + dartSign (d i)*dartSign (f j)* + V.signedIntersection (OrientedDart.edge (d i)) (OrientedDart.edge (f j))+ + C.passageIntersection d f hd hf i j ε := by + obtain ⟨δ₀,hδ₀,h₀⟩ := C.exists_dart_intersection_radius hnorm hstraight htrans + obtain ⟨δ₁,hδ₁,h₁,-,-⟩ := C.exists_vertex_chord_chain_radius hnorm + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro ε hε hs d f hd hf i j hdi hfj + obtain ⟨hdd,hcd,hdc⟩ := h₀ ε hε (hs.trans_le (min_le_left _ _)) + have hcc := h₁ ε hε (hs.trans_le (min_le_right _ _)) + (d i).snd (f j).snd (dartTargetIncident (d i)) (dartPassageNext d hd i) + (dartTargetIncident (f j)) (dartPassageNext f hf j) + (dartPassage_ne d hd i hdi) (dartPassage_ne f hf j hfj) + obtain ⟨hDD,hDI⟩ := hdd (d i) (f j) + obtain ⟨hCD,hCI⟩ := hcd (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i) (f j) + obtain ⟨hDC,hIC⟩ := hdc (f j).snd (dartTargetIncident (f j)) (dartPassageNext f hf j) (d i) + constructor + · exact PolygonalChain.transverse_join_join _ _ _ _ hDD hDC hCD hcc + · change polygonIntersection + ((V.dartTrackChain (d i)).join (V.chordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i))).vertices + ((C.shiftedDartChain (f j) ε).join (C.shiftedChordChain (f j).snd (dartTargetIncident (f j)) (dartPassageNext f hf j) ε)).vertices + ((V.dartTrackChain (d i)).join (V.chordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i))).pieces + ((C.shiftedDartChain (f j) ε).join (C.shiftedChordChain (f j).snd (dartTargetIncident (f j)) (dartPassageNext f hf j) ε)).pieces=_ + rw [PolygonalChain.intersection_join_join,hDI,hIC,hCI,add_zero,add_zero] + rfl + +end TruncatedSpokeCoordinates +end Paper170Geometry + +end +end + +section + +/-! The global sum is derived from the actual closed polygonal curves and every one of their traversals. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +open scoped BigOperators +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_closed_cycle_intersection_radius [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε| < δ → + ∀ (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (N K : ℕ), d N=d 0 → f K=f 0 → + (∀ i, i < N → OrientedDart.edge (d (i+1)) ≠ OrientedDart.edge (d i)) → + (∀ j, j < K → OrientedDart.edge (f (j+1)) ≠ OrientedDart.edge (f j)) → + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + (dartSign (d i)*dartSign (f j)* + V.signedIntersection (OrientedDart.edge (d i)) (OrientedDart.edge (f j))+ + C.passageIntersection d f hd hf i j ε)=0 := by + obtain ⟨δ,hδ,hh⟩ := C.exists_cycle_block_radius hnorm hstraight htrans + refine ⟨δ,hδ,?_⟩ + intro ε hε hs d f hd hf N K hN hK hdi hfj + let P := V.dartCycleChain d hd N hN + let Q := C.shiftedCycleChain f hf K hK ε + have hblocks (i j : ℕ) (hi : i < N) (hj : j < K) := + hh ε hε hs d f hd hf i j (hdi i hi) (hfj j hj) + have hT : P.Transverse Q := by + change (finitePolygonalChain Set.univ (V.dartCycleVertex d) (Set.mem_univ _) (V.dartCycleBlock d hd) N).Transverse + (finitePolygonalChain Set.univ (C.shiftedCycleVertex f ε) (Set.mem_univ _) (C.shiftedCycleBlock f hf ε) K) + apply finitePolygonalChain_transverse_left + intro i hi + apply finitePolygonalChain_transverse_right + intro j hj + exact (hblocks i j hi hj).1 + have hzero := P.closed_intersection_zero Q hT + have hsplit : polygonIntersection P.vertices Q.vertices P.pieces Q.pieces= + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + polygonIntersection (V.dartCycleBlock d hd i).vertices (C.shiftedCycleBlock f hf ε j).vertices + (V.dartCycleBlock d hd i).pieces (C.shiftedCycleBlock f hf ε j).pieces := + finitePolygonalChain_intersection_double _ _ _ _ _ _ _ _ + rw [hsplit] at hzero + calc + _ = ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + polygonIntersection (V.dartCycleBlock d hd i).vertices (C.shiftedCycleBlock f hf ε j).vertices + (V.dartCycleBlock d hd i).pieces (C.shiftedCycleBlock f hf ε j).pieces := by + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + exact (hblocks i j (Finset.mem_range.mp hi) (Finset.mem_range.mp hj)).2.symm + _ = 0 := hzero + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! The local pairing uses one fixed coordinate chart per vertex, including shared chord endpoints. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} [Fintype Vertex] [Fintype Edge] {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_vertex_pairing_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, 0 < t → t < δ → + ∀ j k (a b : IncidentEdges graph j) (c d : IncidentEdges graph k), a ≠ b → c ≠ d → + (polygonIntersection (V.chordChain j a b).vertices (C.shiftedChordChain k c d t).vertices 1 1+ + polygonIntersection (V.chordChain j a b).vertices (C.shiftedChordChain k c d (-t)).vertices 1 1)/2= + C.vertexChordPairing j k a b c d := by + obtain ⟨δ,hδ,-,hzero,havg⟩ := C.exists_vertex_chord_chain_radius hnorm + refine ⟨δ,hδ,?_⟩ + intro t ht hs j k a b c d hab hcd + by_cases h : k=j + · subst k + have hc : incidentCast (rfl : j=j) c=c := Subtype.ext rfl + have hd : incidentCast (rfl : j=j) d=d := Subtype.ext rfl + rw [vertexChordPairing,dite_eq_left rfl,hc,hd] + exact havg t ht hs j a b c d hab hcd + · have hzplus := hzero t (ne_of_gt ht) (by simpa only [abs_of_pos ht] using hs) j k (Ne.symm h) a b c d + have hzminus := hzero (-t) (neg_ne_zero.mpr (ne_of_gt ht)) (by simpa only [abs_neg,abs_of_pos ht] using hs) + j k (Ne.symm h) a b c d + rw [hzplus,hzminus,zero_add,zero_div] + simp only [vertexChordPairing,dite_eq_right h] + +theorem exists_passage_pairing_radius (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, 0 < t → t < δ → + ∀ (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) (i j : ℕ), + OrientedDart.edge (d (i+1)) ≠ OrientedDart.edge (d i) → + OrientedDart.edge (f (j+1)) ≠ OrientedDart.edge (f j) → + (C.passageIntersection d f hd hf i j t+C.passageIntersection d f hd hf i j (-t))/2= + C.passagePairing d f hd hf i j := by + obtain ⟨δ,hδ,hh⟩ := C.exists_vertex_pairing_radius hnorm + refine ⟨δ,hδ,?_⟩ + intro t ht hs d f hd hf i j hi hj + exact hh t ht hs _ _ _ _ _ _ (dartPassage_ne d hd i hi) (dartPassage_ne f hf j hj) + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Two actual physical shifts give the global averaged identity, with no restriction on shared edges between cycles. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} [Fintype Vertex] [Fintype Edge] {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +open scoped BigOperators +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem closed_cycle_averaged_sum (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (N K : ℕ) (hN : d N=d 0) (hK : f K=f 0) + (hdi : ∀ i, i < N → OrientedDart.edge (d (i+1)) ≠ OrientedDart.edge (d i)) + (hfj : ∀ j, j < K → OrientedDart.edge (f (j+1)) ≠ OrientedDart.edge (f j)) : + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + (dartSign (d i)*dartSign (f j)* + V.signedIntersection (OrientedDart.edge (d i)) (OrientedDart.edge (f j))+ + C.passagePairing d f hd hf i j)=0 := by + obtain ⟨δ₀,hδ₀,hglobal⟩ := C.exists_closed_cycle_intersection_radius hnorm hstraight htrans + obtain ⟨δ₁,hδ₁,hlocal⟩ := C.exists_passage_pairing_radius hnorm + let t := min δ₀ δ₁/2 + have ht : 0 < t := half_pos (lt_min hδ₀ hδ₁) + have htmin : t < min δ₀ δ₁ := half_lt_self (lt_min hδ₀ hδ₁) + have ht₀ : t < δ₀ := htmin.trans_le (min_le_left _ _) + have ht₁ : t < δ₁ := htmin.trans_le (min_le_right _ _) + have hzplus := hglobal t (ne_of_gt ht) (by simpa only [abs_of_pos ht] using ht₀) d f hd hf N K hN hK hdi hfj + have hzminus := hglobal (-t) (neg_ne_zero.mpr (ne_of_gt ht)) + (by simpa only [abs_neg,abs_of_pos ht] using ht₀) d f hd hf N K hN hK hdi hfj + let E : ℕ → ℕ → ℝ := fun i j => dartSign (d i)*dartSign (f j)* + V.signedIntersection (OrientedDart.edge (d i)) (OrientedDart.edge (f j)) + calc + _ = ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + ((E i j+C.passageIntersection d f hd hf i j t)+ + (E i j+C.passageIntersection d f hd hf i j (-t)))/2 := by + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + rw [← hlocal t ht ht₁ d f hd hf i j (hdi i (Finset.mem_range.mp hi)) (hfj j (Finset.mem_range.mp hj))] + dsimp only [E] + ring + _ = ((∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, (E i j+C.passageIntersection d f hd hf i j t))+ + (∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, (E i j+C.passageIntersection d f hd hf i j (-t))))/2 := by + simp only [div_eq_mul_inv,Finset.sum_add_distrib,Finset.sum_mul,add_mul] + _ = 0 := by rw [hzplus,hzminus]; norm_num + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Every local passage endpoint is counted once at the corresponding graph-edge endpoint. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +open scoped BigOperators +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem passage_sum_eq_endpoint_sum (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (N K : ℕ) (hN : d N=d 0) (hK : f K=f 0) : + (∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, C.passagePairing d f hd hf i j)= + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + dartSign (d i)*dartSign (f j)* + C.edgeEndpointPairing (OrientedDart.edge (d i)) (OrientedDart.edge (f j)) := by + have hTS := double_sum_cycle_shift_right d f N K hK + (fun a b => C.flagPairing (dartTargetFlag a) (dartSourceFlag b)) + have hST := double_sum_cycle_shift_left d f N K hN + (fun a b => C.flagPairing (dartSourceFlag a) (dartTargetFlag b)) + have hSS₀ := double_sum_cycle_shift_right (fun i => d (i+1)) f N K hK + (fun a b => C.flagPairing (dartSourceFlag a) (dartSourceFlag b)) + have hSS₁ := double_sum_cycle_shift_left d f N K hN + (fun a b => C.flagPairing (dartSourceFlag a) (dartSourceFlag b)) + simp_rw [C.passagePairing_flags,← C.dart_endpoint_pairing] + simp only [Finset.sum_add_distrib,Finset.sum_sub_distrib] + rw [hTS,hST,hSS₀,hSS₁] + +def cycleIntersectionMatrix : Edge → Edge → ℝ := + fun e f => V.signedIntersection e f+C.edgeEndpointPairing e f + +theorem closed_cycle_matrix_sum [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (N K : ℕ) (hN : d N=d 0) (hK : f K=f 0) + (hdi : ∀ i, i < N → OrientedDart.edge (d (i+1)) ≠ OrientedDart.edge (d i)) + (hfj : ∀ j, j < K → OrientedDart.edge (f (j+1)) ≠ OrientedDart.edge (f j)) : + ∑ i ∈ Finset.range N, ∑ j ∈ Finset.range K, + dartSign (d i)*dartSign (f j)* + C.cycleIntersectionMatrix (OrientedDart.edge (d i)) (OrientedDart.edge (f j))=0 := by + have hh := C.closed_cycle_averaged_sum hnorm hstraight htrans d f hd hf N K hN hK hdi hfj + simp only [Finset.sum_add_distrib] at hh + rw [C.passage_sum_eq_endpoint_sum d f hd hf N K hN hK] at hh + simpa only [cycleIntersectionMatrix,mul_add,Finset.sum_add_distrib] using hh + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/CycleSpace.lean b/lean/OAI/Combinatorics/CompleteCrossing/CycleSpace.lean new file mode 100644 index 0000000000000000000000000000000000000000..10656e6c8c74f7eb6d7b3a40216ef270a1967b75 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/CycleSpace.lean @@ -0,0 +1,583 @@ +import OAI.Combinatorics.CompleteCrossing.Drawing +import Mathlib.Dynamics.PeriodicPts.Lemmas +import Mathlib.LinearAlgebra.Span.Defs +import Mathlib.Logic.Equiv.Fin.Rotate +import Mathlib.Tactic +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring + +namespace OAI + +/-! Cycle-space spanning, flows, simple cycles, and oriented darts. -/ + +section + +/-! Linear properties of actual oriented simple cycles. -/ +noncomputable section +open scoped BigOperators Classical +namespace Paper170 +variable {V E : Type} {G : Graph V E} +namespace SimpleCycle + +def next (C : SimpleCycle G) (i : Fin C.length) : Fin C.length := + ⟨(i.val+1)%C.length, Nat.mod_lt _ (by have := C.three_le; omega)⟩ + +theorem follows_next (C : SimpleCycle G) (i : Fin C.length) : + (G.src (C.edge i)=C.vertex i ∧ G.dst (C.edge i)=C.vertex (C.next i)) ∨ + (G.dst (C.edge i)=C.vertex i ∧ G.src (C.edge i)=C.vertex (C.next i)) := C.follows i + +theorem next_eq_finRotate (C : SimpleCycle G) : C.next = finRotate C.length := by + funext i + apply Fin.ext + have hL : 1 < C.length := by have := C.three_le; omega + simp [next, finRotate_apply, Fin.val_add, Nat.mod_eq_of_lt hL] + +theorem next_val (C : SimpleCycle G) (i : Fin C.length) : + (C.next i).val = if i.val+1 omega + +theorem next_next_ne_self (C : SimpleCycle G) (i : Fin C.length) : C.next (C.next i)≠i := by + intro h + have he := congrArg Fin.val h + simp only [next_val] at he + have := C.three_le + split_ifs at he <;> omega + +theorem edge_injective (C : SimpleCycle G) : Function.Injective C.edge := by + intro i j hij + have hi := C.follows_next i + have hj := C.follows_next j + rw [hij] at hi + rcases hi with hi | hi <;> rcases hj with hj | hj + · exact C.vertex_injective (hi.1.symm.trans hj.1) + · have h1 := C.vertex_injective (hi.1.symm.trans hj.2) + have h2 := C.vertex_injective (hi.2.symm.trans hj.1) + exact False.elim (C.next_next_ne_self j (by rw [← h1,h2])) + · have h1 := C.vertex_injective (hi.1.symm.trans hj.2) + have h2 := C.vertex_injective (hi.2.symm.trans hj.1) + exact False.elim (C.next_next_ne_self j (by rw [← h1,h2])) + · exact C.vertex_injective (hi.1.symm.trans hj.1) + +theorem edgeChain_at_edge (C : SimpleCycle G) (i : Fin C.length) : + C.edgeChain (C.edge i) = if G.src (C.edge i)=C.vertex i then 1 else -1 := by + classical + simp only [edgeChain, C.edge_injective.eq_iff] + simp + +theorem edgeChain_at_edge_ne_zero (C : SimpleCycle G) (i : Fin C.length) : + C.edgeChain (C.edge i) ≠ 0 := by + rw [edgeChain_at_edge] + split_ifs <;> norm_num + +theorem edgeChain_eq_zero_of_not_mem_range (C : SimpleCycle G) {e : E} + (he : e∉Set.range C.edge) : C.edgeChain e=0 := by + classical + apply Finset.sum_eq_zero + intro i _ + rw [ite_eq_right (fun h => he ⟨i,h⟩)] + +theorem edgeChain_support (C : SimpleCycle G) (e : E) : + C.edgeChain e≠0 ↔ e∈Set.range C.edge := by + constructor + · exact fun h => Classical.byContradiction (fun he => h (C.edgeChain_eq_zero_of_not_mem_range he)) + · rintro ⟨i,rfl⟩ + exact C.edgeChain_at_edge_ne_zero i + +theorem signed_boundary_step (C : SimpleCycle G) (i : Fin C.length) (v : V) : + (if G.src (C.edge i)=C.vertex i then (1:ℝ) else -1) * + ((if G.dst (C.edge i)=v then 1 else 0)-(if G.src (C.edge i)=v then 1 else 0)) = + (if C.vertex (C.next i)=v then 1 else 0)-(if C.vertex i=v then 1 else 0) := by + classical + rcases C.follows_next i with h | h + · simp [h.1,h.2] + · have hn : C.vertex (C.next i)≠C.vertex i := fun h => C.next_ne_self i (C.vertex_injective h) + simp only [h.1,h.2,ite_eq_right hn] + ring + +theorem boundary_edgeChain [Fintype E] (C : SimpleCycle G) (v : V) : boundary G C.edgeChain v=0 := by + classical + unfold boundary edgeChain + simp only [Finset.sum_mul] + rw [Finset.sum_comm] + have hi (i : Fin C.length) : + (∑e, (if C.edge i=e then (if G.src e=C.vertex i then (1:ℝ) else -1) else 0) * + ((if G.dst e=v then 1 else 0)-(if G.src e=v then 1 else 0))) = + (if C.vertex (C.next i)=v then 1 else 0)-(if C.vertex i=v then 1 else 0) := by + rw [Finset.sum_eq_single (C.edge i)] + · simpa using C.signed_boundary_step i v + · intro e _ he + simp [Ne.symm he] + · simp + simp_rw [hi] + rw [Finset.sum_sub_distrib, next_eq_finRotate] + exact sub_eq_zero.mpr (Equiv.sum_comp (finRotate C.length) + (fun i => if C.vertex i=v then (1:ℝ) else 0)) + +end SimpleCycle +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators Classical +namespace Paper170 + +variable {V E : Type} [Fintype V] [Fintype E] (G : Graph V E) + +omit [Fintype V] in +lemma incoming_has_outgoing (z : E → ℝ) (hz : ∀ v, boundary G z v = 0) + (v : V) (e : E) + (he : (G.dst e = v ∧ 0 < z e) ∨ (G.src e = v ∧ z e < 0)) : + ∃ f, ((G.src f = v ∧ 0 < z f) ∨ (G.dst f = v ∧ z f < 0)) := by + by_contra hn + have hn' (f : E) : ¬ ((G.src f = v ∧ 0 < z f) ∨ (G.dst f = v ∧ z f < 0)) := fun hf => hn ⟨f, hf⟩ + let term := fun f : E => z f * ((if G.dst f = v then 1 else 0) - + (if G.src f = v then 1 else 0)) + have hnonneg (f : E) : 0 ≤ term f := by + by_cases hdst : G.dst f = v + · by_cases hsrc : G.src f = v + · exact (G.loopless f (hsrc.trans hdst.symm)).elim + · have hf : 0 ≤ z f := by + by_contra! h + exact hn' f (Or.inr ⟨hdst, h⟩) + simpa [term, hdst, hsrc] using hf + · by_cases hsrc : G.src f = v + · have hf : z f ≤ 0 := by + by_contra! h + exact hn' f (Or.inl ⟨hsrc, h⟩) + simpa [term, hdst, hsrc] using neg_nonneg.mpr hf + · simp [term, hdst, hsrc] + have hpos : 0 < term e := by + rcases he with ⟨hdst, he⟩ | ⟨hsrc, he⟩ + · have hsrc : G.src e ≠ v := fun h => G.loopless e (h.trans hdst.symm) + simpa [term, hdst, hsrc] using he + · have hdst : G.dst e ≠ v := fun h => G.loopless e (hsrc.trans h.symm) + simpa [term, hdst, hsrc] using neg_pos.mpr he + have ht : 0 < ∑ f, term f := Finset.sum_pos' (fun f _ => hnonneg f) + ⟨e, Finset.mem_univ e, hpos⟩ + have hzero : (∑ f, term f) = 0 := hz v + linarith + +abbrev FlowVertex (z : E → ℝ) := {v : V // ∃ e, ((G.src e = v ∧ 0 < z e) ∨ (G.dst e = v ∧ z e < 0))} + +omit [Fintype V] in +lemma flow_successor_exists (z : E → ℝ) (hz : ∀ v, boundary G z v = 0) + (v : FlowVertex G z) : ∃ w : FlowVertex G z, ∃ e, ((G.src e = v.val ∧ G.dst e = w.val ∧ 0 < z e) ∨ + (G.dst e = v.val ∧ G.src e = w.val ∧ z e < 0)) := by + obtain ⟨e, he⟩ := v.property + rcases he with ⟨hsrc, he⟩ | ⟨hdst, he⟩ + · refine ⟨⟨G.dst e, incoming_has_outgoing G z hz (G.dst e) e (Or.inl ⟨rfl, he⟩)⟩, + e, Or.inl ⟨hsrc, rfl, he⟩⟩ + · refine ⟨⟨G.src e, incoming_has_outgoing G z hz (G.src e) e (Or.inr ⟨rfl, he⟩)⟩, + e, Or.inr ⟨hdst, rfl, he⟩⟩ + +def flowNext (z : E → ℝ) (hz : ∀ v, boundary G z v = 0) (v : FlowVertex G z) : + FlowVertex G z := (flow_successor_exists G z hz v).choose + +def flowEdge (z : E → ℝ) (hz : ∀ v, boundary G z v = 0) (v : FlowVertex G z) : E := + (flow_successor_exists G z hz v).choose_spec.choose + +omit [Fintype V] in +lemma flowEdge_spec (z : E → ℝ) (hz : ∀ v, boundary G z v = 0) (v : FlowVertex G z) : + ((G.src (flowEdge G z hz v) = v.val ∧ G.dst (flowEdge G z hz v) = (flowNext G z hz v).val ∧ 0 < z (flowEdge G z hz v)) ∨ + (G.dst (flowEdge G z hz v) = v.val ∧ G.src (flowEdge G z hz v) = (flowNext G z hz v).val ∧ z (flowEdge G z hz v) < 0)) := + (flow_successor_exists G z hz v).choose_spec.choose_spec + +omit [Fintype V] [Fintype E] in +lemma flowArc_irrefl (z : E → ℝ) (v : V) (e : E) : ¬ ((G.src e = v ∧ G.dst e = v ∧ 0 < z e) ∨ + (G.dst e = v ∧ G.src e = v ∧ z e < 0)) := by + rintro (⟨hs, hd, _⟩ | ⟨hd, hs, _⟩) <;> exact G.loopless e (hs.trans hd.symm) + +omit [Fintype V] [Fintype E] in +lemma flowArc_not_reverse (z : E → ℝ) (v w : V) (e f : E) + (he : ((G.src e = v ∧ G.dst e = w ∧ 0 < z e) ∨ + (G.dst e = v ∧ G.src e = w ∧ z e < 0))) (hf : ((G.src f = w ∧ G.dst f = v ∧ 0 < z f) ∨ + (G.dst f = w ∧ G.src f = v ∧ z f < 0))) : False := by + have hef : e = f := by + apply G.simple e f + rcases he with ⟨he1, he2, _⟩ | ⟨he1, he2, _⟩ <;> + rcases hf with ⟨hf1, hf2, _⟩ | ⟨hf1, hf2, _⟩ + · exact Or.inr ⟨he1.trans hf2.symm, he2.trans hf1.symm⟩ + · exact Or.inl ⟨he1.trans hf2.symm, he2.trans hf1.symm⟩ + · exact Or.inl ⟨he2.trans hf1.symm, he1.trans hf2.symm⟩ + · exact Or.inr ⟨he2.trans hf1.symm, he1.trans hf2.symm⟩ + subst f + rcases he with ⟨he1, he2, hp⟩ | ⟨he1, he2, hp⟩ <;> + rcases hf with ⟨hf1, hf2, hq⟩ | ⟨hf1, hf2, hq⟩ + · exact G.loopless e (he1.trans hf2.symm) + · linarith + · linarith + · exact G.loopless e (hf2.trans he1.symm) + +lemma exists_positive_period {α : Type*} [Finite α] [Nonempty α] (f : α → α) : + ∃ a, 0 < Function.minimalPeriod f a := by + let x : α := Classical.arbitrary α + obtain ⟨m, n, hne, heq⟩ := Finite.exists_ne_map_eq_of_infinite (fun i : ℕ => f^[i] x) + have helper {m n : ℕ} (hmn : m < n) (h : f^[m] x = f^[n] x) : + ∃ a, 0 < Function.minimalPeriod f a := by + have hperiod : Function.IsPeriodicPt f (n - m) (f^[m] x) := by + change f^[n-m] (f^[m] x) = f^[m] x + rw [← Function.iterate_add_apply, Nat.sub_add_cancel hmn.le] + exact h.symm + exact ⟨f^[m] x, hperiod.minimalPeriod_pos (Nat.sub_pos_of_lt hmn)⟩ + rcases lt_or_gt_of_ne hne with hlt | hlt + · exact helper hlt heq + · exact helper hlt heq.symm + +end Paper170 + +end +end + +section + +/-! Directed traversals of the fixed edges of an arbitrary finite simple graph. -/ +noncomputable section +namespace Paper170Geometry +open Paper170 (Graph) +variable {V E : Type} {G : Graph V E} + +structure OrientedDart (G : Graph V E) where + edge : E + forward : Bool + +namespace OrientedDart + +def fst (d : OrientedDart G) : V := if d.forward then G.src d.edge else G.dst d.edge + +def snd (d : OrientedDart G) : V := if d.forward then G.dst d.edge else G.src d.edge + +def symm (d : OrientedDart G) : OrientedDart G := ⟨d.edge,!d.forward⟩ + +@[simp] theorem symm_fst (d : OrientedDart G) : d.symm.fst = d.snd := by + cases d with | mk e b => cases b <;> rfl + +@[simp] theorem symm_snd (d : OrientedDart G) : d.symm.snd = d.fst := by + cases d with | mk e b => cases b <;> rfl + +@[simp] theorem symm_symm (d : OrientedDart G) : d.symm.symm = d := by + cases d with | mk e b => cases b <;> rfl + +theorem fst_ne_snd (d : OrientedDart G) : d.fst ≠ d.snd := by + cases d with + | mk e b => + cases b + · exact (G.loopless e).symm + · exact G.loopless e + +end OrientedDart + +def forwardDart (G : Graph V E) (e : E) : OrientedDart G := ⟨e,true⟩ + +def backwardDart (G : Graph V E) (e : E) : OrientedDart G := ⟨e,false⟩ + +def dartSign (d : OrientedDart G) : ℝ := if d.forward then 1 else -1 + +theorem orientedDart_cases (d : OrientedDart G) : + (∃ e, d = forwardDart G e) ∨ (∃ e, d = backwardDart G e) := by + cases d with + | mk e b => + cases b + · exact Or.inr ⟨e,rfl⟩ + · exact Or.inl ⟨e,rfl⟩ + +theorem dart_source_incident (d : OrientedDart G) : + d.fst = G.src d.edge ∨ d.fst = G.dst d.edge := by + cases d with + | mk e b => + cases b + · exact Or.inr rfl + · exact Or.inl rfl + +theorem dart_target_incident (d : OrientedDart G) : + d.snd = G.src d.edge ∨ d.snd = G.dst d.edge := by + cases d with + | mk e b => + cases b + · exact Or.inl rfl + · exact Or.inr rfl + +@[simp] theorem dartSign_symm (d : OrientedDart G) : dartSign d.symm = -dartSign d := by + cases d with | mk e b => cases b <;> norm_num [dartSign,OrientedDart.symm] + +end Paper170Geometry + +end +end + +section + +/-! Support reduction spans the real kernel of the graph boundary map by simple cycles. -/ +noncomputable section +open scoped BigOperators Classical +namespace Paper170 +variable {V E : Type} [Fintype E] (G : Graph V E) + +def boundaryLinear : (E → ℝ) →ₗ[ℝ] (V → ℝ) where + toFun z := boundary G z + map_add' z w := by + funext v + simp [boundary, add_mul, Finset.sum_add_distrib] + map_smul' a z := by + funext v + simp [boundary, mul_assoc, Finset.mul_sum] + +def chainSupport (z : E → ℝ) : Finset E := Finset.univ.filter fun e => z e≠0 + +theorem mem_chainSupport (z : E → ℝ) (e : E) : e∈chainSupport z ↔ z e≠0 := by + simp [chainSupport] + +theorem simple_cycles_balanced (z : E → ℝ) + (hz : z∈Submodule.span ℝ (Set.range (fun C : SimpleCycle G => C.edgeChain))) : + ∀v, boundary G z v=0 := by + have hle : Submodule.span ℝ (Set.range (fun C : SimpleCycle G => C.edgeChain)) ≤ + LinearMap.ker (boundaryLinear G) := by + rw [Submodule.span_le] + rintro _ ⟨C,rfl⟩ + exact funext C.boundary_edgeChain + exact fun v => congrFun (hle hz) v + +theorem simple_cycles_span_of_supported_cycle + (hex : ∀z : E → ℝ, (∀v, boundary G z v=0) → z≠0 → + ∃C : SimpleCycle G, ∀i, z (C.edge i)≠0) (z : E → ℝ) : + (∀v, boundary G z v=0) ↔ z∈Submodule.span ℝ (Set.range (fun C : SimpleCycle G => C.edgeChain)) := by + constructor + · intro hz + suffices h : ∀m (w : E → ℝ), (chainSupport w).card=m → (∀v, boundary G w v=0) → + w∈Submodule.span ℝ (Set.range (fun C : SimpleCycle G => C.edgeChain)) from + h _ z rfl hz + intro m + induction m using Nat.strong_induction_on with + | h m ih => + intro w hm hw + by_cases hw0 : w=0 + · simp [hw0] + obtain ⟨C,hC⟩ := hex w hw hw0 + let i : Fin C.length := ⟨0,by have := C.three_le; omega⟩ + let e := C.edge i + have hc : C.edgeChain e≠0 := C.edgeChain_at_edge_ne_zero i + let a := w e / C.edgeChain e + let w' := w-a • C.edgeChain + have hw' : ∀v, boundary G w' v=0 := by + have hmapw : boundaryLinear G w=0 := funext hw + have hmapC : boundaryLinear G C.edgeChain=0 := funext C.boundary_edgeChain + have hmap : boundaryLinear G w'=0 := by + simp only [w',map_sub,map_smul,hmapw,hmapC,smul_zero,sub_self] + exact fun v => congrFun hmap v + have he0 : w' e=0 := by + change w e-(w e/C.edgeChain e)*C.edgeChain e=0 + rw [div_mul_cancel₀ _ hc,sub_self] + have hsub : chainSupport w' ⊆ chainSupport w := by + intro f hf + rw [mem_chainSupport] at hf ⊢ + by_contra hwf + have hCf : C.edgeChain f=0 := by + by_contra hh + obtain ⟨j,hj⟩ := (C.edgeChain_support f).mp hh + exact hC j (hj ▸ hwf) + apply hf + change w f-a*C.edgeChain f=0 + rw [hwf,hCf,mul_zero,sub_self] + have hproper : chainSupport w' ⊂ chainSupport w := by + apply Finset.ssubset_iff_subset_ne.mpr + refine ⟨hsub,?_⟩ + intro heq + have hew : e∈chainSupport w := (mem_chainSupport w e).mpr (hC i) + rw [← heq,mem_chainSupport] at hew + exact hew he0 + have hcard : (chainSupport w').card C.edgeChain)) := + Submodule.subset_span ⟨C,rfl⟩ + have hsum := (Submodule.span ℝ (Set.range (fun C : SimpleCycle G => C.edgeChain))).add_mem + hind ((Submodule.span ℝ (Set.range (fun C : SimpleCycle G => C.edgeChain))).smul_mem a hchain) + simpa only [w',sub_add_cancel] using hsum + · exact simple_cycles_balanced G z + +end Paper170 + +end +end + +section + +noncomputable section +open scoped Classical +namespace Paper170 + +variable {V E : Type} [Fintype V] [Fintype E] (G : Graph V E) + +omit [Fintype V] in +lemma flow_period_three (z : E → ℝ) (hz : ∀ v, boundary G z v = 0) + (a : FlowVertex G z) (hp : 0 < Function.minimalPeriod (flowNext G z hz) a) : + 3 ≤ Function.minimalPeriod (flowNext G z hz) a := by + let f := flowNext G z hz + have hone : Function.minimalPeriod f a ≠ 1 := by + intro h + have heq : f a = a := by + simpa [h] using (Function.iterate_minimalPeriod (f := f) (x := a)) + have hs := flowEdge_spec G z hz a + change ((G.src (flowEdge G z hz a) = a.val ∧ G.dst (flowEdge G z hz a) = (f a).val ∧ 0 < z (flowEdge G z hz a)) ∨ + (G.dst (flowEdge G z hz a) = a.val ∧ G.src (flowEdge G z hz a) = (f a).val ∧ z (flowEdge G z hz a) < 0)) at hs + rw [heq] at hs + exact flowArc_irrefl G z a.val _ hs + have htwo : Function.minimalPeriod f a ≠ 2 := by + intro h + have heq : f (f a) = a := by + simpa [h, Function.iterate_succ_apply'] using + (Function.iterate_minimalPeriod (f := f) (x := a)) + have hs := flowEdge_spec G z hz (f a) + change ((G.src (flowEdge G z hz (f a)) = (f a).val ∧ G.dst (flowEdge G z hz (f a)) = (f (f a)).val ∧ 0 < z (flowEdge G z hz (f a))) ∨ + (G.dst (flowEdge G z hz (f a)) = (f a).val ∧ G.src (flowEdge G z hz (f a)) = (f (f a)).val ∧ z (flowEdge G z hz (f a)) < 0)) at hs + rw [heq] at hs + exact flowArc_not_reverse G z a.val (f a).val _ _ (flowEdge_spec G z hz a) hs + change 0 < Function.minimalPeriod f a at hp + change 3 ≤ Function.minimalPeriod f a + omega + +theorem exists_supported_simple_cycle (z : E → ℝ) (hz : ∀ v, boundary G z v = 0) + (hne : z ≠ 0) : ∃ C : SimpleCycle G, ∀ i, z (C.edge i) ≠ 0 := by + obtain ⟨e, he⟩ : ∃ e, z e ≠ 0 := by + by_contra! h + exact hne (funext h) + have hnonempty : Nonempty (FlowVertex G z) := by + rcases lt_or_gt_of_ne he with h | h + · exact ⟨⟨G.dst e, e, Or.inr ⟨rfl, h⟩⟩⟩ + · exact ⟨⟨G.src e, e, Or.inl ⟨rfl, h⟩⟩⟩ + let := hnonempty + let f := flowNext G z hz + obtain ⟨a, ha⟩ := exists_positive_period f + let n := Function.minimalPeriod f a + have hn : 3 ≤ n := flow_period_three G z hz a ha + have hstep (i : Fin n) : + f^[((i.val + 1) % n)] a = f (f^[i.val] a) := by + rw [Function.iterate_mod_minimalPeriod_eq] + exact Function.iterate_succ_apply' _ _ _ + let C : SimpleCycle G := + { length := n + three_le := hn + vertex := fun i => (f^[i.val] a).val + vertex_injective := by + intro i j hij + apply Fin.ext + exact Function.iterate_injOn_Iio_minimalPeriod i.isLt j.isLt (Subtype.ext hij) + edge := fun i => flowEdge G z hz (f^[i.val] a) + follows := by + intro i + change (G.src (flowEdge G z hz (f^[i.val] a)) = (f^[i.val] a).val ∧ + G.dst (flowEdge G z hz (f^[i.val] a)) = (f^[((i.val + 1) % n)] a).val) ∨ + (G.dst (flowEdge G z hz (f^[i.val] a)) = (f^[i.val] a).val ∧ + G.src (flowEdge G z hz (f^[i.val] a)) = (f^[((i.val + 1) % n)] a).val) + rw [hstep] + rcases flowEdge_spec G z hz (f^[i.val] a) with ⟨hs, hd, _⟩ | ⟨hd, hs, _⟩ + · exact Or.inl ⟨hs, hd⟩ + · exact Or.inr ⟨hd, hs⟩ } + refine ⟨C, ?_⟩ + intro i + rcases flowEdge_spec G z hz (f^[i.val] a) with ⟨_, _, hp⟩ | ⟨_, _, hn⟩ + · exact ne_of_gt hp + · exact ne_of_lt hn + +end Paper170 + +end +end + +section + +/-! A frozen simple cycle gives a periodic sequence of actual oriented edge traversals. -/ +noncomputable section +open scoped Classical +namespace Paper170.SimpleCycle +open Paper170Geometry +variable {V E : Type} {G : Graph V E} + +def dart (C : SimpleCycle G) (i : Fin C.length) : OrientedDart G := + ⟨C.edge i,decide (G.src (C.edge i)=C.vertex i)⟩ + +theorem dart_fst (C : SimpleCycle G) (i : Fin C.length) : (C.dart i).fst = C.vertex i := by + rcases C.follows_next i with h | h + · simp [dart,OrientedDart.fst,h.1] + · have hn : G.src (C.edge i) ≠ C.vertex i := by + rw [h.2] + exact fun he => C.next_ne_self i (C.vertex_injective he) + simp [dart,OrientedDart.fst,hn,h.1] + +theorem dart_snd (C : SimpleCycle G) (i : Fin C.length) : (C.dart i).snd = C.vertex (C.next i) := by + rcases C.follows_next i with h | h + · simp [dart,OrientedDart.snd,h.1,h.2] + · have hn : G.src (C.edge i) ≠ C.vertex i := by + rw [h.2] + exact fun he => C.next_ne_self i (C.vertex_injective he) + simpa only [dart,OrientedDart.snd,decide_eq_true_eq,ite_eq_right hn] using h.2 + +theorem dart_edge (C : SimpleCycle G) (i : Fin C.length) : (C.dart i).edge = C.edge i := rfl + +theorem dart_sign (C : SimpleCycle G) (i : Fin C.length) : + dartSign (C.dart i) = if G.src (C.edge i)=C.vertex i then 1 else -1 := by + simp [dart,dartSign] + +def modIndex (C : SimpleCycle G) (i : ℕ) : Fin C.length := + ⟨i % C.length,Nat.mod_lt _ (by have := C.three_le; omega)⟩ + +theorem modIndex_succ (C : SimpleCycle G) (i : ℕ) : C.modIndex (i+1)=C.next (C.modIndex i) := by + apply Fin.ext + simp [modIndex,next,Nat.add_mod] + +theorem modIndex_period (C : SimpleCycle G) : C.modIndex C.length=C.modIndex 0 := by + apply Fin.ext + simp [modIndex] + +def cyclicDart (C : SimpleCycle G) (i : ℕ) : OrientedDart G := C.dart (C.modIndex i) + +theorem cyclicDart_seam (C : SimpleCycle G) (i : ℕ) : + (C.cyclicDart i).snd = (C.cyclicDart (i+1)).fst := by + simp only [cyclicDart,dart_snd,dart_fst,modIndex_succ] + +theorem cyclicDart_period (C : SimpleCycle G) : C.cyclicDart C.length = C.cyclicDart 0 := by + rw [cyclicDart,cyclicDart,modIndex_period] + +theorem cyclicDart_next_edge_ne (C : SimpleCycle G) (i : ℕ) : + (C.cyclicDart (i+1)).edge ≠ (C.cyclicDart i).edge := by + simp only [cyclicDart,dart_edge,modIndex_succ] + exact fun he => C.next_ne_self _ (C.edge_injective he) + +end Paper170.SimpleCycle + +end +end + +section + +/-! The real cycle space of an arbitrary finite simple graph. -/ +noncomputable section +namespace Paper170 +variable {V E : Type} [Fintype V] [Fintype E] (G : Graph V E) + +theorem simple_cycles_span (z : E → ℝ) : + (∀v, boundary G z v=0) ↔ + z∈Submodule.span ℝ (Set.range (fun C : SimpleCycle G => C.edgeChain)) := + simple_cycles_span_of_supported_cycle G (exists_supported_simple_cycle G) z + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/DartPaths.lean b/lean/OAI/Combinatorics/CompleteCrossing/DartPaths.lean new file mode 100644 index 0000000000000000000000000000000000000000..5418448626249757d0800a7cac25d39cc4239e7c --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/DartPaths.lean @@ -0,0 +1,363 @@ +import OAI.Combinatorics.CompleteCrossing.CycleSpace +import OAI.Combinatorics.CompleteCrossing.Tracks +import OAI.Combinatorics.Crossing.FinitePolygonalComposition +import OAI.Combinatorics.Crossing.PolygonalEndpointCasts + +namespace OAI + +/-! Drawn-edge chains, dart-path realizations, and endpoint-flag pairing. -/ + +section + +/-! Incident flags of an oriented traversal in an arbitrary finite simple graph. -/ +noncomputable section +namespace Paper170Geometry +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +instance [Fintype Edge] : Fintype (OrientedDart graph) := + Fintype.ofEquiv (Edge × Bool) + { toFun := fun p => ⟨p.1,p.2⟩ + invFun := fun d => (d.edge,d.forward) + left_inv := fun _ => rfl + right_inv := fun _ => rfl } + +def dartSourceIncident (d : OrientedDart graph) : IncidentEdges graph d.fst := + ⟨d.edge,dart_source_incident d⟩ + +def dartTargetIncident (d : OrientedDart graph) : IncidentEdges graph d.snd := + ⟨d.edge,dart_target_incident d⟩ + +@[simp] theorem OrientedDart.symm_edge (d : OrientedDart graph) : d.symm.edge = d.edge := rfl + +end Paper170Geometry + +end +end + +section + +/-! Actual edge paths between vertex circles, and actual shifted paths with both exterior connectors. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry +namespace VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +def trackChain (e : Edge) : PolygonalChain Set.univ (V.startPort e) (V.endPort e) where + pieces := V.pieces e + vertices := V.vertices e + first := V.vertices_first e + last := V.vertices_last e + start_mem := Set.mem_univ _ + inside := fun _ _ => Set.subset_univ _ + +def chordChain (j : Vertex) (a b : IncidentEdges graph j) : + PolygonalChain Set.univ (V.spokePort j a) (V.spokePort j b) := + PolygonalChain.single Set.univ _ _ (Set.mem_univ _) (Set.subset_univ _) + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +def shiftedTrackChain (e : Edge) (ε : ℝ) : + PolygonalChain Set.univ (C.tangentPort ((graph.src e)) (V.leftIncident e) ε) + (C.tangentPort ((graph.dst e)) (V.rightIncident e) ε) where + pieces := V.pieces e + vertices := shiftedTrack (V.vertices e) (V.pieces e) ε + first := V.shiftedTrack_first C e ε + last := V.shiftedTrack_last C e ε + start_mem := Set.mem_univ _ + inside := fun _ _ => Set.subset_univ _ + +def connectorChain (j : Vertex) (e : IncidentEdges graph j) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedPort j e ε) (C.tangentPort j e ε) := + PolygonalChain.single Set.univ _ _ (Set.mem_univ _) (Set.subset_univ _) + +def shiftedEdgeChain (e : Edge) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedPort ((graph.src e)) (V.leftIncident e) ε) + (C.shiftedPort ((graph.dst e)) (V.rightIncident e) ε) := + ((C.connectorChain ((graph.src e)) (V.leftIncident e) ε).join (C.shiftedTrackChain e ε)).join + (C.connectorChain ((graph.dst e)) (V.rightIncident e) ε).reverse + +def shiftedChordChain (j : Vertex) (a b : IncidentEdges graph j) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedPort j a ε) (C.shiftedPort j b ε) := + PolygonalChain.single Set.univ _ _ (Set.mem_univ _) (Set.subset_univ _) + +theorem shiftedEdgeChain_pieces (e : Edge) (ε : ℝ) : + (C.shiftedEdgeChain e ε).pieces=V.pieces e+2 := by + simp only [shiftedEdgeChain,PolygonalChain.pieces_join,connectorChain, + PolygonalChain.pieces_single,shiftedTrackChain,PolygonalChain.reverse] + omega + +theorem shiftedEdgeChain_intersection_right (e : Edge) (ε : ℝ) + (w : ℕ → Plane) (k : ℕ) : + polygonIntersection w (C.shiftedEdgeChain e ε).vertices k (C.shiftedEdgeChain e ε).pieces = + polygonIntersection w (C.connectorChain ((graph.src e)) (V.leftIncident e) ε).vertices k 1 + + polygonIntersection w (shiftedTrack (V.vertices e) (V.pieces e) ε) k (V.pieces e) - + polygonIntersection w (C.connectorChain ((graph.dst e)) (V.rightIncident e) ε).vertices k 1 := by + unfold shiftedEdgeChain + rw [PolygonalChain.intersection_join_right,PolygonalChain.intersection_join_right, + PolygonalChain.intersection_reverse_right] + rfl + +end TruncatedSpokeCoordinates +end Paper170Geometry + +end +end + +section + +/-! Actual polygonal realizations of the two orientations of every graph edge. -/ +noncomputable section +open Zarankiewicz +namespace Paper170Geometry +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +def dartTrackChain (d : OrientedDart graph) : + PolygonalChain Set.univ (V.spokePort d.fst (dartSourceIncident d)) + (V.spokePort d.snd (dartTargetIncident d)) := by + rcases d with ⟨e,b⟩ + cases b + · exact (V.trackChain e).reverse.castEndpoints + (by simp [spokePort,drawingSpokePort,dartSourceIncident,OrientedDart.fst, + endPort,(graph.loopless e).symm]) + (by simp [spokePort,drawingSpokePort,dartTargetIncident,OrientedDart.snd,startPort]) + · exact (V.trackChain e).castEndpoints + (by simp [spokePort,drawingSpokePort,dartSourceIncident,OrientedDart.fst,startPort]) + (by simp [spokePort,drawingSpokePort,dartTargetIncident,OrientedDart.snd, + endPort,(graph.loopless e).symm]) + +theorem dartTrackChain_forward_vertices (e : Edge) : + (V.dartTrackChain (forwardDart graph e)).vertices = V.vertices e := rfl + +theorem dartTrackChain_backward_vertices (e : Edge) : + (V.dartTrackChain (backwardDart graph e)).vertices = + reversedSequence (V.vertices e) (V.pieces e) := rfl + +theorem dartTrackChain_pieces (d : OrientedDart graph) : + (V.dartTrackChain d).pieces = V.pieces d.edge := by + rcases orientedDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ <;> rfl + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +def shiftedDartChain (d : OrientedDart graph) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedPort d.fst (dartSourceIncident d) ε) + (C.shiftedPort d.snd (dartTargetIncident d) ε) := by + rcases d with ⟨e,b⟩ + cases b + · exact (C.shiftedEdgeChain e ε).reverse.castEndpoints rfl rfl + · exact (C.shiftedEdgeChain e ε).castEndpoints rfl rfl + +theorem shiftedDartChain_forward_vertices (e : Edge) (ε : ℝ) : + (C.shiftedDartChain (forwardDart graph e) ε).vertices = (C.shiftedEdgeChain e ε).vertices := rfl + +theorem shiftedDartChain_backward_vertices (e : Edge) (ε : ℝ) : + (C.shiftedDartChain (backwardDart graph e) ε).vertices = + reversedSequence (C.shiftedEdgeChain e ε).vertices (C.shiftedEdgeChain e ε).pieces := rfl + +theorem shiftedDartChain_pieces (d : OrientedDart graph) (ε : ℝ) : + (C.shiftedDartChain d ε).pieces = (C.shiftedEdgeChain d.edge ε).pieces := by + rcases orientedDart_cases d with ⟨e,rfl⟩ | ⟨e,rfl⟩ <;> rfl + +end TruncatedSpokeCoordinates +end Paper170Geometry + +end +end + +section + +/-! Actual closed polygonal realizations of cyclic graph darts, with a chord at every vertex passage. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry + +def incidentCast {j k : Vertex} (h : j=k) (e : IncidentEdges graph j) : IncidentEdges graph k := + ⟨e.val,by simpa only [← h] using e.property⟩ + +theorem incidentCast_val {j k : Vertex} (h : j=k) (e : IncidentEdges graph j) : + (incidentCast h e).val=e.val := rfl + +def dartPassageNext (d : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (i : ℕ) : IncidentEdges graph (d i).snd := + incidentCast (hd i).symm (dartSourceIncident (d (i+1))) + +theorem dartPassage_ne (d : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (i : ℕ) + (hne : OrientedDart.edge (d (i+1)) ≠ OrientedDart.edge (d i)) : + dartTargetIncident (d i) ≠ dartPassageNext d hd i := by + intro he + exact hne (congrArg Subtype.val he).symm + +namespace VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +theorem spokePort_cast {j k : Vertex} (h : j=k) (e : IncidentEdges graph j) : + V.spokePort k (incidentCast h e)=V.spokePort j e := by subst k; rfl + +def dartCycleVertex (d : ℕ → OrientedDart graph) (i : ℕ) : Plane := + V.spokePort (d i).fst (dartSourceIncident (d i)) + +def dartCycleBlock (d : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (i : ℕ) : + PolygonalChain Set.univ (V.dartCycleVertex d i) (V.dartCycleVertex d (i+1)) := + ((V.dartTrackChain (d i)).join + (V.chordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i))).castEndpoints + rfl (V.spokePort_cast (hd i).symm _).symm + +def dartCycleChain (d : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (N : ℕ) (hN : d N=d 0) : + PolygonalChain Set.univ (V.dartCycleVertex d 0) (V.dartCycleVertex d 0) := + (finitePolygonalChain Set.univ (V.dartCycleVertex d) (Set.mem_univ _) (V.dartCycleBlock d hd) N).castEndpoints + rfl (congrArg (fun a : OrientedDart graph => V.spokePort a.fst (dartSourceIncident a)) hN.symm) + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} (C : TruncatedSpokeCoordinates V) + +theorem shiftedPort_cast {j k : Vertex} (h : j=k) (e : IncidentEdges graph j) (ε : ℝ) : + C.shiftedPort k (incidentCast h e) ε=C.shiftedPort j e ε := by subst k; rfl + +def shiftedCycleVertex (d : ℕ → OrientedDart graph) (ε : ℝ) (i : ℕ) : Plane := + C.shiftedPort (d i).fst (dartSourceIncident (d i)) ε + +def shiftedCycleBlock (d : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (ε : ℝ) (i : ℕ) : + PolygonalChain Set.univ (C.shiftedCycleVertex d ε i) (C.shiftedCycleVertex d ε (i+1)) := + ((C.shiftedDartChain (d i) ε).join + (C.shiftedChordChain (d i).snd (dartTargetIncident (d i)) (dartPassageNext d hd i) ε)).castEndpoints + rfl (C.shiftedPort_cast (hd i).symm _ ε).symm + +def shiftedCycleChain (d : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (N : ℕ) (hN : d N=d 0) (ε : ℝ) : + PolygonalChain Set.univ (C.shiftedCycleVertex d ε 0) (C.shiftedCycleVertex d ε 0) := + (finitePolygonalChain Set.univ (C.shiftedCycleVertex d ε) (Set.mem_univ _) (C.shiftedCycleBlock d hd ε) N).castEndpoints + rfl (congrArg (fun a : OrientedDart graph => C.shiftedPort a.fst (dartSourceIncident a) ε) hN.symm) + +end TruncatedSpokeCoordinates +end Paper170Geometry + +end +end + +section + +/-! Endpoint pairings at actual vertex-circle passages. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +def vertexChordPairing (j k : Vertex) (a b : IncidentEdges graph j) (c d : IncidentEdges graph k) : ℝ := + if h : k=j then chordEndpointPairing (C.node j a) (C.node j b) + (C.node j (incidentCast h c)) (C.node j (incidentCast h d)) else 0 + +def passagePairing (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) + (i j : ℕ) : ℝ := + C.vertexChordPairing (d i).snd (f j).snd (dartTargetIncident (d i)) (dartPassageNext d hd i) + (dartTargetIncident (f j)) (dartPassageNext f hf j) + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Fixed vertex half-order kernels on actual incident edge flags. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +namespace Paper170Geometry +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +abbrev IncidentFlag (graph : Paper170.Graph Vertex Edge) := (j : Vertex) × IncidentEdges graph j + +def dartSourceFlag (d : OrientedDart graph) : IncidentFlag graph := + ⟨d.fst,dartSourceIncident d⟩ + +def dartTargetFlag (d : OrientedDart graph) : IncidentFlag graph := + ⟨d.snd,dartTargetIncident d⟩ + +theorem incidentCast_refl {j : Vertex} (e : IncidentEdges graph j) : + incidentCast (rfl : j=j) e=e := Subtype.ext rfl + +theorem incidentFlag_cast {j k : Vertex} (h : j=k) (e : IncidentEdges graph j) : + (⟨k,incidentCast h e⟩ : IncidentFlag graph)=⟨j,e⟩ := by + subst k + rw [incidentCast_refl] + +theorem dartPassageNext_flag (d : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (i : ℕ) : + (⟨(d i).snd,dartPassageNext d hd i⟩ : IncidentFlag graph)=dartSourceFlag (d (i+1)) := + incidentFlag_cast (hd i).symm _ + +namespace TruncatedSpokeCoordinates +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +def flagPairing (a b : IncidentFlag graph) : ℝ := + if h : b.1=a.1 then orderSign (C.node a.1 a.2) (C.node a.1 (incidentCast h b.2))/2 else 0 + +theorem vertexChordPairing_flags (j k : Vertex) + (a b : IncidentEdges graph j) (c d : IncidentEdges graph k) : + C.vertexChordPairing j k a b c d= + C.flagPairing ⟨j,a⟩ ⟨k,c⟩-C.flagPairing ⟨j,a⟩ ⟨k,d⟩- + C.flagPairing ⟨j,b⟩ ⟨k,c⟩+C.flagPairing ⟨j,b⟩ ⟨k,d⟩ := by + by_cases h : k=j + · subst k + simp only [vertexChordPairing,flagPairing,dite_eq_left rfl,incidentCast_refl,chordEndpointPairing,dite_true] + ring + · simp only [vertexChordPairing,flagPairing,dite_eq_right h,sub_zero,add_zero] + +theorem passagePairing_flags (d f : ℕ → OrientedDart graph) + (hd : ∀ i, (d i).snd=(d (i+1)).fst) (hf : ∀ j, (f j).snd=(f (j+1)).fst) (i j : ℕ) : + C.passagePairing d f hd hf i j= + C.flagPairing (dartTargetFlag (d i)) (dartTargetFlag (f j))- + C.flagPairing (dartTargetFlag (d i)) (dartSourceFlag (f (j+1)))- + C.flagPairing (dartSourceFlag (d (i+1))) (dartTargetFlag (f j))+ + C.flagPairing (dartSourceFlag (d (i+1))) (dartSourceFlag (f (j+1))) := by + rw [passagePairing,C.vertexChordPairing_flags,dartPassageNext_flag,dartPassageNext_flag] + rfl + +def edgeEndpointPairing (e f : Edge) : ℝ := + C.flagPairing (dartTargetFlag (forwardDart graph e)) (dartTargetFlag (forwardDart graph f))- + C.flagPairing (dartTargetFlag (forwardDart graph e)) (dartSourceFlag (forwardDart graph f))- + C.flagPairing (dartSourceFlag (forwardDart graph e)) (dartTargetFlag (forwardDart graph f))+ + C.flagPairing (dartSourceFlag (forwardDart graph e)) (dartSourceFlag (forwardDart graph f)) + +theorem dart_endpoint_pairing (a b : OrientedDart graph) : + C.flagPairing (dartTargetFlag a) (dartTargetFlag b)- + C.flagPairing (dartTargetFlag a) (dartSourceFlag b)- + C.flagPairing (dartSourceFlag a) (dartTargetFlag b)+ + C.flagPairing (dartSourceFlag a) (dartSourceFlag b)= + dartSign a*dartSign b*C.edgeEndpointPairing a.edge b.edge := by + rcases a with ⟨e,a⟩ + rcases b with ⟨f,b⟩ + cases a <;> cases b <;> + simp [dartSign,edgeEndpointPairing,forwardDart,dartSourceFlag,dartTargetFlag, + dartSourceIncident,dartTargetIncident,OrientedDart.fst,OrientedDart.snd] + all_goals ring + +end TruncatedSpokeCoordinates +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Deletion.lean b/lean/OAI/Combinatorics/CompleteCrossing/Deletion.lean new file mode 100644 index 0000000000000000000000000000000000000000..eafb2a3ebd7e78b43ea5872beacb2f299c9959e0 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Deletion.lean @@ -0,0 +1,252 @@ +import OAI.Combinatorics.CompleteCrossing.Drawing +import Mathlib.Order.Fin.Basic +import Mathlib.Tactic + +namespace OAI + +/-! Vertex deletion, its crossing-count identity, and small complete graphs. -/ + +section + +/-! Source-faithful restriction of an actual complete-graph drawing by one vertex. -/ +noncomputable section +namespace Paper170 + +structure VertexDeletion {n : ℕ} (D : AdmissibleDrawing (completeGraph (n + 1))) + (v : Fin (n + 1)) (A : AdmissibleDrawing (completeGraph n)) : Prop where + vertex_eq : ∀ i, A.vertex i = D.vertex (v.succAbove i) + edge_eq : ∀ (e : CompleteEdge n) (f : CompleteEdge (n + 1)), + f.val.1 = v.succAbove e.val.1 → f.val.2 = v.succAbove e.val.2 → + ∀ t, A.edge e t = D.edge f t + +end Paper170 + +end +end + +section + +noncomputable section +open scoped Classical +namespace Paper170 + +lemma crossingCount_zero_of_subsingleton {V E : Type} [Subsingleton E] {G : Graph V E} + (D : AdmissibleDrawing G) : crossingCount D = 0 := by + have h : crossingPoints D.toContinuousDrawing = ∅ := by + ext x + constructor + · rintro ⟨e, f, hef, _, _⟩ + exact (hef (Subsingleton.elim e f)).elim + · simp + simp [crossingCount, h] + +lemma ordinaryCrossingNumber_zero_of_subsingleton {V E : Type} [Subsingleton E] + (G : Graph V E) : ordinaryCrossingNumber G = 0 := by + by_cases h : (Set.range (@crossingCount V E G)).Nonempty + · obtain ⟨_, D, rfl⟩ := h + apply Nat.eq_zero_of_le_zero + rw [← crossingCount_zero_of_subsingleton D] + exact Paper170Geometry.ordinaryCrossingNumber_le_count D + · simp [ordinaryCrossingNumber, Set.not_nonempty_iff_eq_empty.mp h] + +theorem complete_graph_small_orders : + ordinaryCrossingNumber (completeGraph 1) = 0 ∧ + ordinaryCrossingNumber (completeGraph 2) = 0 := by + constructor + · have : Subsingleton (CompleteEdge 1) := ⟨fun e f => by + have := e.property + have h1 := e.val.1.isLt + have h2 := e.val.2.isLt + omega⟩ + exact ordinaryCrossingNumber_zero_of_subsingleton _ + · have : Subsingleton (CompleteEdge 2) := ⟨fun e f => by + apply Subtype.ext + apply Prod.ext <;> apply Fin.ext + all_goals + have he := e.property + have hf := f.property + have he1 := e.val.1.isLt + have he2 := e.val.2.isLt + have hf1 := f.val.1.isLt + have hf2 := f.val.2.isLt + omega⟩ + exact ordinaryCrossingNumber_zero_of_subsingleton _ + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped BigOperators Classical +namespace Paper170 + +def deletionEdge {n : ℕ} (v : Fin (n + 1)) (e : CompleteEdge n) : CompleteEdge (n + 1) := + ⟨(v.succAbove e.val.1, v.succAbove e.val.2), Fin.strictMono_succAbove v e.property⟩ + +lemma deletionEdge_injective {n : ℕ} (v : Fin (n + 1)) : + Function.Injective (deletionEdge v) := by + intro e f h + apply Subtype.ext + apply Prod.ext + · exact Fin.succAbove_right_injective (congrArg (fun a => a.val.1) h) + · exact Fin.succAbove_right_injective (congrArg (fun a => a.val.2) h) + +lemma deletionEdge_range {n : ℕ} (v : Fin (n + 1)) (e : CompleteEdge (n + 1)) : + (∃ f, deletionEdge v f = e) ↔ e.val.1 ≠ v ∧ e.val.2 ≠ v := by + constructor + · rintro ⟨f, rfl⟩ + exact ⟨Fin.succAbove_ne v _, Fin.succAbove_ne v _⟩ + · rintro ⟨h1, h2⟩ + obtain ⟨a, ha⟩ := Fin.exists_succAbove_eq h1 + obtain ⟨b, hb⟩ := Fin.exists_succAbove_eq h2 + have hab : a < b := (Fin.strictMono_succAbove v).lt_iff_lt.mp (by + rw [ha, hb] + exact e.property) + exact ⟨⟨(a,b), hab⟩, Subtype.ext (Prod.ext ha hb)⟩ + +def deleteContinuousDrawing {n : ℕ} (D : ContinuousDrawing (completeGraph (n + 1))) + (v : Fin (n + 1)) : ContinuousDrawing (completeGraph n) where + vertex i := D.vertex (v.succAbove i) + vertex_injective := D.vertex_injective.comp Fin.succAbove_right_injective + edge e := D.edge (deletionEdge v e) + edge_injective e := D.edge_injective (deletionEdge v e) + interior_avoids_vertices e t ht i := + D.interior_avoids_vertices (deletionEdge v e) t ht (v.succAbove i) + +lemma deletion_crossings_subset {n : ℕ} (D : ContinuousDrawing (completeGraph (n + 1))) + (v : Fin (n + 1)) : crossingPoints (deleteContinuousDrawing D v) ⊆ crossingPoints D := by + rintro x ⟨e, f, hef, he, hf⟩ + exact ⟨deletionEdge v e, deletionEdge v f, + fun h => hef (deletionEdge_injective v h), he, hf⟩ + +def deleteDrawing {n : ℕ} (D : AdmissibleDrawing (completeGraph (n + 1))) + (v : Fin (n + 1)) : AdmissibleDrawing (completeGraph n) where + toContinuousDrawing := deleteContinuousDrawing D.toContinuousDrawing v + crossings_finite := D.crossings_finite.subset (deletion_crossings_subset _ v) + crossings_proper e f hef x he hf := D.crossings_proper (deletionEdge v e) (deletionEdge v f) + (fun h => hef (deletionEdge_injective v h)) x he hf + no_triples e f g hef heg hfg := D.no_triples (deletionEdge v e) (deletionEdge v f) + (deletionEdge v g) (fun h => hef (deletionEdge_injective v h)) + (fun h => heg (deletionEdge_injective v h)) (fun h => hfg (deletionEdge_injective v h)) + +lemma deleteDrawing_spec {n : ℕ} (D : AdmissibleDrawing (completeGraph (n + 1))) + (v : Fin (n + 1)) : VertexDeletion D v (deleteDrawing D v) := by + refine ⟨fun _ => rfl, ?_⟩ + intro e f h1 h2 t + have h : f = deletionEdge v e := Subtype.ext (Prod.ext h1 h2) + subst f + rfl + +lemma deletion_crossing_iff {n : ℕ} (D : AdmissibleDrawing (completeGraph (n + 1))) + (v : Fin (n + 1)) (x : Plane) (e f : CompleteEdge (n + 1)) (hef : e ≠ f) + (he : x ∈ edgeInterior D.toContinuousDrawing e) + (hf : x ∈ edgeInterior D.toContinuousDrawing f) : + x ∈ crossingPoints (deleteDrawing D v).toContinuousDrawing ↔ + e.val.1 ≠ v ∧ e.val.2 ≠ v ∧ f.val.1 ≠ v ∧ f.val.2 ≠ v := by + constructor + · rintro ⟨a, b, hab, ha, hb⟩ + have ha' := (Paper170Geometry.crossing_incident_iff D x e f hef he hf + (deletionEdge v a)).mp ha + have hb' := (Paper170Geometry.crossing_incident_iff D x e f hef he hf + (deletionEdge v b)).mp hb + have hab' : deletionEdge v a ≠ deletionEdge v b := + fun h => hab (deletionEdge_injective v h) + have hae := (deletionEdge_range v (deletionEdge v a)).mp ⟨a, rfl⟩ + have hbe := (deletionEdge_range v (deletionEdge v b)).mp ⟨b, rfl⟩ + rcases ha' with ha' | ha' <;> rcases hb' with hb' | hb' + · exact (hab' (ha'.trans hb'.symm)).elim + · simpa [ha', hb', and_assoc] using And.intro hae hbe + · simpa [ha', hb', and_assoc] using And.intro hbe hae + · exact (hab' (ha'.trans hb'.symm)).elim + · rintro ⟨he1, he2, hf1, hf2⟩ + obtain ⟨a, ha⟩ := (deletionEdge_range v e).mpr ⟨he1, he2⟩ + obtain ⟨b, hb⟩ := (deletionEdge_range v f).mpr ⟨hf1, hf2⟩ + refine ⟨a, b, ?_, ?_, ?_⟩ + · intro h + exact hef (ha.symm.trans ((congrArg (deletionEdge v) h).trans hb)) + · change x ∈ edgeInterior D.toContinuousDrawing (deletionEdge v a) + simpa [ha] using he + · change x ∈ edgeInterior D.toContinuousDrawing (deletionEdge v b) + simpa [hb] using hf + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped BigOperators Classical +namespace Paper170 + +lemma crossing_endpoints_distinct {n : ℕ} (N : NormalizedDrawing (completeGraph n)) + (x : Plane) (e f : CompleteEdge n) (hef : e ≠ f) + (he : x ∈ edgeInterior N.toContinuousDrawing e) + (hf : x ∈ edgeInterior N.toContinuousDrawing f) : + e.val.1 ≠ f.val.1 ∧ e.val.1 ≠ f.val.2 ∧ e.val.2 ≠ f.val.1 ∧ e.val.2 ≠ f.val.2 := by + have hn : ¬ (e.val.1 = f.val.1 ∨ e.val.1 = f.val.2 ∨ + e.val.2 = f.val.1 ∨ e.val.2 = f.val.2) := by + intro h + exact Set.disjoint_left.mp (N.no_adjacent e f hef h) he hf + tauto + +lemma deletion_survivor_card {n : ℕ} (N : NormalizedDrawing (completeGraph (n + 1))) + (x : Plane) (hx : x ∈ crossingPoints N.toContinuousDrawing) : + (Finset.univ.filter (fun v : Fin (n + 1) => + x ∈ crossingPoints (deleteDrawing N.toAdmissibleDrawing v).toContinuousDrawing)).card = + n + 1 - 4 := by + obtain ⟨e, f, hef, he, hf⟩ := hx + rcases crossing_endpoints_distinct N x e f hef he hf with ⟨h13, h14, h23, h24⟩ + have h12 : e.val.1 ≠ e.val.2 := ne_of_lt e.property + have h34 : f.val.1 ≠ f.val.2 := ne_of_lt f.property + simp_rw [deletion_crossing_iff N.toAdmissibleDrawing _ x e f hef he hf] + have hset : Finset.univ.filter (fun v : Fin (n + 1) => + e.val.1 ≠ v ∧ e.val.2 ≠ v ∧ f.val.1 ≠ v ∧ f.val.2 ≠ v) = + Finset.univ \ {e.val.1, e.val.2, f.val.1, f.val.2} := by + ext v + simp [eq_comm] + rw [hset, Finset.card_sdiff_of_subset (Finset.subset_univ _)] + simp [h12, h13, h14, h23, h24, h34] + +lemma deleteDrawing_count_filter {n : ℕ} (D : AdmissibleDrawing (completeGraph (n + 1))) + (v : Fin (n + 1)) : + crossingCount (deleteDrawing D v) = (D.crossings_finite.toFinset.filter fun x => + x ∈ crossingPoints (deleteDrawing D v).toContinuousDrawing).card := by + unfold crossingCount + congr 1 + ext x + simp only [Set.Finite.mem_toFinset, Finset.mem_filter] + exact ⟨fun h => ⟨deletion_crossings_subset D.toContinuousDrawing v h, h⟩, And.right⟩ + +theorem vertex_deletion_count (n : ℕ) (_hn : 4 ≤ n) + (N : NormalizedDrawing (completeGraph (n + 1))) : + ∃ A : Fin (n + 1) → AdmissibleDrawing (completeGraph n), + (∀ v, VertexDeletion N.toAdmissibleDrawing v (A v)) ∧ + (∑ v, crossingCount (A v)) = (n + 1 - 4) * crossingCount N.toAdmissibleDrawing := by + refine ⟨deleteDrawing N.toAdmissibleDrawing, deleteDrawing_spec N.toAdmissibleDrawing, ?_⟩ + simp_rw [deleteDrawing_count_filter, Finset.card_filter] + rw [Finset.sum_comm] + calc + (∑ x ∈ N.crossings_finite.toFinset, + ∑ v : Fin (n + 1), if x ∈ crossingPoints + (deleteDrawing N.toAdmissibleDrawing v).toContinuousDrawing then 1 else 0) = + ∑ _x ∈ N.crossings_finite.toFinset, (n + 1 - 4) := by + apply Finset.sum_congr rfl + intro x hx + simpa only [Finset.card_filter] using + deletion_survivor_card N x (by simpa using hx) + _ = (n + 1 - 4) * crossingCount N.toAdmissibleDrawing := by + simp [crossingCount, Nat.mul_comm] + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/DiskChords.lean b/lean/OAI/Combinatorics/CompleteCrossing/DiskChords.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3a115cfb524d9a94c56063b84d0d995a8421808 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/DiskChords.lean @@ -0,0 +1,457 @@ +import OAI.Combinatorics.CompleteCrossing.DiskFilling +import OAI.Combinatorics.Crossing.AlternatingPaths +import OAI.Combinatorics.Crossing.SimultaneousExteriorArcs + +namespace OAI + +/-! Exterior polygonal replacement, ordered passages, and injective middle paths. -/ + +section + +/-! Appendix A's exterior replacement, derived from the actual admissible drawing. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +theorem drawing_exterior_polygonal_replacement [Fintype Vertex] [Fintype Edge] (D : FiniteIntersectionDrawing graph) : + ∃ C : DrawingPassages D, ∃ U : C.ArcIndex → Set Plane, + ∃ P : ∀ i, PolygonalChain (U i) (C.arcStart i) (C.arcEnd i), + (∀ i, IsOpen (U i)) ∧ (∀ i, Function.Injective (P i).path) ∧ + (∀ i t, t ∈ Set.Ioo (0 : unitInterval) 1 → + (P i).path t ∈ outsideDisks (fun x : DrawingMark D => x.val) C.radius) ∧ + (∀ i j, i ≠ j → Disjoint (Set.range (P i).path) (Set.range (P j).path)) := by + classical + obtain ⟨C⟩ := nonempty_drawingPassages D + let : Fintype (DrawingMark D) := (drawingMarks_finite D).fintype + obtain ⟨U,P,hU,hP,hout,hdisjoint⟩ := finite_exterior_arc_replacements + (fun x : DrawingMark D => x.val) C.radius C.radius_pos C.disks_disjoint + C.arcStartMark C.arcEndMark C.arcStart C.arcEnd C.arc_endpoints_ne + C.arc_start_on_circle C.arc_end_on_circle C.arc C.arcs_pairwise_disjoint C.arc_interior_outside + exact ⟨C,U,P,hU,hP,hout,hdisjoint⟩ + +end Paper170Geometry + +end +end + +section + +/-! Constructed polygonal exterior paths, packaged with their actual geometric properties. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D : FiniteIntersectionDrawing graph} + +structure PolygonalExterior (C : DrawingPassages D) where + chain : ∀ i : C.ArcIndex, PolygonalChain Set.univ (C.arcStart i) (C.arcEnd i) + injective : ∀ i, Function.Injective (chain i).path + outside : ∀ i t, t ∈ Set.Ioo (0 : unitInterval) 1 → + (chain i).path t ∈ outsideDisks (fun x : DrawingMark D => x.val) C.radius + disjoint : ∀ i j, i ≠ j → Disjoint (Set.range (chain i).path) (Set.range (chain j).path) + +theorem nonempty_polygonalExterior [Fintype Vertex] [Fintype Edge] (C : DrawingPassages D) : Nonempty (PolygonalExterior C) := by + classical + let : Fintype (DrawingMark D) := (drawingMarks_finite D).fintype + obtain ⟨U,P,hU,hP,hout,hdisjoint⟩ := finite_exterior_arc_replacements + (fun x : DrawingMark D => x.val) C.radius C.radius_pos C.disks_disjoint + C.arcStartMark C.arcEndMark C.arcStart C.arcEnd C.arc_endpoints_ne + C.arc_start_on_circle C.arc_end_on_circle C.arc C.arcs_pairwise_disjoint C.arc_interior_outside + exact ⟨{ + chain := fun i => (P i).widen (Set.subset_univ _) + injective := hP + outside := hout + disjoint := hdisjoint }⟩ + +namespace PolygonalExterior +variable {C : DrawingPassages D} + +theorem outside_open_disks (E : PolygonalExterior C) (i : C.ArcIndex) (t : unitInterval) + (x : DrawingMark D) : C.radius^2 ≤ squaredLength ((E.chain i).path t-x.val) := by + by_cases ht0 : t=0 + · subst t + rw [(E.chain i).path.source] + exact C.portPoint_outside_open_disks (i,false) x + by_cases ht1 : t=1 + · subst t + rw [(E.chain i).path.target] + exact C.portPoint_outside_open_disks (i,true) x + exact (E.outside i t ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ x).le + +theorem avoids_new_vertices (E : PolygonalExterior C) (v : Vertex → Plane) + (hv : ∀ i, squaredLength (v i-D.vertex i) < C.radius^2) + (i : C.ArcIndex) (t : unitInterval) (j : Vertex) : (E.chain i).path t ≠ v j := by + intro he + have h := E.outside_open_disks i t (C.vertexMark j) + rw [he] at h + exact (hv j).not_ge h + +theorem parameter_endpoint_of_mem_disk (E : PolygonalExterior C) (i : C.ArcIndex) + (t : unitInterval) (x : DrawingMark D) + (ht : (E.chain i).path t ∈ closedRoundDisk x.val C.radius) : t=0 ∨ t=1 := by + by_cases h0 : t=0 + · exact Or.inl h0 + by_cases h1 : t=1 + · exact Or.inr h1 + have h := E.outside i t ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm h0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) h1⟩ x + exact False.elim (h.not_ge ht) + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! Exterior pieces and crossing chords meet only at their assigned endpoint joins. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem chord_parameter_endpoint (E : PolygonalExterior C) (i : C.ArcIndex) (p : C.InnerIndex) + (s t : unitInterval) (he : (E.chain i).path s=C.crossingChord p t) : t=0 ∨ t=1 := by + by_cases ht0 : t=0 + · exact Or.inl ht0 + by_cases ht1 : t=1 + · exact Or.inr ht1 + have h := C.crossingChord_interior_in_disk p t + ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ + have hx := E.outside_open_disks i s (C.innerMark p) + rw [he] at hx + exact False.elim (h.not_ge hx) + +theorem exterior_chord_meeting_parameters (E : PolygonalExterior C) (i : C.ArcIndex) (p : C.InnerIndex) + (s t : unitInterval) (he : (E.chain i).path s=C.crossingChord p t) : + (i=C.incomingArc p ∧ s=1 ∧ t=0) ∨ (i=C.outgoingArc p ∧ s=0 ∧ t=1) := by + have hs := E.parameter_endpoint_of_mem_disk i s (C.innerMark p) (by + rw [he] + exact C.crossingChord_range_subset_disk p ⟨t,rfl⟩) + have ht := E.chord_parameter_endpoint i p s t he + rcases hs with rfl | rfl <;> rcases ht with rfl | rfl + · simp only [Path.source] at he + have hp : (i,false)=C.incomingPort p := C.portPoint_injective he + have hh : false=true := congrArg Prod.snd hp + cases hh + · simp only [Path.source,Path.target] at he + have hp : (i,false)=C.outgoingPort p := C.portPoint_injective he + exact Or.inr ⟨congrArg Prod.fst hp,rfl,rfl⟩ + · simp only [Path.source,Path.target] at he + have hp : (i,true)=C.incomingPort p := C.portPoint_injective he + exact Or.inl ⟨congrArg Prod.fst hp,rfl,rfl⟩ + · simp only [Path.target] at he + have hp : (i,true)=C.outgoingPort p := C.portPoint_injective he + have hh : true=false := congrArg Prod.snd hp + cases hh + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Exterior paths meet vertex spokes only at their assigned boundary endpoints. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem exterior_spoke_meeting_parameters (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (i : C.ArcIndex) (j : Vertex) (p : C.PortsAt (C.vertexMark j)) + (s t : unitInterval) (he : (E.chain i).path s=(Path.segment (v j) (C.portPoint p.val)) t) : + t=1 ∧ ((s=0 ∧ (i,false)=p.val) ∨ (s=1 ∧ (i,true)=p.val)) := by + have ht : t=1 := by + apply le_antisymm (show t ≤ 1 from t.property.2) + apply le_of_not_gt + intro ht1 + have hinside := C.vertex_spoke_interior v hv j p t ht1 + have hout := E.outside_open_disks i s (C.vertexMark j) + rw [he] at hout + exact hinside.not_ge hout + subst t + rw [Path.target] at he + have hs := E.parameter_endpoint_of_mem_disk i s (C.vertexMark j) (by + rw [he] + exact (C.portsAt_on_circle (C.vertexMark j) p).le) + refine ⟨rfl,?_⟩ + rcases hs with rfl | rfl + · rw [Path.source] at he + exact Or.inl ⟨rfl,C.portPoint_injective he⟩ + · rw [Path.target] at he + exact Or.inr ⟨rfl,C.portPoint_injective he⟩ + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Ordered actual exterior paths and the internal chords of a fixed edge. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +def orderedArc (C : DrawingPassages D) (e : Edge) (i : ℕ) : C.ArcIndex := + ⟨e,⟨min i (C.count e-1),by have h := C.count_pos e; omega⟩⟩ + +theorem orderedArc_val (C : DrawingPassages D) (e : Edge) (i : ℕ) + (hi : i < C.count e) : (C.orderedArc e i).2.val=i := by + change min i (C.count e-1)=i + omega + +theorem orderedArc_inj (C : DrawingPassages D) (e : Edge) (i j : ℕ) + (hi : i < C.count e) (hj : j < C.count e) + (h : C.orderedArc e i=C.orderedArc e j) : i=j := by + have hh := congrArg (fun p : C.ArcIndex => p.2.val) h + simpa only [C.orderedArc_val e i hi,C.orderedArc_val e j hj] using hh + +theorem orderedArc_first (C : DrawingPassages D) (e : Edge) : + C.orderedArc e 0=C.firstArc e := by + simp [orderedArc,firstArc] + +theorem orderedArc_last (C : DrawingPassages D) (e : Edge) : + C.orderedArc e (C.count e-1)=C.lastArc e := by + simp [orderedArc,lastArc] + +def orderedInner (C : DrawingPassages D) (e : Edge) (j : ℕ) + (hj : j+1 < C.count e) : C.InnerIndex := + ⟨e,⟨⟨j+1,by omega⟩,⟨Nat.succ_pos j,hj⟩⟩⟩ + +theorem orderedInner_incoming (C : DrawingPassages D) (e : Edge) + (j : ℕ) (hj : j+1 < C.count e) : + C.incomingArc (C.orderedInner e j hj)=C.orderedArc e j := by + unfold incomingArc orderedInner orderedArc + congr 1 + apply Fin.ext + change j+1-1=min j (C.count e-1) + omega + +theorem orderedInner_outgoing (C : DrawingPassages D) (e : Edge) + (j : ℕ) (hj : j+1 < C.count e) : + C.outgoingArc (C.orderedInner e j hj)=C.orderedArc e (j+1) := by + unfold outgoingArc orderedInner orderedArc + congr 1 + apply Fin.ext + change j+1=min (j+1) (C.count e-1) + omega + +theorem orderedInner_inj (C : DrawingPassages D) (e : Edge) (i j : ℕ) + (hi : i+1 < C.count e) (hj : j+1 < C.count e) + (h : C.orderedInner e i hi=C.orderedInner e j hj) : i=j := by + have hh : i+1=j+1 := congrArg (fun p : C.InnerIndex => p.2.val.val) h + omega + +end DrawingPassages +namespace PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +def orderedPath (E : PolygonalExterior C) (e : Edge) (i : ℕ) : + Path (C.arcStart (C.orderedArc e i)) (C.arcEnd (C.orderedArc e i)) := + (E.chain (C.orderedArc e i)).path + +def orderedBridge (C : DrawingPassages D) (e : Edge) (i : ℕ) : + Path (C.arcEnd (C.orderedArc e i)) (C.arcStart (C.orderedArc e (i+1))) := Path.segment _ _ + +theorem orderedBridge_apply (e : Edge) (j : ℕ) (hj : j+1 < C.count e) + (t : unitInterval) : + orderedBridge C e j t=C.crossingChord (C.orderedInner e j hj) t := by + change (Path.segment _ _ : Path _ _) t=(Path.segment _ _ : Path _ _) t + have ha : C.portPoint (C.incomingPort (C.orderedInner e j hj))=C.arcEnd (C.orderedArc e j) := by + change C.arcEnd (C.incomingArc (C.orderedInner e j hj))=_ + rw [C.orderedInner_incoming] + have hb : C.portPoint (C.outgoingPort (C.orderedInner e j hj))=C.arcStart (C.orderedArc e (j+1)) := by + change C.arcStart (C.outgoingArc (C.orderedInner e j hj))=_ + rw [C.orderedInner_outgoing] + simp only [Path.segment_apply,ha,hb] + +theorem orderedBridge_range (e : Edge) (j : ℕ) (hj : j+1 < C.count e) : + Set.range (orderedBridge C e j)=Set.range (C.crossingChord (C.orderedInner e j hj)) := by + congr 1 + funext t + exact orderedBridge_apply e j hj t + +def middlePath (E : PolygonalExterior C) (e : Edge) : + Path (C.arcStart (C.orderedArc e 0)) (C.arcEnd (C.orderedArc e (C.count e-1))) := + alternatingPath (fun i => C.arcStart (C.orderedArc e i)) + (fun i => C.arcEnd (C.orderedArc e i)) (E.orderedPath e) (orderedBridge C e) (C.count e-1) + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! The actual ordered replacement of an edge between its first and last boundary ports is simple. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem middlePath_injective (E : PolygonalExterior C) (e : Edge) : + Function.Injective (E.middlePath e) := by + have hc := C.count_pos e + apply alternatingPath_injective + · intro i hi + exact E.injective _ + · intro j hj + have h := C.crossingChord_injective (C.orderedInner e j (by omega)) + intro s t he + apply h + simpa only [orderedBridge_apply (C:=C) e j (by omega)] using he + · intro i j hi hj hij + exact E.disjoint _ _ (fun he => hij (C.orderedArc_inj e i j (by omega) (by omega) he)) + · intro i j hi hj hij + rw [orderedBridge_range e i (by omega),orderedBridge_range e j (by omega)] + apply C.crossingChords_disjoint_of_marks_ne + intro he + apply hij + apply C.orderedInner_inj e i j + exact C.innerIndex_eq_of_edge_mark _ _ rfl he + · intro i j hi hj x hx hy + obtain ⟨s,hs⟩ := hx + obtain ⟨t,ht⟩ := hy + have hbridge := orderedBridge_apply (C:=C) e j (by omega) t + have hm := E.exterior_chord_meeting_parameters (C.orderedArc e i) + (C.orderedInner e j (by omega)) s t (hs.trans (ht.symm.trans hbridge)) + rcases hm with ⟨he,rfl,rfl⟩ | ⟨he,rfl,rfl⟩ + · rw [C.orderedInner_incoming] at he + have hij := C.orderedArc_inj e i j (by omega) (by omega) he + refine Or.inl ⟨hij,?_⟩ + subst i + exact hs.symm.trans (E.orderedPath e j).target + · rw [C.orderedInner_outgoing] at he + have hij := C.orderedArc_inj e i (j+1) (by omega) (by omega) he + refine Or.inr ⟨hij,?_⟩ + subst i + exact hs.symm.trans (E.orderedPath e (j+1)).source + +theorem middlePath_range_iff (E : PolygonalExterior C) (e : Edge) (x : Plane) : + x ∈ Set.range (E.middlePath e) ↔ + (∃ i : C.ArcIndex, i.1=e ∧ x ∈ Set.range (E.chain i).path) ∨ + (∃ p : C.InnerIndex, p.1=e ∧ x ∈ Set.range (C.crossingChord p)) := by + have hc := C.count_pos e + rw [middlePath,alternatingPath_range_iff] + constructor + · rintro (⟨i,hi,hx⟩ | ⟨j,hj,hx⟩) + · exact Or.inl ⟨C.orderedArc e i,rfl,hx⟩ + · exact Or.inr ⟨C.orderedInner e j (by omega),rfl, + by simpa only [orderedBridge_range (C:=C) e j (by omega)] using hx⟩ + · rintro (⟨⟨f,i⟩,he,hx⟩ | ⟨⟨f,⟨j,hj⟩⟩,he,hx⟩) + · change f=e at he + subst f + refine Or.inl ⟨i.val,by omega,?_⟩ + have heq : C.orderedArc e i.val=⟨e,i⟩ := by + unfold DrawingPassages.orderedArc + congr 1 + apply Fin.ext + change min i.val (C.count e-1)=i.val + omega + change x ∈ Set.range (E.chain (C.orderedArc e i.val)).path + rw [heq] + exact hx + · change f=e at he + subst f + refine Or.inr ⟨j.val-1,by omega,?_⟩ + rw [orderedBridge_range e (j.val-1) (by omega)] + have heq : C.orderedInner e (j.val-1) (by omega)=⟨e,⟨j,hj⟩⟩ := by + unfold DrawingPassages.orderedInner + congr 1 + apply Subtype.ext + apply Fin.ext + change j.val-1+1=j.val + omega + rw [heq] + exact hx + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! A constructed middle path meets a vertex spoke only at its boundary port. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +theorem vertex_spoke_range_in_disk (C : DrawingPassages D) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (j : Vertex) (p : C.PortsAt (C.vertexMark j)) : + Set.range (Path.segment (v j) (C.portPoint p.val)) ⊆ closedRoundDisk (D.vertex j) C.radius := by + rintro x ⟨t,rfl⟩ + by_cases ht : t=1 + · subst t + rw [Path.target] + exact (C.portsAt_on_circle (C.vertexMark j) p).le + · exact (C.vertex_spoke_interior v hv j p t + (lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht)).le + +theorem vertex_spokes_disjoint_of_vertices_ne (C : DrawingPassages D) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (j k : Vertex) (hjk : j ≠ k) + (p : C.PortsAt (C.vertexMark j)) (q : C.PortsAt (C.vertexMark k)) : + Disjoint (Set.range (Path.segment (v j) (C.portPoint p.val))) + (Set.range (Path.segment (v k) (C.portPoint q.val))) := + (C.disks_disjoint _ _ (C.vertexMark_injective.ne hjk)).mono + (C.vertex_spoke_range_in_disk v hv j p) (C.vertex_spoke_range_in_disk v hv k q) + +end DrawingPassages +namespace PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem middle_spoke_meeting (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : Edge) (j : Vertex) (p : C.PortsAt (C.vertexMark j)) + (x : Plane) (hx : x ∈ Set.range (E.middlePath e)) + (hy : x ∈ Set.range (Path.segment (v j) (C.portPoint p.val))) : x=C.portPoint p.val := by + rcases (E.middlePath_range_iff e x).mp hx with ⟨i,hi,⟨s,hs⟩⟩ | ⟨q,hq,hx⟩ + · obtain ⟨t,ht⟩ := hy + have he := E.exterior_spoke_meeting_parameters v hv i j p s t (hs.trans ht.symm) + rw [he.1,Path.target] at ht + exact ht.symm + · exact False.elim (Set.disjoint_left.mp (C.crossingChord_avoids_vertex_disks q j) + hx (C.vertex_spoke_range_in_disk v hv j p hy)) + +def anchoredMiddle (E : PolygonalExterior C) (e : Edge) : + Path (C.arcStart (C.firstArc e)) (C.arcEnd (C.lastArc e)) := + (E.middlePath e).cast (congrArg C.arcStart (C.orderedArc_first e).symm) + (congrArg C.arcEnd (C.orderedArc_last e).symm) + +theorem anchoredMiddle_range (E : PolygonalExterior C) (e : Edge) : + Set.range (E.anchoredMiddle e)=Set.range (E.middlePath e) := rfl + +theorem anchoredMiddle_injective (E : PolygonalExterior C) (e : Edge) : + Function.Injective (E.anchoredMiddle e) := E.middlePath_injective e + +end PolygonalExterior +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/DiskFilling.lean b/lean/OAI/Combinatorics/CompleteCrossing/DiskFilling.lean new file mode 100644 index 0000000000000000000000000000000000000000..cca13b697fde41da8f5420d7274dd474990ee72d --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/DiskFilling.lean @@ -0,0 +1,475 @@ +import OAI.Combinatorics.CompleteCrossing.Ports +import OAI.Combinatorics.Crossing.RoundCircleChords +import OAI.Combinatorics.Crossing.SegmentIntersectionUnique +import OAI.Combinatorics.Crossing.VertexDiskSpokes + +namespace OAI + +/-! Interior disk passages, vertex ports, filling containment, and crossing uniqueness. -/ + +section + +/-! The actual internal marked passages and their two boundary endpoints. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +abbrev InnerIndex (C : DrawingPassages D) := + (e : Edge) × {i : Fin (C.count e+1) // 0 < i.val ∧ i.val < C.count e} + +def innerMark (C : DrawingPassages D) (p : C.InnerIndex) : DrawingMark D := + ⟨D.edge p.1 (C.node p.1 p.2.val),C.node_mark p.1 p.2.val⟩ + +def incomingArc (C : DrawingPassages D) (p : C.InnerIndex) : C.ArcIndex := + ⟨p.1,⟨p.2.val.val-1,by have h := p.2.property; omega⟩⟩ + +def outgoingArc (C : DrawingPassages D) (p : C.InnerIndex) : C.ArcIndex := + ⟨p.1,⟨p.2.val.val,p.2.property.2⟩⟩ + +def incomingPort (C : DrawingPassages D) (p : C.InnerIndex) : C.Port := (C.incomingArc p,true) +def outgoingPort (C : DrawingPassages D) (p : C.InnerIndex) : C.Port := (C.outgoingArc p,false) + +theorem incoming_node (C : DrawingPassages D) (p : C.InnerIndex) : + (C.incomingArc p).2.succ=p.2.val := by + apply Fin.ext + change p.2.val.val-1+1=p.2.val.val + have h := p.2.property.1 + omega + +theorem outgoing_node (C : DrawingPassages D) (p : C.InnerIndex) : + (C.outgoingArc p).2.castSucc=p.2.val := rfl + +theorem incomingPort_mark (C : DrawingPassages D) (p : C.InnerIndex) : + C.portMark (C.incomingPort p)=C.innerMark p := by + apply Subtype.ext + change D.edge p.1 (C.node p.1 (C.incomingArc p).2.succ)=D.edge p.1 (C.node p.1 p.2.val) + rw [C.incoming_node] + +theorem outgoingPort_mark (C : DrawingPassages D) (p : C.InnerIndex) : + C.portMark (C.outgoingPort p)=C.innerMark p := rfl + +theorem incomingPort_point (C : DrawingPassages D) (p : C.InnerIndex) : + C.portPoint (C.incomingPort p)=D.edge p.1 (C.passage p.1 p.2.val).enter := by + change D.edge p.1 (C.passage p.1 (C.incomingArc p).2.succ).enter=_ + rw [C.incoming_node] + +theorem outgoingPort_point (C : DrawingPassages D) (p : C.InnerIndex) : + C.portPoint (C.outgoingPort p)=D.edge p.1 (C.passage p.1 p.2.val).leave := rfl + +theorem inner_parameter_interior (C : DrawingPassages D) (p : C.InnerIndex) : + C.node p.1 p.2.val ∈ Set.Ioo (0 : unitInterval) 1 := by + constructor + · rw [← C.first p.1] + exact C.increasing p.1 (show (0 : Fin (C.count p.1+1)) < p.2.val from p.2.property.1) + · rw [← C.last p.1] + exact C.increasing p.1 (show p.2.val < Fin.last (C.count p.1) from p.2.property.2) + +theorem innerMark_is_crossing (C : DrawingPassages D) (p : C.InnerIndex) : + (C.innerMark p).val ∈ Paper170.crossingPoints D.toContinuousDrawing := by + have hm := (C.innerMark p).property + rcases hm with ⟨v,hv⟩ | hcross + · exact False.elim (D.interior_avoids_vertices p.1 (C.node p.1 p.2.val) + (C.inner_parameter_interior p) v hv.symm) + · exact hcross + +def crossingChord (C : DrawingPassages D) (p : C.InnerIndex) : + Path (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) := + Path.segment _ _ + +theorem crossingChord_injective (C : DrawingPassages D) (p : C.InnerIndex) : + Function.Injective (C.crossingChord p) := by + apply Path.segment_injective_of_ne + intro he + rw [C.incomingPort_point,C.outgoingPort_point] at he + exact (C.passage p.1 p.2.val).enter_lt_leave.ne (D.edge_injective p.1 he) + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! Actual replacement vertices and all incident straight-spoke directions. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +def vertexMark (_C : DrawingPassages D) (v : Vertex) : DrawingMark D := + ⟨D.vertex v,Or.inl ⟨v,rfl⟩⟩ + +theorem vertexMark_injective (C : DrawingPassages D) : Function.Injective C.vertexMark := by + intro v w he + exact D.vertex_injective (congrArg Subtype.val he) + +theorem exists_drawing_vertex_placement [Fintype Edge] (C : DrawingPassages D) : + ∃ v : Vertex → Plane, Function.Injective v ∧ + (∀ i, squaredLength (v i-D.vertex i) < C.radius^2) ∧ + (∀ i (p : C.PortsAt (C.vertexMark i)), v i ≠ C.portPoint p.val) ∧ + (∀ i (p q : C.PortsAt (C.vertexMark i)), p ≠ q → + det2 (C.portPoint p.val-v i) (C.portPoint q.val-v i) ≠ 0) := by + classical + have hex (i : Vertex) : ∃ v : Plane, + squaredLength (v-D.vertex i) < C.radius^2 ∧ + (∀ p : C.PortsAt (C.vertexMark i), v ≠ C.portPoint p.val) ∧ + (∀ p q : C.PortsAt (C.vertexMark i), p ≠ q → det2 (C.portPoint p.val-v) (C.portPoint q.val-v) ≠ 0) := + exists_vertex_disk_point (D.vertex i) C.radius C.radius_pos + (fun p : C.PortsAt (C.vertexMark i) => C.portPoint p.val) + (C.portPoint_injective.comp Subtype.val_injective) (C.portsAt_on_circle (C.vertexMark i)) + choose v hv hne hdet using hex + refine ⟨v,?_,hv,hne,hdet⟩ + intro i j he + by_contra hij + have hd := C.disks_disjoint (C.vertexMark i) (C.vertexMark j) (C.vertexMark_injective.ne hij) + have hi : v i ∈ closedRoundDisk (C.vertexMark i).val C.radius := (hv i).le + have hj : v j ∈ closedRoundDisk (C.vertexMark j).val C.radius := (hv j).le + exact Set.disjoint_left.mp hd hi (he.symm ▸ hj) + +theorem vertex_spoke_injective (C : DrawingPassages D) (v : Vertex → Plane) + (hv : ∀ i, squaredLength (v i-D.vertex i) < C.radius^2) + (i : Vertex) (p : C.PortsAt (C.vertexMark i)) : + Function.Injective (Path.segment (v i) (C.portPoint p.val)) := by + apply Path.segment_injective_of_ne + intro he + have h := hv i + have hp : squaredLength (C.portPoint p.val-D.vertex i)=C.radius^2 := C.portsAt_on_circle (C.vertexMark i) p + rw [he,hp] at h + exact lt_irrefl _ h + +theorem vertex_spoke_interior (C : DrawingPassages D) (v : Vertex → Plane) + (hv : ∀ i, squaredLength (v i-D.vertex i) < C.radius^2) + (i : Vertex) (p : C.PortsAt (C.vertexMark i)) (t : unitInterval) + (ht : t < 1) : squaredLength ((Path.segment (v i) (C.portPoint p.val)) t-D.vertex i) < C.radius^2 := by + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + exact spoke_in_open_disk (D.vertex i) (v i) (C.portPoint p.val) C.radius (hv i) + (C.portsAt_on_circle (C.vertexMark i) p) t.val ⟨t.property.1,ht⟩ + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! Actual crossing-disk chord incidence, with no triples inherited from the original drawing. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +theorem innerIndex_eq_of_edge_mark (C : DrawingPassages D) (p q : C.InnerIndex) + (he : p.1=q.1) (hm : C.innerMark p=C.innerMark q) : p=q := by + rcases p with ⟨e,i⟩ + rcases q with ⟨f,j⟩ + change e=f at he + subst f + congr 1 + apply Subtype.ext + exact (C.increasing e).injective (D.edge_injective e (congrArg Subtype.val hm)) + +theorem incomingPort_injective (C : DrawingPassages D) : Function.Injective C.incomingPort := by + intro p q he + apply C.innerIndex_eq_of_edge_mark p q (congrArg (fun x : C.Port => x.1.1) he) + have hh := congrArg C.portMark he + simpa only [C.incomingPort_mark] using hh + +theorem outgoingPort_injective (C : DrawingPassages D) : Function.Injective C.outgoingPort := by + intro p q he + apply C.innerIndex_eq_of_edge_mark p q (congrArg (fun x : C.Port => x.1.1) he) + have hh := congrArg C.portMark he + simpa only [C.outgoingPort_mark] using hh + +theorem incomingPort_ne_outgoingPort (C : DrawingPassages D) (p q : C.InnerIndex) : + C.incomingPort p ≠ C.outgoingPort q := by + intro he + have hh : true=false := congrArg Prod.snd he + cases hh + +theorem incomingPoint_on_circle (C : DrawingPassages D) (p : C.InnerIndex) : + squaredLength (C.portPoint (C.incomingPort p)-(C.innerMark p).val)=C.radius^2 := by + simpa only [C.incomingPort_mark] using C.portPoint_on_circle (C.incomingPort p) + +theorem outgoingPoint_on_circle (C : DrawingPassages D) (p : C.InnerIndex) : + squaredLength (C.portPoint (C.outgoingPort p)-(C.innerMark p).val)=C.radius^2 := by + simpa only [C.outgoingPort_mark] using C.portPoint_on_circle (C.outgoingPort p) + +theorem crossing_chords_transverse_at_mark (C : DrawingPassages D) (p q : C.InnerIndex) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + SegmentPairTransverse (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) := by + apply round_circle_chords_transverse (C.innerMark p).val _ _ _ _ C.radius + · exact C.incomingPoint_on_circle p + · exact C.outgoingPoint_on_circle p + · simpa only [hm] using C.incomingPoint_on_circle q + · simpa only [hm] using C.outgoingPoint_on_circle q + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort p p) + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort q q) + · exact C.portPoint_injective.ne (C.incomingPort_injective.ne hpq) + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort p q) + · exact C.portPoint_injective.ne (Ne.symm (C.incomingPort_ne_outgoingPort q p)) + · exact C.portPoint_injective.ne (C.outgoingPort_injective.ne hpq) + +theorem innerMark_no_triples (C : DrawingPassages D) (p q r : C.InnerIndex) + (hpq : p ≠ q) (hpr : p ≠ r) (hqr : q ≠ r) + (hpqM : C.innerMark p=C.innerMark q) (hprM : C.innerMark p=C.innerMark r) : False := by + have heq : p.1 ≠ q.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hpqM) + have her : p.1 ≠ r.1 := fun he => hpr (C.innerIndex_eq_of_edge_mark p r he hprM) + have hqrM : C.innerMark q=C.innerMark r := hpqM.symm.trans hprM + have hfr : q.1 ≠ r.1 := fun he => hqr (C.innerIndex_eq_of_edge_mark q r he hqrM) + have hp : (C.innerMark p).val ∈ Paper170.edgeInterior D.toContinuousDrawing p.1 := + ⟨C.node p.1 p.2.val,C.inner_parameter_interior p,rfl⟩ + have hq : (C.innerMark p).val ∈ Paper170.edgeInterior D.toContinuousDrawing q.1 := by + rw [hpqM] + exact ⟨C.node q.1 q.2.val,C.inner_parameter_interior q,rfl⟩ + have hr : (C.innerMark p).val ∈ Paper170.edgeInterior D.toContinuousDrawing r.1 := by + rw [hprM] + exact ⟨C.node r.1 r.2.val,C.inner_parameter_interior r,rfl⟩ + have hmem : (C.innerMark p).val ∈ Paper170.edgeInterior D.toContinuousDrawing p.1 ∩ + Paper170.edgeInterior D.toContinuousDrawing q.1 ∩ Paper170.edgeInterior D.toContinuousDrawing r.1 := ⟨⟨hp,hq⟩,hr⟩ + rw [D.no_triples p.1 q.1 r.1 heq her hfr] at hmem + exact hmem + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! The actual first and last retained ports attach to the prescribed graph vertices. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +def firstArc (C : DrawingPassages D) (e : Edge) : C.ArcIndex := + ⟨e,⟨0,C.count_pos e⟩⟩ + +def lastArc (C : DrawingPassages D) (e : Edge) : C.ArcIndex := + ⟨e,⟨C.count e-1,by have h := C.count_pos e; omega⟩⟩ + +theorem lastArc_node (C : DrawingPassages D) (e : Edge) : + (C.lastArc e).2.succ=Fin.last (C.count e) := by + apply Fin.ext + have h := C.count_pos e + change C.count e-1+1=C.count e + omega + +theorem firstArc_mark (C : DrawingPassages D) (e : Edge) : + C.arcStartMark (C.firstArc e)=C.vertexMark (graph.src e) := by + apply Subtype.ext + change D.edge e (C.node e 0)=D.vertex (graph.src e) + rw [C.first,Path.source] + +theorem lastArc_mark (C : DrawingPassages D) (e : Edge) : + C.arcEndMark (C.lastArc e)=C.vertexMark (graph.dst e) := by + apply Subtype.ext + change D.edge e (C.node e (C.lastArc e).2.succ)=D.vertex (graph.dst e) + rw [C.lastArc_node,C.last,Path.target] + +def startPortAt (C : DrawingPassages D) (e : Edge) : C.PortsAt (C.vertexMark (graph.src e)) := + ⟨(C.firstArc e,false),C.firstArc_mark e⟩ + +def endPortAt (C : DrawingPassages D) (e : Edge) : C.PortsAt (C.vertexMark (graph.dst e)) := + ⟨(C.lastArc e,true),C.lastArc_mark e⟩ + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! Actual closed-disk containment and strict interior containment of disk fillings. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +theorem round_chord_in_disk (z a b : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (t : ℝ) (ht : t ∈ Set.Icc (0 : ℝ) 1) : + squaredLength (segmentPoint a b t-z) ≤ r^2 := by + have he : squaredLength (segmentPoint a b t-z)= + (1-t)*squaredLength (a-z)+t*squaredLength (b-z)-t*(1-t)*squaredLength (b-a) := by + dsimp [squaredLength,segmentPoint] + ring + have hnon : 0 ≤ t*(1-t)*squaredLength (b-a) := by + apply mul_nonneg (mul_nonneg ht.1 (sub_nonneg.mpr ht.2)) + dsimp [squaredLength] + positivity + rw [he,ha,hb] + linarith + +namespace DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +theorem crossingChord_range_subset_disk (C : DrawingPassages D) (p : C.InnerIndex) : + Set.range (C.crossingChord p) ⊆ closedRoundDisk (C.innerMark p).val C.radius := by + rintro x ⟨t,rfl⟩ + change squaredLength ((Path.segment _ _) t-(C.innerMark p).val) ≤ C.radius^2 + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + exact round_chord_in_disk _ _ _ _ (C.incomingPoint_on_circle p) (C.outgoingPoint_on_circle p) t.val t.property + +theorem crossingChord_interior_in_disk (C : DrawingPassages D) (p : C.InnerIndex) + (t : unitInterval) (ht : t ∈ Set.Ioo (0 : unitInterval) 1) : + squaredLength (C.crossingChord p t-(C.innerMark p).val) < C.radius^2 := by + change squaredLength ((Path.segment _ _) t-(C.innerMark p).val) < C.radius^2 + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + exact round_chord_in_open_disk _ _ _ _ (C.incomingPoint_on_circle p) (C.outgoingPoint_on_circle p) + (C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort p p)) t.val ht + +theorem crossingChords_disjoint_of_marks_ne (C : DrawingPassages D) (p q : C.InnerIndex) + (hm : C.innerMark p ≠ C.innerMark q) : + Disjoint (Set.range (C.crossingChord p)) (Set.range (C.crossingChord q)) := + (C.disks_disjoint _ _ hm).mono (C.crossingChord_range_subset_disk p) (C.crossingChord_range_subset_disk q) + +theorem portPoint_outside_other_disk (C : DrawingPassages D) (p : C.Port) (x : DrawingMark D) + (hx : C.portMark p ≠ x) : C.radius^2 < squaredLength (C.portPoint p-x.val) := by + apply lt_of_not_ge + intro hh + have hp : C.portPoint p ∈ closedRoundDisk (C.portMark p).val C.radius := (C.portPoint_on_circle p).le + exact Set.disjoint_left.mp (C.disks_disjoint _ _ hx) hp hh + +theorem portPoint_outside_open_disks (C : DrawingPassages D) (p : C.Port) (x : DrawingMark D) : + C.radius^2 ≤ squaredLength (C.portPoint p-x.val) := by + by_cases he : C.portMark p=x + · have hp := C.portPoint_on_circle p + rw [he] at hp + exact hp.ge + · exact (C.portPoint_outside_other_disk p x he).le + +theorem crossingChord_avoids_vertex_disks (C : DrawingPassages D) (p : C.InnerIndex) + (v : Vertex) : + Disjoint (Set.range (C.crossingChord p)) (closedRoundDisk (D.vertex v) C.radius) := by + have hn : C.innerMark p ≠ C.vertexMark v := by + intro he + exact crossing_not_vertex D (C.innerMark p).val (C.innerMark_is_crossing p) v (congrArg Subtype.val he) + exact (C.disks_disjoint _ _ hn).mono (C.crossingChord_range_subset_disk p) Set.Subset.rfl + +end DrawingPassages +end Paper170Geometry + +end +end + +section + +/-! At most one actual chord crossing point in each original crossing disk. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +theorem innerIndex_at_mark_pair (C : DrawingPassages D) (p q r : C.InnerIndex) + (hpq : p ≠ q) (hpqM : C.innerMark p=C.innerMark q) (hprM : C.innerMark p=C.innerMark r) : + r=p ∨ r=q := by + by_cases hrp : r=p + · exact Or.inl hrp + by_cases hrq : r=q + · exact Or.inr hrq + exact False.elim (C.innerMark_no_triples p q r hpq (Ne.symm hrp) (Ne.symm hrq) hpqM hprM) + +def chordCrossingsAt (C : DrawingPassages D) (w : DrawingMark D) : Set Plane := + {x | ∃ p q : C.InnerIndex, p ≠ q ∧ C.innerMark p=w ∧ C.innerMark q=w ∧ + x ∈ Set.range (C.crossingChord p) ∧ x ∈ Set.range (C.crossingChord q)} + +theorem chordCrossingsAt_subsingleton (C : DrawingPassages D) (w : DrawingMark D) : + (C.chordCrossingsAt w).Subsingleton := by + rintro x ⟨p,q,hpq,hp,hq,hxp,hxq⟩ y ⟨r,s,hrs,hr,hs,hyr,hys⟩ + have hpm : C.innerMark p=C.innerMark q := hp.trans hq.symm + have hrpair := C.innerIndex_at_mark_pair p q r hpq hpm (hp.trans hr.symm) + have hspair := C.innerIndex_at_mark_pair p q s hpq hpm (hp.trans hs.symm) + have hunique := transverse_segment_intersection_subsingleton _ _ _ _ + (C.crossing_chords_transverse_at_mark p q hpq hpm) + rcases hrpair with rfl | rfl <;> rcases hspair with rfl | rfl + · exact False.elim (hrs rfl) + · exact hunique ⟨hxp,hxq⟩ ⟨hyr,hys⟩ + · exact hunique ⟨hxp,hxq⟩ ⟨hys,hyr⟩ + · exact False.elim (hrs rfl) + +theorem chord_meeting_marks_eq (C : DrawingPassages D) (p q : C.InnerIndex) {x : Plane} + (hp : x ∈ Set.range (C.crossingChord p)) (hq : x ∈ Set.range (C.crossingChord q)) : + C.innerMark p=C.innerMark q := by + by_contra h + exact Set.disjoint_left.mp (C.crossingChords_disjoint_of_marks_ne p q h) hp hq + +def chordCrossings (C : DrawingPassages D) : Set Plane := + {x | ∃ p q : C.InnerIndex, p ≠ q ∧ x ∈ Set.range (C.crossingChord p) ∧ x ∈ Set.range (C.crossingChord q)} + +theorem chord_crossing_original_mark (C : DrawingPassages D) {x : Plane} (hx : x ∈ C.chordCrossings) : + ∃ w : DrawingMark D, w.val ∈ Paper170.crossingPoints D.toContinuousDrawing ∧ x ∈ C.chordCrossingsAt w := by + obtain ⟨p,q,hpq,hp,hq⟩ := hx + refine ⟨C.innerMark p,C.innerMark_is_crossing p,p,q,hpq,rfl,?_,hp,hq⟩ + exact (C.chord_meeting_marks_eq p q hp hq).symm + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! Count actual spatial chord crossings by their original crossing disks. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +open scoped Classical +variable {D : FiniteIntersectionDrawing graph} + +def chordCrossingOrigin (C : DrawingPassages D) (x : Plane) : Plane := + if hx : x ∈ C.chordCrossings then (C.chord_crossing_original_mark hx).choose.val else 0 + +theorem chordCrossingOrigin_mapsTo (C : DrawingPassages D) : + Set.MapsTo C.chordCrossingOrigin C.chordCrossings (Paper170.crossingPoints D.toContinuousDrawing) := by + intro x hx + have hh := (C.chord_crossing_original_mark hx).choose_spec.1 + simpa only [chordCrossingOrigin,dite_eq_left hx] using hh + +theorem chordCrossingOrigin_injOn (C : DrawingPassages D) : + Set.InjOn C.chordCrossingOrigin C.chordCrossings := by + intro x hx y hy he + let w : DrawingMark D := (C.chord_crossing_original_mark hx).choose + let v : DrawingMark D := (C.chord_crossing_original_mark hy).choose + have hwx : x ∈ C.chordCrossingsAt w := (C.chord_crossing_original_mark hx).choose_spec.2 + have hvy : y ∈ C.chordCrossingsAt v := (C.chord_crossing_original_mark hy).choose_spec.2 + have hvw : w=v := by + apply Subtype.ext + simpa only [chordCrossingOrigin,dite_eq_left hx,dite_eq_left hy] using he + rw [← hvw] at hvy + exact (C.chordCrossingsAt_subsingleton w) hwx hvy + +theorem chordCrossings_finite (C : DrawingPassages D) : C.chordCrossings.Finite := + Set.Finite.of_injOn C.chordCrossingOrigin_mapsTo C.chordCrossingOrigin_injOn D.crossings_finite + +/-- Different original crossing disks remain separately counted, even when +their two chords come from the same pair of graph edges. -/ +theorem chordCrossings_ncard_le (C : DrawingPassages D) : + C.chordCrossings.ncard ≤ finiteCrossingCount D := by + calc + C.chordCrossings.ncard ≤ (Paper170.crossingPoints D.toContinuousDrawing).ncard := + Set.ncard_le_ncard_of_injOn C.chordCrossingOrigin C.chordCrossingOrigin_mapsTo + C.chordCrossingOrigin_injOn D.crossings_finite + _ = finiteCrossingCount D := Set.ncard_eq_toFinset_card _ D.crossings_finite + +end Paper170Geometry.DrawingPassages + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Drawing.lean b/lean/OAI/Combinatorics/CompleteCrossing/Drawing.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a417f54ef1927dc40bb8201f1a6bcd1ef153fa4 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Drawing.lean @@ -0,0 +1,461 @@ +import OAI.Combinatorics.Crossing.DrawingDefinition +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Analysis.SpecialFunctions.Complex.Arg +import Mathlib.Data.Set.Card +import Mathlib.Order.Lattice.Nat +import Mathlib.Topology.OpenPartialHomeomorph.Defs +import Mathlib.Topology.Path + +namespace OAI + +/-! Continuous graph drawings, proper spatial crossings, incidence, and endpoint properties. -/ + +section + +/-! + +The coordinate plane has its usual topology; every Euclidean circle below is +specified by squaredLength, not by the product norm. +-/ + +noncomputable section +open Set +open scoped BigOperators Classical + +namespace Paper170 + +abbrev Plane := ℝ × ℝ + +def squaredLength (x : Plane) : ℝ := x.1 ^ 2 + x.2 ^ 2 + +def det2 (x y : Plane) : ℝ := x.1 * y.2 - x.2 * y.1 + +def segmentPoint (a b : Plane) (t : ℝ) : Plane := (1 - t) • a + t • b + +/-- One chosen orientation of each edge of a finite simple graph. -/ +structure Graph (V E : Type) where + src : E → V + dst : E → V + loopless : ∀ e, src e ≠ dst e + simple : ∀ e f, ((src e = src f ∧ dst e = dst f) ∨ + (src e = dst f ∧ dst e = src f)) → e = f + +abbrev CompleteEdge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +instance (n : ℕ) : Fintype (CompleteEdge n) := Fintype.ofFinite _ + +def completeGraph (n : ℕ) : Graph (Fin n) (CompleteEdge n) where + src e := e.val.1 + dst e := e.val.2 + loopless e := ne_of_lt e.property + simple e f h := by + rcases h with h | h + · exact Subtype.ext (Prod.ext h.1 h.2) + · have he := e.property + have hf := f.property + rw [h.1, h.2] at he + exact (lt_asymm he hf).elim + +variable {V E : Type} (G : Graph V E) + +namespace Graph + +abbrev IncidentEdge (v : V) := {e : E // G.src e = v ∨ G.dst e = v} + +end Graph + +/-- Actual injective continuous edge arcs, with unrestricted routing. -/ +structure ContinuousDrawing where + vertex : V → Plane + vertex_injective : Function.Injective vertex + edge : ∀ e : E, Path (vertex (G.src e)) (vertex (G.dst e)) + edge_injective : ∀ e, Function.Injective (edge e) + interior_avoids_vertices : ∀ e t, t ∈ Ioo (0 : unitInterval) 1 → + ∀ v, edge e t ≠ vertex v + +variable {G} + +def edgeInterior (D : ContinuousDrawing G) (e : E) : Set Plane := + D.edge e '' Ioo (0 : unitInterval) 1 + +/-- A proper double crossing is locally homeomorphic to two coordinate axes. -/ +structure ProperCrossing (A B : Set Plane) (x : Plane) : Prop where + chart_exists : ∃ chart : OpenPartialHomeomorph Plane Plane, + x ∈ chart.source ∧ chart x = (0, 0) ∧ + chart '' (chart.source ∩ A) = chart.target ∩ {y | y.2 = 0} ∧ + chart '' (chart.source ∩ B) = chart.target ∩ {y | y.1 = 0} + +/-- Spatial intersection points. Different meetings of the same pair remain distinct. -/ +def crossingPoints (D : ContinuousDrawing G) : Set Plane := + {x | ∃ e f : E, e ≠ f ∧ x ∈ edgeInterior D e ∧ x ∈ edgeInterior D f} + +structure AdmissibleDrawing (G : Graph V E) extends ContinuousDrawing G where + crossings_finite : (crossingPoints toContinuousDrawing).Finite + crossings_proper : ∀ e f, e ≠ f → ∀ x, + x ∈ edgeInterior toContinuousDrawing e → x ∈ edgeInterior toContinuousDrawing f → + ProperCrossing (edgeInterior toContinuousDrawing e) (edgeInterior toContinuousDrawing f) x + no_triples : ∀ e f g, e ≠ f → e ≠ g → f ≠ g → + edgeInterior toContinuousDrawing e ∩ edgeInterior toContinuousDrawing f ∩ + edgeInterior toContinuousDrawing g = ∅ + +def crossingCount (D : AdmissibleDrawing G) : ℕ := D.crossings_finite.toFinset.card + +/-- The minimum spatial crossing count over admissible drawings. -/ +def ordinaryCrossingNumber (G : Graph V E) : ℕ := sInf (range (@crossingCount V E G)) + +/-- A finite affine parametrization of the actual path. -/ +structure PolygonalParametrization {a b : Plane} (γ : Path a b) where + pieces : ℕ + positive : 0 < pieces + knot : Fin (pieces + 1) → unitInterval + increasing : StrictMono knot + first : knot 0 = 0 + last : knot (Fin.last pieces) = 1 + affine : ∀ i : Fin pieces, ∀ t : unitInterval, + knot i.castSucc ≤ t → t ≤ knot i.succ → + γ t = segmentPoint (γ (knot i.castSucc)) (γ (knot i.succ)) + (((t : ℝ) - knot i.castSucc) / ((knot i.succ : ℝ) - knot i.castSucc)) + +def PolygonalParametrization.vertices {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) (i : ℕ) : Plane := + γ (P.knot ⟨min i P.pieces, Nat.lt_succ_of_le (Nat.min_le_right _ _)⟩) + +/-- A convenient subdivision of a normalized drawing. Avoiding subdivision +knots at crossings is additional presentation data, obtained by the normalization theorem. -/ +structure NormalizedDrawing (G : Graph V E) extends AdmissibleDrawing G where + polygonal : ∀ e, PolygonalParametrization (edge e) + no_adjacent : ∀ e f, e ≠ f → + (G.src e = G.src f ∨ G.src e = G.dst f ∨ G.dst e = G.src f ∨ G.dst e = G.dst f) → + Disjoint (edgeInterior toContinuousDrawing e) (edgeInterior toContinuousDrawing f) + crossings_not_knots : ∀ e (i : Fin ((polygonal e).pieces + 1)), + edge e ((polygonal e).knot i) ∉ crossingPoints toContinuousDrawing + +/-- Directed open-segment intersection, with the ordinary determinant sign. -/ +def segmentIntersection (a b c d : Plane) : ℝ := + if ∃ s ∈ Ioo (0 : ℝ) 1, ∃ t ∈ Ioo (0 : ℝ) 1, + segmentPoint a b s = segmentPoint c d t then + if 0 < det2 (b - a) (d - c) then 1 + else if det2 (b - a) (d - c) < 0 then -1 else 0 + else 0 + +def interiorIntersection (N : NormalizedDrawing G) (e f : E) : ℝ := + if e = f then 0 else + ∑ i ∈ Finset.range (N.polygonal e).pieces, + ∑ j ∈ Finset.range (N.polygonal f).pieces, + segmentIntersection ((N.polygonal e).vertices i) ((N.polygonal e).vertices (i + 1)) + ((N.polygonal f).vertices j) ((N.polygonal f).vertices (j + 1)) + +def outwardSpoke (N : NormalizedDrawing G) (v : V) (e : E) : Plane := + if G.src e = v then (N.polygonal e).vertices 1 - (N.polygonal e).vertices 0 + else (N.polygonal e).vertices ((N.polygonal e).pieces - 1) - + (N.polygonal e).vertices (N.polygonal e).pieces + +def spokeAngle (cut : ℝ) (a : Plane) : ℝ := + Complex.arg (Complex.exp (-(cut : ℂ) * Complex.I) * (⟨a.1, a.2⟩ : ℂ)) + +/-- The linear local orders are witnessed by the actual counterclockwise angles, +with a cut in a gap. No intersection identity is part of this data. -/ +structure SpokeOrders (N : NormalizedDrawing G) where + cut : V → ℝ + order : ∀ v, LinearOrder (G.IncidentEdge v) + cut_avoids : ∀ v (e : G.IncidentEdge v), spokeAngle (cut v) (outwardSpoke N v e.val) ≠ Real.pi + compatible : ∀ v (e f : G.IncidentEdge v), + @LT.lt _ (order v).toLT e f ↔ + spokeAngle (cut v) (outwardSpoke N v e.val) < + spokeAngle (cut v) (outwardSpoke N v f.val) + +def endpointSign (G : Graph V E) (v : V) (e : E) : ℝ := + if G.src e = v then 1 else if G.dst e = v then -1 else 0 + +def spokeComparison {N : NormalizedDrawing G} (O : SpokeOrders N) (v : V) (e f : E) : ℝ := + if he : G.src e = v ∨ G.dst e = v then if hf : G.src f = v ∨ G.dst f = v then + if @LT.lt _ (O.order v).toLT ⟨e, he⟩ ⟨f, hf⟩ then 1 + else if @LT.lt _ (O.order v).toLT ⟨f, hf⟩ ⟨e, he⟩ then -1 else 0 + else 0 else 0 + +variable [Fintype V] [Fintype E] + +def cycleIntersection {N : NormalizedDrawing G} (O : SpokeOrders N) (e f : E) : ℝ := + interiorIntersection N e f + (1 / 2 : ℝ) * + ∑ v, endpointSign G v e * endpointSign G v f * spokeComparison O v e f + +def edgePairing (J : E → E → ℝ) (z z' : E → ℝ) : ℝ := + ∑ e, ∑ f, z e * z' f * J e f + +def boundary (G : Graph V E) (z : E → ℝ) (v : V) : ℝ := + ∑ e, z e * ((if G.dst e = v then 1 else 0) - (if G.src e = v then 1 else 0)) + +def completeEdgeVector {n : ℕ} (i p : Fin n) : CompleteEdge n → ℝ := + fun e => if e.val.1 = i ∧ e.val.2 = p then 1 + else if e.val.1 = p ∧ e.val.2 = i then -1 else 0 + +def rawCycleIntersection {n : ℕ} {N : NormalizedDrawing (completeGraph n)} + (O : SpokeOrders N) (i p k q : Fin n) : ℝ := + edgePairing (cycleIntersection O) (completeEdgeVector i p) (completeEdgeVector k q) + +/-- A simple combinatorial cycle with a chosen direction of traversal. -/ +structure SimpleCycle (G : Graph V E) where + length : ℕ + three_le : 3 ≤ length + vertex : Fin length → V + vertex_injective : Function.Injective vertex + edge : Fin length → E + follows : ∀ i, + let j : Fin length := ⟨(i.val + 1) % length, + Nat.mod_lt _ (lt_of_lt_of_le (by decide : 0 < 3) three_le)⟩ + (G.src (edge i) = vertex i ∧ G.dst (edge i) = vertex j) ∨ + (G.dst (edge i) = vertex i ∧ G.src (edge i) = vertex j) + +def SimpleCycle.edgeChain (C : SimpleCycle G) : E → ℝ := + fun e => ∑ i, if C.edge i = e then (if G.src e = C.vertex i then 1 else -1) else 0 + +def polygonIntersection (v w : ℕ → Plane) (n m : ℕ) : ℝ := + ∑ i ∈ Finset.range n, ∑ j ∈ Finset.range m, + segmentIntersection (v i) (v (i + 1)) (w j) (w (j + 1)) + +/-- Only proper interior meetings between the two polygonal walks. -/ +structure TransversePolygons (v w : ℕ → Plane) (n m : ℕ) : Prop where + left_vertices_avoid : ∀ i, i ≤ n → ∀ j, j < m → ∀ t ∈ Icc (0 : ℝ) 1, + v i ≠ segmentPoint (w j) (w (j + 1)) t + right_vertices_avoid : ∀ j, j ≤ m → ∀ i, i < n → ∀ t ∈ Icc (0 : ℝ) 1, + w j ≠ segmentPoint (v i) (v (i + 1)) t + transverse : ∀ i, i < n → ∀ j, j < m → + (∃ s ∈ Ioo (0 : ℝ) 1, ∃ t ∈ Ioo (0 : ℝ) 1, + segmentPoint (v i) (v (i + 1)) s = segmentPoint (w j) (w (j + 1)) t) → + det2 (v (i + 1) - v i) (w (j + 1) - w j) ≠ 0 + +def circleComparison (cut : ℝ) (a b : Plane) : ℝ := + if spokeAngle cut a < spokeAngle cut b then 1 + else if spokeAngle cut b < spokeAngle cut a then -1 else 0 + +def inversion (z : Plane) : Plane := (z.1 / squaredLength z, z.2 / squaredLength z) + +end Paper170 + +end +end + +section + +/-! Converting actual nonvertex trace contacts to the exact crossing-point definition. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem edgeInterior_subset_range (D : Paper170.ContinuousDrawing graph) (e : Edge) : + Paper170.edgeInterior D e ⊆ Set.range (D.edge e) := by + rintro x ⟨t,_,he⟩ + exact ⟨t,he⟩ + +theorem edgeInterior_of_range_not_vertices (D : Paper170.ContinuousDrawing graph) (e : Edge) + (x : Plane) (hx : x ∈ Set.range (D.edge e)) (hvertex : ∀ j, x ≠ D.vertex j) : + x ∈ Paper170.edgeInterior D e := by + obtain ⟨t,he⟩ := hx + have ht0 : t ≠ 0 := by + intro ht + subst t + exact hvertex _ (he.symm.trans (D.edge e).source) + have ht1 : t ≠ 1 := by + intro ht + subst t + exact hvertex _ (he.symm.trans (D.edge e).target) + exact ⟨t,⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩,he⟩ + +theorem edgeInterior_not_vertex (D : Paper170.ContinuousDrawing graph) (e : Edge) + (x : Plane) (hx : x ∈ Paper170.edgeInterior D e) (j : Vertex) : x ≠ D.vertex j := by + obtain ⟨t,ht,he⟩ := hx + exact fun hj => D.interior_avoids_vertices e t ht j (he.trans hj) + +theorem crossing_of_ranges_not_vertices (D : Paper170.ContinuousDrawing graph) (e f : Edge) + (hef : e ≠ f) (x : Plane) (he : x ∈ Set.range (D.edge e)) (hf : x ∈ Set.range (D.edge f)) + (hv : ∀ j, x ≠ D.vertex j) : x ∈ Paper170.crossingPoints D := + ⟨e,f,hef,edgeInterior_of_range_not_vertices D e x he hv,edgeInterior_of_range_not_vertices D f x hf hv⟩ + +end Paper170Geometry + +end +end + +section + +namespace Paper170Geometry +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +theorem drawing_edge_vertex_parameter (D : Paper170.ContinuousDrawing graph) (e : Edge) + (t : unitInterval) (v : Vertex) (he : D.edge e t=D.vertex v) : + (t=0 ∧ v=(graph.src e)) ∨ (t=1 ∧ v=(graph.dst e)) := by + by_cases ht0 : t=0 + · subst t + exact Or.inl ⟨rfl,(D.vertex_injective ((D.edge e).source.symm.trans he)).symm⟩ + by_cases ht1 : t=1 + · subst t + exact Or.inr ⟨rfl,(D.vertex_injective ((D.edge e).target.symm.trans he)).symm⟩ + exact False.elim (D.interior_avoids_vertices e t + ⟨lt_of_le_of_ne t.property.1 (Ne.symm ht0),lt_of_le_of_ne t.property.2 ht1⟩ v he) + +end Paper170Geometry + +end + +section + +/-! A weaker INPUT for normalization: actual simple routes with finite contacts and no triples. +The endpoint's Paper170.AdmissibleDrawing and MainTarget definitions are unchanged. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +structure FiniteIntersectionDrawing (graph : Paper170.Graph Vertex Edge) extends Paper170.ContinuousDrawing graph where + crossings_finite : (Paper170.crossingPoints toContinuousDrawing).Finite + no_triples : ∀ e f g, e ≠ f → e ≠ g → f ≠ g → + Paper170.edgeInterior toContinuousDrawing e ∩ Paper170.edgeInterior toContinuousDrawing f ∩ + Paper170.edgeInterior toContinuousDrawing g = ∅ + +abbrev toFiniteIntersectionDrawing (D : Paper170.AdmissibleDrawing graph) : + FiniteIntersectionDrawing graph where + toContinuousDrawing := D.toContinuousDrawing + crossings_finite := D.crossings_finite + no_triples := D.no_triples + +instance admissibleToFiniteIntersectionDrawing : + CoeOut (Paper170.AdmissibleDrawing graph) (FiniteIntersectionDrawing graph) := + ⟨toFiniteIntersectionDrawing⟩ + +def finiteCrossingCount (D : FiniteIntersectionDrawing graph) : ℕ := + D.crossings_finite.toFinset.card + +theorem finiteCrossingCount_of_admissible (D : Paper170.AdmissibleDrawing graph) : + finiteCrossingCount (D : FiniteIntersectionDrawing graph)=Paper170.crossingCount D := rfl + +theorem finiteCrossingCount_eq_ncard (D : FiniteIntersectionDrawing graph) : + finiteCrossingCount D=(Paper170.crossingPoints D.toContinuousDrawing).ncard := + (Set.ncard_eq_toFinset_card _ D.crossings_finite).symm + +end Paper170Geometry + +namespace Paper170.AdmissibleDrawing + +abbrev toFiniteIntersectionDrawing {V E : Type} {G : Graph V E} (D : AdmissibleDrawing G) : + Paper170Geometry.FiniteIntersectionDrawing G := Paper170Geometry.toFiniteIntersectionDrawing D + +end Paper170.AdmissibleDrawing + +end +end + +section + +/-! Finite point incidence for actual drawings, retaining repeated pair crossings. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +open scoped BigOperators Classical +/-- A minimum exists once an actual admissible drawing has been constructed. +This is the well-ordering step; construction of a drawing remains a separate obligation. -/ +theorem crossingCount_attainment (D₀ : Paper170.AdmissibleDrawing graph) : + ∃ D : Paper170.AdmissibleDrawing graph, Paper170.crossingCount D = Paper170.ordinaryCrossingNumber graph := by + exact csInf_mem (show (Set.range (@Paper170.crossingCount Vertex Edge graph)).Nonempty from + ⟨Paper170.crossingCount D₀, D₀, rfl⟩) + +theorem ordinaryCrossingNumber_le_count (D : Paper170.AdmissibleDrawing graph) : + Paper170.ordinaryCrossingNumber graph ≤ Paper170.crossingCount D := + csInf_le' ⟨D, rfl⟩ + +theorem crossing_incident_iff (D : Paper170.AdmissibleDrawing graph) (x : Plane) + (e f : Edge) (hef : e ≠ f) + (he : x ∈ Paper170.edgeInterior D.toContinuousDrawing e) + (hf : x ∈ Paper170.edgeInterior D.toContinuousDrawing f) (g : Edge) : + x ∈ Paper170.edgeInterior D.toContinuousDrawing g ↔ g = e ∨ g = f := by + constructor + · intro hg + by_contra hh + have hge : e ≠ g := by tauto + have hgf : f ≠ g := by tauto + have hmem : x ∈ Paper170.edgeInterior D.toContinuousDrawing e ∩ Paper170.edgeInterior D.toContinuousDrawing f ∩ + Paper170.edgeInterior D.toContinuousDrawing g := ⟨⟨he,hf⟩,hg⟩ + rw [D.no_triples e f g hef hge hgf] at hmem + exact hmem + · rintro (rfl | rfl) <;> assumption + +/-- Every spatial crossing has exactly two incident edges; no bound is imposed +on the number of points common to that edge pair. -/ +theorem crossing_two_edges (D : Paper170.AdmissibleDrawing graph) (x : Plane) + (hx : x ∈ Paper170.crossingPoints D.toContinuousDrawing) : + ∃ e f : Edge, e ≠ f ∧ + ∀ g, x ∈ Paper170.edgeInterior D.toContinuousDrawing g ↔ g = e ∨ g = f := by + obtain ⟨e,f,hef,he,hf⟩ := hx + exact ⟨e,f,hef,crossing_incident_iff D x e f hef he hf⟩ + +/-- The actual finite set of crossing points for a specified ordered edge pair. -/ +def pairCrossings (D : Paper170.AdmissibleDrawing graph) (e f : Edge) : Finset Plane := + D.crossings_finite.toFinset.filter (fun x => e ≠ f ∧ + x ∈ Paper170.edgeInterior D.toContinuousDrawing e ∧ x ∈ Paper170.edgeInterior D.toContinuousDrawing f) + +theorem pairCrossings_self (D : Paper170.AdmissibleDrawing graph) (e : Edge) : + pairCrossings D e e = ∅ := by + simp [pairCrossings] + +theorem pairCrossings_comm (D : Paper170.AdmissibleDrawing graph) (e f : Edge) : + pairCrossings D e f = pairCrossings D f e := by + ext x + simp only [pairCrossings, Finset.mem_filter] + tauto + +variable [Fintype Edge] + +/-- Each crossing point contributes two ordered edge pairs. -/ +theorem crossing_ordered_incidence (D : Paper170.AdmissibleDrawing graph) (x : Plane) + (hx : x ∈ Paper170.crossingPoints D.toContinuousDrawing) : + (∑ e : Edge, ∑ f : Edge, + if e ≠ f ∧ x ∈ Paper170.edgeInterior D.toContinuousDrawing e ∧ + x ∈ Paper170.edgeInterior D.toContinuousDrawing f then (1 : ℕ) else 0) = 2 := by + classical + obtain ⟨e,f,hef,hinc⟩ := crossing_two_edges D x hx + simp_rw [hinc] + have hp : ∀ a b : Edge, + (a ≠ b ∧ (a = e ∨ a = f) ∧ (b = e ∨ b = f)) ↔ + ((a = e ∧ b = f) ∨ (a = f ∧ b = e)) := by + intro a b + constructor + · rintro ⟨hab, rfl | rfl, rfl | rfl⟩ <;> tauto + · rintro (⟨rfl,rfl⟩ | ⟨rfl,rfl⟩) <;> tauto + simp_rw [hp] + have hi : ∀ a b : Edge, + (if (a = e ∧ b = f) ∨ (a = f ∧ b = e) then (1 : ℕ) else 0) = + (if a = e ∧ b = f then 1 else 0) + (if a = f ∧ b = e then 1 else 0) := by + intro a b + split_ifs <;> simp_all + simp_rw [hi, Finset.sum_add_distrib] + simp [ite_and] + +/-- Sum over ordered edge pairs equals twice the number of spatial crossing points. -/ +theorem sum_pairCrossings_card (D : Paper170.AdmissibleDrawing graph) : + (∑ e : Edge, ∑ f : Edge, (pairCrossings D e f).card) = + 2 * Paper170.crossingCount D := by + classical + simp only [pairCrossings, Finset.card_filter] + rw [Finset.sum_comm] + conv_lhs => arg 2; ext f; rw [Finset.sum_comm] + rw [Finset.sum_comm] + have he : ∀ x ∈ D.crossings_finite.toFinset, + (∑ f : Edge, ∑ e : Edge, + if e ≠ f ∧ x ∈ Paper170.edgeInterior D.toContinuousDrawing e ∧ + x ∈ Paper170.edgeInterior D.toContinuousDrawing f then (1 : ℕ) else 0) = 2 := by + intro x hx + rw [Finset.sum_comm] + exact crossing_ordered_incidence D x (by simpa using hx) + simp_rw [Finset.sum_congr rfl he] + simp [Paper170.crossingCount, Nat.mul_comm] + +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/DrawingMarks.lean b/lean/OAI/Combinatorics/CompleteCrossing/DrawingMarks.lean new file mode 100644 index 0000000000000000000000000000000000000000..77ac333ae46150c20fa7910000ea536833d239c8 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/DrawingMarks.lean @@ -0,0 +1,512 @@ +import OAI.Combinatorics.CompleteCrossing.Drawing +import OAI.Combinatorics.Crossing.AffineSubdivisionRefinement +import OAI.Combinatorics.Crossing.DrawingEdgeWalkTrace +import OAI.Combinatorics.Crossing.EmbeddedGraphPaths +import OAI.Combinatorics.Crossing.GraphSequenceWalk +import OAI.Combinatorics.Crossing.OrderedAffineSubdivision +import OAI.Combinatorics.Crossing.OrderedKnotCover +import OAI.Combinatorics.Crossing.PathSubarc +import OAI.Combinatorics.Crossing.SortedMarkedParameters +import OAI.Combinatorics.Crossing.SubdivisionSegments + +namespace OAI + +/-! Marked subdivision parameters, incidence graphs, and edge walks. -/ + +section + +/-! The actual finite marks and marked parameters of a continuous drawing. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +def drawingMarks (D : FiniteIntersectionDrawing graph) : Set Plane := + Set.range D.vertex ∪ Paper170.crossingPoints D.toContinuousDrawing + +theorem drawingMarks_finite [Fintype Vertex] (D : FiniteIntersectionDrawing graph) : (drawingMarks D).Finite := + (Set.finite_range D.vertex).union D.crossings_finite + +theorem crossing_not_vertex (D : FiniteIntersectionDrawing graph) (x : Plane) + (hx : x ∈ Paper170.crossingPoints D.toContinuousDrawing) (v : Vertex) : x ≠ D.vertex v := by + obtain ⟨e,f,hef,⟨t,ht,he⟩,hf⟩ := hx + intro hh + exact D.interior_avoids_vertices e t ht v (he.trans hh) + +theorem marked_parameters_finite [Fintype Vertex] (D : FiniteIntersectionDrawing graph) (e : Edge) : + ((D.edge e) ⁻¹' drawingMarks D).Finite := + Set.Finite.preimage (D.edge_injective e).injOn (drawingMarks_finite D) + +theorem marked_parameter_zero (D : FiniteIntersectionDrawing graph) (e : Edge) : + (0 : unitInterval) ∈ (D.edge e) ⁻¹' drawingMarks D := by + exact Or.inl ⟨graph.src e,(D.edge e).source.symm⟩ + +theorem marked_parameter_one (D : FiniteIntersectionDrawing graph) (e : Edge) : + (1 : unitInterval) ∈ (D.edge e) ⁻¹' drawingMarks D := by + exact Or.inl ⟨graph.dst e,(D.edge e).target.symm⟩ + +theorem unmarked_edge_point_interior (D : FiniteIntersectionDrawing graph) (e : Edge) + (t : unitInterval) (ht : D.edge e t ∉ drawingMarks D) : t ∈ Set.Ioo (0 : unitInterval) 1 := by + have ht0 : t ≠ 0 := by + intro he + subst t + exact ht (marked_parameter_zero D e) + have ht1 : t ≠ 1 := by + intro he + subst t + exact ht (marked_parameter_one D e) + exact ⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩ + +theorem unmarked_intersection_same_edge (D : FiniteIntersectionDrawing graph) + (e f : Edge) (s t : unitInterval) + (he : D.edge e s=D.edge f t) (hs : D.edge e s ∉ drawingMarks D) : e=f := by + by_contra hef + have hsi := unmarked_edge_point_interior D e s hs + have hti := unmarked_edge_point_interior D f t (he ▸ hs) + exact hs (Or.inr ⟨e,f,hef,⟨s,hsi,rfl⟩,⟨t,hti,he.symm⟩⟩) + +end Paper170Geometry + +end +end + +section + +/-! Increasing enumeration of the actual marked parameters, with both endpoints. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +theorem exists_sorted_drawing_parameters [Fintype Vertex] (D : FiniteIntersectionDrawing graph) + (e : Edge) : + ∃ k : ℕ, 0 < k ∧ ∃ t : Fin (k+1) → unitInterval, + StrictMono t ∧ t 0=0 ∧ t (Fin.last k)=1 ∧ + Set.range t=(D.edge e) ⁻¹' drawingMarks D := by + obtain ⟨k,hk,t,ht,h0,h1,hR⟩ := exists_sorted_unitInterval_finset (marked_parameters_finite D e).toFinset + (by simpa using marked_parameter_zero D e) (by simpa using marked_parameter_one D e) + exact ⟨k,hk,t,ht,h0,h1,by simpa using hR⟩ + +end Paper170Geometry + +end +end + +section + +/-! Refine an actual polygonal path at any prescribed finite set of parameters. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +theorem exists_marked_polygonal_subdivision [Fintype Vertex] (D : Paper170.AdmissibleDrawing graph) + (hpoly : ∀ e, HasFiniteAffineCover (D.edge e)) : + ∃ P : ∀ e, PolygonalParametrization (D.edge e), + ∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot := by + classical + have hex (e : Edge) := (hpoly e).refine (marked_parameters_finite D.toFiniteIntersectionDrawing e).toFinset + choose P hP using hex + exact ⟨P,fun e t ht => hP e (by simpa using ht)⟩ + +end Paper170Geometry + +end +end + +section + +/-! Actual subdivision segments, parameter witnesses, and marked-point endpoints. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem subdivision_mark_endpoint (D : Paper170.AdmissibleDrawing graph) + (P : ∀ e, PolygonalParametrization (D.edge e)) + (hmark : ∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) + (e : Edge) (i : Fin (P e).pieces) (x : Plane) + (hx : x ∈ (P e).pieceTrace i) (hm : x ∈ drawingMarks D.toFiniteIntersectionDrawing) : + x=D.edge e ((P e).knot i.castSucc) ∨ x=D.edge e ((P e).knot i.succ) := by + obtain ⟨t,ht⟩ := (P e).pieceTrace_subset_range i hx + obtain ⟨j,hj⟩ := hmark e t (ht.symm ▸ hm) + have he : D.edge e ((P e).knot j)=x := (congrArg (D.edge e) hj).trans ht + have hh := (P e).pieceTrace_knot_endpoint (D.edge_injective e) i j (he.symm ▸ hx) + simpa only [he] using hh + +end Paper170Geometry + +end +end + +section + +/-! Refined segments of the actual drawing meet only at common subdivision endpoints. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem drawing_curve_meeting_mark (D : Paper170.AdmissibleDrawing graph) (e f : Edge) + (hef : e ≠ f) (x : Plane) (hx : x ∈ Set.range (D.edge e)) (hy : x ∈ Set.range (D.edge f)) : + x ∈ drawingMarks D.toFiniteIntersectionDrawing := by + obtain ⟨s,hs⟩ := hx + obtain ⟨t,ht⟩ := hy + by_cases hs0 : s=0 + · subst s + exact Or.inl ⟨(graph.src e),by simpa using hs⟩ + by_cases hs1 : s=1 + · subst s + exact Or.inl ⟨(graph.dst e),by simpa using hs⟩ + by_cases ht0 : t=0 + · subst t + exact Or.inl ⟨(graph.src f),by simpa using ht⟩ + by_cases ht1 : t=1 + · subst t + exact Or.inl ⟨(graph.dst f),by simpa using ht⟩ + exact Or.inr ⟨e,f,hef, + ⟨s,⟨lt_of_le_of_ne (show 0 ≤ s from s.property.1) (Ne.symm hs0), + lt_of_le_of_ne (show s ≤ 1 from s.property.2) hs1⟩,hs⟩, + ⟨t,⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩,ht⟩⟩ + +abbrev DrawingPiece {D : Paper170.AdmissibleDrawing graph} (P : ∀ e, PolygonalParametrization (D.edge e)) := + (e : Edge) × Fin (P e).pieces + +def drawingPieceStart {D : Paper170.AdmissibleDrawing graph} (P : ∀ e, PolygonalParametrization (D.edge e)) + (i : DrawingPiece P) : Plane := D.edge i.1 ((P i.1).knot i.2.castSucc) + +def drawingPieceEnd {D : Paper170.AdmissibleDrawing graph} (P : ∀ e, PolygonalParametrization (D.edge e)) + (i : DrawingPiece P) : Plane := D.edge i.1 ((P i.1).knot i.2.succ) + +theorem drawingPiece_endpoints_ne {D : Paper170.AdmissibleDrawing graph} + (P : ∀ e, PolygonalParametrization (D.edge e)) (i : DrawingPiece P) : + drawingPieceStart P i ≠ drawingPieceEnd P i := by + intro he + have hh := D.edge_injective i.1 he + exact ((P i.1).increasing (show i.2.castSucc < i.2.succ by change i.2.val < i.2.val+1; omega)).ne hh + +theorem drawing_pieces_meeting_endpoints (D : Paper170.AdmissibleDrawing graph) + (P : ∀ e, PolygonalParametrization (D.edge e)) + (hmark : ∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) + (p q : DrawingPiece P) (hpq : p ≠ q) (x : Plane) + (hx : x ∈ segment ℝ (drawingPieceStart P p) (drawingPieceEnd P p)) + (hy : x ∈ segment ℝ (drawingPieceStart P q) (drawingPieceEnd P q)) : + (x=drawingPieceStart P p ∨ x=drawingPieceEnd P p) ∧ + (x=drawingPieceStart P q ∨ x=drawingPieceEnd P q) := by + rcases p with ⟨e,i⟩ + rcases q with ⟨f,j⟩ + by_cases hef : e=f + · subst f + have hij : i ≠ j := fun he => hpq (by subst j; rfl) + exact ⟨(P e).pieceTrace_other_piece_endpoint (D.edge_injective e) i j hij x hx hy, + (P e).pieceTrace_other_piece_endpoint (D.edge_injective e) j i (Ne.symm hij) x hy hx⟩ + · have hm := drawing_curve_meeting_mark D e f hef x + ((P e).pieceTrace_subset_range i hx) ((P f).pieceTrace_subset_range j hy) + exact ⟨subdivision_mark_endpoint D P hmark e i x hx hm, + subdivision_mark_endpoint D P hmark f j x hy hm⟩ + +end Paper170Geometry + +end +end + +section + +/-! The actual straight embedded graph formed by refined drawing segments. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D : Paper170.AdmissibleDrawing graph} + +def drawingSubdivisionGraph (P : ∀ e, PolygonalParametrization (D.edge e)) : SimpleGraph Plane where + Adj := fun a b => a ≠ b ∧ ∃ p : DrawingPiece P, + (a=drawingPieceStart P p ∧ b=drawingPieceEnd P p) ∨ + (a=drawingPieceEnd P p ∧ b=drawingPieceStart P p) + symm := ⟨by + rintro a b ⟨hab,p,hp⟩ + refine ⟨Ne.symm hab,p,?_⟩ + rcases hp with ⟨ha,hb⟩ | ⟨ha,hb⟩ + · exact Or.inr ⟨hb,ha⟩ + · exact Or.inl ⟨hb,ha⟩⟩ + loopless := ⟨by rintro a ⟨ha,_⟩; exact ha rfl⟩ + +theorem drawingSubdivisionGraph_piece_adj (P : ∀ e, PolygonalParametrization (D.edge e)) + (p : DrawingPiece P) : + (drawingSubdivisionGraph P).Adj (drawingPieceStart P p) (drawingPieceEnd P p) := + ⟨drawingPiece_endpoints_ne P p,p,Or.inl ⟨rfl,rfl⟩⟩ + +theorem common_endpoint_alternatives (a b c d x : Plane) (hab : x=a ∨ x=b) (hcd : x=c ∨ x=d) : + (a=c ∧ x=a) ∨ (a=d ∧ x=a) ∨ (b=c ∧ x=b) ∨ (b=d ∧ x=b) := by + rcases hab with ha | hb <;> rcases hcd with hc | hd + · exact Or.inl ⟨ha.symm.trans hc,ha⟩ + · exact Or.inr (Or.inl ⟨ha.symm.trans hd,ha⟩) + · exact Or.inr (Or.inr (Or.inl ⟨hb.symm.trans hc,hb⟩)) + · exact Or.inr (Or.inr (Or.inr ⟨hb.symm.trans hd,hb⟩)) + +theorem drawingSubdivisionGraph_embedding (P : ∀ e, PolygonalParametrization (D.edge e)) + (hmark : ∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) : + StraightEdgeEmbedding (drawingSubdivisionGraph P) id := by + refine ⟨Function.injective_id,?_⟩ + rintro a b c d ⟨hab,p,hp⟩ ⟨hcd,q,hq⟩ x hx hy + by_cases hpq : p=q + · subst q + rcases hp with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ <;> rcases hq with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact Or.inl ⟨rfl,rfl⟩ + · exact Or.inr (Or.inl ⟨rfl,rfl⟩) + · exact Or.inr (Or.inl ⟨rfl,rfl⟩) + · exact Or.inl ⟨rfl,rfl⟩ + · have hxp : x ∈ segment ℝ (drawingPieceStart P p) (drawingPieceEnd P p) := by + rcases hp with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hx + · simpa only [id_eq,segment_symm] using hx + have hxq : x ∈ segment ℝ (drawingPieceStart P q) (drawingPieceEnd P q) := by + rcases hq with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hy + · simpa only [id_eq,segment_symm] using hy + obtain ⟨hpe,hqe⟩ := drawing_pieces_meeting_endpoints D P hmark p q hpq x hxp hxq + have heab : x=a ∨ x=b := by + rcases hp with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hpe + · exact hpe.symm + have hecd : x=c ∨ x=d := by + rcases hq with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact hqe + · exact hqe.symm + exact Or.inr (Or.inr (common_endpoint_alternatives a b c d x heab hecd)) + +theorem drawingSubdivisionGraph_finite_support [Fintype Edge] (P : ∀ e, PolygonalParametrization (D.edge e)) : + {a : Plane | ∃ b, (drawingSubdivisionGraph P).Adj a b}.Finite := by + have hf : (Set.range (drawingPieceStart P) ∪ Set.range (drawingPieceEnd P)).Finite := + (Set.finite_range _).union (Set.finite_range _) + apply hf.subset + rintro a ⟨b,hab,p,hp⟩ + rcases hp with ⟨ha,hb⟩ | ⟨ha,hb⟩ + · exact Or.inl ⟨p,ha.symm⟩ + · exact Or.inr ⟨p,ha.symm⟩ + +end Paper170Geometry + +end +end + +section + +/-! Prescribed subdivision points cannot lie in the interior of a graph segment. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D : Paper170.AdmissibleDrawing graph} + +theorem subdivision_point_endpoint (P : ∀ e, PolygonalParametrization (D.edge e)) + (x : Plane) (hpoint : ∀ e t, D.edge e t=x → t ∈ Set.range (P e).knot) + (e : Edge) (i : Fin (P e).pieces) (hx : x ∈ (P e).pieceTrace i) : + x=D.edge e ((P e).knot i.castSucc) ∨ x=D.edge e ((P e).knot i.succ) := by + obtain ⟨t,ht⟩ := (P e).pieceTrace_subset_range i hx + obtain ⟨j,hj⟩ := hpoint e t ht + have he : D.edge e ((P e).knot j)=x := (congrArg (D.edge e) hj).trans ht + have hh := (P e).pieceTrace_knot_endpoint (D.edge_injective e) i j (he.symm ▸ hx) + simpa only [he] using hh + +theorem drawingSubdivisionGraph_point_endpoint (P : ∀ e, PolygonalParametrization (D.edge e)) + (x : Plane) (hpoint : ∀ e t, D.edge e t=x → t ∈ Set.range (P e).knot) + (a b : Plane) (hab : (drawingSubdivisionGraph P).Adj a b) (hx : x ∈ segment ℝ a b) : + x=a ∨ x=b := by + obtain ⟨hab,p,hp⟩ := hab + rcases hp with ⟨rfl,rfl⟩ | ⟨rfl,rfl⟩ + · exact subdivision_point_endpoint P x hpoint p.1 p.2 hx + · have hx' : x ∈ segment ℝ (drawingPieceStart P p) (drawingPieceEnd P p) := by + simpa only [segment_symm] using hx + exact (subdivision_point_endpoint P x hpoint p.1 p.2 hx').symm + +end Paper170Geometry + +end +end + +section + +/-! Each actual subdivided drawing edge is a simple walk of the constructed embedded graph. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D : Paper170.AdmissibleDrawing graph} + +theorem drawingEdgeSequence_adj (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : Edge) (i : ℕ) (hi : i < (P e).pieces) : + (drawingSubdivisionGraph P).Adj ((P e).vertices i) ((P e).vertices (i+1)) := by + let j : Fin (P e).pieces := ⟨i,hi⟩ + have h0 : (P e).vertices i=drawingPieceStart P ⟨e,j⟩ := (P e).vertices_at j.castSucc + have h1 : (P e).vertices (i+1)=drawingPieceEnd P ⟨e,j⟩ := (P e).vertices_at j.succ + rw [h0,h1] + exact drawingSubdivisionGraph_piece_adj P ⟨e,j⟩ + +def drawingEdgeWalk (P : ∀ e, PolygonalParametrization (D.edge e)) (e : Edge) : + (drawingSubdivisionGraph P).Walk (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))) := + (graphSequenceWalk (drawingSubdivisionGraph P) (P e).vertices (P e).pieces + (drawingEdgeSequence_adj P e)).copy (P e).vertices_first (P e).vertices_last + +theorem drawingEdgeWalk_length (P : ∀ e, PolygonalParametrization (D.edge e)) (e : Edge) : + (drawingEdgeWalk P e).length=(P e).pieces := by + simp only [drawingEdgeWalk,SimpleGraph.Walk.length_copy,graphSequenceWalk_length] + +theorem drawingEdgeWalk_getVert (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : Edge) (i : ℕ) (hi : i ≤ (P e).pieces) : + (drawingEdgeWalk P e).getVert i=(P e).vertices i := by + simp only [drawingEdgeWalk,SimpleGraph.Walk.getVert_copy] + exact graphSequenceWalk_getVert _ _ _ _ i hi + +theorem drawingEdgeWalk_isPath (P : ∀ e, PolygonalParametrization (D.edge e)) (e : Edge) : + (drawingEdgeWalk P e).IsPath := by + rw [drawingEdgeWalk,SimpleGraph.Walk.isPath_copy] + apply graphSequenceWalk_isPath + intro i hi j hj he + change i ≤ (P e).pieces at hi + change j ≤ (P e).pieces at hj + have h0 := (P e).vertices_at (⟨i,by omega⟩ : Fin ((P e).pieces+1)) + have h1 := (P e).vertices_at (⟨j,by omega⟩ : Fin ((P e).pieces+1)) + rw [h0,h1] at he + have hh := (P e).increasing.injective (D.edge_injective e he) + exact congrArg Fin.val hh + +theorem drawingEdgeWalk_uniqueVisit (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : Edge) (x : Plane) : UniqueWalkVisit (drawingEdgeWalk P e) x := by + intro i j hi hj hix hjx + exact (drawingEdgeWalk_isPath P e).getVert_injOn hi hj (hix.trans hjx.symm) + +end Paper170Geometry + +end +end + +section + +/-! Exact equality of the actual edge trace and its subdivision-graph walk realization. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +variable {D : Paper170.AdmissibleDrawing graph} + +theorem drawingEdgeWalk_range_eq (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : Edge) : + Set.range (graphWalkPath id (drawingEdgeWalk P e))=Set.range (D.edge e) := by + apply Set.Subset.antisymm + · intro x hx + have hlen := drawingEdgeWalk_length P e + obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece (fun i => (drawingEdgeWalk P e).getVert i) + (drawingEdgeWalk P e).length (by rw [hlen]; exact (P e).pieces_pos) x hx + rw [hlen] at hi + rw [drawingEdgeWalk_getVert P e i (by omega),drawingEdgeWalk_getVert P e (i+1) (by omega)] at hxi + let j : Fin (P e).pieces := ⟨i,hi⟩ + have h0 : (P e).vertices i=D.edge e ((P e).knot j.castSucc) := (P e).vertices_at j.castSucc + have h1 : (P e).vertices (i+1)=D.edge e ((P e).knot j.succ) := (P e).vertices_at j.succ + rw [h0,h1] at hxi + exact (P e).pieceTrace_subset_range j hxi + · intro x hx + obtain ⟨i,hi⟩ := ((P e).range_pieceTrace_iff x).mp hx + apply polygonalArcPath_piece_subset_range (fun j => (drawingEdgeWalk P e).getVert j) + (drawingEdgeWalk P e).length i.val (by rw [drawingEdgeWalk_length]; exact i.isLt) + rw [drawingEdgeWalk_getVert P e i.val (by omega),drawingEdgeWalk_getVert P e (i.val+1) (by omega)] + have h0 : (P e).vertices i.val=D.edge e ((P e).knot i.castSucc) := (P e).vertices_at i.castSucc + have h1 : (P e).vertices (i.val+1)=D.edge e ((P e).knot i.succ) := (P e).vertices_at i.succ + rw [h0,h1] + exact hi + +end Paper170Geometry + +end +end + +section + +/-! Exact parameter-side control of actual graph-walk prefixes and suffixes. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +theorem graphWalkPath_range_cases {V : Type*} {G : SimpleGraph V} (pos : V → Plane) + {a b : V} (p : G.Walk a b) (x : Plane) (hx : x ∈ Set.range (graphWalkPath pos p)) : + x=pos a ∨ ∃ i, i < p.length ∧ x ∈ segment ℝ (pos (p.getVert i)) (pos (p.getVert (i+1))) := by + by_cases hp : p.length=0 + · change x ∈ Set.range (polygonalArcPath (fun i => pos (p.getVert i)) p.length) at hx + rw [hp] at hx + obtain ⟨t,ht⟩ := hx + exact Or.inl (by simpa [polygonalArcPath,p.getVert_zero] using ht.symm) + · exact Or.inr (polygonalArcPath_range_piece _ _ (by omega) x hx) + +variable {D : Paper170.AdmissibleDrawing graph} + +theorem drawingEdgeWalk_take_trace (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : Edge) (k : Fin ((P e).pieces+1)) : + Set.range (graphWalkPath id ((drawingEdgeWalk P e).take k.val)) ⊆ + D.edge e '' Set.Icc (0 : unitInterval) ((P e).knot k) := by + intro x hx + rcases graphWalkPath_range_cases id ((drawingEdgeWalk P e).take k.val) x hx with he | ⟨i,hi,hxi⟩ + · exact ⟨0,⟨le_rfl,((P e).knot k).property.1⟩,(D.edge e).source.trans he.symm⟩ + · have hil : i < (P e).pieces := by + rw [SimpleGraph.Walk.take_length,drawingEdgeWalk_length] at hi + omega + have hik : i+1 ≤ k.val := by + rw [SimpleGraph.Walk.take_length,drawingEdgeWalk_length] at hi + omega + simp only [id_eq,SimpleGraph.Walk.take_getVert] at hxi + rw [show min k.val i=i by omega,show min k.val (i+1)=i+1 by omega, + drawingEdgeWalk_getVert P e i (by omega),drawingEdgeWalk_getVert P e (i+1) (by omega)] at hxi + let j : Fin (P e).pieces := ⟨i,hil⟩ + have h0 : (P e).vertices i=D.edge e ((P e).knot j.castSucc) := (P e).vertices_at j.castSucc + have h1 : (P e).vertices (i+1)=D.edge e ((P e).knot j.succ) := (P e).vertices_at j.succ + rw [h0,h1] at hxi + obtain ⟨t,ht⟩ := (P e).pieceTrace_parameter j x hxi + have hbetween := intervalSegment_between ((P e).knot j.castSucc) ((P e).knot j.succ) t + ((P e).increasing.monotone (by change i ≤ i+1; omega)) + exact ⟨intervalSegment ((P e).knot j.castSucc) ((P e).knot j.succ) t, + ⟨(intervalSegment _ _ t).property.1,hbetween.2.trans ((P e).increasing.monotone hik)⟩,ht⟩ + +theorem drawingEdgeWalk_drop_trace (P : ∀ e, PolygonalParametrization (D.edge e)) + (e : Edge) (k : Fin ((P e).pieces+1)) : + Set.range (graphWalkPath id ((drawingEdgeWalk P e).drop k.val)) ⊆ + D.edge e '' Set.Icc ((P e).knot k) (1 : unitInterval) := by + intro x hx + rcases graphWalkPath_range_cases id ((drawingEdgeWalk P e).drop k.val) x hx with he | ⟨i,hi,hxi⟩ + · refine ⟨(P e).knot k,⟨le_rfl,((P e).knot k).property.2⟩,?_⟩ + have hh : (drawingEdgeWalk P e).getVert k.val=D.edge e ((P e).knot k) := + (drawingEdgeWalk_getVert P e k.val (by omega)).trans ((P e).vertices_at k) + exact hh.symm.trans he.symm + · have hil : k.val+i < (P e).pieces := by + rw [SimpleGraph.Walk.drop_length,drawingEdgeWalk_length] at hi + omega + simp only [id_eq,SimpleGraph.Walk.drop_getVert] at hxi + rw [drawingEdgeWalk_getVert P e (k.val+i) (by omega), + drawingEdgeWalk_getVert P e (k.val+(i+1)) (by omega)] at hxi + let j : Fin (P e).pieces := ⟨k.val+i,hil⟩ + have h0 : (P e).vertices (k.val+i)=D.edge e ((P e).knot j.castSucc) := (P e).vertices_at j.castSucc + have h1 : (P e).vertices (k.val+(i+1))=D.edge e ((P e).knot j.succ) := by + have hh : (P e).vertices (k.val+i+1)=D.edge e ((P e).knot j.succ) := (P e).vertices_at j.succ + simpa only [Nat.add_assoc] using hh + rw [h0,h1] at hxi + obtain ⟨t,ht⟩ := (P e).pieceTrace_parameter j x hxi + have hbetween := intervalSegment_between ((P e).knot j.castSucc) ((P e).knot j.succ) t + ((P e).increasing.monotone (by change k.val+i ≤ k.val+i+1; omega)) + refine ⟨intervalSegment ((P e).knot j.castSucc) ((P e).knot j.succ) t,⟨?_,?_⟩,ht⟩ + · exact ((P e).increasing.monotone (show k ≤ j.castSucc by change k.val ≤ k.val+i; omega)).trans hbetween.1 + · exact (intervalSegment _ _ t).property.2 + +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Hill.lean b/lean/OAI/Combinatorics/CompleteCrossing/Hill.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fdf4c62d1f4e38d1c1284f06e53bee74b5bfd95 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Hill.lean @@ -0,0 +1,283 @@ +import Mathlib.Algebra.BigOperators.Group.Finset.Defs +import Mathlib.Algebra.BigOperators.Intervals +import Mathlib.Algebra.Order.Archimedean.Real.Basic +import Mathlib.Algebra.Ring.Parity +import Mathlib.Data.Finset.Card +import Mathlib.Data.Finset.Prod +import Mathlib.Data.Fintype.Pi +import Mathlib.Data.Nat.Cast.Field +import Mathlib.Data.Nat.Choose.Basic +import Mathlib.Data.Nat.Choose.Cast +import Mathlib.Order.Interval.Finset.Nat +import Mathlib.Tactic.IntervalCases +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Ring +import Mathlib.Tactic.Zify + +namespace OAI + +/-! Harary–Hill arithmetic, residue-page definitions, and the even-order deletion inequality. -/ + +section + +/-! The Harary–Hill formula and two-page crossing counts. + +-/ + +open scoped BigOperators +noncomputable section +namespace Paper170 + +/-- The integer in the Harary–Hill formula. -/ +def hill (n : ℕ) : ℕ := + (n / 2 * ((n - 1) / 2) * ((n - 2) / 2) * ((n - 3) / 2)) / 4 + +/-- The two contiguous residue blocks used by the explicit drawing. -/ +def residueColor (n r : ℕ) : Bool := decide (r % n < n / 2) + +/-- Increasing four-tuples whose alternating edges occupy the same page. -/ +def crossingTuples (n : ℕ) : Finset (Fin 4 → Fin n) := by + classical + exact Finset.univ.filter (fun v => StrictMono v ∧ + residueColor n ((v 0).val + (v 2).val) = + residueColor n ((v 1).val + (v 3).val)) + +/-- Residues with the same color after a cyclic shift by k. -/ +def sameColorResidues (n k : ℕ) : Finset ℕ := + (Finset.range n).filter (fun r => residueColor n r = residueColor n (r + k)) + +/-- Cyclic starting points and the first two positive gaps in the source count. -/ +def sameColorGapTuples (n k : ℕ) : Finset (ℕ × ℕ × ℕ) := + ((Finset.range n) ×ˢ ((Finset.Icc 1 (k - 1)) ×ˢ (Finset.Icc 1 (n - k - 1)))).filter + (fun v => residueColor n (2 * v.1 + v.2.1 + v.2.2) = + residueColor n (2 * v.1 + v.2.1 + v.2.2 + k)) + +/-- Starting labels producing a prescribed diagonal-sum residue. -/ +def residueFiber (n b r : ℕ) : Finset ℕ := + (Finset.range n).filter (fun a => (2 * a + b) % n = r) + +/-- One parity class of the same-color residues. -/ +def sameColorResiduesParity (n k p : ℕ) : Finset ℕ := + (sameColorResidues n k).filter (fun r => r % 2 = p) + +/-- One parity class of the first-gap choices after a fixed offset. -/ +def firstGapParity (k b p : ℕ) : Finset ℕ := + (Finset.Icc 1 (k - 1)).filter (fun g => (g + b) % 2 = p) + +/-- The polynomial whose finite difference evaluates the crossing sum. -/ +def crossingAntiderivative (n k : ℤ) : ℤ := + k * (k - 1) * (n - k - 1) * (n - k - 2) + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators +namespace Paper170 + +theorem crossingAntiderivative_sub (n k : ℤ) : + crossingAntiderivative n k - crossingAntiderivative n (k - 1) = + 2 * (k - 1) * (n - k - 1) * (n - 2 * k) := by + unfold crossingAntiderivative + ring + +theorem hill_numerator_dvd (n : ℕ) : + 4 ∣ n / 2 * ((n - 1) / 2) * ((n - 2) / 2) * ((n - 3) / 2) := by + have h₂ : (n - 2) / 2 = n / 2 - 1 := by omega + have h₃ : (n - 3) / 2 = (n - 1) / 2 - 1 := by omega + rw [h₂, h₃] + convert Nat.mul_dvd_mul (Nat.two_dvd_mul_sub_one (n / 2)) + (Nat.two_dvd_mul_sub_one ((n - 1) / 2)) using 1 + ring + +theorem hill_even (s : ℕ) : hill (2 * s) = s * (s - 1) ^ 2 * (s - 2) / 4 := by + have h₁ : (2 * s - 1) / 2 = s - 1 := by omega + have h₂ : (2 * s - 2) / 2 = s - 1 := by omega + have h₃ : (2 * s - 3) / 2 = s - 2 := by omega + simp only [hill, Nat.mul_div_right s (by decide : 0 < 2), h₁, h₂, h₃] + congr 1 + ring + +theorem hill_odd (s : ℕ) : hill (2 * s + 1) = (s.choose 2) ^ 2 := by + have h₀ : (2 * s + 1) / 2 = s := by omega + have h₁ : (2 * s + 1 - 1) / 2 = s := by omega + have h₂ : (2 * s + 1 - 2) / 2 = s - 1 := by omega + have h₃ : (2 * s + 1 - 3) / 2 = s - 1 := by omega + have hdiv := Nat.two_dvd_mul_sub_one s + obtain ⟨a, ha⟩ := hdiv + rw [hill, h₀, h₁, h₂, h₃, Nat.choose_two_right] + have hp : s * s * (s - 1) * (s - 1) = 4 * a ^ 2 := by nlinarith [ha] + rw [hp, ha] + simp + +theorem hill_eq_floor_product {n : ℕ} (hn : 1 ≤ n) : + (hill n : ℝ) = (1 / 4 : ℝ) * (⌊(n : ℝ) / 2⌋ : ℝ) * + (⌊((n : ℝ) - 1) / 2⌋ : ℝ) * (⌊((n : ℝ) - 2) / 2⌋ : ℝ) * + (⌊((n : ℝ) - 3) / 2⌋ : ℝ) := by + by_cases hsmall : n < 3 + · interval_cases n <;> norm_num [hill] + have hf (j : ℕ) (hj : j ≤ n) : + (⌊((n : ℝ) - j) / 2⌋ : ℝ) = ((n - j) / 2 : ℕ) := by + rw [← Nat.cast_sub hj, show (2 : ℝ) = ((2 : ℕ) : ℝ) by rfl, + Int.floor_div_natCast, Int.floor_natCast] + norm_cast + rw [hill, Nat.cast_div (hill_numerator_dvd n) (by norm_num : (4 : ℝ) ≠ 0)] + have hf₀ := hf 0 (by omega) + have hf₁ := hf 1 (by omega) + have hf₂ := hf 2 (by omega) + have hf₃ := hf 3 (by omega) + simp only [Nat.cast_zero, sub_zero, Nat.sub_zero] at hf₀ + norm_num only [Nat.cast_one, Nat.cast_ofNat] at hf₁ hf₂ hf₃ + rw [hf₀, hf₁, hf₂, hf₃] + push_cast + ring + +theorem crossing_sum_partial {n m : ℕ} (hn : 3 ≤ n) (hm : 2 * m ≤ n) : + 2 * ∑ k ∈ Finset.Icc 1 m, (k - 1) * (n - k - 1) * (n - 2 * k) = + m * (m - 1) * (n - m - 1) * (n - m - 2) := by + induction m with + | zero => simp + | succ m ih => + rw [Finset.sum_Icc_succ_top (by omega : 1 ≤ m + 1), mul_add, + ih (by omega)] + by_cases hzero : m = 0 + · subst m; simp + have hm₁ : 1 ≤ m := by omega + zify + simp (disch := omega) only [Nat.cast_sub, Nat.cast_add, Nat.cast_mul, + Nat.cast_one, Nat.cast_ofNat] + ring + +theorem crossing_sum_telescope {n : ℕ} (hn : 3 ≤ n) : + (2 * ∑ k ∈ Finset.Icc 1 (n / 2), (k - 1) * (n - k - 1) * (n - 2 * k)) = + (n / 2) * (n / 2 - 1) * (n - n / 2 - 1) * (n - n / 2 - 2) := + crossing_sum_partial hn (by omega) + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators +namespace Paper170 + +theorem cyclic_count_pairing {n : ℕ} (hn : 3 ≤ n) : + (∑ k ∈ Finset.Icc 2 (n - 2), + (k - 1) * (n - k - 1) * (n - 2 * min k (n - k))) = + 2 * ∑ k ∈ Finset.Icc 1 (n / 2), (k - 1) * (n - k - 1) * (n - 2 * k) := by + let F : ℕ → ℕ := fun k => (k - 1) * (n - k - 1) * (n - 2 * min k (n - k)) + have hsym (k : ℕ) (hk : k ≤ n) : F (n - k) = F k := by + dsimp [F] + rw [Nat.sub_sub_self hk, min_comm] + ring + have hfull : (∑ k ∈ Finset.Icc 2 (n - 2), F k) = ∑ k ∈ Finset.Ico 1 n, F k := by + apply Finset.sum_subset + · intro k hk + simp only [Finset.mem_Icc, Finset.mem_Ico] at hk ⊢ + omega + · intro k hk hnot + simp only [Finset.mem_Ico, Finset.mem_Icc, not_and] at hk hnot + have he : k = 1 ∨ k = n - 1 := by omega + rcases he with rfl | rfl + · simp [F] + · have he : n - (n - 1) - 1 = 0 := by omega + simp [F, he] + have hsplit := Finset.sum_Ico_consecutive F (show 1 ≤ n / 2 + 1 by omega) + (show n / 2 + 1 ≤ n by omega) + have htail : (∑ k ∈ Finset.Ico (n / 2 + 1) n, F k) = + ∑ k ∈ Finset.Ico 1 (n - n / 2), F k := by + calc + _ = ∑ k ∈ Finset.Ico (n / 2 + 1) n, F (n - k) := by + apply Finset.sum_congr rfl + intro k hk + exact (hsym k (by have := (Finset.mem_Ico.mp hk).2; omega)).symm + _ = _ := by + simpa only [Nat.add_sub_cancel_left, Nat.add_sub_add_right] using + (Finset.sum_Ico_reflect F (n / 2 + 1) (m := n) (n := n) (by omega)) + have hlow : (∑ k ∈ Finset.Ico 1 (n - n / 2), F k) = + ∑ k ∈ Finset.Ico 1 (n / 2 + 1), F k := by + apply Finset.sum_subset + · intro k hk + simp only [Finset.mem_Ico] at hk ⊢ + omega + · intro k hk hnot + simp only [Finset.mem_Ico, not_and] at hk hnot + have he : n = 2 * k := by omega + subst n + simp [F, show 2 * k - k = k by omega] + have hterm : (∑ k ∈ Finset.Ico 1 (n / 2 + 1), F k) = + ∑ k ∈ Finset.Icc 1 (n / 2), (k - 1) * (n - k - 1) * (n - 2 * k) := by + rw [Finset.Ico_add_one_right_eq_Icc] + apply Finset.sum_congr rfl + intro k hk + dsimp [F] + rw [min_eq_left (by have := (Finset.mem_Icc.mp hk).2; omega)] + change (∑ k ∈ Finset.Icc 2 (n - 2), F k) = _ + rw [hfull, ← hsplit, htail, hlow, hterm] + omega + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +lemma four_mul_hill (n : ℕ) : + 4 * hill n = n / 2 * ((n - 1) / 2) * ((n - 2) / 2) * ((n - 3) / 2) := by + exact Nat.mul_div_cancel' (hill_numerator_dvd n) + +lemma four_mul_hill_even (s : ℕ) : + 4 * hill (2 * s) = s * (s - 1) ^ 2 * (s - 2) := by + rw [four_mul_hill] + have h0 : 2 * s / 2 = s := by omega + have h1 : (2 * s - 1) / 2 = s - 1 := by omega + have h2 : (2 * s - 2) / 2 = s - 1 := by omega + have h3 : (2 * s - 3) / 2 = s - 2 := by omega + rw [h0, h1, h2, h3] + ring + +lemma four_mul_hill_preceding (s : ℕ) : + 4 * hill (2 * s - 1) = (s - 1) ^ 2 * (s - 2) ^ 2 := by + rw [four_mul_hill] + have h0 : (2 * s - 1) / 2 = s - 1 := by omega + have h1 : (2 * s - 1 - 1) / 2 = s - 1 := by omega + have h2 : (2 * s - 1 - 2) / 2 = s - 2 := by omega + have h3 : (2 * s - 1 - 3) / 2 = s - 2 := by omega + rw [h0, h1, h2, h3] + ring + +lemma hill_deletion_relation (s : ℕ) : + (2 * s - 4) * hill (2 * s) = 2 * s * hill (2 * s - 1) := by + have hs : 2 * s - 4 = 2 * (s - 2) := by omega + apply Nat.eq_of_mul_eq_mul_left (by decide : 0 < 4) + calc + 4 * ((2 * s - 4) * hill (2 * s)) = + (2 * s - 4) * (4 * hill (2 * s)) := by ring + _ = (2 * s - 4) * (s * (s - 1) ^ 2 * (s - 2)) := by rw [four_mul_hill_even] + _ = 2 * s * ((s - 1) ^ 2 * (s - 2) ^ 2) := by rw [hs]; ring + _ = 4 * (2 * s * hill (2 * s - 1)) := by rw [← four_mul_hill_preceding]; ring + +lemma even_lower_bound_of_deletion (s c : ℕ) (hs : 3 ≤ s) + (h : 2 * s * hill (2 * s - 1) ≤ (2 * s - 4) * c) : hill (2 * s) ≤ c := by + rw [← hill_deletion_relation] at h + have hp : 0 < 2 * s - 4 := by omega + nlinarith + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Interpolation.lean b/lean/OAI/Combinatorics/CompleteCrossing/Interpolation.lean new file mode 100644 index 0000000000000000000000000000000000000000..f94eace5b7198cd36391937feb0d87f190ad746e --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Interpolation.lean @@ -0,0 +1,528 @@ +import OAI.Combinatorics.CompleteCrossing.AlgebraDefs +import OAI.Combinatorics.Crossing.TwoTriangleUnisolvence +import Mathlib.Algebra.BigOperators.Field +import Mathlib.Algebra.BigOperators.Fin +import Mathlib.Algebra.MvPolynomial.CommRing +import Mathlib.Algebra.MvPolynomial.Variables +import Mathlib.LinearAlgebra.FiniteDimensional.Basic +import Mathlib.RingTheory.MvPolynomial.Basic +import Mathlib.RingTheory.Polynomial.Basic +import Mathlib.Tactic.FinCases +import Mathlib.Tactic.Ring + +namespace OAI + +/-! Bivariate interpolation degrees, spaces, pairings, and polynomial tests. -/ + +section + +/-! Degree conventions and interpolation weights. + -/ + +open scoped BigOperators +noncomputable section + +namespace Paper170 + +theorem rectangle_membership (a b : ℕ) (P : Poly2) : + P ∈ rectangle a b ↔ P.degreeOf 0 ≤ a ∧ P.degreeOf 1 ≤ b := by + change P.degrees ≤ _ ↔ _ + rw [Multiset.le_iff_count] + simp [← MvPolynomial.degreeOf_def, Fin.forall_fin_two, Multiset.count_replicate] + +theorem box4_membership (d : ℕ) (P : Poly4) : + P ∈ box4 d ↔ ∀ i, P.degreeOf i ≤ d := by + change P.degrees ≤ _ ↔ _ + rw [Multiset.le_iff_count] + simp [← MvPolynomial.degreeOf_def] + +theorem symmetric_space_membership (s : ℕ) (P : Poly4) : + P ∈ endpointSymmetricSpace s ↔ + (∀ i, P.degreeOf i ≤ s - 2) ∧ swapFirstPair P = P ∧ swapSecondPair P = P := by + simp [endpointSymmetricSpace, box4_membership, sub_eq_zero, and_assoc] + +theorem derivative_product {ι : Type*} [Fintype ι] [DecidableEq ι] + (node : ι → ℝ) (i : ι) : + Zarankiewicz.derivativeAtNode node i = ∏ j ∈ Finset.univ.erase i, (node i - node j) := + Zarankiewicz.derivativeAtNode_eq_prod node i + +theorem weight_nonzero {ι : Type*} [Fintype ι] (node : ι → ℝ) + (hn : Function.Injective node) (i : ι) : nodeWeight node i ≠ 0 := by + classical + exact inv_ne_zero (Zarankiewicz.derivativeAtNode_ne_zero node hn i) + +theorem interpolation_weights {ι : Type*} [Fintype ι] (node : ι → ℝ) + (hn : Function.Injective node) (A : Polynomial ℝ) + (hA : A.degree < (Fintype.card ι - 1 : ℕ)) : + (∑ i, A.eval (node i) / Zarankiewicz.derivativeAtNode node i) = 0 := by + classical + exact Zarankiewicz.node_polynomial_moment node hn A hA + +theorem omitted_node_weight {ι : Type*} [Fintype ι] [DecidableEq ι] + (node : ι → ℝ) (hn : Function.Injective node) (i p : ι) (hip : i ≠ p) : + (node p - node i) * nodeWeight node p = + ((omittedNodePolynomial node i).derivative.eval (node p))⁻¹ := by + have hF : Zarankiewicz.nodePolynomial node = + (Polynomial.X - Polynomial.C (node i)) * omittedNodePolynomial node i := + Lagrange.nodal_eq_mul_nodal_erase (Finset.mem_univ i) + have hzero : (omittedNodePolynomial node i).eval (node p) = 0 := + Lagrange.eval_nodal_at_node (Finset.mem_erase.mpr ⟨hip.symm, Finset.mem_univ p⟩) + have hd : Zarankiewicz.derivativeAtNode node p = (node p - node i) * + (omittedNodePolynomial node i).derivative.eval (node p) := by + rw [Zarankiewicz.derivativeAtNode, hF, Polynomial.derivative_mul] + simp [hzero] + have hdiff : node p - node i ≠ 0 := sub_ne_zero.mpr (hn.ne hip.symm) + rw [nodeWeight, hd, mul_inv, ← mul_assoc, mul_inv_cancel₀ hdiff, one_mul] + +theorem weighted_chain_boundary {n : ℕ} (node : Fin n → ℝ) + (hn : Function.Injective node) (a b : ℕ) (ha : a + 1 < n) (hb : b + 1 < n) : + ∀ v, chainBoundary (weightedChain node a b) v = 0 := by + have hsum (k : ℕ) (hk : k + 1 < n) : ∑ i, nodeWeight node i * node i ^ k = 0 := by + simpa only [nodeWeight, div_eq_mul_inv, mul_comm] using + Zarankiewicz.node_power_moment node hn k (by simpa using hk) + have hz (i p : Fin n) : weightedChain node a b i p = + (nodeWeight node i * node i ^ a) * (nodeWeight node p * node p ^ b) := by + unfold weightedChain + ring + intro v + simp only [chainBoundary, hz, ← Finset.sum_mul, ← Finset.mul_sum, hsum a ha, hsum b hb, + zero_mul, mul_zero, sub_self] + +end Paper170 + +end +end + +section + +/-! Separate degree bounds for the local four-variable test polynomial. -/ +noncomputable section +open scoped BigOperators +namespace Paper170 + +theorem degreeOf_mul_bound {i : Fin 4} {P Q : Poly4} {a b : ℕ} + (hP : P.degreeOf i ≤ a) (hQ : Q.degreeOf i ≤ b) : (P*Q).degreeOf i ≤ a+b := + (MvPolynomial.degreeOf_mul_le i P Q).trans (Nat.add_le_add hP hQ) + +theorem degreeOf_liftUnivariate (i k : Fin 4) (U : Polynomial ℝ) : + (liftUnivariate i U).degreeOf k ≤ if k=i then U.natDegree else 0 := by + classical + unfold liftUnivariate + conv_lhs => rw [← Polynomial.sum_monomial_eq U, Polynomial.sum, map_sum] + apply (MvPolynomial.degreeOf_sum_le k _ _).trans + apply Finset.sup_le + intro a ha + rw [Polynomial.aeval_monomial] + change (MvPolynomial.C (U.coeff a) * MvPolynomial.X i ^ a).degreeOf k ≤ _ + apply (MvPolynomial.degreeOf_C_mul_le _ k _).trans + by_cases h : k=i + · subst k + simpa using Polynomial.le_natDegree_of_mem_supp a ha + · simp only [ite_eq_right h, MvPolynomial.degreeOf_X_pow_of_ne a h] + exact Nat.le_refl 0 + +theorem liftBivariate_eq_rename (i j : Fin 4) (B : Poly2) : + liftBivariate i j B = MvPolynomial.rename ![i,j] B := by + have hf : (MvPolynomial.X ∘ (![i,j] : Fin 2 → Fin 4)) = + (![MvPolynomial.X i, MvPolynomial.X j] : Fin 2 → Poly4) := by + funext k + fin_cases k <;> rfl + simp only [liftBivariate, MvPolynomial.rename_eq_aeval, hf] + +theorem degreeOf_rename_zero {σ : Type*} (f : σ → Fin 4) (B : MvPolynomial σ ℝ) + (k : Fin 4) (hk : ∀i, f i ≠ k) : (MvPolynomial.rename f B).degreeOf k = 0 := by + by_contra h + obtain ⟨i, _, hi⟩ := MvPolynomial.mem_vars_rename f B + (MvPolynomial.mem_vars_iff_degreeOf_ne_zero.mpr h) + exact hk i hi + +theorem degreeOf_liftBivariate13 (B : Poly2) (k : Fin 4) : + (liftBivariate 1 3 B).degreeOf k = ![0,B.degreeOf 0,0,B.degreeOf 1] k := by + have hi : Function.Injective (![1,3] : Fin 2 → Fin 4) := by + intro a b h + fin_cases a <;> fin_cases b <;> simp at h ⊢ + rw [liftBivariate_eq_rename] + fin_cases k + · exact degreeOf_rename_zero _ B 0 (by intro i; fin_cases i <;> decide) + · exact MvPolynomial.degreeOf_rename_of_injective hi 0 + · exact degreeOf_rename_zero _ B 2 (by intro i; fin_cases i <;> decide) + · exact MvPolynomial.degreeOf_rename_of_injective hi 1 + +theorem degreeOf_difference_bound (i j k : Fin 4) : + (MvPolynomial.X i - MvPolynomial.X j : Poly4).degreeOf k ≤ + max (if k=i then 1 else 0) (if k=j then 1 else 0) := by + simpa only [MvPolynomial.degreeOf_X] using + MvPolynomial.degreeOf_sub_le k (MvPolynomial.X i : Poly4) (MvPolynomial.X j) + +theorem local_test_degree (s : ℕ) (hs : 2 ≤ s) (P : Poly4) + (hP : P ∈ endpointSymmetricSpace s) (U V : Polynomial ℝ) + (hU : U.natDegree ≤ s) (hV : V.natDegree ≤ s) (B : Poly2) + (hB : B ∈ rectangle (s-1) (s-1)) : + localTestPolynomial P U V B ∈ box4 (2*s-1) := by + apply (box4_membership _ _).mpr + intro k + have hP := ((symmetric_space_membership s P).mp hP).1 k + have hB := (rectangle_membership _ _ B).mp hB + have h := degreeOf_mul_bound + (degreeOf_mul_bound + (degreeOf_mul_bound + (degreeOf_mul_bound + (degreeOf_mul_bound + (degreeOf_mul_bound hP (degreeOf_difference_bound 1 3 k)) + (degreeOf_difference_bound 1 2 k)) + (degreeOf_difference_bound 3 0 k)) + (degreeOf_liftUnivariate 0 k U)) + (degreeOf_liftUnivariate 2 k V)) + (Nat.le_of_eq (degreeOf_liftBivariate13 B k)) + change (localTestPolynomial P U V B).degreeOf k ≤ _ at h + fin_cases k <;> norm_num [Fin.ext_iff] at h ⊢ <;> omega + +end Paper170 + +end +end + +section + +/-! Interpolation moments remove row and column perturbations from the order pairing. -/ +noncomputable section +open scoped BigOperators +namespace Paper170 + +theorem evalTwo_monomial (u v : ℝ) (m : Fin 2 →₀ ℕ) (c : ℝ) : + evalTwo u v (MvPolynomial.monomial m c) = c*(u^m 0*v^m 1) := by + simp only [evalTwo, AlgHom.toLinearMap_apply, MvPolynomial.aeval_monomial, + Algebra.algebraMap_self, RingHom.id_apply] + rw [Finsupp.prod_fintype] + · simp [Fin.prod_univ_two] + · intro i + simp + +theorem weighted_evalTwo_second_zero {ι : Type*} [Fintype ι] + (node : ι → ℝ) (hn : Function.Injective node) (u : ℝ) (P : Poly2) + (hP : P.degreeOf 1 + 1 < Fintype.card ι) : + (∑q, evalTwo u (node q) P / Zarankiewicz.derivativeAtNode node q) = 0 := by + classical + rw [P.as_sum] + simp only [map_sum, Finset.sum_div] + rw [Finset.sum_comm] + apply Finset.sum_eq_zero + intro m hm + have hmdeg := MvPolynomial.le_degreeOf_of_mem_support 1 hm + have hz := Zarankiewicz.node_power_moment node hn (m 1) (by omega) + calc + (∑q, evalTwo u (node q) (MvPolynomial.monomial m (P.coeff m)) / + Zarankiewicz.derivativeAtNode node q) = + (P.coeff m*u^m 0) * ∑q, node q^m 1 / Zarankiewicz.derivativeAtNode node q := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro q _ + rw [evalTwo_monomial] + ring + _ = 0 := by rw [hz,mul_zero] + +theorem weighted_evalTwo_first_zero {ι : Type*} [Fintype ι] + (node : ι → ℝ) (hn : Function.Injective node) (v : ℝ) (P : Poly2) + (hP : P.degreeOf 0 + 1 < Fintype.card ι) : + (∑p, evalTwo (node p) v P / Zarankiewicz.derivativeAtNode node p) = 0 := by + classical + rw [P.as_sum] + simp only [map_sum, Finset.sum_div] + rw [Finset.sum_comm] + apply Finset.sum_eq_zero + intro m hm + have hmdeg := MvPolynomial.le_degreeOf_of_mem_support 0 hm + have hz := Zarankiewicz.node_power_moment node hn (m 0) (by omega) + calc + (∑p, evalTwo (node p) v (MvPolynomial.monomial m (P.coeff m)) / + Zarankiewicz.derivativeAtNode node p) = + (P.coeff m*v^m 1) * ∑p, node p^m 0 / Zarankiewicz.derivativeAtNode node p := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro p _ + rw [evalTwo_monomial] + ring + _ = 0 := by rw [hz,mul_zero] + +theorem weightedPairing_add {ι : Type*} [Fintype ι] (node : ι → ℝ) + (K L : ι → ι → ℝ) (A B : Poly2) : + weightedPairing node (fun p q => K p q+L p q) A B = + weightedPairing node K A B + weightedPairing node L A B := by + simp [weightedPairing, add_mul, add_div, Finset.sum_add_distrib] + +theorem evalTwo_difference_mul (u v : ℝ) (A B : Poly2) : + evalTwo u v ((MvPolynomial.X 0-MvPolynomial.X 1)*A*B) = + (u-v)*evalTwo u v A*evalTwo u v B := by + simp [evalTwo] + +theorem pairing_row_column_invariant {ι : Type*} [Fintype ι] + (s : ℕ) (hs : 2 ≤ s) (hc : Fintype.card ι = 2*s) + (node : ι → ℝ) (hn : Function.Injective node) (K : ι → ι → ℝ) + (r c : ι → ℝ) (A B : Poly2) + (hA : A ∈ rectangle (s-1) (s-2)) + (hB : B ∈ rectangle (s-2) (s-1)) : + weightedPairing node (fun p q => K p q+r p+c q) A B = + weightedPairing node K A B := by + classical + let C : Poly2 := (MvPolynomial.X 0-MvPolynomial.X 1)*A*B + have hC (i : Fin 2) : C.degreeOf i + 1 < Fintype.card ι := by + have hA := (rectangle_membership _ _ A).mp hA + have hB := (rectangle_membership _ _ B).mp hB + have h1 := MvPolynomial.degreeOf_mul_le i ((MvPolynomial.X 0-MvPolynomial.X 1)*A) B + have h2 := MvPolynomial.degreeOf_mul_le i (MvPolynomial.X 0-MvPolynomial.X 1) A + have h3 := MvPolynomial.degreeOf_sub_le i (MvPolynomial.X 0 : Poly2) (MvPolynomial.X 1) + change C.degreeOf i ≤ _ at h1 + rw [hc] + fin_cases i <;> norm_num [MvPolynomial.degreeOf_X, Fin.ext_iff] at h1 h2 h3 ⊢ <;> omega + have hr : weightedPairing node (fun p _ => r p) A B = 0 := by + unfold weightedPairing + apply Finset.sum_eq_zero + intro p _ + calc + (∑q, r p*(node p-node q)/ + (Zarankiewicz.derivativeAtNode node p*Zarankiewicz.derivativeAtNode node q)* + evalTwo (node p) (node q) A*evalTwo (node p) (node q) B) = + (r p/Zarankiewicz.derivativeAtNode node p) * + ∑q, evalTwo (node p) (node q) C/Zarankiewicz.derivativeAtNode node q := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro q _ + rw [show evalTwo (node p) (node q) C = _ from evalTwo_difference_mul _ _ A B] + ring + _ = 0 := by rw [weighted_evalTwo_second_zero node hn _ C (hC 1), mul_zero] + have hcol : weightedPairing node (fun _ q => c q) A B = 0 := by + unfold weightedPairing + rw [Finset.sum_comm] + apply Finset.sum_eq_zero + intro q _ + calc + (∑p, c q*(node p-node q)/ + (Zarankiewicz.derivativeAtNode node p*Zarankiewicz.derivativeAtNode node q)* + evalTwo (node p) (node q) A*evalTwo (node p) (node q) B) = + (c q/Zarankiewicz.derivativeAtNode node q) * + ∑p, evalTwo (node p) (node q) C/Zarankiewicz.derivativeAtNode node p := by + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro p _ + rw [show evalTwo (node p) (node q) C = _ from evalTwo_difference_mul _ _ A B] + ring + _ = 0 := by rw [weighted_evalTwo_first_zero node hn _ C (hC 0), mul_zero] + rw [weightedPairing_add, weightedPairing_add, hr, hcol, add_zero, add_zero] + +end Paper170 + +end +end + +section + +/-! Coefficient spaces for the even-node interpolation argument. -/ +noncomputable section +open scoped BigOperators +open Module +namespace Paper170 + +def exponentPair : (Fin 2 →₀ ℕ) ≃ ℕ × ℕ where + toFun m := (m 0, m 1) + invFun p := Finsupp.equivFunOnFinite.symm ![p.1, p.2] + left_inv m := by + ext i + fin_cases i <;> simp + right_inv p := by simp + +@[simp] theorem exponentPair_symm_zero (a b : ℕ) : exponentPair.symm (a,b) 0 = a := rfl +@[simp] theorem exponentPair_symm_one (a b : ℕ) : exponentPair.symm (a,b) 1 = b := rfl + +theorem rectangle_eq_restrictSupport (a b : ℕ) : + rectangle a b = MvPolynomial.restrictSupport ℝ {m | m 0 ≤ a ∧ m 1 ≤ b} := by + ext P + rw [rectangle_membership, MvPolynomial.mem_restrictSupport_iff] + simp only [MvPolynomial.degreeOf_le_iff, Set.subset_def, Finset.mem_coe, Set.mem_ofPred_eq] + exact ⟨fun h m hm => ⟨h.1 m hm, h.2 m hm⟩, + fun h => ⟨fun m hm => (h m hm).1, fun m hm => (h m hm).2⟩⟩ + +def rectangleExponentEquiv (a b : ℕ) : + {m : Fin 2 →₀ ℕ // m 0 ≤ a ∧ m 1 ≤ b} ≃ Fin (a+1) × Fin (b+1) where + toFun m := (⟨m.val 0, by omega⟩, ⟨m.val 1, by omega⟩) + invFun p := ⟨exponentPair.symm (p.1.val,p.2.val), by simp; omega⟩ + left_inv m := by + apply Subtype.ext + exact exponentPair.symm_apply_apply m.val + right_inv p := by rfl + +def rectangleBasis (a b : ℕ) : Basis (Fin (a+1) × Fin (b+1)) ℝ (rectangle a b) := + ((MvPolynomial.basisRestrictSupport ℝ _).reindex (rectangleExponentEquiv a b)).map + (LinearEquiv.ofEq _ _ (rectangle_eq_restrictSupport a b).symm) + +theorem rectangle_finite (a b : ℕ) : FiniteDimensional ℝ (rectangle a b) := + Module.Finite.of_basis (rectangleBasis a b) + +theorem rectangle_dimension (a b : ℕ) : + Module.finrank ℝ (rectangle a b) = (a+1)*(b+1) := by + rw [Module.finrank_eq_card_basis (rectangleBasis a b)] + simp + +/-- The coefficient-preserving bridge to the existing bivariate interpolation library. -/ +def toBiPolynomial : Poly2 ≃ₗ[ℝ] Zarankiewicz.BiPoly := + ((MvPolynomial.basisMonomials (Fin 2) ℝ).repr.trans + (Finsupp.domLCongr exponentPair)).trans Zarankiewicz.flattenBi.symm + +theorem toBiPolynomial_coeff (P : Poly2) (a b : ℕ) : + Zarankiewicz.biCoeff (toBiPolynomial P) a b = + P.coeff (exponentPair.symm (a,b)) := by + rw [← Zarankiewicz.flattenBi_apply] + change (Zarankiewicz.flattenBi (Zarankiewicz.flattenBi.symm _)) _ = _ + rw [LinearEquiv.apply_symm_apply] + rfl + +theorem toBiPolynomial_monomial (m : Fin 2 →₀ ℕ) (c : ℝ) : + toBiPolynomial (MvPolynomial.monomial m c) = + PolynomialModule.single ℝ (m 0) (PolynomialModule.single ℝ (m 1) c) := by + apply Zarankiewicz.bi_ext + intro a b + rw [toBiPolynomial_coeff] + simp only [MvPolynomial.coeff_monomial, Zarankiewicz.biCoeff, + PolynomialModule.coeff_single, Finsupp.single_apply] + by_cases hm : m = exponentPair.symm (a,b) + · subst m + simp + · have hne : m 0 ≠ a ∨ m 1 ≠ b := by + by_contra h + simp only [not_or, not_not] at h + apply hm + apply exponentPair.injective + exact Prod.ext h.1 h.2 + rcases hne with h | h + · simp [hm, h] + · by_cases ha : m 0 = a <;> simp [hm, h, ha] + +theorem toBiPolynomial_eval (P : Poly2) (u v : ℝ) : + Zarankiewicz.biEval u v (toBiPolynomial P) = evalTwo u v P := by + induction P using MvPolynomial.induction_on' with + | add P Q hP hQ => simp [hP, hQ] + | monomial m c => + rw [toBiPolynomial_monomial] + simp only [Zarankiewicz.biEval, LinearMap.comp_apply, PolynomialModule.eval_single, + map_smul, smul_eq_mul] + simp only [evalTwo, AlgHom.toLinearMap_apply, MvPolynomial.aeval_monomial, + Algebra.algebraMap_self, RingHom.id_apply] + rw [Finsupp.prod_fintype] + · simp [Fin.prod_univ_two] + ring + · intro i + simp + +theorem toBiPolynomial_bounded (a b : ℕ) (P : Poly2) (hP : P ∈ rectangle a b) : + Zarankiewicz.BiBounded (a+1) (b+1) (toBiPolynomial P) := by + obtain ⟨ha,hb⟩ := (rectangle_membership a b P).mp hP + constructor + · intro k hk + apply PolynomialModule.ext + apply Finsupp.ext + intro j + change Zarankiewicz.biCoeff (toBiPolynomial P) k j = 0 + rw [toBiPolynomial_coeff] + by_contra h + have := MvPolynomial.degreeOf_le_iff.mp ha _ (MvPolynomial.mem_support_iff.mpr h) + simp only [exponentPair_symm_zero] at this + omega + · intro k j hj + change Zarankiewicz.biCoeff (toBiPolynomial P) k j = 0 + rw [toBiPolynomial_coeff] + by_contra h + have := MvPolynomial.degreeOf_le_iff.mp hb _ (MvPolynomial.mem_support_iff.mpr h) + simp only [exponentPair_symm_one] at this + omega + +end Paper170 + +end +end + +section + +/-! Polynomial cycle tests and the span of products of bounded-degree polynomials. -/ +noncomputable section +open scoped BigOperators +namespace Paper170 + +def polynomialTestLinear {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) : Poly4 →ₗ[ℝ] ℝ := + ∑ i, ∑ p, ∑ k, ∑ q, + (J i p k q * nodeWeight node i * nodeWeight node p * nodeWeight node k * nodeWeight node q) • + evalFour (node i) (node p) (node k) (node q) + +theorem polynomialTestLinear_apply {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) (P : Poly4) : + polynomialTestLinear node J P = polynomialTest node J P := by + simp [polynomialTestLinear, polynomialTest] + +theorem evalFour_monomial (x u y v : ℝ) (m : Fin 4 →₀ ℕ) (c : ℝ) : + evalFour x u y v (MvPolynomial.monomial m c) = c * (x^m 0 * u^m 1 * y^m 2 * v^m 3) := by + simp only [evalFour, AlgHom.toLinearMap_apply, MvPolynomial.aeval_monomial, + Algebra.algebraMap_self, RingHom.id_apply] + rw [Finsupp.prod_fintype] + · simp [Fin.prod_univ_four] + · intro i + simp + +theorem polynomialTest_monomial {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (m : Fin 4 →₀ ℕ) (c : ℝ) : + polynomialTest node J (MvPolynomial.monomial m c) = c * + chainPairing J (weightedChain node (m 0) (m 1)) (weightedChain node (m 2) (m 3)) := by + simp only [polynomialTest, evalFour_monomial, chainPairing, Finset.mul_sum, weightedChain] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro p _ + apply Finset.sum_congr rfl + intro k _ + apply Finset.sum_congr rfl + intro q _ + ring + +theorem polynomial_cycle_tests {n : ℕ} (hn : 2 ≤ n) (node : Fin n → ℝ) + (hnode : Function.Injective node) (J : CrossingTensor n) + (hcycles : ∀ z z' : Fin n → Fin n → ℝ, + (∀ v, chainBoundary z v = 0) → (∀ v, chainBoundary z' v = 0) → + chainPairing J z z' = 0) + (H : Poly4) (hH : H ∈ box4 (n-2)) : polynomialTest node J H = 0 := by + rw [← polynomialTestLinear_apply, H.as_sum, map_sum] + apply Finset.sum_eq_zero + intro m hm + rw [polynomialTestLinear_apply, polynomialTest_monomial] + have hb (i : Fin 4) : m i + 1 < n := by + have := MvPolynomial.degreeOf_le_iff.mp ((box4_membership (n-2) H).mp hH i) m hm + omega + rw [hcycles _ _ (weighted_chain_boundary node hnode _ _ (hb 0) (hb 1)) + (weighted_chain_boundary node hnode _ _ (hb 2) (hb 3)), mul_zero] + +theorem products_span_degree (s : ℕ) : + Submodule.span ℝ {P : Polynomial ℝ | ∃ U V : Polynomial ℝ, + U.natDegree ≤ s ∧ V.natDegree ≤ s ∧ P = U * V} = Polynomial.degreeLT ℝ (2*s+1) := by + classical + apply le_antisymm + · rw [Submodule.span_le] + rintro P ⟨U,V,hU,hV,rfl⟩ + change U * V ∈ Polynomial.degreeLT ℝ (2*s+1) + rw [Polynomial.mem_degreeLT, Polynomial.degree_lt_iff_coeff_zero] + intro k hk + apply Polynomial.coeff_eq_zero_of_natDegree_lt + have := Polynomial.natDegree_mul_le_of_le hU hV + omega + · rw [Polynomial.degreeLT_eq_span_X_pow, Submodule.span_le] + intro P hP + obtain ⟨k,hk,rfl⟩ := Finset.mem_image.mp hP + have hk : k ≤ 2*s := by rw [Finset.mem_range] at hk; omega + apply Submodule.subset_span + refine ⟨Polynomial.X ^ min k s, Polynomial.X ^ (k-min k s), ?_, ?_, ?_⟩ + · simp only [Polynomial.natDegree_X_pow] + exact min_le_right _ _ + · simp only [Polynomial.natDegree_X_pow] + omega + · rw [← pow_add, Nat.add_sub_of_le (min_le_left k s)] + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Isotropy.lean b/lean/OAI/Combinatorics/CompleteCrossing/Isotropy.lean new file mode 100644 index 0000000000000000000000000000000000000000..390bab5e2e2e99c49e01bcb85b9e3cdbc950c480 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Isotropy.lean @@ -0,0 +1,262 @@ +import OAI.Combinatorics.CompleteCrossing.PairSums +import OAI.Combinatorics.CompleteCrossing.Support + +namespace OAI + +/-! Isotropic evaluation image and order-pairing identities. -/ + +section + +noncomputable section +open scoped BigOperators Classical +open MvPolynomial +namespace Paper170 + +theorem evalFour_swap_first (P : Poly4) (x u y v : ℝ) : + evalFour x u y v (swapFirstPair P) = evalFour u x y v P := by + change aeval ![x, u, y, v] (rename (Equiv.swap (0 : Fin 4) 1) P) = aeval ![u, x, y, v] P + rw [aeval_rename] + congr 2 + funext i + fin_cases i <;> simp [Equiv.swap_apply_def] + +theorem evalFour_swap_second (P : Poly4) (x u y v : ℝ) : + evalFour x u y v (swapSecondPair P) = evalFour x u v y P := by + change aeval ![x, u, y, v] (rename (Equiv.swap (2 : Fin 4) 3) P) = aeval ![x, u, v, y] P + rw [aeval_rename] + congr 2 + funext i + fin_cases i <;> simp [Equiv.swap_apply_def] + +theorem evalFour_fullDifference (x u y v : ℝ) : + evalFour x u y v fullDifference = + (x - u) * (y - v) * (x - y) * (x - v) * (u - y) * (u - v) := by + simp [evalFour, fullDifference, collisionFactor] + ring + +def isotropicTerm {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) (P Q : Poly4) + (i p k q : Fin n) : ℝ := + J i p k q * nodeWeight node i * nodeWeight node p * nodeWeight node k * nodeWeight node q * + evalFour (node i) (node p) (node k) (node q) fullDifference * + evalFour (node i) (node p) (node k) (node q) P * + evalFour (node i) (node p) (node k) (node q) Q + +theorem isotropicTerm_first {n s : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (hJ : ∀ i p k q, J p i k q = -J i p k q) (P Q : endpointSymmetricSpace s) + (i p k q : Fin n) : + isotropicTerm node J P.val Q.val p i k q = isotropicTerm node J P.val Q.val i p k q := by + have hp := ((symmetric_space_membership s P.val).mp P.property).2.1 + have hq := ((symmetric_space_membership s Q.val).mp Q.property).2.1 + have hep := evalFour_swap_first P.val (node i) (node p) (node k) (node q) + have heq := evalFour_swap_first Q.val (node i) (node p) (node k) (node q) + rw [hp] at hep + rw [hq] at heq + unfold isotropicTerm + rw [hJ i p k q, ← hep, ← heq] + simp only [evalFour_fullDifference] + ring + +theorem isotropicTerm_second {n s : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (hJ : ∀ i p k q, J i p q k = -J i p k q) (P Q : endpointSymmetricSpace s) + (i p k q : Fin n) : + isotropicTerm node J P.val Q.val i p q k = isotropicTerm node J P.val Q.val i p k q := by + have hp := ((symmetric_space_membership s P.val).mp P.property).2.2 + have hq := ((symmetric_space_membership s Q.val).mp Q.property).2.2 + have hep := evalFour_swap_second P.val (node i) (node p) (node k) (node q) + have heq := evalFour_swap_second Q.val (node i) (node p) (node k) (node q) + rw [hp] at hep + rw [hq] at heq + unfold isotropicTerm + rw [hJ i p k q, ← hep, ← heq] + simp only [evalFour_fullDifference] + ring + +theorem isotropicTerm_vanish {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (P Q : Poly4) (i p k q : Fin n) + (h : i = p ∨ k = q ∨ i = k ∨ i = q ∨ p = k ∨ p = q ∨ J i p k q = 0) : + isotropicTerm node J P Q i p k q = 0 := by + rcases h with h | h | h | h | h | h | h <;> + simp [isotropicTerm, evalFour_fullDifference, h] + +theorem support_sum_eq_upper {n : ℕ} (J : CrossingTensor n) + (f : Fin n → Fin n → Fin n → Fin n → ℝ) + (hzero : ∀ i p k q, i = k ∨ i = q ∨ p = k ∨ p = q ∨ J i p k q = 0 → f i p k q = 0) : + (∑ a : SupportCoord J, f a.val.1.1 a.val.1.2 a.val.2.1 a.val.2.2) = + upperPairSum (fun i p => upperPairSum (f i p)) := by + let F (a : (Fin n × Fin n) × (Fin n × Fin n)) := f a.1.1 a.1.2 a.2.1 a.2.2 + change (∑ a : SupportCoord J, F a.val) = _ + rw [Finset.sum_coe_sort (supportedPairs J) F] + simp only [supportedPairs, Finset.sum_filter, Fintype.sum_prod_type, upperPairSum, F] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro p _ + by_cases hip : i < p + · simp only [hip, true_and, ite_true] + apply Finset.sum_congr rfl + intro k _ + apply Finset.sum_congr rfl + intro q _ + by_cases hkq : k < q + · simp only [hkq, true_and, ite_true] + by_cases hgood : i ≠ k ∧ i ≠ q ∧ p ≠ k ∧ p ≠ q ∧ J i p k q ≠ 0 + · simp [hgood] + · have hz : f i p k q = 0 := hzero i p k q (by tauto) + simp [hz] + · simp [hkq] + · simp [hip] + +theorem supportBilinear_eq_isotropicSum {n s : ℕ} (node : Fin n → ℝ) + (J : CrossingTensor n) (P Q : endpointSymmetricSpace s) : + supportBilinear node J (supportEvaluation s node J P) (supportEvaluation s node J Q) = + upperPairSum (fun i p => upperPairSum (isotropicTerm node J P.val Q.val i p)) := by + calc + _ = ∑ a : SupportCoord J, isotropicTerm node J P.val Q.val + a.val.1.1 a.val.1.2 a.val.2.1 a.val.2.2 := by + simp only [supportBilinear, Matrix.toBilin'_apply, Matrix.diagonal_apply, + mul_ite, ite_mul, mul_zero, zero_mul, Finset.sum_ite_eq, Finset.mem_univ, ite_true] + apply Finset.sum_congr rfl + intro a _ + change evalFour _ _ _ _ P.val * supportDiagonal node J a * evalFour _ _ _ _ Q.val = _ + unfold supportDiagonal isotropicTerm + ring + _ = _ := support_sum_eq_upper J _ (fun i p k q h => + isotropicTerm_vanish node J P.val Q.val i p k q (Or.inr (Or.inr h))) + +theorem isotropic_test_degree {s : ℕ} (hs : 2 ≤ s) (P Q : endpointSymmetricSpace s) : + P.val * Q.val * fullDifference ∈ box4 (2 * s - 1) := by + apply (box4_membership _ _).mpr + intro i + have hΔ : fullDifference.degreeOf i ≤ 3 := by + have h := degreeOf_mul_bound + (degreeOf_mul_bound (degreeOf_difference_bound 0 1 i) (degreeOf_difference_bound 2 3 i)) + (le_of_eq (collision_factor_properties.2.2.2 i)) + fin_cases i <;> norm_num [fullDifference] at h ⊢ <;> exact h + have hp := ((symmetric_space_membership s P.val).mp P.property).1 i + have hq := ((symmetric_space_membership s Q.val).mp Q.property).1 i + exact (degreeOf_mul_bound (degreeOf_mul_bound hp hq) hΔ).trans (by omega) + +theorem polynomialTest_isotropic {n s : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (hfirst : ∀ i p k q, J p i k q = -J i p k q) + (hsecond : ∀ i p k q, J i p q k = -J i p k q) + (P Q : endpointSymmetricSpace s) : + polynomialTest node J (P.val * Q.val * fullDifference) = + 4 * supportBilinear node J (supportEvaluation s node J P) (supportEvaluation s node J Q) := by + rw [supportBilinear_eq_isotropicSum] + have hterm : polynomialTest node J (P.val * Q.val * fullDifference) = + ∑ i, ∑ p, ∑ k, ∑ q, isotropicTerm node J P.val Q.val i p k q := by + unfold polynomialTest + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro p _ + apply Finset.sum_congr rfl + intro k _ + apply Finset.sum_congr rfl + intro q _ + rw [evalFour_mul, evalFour_mul] + unfold isotropicTerm + ring + rw [hterm] + exact sum_symmetric_quad _ (isotropicTerm_first node J hfirst P Q) + (isotropicTerm_second node J hsecond P Q) + (fun i k q => isotropicTerm_vanish node J P.val Q.val i i k q (Or.inl rfl)) + (fun i p k => isotropicTerm_vanish node J P.val Q.val i p k k (Or.inr (Or.inl rfl))) + +theorem evaluation_image_isotropic {s : ℕ} (hs : 2 ≤ s) (node : Fin (2 * s + 1) → ℝ) + (_hnode : Function.Injective node) (J : CrossingTensor (2 * s + 1)) + (_orders : ∀ i : Fin (2 * s + 1), LinearOrder {j : Fin (2 * s + 1) // j ≠ i}) + (_hloopLeft : ∀ i k q, J i i k q = 0) + (_hloopRight : ∀ i p k, J i p k k = 0) + (hreverseLeft : ∀ i p k q, J p i k q = -J i p k q) + (hreverseRight : ∀ i p k q, J i p q k = -J i p k q) + (_hskew : ∀ i p k q, J k q i p = -J i p k q) + (_hlocal : ∀ i (p q : {j : Fin (2 * s + 1) // j ≠ i}), + J i p.val i q.val = halfOrder (_orders i) p q) + (htests : ∀ H ∈ box4 (2 * s - 1), polynomialTest node J H = 0) + (P Q : endpointSymmetricSpace s) : + supportBilinear node J (supportEvaluation s node J P) (supportEvaluation s node J Q) = 0 := by + have h := htests _ (isotropic_test_degree hs P Q) + rw [polynomialTest_isotropic node J hreverseLeft hreverseRight P Q] at h + linarith + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators Classical +namespace Paper170 + +theorem weightedPairing_diagonal_invariant {ι : Type*} [Fintype ι] + (node : ι → ℝ) (K L : ι → ι → ℝ) (h : ∀p q, p≠q → K p q=L p q) + (A B : Poly2) : weightedPairing node K A B=weightedPairing node L A B := by + unfold weightedPairing + apply Finset.sum_congr rfl + intro p _ + apply Finset.sum_congr rfl + intro q _ + by_cases hpq : p=q + · subst q + simp + · rw [h p q hpq] + +theorem support_swap_mem {n : ℕ} (J : CrossingTensor n) + (hskew : ∀i p k q, J k q i p = -J i p k q) + (a : SupportCoord J) : (a.val.2,a.val.1)∈supportedPairs J := by + obtain ⟨h01,h23,h02,h03,h12,h13,hJ⟩ := (Finset.mem_filter.mp a.property).2 + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,h23,h01,h02.symm,h12.symm,h03.symm,h13.symm,?_⟩ + rwa [hskew,neg_ne_zero] + +def supportEdgeSwap {n : ℕ} (J : CrossingTensor n) + (hskew : ∀i p k q, J k q i p = -J i p k q) (a : SupportCoord J) : SupportCoord J := + ⟨(a.val.2,a.val.1),support_swap_mem J hskew a⟩ + +theorem supportEdgeSwap_involutive {n : ℕ} (J : CrossingTensor n) + (hskew : ∀i p k q, J k q i p = -J i p k q) : + Function.Involutive (supportEdgeSwap J hskew) := fun _ => Subtype.ext rfl + +theorem supportEdgeSwap_ne {n : ℕ} (J : CrossingTensor n) + (hskew : ∀i p k q, J k q i p = -J i p k q) (a : SupportCoord J) : + supportEdgeSwap J hskew a ≠ a := by + intro he + have h02 := (Finset.mem_filter.mp a.property).2.2.2.1 + exact h02 (congrArg (fun a : SupportCoord J => a.val.1.1) he).symm + +theorem supportDiagonal_swap {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (hskew : ∀i p k q, J k q i p = -J i p k q) (a : SupportCoord J) : + supportDiagonal node J (supportEdgeSwap J hskew a) = -supportDiagonal node J a := by + unfold supportDiagonal supportEdgeSwap + dsimp only + rw [hskew] + simp only [evalFour_fullDifference] + ring + +theorem supportBilinear_symmetric {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (x y : SupportCoord J → ℝ) : supportBilinear node J x y=supportBilinear node J y x := by + simp only [supportBilinear,Matrix.toBilin'_apply,Matrix.diagonal_apply, + mul_ite,ite_mul,mul_zero,zero_mul,Finset.sum_ite_eq,Finset.mem_univ,ite_true] + apply Finset.sum_congr rfl + intro a _ + ring + +theorem supportDiagonal_swap_block {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (hskew : ∀i p k q, J k q i p = -J i p k q) (a : SupportCoord J) : + (Matrix.diagonal (supportDiagonal node J)).submatrix + ![a,supportEdgeSwap J hskew a] ![a,supportEdgeSwap J hskew a] = + Matrix.diagonal ![supportDiagonal node J a,-supportDiagonal node J a] := by + ext i j + fin_cases i <;> fin_cases j <;> + simp [Matrix.submatrix,Matrix.diagonal_apply,supportEdgeSwap_ne, + Ne.symm (supportEdgeSwap_ne J hskew a),supportDiagonal_swap] + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/LocalGeometry.lean b/lean/OAI/Combinatorics/CompleteCrossing/LocalGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..01882b8e8009464c39ad88e1e346998045f35d34 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/LocalGeometry.lean @@ -0,0 +1,254 @@ +import OAI.Combinatorics.CompleteCrossing.Plane +import OAI.Combinatorics.Crossing.LocalSegmentTransversality +import OAI.Combinatorics.Crossing.ProperCrossingLocality +import OAI.Combinatorics.Crossing.SegmentAffineForms +import Mathlib.Data.Fin.Tuple.Basic +import Mathlib.Topology.Separation.Hausdorff + +namespace OAI + +/-! Local straightness and transversality of normalized drawings. -/ + +section + +/-! Actual local line and adjacency properties used in the cycle-intersection proof. -/ +noncomputable section +open Zarankiewicz +namespace Paper170Geometry +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +structure NoAdjacentCrossings (D : Paper170.AdmissibleDrawing graph) : Prop where + eq_empty : ∀ e f : Edge, e≠f → + (graph.src e=graph.src f ∨ graph.src e=graph.dst f ∨ + graph.dst e=graph.src f ∨ graph.dst e=graph.dst f) → + Paper170.edgeInterior D.toContinuousDrawing e ∩ + Paper170.edgeInterior D.toContinuousDrawing f = ∅ + +structure LocallyStraightAt (D : Paper170.ContinuousDrawing graph) (e : Edge) (x : Plane) : Prop where + exists_line : ∃a b : Plane, a≠b ∧ x∈openSegmentTrace a b ∧ + ∃U : Set Plane, IsOpen U ∧ x∈U ∧ + ∀z∈U, z∈Paper170.edgeInterior D e ↔ z∈openSegmentTrace a b + +structure LocallyStraightCrossings (D : Paper170.AdmissibleDrawing graph) : Prop where + at_crossing : ∀e f : Edge, e≠f → ∀x, + x∈Paper170.edgeInterior D.toContinuousDrawing e → + x∈Paper170.edgeInterior D.toContinuousDrawing f → + LocallyStraightAt D.toContinuousDrawing e x ∧ LocallyStraightAt D.toContinuousDrawing f x + +structure LocallyTransverseCrossings (D : Paper170.AdmissibleDrawing graph) : Prop where + at_crossing : ∀e f : Edge, e≠f → ∀x, + x∈Paper170.edgeInterior D.toContinuousDrawing e → + x∈Paper170.edgeInterior D.toContinuousDrawing f → + ∃a b c d : Plane, det2 (b-a) (d-c)≠0 ∧ + x∈openSegmentTrace a b ∧ x∈openSegmentTrace c d ∧ + ∃U : Set Plane, IsOpen U ∧ x∈U ∧ + (∀z∈U, z∈Paper170.edgeInterior D.toContinuousDrawing e ↔ z∈openSegmentTrace a b) ∧ + (∀z∈U, z∈Paper170.edgeInterior D.toContinuousDrawing f ↔ z∈openSegmentTrace c d) + +theorem normalized_noAdjacent (N : Paper170.NormalizedDrawing graph) : + NoAdjacentCrossings N.toAdmissibleDrawing := + ⟨fun e f hef hadj => Set.disjoint_iff_inter_eq_empty.mp (N.no_adjacent e f hef hadj)⟩ + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Set Zarankiewicz +namespace Paper170Geometry + +/-- A point away from the subdivision knots lies strictly inside one piece. -/ +theorem parametrization_knot_interval {a b : Paper170.Plane} {γ : Path a b} + (P : Paper170.PolygonalParametrization γ) (t : unitInterval) + (ht : t ∈ Ioo (0 : unitInterval) 1) (hne : ∀i, t ≠ P.knot i) : + ∃i : Fin P.pieces, P.knot i.castSucc < t ∧ t < P.knot i.succ := by + classical + have hex : ∃i, t < P.knot i := ⟨Fin.last P.pieces, by simpa only [P.last] using ht.2⟩ + let j := Fin.find (fun i => t < P.knot i) hex + have hj : t < P.knot j := Fin.find_spec hex + have hj0 : j ≠ 0 := by + intro he + rw [he, P.first] at hj + exact (lt_asymm ht.1 hj) + obtain ⟨i, hi⟩ := Fin.exists_succ_eq_of_ne_zero hj0 + refine ⟨i, ?_, by simpa only [hi] using hj⟩ + have hm : ¬t < P.knot i.castSucc := Fin.find_min hex (by change i.castSucc < j; rw [← hi]; exact Fin.castSucc_lt_succ) + exact lt_of_le_of_ne (le_of_not_gt hm) (hne i.castSucc).symm + +/-- The open part of a subdivided path is exactly its open segment. -/ +theorem parametrization_open_piece {a b : Paper170.Plane} {γ : Path a b} + (P : Paper170.PolygonalParametrization γ) (i : Fin P.pieces) : + γ '' Ioo (P.knot i.castSucc) (P.knot i.succ) = + openSegmentTrace (P.vertices i.val) (P.vertices (i.val+1)) := by + have hab := P.increasing (Fin.castSucc_lt_succ (i := i)) + ext x + constructor + · rintro ⟨t, ht, rfl⟩ + obtain ⟨u, hu⟩ := intervalSegment_surjective_interval _ _ hab t ⟨ht.1.le, ht.2.le⟩ + have hu0 : 0 < (u : ℝ) := by + by_contra hn + have hue : u = 0 := Subtype.ext (le_antisymm (le_of_not_gt hn) u.property.1) + have he : P.knot i.castSucc = t := by simpa [hue, intervalSegment] using hu + exact ht.1.ne he + have hu1 : (u : ℝ) < 1 := by + by_contra hn + have hue : u = 1 := Subtype.ext (le_antisymm u.property.2 (le_of_not_gt hn)) + have he : P.knot i.succ = t := by simpa [hue, intervalSegment] using hu + exact ht.2.ne he.symm + refine ⟨u, ⟨hu0, hu1⟩, ?_⟩ + exact ((Paper170.toZarankiewiczParametrization P).segment_formula i u).symm.trans + (congrArg γ hu) + · rintro ⟨s, hs, rfl⟩ + let u : unitInterval := ⟨s, hs.1.le, hs.2.le⟩ + refine ⟨intervalSegment (P.knot i.castSucc) (P.knot i.succ) u, + intervalSegment_strict_between _ _ u hab hs, ?_⟩ + exact (Paper170.toZarankiewiczParametrization P).segment_formula i u + +/-- An injective polygonal path is locally a straight segment away from its knots. -/ +theorem locallyStraightAt_of_not_knot {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + (D : Paper170.ContinuousDrawing graph) (e : Edge) + (P : Paper170.PolygonalParametrization (D.edge e)) (t : unitInterval) + (ht : t ∈ Ioo (0 : unitInterval) 1) (hne : ∀i, t ≠ P.knot i) : + LocallyStraightAt D e (D.edge e t) := by + obtain ⟨i, hti⟩ := parametrization_knot_interval P t ht hne + have hem := (D.edge e).continuous.isClosedEmbedding (D.edge_injective e) + obtain ⟨U, hU, heq⟩ := hem.isInducing.isOpen_iff.mp + (isOpen_Ioo : IsOpen (Ioo (P.knot i.castSucc) (P.knot i.succ))) + have hpiece := parametrization_open_piece P i + have hsub : Ioo (P.knot i.castSucc) (P.knot i.succ) ⊆ Ioo (0 : unitInterval) 1 := by + intro s hs + exact ⟨lt_of_le_of_lt (P.knot i.castSucc).property.1 hs.1, + lt_of_lt_of_le hs.2 (P.knot i.succ).property.2⟩ + refine ⟨P.vertices i.val, P.vertices (i.val+1), ?_, ?_, U, hU, ?_, ?_⟩ + · exact fun he => P.direction_ne_zero (D.edge_injective e) i.val i.isLt (sub_eq_zero.mpr he.symm) + · rw [← hpiece] + exact ⟨t, hti, rfl⟩ + · change t ∈ (D.edge e) ⁻¹' U + rw [heq] + exact hti + · intro z hz + rw [← hpiece] + constructor + · rintro ⟨s, _, rfl⟩ + refine ⟨s, ?_, rfl⟩ + rw [← heq] + exact hz + · rintro ⟨s, hs, rfl⟩ + exact ⟨s, hsub hs, rfl⟩ + +theorem normalized_locallyStraight {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + (N : Paper170.NormalizedDrawing graph) : LocallyStraightCrossings N.toAdmissibleDrawing := by + refine ⟨?_⟩ + intro e f hef x hxe hxf + have hx : x ∈ Paper170.crossingPoints N.toContinuousDrawing := ⟨e, f, hef, hxe, hxf⟩ + have hlocal (g : Edge) (hg : x ∈ Paper170.edgeInterior N.toContinuousDrawing g) : + LocallyStraightAt N.toContinuousDrawing g x := by + obtain ⟨t, ht, rfl⟩ := hg + apply locallyStraightAt_of_not_knot N.toContinuousDrawing g (N.polygonal g) t ht + intro i he + exact N.crossings_not_knots g i (he ▸ hx) + exact ⟨hlocal e hxe, hlocal f hxf⟩ + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Set Zarankiewicz +open scoped Topology +namespace Paper170Geometry + +/-- A crossing chart makes the local intersection a single point. -/ +theorem properCrossing_locally_unique (A B : Set Paper170.Plane) (x : Paper170.Plane) + (h : Paper170.ProperCrossing A B x) : + ∃U : Set Paper170.Plane, IsOpen U ∧ x ∈ U ∧ + ∀y ∈ U, y ∈ A → y ∈ B → y = x := by + obtain ⟨chart, hx, hz, hA, hB⟩ := h.chart_exists + refine ⟨chart.source, chart.open_source, hx, ?_⟩ + intro y hy hyA hyB + have hyA' := (chart_image_mem_iff chart A {z | z.2=0} hA y hy).mp hyA + have hyB' := (chart_image_mem_iff chart B {z | z.1=0} hB y hy).mp hyB + apply chart.injOn hy hx + rw [hz] + exact Prod.ext hyB' hyA' + +/-- Two straight segments meeting locally only once have independent directions. -/ +theorem local_segment_directions_ne_zero (a b c d x : Plane) + (hab : a ≠ b) (hcd : c ≠ d) + (hxab : x ∈ openSegmentTrace a b) (hxcd : x ∈ openSegmentTrace c d) + (U : Set Plane) (hU : IsOpen U) (hxU : x ∈ U) + (hunique : ∀y ∈ U, y ∈ openSegmentTrace a b → y ∈ openSegmentTrace c d → y=x) : + det2 (b-a) (d-c) ≠ 0 := by + intro hdet + obtain ⟨s, hs, hsx⟩ := hxab + obtain ⟨t, ht, htx⟩ := hxcd + let k := dot2 (b-a) (d-c) / squaredLength (b-a) + have hparallel : d-c = k • (b-a) := vector_parallel_of_det_zero _ _ (sub_ne_zero.mpr hab.symm) hdet + let f : ℝ → Plane := fun r => x + r • (d-c) + have hf : Continuous f := by dsimp [f]; fun_prop + have hf0 : f 0 = x := by simp [f] + have hevent : ∀ᶠr : ℝ in 𝓝 0, + f r ∈ U ∧ s+r*k ∈ Ioo (0:ℝ) 1 ∧ t+r ∈ Ioo (0:ℝ) 1 := by + have h₁ := hf.continuousAt.eventually (show U ∈ 𝓝 (f 0) by simpa only [hf0] using hU.mem_nhds hxU) + have h₂ : ∀ᶠr : ℝ in 𝓝 0, s+r*k ∈ Ioo (0:ℝ) 1 := by + have hc : Continuous (fun r : ℝ => s+r*k) := by fun_prop + apply hc.continuousAt.eventually + change Ioo (0:ℝ) 1 ∈ 𝓝 (s+0*k) + simpa only [zero_mul, add_zero] using (isOpen_Ioo.mem_nhds hs) + have h₃ : ∀ᶠr : ℝ in 𝓝 0, t+r ∈ Ioo (0:ℝ) 1 := by + have hc : Continuous (fun r : ℝ => t+r) := by fun_prop + apply hc.continuousAt.eventually + change Ioo (0:ℝ) 1 ∈ 𝓝 (t+0) + simpa only [add_zero] using (isOpen_Ioo.mem_nhds ht) + filter_upwards [h₁, h₂, h₃] with r h₁ h₂ h₃ using ⟨h₁,h₂,h₃⟩ + obtain ⟨ε, hε, hsmall⟩ := Metric.eventually_nhds_iff.mp hevent + have he : dist (ε/2) (0:ℝ) < ε := by rw [Real.dist_eq, sub_zero, abs_of_pos (by positivity)]; linarith + obtain ⟨hfU, hs', ht'⟩ := hsmall he + have habf : segmentPoint a b (s+(ε/2)*k) = f (ε/2) := by + dsimp [f] + rw [segmentPoint_start_form, show x = a+s • (b-a) from hsx.symm.trans (segmentPoint_start_form a b s)] + rw [hparallel, smul_smul, add_smul] + abel + have hcdf : segmentPoint c d (t+ε/2) = f (ε/2) := by + dsimp [f] + rw [segmentPoint_start_form, show x = c+t • (d-c) from htx.symm.trans (segmentPoint_start_form c d t)] + rw [add_smul] + abel + have hfx : f (ε/2) = x := hunique _ hfU ⟨_,hs',habf⟩ ⟨_,ht',hcdf⟩ + have hzero : (ε/2) • (d-c) = 0 := by simpa only [f, add_eq_left] using hfx + exact (smul_eq_zero.mp hzero).elim (ne_of_gt (by positivity)) (sub_ne_zero.mpr hcd.symm) + +/-- Local straightness and the actual crossing charts imply transversality. -/ +theorem locallyTransverse_of_locallyStraight {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + (D : Paper170.AdmissibleDrawing graph) (h : LocallyStraightCrossings D) : + LocallyTransverseCrossings D := by + refine ⟨?_⟩ + intro e f hef x hxe hxf + obtain ⟨he,hf⟩ := h.at_crossing e f hef x hxe hxf + obtain ⟨a,b,hab,hxab,U,hU,hxU,hAU⟩ := he.exists_line + obtain ⟨c,d,hcd,hxcd,V,hV,hxV,hBV⟩ := hf.exists_line + obtain ⟨W,hW,hxW,hunique⟩ := properCrossing_locally_unique _ _ x (D.crossings_proper e f hef x hxe hxf) + have hdet : det2 (b-a) (d-c) ≠ 0 := by + apply local_segment_directions_ne_zero a b c d x hab hcd hxab hxcd (U∩V∩W) + ((hU.inter hV).inter hW) ⟨⟨hxU,hxV⟩,hxW⟩ + intro y hy hyA hyB + exact hunique y hy.2 ((hAU y hy.1.1).mpr hyA) ((hBV y hy.1.2).mpr hyB) + exact ⟨a,b,c,d,hdet,hxab,hxcd,U∩V,hU.inter hV,⟨hxU,hxV⟩, + fun y hy => hAU y hy.1,fun y hy => hBV y hy.2⟩ + +theorem normalized_locallyTransverse {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + (N : Paper170.NormalizedDrawing graph) : LocallyTransverseCrossings N.toAdmissibleDrawing := + locallyTransverse_of_locallyStraight N.toAdmissibleDrawing (normalized_locallyStraight N) + +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/LowerBound.lean b/lean/OAI/Combinatorics/CompleteCrossing/LowerBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfda969004c9b3c12af2e04b053aec062ff256d1 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/LowerBound.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.CompleteCrossing.Isotropy +import OAI.Combinatorics.CompleteCrossing.TriangleFactors +import OAI.Combinatorics.CompleteCrossing.VertexEvaluation + +namespace OAI + +/-! Polynomial injectivity and the lower bound on crossing-tensor support. -/ + +section + +/-! The polynomial lower-bound argument for complete graphs. -/ +noncomputable section +namespace Paper170 +section CrossingTensor + +variable {s : ℕ} (hs : 2 ≤ s) (node : Fin (2 * s + 1) → ℝ) + (hnode : Function.Injective node) (J : CrossingTensor (2 * s + 1)) + (orders : ∀ i : Fin (2 * s + 1), LinearOrder {j : Fin (2 * s + 1) // j ≠ i}) + (hloopLeft : ∀ i k q, J i i k q = 0) + (hloopRight : ∀ i p k, J i p k k = 0) + (hreverseLeft : ∀ i p k q, J p i k q = -J i p k q) + (hreverseRight : ∀ i p k q, J i p q k = -J i p k q) + (hskew : ∀ i p k q, J k q i p = -J i p k q) + (hlocal : ∀ i (p q : {j : Fin (2 * s + 1) // j ≠ i}), + J i p.val i q.val = halfOrder (orders i) p q) + (htests : ∀ H ∈ box4 (2 * s - 1), polynomialTest node J H = 0) + +include hs hnode orders hloopLeft hloopRight hreverseLeft hreverseRight hskew hlocal htests + +theorem kernel_diagonal_vanishing (P : endpointSymmetricSpace s) + (hP : supportEvaluation s node J P = 0) : + diagonalSpecialization P.val = 0 := + diagonal_zero_of_vertices s node hnode P (kernel_vertex_vanishing hs node hnode J orders + hloopLeft hloopRight hreverseLeft hreverseRight hskew hlocal htests P hP) + +theorem kernel_collision_divisibility (P : endpointSymmetricSpace s) + (hP : supportEvaluation s node J P = 0) : collisionFactor ∣ P.val := + collision_divides_of_diagonal_vanishing s P (kernel_diagonal_vanishing hs node hnode J orders + hloopLeft hloopRight hreverseLeft hreverseRight hskew hlocal htests P hP) + +theorem support_evaluation_injective : Function.Injective (supportEvaluation s node J) := + support_evaluation_injective_of_collision hs node hnode J + (kernel_collision_divisibility hs node hnode J orders hloopLeft hloopRight + hreverseLeft hreverseRight hskew hlocal htests) + +theorem support_cardinality_lower_bound : + 2 * (Nat.choose s 2) ^ 2 ≤ (supportedPairs J).card := + support_cardinality_of_injective_isotropic hs node hnode J + (support_evaluation_injective hs node hnode J orders hloopLeft hloopRight + hreverseLeft hreverseRight hskew hlocal htests) + (evaluation_image_isotropic hs node hnode J orders hloopLeft hloopRight + hreverseLeft hreverseRight hskew hlocal htests) + +end CrossingTensor +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Main.lean b/lean/OAI/Combinatorics/CompleteCrossing/Main.lean new file mode 100644 index 0000000000000000000000000000000000000000..bbb76af01755a1712567b4d96e46c05b0c60fbb3 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Main.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.CompleteCrossing.Counting +import OAI.Combinatorics.CompleteCrossing.CycleIdentity +import OAI.Combinatorics.CompleteCrossing.Deletion +import OAI.Combinatorics.CompleteCrossing.LowerBound +import OAI.Combinatorics.CompleteCrossing.Normalization +import OAI.Combinatorics.CompleteCrossing.TwoPage + +namespace OAI + +/-! Odd and even lower bounds, explicit attainment, and the ordinary complete-graph crossing formula. -/ + +section + +noncomputable section +open scoped BigOperators Classical +namespace Paper170 + +theorem complete_graph_odd_lower_bound (s : ℕ) (hs : 2 ≤ s) + (N : NormalizedDrawing (completeGraph (2 * s + 1))) : + (s.choose 2) ^ 2 ≤ crossingCount N.toAdmissibleDrawing := by + obtain ⟨O⟩ := spoke_orders_exist _ N + obtain ⟨orders, hlocal⟩ := complete_local_orders N O + obtain ⟨hleft, hright, hrevleft, hrevright, hskew⟩ := raw_cycle_symmetries N O + let node : Fin (2 * s + 1) → ℝ := fun i => i.val + have hn : Function.Injective node := by + intro i j h + exact Fin.ext (Nat.cast_injective h) + have ht (H : Poly4) (hH : H ∈ box4 (2 * s - 1)) : + polynomialTest node (rawCycleIntersection O) H = 0 := by + apply polynomial_cycle_tests (by omega) node hn (rawCycleIntersection O) + (raw_cycle_pairing N O) H + convert hH using 1 + congr 1 + have hl := support_cardinality_lower_bound hs node hn (rawCycleIntersection O) orders + hleft hright hrevleft hrevright hskew hlocal ht + have hu := signed_support_bound N O + omega + +lemma complete_graph_odd_lower_arbitrary (s : ℕ) (hs : 2 ≤ s) + (D : AdmissibleDrawing (completeGraph (2 * s + 1))) : hill (2 * s + 1) ≤ crossingCount D := by + obtain ⟨N, hN⟩ := polygonal_no_adjacent_normalization _ D + rw [hill_odd] + exact (complete_graph_odd_lower_bound s hs N).trans hN + +lemma complete_graph_even_lower_normalized (s : ℕ) (hs : 2 ≤ s) + (N : NormalizedDrawing (completeGraph (2 * s + 2))) : + hill (2 * s + 2) ≤ crossingCount N.toAdmissibleDrawing := by + obtain ⟨A, _, hA⟩ := vertex_deletion_count (2 * s + 1) (by omega) N + have hl : ∀ v, hill (2 * s + 1) ≤ crossingCount (A v) := + fun v => complete_graph_odd_lower_arbitrary s hs (A v) + have hh := Finset.sum_le_sum (s := Finset.univ) (fun v _ => hl v) + rw [hA] at hh + simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] at hh + have he : 2 * (s + 1) = 2 * s + 2 := by omega + have ho : 2 * s + 2 - 1 = 2 * s + 1 := by omega + conv_lhs => rw [← he] + apply even_lower_bound_of_deletion (s + 1) _ (by omega) + simpa only [he, ho, Nat.add_assoc] using hh + +theorem complete_graph_lower_bound (n : ℕ) (hn : 3 ≤ n) + (D : AdmissibleDrawing (completeGraph n)) : hill n ≤ crossingCount D := by + by_cases hsmall : n < 5 + · interval_cases n <;> norm_num [hill] + by_cases hodd : n % 2 = 1 + · obtain ⟨s, rfl⟩ : ∃ s, n = 2 * s + 1 := ⟨n / 2, by omega⟩ + exact complete_graph_odd_lower_arbitrary s (by omega) D + · obtain ⟨s, rfl⟩ : ∃ s, n = 2 * s + 2 := ⟨n / 2 - 1, by omega⟩ + obtain ⟨N, hN⟩ := polygonal_no_adjacent_normalization _ D + exact (complete_graph_even_lower_normalized s (by omega) N).trans hN + +theorem complete_graph_upper_bound (n : ℕ) (hn : 3 ≤ n) : + ∃ D : AdmissibleDrawing (completeGraph n), crossingCount D = hill n := by + obtain ⟨D, hD⟩ := complete_graph_upper_drawing n + exact ⟨D, hD.trans (crossingTuples_card hn)⟩ + +theorem complete_graph_crossing_number (n : ℕ) (hn : 3 ≤ n) : + ordinaryCrossingNumber (completeGraph n) = hill n := by + obtain ⟨D, hD⟩ := complete_graph_upper_bound n hn + apply Nat.le_antisymm + · rw [← hD] + exact Paper170Geometry.ordinaryCrossingNumber_le_count D + · obtain ⟨A,hA,_⟩ := minimum_drawing_exists (completeGraph n) + rw [← hA] + exact complete_graph_lower_bound n hn A + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Normalization.lean b/lean/OAI/Combinatorics/CompleteCrossing/Normalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac0fa6366159d284d29c7a9aea2f1d98a21ded23 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Normalization.lean @@ -0,0 +1,478 @@ +import OAI.Combinatorics.CompleteCrossing.CirclePlacement +import OAI.Combinatorics.CompleteCrossing.Subdivision +import OAI.Combinatorics.CompleteCrossing.SurgeryIntersections +import OAI.Combinatorics.CompleteCrossing.Truncation +import OAI.Combinatorics.Crossing.ReconnectedVertexAvoidance +import OAI.Combinatorics.Crossing.ReducedPolygonalPresentation + +namespace OAI + +/-! Reorientation invariance and normalization without adjacent crossings or crossing knots. -/ + +section + +/-! Reversing chosen oriented representatives changes no spatial drawing or crossing count. -/ +noncomputable section +open Set +open scoped Classical +namespace Paper170 +variable {V E : Type} + +def Graph.reorient (G : Graph V E) (reverse : E → Bool) : Graph V E where + src e := if reverse e = true then G.dst e else G.src e + dst e := if reverse e = true then G.src e else G.dst e + loopless e := by + by_cases h : reverse e = true + · simpa only [ite_eq_left h] using (G.loopless e).symm + · simpa only [ite_eq_right h] using G.loopless e + simple e f h := by + apply G.simple e f + by_cases he : reverse e = true <;> by_cases hf : reverse f = true <;> + simp [he,hf] at h <;> tauto + +theorem unitInterval_symm_mem_Ioo (t : unitInterval) : + unitInterval.symm t ∈ Ioo (0 : unitInterval) 1 ↔ t ∈ Ioo (0 : unitInterval) 1 := by + change (0 < 1-(t : ℝ) ∧ 1-(t : ℝ) < 1) ↔ (0 < (t : ℝ) ∧ (t : ℝ) < 1) + constructor <;> rintro ⟨h0,h1⟩ <;> constructor <;> linarith + +namespace ContinuousDrawing +variable {G : Graph V E} + +def reorientedPath (D : ContinuousDrawing G) (reverse : E → Bool) (e : E) : + Path (D.vertex ((G.reorient reverse).src e)) (D.vertex ((G.reorient reverse).dst e)) := + if h : reverse e = true then (D.edge e).symm.cast + (by simp only [Graph.reorient,ite_eq_left h]) (by simp only [Graph.reorient,ite_eq_left h]) + else (D.edge e).cast + (by simp only [Graph.reorient,ite_eq_right h]) (by simp only [Graph.reorient,ite_eq_right h]) + +theorem reorientedPath_apply (D : ContinuousDrawing G) (reverse : E → Bool) (e : E) + (t : unitInterval) : D.reorientedPath reverse e t = + if reverse e = true then D.edge e (unitInterval.symm t) else D.edge e t := by + unfold reorientedPath + split <;> rfl + +def reorient (D : ContinuousDrawing G) (reverse : E → Bool) : + ContinuousDrawing (G.reorient reverse) where + vertex := D.vertex + vertex_injective := D.vertex_injective + edge := D.reorientedPath reverse + edge_injective e := by + intro s t hst + rw [reorientedPath_apply,reorientedPath_apply] at hst + by_cases h : reverse e = true + · rw [ite_eq_left h,ite_eq_left h] at hst + exact unitInterval.symm_bijective.1 (D.edge_injective e hst) + · rw [ite_eq_right h,ite_eq_right h] at hst + exact D.edge_injective e hst + interior_avoids_vertices e t ht v := by + rw [reorientedPath_apply] + by_cases h : reverse e = true + · rw [ite_eq_left h] + exact D.interior_avoids_vertices e _ ((unitInterval_symm_mem_Ioo t).mpr ht) v + · rw [ite_eq_right h] + exact D.interior_avoids_vertices e t ht v + +theorem reorient_edgeInterior (D : ContinuousDrawing G) (reverse : E → Bool) (e : E) : + edgeInterior (D.reorient reverse) e = edgeInterior D e := by + ext x + by_cases h : reverse e = true + · constructor + · rintro ⟨t,ht,hx⟩ + refine ⟨unitInterval.symm t,(unitInterval_symm_mem_Ioo t).mpr ht,?_⟩ + change D.reorientedPath reverse e t = x at hx + simpa only [reorientedPath_apply,ite_eq_left h] using hx + · rintro ⟨t,ht,hx⟩ + refine ⟨unitInterval.symm t,(unitInterval_symm_mem_Ioo t).mpr ht,?_⟩ + change D.reorientedPath reverse e (unitInterval.symm t) = x + simpa only [reorientedPath_apply,ite_eq_left h,unitInterval.symm_symm] using hx + · constructor + · rintro ⟨t,ht,hx⟩ + refine ⟨t,ht,?_⟩ + change D.reorientedPath reverse e t = x at hx + simpa only [reorientedPath_apply,ite_eq_right h] using hx + · rintro ⟨t,ht,hx⟩ + refine ⟨t,ht,?_⟩ + change D.reorientedPath reverse e t = x + simpa only [reorientedPath_apply,ite_eq_right h] using hx + +theorem reorient_crossingPoints (D : ContinuousDrawing G) (reverse : E → Bool) : + crossingPoints (D.reorient reverse) = crossingPoints D := by + ext x + simp only [crossingPoints, mem_ofPred_eq, reorient_edgeInterior] + +end ContinuousDrawing + +namespace AdmissibleDrawing +variable {G : Graph V E} + +def reorient (D : AdmissibleDrawing G) (reverse : E → Bool) : + AdmissibleDrawing (G.reorient reverse) where + toContinuousDrawing := D.toContinuousDrawing.reorient reverse + crossings_finite := by + rw [ContinuousDrawing.reorient_crossingPoints] + exact D.crossings_finite + crossings_proper e f hef x he hf := by + rw [ContinuousDrawing.reorient_edgeInterior] at he hf + rw [ContinuousDrawing.reorient_edgeInterior,ContinuousDrawing.reorient_edgeInterior] + exact D.crossings_proper e f hef x he hf + no_triples e f g hef heg hfg := by + simp only [ContinuousDrawing.reorient_edgeInterior] + exact D.no_triples e f g hef heg hfg + +theorem reorient_crossingCount (D : AdmissibleDrawing G) (reverse : E → Bool) : + crossingCount (D.reorient reverse) = crossingCount D := by + unfold crossingCount + congr 1 + ext x + simp only [Set.Finite.mem_toFinset, reorient, ContinuousDrawing.reorient_crossingPoints] + +end AdmissibleDrawing +end Paper170 + +end +end + +section + +/-! Reorientation preserves the minimum property among ordinary drawings. -/ +noncomputable section +namespace Paper170 +variable {V E : Type} + +theorem Graph.eq_of_endpoints {G H : Graph V E} (hs : G.src = H.src) + (ht : G.dst = H.dst) : G = H := by + cases G + cases H + cases hs + cases ht + rfl + +theorem Graph.reorient_reorient (G : Graph V E) (reverse : E → Bool) : + (G.reorient reverse).reorient reverse = G := by + apply Graph.eq_of_endpoints + · funext e + by_cases h : reverse e = true <;> simp [Graph.reorient,h] + · funext e + by_cases h : reverse e = true <;> simp [Graph.reorient,h] + +namespace AdmissibleDrawing +variable {G H : Graph V E} + +def castGraph (h : G = H) (D : AdmissibleDrawing G) : AdmissibleDrawing H := h ▸ D + +theorem castGraph_crossingCount (h : G = H) (D : AdmissibleDrawing G) : + crossingCount (D.castGraph h) = crossingCount D := by + cases h + rfl + +theorem reorient_minimal (D : AdmissibleDrawing G) (reverse : E → Bool) + (hmin : ∀ A : AdmissibleDrawing G, crossingCount D ≤ crossingCount A) : + ∀ A : AdmissibleDrawing (G.reorient reverse), + crossingCount (D.reorient reverse) ≤ crossingCount A := by + intro A + have h := hmin ((A.reorient reverse).castGraph (G.reorient_reorient reverse)) + simpa only [castGraph_crossingCount,reorient_crossingCount] using h + +end AdmissibleDrawing +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +variable {V E : Type} {G : Graph V E} + +def reparametrizedContinuous (D : ContinuousDrawing G) + (P : ∀ e, Zarankiewicz.PolygonalChain (range (D.edge e)) + (D.vertex (G.src e)) (D.vertex (G.dst e))) + (hP : ∀ e, Function.Injective (P e).path) : ContinuousDrawing G where + vertex := D.vertex + vertex_injective := D.vertex_injective + edge e := (P e).path + edge_injective := hP + interior_avoids_vertices e t ht v := + Zarankiewicz.path_interior_avoids_vertices_of_range D.vertex (G.src e) (G.dst e) + (P e).path (hP e) (by + intro w hw + obtain ⟨s, hs⟩ := (P e).path_range_subset hw + rcases Paper170Geometry.drawing_edge_vertex_parameter D e s w hs with h | h + · exact Or.inl h.2 + · exact Or.inr h.2) t ht v + +lemma reparametrized_interior (D : ContinuousDrawing G) + (P : ∀ e, Zarankiewicz.PolygonalChain (range (D.edge e)) + (D.vertex (G.src e)) (D.vertex (G.dst e))) + (hP : ∀ e, Function.Injective (P e).path) + (htrace : ∀ e, range (P e).path = range (D.edge e)) (e : E) : + edgeInterior (reparametrizedContinuous D P hP) e = edgeInterior D e := by + ext x + constructor + · intro hx + apply Paper170Geometry.edgeInterior_of_range_not_vertices D e x + · rw [← htrace e] + exact Paper170Geometry.edgeInterior_subset_range _ e hx + · exact Paper170Geometry.edgeInterior_not_vertex (reparametrizedContinuous D P hP) e x hx + · intro hx + apply Paper170Geometry.edgeInterior_of_range_not_vertices (reparametrizedContinuous D P hP) e x + · change x ∈ range (P e).path + rw [htrace e] + exact Paper170Geometry.edgeInterior_subset_range D e hx + · exact Paper170Geometry.edgeInterior_not_vertex D e x hx + +lemma reparametrized_crossings (D : ContinuousDrawing G) + (P : ∀ e, Zarankiewicz.PolygonalChain (range (D.edge e)) + (D.vertex (G.src e)) (D.vertex (G.dst e))) + (hP : ∀ e, Function.Injective (P e).path) + (htrace : ∀ e, range (P e).path = range (D.edge e)) : + crossingPoints (reparametrizedContinuous D P hP) = crossingPoints D := by + ext x + simp only [crossingPoints, reparametrized_interior D P hP htrace] + +def reparametrizedDrawing (D : AdmissibleDrawing G) + (P : ∀ e, Zarankiewicz.PolygonalChain (range (D.edge e)) + (D.vertex (G.src e)) (D.vertex (G.dst e))) + (hP : ∀ e, Function.Injective (P e).path) + (htrace : ∀ e, range (P e).path = range (D.edge e)) : AdmissibleDrawing G where + toContinuousDrawing := reparametrizedContinuous D.toContinuousDrawing P hP + crossings_finite := by + rw [reparametrized_crossings D.toContinuousDrawing P hP htrace] + exact D.crossings_finite + crossings_proper := by + intro e f hef x he hf + simp only [reparametrized_interior D.toContinuousDrawing P hP htrace] at he hf ⊢ + exact D.crossings_proper e f hef x he hf + no_triples := by + intro e f g hef heg hfg + simp only [reparametrized_interior D.toContinuousDrawing P hP htrace] + exact D.no_triples e f g hef heg hfg + +lemma reparametrized_count (D : AdmissibleDrawing G) + (P : ∀ e, Zarankiewicz.PolygonalChain (range (D.edge e)) + (D.vertex (G.src e)) (D.vertex (G.dst e))) + (hP : ∀ e, Function.Injective (P e).path) + (htrace : ∀ e, range (P e).path = range (D.edge e)) : + crossingCount (reparametrizedDrawing D P hP htrace) = crossingCount D := by + unfold crossingCount + congr 1 + ext x + simp only [Set.Finite.mem_toFinset] + change x ∈ crossingPoints (reparametrizedContinuous D.toContinuousDrawing P hP) ↔ _ + rw [reparametrized_crossings D.toContinuousDrawing P hP htrace] + +lemma normalized_of_locally_straight [Fintype V] (D : AdmissibleDrawing G) + (hpoly : ∀ e, Zarankiewicz.HasFiniteAffineCover (D.edge e)) + (hnoadj : Paper170Geometry.NoAdjacentCrossings D) + (hstraight : Paper170Geometry.LocallyStraightCrossings D) : + ∃ N : NormalizedDrawing G, crossingCount N.toAdmissibleDrawing = crossingCount D := by + have hp (e : E) : ∃ P : Zarankiewicz.PolygonalChain (range (D.edge e)) + (D.vertex (G.src e)) (D.vertex (G.dst e)), + range P.path = range (D.edge e) ∧ Function.Injective P.path ∧ 0 < P.pieces ∧ + ∀ Q : Zarankiewicz.PolygonalChain (range (D.edge e)) + (D.vertex (G.src e)) (D.vertex (G.dst e)), P.pieces ≤ Q.pieces := by + obtain ⟨P, ht, hi, hn, _, _, hm⟩ := + Zarankiewicz.exists_reduced_polygonalChain (D.edge e) (D.edge_injective e) (hpoly e) + exact ⟨P, ht, hi, hn, hm⟩ + choose P htrace hinj hpos hmin using hp + have hq (e : E) : ∃ Q : PolygonalParametrization (P e).path, + ∀ i, (P e).path (Q.knot i) ∉ crossingPoints D.toContinuousDrawing := + chain_subdivision_avoiding (P e) (hpos e) {x | x ∉ crossingPoints D.toContinuousDrawing} + (Paper170Geometry.minimum_vertices_not_crossing D hstraight e (P e) (hmin e)) + choose Q hQ using hq + let N : NormalizedDrawing G := { + toAdmissibleDrawing := reparametrizedDrawing D P hinj htrace + polygonal := Q + no_adjacent := by + intro e f hef hinc + change Disjoint (edgeInterior (reparametrizedContinuous D.toContinuousDrawing P hinj) e) + (edgeInterior (reparametrizedContinuous D.toContinuousDrawing P hinj) f) + simp only [reparametrized_interior D.toContinuousDrawing P hinj htrace] + exact Set.disjoint_iff_inter_eq_empty.mpr (hnoadj.eq_empty e f hef hinc) + crossings_not_knots := by + intro e i + change (P e).path ((Q e).knot i) ∉ + crossingPoints (reparametrizedContinuous D.toContinuousDrawing P hinj) + rw [reparametrized_crossings D.toContinuousDrawing P hinj htrace] + exact hQ e i } + exact ⟨N, reparametrized_count D P hinj htrace⟩ + +end Paper170 + +end +end + +section + +/-! The assembled ordinary drawing is genuinely straight near every crossing. -/ +noncomputable section +namespace Paper170Geometry +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} + {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem assembled_locallyStraightCrossings (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + LocallyStraightCrossings (E.assembledAdmissible v hvinj hv hdet) := by + constructor + intro e f hef x hx hy + obtain ⟨s,hs,he⟩ := hx + obtain ⟨t,ht,hf⟩ := hy + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x + (fun j heq => E.assembledEdge_interior_avoids_vertices v hv e s hs j (he.trans heq)) ⟨s,he⟩ ⟨t,hf⟩ + have hpq : p ≠ q := fun heq => hef (hp.symm.trans ((congrArg Sigma.fst heq).trans hq)) + have hpx := (C.crossingChord_meeting_proper p q hpq x hxp hxq).1 + have hqx := (C.crossingChord_meeting_proper q p (Ne.symm hpq) x hxq hxp).1 + have hlocal (r : C.InnerIndex) (hr : x ∈ C.crossingDisk r) + (hxr : x ∈ Set.range (C.crossingChord r)) : + LocallyStraightAt (E.assembledDrawing v hvinj hv) r.1 x := by + constructor + refine ⟨C.portPoint (C.incomingPort r),C.portPoint (C.outgoingPort r), + C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort r r), + (C.crossingChord_openTrace_iff r x hr).mp hxr,C.crossingDisk r,C.crossingDisk_isOpen r,hr,?_⟩ + exact E.assembled_trace_in_crossingDisk v hvinj hv r + change LocallyStraightAt (E.assembledDrawing v hvinj hv) e x ∧ + LocallyStraightAt (E.assembledDrawing v hvinj hv) f x + exact ⟨by simpa only [hp] using hlocal p hpx hxp,by simpa only [hq] using hlocal q hqx hxq⟩ + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! Minimum ordinary drawings have no crossing between any pair sharing a vertex. -/ +noncomputable section +namespace Paper170Geometry +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} [Fintype Vertex] [Fintype Edge] + {graph : Paper170.Graph Vertex Edge} + +theorem minimum_no_common_source_or_target (D : Paper170.AdmissibleDrawing graph) + (hmin : ∀ A : Paper170.AdmissibleDrawing graph, + Paper170.crossingCount D ≤ Paper170.crossingCount A) + (e f : Edge) (hef : e ≠ f) + (hadj : graph.src e = graph.src f ∨ graph.dst e = graph.dst f) : + Paper170.edgeInterior D.toContinuousDrawing e ∩ + Paper170.edgeInterior D.toContinuousDrawing f = ∅ := by + apply Set.eq_empty_iff_forall_notMem.mpr + rintro x ⟨hxe,hxf⟩ + obtain ⟨C⟩ := nonempty_drawingPassages D.toFiniteIntersectionDrawing + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + have hcount : Paper170.crossingCount (E.assembledAdmissible v hvinj hv hdet) = + Paper170.crossingCount D := + le_antisymm (E.assembled_crossingCount_le v hvinj hv hdet) (hmin _) + obtain ⟨y,hye,hyf⟩ := E.assembled_pair_retained_of_count_eq v hvinj hv hdet hcount e f hef x hxe hxf + obtain ⟨p,q,hp,hq,hyp,hyq⟩ := E.assembled_meeting_chords v hv hdet e f hef y + (edgeInterior_not_vertex (E.assembledDrawing v hvinj hv) e y hye) + (edgeInterior_subset_range (E.assembledDrawing v hvinj hv) e hye) + (edgeInterior_subset_range (E.assembledDrawing v hvinj hv) f hyf) + have hpq : p ≠ q := fun h => hef (hp.symm.trans ((congrArg Sigma.fst h).trans hq)) + have hadj' : graph.src p.1 = graph.src q.1 ∨ graph.dst p.1 = graph.dst q.1 := by + simpa only [hp,hq] using hadj + obtain ⟨R,hRpoly,hRcount⟩ := E.exists_admissible_adjacent_surgery + v hvinj hv hdet p q hpq hadj' y hyp hyq + rw [hcount] at hRcount + exact (not_lt_of_ge (hmin R)) hRcount + +theorem minimum_no_adjacent (D : Paper170.AdmissibleDrawing graph) + (hmin : ∀ A : Paper170.AdmissibleDrawing graph, + Paper170.crossingCount D ≤ Paper170.crossingCount A) : NoAdjacentCrossings D := by + constructor + intro e f hef hadj + obtain ⟨i,he,hf⟩ : ∃ i, (graph.src e = i ∨ graph.dst e = i) ∧ + (graph.src f = i ∨ graph.dst f = i) := by + rcases hadj with h | h | h | h + · exact ⟨graph.src e,Or.inl rfl,Or.inl h.symm⟩ + · exact ⟨graph.src e,Or.inl rfl,Or.inr h.symm⟩ + · exact ⟨graph.dst e,Or.inr rfl,Or.inl h.symm⟩ + · exact ⟨graph.dst e,Or.inr rfl,Or.inr h.symm⟩ + let reverse : Edge → Bool := fun a => decide (graph.dst a = i) + have hsource (a : Edge) (ha : graph.src a = i ∨ graph.dst a = i) : + (graph.reorient reverse).src a = i := by + simp only [Paper170.Graph.reorient,reverse,decide_eq_true_eq] + split + · assumption + · exact ha.resolve_right (by assumption) + have h := minimum_no_common_source_or_target (D.reorient reverse) + (D.reorient_minimal reverse hmin) e f hef + (Or.inl ((hsource e he).trans (hsource f hf).symm)) + simpa only [Paper170.AdmissibleDrawing.reorient, + Paper170.ContinuousDrawing.reorient_edgeInterior] using h + +theorem exists_minimum_assembled (D : Paper170.AdmissibleDrawing graph) : + ∃ (B : Paper170.AdmissibleDrawing graph) (C : DrawingPassages B.toFiniteIntersectionDrawing) + (E : PolygonalExterior C) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-B.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0), + NoAdjacentCrossings (E.assembledAdmissible v hvinj hv hdet) ∧ + Paper170.crossingCount (E.assembledAdmissible v hvinj hv hdet) = + Paper170.ordinaryCrossingNumber graph := by + obtain ⟨B,hB⟩ := crossingCount_attainment D + obtain ⟨C⟩ := nonempty_drawingPassages B.toFiniteIntersectionDrawing + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + let A := E.assembledAdmissible v hvinj hv hdet + have hcount : Paper170.crossingCount A = Paper170.ordinaryCrossingNumber graph := by + apply le_antisymm + · exact (E.assembled_crossingCount_le v hvinj hv hdet).trans_eq hB + · exact ordinaryCrossingNumber_le_count A + refine ⟨B,C,E,v,hvinj,hv,hdet,minimum_no_adjacent A ?_,hcount⟩ + intro R + rw [hcount] + exact ordinaryCrossingNumber_le_count R + +theorem polygonal_no_adjacent_locally_straight (D : Paper170.AdmissibleDrawing graph) : + ∃ A : Paper170.AdmissibleDrawing graph, + Paper170.crossingCount A = Paper170.ordinaryCrossingNumber graph ∧ + (∀ e, HasFiniteAffineCover (A.edge e)) ∧ NoAdjacentCrossings A ∧ LocallyStraightCrossings A := by + obtain ⟨B,C,E,v,hvinj,hv,hdet,hnorm,hcount⟩ := exists_minimum_assembled D + exact ⟨E.assembledAdmissible v hvinj hv hdet,hcount,E.assembledEdge_hasFiniteAffineCover v, + hnorm,E.assembled_locallyStraightCrossings v hvinj hv hdet⟩ + +end Paper170Geometry + +end +end + +section + +noncomputable section +namespace Paper170 +variable {V E : Type} [Fintype V] [Fintype E] (G : Graph V E) + +theorem polygonal_no_adjacent_normalization (D : AdmissibleDrawing G) : + ∃ N : NormalizedDrawing G, crossingCount N.toAdmissibleDrawing ≤ crossingCount D := by + obtain ⟨A, hcount, hpoly, hnoadj, hstraight⟩ := + Paper170Geometry.polygonal_no_adjacent_locally_straight D + obtain ⟨N, hN⟩ := normalized_of_locally_straight A hpoly hnoadj hstraight + exact ⟨N, (hN.trans hcount).le.trans (Paper170Geometry.ordinaryCrossingNumber_le_count D)⟩ + +theorem normalized_minimum_exists : + ∃ N : NormalizedDrawing G, + crossingCount N.toAdmissibleDrawing = ordinaryCrossingNumber G := by + obtain ⟨D, hD, _⟩ := minimum_drawing_exists G + obtain ⟨N, hN⟩ := polygonal_no_adjacent_normalization G D + exact ⟨N, le_antisymm (hN.trans_eq hD) + (Paper170Geometry.ordinaryCrossingNumber_le_count N.toAdmissibleDrawing)⟩ + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/OrderPairing.lean b/lean/OAI/Combinatorics/CompleteCrossing/OrderPairing.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7779259bcf9c0ef007ba7ec8eaebc7e53dbd0a4 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/OrderPairing.lean @@ -0,0 +1,199 @@ +import OAI.Combinatorics.CompleteCrossing.Triangle +import Mathlib.Data.Finset.Sort + +namespace OAI + +/-! Order-detecting interpolation and its kernel. -/ + +section + +/-! The order pairing as a nonzero diagonal pairing on the even two-triangle set. -/ +noncomputable section +open scoped BigOperators +namespace Paper170 + +def evenTriangleWeight (s : ℕ) (node : Fin (2*s) → ℝ) (a : EvenTriangleCoord s) : ℝ := + (if a.val.1.val < s then -1 else 1) * (node a.val.1-node a.val.2) / + (Zarankiewicz.derivativeAtNode node a.val.1 * Zarankiewicz.derivativeAtNode node a.val.2) + +theorem evenTriangleWeight_ne_zero (s : ℕ) (node : Fin (2*s) → ℝ) + (hn : Function.Injective node) (a : EvenTriangleCoord s) : evenTriangleWeight s node a ≠ 0 := by + have ha := (mem_evenTriangle s a.val.1 a.val.2).mp a.property + have hne : a.val.1 ≠ a.val.2 := by rcases ha with ha | ha; exact ne_of_gt ha.2; exact ne_of_lt ha.2 + unfold evenTriangleWeight + apply div_ne_zero + · apply mul_ne_zero + · split_ifs <;> norm_num + · exact sub_ne_zero.mpr (hn.ne hne) + · exact mul_ne_zero (Zarankiewicz.derivativeAtNode_ne_zero node hn _) + (Zarankiewicz.derivativeAtNode_ne_zero node hn _) + +theorem shifted_halfOrder (s : ℕ) (node : Fin (2*s) → ℝ) (p q : Fin (2*s)) : + (halfOrder inferInstance p q + (if p.val < s then -(1/2) else 1/2)) * (node p-node q) = + if (p,q) ∈ evenTriangle s then + (if p.val < s then -1 else 1) * (node p-node q) else 0 := by + rcases lt_trichotomy p q with hpq | rfl | hqp + · have hqp := not_lt_of_ge (le_of_lt hpq) + by_cases hp : p.val < s <;> + simp [halfOrder, hpq, hqp, mem_evenTriangle, hp, not_lt.mp] + ring + · simp [halfOrder] + · have hpq := not_lt_of_ge (le_of_lt hqp) + by_cases hp : p.val < s <;> + simp [halfOrder, hpq, hqp, mem_evenTriangle, hp, not_lt.mp] + ring + +theorem orderPairing_triangle (s : ℕ) (hs : 2 ≤ s) + (node : Fin (2*s) → ℝ) (hn : Function.Injective node) (A B : Poly2) + (hA : A ∈ rectangle (s-1) (s-2)) (hB : B ∈ rectangle (s-2) (s-1)) : + orderPairing node inferInstance A B = ∑ a : EvenTriangleCoord s, + evenTriangleWeight s node a * evalTwo (node a.val.1) (node a.val.2) A * + evalTwo (node a.val.1) (node a.val.2) B := by + have hshift := pairing_row_column_invariant s hs (by simp) node hn (halfOrder inferInstance) + (fun p => if p.val < s then -(1/2) else 1/2) (fun _ => 0) A B hA hB + simp only [add_zero] at hshift + rw [orderPairing, ← hshift] + let F (a : Fin (2*s) × Fin (2*s)) : ℝ := + (if a.1.val < s then -1 else 1) * (node a.1-node a.2) / + (Zarankiewicz.derivativeAtNode node a.1 * Zarankiewicz.derivativeAtNode node a.2) * + evalTwo (node a.1) (node a.2) A * evalTwo (node a.1) (node a.2) B + change _ = ∑ a : EvenTriangleCoord s, F a.val + calc + _ = ∑ a ∈ evenTriangle s, F a := by + unfold weightedPairing + simp_rw [shifted_halfOrder] + rw [evenTriangle, Finset.sum_filter, Fintype.sum_prod_type] + apply Finset.sum_congr rfl + intro p _ + apply Finset.sum_congr rfl + intro q _ + by_cases ha : (p,q) ∈ evenTriangle s + · have hh := (mem_evenTriangle s p q).mp ha + simp only [Finset.mem_filter, Finset.mem_univ, true_and, ite_eq_left hh, F] + · have hh := (mem_evenTriangle s p q).not.mp ha + simp only [Finset.mem_filter, Finset.mem_univ, true_and, ite_eq_right hh, zero_div, zero_mul] + _ = ∑ a : EvenTriangleCoord s, F a.val := (Finset.sum_coe_sort (evenTriangle s) F).symm + +theorem derivativeAtNode_equiv {ι κ : Type*} [Fintype ι] [Fintype κ] + (node : ι → ℝ) (e : κ ≃ ι) (p : κ) : + Zarankiewicz.derivativeAtNode (node ∘ e) p = Zarankiewicz.derivativeAtNode node (e p) := by + classical + have h : Zarankiewicz.nodePolynomial (node ∘ e) = Zarankiewicz.nodePolynomial node := by + unfold Zarankiewicz.nodePolynomial + exact e.prod_comp (fun i => (Polynomial.X-Polynomial.C (node i) : Polynomial ℝ)) + simp only [Zarankiewicz.derivativeAtNode, h, Function.comp_apply] + +theorem weightedPairing_equiv {ι κ : Type*} [Fintype ι] [Fintype κ] + (node : ι → ℝ) (e : κ ≃ ι) (K : ι → ι → ℝ) (A B : Poly2) : + weightedPairing (node ∘ e) (fun p q => K (e p) (e q)) A B = weightedPairing node K A B := by + unfold weightedPairing + simp_rw [derivativeAtNode_equiv, Function.comp_apply] + let F (p q : ι) : ℝ := K p q * (node p-node q) / + (Zarankiewicz.derivativeAtNode node p*Zarankiewicz.derivativeAtNode node q) * + evalTwo (node p) (node q) A * evalTwo (node p) (node q) B + change (∑p : κ, ∑q : κ, F (e p) (e q)) = ∑p : ι, ∑q : ι, F p q + calc + _ = ∑p : κ, ∑q : ι, F (e p) q := by + apply Finset.sum_congr rfl + intro p _ + exact e.sum_comp (F (e p)) + _ = _ := e.sum_comp (fun p => ∑q, F p q) + +theorem orderPairing_orderIso {ι κ : Type*} [Fintype ι] [Fintype κ] + [LinearOrder ι] [LinearOrder κ] (node : ι → ℝ) (e : κ ≃o ι) (A B : Poly2) : + orderPairing (node ∘ e) inferInstance A B = orderPairing node inferInstance A B := by + have h : (fun p q => halfOrder inferInstance (e p) (e q)) = halfOrder (inferInstance : LinearOrder κ) := by + funext p q + simp only [halfOrder, e.lt_iff_lt] + rw [orderPairing, ← h] + exact weightedPairing_equiv node e.toEquiv _ A B + +end Paper170 + +end +end + +section + +/-! Nonsingularity of the weighted half-order pairing for every node order. -/ +noncomputable section +open scoped BigOperators +namespace Paper170 + +theorem order_pairing_nonsingular_fin (s : ℕ) (hs : 2 ≤ s) + (node : Fin (2*s) → ℝ) (hn : Function.Injective node) : + (∀ A ∈ rectangle (s-1) (s-2), + (∀ B ∈ rectangle (s-2) (s-1), orderPairing node inferInstance A B = 0) → A=0) ∧ + (∀ B ∈ rectangle (s-2) (s-1), + (∀ A ∈ rectangle (s-1) (s-2), orderPairing node inferInstance A B = 0) → B=0) := by + classical + obtain ⟨hfirst,hsecond⟩ := two_triangle_interpolation s hs node hn + constructor + · intro A hA hz + apply evenTriangle_vanish_first s hs node hn A hA + intro i j hij + let a : EvenTriangleCoord s := ⟨(i,j),hij⟩ + obtain ⟨B,hB⟩ := hsecond.surjective (Pi.single a (1:ℝ)) + have he (b : EvenTriangleCoord s) : evalTwo (node b.val.1) (node b.val.2) B.val = + (Pi.single a (1:ℝ) : EvenTriangleCoord s → ℝ) b := congrFun hB b + have hzero := hz B.val B.property + rw [orderPairing_triangle s hs node hn A B.val hA B.property] at hzero + simp_rw [he] at hzero + have hv : evenTriangleWeight s node a * evalTwo (node i) (node j) A = 0 := by + simpa [Pi.single_apply, mul_ite, a] using hzero + exact (mul_eq_zero.mp hv).resolve_left (evenTriangleWeight_ne_zero s node hn a) + · intro B hB hz + apply evenTriangle_vanish_second s hs node hn B hB + intro i j hij + let a : EvenTriangleCoord s := ⟨(i,j),hij⟩ + obtain ⟨A,hA⟩ := hfirst.surjective (Pi.single a (1:ℝ)) + have he (b : EvenTriangleCoord s) : evalTwo (node b.val.1) (node b.val.2) A.val = + (Pi.single a (1:ℝ) : EvenTriangleCoord s → ℝ) b := congrFun hA b + have hzero := hz A.val A.property + rw [orderPairing_triangle s hs node hn A.val B A.property hB] at hzero + simp_rw [he] at hzero + have hv : evenTriangleWeight s node a * evalTwo (node i) (node j) B = 0 := by + simpa [Pi.single_apply, mul_ite, ite_mul, a] using hzero + exact (mul_eq_zero.mp hv).resolve_left (evenTriangleWeight_ne_zero s node hn a) + +theorem order_pairing_nonsingular {ι : Type*} [Fintype ι] + (s : ℕ) (hs : 2 ≤ s) (hc : Fintype.card ι = 2*s) + (node : ι → ℝ) (hn : Function.Injective node) (order : LinearOrder ι) : + (∀ A ∈ rectangle (s-1) (s-2), + (∀ B ∈ rectangle (s-2) (s-1), orderPairing node order A B = 0) → A=0) ∧ + (∀ B ∈ rectangle (s-2) (s-1), + (∀ A ∈ rectangle (s-1) (s-2), orderPairing node order A B = 0) → B=0) := by + let := order + let e : Fin (2*s) ≃o ι := Fintype.orderIsoFinOfCardEq ι hc + obtain ⟨hfirst,hsecond⟩ := order_pairing_nonsingular_fin s hs (node ∘ e) (hn.comp e.injective) + constructor + · intro A hA hz + apply hfirst A hA + intro B hB + rw [orderPairing_orderIso node e] + exact hz B hB + · intro B hB hz + apply hsecond B hB + intro A hA + rw [orderPairing_orderIso node e] + exact hz A hA + +theorem order_detector {ι : Type*} [Fintype ι] + (s : ℕ) (hs : 2 ≤ s) (hc : Fintype.card ι = 2*s) + (node : ι → ℝ) (hn : Function.Injective node) (order : LinearOrder ι) + (A : Poly2) (hA : A ∈ rectangle (s-2) (s-2)) + (hzero : ∀ B ∈ rectangle (s-1) (s-1), orderPairing node order A B = 0) : A=0 := by + apply (order_pairing_nonsingular s hs hc node hn order).1 A + · rw [rectangle_membership] at hA ⊢ + exact ⟨hA.1.trans (by omega), hA.2⟩ + · intro B hB + apply hzero B + rw [rectangle_membership] at hB ⊢ + exact ⟨hB.1.trans (by omega), hB.2⟩ + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/PairSums.lean b/lean/OAI/Combinatorics/CompleteCrossing/PairSums.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f40e996af18fbc40742286bf25c2b815a78cca8 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/PairSums.lean @@ -0,0 +1,78 @@ +import Mathlib.Algebra.BigOperators.Group.Finset.Sigma +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Ring + +namespace OAI + +/-! Symmetric double and quadruple sums over unordered pairs. -/ + +section + +noncomputable section +open scoped BigOperators Classical +namespace Paper170 + +def upperPairSum {α : Type*} [Fintype α] [LinearOrder α] (f : α → α → ℝ) : ℝ := + ∑ i, ∑ p, if i < p then f i p else 0 + +theorem upperPairSum_mul {α : Type*} [Fintype α] [LinearOrder α] + (r : ℝ) (f : α → α → ℝ) : + upperPairSum (fun i p => r * f i p) = r * upperPairSum f := by + simp only [upperPairSum, Finset.mul_sum, mul_ite, mul_zero] + +theorem sum_symmetric_pair {α : Type*} [Fintype α] [LinearOrder α] + (f : α → α → ℝ) (hsym : ∀ i p, f p i = f i p) (hdiag : ∀ i, f i i = 0) : + (∑ i, ∑ p, f i p) = 2 * upperPairSum f := by + have hpoint (i p : α) : f i p = + (if i < p then f i p else 0) + (if p < i then f i p else 0) := by + rcases lt_trichotomy i p with h | rfl | h + · simp [h, not_lt_of_ge h.le] + · simp [hdiag] + · simp [h, not_lt_of_ge h.le] + have hsum : (∑ i, ∑ p, f i p) = + upperPairSum f + ∑ i, ∑ p, if p < i then f i p else 0 := by + calc + _ = ∑ i, ∑ p, ((if i < p then f i p else 0) + + (if p < i then f i p else 0)) := by + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro p _ + exact hpoint i p + _ = _ := by simp only [upperPairSum, Finset.sum_add_distrib] + rw [hsum, Finset.sum_comm] + have he : (∑ p, ∑ i, if p < i then f i p else 0) = upperPairSum f := by + unfold upperPairSum + apply Finset.sum_congr rfl + intro p _ + apply Finset.sum_congr rfl + intro i _ + rw [hsym] + rw [he] + ring + +theorem sum_symmetric_quad {α : Type*} [Fintype α] [LinearOrder α] + (f : α → α → α → α → ℝ) + (hfirst : ∀ i p k q, f p i k q = f i p k q) + (hsecond : ∀ i p k q, f i p q k = f i p k q) + (hdiag₁ : ∀ i k q, f i i k q = 0) (hdiag₂ : ∀ i p k, f i p k k = 0) : + (∑ i, ∑ p, ∑ k, ∑ q, f i p k q) = + 4 * upperPairSum (fun i p => upperPairSum (f i p)) := by + have hs (i p : α) : (∑ k, ∑ q, f p i k q) = ∑ k, ∑ q, f i p k q := by + simp only [hfirst] + have hd (i : α) : (∑ k, ∑ q, f i i k q) = 0 := by simp [hdiag₁] + rw [sum_symmetric_pair _ hs hd] + have he : (fun i p => ∑ k, ∑ q, f i p k q) = + (fun i p => 2 * upperPairSum (f i p)) := by + funext i p + exact sum_symmetric_pair _ (hsecond i p) (hdiag₂ i p) + rw [he, upperPairSum_mul] + ring + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Plane.lean b/lean/OAI/Combinatorics/CompleteCrossing/Plane.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce10f59d49b0ad8516b15d0f1d633f31c578e904 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Plane.lean @@ -0,0 +1,485 @@ +import OAI.Combinatorics.CompleteCrossing.Drawing +import OAI.Combinatorics.Crossing.ClosedPolygonIntersection +import OAI.Combinatorics.Crossing.IntervalSegmentStrict +import OAI.Combinatorics.Crossing.OrderedAffineSubdivision +import OAI.Combinatorics.Crossing.PolygonalArcInjective +import Mathlib.Topology.Homeomorph.Lemmas +import Mathlib.Topology.Order.IntermediateValue + +namespace OAI + +/-! Planar segment geometry, affine parametrizations, and oriented arc directions. -/ + +section + +/-! Generic planar ingredients reused through exact definitions of actual paths. -/ +noncomputable section +open Set +open scoped BigOperators Classical + +namespace Paper170 + +theorem segmentPoint_eq (a b : Plane) (t : ℝ) : + segmentPoint a b t = Zarankiewicz.segmentPoint a b t := rfl + +theorem det2_eq (a b : Plane) : det2 a b = Zarankiewicz.det2 a b := rfl + +theorem segmentIntersection_eq_segmentCrossingSign (a b c d : Plane) : + segmentIntersection a b c d = Zarankiewicz.segmentCrossingSign a b c d := by + simp only [segmentIntersection, segmentPoint_eq, det2_eq, + Zarankiewicz.segmentCrossingSign, Zarankiewicz.SegmentsCrossProperly] + by_cases h : ∃ s ∈ Ioo (0 : ℝ) 1, ∃ t ∈ Ioo (0 : ℝ) 1, + Zarankiewicz.segmentPoint a b s = Zarankiewicz.segmentPoint c d t + · simp only [h, ite_true, and_true] + rcases lt_trichotomy (Zarankiewicz.det2 (b-a) (d-c)) 0 with hd | hd | hd + · simp [hd, ne_of_lt hd, not_lt.mpr hd.le] + · simp [hd] + · simp [hd, ne_of_gt hd] + · simp only [h, ite_false, and_false] + +theorem segmentIntersection_swap (a b c d : Plane) : + segmentIntersection c d a b = -segmentIntersection a b c d := by + simpa only [segmentIntersection_eq_segmentCrossingSign] using + Zarankiewicz.segmentCrossingSign_swap a b c d + +theorem TransversePolygons.segmentPairTransverse {v w : ℕ → Plane} {n m : ℕ} + (h : TransversePolygons v w n m) (i : Fin n) (j : Fin m) : + Zarankiewicz.SegmentPairTransverse (v i.val) (v (i.val+1)) + (w j.val) (w (j.val+1)) := by + intro s hs t ht he + have hs0 : s ≠ 0 := by + intro hz + subst s + have hh : v i.val = segmentPoint (w j.val) (w (j.val+1)) t := by + simpa only [segmentPoint_eq, Zarankiewicz.segmentPoint_zero] using he + exact h.left_vertices_avoid i.val (Nat.le_of_lt i.isLt) j.val j.isLt t ht hh + have hs1 : s ≠ 1 := by + intro hz + subst s + have hh : v (i.val+1) = segmentPoint (w j.val) (w (j.val+1)) t := by + simpa only [segmentPoint_eq, Zarankiewicz.segmentPoint_one] using he + exact h.left_vertices_avoid (i.val+1) i.isLt j.val j.isLt t ht hh + have ht0 : t ≠ 0 := by + intro hz + subst t + have hh : w j.val = segmentPoint (v i.val) (v (i.val+1)) s := by + simpa only [segmentPoint_eq, Zarankiewicz.segmentPoint_zero] using he.symm + exact h.right_vertices_avoid j.val (Nat.le_of_lt j.isLt) i.val i.isLt s hs hh + have ht1 : t ≠ 1 := by + intro hz + subst t + have hh : w (j.val+1) = segmentPoint (v i.val) (v (i.val+1)) s := by + simpa only [segmentPoint_eq, Zarankiewicz.segmentPoint_one] using he.symm + exact h.right_vertices_avoid (j.val+1) j.isLt i.val i.isLt s hs hh + have hs' : s ∈ Ioo (0 : ℝ) 1 := ⟨lt_of_le_of_ne hs.1 hs0.symm, lt_of_le_of_ne hs.2 hs1⟩ + have ht' : t ∈ Ioo (0 : ℝ) 1 := ⟨lt_of_le_of_ne ht.1 ht0.symm, lt_of_le_of_ne ht.2 ht1⟩ + exact ⟨h.transverse i.val i.isLt j.val j.isLt ⟨s,hs',t,ht',he⟩, hs', ht'⟩ + +theorem closed_polygon_intersection_zero (v w : ℕ → Plane) (n m : ℕ) + (hv : v n = v 0) (hw : w m = w 0) (htrans : TransversePolygons v w n m) : + polygonIntersection v w n m = 0 := by + simpa only [polygonIntersection, segmentIntersection_eq_segmentCrossingSign, + Zarankiewicz.polygonIntersection] using + Zarankiewicz.closed_polygon_intersection_zero v w n m hv hw htrans.segmentPairTransverse + +/-- Transfer a genuine affine parametrization, retaining the identical path and knots. -/ +def ofZarankiewiczParametrization {a b : Plane} {γ : Path a b} + (P : Zarankiewicz.PolygonalParametrization γ) : PolygonalParametrization γ where + pieces := P.pieces + positive := by + by_contra hn + have hp : P.pieces = 0 := by omega + have hi : (0 : Fin (P.pieces+1)) = Fin.last P.pieces := by + apply Fin.ext + exact hp.symm + have he := P.first.symm.trans ((congrArg P.knot hi).trans P.last) + exact zero_ne_one he + knot := P.knot + increasing := P.increasing + first := P.first + last := P.last + affine := by + intro i t hlo hhi + have hlt : P.knot i.castSucc < P.knot i.succ := P.increasing Fin.castSucc_lt_succ + obtain ⟨u,hu⟩ := Zarankiewicz.intervalSegment_surjective_interval + (P.knot i.castSucc) (P.knot i.succ) hlt t ⟨hlo,hhi⟩ + have he := P.affine i u + rw [hu] at he + have hp := congrArg Subtype.val hu + have hd : (P.knot i.succ : ℝ) - P.knot i.castSucc ≠ 0 := sub_ne_zero.mpr (ne_of_gt (show (P.knot i.castSucc : ℝ) < P.knot i.succ from hlt)) + have hquot : ((t : ℝ) - P.knot i.castSucc) / + ((P.knot i.succ : ℝ) - P.knot i.castSucc) = (u : ℝ) := by + apply (div_eq_iff hd).mpr + dsimp [Zarankiewicz.intervalSegment] at hp + nlinarith + rw [hquot] + exact he + +theorem simple_polygonal_replacement {a b : Plane} (hab : a ≠ b) + (U : Set Plane) (hU : IsOpen U) (γ : Path a b) (hγ : range γ ⊆ U) : + ∃ η : Path a b, Function.Injective η ∧ range η ⊆ U ∧ + Nonempty (PolygonalParametrization η) := by + obtain ⟨P,hP,hPU,_⟩ := Zarankiewicz.exists_simple_polygonalChain_of_path hab γ U hU + (fun t => hγ ⟨t,rfl⟩) + obtain ⟨Q⟩ := P.hasFiniteAffineCover.nonempty_polygonalParametrization + exact ⟨P.path,hP,hPU,⟨ofZarankiewiczParametrization Q⟩⟩ + +theorem squaredLength_pos {x : Plane} (hx : x ≠ 0) : 0 < squaredLength x := by + have h0 : 0 ≤ x.1^2 := sq_nonneg x.1 + have h1 : 0 ≤ x.2^2 := sq_nonneg x.2 + change 0 < x.1^2 + x.2^2 + by_contra hh + have ha : x.1 = 0 := by nlinarith + have hb : x.2 = 0 := by nlinarith + exact hx (Prod.ext ha hb) + +theorem inversion_involutive : Function.Involutive inversion := by + intro x + by_cases hx : x = 0 + · subst x + simp [inversion, squaredLength] + · have hq : squaredLength x ≠ 0 := ne_of_gt (squaredLength_pos hx) + have hlen : squaredLength (inversion x) = (squaredLength x)⁻¹ := by + change (x.1 / squaredLength x)^2 + (x.2 / squaredLength x)^2 = _ + rw [div_pow, div_pow, ← add_div] + change squaredLength x / squaredLength x ^ 2 = (squaredLength x)⁻¹ + field_simp [hq] + rw [inversion, hlen] + apply Prod.ext <;> simp [inversion, hq] + +theorem inversion_fixes_circle (x : Plane) (hx : squaredLength x = 1) : inversion x = x := by + simp [inversion, hx] + +end Paper170 + +end +end + +section + +/-! The frozen subdivision and the reused geometric subdivision describe the same path. -/ +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +def toZarankiewiczParametrization {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) : Zarankiewicz.PolygonalParametrization γ where + pieces := P.pieces + knot := P.knot + increasing := P.increasing + first := P.first + last := P.last + affine := by + intro i t + have hlt : P.knot i.castSucc < P.knot i.succ := P.increasing Fin.castSucc_lt_succ + have hlohi := Zarankiewicz.intervalSegment_between + (P.knot i.castSucc) (P.knot i.succ) t hlt.le + have he := P.affine i _ hlohi.1 hlohi.2 + have hd : (P.knot i.succ : ℝ) - P.knot i.castSucc ≠ 0 := + sub_ne_zero.mpr (ne_of_gt (show (P.knot i.castSucc : ℝ) < P.knot i.succ from hlt)) + have hquot : (((Zarankiewicz.intervalSegment (P.knot i.castSucc) (P.knot i.succ) t : + unitInterval) : ℝ) - P.knot i.castSucc) / + ((P.knot i.succ : ℝ) - P.knot i.castSucc) = (t : ℝ) := by + apply (div_eq_iff hd).mpr + dsimp [Zarankiewicz.intervalSegment] + ring + rw [hquot] at he + exact he + +theorem vertices_toZarankiewicz {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) (i : ℕ) : + (toZarankiewiczParametrization P).vertices i = P.vertices i := rfl + +theorem PolygonalParametrization.segment_mem_interior {V E : Type} {G : Graph V E} + (D : ContinuousDrawing G) (e : E) (P : PolygonalParametrization (D.edge e)) + (i : Fin P.pieces) (s : ℝ) (hs : s ∈ Ioo (0 : ℝ) 1) : + segmentPoint (P.vertices i.val) (P.vertices (i.val+1)) s ∈ edgeInterior D e := by + let t : unitInterval := ⟨s,hs.1.le,hs.2.le⟩ + let u := Zarankiewicz.intervalSegment (P.knot i.castSucc) (P.knot i.succ) t + have hlt : P.knot i.castSucc < P.knot i.succ := P.increasing Fin.castSucc_lt_succ + have hu := Zarankiewicz.intervalSegment_strict_between + (P.knot i.castSucc) (P.knot i.succ) t hlt (show t ∈ Ioo (0 : unitInterval) 1 from hs) + refine ⟨u,⟨lt_of_le_of_lt (P.knot i.castSucc).property.1 hu.1, + lt_of_lt_of_le hu.2 (P.knot i.succ).property.2⟩,?_⟩ + exact (toZarankiewiczParametrization P).segment_formula i t + +theorem PolygonalParametrization.vertices_first {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) : P.vertices 0 = a := + (toZarankiewiczParametrization P).vertices_first + +theorem PolygonalParametrization.vertices_last {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) : P.vertices P.pieces = b := + (toZarankiewiczParametrization P).vertices_last + +theorem PolygonalParametrization.direction_ne_zero {a b : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) (hγ : Function.Injective γ) + (i : ℕ) (hi : i < P.pieces) : P.vertices (i+1) - P.vertices i ≠ 0 := + (toZarankiewiczParametrization P).direction_ne_zero hγ i hi + +end Paper170 + +end +end + +section + +noncomputable section +open Set Zarankiewicz +open scoped BigOperators +namespace Paper170Geometry + +theorem sum_eq_sum_of_unique_match {A B : Type} [Fintype A] [Fintype B] + (f : A → ℝ) (g : B → ℝ) (R : A → B → Prop) + (hf : ∀a, f a≠0 → ∃!b, g b≠0 ∧ R a b) + (hg : ∀b, g b≠0 → ∃!a, f a≠0 ∧ R a b) + (heq : ∀a b, f a≠0 → g b≠0 → R a b → f a=g b) : + ∑a, f a = ∑b, g b := by + classical + have hrow (a : A) : f a = ∑b : B, if f a≠0 ∧ g b≠0 ∧ R a b then f a else 0 := by + by_cases ha : f a=0 + · simp [ha] + · obtain ⟨b, hb, hu⟩ := hf a ha + symm + rw [Finset.sum_eq_single b] + · rw [ite_eq_left ⟨ha, hb.1, hb.2⟩] + · intro c _ hcb + have hn : ¬(f a≠0 ∧ g c≠0 ∧ R a c) := fun h => hcb (hu c h.2) + simp only [ite_eq_right hn] + · simp + have hcol (b : B) : (∑a : A, if f a≠0 ∧ g b≠0 ∧ R a b then f a else 0) = g b := by + by_cases hb : g b=0 + · simp [hb] + · obtain ⟨a, ha, hu⟩ := hg b hb + rw [Finset.sum_eq_single a] + · rw [ite_eq_left ⟨ha.1,hb,ha.2⟩] + exact heq a b ha.1 hb ha.2 + · intro c _ hca + have hn : ¬(f c≠0 ∧ g b≠0 ∧ R c b) := fun h => hca (hu c ⟨h.1,h.2.2⟩) + simp only [ite_eq_right hn] + · simp + calc + ∑a, f a = ∑a, ∑b, if f a≠0 ∧ g b≠0 ∧ R a b then f a else 0 := + Finset.sum_congr rfl (fun a _ => hrow a) + _ = ∑b, ∑a, if f a≠0 ∧ g b≠0 ∧ R a b then f a else 0 := Finset.sum_comm + _ = ∑b, g b := Finset.sum_congr rfl (fun b _ => hcol b) + +theorem segmentCrossingSign_ne_zero_iff (a b c d : Plane) : + segmentCrossingSign a b c d ≠ 0 ↔ SegmentsCrossProperly a b c d := by + unfold segmentCrossingSign + split_ifs <;> simp_all + +theorem meeting_of_mem_openSegments (a b c d x : Plane) + (hx : x∈openSegmentTrace a b) (hy : x∈openSegmentTrace c d) : + ∃s∈Ioo (0:ℝ) 1, ∃t∈Ioo (0:ℝ) 1, segmentPoint a b s=segmentPoint c d t := by + obtain ⟨s,hs,hsx⟩ := hx + obtain ⟨t,ht,htx⟩ := hy + exact ⟨s,hs,t,ht,hsx.trans htx.symm⟩ + +theorem openSegments_inter_subsingleton (a b c d : Plane) (hdet : det2 (b-a) (d-c)≠0) : + (openSegmentTrace a b ∩ openSegmentTrace c d).Subsingleton := by + rintro x ⟨⟨s,hs,hsx⟩,⟨t,ht,htx⟩⟩ y ⟨⟨u,hu,huy⟩,⟨v,hv,hvy⟩⟩ + have he := segment_intersection_parameters_unique a b c d hdet s t u v + (hsx.trans htx.symm) (huy.trans hvy.symm) + exact hsx.symm.trans ((congrArg (segmentPoint a b) he.1).trans huy) + +theorem segmentCrossingSign_eq_of_pos_directions + (a b c d a' b' c' d' x : Plane) (r s : ℝ) (hr : 0 + ⟨η t, hrange.symm ▸ Set.mem_range_self t⟩ + let f : unitInterval → unitInterval := fun t => e.symm (lift t) + have heval (t) : γ (f t) = η t := by + have h := congrArg Subtype.val (e.apply_symm_apply (lift t)) + exact h + have hzero : f 0 = 0 := hγ (by simpa using heval 0) + have hone : f 1 = 1 := hγ (by simpa using heval 1) + have hc : Continuous f := e.symm.continuous.comp + (η.continuous.subtype_mk (fun t => hrange.symm ▸ Set.mem_range_self t)) + have hi : Function.Injective f := by + intro s t hst + apply hη + rw [← heval s, ← heval t, hst] + refine ⟨f, hc, ?_, hzero, hone, heval⟩ + apply hc.strictMono_of_inj_boundedOrder _ hi + simpa only [show (⊥ : unitInterval) = 0 from rfl, + show (⊤ : unitInterval) = 1 from rfl, hzero, hone] using + (show (0 : unitInterval) ≤ 1 from zero_le_one) + +end Paper170 + +end +end + +section + +noncomputable section +open Set Zarankiewicz +namespace Paper170 + +lemma intervalSegment_lt_iff {a b p q : unitInterval} (hab : a < b) : + intervalSegment a b p < intervalSegment a b q ↔ p < q := by + have hd : 0 < b.val - a.val := sub_pos.mpr hab + change (1 - p.val) * a.val + p.val * b.val < + (1 - q.val) * a.val + q.val * b.val ↔ p.val < q.val + have he : ((1 - q.val) * a.val + q.val * b.val) - + ((1 - p.val) * a.val + p.val * b.val) = + (q.val - p.val) * (b.val - a.val) := by ring + rw [← sub_pos, he, mul_pos_iff_of_pos_right hd, sub_pos] + +lemma segmentPoint_sub_segmentPoint (A B : Plane) (p q : ℝ) : + Paper170.segmentPoint A B q - Paper170.segmentPoint A B p = (q-p) • (B-A) := by + ext <;> simp [Paper170.segmentPoint] <;> ring + +/-- Oriented affine pieces of two parametrizations of the same simple arc have +positively proportional directions whenever they overlap to the right. -/ +theorem path_segments_direction {a b : Plane} (γ η : Path a b) + (hγ : Function.Injective γ) (hη : Function.Injective η) + (hrange : Set.range γ = Set.range η) + (a₀ a₁ b₀ b₁ : unitInterval) (ha : a₀ < a₁) (hb : b₀ < b₁) + (A B C D : Plane) + (hγseg : ∀t, γ (intervalSegment a₀ a₁ t) = Paper170.segmentPoint A B t.val) + (hηseg : ∀t, η (intervalSegment b₀ b₁ t) = Paper170.segmentPoint C D t.val) + (p q : unitInterval) (hp : p < 1) (hq : q < 1) + (hpoint : Paper170.segmentPoint A B p.val = Paper170.segmentPoint C D q.val) : + ∃ r : ℝ, 0 < r ∧ D-C = r • (B-A) := by + obtain ⟨f, hc, hf, _, _, heval⟩ := path_reparametrization γ η hγ hη hrange + let u := intervalSegment a₀ a₁ p + let v := intervalSegment b₀ b₁ q + have hmatch : f v = u := hγ (by rw [heval, hηseg, hγseg, hpoint]) + have hu : u < a₁ := by + simpa [u, intervalSegment] using (intervalSegment_lt_iff ha).mpr hp + have hv : v < b₁ := by + simpa [v, intervalSegment] using (intervalSegment_lt_iff hb).mpr hq + obtain ⟨c, huc, hcmin⟩ := exists_between (lt_min hu (hmatch ▸ hf hv)) + have hfc : f v < c := by rwa [hmatch] + obtain ⟨t, ht, hft⟩ := intermediate_value_Ioo hv.le hc.continuousOn + ⟨hfc, (lt_min_iff.mp hcmin).2⟩ + have hctop : c < a₁ := (lt_min_iff.mp hcmin).1 + obtain ⟨p', hp'⟩ := intervalSegment_surjective_interval a₀ a₁ ha c + ⟨(intervalSegment_between a₀ a₁ p ha.le).1.trans huc.le, hctop.le⟩ + obtain ⟨q', hq'⟩ := intervalSegment_surjective_interval b₀ b₁ hb t + ⟨(intervalSegment_between b₀ b₁ q hb.le).1.trans ht.1.le, ht.2.le⟩ + have hpp : p < p' := (intervalSegment_lt_iff ha).mp (by simpa [hp'] using huc) + have hqq : q < q' := (intervalSegment_lt_iff hb).mp (by simpa [hq'] using ht.1) + have hpoint' : Paper170.segmentPoint A B p'.val = + Paper170.segmentPoint C D q'.val := by + rw [← hγseg, ← hηseg, hp', hq', ← hft, heval] + have heq : (p'.val-p.val) • (B-A) = (q'.val-q.val) • (D-C) := by + rw [← segmentPoint_sub_segmentPoint, ← segmentPoint_sub_segmentPoint, + hpoint, hpoint'] + have hα : 0 < p'.val-p.val := sub_pos.mpr hpp + have hβ : 0 < q'.val-q.val := sub_pos.mpr hqq + refine ⟨(q'.val-q.val)⁻¹ * (p'.val-p.val), mul_pos (inv_pos.mpr hβ) hα, ?_⟩ + calc + D-C = (q'.val-q.val)⁻¹ • ((q'.val-q.val) • (D-C)) := by + rw [smul_smul, inv_mul_cancel₀ hβ.ne', one_smul] + _ = (q'.val-q.val)⁻¹ • ((p'.val-p.val) • (B-A)) := by rw [heq] + _ = _ := by rw [smul_smul] + +/-- Interior overlap is sufficient for the positive direction comparison. -/ +theorem path_segments_direction_of_mem {a b : Plane} (γ η : Path a b) + (hγ : Function.Injective γ) (hη : Function.Injective η) + (hrange : Set.range γ = Set.range η) + (a₀ a₁ b₀ b₁ : unitInterval) (ha : a₀ < a₁) (hb : b₀ < b₁) + (A B C D : Plane) + (hγseg : ∀t, γ (intervalSegment a₀ a₁ t) = Paper170.segmentPoint A B t.val) + (hηseg : ∀t, η (intervalSegment b₀ b₁ t) = Paper170.segmentPoint C D t.val) + (x : Plane) (hx : x ∈ openSegmentTrace A B) (hy : x ∈ openSegmentTrace C D) : + ∃ r : ℝ, 0 < r ∧ D-C = r • (B-A) := by + obtain ⟨p, hp, hpx⟩ := hx + obtain ⟨q, hq, hqx⟩ := hy + exact path_segments_direction γ η hγ hη hrange a₀ a₁ b₀ b₁ ha hb A B C D + hγseg hηseg ⟨p, hp.1.le, hp.2.le⟩ ⟨q, hq.1.le, hq.2.le⟩ hp.2 hq.2 + (hpx.trans hqx.symm) + +end Paper170 + +end +end + +section + +noncomputable section +open Set Zarankiewicz +namespace Paper170 + +lemma reverse_affine_piece {a b : Plane} (γ : Path a b) + (a₀ a₁ : unitInterval) (A B : Plane) + (hseg : ∀t, γ (intervalSegment a₀ a₁ t) = Paper170.segmentPoint A B t.val) : + ∀t, γ.symm (intervalSegment (unitInterval.symm a₁) (unitInterval.symm a₀) t) = + Paper170.segmentPoint B A t.val := by + intro t + have hi : unitInterval.symm + (intervalSegment (unitInterval.symm a₁) (unitInterval.symm a₀) t) = + intervalSegment a₀ a₁ (unitInterval.symm t) := by + apply Subtype.ext + simp only [unitInterval.symm, intervalSegment] + ring + rw [Path.symm_apply, Function.comp_apply, hi, hseg] + ext <;> simp [Paper170.segmentPoint, unitInterval.symm] <;> ring + +theorem path_final_segments_direction {a b : Plane} (γ η : Path a b) + (hγ : Function.Injective γ) (hη : Function.Injective η) + (hrange : Set.range γ = Set.range η) + (a₀ a₁ b₀ b₁ : unitInterval) (ha : a₀ < a₁) (hb : b₀ < b₁) + (A B C D : Plane) + (hγseg : ∀t, γ (intervalSegment a₀ a₁ t) = Paper170.segmentPoint A B t.val) + (hηseg : ∀t, η (intervalSegment b₀ b₁ t) = Paper170.segmentPoint C D t.val) + (hpoint : B = D) : + ∃ r : ℝ, 0 < r ∧ C-D = r • (A-B) := by + apply path_segments_direction γ.symm η.symm + (hγ.comp unitInterval.symmHomeomorph.injective) + (hη.comp unitInterval.symmHomeomorph.injective) + (by simpa only [Path.symm_range] using hrange) + (unitInterval.symm a₁) (unitInterval.symm a₀) + (unitInterval.symm b₁) (unitInterval.symm b₀) + (unitInterval.symm_lt_symm.mpr ha) (unitInterval.symm_lt_symm.mpr hb) + B A D C (reverse_affine_piece γ a₀ a₁ A B hγseg) + (reverse_affine_piece η b₀ b₁ C D hηseg) 0 0 + (by norm_num) (by norm_num) + simpa [Paper170.segmentPoint] using hpoint + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Polygonalization.lean b/lean/OAI/Combinatorics/CompleteCrossing/Polygonalization.lean new file mode 100644 index 0000000000000000000000000000000000000000..a39644eb6037568c829c43712eb720a9b555e3b3 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Polygonalization.lean @@ -0,0 +1,423 @@ +import OAI.Combinatorics.CompleteCrossing.Assembly +import OAI.Combinatorics.Crossing.PolygonalNormalization +import OAI.Combinatorics.Crossing.ProperCrossingLocality +import OAI.Combinatorics.Crossing.ProperSegmentCrossing + +namespace OAI + +/-! Admissible polygonal replacement and retention of crossing counts. -/ + +section + +/-! Inside a crossing disk, an assembled edge has exactly its assigned straight chord trace. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +def crossingDisk (C : DrawingPassages D) (p : C.InnerIndex) : Set Plane := + {x | squaredLength (x-(C.innerMark p).val) < C.radius^2} + +theorem crossingDisk_isOpen (C : DrawingPassages D) (p : C.InnerIndex) : IsOpen (C.crossingDisk p) := by + apply isOpen_lt _ continuous_const + unfold squaredLength + fun_prop + +theorem crossingDisk_subset_closed (C : DrawingPassages D) (p : C.InnerIndex) : + C.crossingDisk p ⊆ closedRoundDisk (C.innerMark p).val C.radius := by + intro x hx + exact (show squaredLength (x-(C.innerMark p).val) < C.radius^2 from hx).le + +theorem crossingDisk_disjoint_vertex_disk (C : DrawingPassages D) (p : C.InnerIndex) + (j : Vertex) : + Disjoint (C.crossingDisk p) (closedRoundDisk (D.vertex j) C.radius) := by + have hn : C.innerMark p ≠ C.vertexMark j := by + intro he + exact crossing_not_vertex D (C.innerMark p).val (C.innerMark_is_crossing p) j (congrArg Subtype.val he) + exact (C.disks_disjoint _ _ hn).mono (C.crossingDisk_subset_closed p) Set.Subset.rfl + +theorem crossingChord_openTrace_iff (C : DrawingPassages D) (p : C.InnerIndex) + (x : Plane) (hx : x ∈ C.crossingDisk p) : + x ∈ Set.range (C.crossingChord p) ↔ + x ∈ openSegmentTrace (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) := by + constructor + · rintro ⟨t,ht⟩ + have ht0 : t ≠ 0 := by + intro he + subst t + rw [Path.source] at ht + change squaredLength (x-(C.innerMark p).val) < C.radius^2 at hx + rw [← ht,C.incomingPoint_on_circle] at hx + exact lt_irrefl _ hx + have ht1 : t ≠ 1 := by + intro he + subst t + rw [Path.target] at ht + change squaredLength (x-(C.innerMark p).val) < C.radius^2 at hx + rw [← ht,C.outgoingPoint_on_circle] at hx + exact lt_irrefl _ hx + refine ⟨t.val,⟨?_,?_⟩,?_⟩ + · exact lt_of_le_of_ne t.property.1 (fun he => ht0 (Subtype.ext he.symm)) + · exact lt_of_le_of_ne t.property.2 (fun he => ht1 (Subtype.ext he)) + · simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + · rintro ⟨t,ht,he⟩ + refine ⟨⟨t,ht.1.le,ht.2.le⟩,?_⟩ + simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he + +end DrawingPassages +namespace PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem assembled_range_in_crossingDisk (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p : C.InnerIndex) (x : Plane) (hx : x ∈ C.crossingDisk p) : + x ∈ Set.range (E.assembledEdge v p.1) ↔ x ∈ Set.range (C.crossingChord p) := by + constructor + · intro he + rcases (E.assembledEdge_range_iff v p.1 x).mp he with (he | ⟨i,hi,he⟩ | ⟨q,hq,he⟩) | he + · exact False.elim (Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p _) + hx (C.vertex_spoke_range_in_disk v hv _ (C.startPortAt p.1) he)) + · obtain ⟨t,rfl⟩ := he + exact False.elim (hx.not_ge (E.outside_open_disks i t (C.innerMark p))) + · have hm : C.innerMark q=C.innerMark p := by + by_contra hn + exact Set.disjoint_left.mp (C.disks_disjoint _ _ hn) + (C.crossingChord_range_subset_disk q he) (C.crossingDisk_subset_closed p hx) + have hqp := C.innerIndex_eq_of_edge_mark q p hq hm + exact hqp ▸ he + · rw [endSpoke_range] at he + exact False.elim (Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p _) + hx (C.vertex_spoke_range_in_disk v hv _ (C.endPortAt p.1) he)) + · intro he + apply (E.assembledEdge_range_iff v p.1 x).mpr + exact Or.inl (Or.inr (Or.inr ⟨p,rfl,he⟩)) + +theorem assembled_trace_in_crossingDisk (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p : C.InnerIndex) (x : Plane) (hx : x ∈ C.crossingDisk p) : + x ∈ Paper170.edgeInterior (E.assembledDrawing v hvinj hv) p.1 ↔ + x ∈ openSegmentTrace (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) := by + have havoid : ∀ j, x ≠ v j := by + intro j he + exact Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p j) hx (he.symm ▸ (hv j).le) + rw [← C.crossingChord_openTrace_iff p x hx,← E.assembled_range_in_crossingDisk v hv p x hx] + constructor + · rintro ⟨t,ht,he⟩ + exact ⟨t,he⟩ + · rintro ⟨t,he⟩ + have ht0 : t ≠ 0 := by + intro ht + subst t + rw [Path.source] at he + exact havoid _ he.symm + have ht1 : t ≠ 1 := by + intro ht + subst t + rw [Path.target] at he + exact havoid _ he.symm + exact ⟨t,⟨lt_of_le_of_ne (show 0 ≤ t from t.property.1) (Ne.symm ht0), + lt_of_le_of_ne (show t ≤ 1 from t.property.2) ht1⟩,he⟩ + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! All admissibility conditions and spatial crossing-count nonincrease for the assembled drawing. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +theorem crossingChord_meeting_proper (C : DrawingPassages D) (p q : C.InnerIndex) + (hpq : p ≠ q) (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) + (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∈ C.crossingDisk p ∧ + Paper170.ProperCrossing + (openSegmentTrace (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p))) + (openSegmentTrace (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) x := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨s,hs⟩ := hxp + obtain ⟨t,ht⟩ := hxq + have hst : segmentPoint (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) s.val = + segmentPoint (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) t.val := by + simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs.trans ht.symm + obtain ⟨hd,hsi,hti⟩ := C.crossing_chords_transverse_at_mark p q hpq hm s.val s.property t.val t.property hst + refine ⟨?_,?_⟩ + · rw [← hs] + exact C.crossingChord_interior_in_disk p s hsi + · constructor + apply properCrossing_openSegments _ _ _ _ x hd + · exact ⟨s.val,hsi,by simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs⟩ + · exact ⟨t.val,hti,by simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht⟩ + +end DrawingPassages +namespace PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem assembled_crossings_proper (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e f : Edge) (hef : e ≠ f) (x : Plane) + (hx : x ∈ Paper170.edgeInterior (E.assembledDrawing v hvinj hv) e) + (hy : x ∈ Paper170.edgeInterior (E.assembledDrawing v hvinj hv) f) : + Paper170.ProperCrossing (Paper170.edgeInterior (E.assembledDrawing v hvinj hv) e) + (Paper170.edgeInterior (E.assembledDrawing v hvinj hv) f) x := by + obtain ⟨s,hs,he⟩ := hx + obtain ⟨t,ht,hf⟩ := hy + obtain ⟨p,q,hp,hq,hxp,hxq⟩ := E.assembled_meeting_chords v hv hdet e f hef x + (fun j heq => E.assembledEdge_interior_avoids_vertices v hv e s hs j (he.trans heq)) ⟨s,he⟩ ⟨t,hf⟩ + have hpq : p ≠ q := fun heq => hef (hp.symm.trans ((congrArg Sigma.fst heq).trans hq)) + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨hxin,hproper⟩ := C.crossingChord_meeting_proper p q hpq x hxp hxq + constructor + apply properCrossing_of_local_eq _ _ _ _ x hproper.chart_exists (C.crossingDisk p) (C.crossingDisk_isOpen p) hxin + · intro z hz + simpa only [hp] using (E.assembled_trace_in_crossingDisk v hvinj hv p z hz).symm + · intro z hz + have hzq : z ∈ C.crossingDisk q := by + change squaredLength (z-(C.innerMark q).val) < C.radius^2 + rw [← hm] + exact hz + simpa only [hq] using (E.assembled_trace_in_crossingDisk v hvinj hv q z hzq).symm + +def assembledAdmissible (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : Paper170.AdmissibleDrawing graph where + toContinuousDrawing := E.assembledDrawing v hvinj hv + crossings_finite := E.assembled_crossings_finite v hvinj hv hdet + crossings_proper := E.assembled_crossings_proper v hvinj hv hdet + no_triples := E.assembled_no_triples v hvinj hv hdet + +theorem assembled_crossingCount_le (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + Paper170.crossingCount (E.assembledAdmissible v hvinj hv hdet) ≤ finiteCrossingCount D := by + have h := Set.ncard_le_ncard (E.assembled_crossings_subset v hvinj hv hdet) C.chordCrossings_finite + have hcount : Paper170.crossingCount (E.assembledAdmissible v hvinj hv hdet)= + (Paper170.crossingPoints (E.assembledDrawing v hvinj hv)).ncard := by + rw [Set.ncard_eq_toFinset_card _ (E.assembled_crossings_finite v hvinj hv hdet)] + rfl + rw [hcount] + exact h.trans C.chordCrossings_ncard_le + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! Appendix A's actual polygonal normalization, with full admissibility and point-count control. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +namespace PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem middlePath_hasFiniteAffineCover (E : PolygonalExterior C) (e : Edge) : + HasFiniteAffineCover (E.middlePath e) := + alternatingPath_hasFiniteAffineCover _ _ _ _ (fun i => (E.chain (C.orderedArc e i)).hasFiniteAffineCover) + (fun _ => hasFiniteAffineCover_segment _ _) _ + +theorem assembledEdge_hasFiniteAffineCover (E : PolygonalExterior C) + (v : Vertex → Plane) (e : Edge) : + HasFiniteAffineCover (E.assembledEdge v e) := by + apply HasFiniteAffineCover.trans + · apply HasFiniteAffineCover.trans (hasFiniteAffineCover_segment _ _) + exact E.middlePath_hasFiniteAffineCover e + · simp only [endSpoke,Path.segment_symm] + exact hasFiniteAffineCover_segment _ _ + +end PolygonalExterior + +/-- Finite contacts and no triples suffice to construct genuinely proper crossings. -/ +theorem finite_intersection_normalization [Fintype Vertex] [Fintype Edge] (D : FiniteIntersectionDrawing graph) : + ∃ D' : Paper170.AdmissibleDrawing graph, + (∀ e, HasFiniteAffineCover (D'.edge e)) ∧ Paper170.crossingCount D' ≤ finiteCrossingCount D := by + obtain ⟨C⟩ := nonempty_drawingPassages D + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + exact ⟨E.assembledAdmissible v hvinj hv hdet,E.assembledEdge_hasFiniteAffineCover v, + E.assembled_crossingCount_le v hvinj hv hdet⟩ + +/-- An arbitrary admissible continuous drawing admits an actual admissible +polygonal drawing with no more spatial crossing points. Vertices and routes +are allowed to move. No one-crossing-per-pair or adjacency condition is assumed. -/ +theorem polygonal_normalization [Fintype Vertex] [Fintype Edge] (D : Paper170.AdmissibleDrawing graph) : + ∃ D' : Paper170.AdmissibleDrawing graph, + (∀ e, HasFiniteAffineCover (D'.edge e)) ∧ Paper170.crossingCount D' ≤ Paper170.crossingCount D := by + obtain ⟨C⟩ := nonempty_drawingPassages D.toFiniteIntersectionDrawing + obtain ⟨E⟩ := nonempty_polygonalExterior C + obtain ⟨v,hvinj,hv,hne,hdet⟩ := C.exists_drawing_vertex_placement + exact ⟨E.assembledAdmissible v hvinj hv hdet,E.assembledEdge_hasFiniteAffineCover v, + E.assembled_crossingCount_le v hvinj hv hdet⟩ + +end Paper170Geometry + +end +end + +section + +/-! At equal total count, reassembly retains every original crossing and its incident pair. -/ +noncomputable section +open Set +namespace Paper170Geometry +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +theorem chordCrossingOrigin_eq_innerMark (C : DrawingPassages D) {y : Plane} + (hy : y ∈ C.chordCrossings) (p : C.InnerIndex) (hp : y ∈ Set.range (C.crossingChord p)) : + C.chordCrossingOrigin y = (C.innerMark p).val := by + unfold chordCrossingOrigin + rw [dite_eq_left hy] + obtain ⟨r,s,hrs,hr,hs,hyr,hys⟩ := (C.chord_crossing_original_mark hy).choose_spec.2 + exact congrArg Subtype.val ((C.chord_meeting_marks_eq p r hp hyr).trans hr).symm + +end DrawingPassages +namespace PolygonalExterior +variable {D : FiniteIntersectionDrawing graph} {C : DrawingPassages D} + +theorem assembled_origin_mem_pair (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (e f : Edge) (hef : e ≠ f) (y : Plane) + (he : y ∈ Paper170.edgeInterior (E.assembledDrawing v hvinj hv) e) + (hf : y ∈ Paper170.edgeInterior (E.assembledDrawing v hvinj hv) f) : + C.chordCrossingOrigin y ∈ Paper170.edgeInterior D.toContinuousDrawing e ∧ + C.chordCrossingOrigin y ∈ Paper170.edgeInterior D.toContinuousDrawing f := by + have hy := E.assembled_crossings_subset v hvinj hv hdet ⟨e,f,hef,he,hf⟩ + obtain ⟨s,hs,hys⟩ := he + obtain ⟨t,ht,hyt⟩ := hf + obtain ⟨p,q,hp,hq,hyp,hyq⟩ := E.assembled_meeting_chords v hv hdet e f hef y + (fun j heq => E.assembledEdge_interior_avoids_vertices v hv e s hs j (hys.trans heq)) + ⟨s,hys⟩ ⟨t,hyt⟩ + constructor + · rw [C.chordCrossingOrigin_eq_innerMark hy p hyp, ← hp] + exact ⟨C.node p.1 p.2.val,C.inner_parameter_interior p,rfl⟩ + · rw [C.chordCrossingOrigin_eq_innerMark hy q hyq, ← hq] + exact ⟨C.node q.1 q.2.val,C.inner_parameter_interior q,rfl⟩ + +theorem assembled_origin_surj_of_count_eq (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (hcount : Paper170.crossingCount (E.assembledAdmissible v hvinj hv hdet) = finiteCrossingCount D) : + Set.SurjOn C.chordCrossingOrigin (Paper170.crossingPoints (E.assembledDrawing v hvinj hv)) + (Paper170.crossingPoints D.toContinuousDrawing) := by + have hsub := E.assembled_crossings_subset v hvinj hv hdet + have hmap := C.chordCrossingOrigin_mapsTo.mono_left hsub + have hinj := C.chordCrossingOrigin_injOn.mono hsub + have hsize : (Paper170.crossingPoints D.toContinuousDrawing).ncard ≤ + (C.chordCrossingOrigin '' Paper170.crossingPoints (E.assembledDrawing v hvinj hv)).ncard := by + rw [hinj.ncard_image, ← finiteCrossingCount_eq_ncard] + rw [Set.ncard_eq_toFinset_card _ (E.assembled_crossings_finite v hvinj hv hdet)] + exact hcount.ge + have heq := Set.eq_of_subset_of_ncard_le hmap.image_subset hsize D.crossings_finite + intro x hx + rw [← heq] at hx + exact hx + +theorem assembled_pair_retained_of_count_eq + {D₀ : Paper170.AdmissibleDrawing graph} {C₀ : DrawingPassages D₀.toFiniteIntersectionDrawing} + (E : PolygonalExterior C₀) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D₀.vertex j) < C₀.radius^2) + (hdet : ∀ j (p q : C₀.PortsAt (C₀.vertexMark j)), p ≠ q → + det2 (C₀.portPoint p.val-v j) (C₀.portPoint q.val-v j) ≠ 0) + (hcount : Paper170.crossingCount (E.assembledAdmissible v hvinj hv hdet) = + Paper170.crossingCount D₀) + (e f : Edge) (hef : e ≠ f) (x : Plane) + (hxe : x ∈ Paper170.edgeInterior D₀.toContinuousDrawing e) + (hxf : x ∈ Paper170.edgeInterior D₀.toContinuousDrawing f) : + ∃ y, y ∈ Paper170.edgeInterior (E.assembledDrawing v hvinj hv) e ∧ + y ∈ Paper170.edgeInterior (E.assembledDrawing v hvinj hv) f := by + obtain ⟨y,hy,hxy⟩ := E.assembled_origin_surj_of_count_eq v hvinj hv hdet hcount + (show x ∈ Paper170.crossingPoints D₀.toContinuousDrawing from ⟨e,f,hef,hxe,hxf⟩) + obtain ⟨a,b,hab,hya,hyb⟩ := hy + have hold := E.assembled_origin_mem_pair v hvinj hv hdet a b hab y hya hyb + rw [hxy] at hold + have ha := (crossing_incident_iff D₀ x e f hef hxe hxf a).mp hold.1 + have hb := (crossing_incident_iff D₀ x e f hef hxe hxf b).mp hold.2 + rcases ha with rfl | rfl <;> rcases hb with rfl | rfl + · exact False.elim (hab rfl) + · exact ⟨y,hya,hyb⟩ + · exact ⟨y,hyb,hya⟩ + · exact False.elim (hab rfl) + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! Subdivide actual polygonal drawings at all marks and any extra finite set of spatial points. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem exists_drawing_subdivision_at [Fintype Vertex] (D : Paper170.AdmissibleDrawing graph) + (hpoly : ∀ e, HasFiniteAffineCover (D.edge e)) (S : Set Plane) (hS : S.Finite) : + ∃ P : ∀ e, PolygonalParametrization (D.edge e), + (∀ e t, D.edge e t ∈ drawingMarks D.toFiniteIntersectionDrawing → t ∈ Set.range (P e).knot) ∧ + (∀ e t, D.edge e t ∈ S → t ∈ Set.range (P e).knot) := by + classical + have hfinite (e : Edge) : ((D.edge e) ⁻¹' (drawingMarks D.toFiniteIntersectionDrawing ∪ S)).Finite := + ((drawingMarks_finite D.toFiniteIntersectionDrawing).union hS).preimage (D.edge_injective e).injOn + have hex (e : Edge) := (hpoly e).refine (hfinite e).toFinset + choose P hP using hex + refine ⟨P,?_,?_⟩ + · intro e t ht + exact hP e (by simpa using Or.inl ht) + · intro e t ht + exact hP e (by simpa using Or.inr ht) + +namespace PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem exists_assembled_port_subdivision [Fintype Vertex] [Fintype Edge] (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) : + ∃ P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e), + (∀ e t, E.assembledEdge v e t ∈ drawingMarks (E.assembledAdmissible v hvinj hv hdet).toFiniteIntersectionDrawing → + t ∈ Set.range (P e).knot) ∧ + (∀ e t, E.assembledEdge v e t ∈ Set.range C.portPoint → t ∈ Set.range (P e).knot) := + exists_drawing_subdivision_at (E.assembledAdmissible v hvinj hv hdet) + (E.assembledEdge_hasFiniteAffineCover v) (Set.range C.portPoint) (Set.finite_range _) + +end PolygonalExterior +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Polynomials.lean b/lean/OAI/Combinatorics/CompleteCrossing/Polynomials.lean new file mode 100644 index 0000000000000000000000000000000000000000..03279cd7b48dc0af2bd9b05fc9da57d1129448a0 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Polynomials.lean @@ -0,0 +1,621 @@ +import OAI.Combinatorics.CompleteCrossing.Interpolation +import Mathlib.Algebra.BigOperators.Associated +import Mathlib.Algebra.MvPolynomial.Equiv +import Mathlib.Algebra.MvPolynomial.Funext +import Mathlib.Algebra.Polynomial.Roots +import Mathlib.Data.Sym.Card +import Mathlib.LinearAlgebra.Dimension.Constructions +import Mathlib.RingTheory.Ideal.Quotient.Operations +import Mathlib.RingTheory.MvPolynomial.IrreducibleQuadratic +import Mathlib.RingTheory.Polynomial.UniqueFactorization +import Mathlib.Tactic +import Mathlib.Tactic.NormNum + +namespace OAI + +/-! Coordinate symmetry, polynomial quotients, collision divisibility, and specialization. -/ + +section + +noncomputable section +open MvPolynomial +namespace Paper170 + +lemma substitution_difference_dvd {σ : Type*} (f : MvPolynomial σ ℝ) + (φ : MvPolynomial σ ℝ →ₐ[ℝ] MvPolynomial σ ℝ) + (hX : ∀ i, f ∣ X i - φ (X i)) (P : MvPolynomial σ ℝ) : f ∣ P - φ P := by + induction P using MvPolynomial.induction_on with + | C r => simp + | add P Q hP hQ => + have h := dvd_add hP hQ + simpa only [map_add, sub_add_sub_comm] using h + | mul_X P i hP => + have h := dvd_add (dvd_mul_of_dvd_left hP (X i)) + (dvd_mul_of_dvd_right (hX i) (φ P)) + convert h using 1 + rw [map_mul] + ring + +private def reinsertDiagonal : MvPolynomial (Fin 3) ℝ →ₐ[ℝ] Poly4 := + MvPolynomial.aeval ![MvPolynomial.X 0, MvPolynomial.X 1, MvPolynomial.X 3] + +theorem diagonal_vanishing_iff_divisible (P : Poly4) : + diagonalSpecialization P = 0 ↔ (X 0 - X 2 : Poly4) ∣ P := by + let φ : Poly4 →ₐ[ℝ] Poly4 := reinsertDiagonal.comp diagonalSpecialization + have hX : ∀ i, (X 0 - X 2 : Poly4) ∣ X i - φ (X i) := by + intro i + fin_cases i <;> simp [φ, reinsertDiagonal, diagonalSpecialization, + Matrix.cons_val_two, Matrix.cons_val_three] + exact ⟨-1, by ring⟩ + constructor + · intro hP + have h := substitution_difference_dvd (X 0 - X 2) φ hX P + simpa [φ, hP] using h + · rintro ⟨Q, rfl⟩ + simp [diagonalSpecialization, Matrix.cons_val_two] + +end Paper170 + +end +end + +section + +noncomputable section +open MvPolynomial +namespace Paper170 + +lemma difference_coefficient (i j : Fin 4) (hij : i ≠ j) : + (X i - X j : Poly4).coeff (Finsupp.single i 1) = 1 := by + simp [coeff_X, Finsupp.single_left_inj, Ne.symm hij] + +lemma difference_degree (i j : Fin 4) (hij : i ≠ j) (k : Fin 4) : + (X i - X j : Poly4).degreeOf k = if k = i ∨ k = j then 1 else 0 := by + have hupper := degreeOf_sub_le k (X i : Poly4) (X j) + simp only [degreeOf_X] at hupper + by_cases hki : k = i + · subst k + rw [ite_eq_left (Or.inl rfl)] + apply Nat.le_antisymm + · simpa [hij] using hupper + · have hm : Finsupp.single i 1 ∈ (X i - X j : Poly4).support := + mem_support_iff.mpr (by rw [difference_coefficient i j hij]; norm_num) + simpa using monomial_le_degreeOf i hm + · by_cases hkj : k = j + · subst k + rw [ite_eq_left (Or.inr rfl)] + apply Nat.le_antisymm + · simpa [hki] using hupper + · have hc : (X i - X j : Poly4).coeff (Finsupp.single j 1) = -1 := by + simp [coeff_X, Finsupp.single_left_inj, hij] + have hm : Finsupp.single j 1 ∈ (X i - X j : Poly4).support := + mem_support_iff.mpr (by rw [hc]; norm_num) + simpa using monomial_le_degreeOf j hm + · rw [ite_eq_right (not_or.mpr ⟨hki, hkj⟩)] + exact Nat.eq_zero_of_le_zero (by simpa [hki, hkj] using hupper) + +theorem difference_prime (i j : Fin 4) (hij : i ≠ j) : + Prime (X i - X j : Poly4) := by + apply UniqueFactorizationMonoid.irreducible_iff_prime.mp + apply irreducible_of_totalDegree_eq_one + · apply Nat.le_antisymm + · simpa using totalDegree_sub (X i : Poly4) (X j) + · have h := degreeOf_le_totalDegree (X i - X j : Poly4) i + simpa [difference_degree i j hij] using h + · intro r hr + apply isUnit_of_dvd_one + simpa only [difference_coefficient i j hij] using hr (Finsupp.single i 1) + +theorem collision_factors_nonassociate : + Pairwise (fun i j : Fin 4 => ¬ Associated (collisionFactors i) (collisionFactors j)) := by + let w : Fin 4 → Fin 4 → ℝ := ![![0, 1, 0, 2], ![0, 1, 2, 0], + ![1, 0, 0, 2], ![1, 0, 2, 0]] + intro i j hij ha + have hi : eval (w i) (collisionFactors i) = 0 := by + fin_cases i <;> norm_num [w, collisionFactors, Matrix.cons_val_two, Matrix.cons_val_three] + have hj : eval (w i) (collisionFactors j) ≠ 0 := by + fin_cases i <;> fin_cases j + all_goals first | exact (hij rfl).elim | norm_num [w, collisionFactors, + Matrix.cons_val_two, Matrix.cons_val_three] + obtain ⟨Q, hQ⟩ := ha.dvd + have h := congrArg (eval (w i)) hQ + simp only [eval_mul, hi, zero_mul] at h + exact hj h + +theorem collision_factor_properties : + collisionFactor ≠ 0 ∧ swapFirstPair collisionFactor = collisionFactor ∧ + swapSecondPair collisionFactor = collisionFactor ∧ + ∀ i : Fin 4, collisionFactor.degreeOf i = 2 := by + have h02 := (difference_prime 0 2 (by decide)).ne_zero + have h03 := (difference_prime 0 3 (by decide)).ne_zero + have h12 := (difference_prime 1 2 (by decide)).ne_zero + have h13 := (difference_prime 1 3 (by decide)).ne_zero + refine ⟨mul_ne_zero (mul_ne_zero (mul_ne_zero h02 h03) h12) h13, ?_, ?_, ?_⟩ + · norm_num [collisionFactor, swapFirstPair, Equiv.swap_apply_def, Fin.ext_iff] + ring + · norm_num [collisionFactor, swapSecondPair, Equiv.swap_apply_def, Fin.ext_iff] + ring + · intro i + rw [collisionFactor, degreeOf_mul_eq (mul_ne_zero (mul_ne_zero h02 h03) h12) h13, + degreeOf_mul_eq (mul_ne_zero h02 h03) h12, degreeOf_mul_eq h02 h03] + fin_cases i <;> norm_num [difference_degree, Fin.ext_iff, show (0 : Fin 4) ≠ 2 by decide, + show (0 : Fin 4) ≠ 3 by decide, show (1 : Fin 4) ≠ 2 by decide, + show (1 : Fin 4) ≠ 3 by decide] + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators Classical +open Module MvPolynomial +namespace Paper170 + +abbrev BoundedExponents (d : ℕ) := Fin 4 → Fin (d + 1) + +def tupleExponent {d : ℕ} (t : BoundedExponents d) : Fin 4 →₀ ℕ := + Finsupp.equivFunOnFinite.symm (fun i => (t i).val) + +@[simp] lemma tupleExponent_apply {d : ℕ} (t : BoundedExponents d) (i : Fin 4) : + tupleExponent t i = (t i).val := rfl + +def boxExponentEquiv (d : ℕ) : + {m : Fin 4 →₀ ℕ // ∀ i, m i ≤ d} ≃ BoundedExponents d where + toFun m i := ⟨m.val i, Nat.lt_succ_of_le (m.property i)⟩ + invFun t := ⟨tupleExponent t, fun i => Nat.le_of_lt_succ (t i).isLt⟩ + left_inv m := by apply Subtype.ext; ext i; rfl + right_inv t := rfl + +lemma box_eq_restrictSupport (d : ℕ) : + box4 d = MvPolynomial.restrictSupport ℝ {m | ∀ i, m i ≤ d} := by + ext P + rw [box4_membership, MvPolynomial.mem_restrictSupport_iff] + simp only [degreeOf_le_iff, Set.subset_def, Finset.mem_coe, Set.mem_ofPred_eq] + exact ⟨fun h m hm i => h i m hm, fun h i m hm => h m hm i⟩ + +def boxBasis (d : ℕ) : Basis (BoundedExponents d) ℝ (box4 d) := + ((MvPolynomial.basisRestrictSupport ℝ _).reindex (boxExponentEquiv d)).map + (LinearEquiv.ofEq _ _ (box_eq_restrictSupport d).symm) + +lemma box_finite (d : ℕ) : FiniteDimensional ℝ (box4 d) := + Module.Finite.of_basis (boxBasis d) + +@[simp] lemma boxBasis_repr (d : ℕ) (P : box4 d) (t : BoundedExponents d) : + (boxBasis d).repr P t = P.val.coeff (tupleExponent t) := by + rfl + +theorem symmetric_space_finite (s : ℕ) : + FiniteDimensional ℝ (endpointSymmetricSpace s) := by + let := box_finite (s - 2) + let f : endpointSymmetricSpace s →ₗ[ℝ] box4 (s - 2) := + Submodule.inclusion (inf_le_left.trans inf_le_left) + exact FiniteDimensional.of_injective f (Submodule.inclusion_injective _) + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +@[simp] lemma swapFirstPair_mul (P Q : Poly4) : + swapFirstPair (P * Q) = swapFirstPair P * swapFirstPair Q := by + exact map_mul (MvPolynomial.rename (Equiv.swap (0 : Fin 4) 1)) P Q + +@[simp] lemma swapSecondPair_mul (P Q : Poly4) : + swapSecondPair (P * Q) = swapSecondPair P * swapSecondPair Q := by + exact map_mul (MvPolynomial.rename (Equiv.swap (2 : Fin 4) 3)) P Q + +theorem collision_quotient (s : ℕ) (_hs : 2 ≤ s) (P : Poly4) + (hP : P ∈ endpointSymmetricSpace s) (hP0 : P ≠ 0) (hdiv : collisionFactor ∣ P) : + ∃ Q : Poly4, Q ≠ 0 ∧ P = collisionFactor * Q ∧ + Q ∈ endpointSymmetricSpace s ∧ + (∀ i : Fin 4, Q.degreeOf i + 2 = P.degreeOf i) ∧ + Q.degreeOf 0 < P.degreeOf 0 := by + obtain ⟨Q, hQ⟩ := hdiv + have hQ0 : Q ≠ 0 := by + intro h + apply hP0 + simp [h, hQ] + rcases collision_factor_properties with ⟨hc, hc1, hc2, hcd⟩ + rcases (symmetric_space_membership s P).mp hP with ⟨hpdeg, hp1, hp2⟩ + have hdeg (i : Fin 4) : Q.degreeOf i + 2 = P.degreeOf i := by + rw [hQ, MvPolynomial.degreeOf_mul_eq hc hQ0, hcd, add_comm] + have hfirst : swapFirstPair Q = Q := by + apply mul_left_cancel₀ hc + calc + collisionFactor * swapFirstPair Q = swapFirstPair (collisionFactor * Q) := by + rw [swapFirstPair_mul, hc1] + _ = collisionFactor * Q := by rw [← hQ, hp1, hQ] + have hsecond : swapSecondPair Q = Q := by + apply mul_left_cancel₀ hc + calc + collisionFactor * swapSecondPair Q = swapSecondPair (collisionFactor * Q) := by + rw [swapSecondPair_mul, hc2] + _ = collisionFactor * Q := by rw [← hQ, hp2, hQ] + refine ⟨Q, hQ0, hQ, (symmetric_space_membership s Q).mpr ⟨?_, hfirst, hsecond⟩, + hdeg, ?_⟩ + · intro i + have := hdeg i + have := hpdeg i + omega + · have := hdeg 0 + omega + +end Paper170 + +end +end + +section + +noncomputable section +open MvPolynomial +namespace Paper170 + +/-- The three extra factors in the local test have the degree vector printed in the paper. -/ +theorem local_weight_degrees (i : Fin 4) : + ((X 1 - X 3) * (X 1 - X 2) * (X 3 - X 0) : Poly4).degreeOf i = + (![1, 2, 1, 2] : Fin 4 → ℕ) i := by + have h13 := (difference_prime 1 3 (by decide)).ne_zero + have h12 := (difference_prime 1 2 (by decide)).ne_zero + have h30 := (difference_prime 3 0 (by decide)).ne_zero + rw [degreeOf_mul_eq (mul_ne_zero h13 h12) h30, degreeOf_mul_eq h13 h12] + fin_cases i <;> norm_num [difference_degree, Fin.ext_iff, + show (1 : Fin 4) ≠ 3 by decide, show (1 : Fin 4) ≠ 2 by decide, + show (3 : Fin 4) ≠ 0 by decide] + +/-- Identifying any two variables leaves a polynomial ring in the other three. -/ +theorem difference_quotient_polynomial (i j : Fin 4) (hij : i ≠ j) : + Nonempty ((Poly4 ⧸ Ideal.span ({X i - X j} : Set Poly4)) ≃ₐ[ℝ] + MvPolynomial (Fin 3) ℝ) := by + classical + let collapse : Fin 4 → {k : Fin 4 // k ≠ i} := fun k => + if h : k = i then ⟨j, hij.symm⟩ else ⟨k, h⟩ + let φ : Poly4 →ₐ[ℝ] MvPolynomial {k : Fin 4 // k ≠ i} ℝ := rename collapse + let insert : MvPolynomial {k : Fin 4 // k ≠ i} ℝ →ₐ[ℝ] Poly4 := rename Subtype.val + have hs : Function.Surjective φ := by + apply rename_surjective + intro k + refine ⟨k.val, ?_⟩ + simp [collapse, k.property] + have hk : RingHom.ker φ.toRingHom = Ideal.span ({X i - X j} : Set Poly4) := by + ext P + rw [RingHom.mem_ker, Ideal.mem_span_singleton] + change φ P = 0 ↔ (X i - X j : Poly4) ∣ P + constructor + · intro hp + have hx : ∀k, (X i - X j : Poly4) ∣ X k - (insert.comp φ) (X k) := by + intro k + by_cases hki : k = i + · subst k + simp [insert, φ, collapse] + · simp [insert, φ, collapse, hki] + have h := substitution_difference_dvd (X i - X j) (insert.comp φ) hx P + simpa [hp] using h + · rintro ⟨Q, rfl⟩ + simp [φ, collapse, hij.symm] + exact ⟨(Ideal.quotientEquivAlgOfEq ℝ hk.symm).trans + ((Ideal.quotientKerAlgEquivOfSurjective hs).trans + (renameEquiv ℝ (finSuccAboveEquiv (p := i)).symm))⟩ + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators Classical +open MvPolynomial +namespace Paper170 + +def diagonalUnivariate (u v : ℝ) : Poly4 →ₐ[ℝ] Polynomial ℝ := + MvPolynomial.aeval ![Polynomial.X, Polynomial.C u, Polynomial.X, Polynomial.C v] + +lemma diagonalUnivariate_monomial (u v : ℝ) (m : Fin 4 →₀ ℕ) (c : ℝ) : + diagonalUnivariate u v (monomial m c) = + Polynomial.C (c * u ^ m 1 * v ^ m 3) * Polynomial.X ^ (m 0 + m 2) := by + simp only [diagonalUnivariate, MvPolynomial.aeval_monomial, + Polynomial.algebraMap_apply] + rw [Finsupp.prod_fintype] + · simp [Fin.prod_univ_four, pow_add] + ring + · intro i + simp + +lemma diagonalUnivariate_bound (s : ℕ) (P : endpointSymmetricSpace s) (u v : ℝ) : + (diagonalUnivariate u v P.val).natDegree ≤ 2 * (s - 2) := by + have hp := ((symmetric_space_membership s P.val).mp P.property).1 + rw [P.val.as_sum, map_sum] + apply Polynomial.natDegree_sum_le_of_forall_le + intro m hm + rw [diagonalUnivariate_monomial] + have h0 := degreeOf_le_iff.mp (hp 0) m hm + have h2 := degreeOf_le_iff.mp (hp 2) m hm + calc + (Polynomial.C (P.val.coeff m * u ^ m 1 * v ^ m 3) * + Polynomial.X ^ (m 0 + m 2)).natDegree ≤ m 0 + m 2 := by + simpa using Polynomial.natDegree_C_mul_le (P.val.coeff m * u ^ m 1 * v ^ m 3) + (Polynomial.X ^ (m 0 + m 2) : Polynomial ℝ) + _ ≤ 2 * (s - 2) := by omega + +lemma diagonalUnivariate_eval (u v x : ℝ) (P : Poly4) : + (diagonalUnivariate u v P).eval x = evalFour x u x v P := by + induction P using MvPolynomial.induction_on with + | C r => simp [diagonalUnivariate, evalFour] + | add P Q hP hQ => simpa using congrArg₂ (· + ·) hP hQ + | mul_X P i hP => + simp only [map_mul, Polynomial.eval_mul] + rw [hP] + fin_cases i <;> simp [diagonalUnivariate, evalFour, Matrix.cons_val_two, + Matrix.cons_val_three] + +lemma diagonal_eval (P : Poly4) (x u v : ℝ) : + MvPolynomial.eval ![x, u, v] (diagonalSpecialization P) = evalFour x u x v P := by + induction P using MvPolynomial.induction_on with + | C r => simp [diagonalSpecialization, evalFour] + | add P Q hP hQ => simpa using congrArg₂ (· + ·) hP hQ + | mul_X P i hP => + simp only [map_mul] + rw [hP] + fin_cases i <;> simp [diagonalSpecialization, evalFour, Matrix.cons_val_two, + Matrix.cons_val_three] + +lemma vertex_eval (P : Poly4) (x u v : ℝ) : + evalTwo u v (vertexSpecialization x P) = evalFour x u x v P := by + induction P using MvPolynomial.induction_on with + | C r => simp [vertexSpecialization, evalFour, evalTwo] + | add P Q hP hQ => simpa using congrArg₂ (· + ·) hP hQ + | mul_X P i hP => + change MvPolynomial.aeval ![u, v] _ = MvPolynomial.aeval ![x, u, x, v] _ + change MvPolynomial.aeval ![u, v] _ = MvPolynomial.aeval ![x, u, x, v] _ at hP + simp only [map_mul] + rw [hP] + fin_cases i <;> simp [vertexSpecialization, Matrix.cons_val_two, + Matrix.cons_val_three] + +lemma diagonal_zero_of_vertices (s : ℕ) (node : Fin (2 * s + 1) → ℝ) + (hn : Function.Injective node) (P : endpointSymmetricSpace s) + (hP : ∀ i, vertexSpecialization (node i) P.val = 0) : + diagonalSpecialization P.val = 0 := by + have hpoly (u v : ℝ) : diagonalUnivariate u v P.val = 0 := by + apply Polynomial.eq_zero_of_natDegree_lt_card_of_eval_eq_zero _ hn + · intro i + rw [diagonalUnivariate_eval, ← vertex_eval, hP, map_zero] + · have h := diagonalUnivariate_bound s P u v + simp only [Fintype.card_fin] + omega + apply MvPolynomial.funext + intro t + have ht : t = ![t 0, t 1, t 2] := by ext i; fin_cases i <;> rfl + rw [ht, diagonal_eval, ← diagonalUnivariate_eval, hpoly] + simp + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators Classical +open MvPolynomial +namespace Paper170 + +theorem box_rename {d : ℕ} {P : Poly4} (hP : P ∈ box4 d) (e : Equiv.Perm (Fin 4)) : + rename e P ∈ box4 d := by + apply (box4_membership _ _).mpr + intro i + obtain ⟨j, rfl⟩ := e.surjective i + rw [degreeOf_rename_of_injective e.injective] + exact (box4_membership _ _).mp hP j + +theorem coeff_rename_tuple {d : ℕ} (e : Equiv.Perm (Fin 4)) (P : Poly4) + (t : BoundedExponents d) : + (rename e P).coeff (tupleExponent t) = + P.coeff (tupleExponent (fun i => t (e i))) := by + have he : (tupleExponent (fun i => t (e i))).mapDomain e = tupleExponent t := by + ext i + simp [Finsupp.mapDomain_equiv_apply] + rw [← he, coeff_rename_mapDomain e e.injective] + +theorem box_coeff_ext {d : ℕ} {P Q : Poly4} (hP : P ∈ box4 d) (hQ : Q ∈ box4 d) + (h : ∀ t : BoundedExponents d, P.coeff (tupleExponent t) = Q.coeff (tupleExponent t)) : + P = Q := by + have he : (⟨P, hP⟩ : box4 d) = ⟨Q, hQ⟩ := by + apply (boxBasis d).repr.injective + ext t + exact h t + exact congrArg Subtype.val he + +theorem tuple4_eta {α : Type*} (t : Fin 4 → α) : ![t 0, t 1, t 2, t 3] = t := by + funext i + fin_cases i <;> simp + +abbrev SymmetricCoordinate (d : ℕ) := Sym2 (Fin (d + 1)) × Sym2 (Fin (d + 1)) + +def tupleOrbit {d : ℕ} (t : BoundedExponents d) : SymmetricCoordinate d := + (s(t 0, t 1), s(t 2, t 3)) + +theorem tupleOrbit_swap_first {d : ℕ} (t : BoundedExponents d) : + tupleOrbit (fun i => t (Equiv.swap (0 : Fin 4) 1 i)) = tupleOrbit t := by + change (s(t 1, t 0), s(t 2, t 3)) = (s(t 0, t 1), s(t 2, t 3)) + exact Prod.ext Sym2.eq_swap rfl + +theorem tupleOrbit_swap_second {d : ℕ} (t : BoundedExponents d) : + tupleOrbit (fun i => t (Equiv.swap (2 : Fin 4) 3 i)) = tupleOrbit t := by + change (s(t 0, t 1), s(t 3, t 2)) = (s(t 0, t 1), s(t 2, t 3)) + exact Prod.ext rfl Sym2.eq_swap + +theorem symmetric_coeff_first {s : ℕ} (P : endpointSymmetricSpace s) + (a b c d : Fin (s - 2 + 1)) : + P.val.coeff (tupleExponent ![a, b, c, d]) = P.val.coeff (tupleExponent ![b, a, c, d]) := by + have he : (fun i => (![a, b, c, d] : BoundedExponents (s - 2)) + (Equiv.swap (0 : Fin 4) 1 i)) = ![b, a, c, d] := by + funext i + fin_cases i <;> simp [Equiv.swap_apply_def] + have hp := ((symmetric_space_membership s P.val).mp P.property).2.1 + change rename (Equiv.swap (0 : Fin 4) 1) P.val = P.val at hp + have hc := coeff_rename_tuple (Equiv.swap (0 : Fin 4) 1) P.val ![a, b, c, d] + rwa [he, hp] at hc + +theorem symmetric_coeff_second {s : ℕ} (P : endpointSymmetricSpace s) + (a b c d : Fin (s - 2 + 1)) : + P.val.coeff (tupleExponent ![a, b, c, d]) = P.val.coeff (tupleExponent ![a, b, d, c]) := by + have he : (fun i => (![a, b, c, d] : BoundedExponents (s - 2)) + (Equiv.swap (2 : Fin 4) 3 i)) = ![a, b, d, c] := by + funext i + fin_cases i <;> simp [Equiv.swap_apply_def] + have hp := ((symmetric_space_membership s P.val).mp P.property).2.2 + change rename (Equiv.swap (2 : Fin 4) 3) P.val = P.val at hp + have hc := coeff_rename_tuple (Equiv.swap (2 : Fin 4) 3) P.val ![a, b, c, d] + rwa [he, hp] at hc + +def symmetricCoefficients {s : ℕ} (P : endpointSymmetricSpace s) : + SymmetricCoordinate (s - 2) → ℝ := fun q => + Sym2.lift₂ ⟨(fun a b c d => P.val.coeff (tupleExponent ![a, b, c, d])), + fun a b c d => ⟨symmetric_coeff_first P a b c d, symmetric_coeff_second P a b c d⟩⟩ q.1 q.2 + +@[simp] theorem symmetricCoefficients_orbit {s : ℕ} (P : endpointSymmetricSpace s) + (t : BoundedExponents (s - 2)) : + symmetricCoefficients P (tupleOrbit t) = P.val.coeff (tupleExponent t) := by + simp [symmetricCoefficients, tupleOrbit, tuple4_eta] + +def realizeBox (d : ℕ) (f : SymmetricCoordinate d → ℝ) : box4 d := + (boxBasis d).equivFun.symm (fun t => f (tupleOrbit t)) + +@[simp] theorem realizeBox_coeff (d : ℕ) (f : SymmetricCoordinate d → ℝ) + (t : BoundedExponents d) : + (realizeBox d f).val.coeff (tupleExponent t) = f (tupleOrbit t) := by + change (boxBasis d).equivFun ((boxBasis d).equivFun.symm _) t = _ + rw [LinearEquiv.apply_symm_apply] + +theorem realizeBox_symmetric (s : ℕ) (f : SymmetricCoordinate (s - 2) → ℝ) : + (realizeBox (s - 2) f).val ∈ endpointSymmetricSpace s := by + apply (symmetric_space_membership _ _).mpr + refine ⟨(box4_membership _ _).mp (realizeBox (s - 2) f).property, ?_, ?_⟩ + · apply box_coeff_ext (box_rename (realizeBox (s - 2) f).property _) + (realizeBox (s - 2) f).property + intro t + change (rename (Equiv.swap (0 : Fin 4) 1) _).coeff (tupleExponent t) = _ + rw [coeff_rename_tuple, realizeBox_coeff, realizeBox_coeff, tupleOrbit_swap_first] + · apply box_coeff_ext (box_rename (realizeBox (s - 2) f).property _) + (realizeBox (s - 2) f).property + intro t + change (rename (Equiv.swap (2 : Fin 4) 3) _).coeff (tupleExponent t) = _ + rw [coeff_rename_tuple, realizeBox_coeff, realizeBox_coeff, tupleOrbit_swap_second] + +def realizeSymmetric (s : ℕ) (f : SymmetricCoordinate (s - 2) → ℝ) : endpointSymmetricSpace s := + ⟨(realizeBox (s - 2) f).val, realizeBox_symmetric s f⟩ + +def symmetricCoordinatesEquiv (s : ℕ) : + endpointSymmetricSpace s ≃ₗ[ℝ] (SymmetricCoordinate (s - 2) → ℝ) where + toFun := symmetricCoefficients + invFun := realizeSymmetric s + left_inv P := by + apply Subtype.ext + apply box_coeff_ext (realizeBox (s - 2) (symmetricCoefficients P)).property + ((box4_membership _ _).mpr ((symmetric_space_membership _ _).mp P.property).1) + intro t + rw [realizeBox_coeff, symmetricCoefficients_orbit] + right_inv f := by + funext q + rcases q with ⟨a, b⟩ + induction a using Sym2.ind + induction b using Sym2.ind + simp [symmetricCoefficients, realizeSymmetric, realizeBox_coeff, tupleOrbit] + map_add' P Q := by + funext q + rcases q with ⟨a, b⟩ + induction a using Sym2.ind + induction b using Sym2.ind + simp [symmetricCoefficients] + map_smul' c P := by + funext q + rcases q with ⟨a, b⟩ + induction a using Sym2.ind + induction b using Sym2.ind + simp [symmetricCoefficients] + +theorem symmetric_space_dimension (s : ℕ) (hs : 2 ≤ s) : + Module.finrank ℝ (endpointSymmetricSpace s) = (Nat.choose s 2) ^ 2 := by + rw [(symmetricCoordinatesEquiv s).finrank_eq, Module.finrank_pi] + simp only [SymmetricCoordinate, Fintype.card_prod, Sym2.card, Fintype.card_fin] + have he : s - 2 + 1 + 1 = s := by omega + rw [he] + ring + +end Paper170 + +end +end + +section + +noncomputable section +open scoped BigOperators Classical +open MvPolynomial +namespace Paper170 + +lemma collisionFactors_prime (i : Fin 4) : Prime (collisionFactors i) := by + fin_cases i <;> exact difference_prime _ _ (by decide) + +lemma collisionFactors_coprime : + Pairwise (fun i j : Fin 4 => IsRelPrime (collisionFactors i) (collisionFactors j)) := by + intro i j hij + rw [(collisionFactors_prime i).irreducible.isRelPrime_iff_not_dvd, + (collisionFactors_prime i).dvd_prime_iff_associated (collisionFactors_prime j)] + exact collision_factors_nonassociate hij + +lemma collision_divides_of_diagonal_vanishing (s : ℕ) (P : endpointSymmetricSpace s) + (hP : diagonalSpecialization P.val = 0) : collisionFactor ∣ P.val := by + have h02 := (diagonal_vanishing_iff_divisible P.val).mp hP + rcases (symmetric_space_membership s P.val).mp P.property with ⟨_, hp1, hp2⟩ + have h03 : (X 0 - X 3 : Poly4) ∣ P.val := by + obtain ⟨Q, hQ⟩ := h02 + refine ⟨swapSecondPair Q, ?_⟩ + have h := congrArg swapSecondPair hQ + rw [hp2, swapSecondPair_mul] at h + simpa [swapSecondPair, Equiv.swap_apply_def, + Fin.ext_iff] using h + have h12 : (X 1 - X 2 : Poly4) ∣ P.val := by + obtain ⟨Q, hQ⟩ := h02 + refine ⟨swapFirstPair Q, ?_⟩ + have h := congrArg swapFirstPair hQ + rw [hp1, swapFirstPair_mul] at h + simpa [swapFirstPair, Equiv.swap_apply_def, + Fin.ext_iff] using h + have h13 : (X 1 - X 3 : Poly4) ∣ P.val := by + obtain ⟨Q, hQ⟩ := h03 + refine ⟨swapFirstPair Q, ?_⟩ + have h := congrArg swapFirstPair hQ + rw [hp1, swapFirstPair_mul] at h + simpa [swapFirstPair, Equiv.swap_apply_def, + Fin.ext_iff] using h + have hdvd (i : Fin 4) : collisionFactors i ∣ P.val := by + fin_cases i + · exact h02 + · exact h03 + · exact h12 + · exact h13 + have h := Finset.prod_dvd_of_isRelPrime + (fun i (_ : i ∈ (Finset.univ : Finset (Fin 4))) j _ hij => + collisionFactors_coprime hij) (fun i _ => hdvd i) + simpa [Fin.prod_univ_four, collisionFactors, collisionFactor, + Matrix.cons_val_two, Matrix.cons_val_three] using h + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Ports.lean b/lean/OAI/Combinatorics/CompleteCrossing/Ports.lean new file mode 100644 index 0000000000000000000000000000000000000000..fcc425377025713c0622a3cbcec7dbd1584c0ead --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Ports.lean @@ -0,0 +1,321 @@ +import OAI.Combinatorics.CompleteCrossing.DrawingMarks +import OAI.Combinatorics.Crossing.CurveDiskIsolation +import OAI.Combinatorics.Crossing.FiniteDiskCollar +import OAI.Combinatorics.Crossing.IntervalSegmentStrict +import OAI.Combinatorics.Crossing.OrderedPassages + +namespace OAI + +/-! Isolated drawing disks, retained arcs, and boundary ports. -/ + +section + +/-! The actual finite vertex/crossing marks supply the normalization disk family. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +abbrev DrawingMark (D : FiniteIntersectionDrawing graph) := ↥(drawingMarks D) + +theorem drawing_disk_isolation [Fintype Vertex] [Fintype Edge] (D : FiniteIntersectionDrawing graph) : + ∃ δ : Edge → ℝ, ∃ r : ℝ, (∀ e, 0 < δ e) ∧ 0 < r ∧ + (∀ x y : DrawingMark D, x ≠ y → + Disjoint (closedRoundDisk x.val r) (closedRoundDisk y.val r)) ∧ + (∀ e (x : DrawingMark D) t, D.edge e t ∈ closedRoundDisk x.val r → + ∃ u : unitInterval, D.edge e u=x.val ∧ t ∈ parameterNeighborhood u (δ e)) ∧ + (∀ e u v, D.edge e u ∈ drawingMarks D → D.edge e v ∈ drawingMarks D → u ≠ v → + Disjoint (closure (parameterNeighborhood u (δ e))) + (closure (parameterNeighborhood v (δ e)))) := by + let : Fintype (DrawingMark D) := (drawingMarks_finite D).fintype + let : DecidableEq (DrawingMark D) := Classical.decEq _ + obtain ⟨δ,r,hδ,hr,hd,hv,hs⟩ := finite_injective_curve_disk_isolation + (fun e => D.edge e) (fun e => (D.edge e).continuous) D.edge_injective + (fun x : DrawingMark D => x.val) Subtype.val_injective + refine ⟨δ,r,hδ,hr,hd,hv,?_⟩ + intro e u v hu hv huv + exact hs e u v ⟨⟨D.edge e u,hu⟩,rfl⟩ ⟨⟨D.edge e v,hv⟩,rfl⟩ huv + +end Paper170Geometry + +end +end + +section + +/-! Constructed finite marked-passage decomposition of the given actual drawing. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +/-- Geometric cut data for the original drawing. Existence is proved below; +this record asserts no crossing bound or drawing-normalization conclusion. -/ +structure DrawingPassages (D : FiniteIntersectionDrawing graph) where + radius : ℝ + radius_pos : 0 < radius + disks_disjoint : ∀ x y : DrawingMark D, x ≠ y → + Disjoint (closedRoundDisk x.val radius) (closedRoundDisk y.val radius) + count : Edge → ℕ + count_pos : ∀ e, 0 < count e + node : ∀ e, Fin (count e+1) → unitInterval + increasing : ∀ e, StrictMono (node e) + first : ∀ e, node e 0=0 + last : ∀ e, node e (Fin.last (count e))=1 + node_range : ∀ e, Set.range (node e)=(D.edge e) ⁻¹' drawingMarks D + passage : ∀ e i, DiskPassage (D.edge e) (D.edge e (node e i)) radius (node e i) + separated : ∀ e i j, i < j → (passage e i).leave < (passage e j).enter + visited_mark_on_edge : ∀ e (x : DrawingMark D) t, + D.edge e t ∈ closedRoundDisk x.val radius → ∃ u, D.edge e u=x.val + +theorem nonempty_drawingPassages [Fintype Vertex] [Fintype Edge] (D : FiniteIntersectionDrawing graph) : Nonempty (DrawingPassages D) := by + classical + obtain ⟨δ,r,hδ,hr,hdisks,hvisits,hparam⟩ := drawing_disk_isolation D + choose k hk τ hτ h0 h1 hR using (fun e => exists_sorted_drawing_parameters D e) + have hnode (e : Edge) (i : Fin (k e+1)) : D.edge e (τ e i) ∈ drawingMarks D := by + change τ e i ∈ (D.edge e) ⁻¹' drawingMarks D + rw [← hR e] + exact ⟨i,rfl⟩ + have hex (e : Edge) (i : Fin (k e+1)) : + Nonempty (DiskPassage (D.edge e) (D.edge e (τ e i)) r (τ e i)) := + nonempty_diskPassage (D.edge e) (D.edge e (τ e i)) r (τ e i) + (by simpa [squaredLength] using sq_pos_of_pos hr) + let P (e : Edge) (i : Fin (k e+1)) := Classical.choice (hex e i) + have hlocal (e : Edge) (i : Fin (k e+1)) (t : unitInterval) + (ht : D.edge e t ∈ closedRoundDisk (D.edge e (τ e i)) r) : + t ∈ parameterNeighborhood (τ e i) (δ e) := by + obtain ⟨u,hu,hh⟩ := hvisits e ⟨D.edge e (τ e i),hnode e i⟩ t ht + have he : u=τ e i := D.edge_injective e hu + simpa [he] using hh + have hsep (e : Edge) (i j : Fin (k e+1)) (hij : i < j) : + (P e i).leave < (P e j).enter := by + apply diskPassage_separated (P e i) (P e j) (hτ e hij) (hδ e) + · exact hparam e (τ e i) (τ e j) (hnode e i) (hnode e j) ((hτ e).injective.ne (ne_of_lt hij)) + · exact hlocal e i _ (P e i).leave_mem + · exact hlocal e j _ (P e j).enter_mem + exact ⟨{ + radius := r + radius_pos := hr + disks_disjoint := hdisks + count := k + count_pos := hk + node := τ + increasing := hτ + first := h0 + last := h1 + node_range := hR + passage := P + separated := hsep + visited_mark_on_edge := fun e x t ht => by + obtain ⟨u,hu,_⟩ := hvisits e x t ht + exact ⟨u,hu⟩ }⟩ + +end Paper170Geometry + +end +end + +section + +/-! Actual retained middle arcs: endpoint circles and avoidance of every disk and mark. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +abbrev ArcIndex (C : DrawingPassages D) := (e : Edge) × Fin (C.count e) + +theorem node_mark (C : DrawingPassages D) (e : Edge) (i : Fin (C.count e+1)) : + D.edge e (C.node e i) ∈ drawingMarks D := by + change C.node e i ∈ (D.edge e) ⁻¹' drawingMarks D + rw [← C.node_range e] + exact ⟨i,rfl⟩ + +def arcStartMark (C : DrawingPassages D) (i : C.ArcIndex) : DrawingMark D := + ⟨D.edge i.1 (C.node i.1 i.2.castSucc),C.node_mark i.1 i.2.castSucc⟩ + +def arcEndMark (C : DrawingPassages D) (i : C.ArcIndex) : DrawingMark D := + ⟨D.edge i.1 (C.node i.1 i.2.succ),C.node_mark i.1 i.2.succ⟩ + +def arcStart (C : DrawingPassages D) (i : C.ArcIndex) : Plane := + D.edge i.1 (C.passage i.1 i.2.castSucc).leave + +def arcEnd (C : DrawingPassages D) (i : C.ArcIndex) : Plane := + D.edge i.1 (C.passage i.1 i.2.succ).enter + +def arc (C : DrawingPassages D) (i : C.ArcIndex) : Path (C.arcStart i) (C.arcEnd i) := + retainedSubarc (D.edge i.1) (C.node i.1) C.radius (C.passage i.1) i.2 + +theorem arc_gap (C : DrawingPassages D) (i : C.ArcIndex) : + (C.passage i.1 i.2.castSucc).leave < (C.passage i.1 i.2.succ).enter := + C.separated i.1 i.2.castSucc i.2.succ (by change i.2.val < i.2.val+1; omega) + +theorem arc_injective (C : DrawingPassages D) (i : C.ArcIndex) : Function.Injective (C.arc i) := + pathSubarc_injective (D.edge i.1) (D.edge_injective i.1) _ _ (C.arc_gap i) + +theorem arc_endpoints_ne (C : DrawingPassages D) (i : C.ArcIndex) : C.arcStart i ≠ C.arcEnd i := by + intro he + exact (C.arc_gap i).ne (D.edge_injective i.1 he) + +theorem arc_range (C : DrawingPassages D) (i : C.ArcIndex) : + Set.range (C.arc i)=D.edge i.1 '' Set.Icc (C.passage i.1 i.2.castSucc).leave (C.passage i.1 i.2.succ).enter := + pathSubarc_range (D.edge i.1) _ _ (C.arc_gap i) + +theorem arc_avoids_marks (C : DrawingPassages D) (i : C.ArcIndex) (x : Plane) + (hx : x ∈ Set.range (C.arc i)) : x ∉ drawingMarks D := by + rw [C.arc_range] at hx + obtain ⟨t,ht,rfl⟩ := hx + intro hh + have hp : t ∈ Set.range (C.node i.1) := by rw [C.node_range]; exact hh + exact retained_interval_no_mark (D.edge i.1) (C.node i.1) (C.increasing i.1) + (C.first i.1) (C.last i.1) C.radius (C.passage i.1) i.2 t ht hp + +theorem retained_parameter_outside (C : DrawingPassages D) (i : C.ArcIndex) (t : unitInterval) + (ht : t ∈ Set.Ioo (C.passage i.1 i.2.castSucc).leave (C.passage i.1 i.2.succ).enter) : + D.edge i.1 t ∈ outsideDisks (fun x : DrawingMark D => x.val) C.radius := by + intro x + apply lt_of_not_ge + intro hh + obtain ⟨u,hu⟩ := C.visited_mark_on_edge i.1 x t hh + have hmu : u ∈ Set.range (C.node i.1) := by + rw [C.node_range] + change D.edge i.1 u ∈ drawingMarks D + rw [hu] + exact x.property + obtain ⟨j,hj⟩ := hmu + have hc : D.edge i.1 (C.node i.1 j)=x.val := (congrArg (D.edge i.1) hj).trans hu + have hv := (C.passage i.1 j).all_visits t (by rw [hc]; exact hh) + by_cases hji : j ≤ i.2.castSucc + · have hm := (ordered_passage_leave_strictMono (D.edge i.1) (C.node i.1) C.radius + (C.passage i.1) (C.separated i.1)).monotone hji + exact ht.1.not_ge (hv.2.trans hm) + · have hij : i.2.succ ≤ j := by + change i.2.val+1 ≤ j.val + have hn : ¬ j.val ≤ i.2.val := hji + omega + have hm := (ordered_passage_enter_strictMono (D.edge i.1) (C.node i.1) C.radius + (C.passage i.1) (C.separated i.1)).monotone hij + exact ht.2.not_ge (hm.trans hv.1) + +theorem arc_interior_outside (C : DrawingPassages D) (i : C.ArcIndex) (t : unitInterval) + (ht : t ∈ Set.Ioo (0 : unitInterval) 1) : + C.arc i t ∈ outsideDisks (fun x : DrawingMark D => x.val) C.radius := by + exact C.retained_parameter_outside i _ (intervalSegment_strict_between _ _ t (C.arc_gap i) ht) + +theorem arc_start_on_circle (C : DrawingPassages D) (i : C.ArcIndex) : + squaredLength (C.arcStart i-(C.arcStartMark i).val)=C.radius^2 := by + exact (C.passage i.1 i.2.castSucc).leave_boundary + ((C.arc_gap i).trans_le (show (C.passage i.1 i.2.succ).enter ≤ 1 from (C.passage i.1 i.2.succ).enter.property.2)) + +theorem arc_end_on_circle (C : DrawingPassages D) (i : C.ArcIndex) : + squaredLength (C.arcEnd i-(C.arcEndMark i).val)=C.radius^2 := by + exact (C.passage i.1 i.2.succ).enter_boundary + ((show 0 ≤ (C.passage i.1 i.2.castSucc).leave from (C.passage i.1 i.2.castSucc).leave.property.1).trans_lt (C.arc_gap i)) + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! The retained actual compact arcs are pairwise disjoint, including on the same edge. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +theorem arcs_pairwise_disjoint (C : DrawingPassages D) (p q : C.ArcIndex) (hpq : p ≠ q) : + Disjoint (Set.range (C.arc p)) (Set.range (C.arc q)) := by + apply Set.disjoint_left.mpr + intro x hx hy + have hxm := C.arc_avoids_marks p x hx + rcases p with ⟨e,i⟩ + rcases q with ⟨f,j⟩ + rw [C.arc_range] at hx hy + obtain ⟨s,hs,hsx⟩ := hx + obtain ⟨t,ht,htx⟩ := hy + have hef : e=f := unmarked_intersection_same_edge D e f s t (hsx.trans htx.symm) + (hsx.symm ▸ hxm) + subst f + have hst : s=t := D.edge_injective e (hsx.trans htx.symm) + rw [← hst] at ht + have hij : i ≠ j := by + intro he + subst j + exact hpq rfl + rcases lt_or_gt_of_ne hij with hij | hji + · exact Set.disjoint_left.mp + (retained_interval_pair_disjoint (D.edge e) (C.node e) C.radius (C.passage e) (C.separated e) i j hij) hs ht + · exact Set.disjoint_left.mp + (retained_interval_pair_disjoint (D.edge e) (C.node e) C.radius (C.passage e) (C.separated e) j i hji) ht hs + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! The actual distinct disk-boundary endpoints of all retained arcs. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : FiniteIntersectionDrawing graph} + +abbrev Port (C : DrawingPassages D) := C.ArcIndex × Bool + +def portPoint (C : DrawingPassages D) (p : C.Port) : Plane := + if p.2 then C.arcEnd p.1 else C.arcStart p.1 + +def portMark (C : DrawingPassages D) (p : C.Port) : DrawingMark D := + if p.2 then C.arcEndMark p.1 else C.arcStartMark p.1 + +theorem portPoint_mem_arc (C : DrawingPassages D) (p : C.Port) : + C.portPoint p ∈ Set.range (C.arc p.1) := by + rcases p with ⟨i,flag⟩ + cases flag + · exact ⟨0,(C.arc i).source⟩ + · exact ⟨1,(C.arc i).target⟩ + +theorem portPoint_injective (C : DrawingPassages D) : Function.Injective C.portPoint := by + rintro ⟨i,s⟩ ⟨j,t⟩ he + have hij : i=j := by + by_contra h + exact Set.disjoint_left.mp (C.arcs_pairwise_disjoint i j h) + (C.portPoint_mem_arc (i,s)) (he.symm ▸ C.portPoint_mem_arc (j,t)) + subst j + have hst : s=t := by + cases s <;> cases t + · rfl + · exact False.elim (C.arc_endpoints_ne i he) + · exact False.elim (C.arc_endpoints_ne i he.symm) + · rfl + subst t + rfl + +theorem portPoint_on_circle (C : DrawingPassages D) (p : C.Port) : + squaredLength (C.portPoint p-(C.portMark p).val)=C.radius^2 := by + rcases p with ⟨i,flag⟩ + cases flag + · exact C.arc_start_on_circle i + · exact C.arc_end_on_circle i + +abbrev PortsAt (C : DrawingPassages D) (x : DrawingMark D) := {p : C.Port // C.portMark p=x} + +theorem portsAt_on_circle (C : DrawingPassages D) (x : DrawingMark D) (p : C.PortsAt x) : + squaredLength (C.portPoint p.val-x.val)=C.radius^2 := by + simpa only [p.property] using C.portPoint_on_circle p.val + +end Paper170Geometry.DrawingPassages + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/RadialTracks.lean b/lean/OAI/Combinatorics/CompleteCrossing/RadialTracks.lean new file mode 100644 index 0000000000000000000000000000000000000000..d58e58c886af85216f8c509c86b4f53df2724c9f --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/RadialTracks.lean @@ -0,0 +1,392 @@ +import OAI.Combinatorics.CompleteCrossing.Tracks +import OAI.Combinatorics.Crossing.MovingDiskClearance +import OAI.Combinatorics.Crossing.NormalOffsetExterior + +namespace OAI + +/-! Radial track displacements and connector clearance from other disks and tracks. -/ + +section + +/-! Endpoint radial directions have the correct sign in the fixed left-to-right edge orientation. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry + +theorem dot2_scaled_self (v : Plane) (a b : ℝ) : dot2 (a • v) (b • v)=a*b*squaredLength v := by + dsimp [dot2,squaredLength] + ring + +namespace VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +theorem start_radial_dot_pos (e : Edge) : + 0 < dot2 (V.startPort e-D.vertex ((graph.src e))) (trackDirection (V.vertices e) 0) := by + have hp := V.pieces_pos e + have hα := (radialPort_parameter_half ((V.chain e).vertices 0) ((V.chain e).vertices 1) + V.radius V.radius_pos (V.short e).1).1 + have hβ := (V.chain e).truncatedScale_pos V.radius V.radius_pos (V.short e).1 (V.short e).2 0 + have he : V.startPort e-D.vertex ((graph.src e))= + (V.chain e).startFraction V.radius • trackDirection (V.chain e).vertices 0 := by + have hh := radialPort_sub ((V.chain e).vertices 0) ((V.chain e).vertices 1) V.radius + change (V.chain e).startPort V.radius-(V.chain e).vertices 0= + (V.chain e).startFraction V.radius • trackDirection (V.chain e).vertices 0 at hh + simpa only [startPort,(V.chain e).first] using hh + rw [he] + change 0 < dot2 _ (trackDirection ((V.chain e).truncatedVertices V.radius) 0) + rw [(V.chain e).truncated_direction V.radius 0 hp,dot2_scaled_self] + exact mul_pos (mul_pos hα hβ) + (squaredLength_pos _ ((V.chain e).minimum_piece_ne_zero (V.minimal e) 0 hp)) + +theorem end_radial_dot_neg (e : Edge) : + dot2 (V.endPort e-D.vertex ((graph.dst e))) + (trackDirection (V.vertices e) (V.pieces e-1)) < 0 := by + have hp := V.pieces_pos e + have hp' : 0 < (V.chain e).pieces := hp + have hi : V.pieces e-1 < V.pieces e := by omega + have hα := (radialPort_parameter_half ((V.chain e).vertices ((V.chain e).pieces-1)) + ((V.chain e).vertices (V.chain e).pieces) V.radius V.radius_pos (V.short e).2).1 + have hβ := (V.chain e).truncatedScale_pos V.radius V.radius_pos (V.short e).1 (V.short e).2 (V.pieces e-1) + have he : V.endPort e-D.vertex ((graph.dst e))= + (-(V.chain e).endFraction V.radius) • trackDirection (V.chain e).vertices (V.pieces e-1) := by + have hh : (V.chain e).endPort V.radius-(V.chain e).vertices (V.chain e).pieces= + (-(V.chain e).endFraction V.radius) • trackDirection (V.chain e).vertices (V.pieces e-1) := by + rw [(V.chain e).endPort_eq_fraction] + simp only [trackDirection,pieces,show (V.chain e).pieces-1+1=(V.chain e).pieces by omega,neg_smul] + abel + simpa only [endPort,(V.chain e).last] using hh + rw [he] + change dot2 _ (trackDirection ((V.chain e).truncatedVertices V.radius) (V.pieces e-1)) < 0 + rw [(V.chain e).truncated_direction V.radius _ hi,dot2_scaled_self] + exact mul_neg_of_neg_of_pos (mul_neg_of_neg_of_pos (neg_neg_of_pos hα) hβ) + (squaredLength_pos _ ((V.chain e).minimum_piece_ne_zero (V.minimal e) _ hi)) + +theorem bend_ne_zero (e : Edge) (i : ℕ) (hi0 : 0 < i) (hin : i < V.pieces e) : + det2 (trackDirection (V.vertices e) (i-1)) (trackDirection (V.vertices e) i) ≠ 0 := by + exact (V.chain e).truncated_bend_ne_zero (V.minimal e) V.radius V.radius_pos + (V.short e).1 (V.short e).2 i hi0 hin + +theorem exists_forward_radius (e : Edge) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ i : Fin (V.pieces e), + ∃ ℓ : ℝ, 0<ℓ ∧ shiftedTrack (V.vertices e) (V.pieces e) ε (i.val+1)- + shiftedTrack (V.vertices e) (V.pieces e) ε i.val=ℓ • trackDirection (V.vertices e) i.val := + exists_forward_shiftedTrack_radius (V.vertices e) (V.pieces e) (V.direction_ne_zero e) (V.bend_ne_zero e) + +end VertexTruncation +end Paper170Geometry + +end +end + +section + +/-! The actual first and last shifted segments remain outside their incident vertex disks. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +theorem shifted_first_piece_exterior (e : Edge) (ε ℓ : ℝ) + (hε : ε ≠ 0) (hℓ : 0<ℓ) + (hdir : shiftedTrack (V.vertices e) (V.pieces e) ε 1- + shiftedTrack (V.vertices e) (V.pieces e) ε 0=ℓ • trackDirection (V.vertices e) 0) : + segment ℝ (shiftedTrack (V.vertices e) (V.pieces e) ε 0) + (shiftedTrack (V.vertices e) (V.pieces e) ε 1) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex ((graph.src e)))} := by + have hstart : shiftedTrack (V.vertices e) (V.pieces e) ε 0= + V.startPort e+ε • normalShift (trackDirection (V.vertices e) 0) := by + simp [shiftedTrack,trackOffset,V.vertices_first] + have hc : squaredLength (V.startPort e-D.vertex ((graph.src e)))=V.radius^2 := by + simpa only [V.spokePort_left] using V.spokePort_circle ((graph.src e)) (V.leftIncident e) + have hp : det2 (trackDirection (V.vertices e) 0) (V.startPort e-D.vertex ((graph.src e)))=0 := by + simpa [spokeDirection,spokeIndex,leftIncident,spokePort,drawingSpokePort,startPort] using + V.spokeDirection_parallel ((graph.src e)) (V.leftIncident e) + rw [hstart] at hdir ⊢ + exact normal_offset_segment_exterior _ _ _ _ _ ε ℓ (V.direction_ne_zero e 0 (V.pieces_pos e)) + hc hp (mul_nonneg hℓ.le (V.start_radial_dot_pos e).le) hε hdir + +theorem shifted_last_piece_exterior (e : Edge) (ε ℓ : ℝ) + (hε : ε ≠ 0) (hℓ : 0<ℓ) + (hdir : shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e)- + shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e-1)= + ℓ • trackDirection (V.vertices e) (V.pieces e-1)) : + segment ℝ (shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e-1)) + (shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e)) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex ((graph.dst e)))} := by + have hn : V.pieces e ≠ 0 := ne_of_gt (V.pieces_pos e) + have hi : V.pieces e-1 < V.pieces e := by have hh := V.pieces_pos e; omega + have hend : shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e)= + V.endPort e+ε • normalShift (trackDirection (V.vertices e) (V.pieces e-1)) := by + simp [shiftedTrack,trackOffset,hn,V.vertices_last] + have hc : squaredLength (V.endPort e-D.vertex ((graph.dst e)))=V.radius^2 := by + simpa only [V.spokePort_right] using V.spokePort_circle ((graph.dst e)) (V.rightIncident e) + have hp : det2 (trackDirection (V.vertices e) (V.pieces e-1)) (V.endPort e-D.vertex ((graph.dst e)))=0 := by + simpa [spokeDirection,spokeIndex,rightIncident,spokePort,drawingSpokePort,endPort,(graph.loopless e).symm] using + V.spokeDirection_parallel ((graph.dst e)) (V.rightIncident e) + have hrev : shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e-1)- + (V.endPort e+ε • normalShift (trackDirection (V.vertices e) (V.pieces e-1)))= + (-ℓ) • trackDirection (V.vertices e) (V.pieces e-1) := by + rw [neg_smul,← hdir,hend] + abel + rw [segment_symm,hend] + exact normal_offset_segment_exterior _ _ _ _ _ ε (-ℓ) (V.direction_ne_zero e _ hi) + hc hp (mul_nonneg_of_nonpos_of_nonpos (by linarith) (V.end_radial_dot_neg e).le) hε hrev + +end Paper170Geometry.VertexTruncation + +end +end + +section + +/-! Actual connectors stay on the displaced supporting line and avoid their own original spoke piece. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry + +theorem det2_segmentPoint_sub (d p a b : Plane) (t : ℝ) : + det2 d (segmentPoint a b t-p)=(1-t)*det2 d (a-p)+t*det2 d (b-p) := by + dsimp [det2,segmentPoint] + ring + +theorem segment_line_level_zero (a b p : Plane) (hp : p=a ∨ p=b) (t : ℝ) : + det2 (b-a) (segmentPoint a b t-p)=0 := by + rcases hp with rfl | rfl <;> dsimp [det2,segmentPoint] <;> ring + +namespace VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +theorem spokePort_is_piece_endpoint (j : Vertex) (e : IncidentEdges graph j) : + V.spokePort j e=V.vertices e.val (V.spokeIndex j e) ∨ + V.spokePort j e=V.vertices e.val (V.spokeIndex j e+1) := by + unfold spokePort drawingSpokePort spokeIndex + split_ifs + · exact Or.inl (V.vertices_first e.val).symm + · right + have hp := V.pieces_pos e.val + rw [show V.pieces e.val-1+1=V.pieces e.val by omega] + exact (V.vertices_last e.val).symm + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem continuous_tangentPort (j : Vertex) (e : IncidentEdges graph j) : + Continuous (C.tangentPort j e) := by + change Continuous (fun ε : ℝ => V.spokePort j e+ε • normalShift (V.spokeDirection j e)) + fun_prop + +theorem tangentPort_zero (j : Vertex) (e : IncidentEdges graph j) : + C.tangentPort j e 0=V.spokePort j e := by simp [tangentPort] + +theorem tangentPort_level (j : Vertex) (e : IncidentEdges graph j) (ε : ℝ) : + det2 (V.spokeDirection j e) (C.tangentPort j e ε-V.spokePort j e)=ε := by + simp only [tangentPort,add_sub_cancel_left,det2_smul_right, + det2_normalShift _ (V.spokeDirection_ne_zero j e),mul_one] + +theorem connector_level (j : Vertex) (e : IncidentEdges graph j) (ε t : ℝ) : + det2 (V.spokeDirection j e) + (segmentPoint (C.shiftedPort j e ε) (C.tangentPort j e ε) t-V.spokePort j e)=ε := by + rw [det2_segmentPoint_sub,C.shiftedPort_level,C.tangentPort_level] + ring + +theorem connector_avoids_incident_piece (j : Vertex) (e : IncidentEdges graph j) + (ε : ℝ) (hε : ε ≠ 0) : + ¬ ClosedSegmentsMeet (V.vertices e.val (V.spokeIndex j e)) + (V.vertices e.val (V.spokeIndex j e+1)) (C.shiftedPort j e ε) (C.tangentPort j e ε) := by + rintro ⟨s,hs,t,ht,he⟩ + have hzero := segment_line_level_zero (V.vertices e.val (V.spokeIndex j e)) + (V.vertices e.val (V.spokeIndex j e+1)) (V.spokePort j e) (V.spokePort_is_piece_endpoint j e) s + change det2 (V.spokeDirection j e) + (segmentPoint (V.vertices e.val (V.spokeIndex j e)) (V.vertices e.val (V.spokeIndex j e+1)) s-V.spokePort j e)=0 at hzero + rw [he,C.connector_level] at hzero + exact hε hzero + +end TruncatedSpokeCoordinates +end Paper170Geometry + +end +end + +section + +/-! One genuine radius keeps every shifted exterior edge track outside every vertex disk. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +theorem exists_nonincident_shift_radius [Fintype Vertex] [Fintype Edge] : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ j e (i : Fin (V.pieces e)), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=V.pieces e)) → + segment ℝ (shiftedTrack (V.vertices e) (V.pieces e) ε i.val) + (shiftedTrack (V.vertices e) (V.pieces e) ε (i.val+1)) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex j)} := by + classical + let Bad := Σ j : Vertex, Σ e : Edge, + {i : Fin (V.pieces e) // ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=V.pieces e))} + have hdis (b : Bad) : Disjoint (closedRoundDisk (D.vertex b.1) V.radius) + (segment ℝ (V.vertices b.2.1 b.2.2.val.val) (V.vertices b.2.1 (b.2.2.val.val+1))) := by + exact (V.piece_clearance b.1 b.2.1 b.2.2.val b.2.2.property).mono_right + ((V.chain b.2.1).truncated_piece_subset V.radius V.radius_pos + (V.weak_short b.2.1).1 (V.weak_short b.2.1).2 _ b.2.2.val.isLt) + have hex (b : Bad) := exists_shifted_segment_disk_radius + (V.vertices b.2.1 b.2.2.val.val) (V.vertices b.2.1 (b.2.2.val.val+1)) + (trackOffset (V.vertices b.2.1) (V.pieces b.2.1) b.2.2.val.val) + (trackOffset (V.vertices b.2.1) (V.pieces b.2.1) (b.2.2.val.val+1)) + (D.vertex b.1) V.radius (hdis b) + choose radius hpos hprop using hex + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun b _ => hpos b) + refine ⟨δ,hδ,?_⟩ + intro ε hε j e i hi + exact hprop ⟨j,e,⟨i,hi⟩⟩ ε (hε.trans (hbound ⟨j,e,⟨i,hi⟩⟩ (Finset.mem_univ _))) + +theorem exists_all_vertex_disk_radius [Fintype Vertex] [Fintype Edge] : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j e (i : Fin (V.pieces e)), + segment ℝ (shiftedTrack (V.vertices e) (V.pieces e) ε i.val) + (shiftedTrack (V.vertices e) (V.pieces e) ε (i.val+1)) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex j)} := by + classical + obtain ⟨δ₀,hδ₀,hclear⟩ := V.exists_nonincident_shift_radius + choose radius hpos hforward using V.exists_forward_radius + obtain ⟨δ₁,hδ₁,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun e _ => hpos e) + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro ε hε hsmall j e i + obtain ⟨ℓ,hℓ,hdir⟩ := hforward e ε + (hsmall.trans_le (min_le_right _ _ ) |>.trans (hbound e (Finset.mem_univ _))) i + by_cases hleft : j=(graph.src e) ∧ i.val=0 + · rcases hleft with ⟨rfl,hi⟩ + simpa only [hi,zero_add] using V.shifted_first_piece_exterior e ε ℓ hε hℓ (by simpa only [hi,zero_add] using hdir) + · by_cases hright : j=(graph.dst e) ∧ i.val+1=V.pieces e + · rcases hright with ⟨rfl,hi⟩ + have hi' : i.val=V.pieces e-1 := by omega + have hn : V.pieces e-1+1=V.pieces e := by omega + simpa only [hi',hn] using V.shifted_last_piece_exterior e ε ℓ hε hℓ (by simpa only [hi',hn] using hdir) + · exact hclear ε (hsmall.trans_le (min_le_left _ _)) j e i (not_or.mpr ⟨hleft,hright⟩) + +end Paper170Geometry.VertexTruncation + +end +end + +section + +/-! Every shrinking circle connector stays outside all other vertex disks at one common radius. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +open scoped Topology +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem exists_connector_other_disks_radius [Fintype Vertex] [Fintype Edge] : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ j k, j ≠ k → ∀ f : IncidentEdges graph j, + segment ℝ (C.shiftedPort j f ε) (C.tangentPort j f ε) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex k)} := by + classical + let Pair := Σ j : Vertex, Σ k : {k : Vertex // j ≠ k}, IncidentEdges graph j + have hstart (b : Pair) : segment ℝ (C.shiftedPort b.1 b.2.2 0) (C.tangentPort b.1 b.2.2 0) ⊆ + {x | V.radius^2 < squaredLength (x-D.vertex b.2.1.val)} := by + rw [C.shiftedPort_zero,C.tangentPort_zero,segment_same] + intro x hx + have he : x=V.spokePort b.1 b.2.2 := hx + subst x + change V.radius^2 < squaredLength (V.spokePort b.1 b.2.2-D.vertex b.2.1.val) + by_contra hh + have hj : V.spokePort b.1 b.2.2 ∈ closedRoundDisk (D.vertex b.1) V.radius := by + change squaredLength (V.spokePort b.1 b.2.2-D.vertex b.1) ≤ V.radius^2 + rw [V.spokePort_circle] + have hk : V.spokePort b.1 b.2.2 ∈ closedRoundDisk (D.vertex b.2.1.val) V.radius := not_lt.mp hh + exact Set.disjoint_left.mp (V.disks_disjoint b.1 b.2.1.val b.2.1.property) hj hk + have hevent (b : Pair) := eventually_moving_segment_outside_disk + (C.shiftedPort b.1 b.2.2) (C.tangentPort b.1 b.2.2) + (C.continuous_shiftedPort b.1 b.2.2) (C.continuous_tangentPort b.1 b.2.2) + (D.vertex b.2.1.val) V.radius (hstart b) + have hex (b : Pair) := Metric.eventually_nhds_iff.mp (hevent b) + choose radius hpos hprop using hex + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun b _ => hpos b) + refine ⟨δ,hδ,?_⟩ + intro ε hε j k hjk f + exact hprop ⟨j,⟨k,hjk⟩,f⟩ (by simpa [Real.dist_eq] using hε.trans (hbound ⟨j,⟨k,hjk⟩,f⟩ (Finset.mem_univ _))) + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! One two-sided physical radius excludes every connector/track meeting, including shared edges. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +open scoped Topology +variable {D : Paper170.AdmissibleDrawing graph} {V : VertexTruncation D.toContinuousDrawing} + (C : TruncatedSpokeCoordinates V) + +theorem exists_nonincident_connector_radius [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ j (f : IncidentEdges graph j) e (i : Fin (V.pieces e)), + ¬ (e=f.val ∧ i.val=V.spokeIndex j f) → + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (C.shiftedPort j f ε) (C.tangentPort j f ε) := by + classical + let Bad := Σ j : Vertex, Σ f : IncidentEdges graph j, Σ e : Edge, + {i : Fin (V.pieces e) // ¬ (e=f.val ∧ i.val=V.spokeIndex j f)} + have hnot (b : Bad) : ¬ ClosedSegmentsMeet + (V.vertices b.2.2.1 b.2.2.2.val.val) (V.vertices b.2.2.1 (b.2.2.2.val.val+1)) + (V.spokePort b.1 b.2.1) (V.spokePort b.1 b.2.1) := by + rintro ⟨s,hs,t,ht,he⟩ + have he0 : segmentPoint (V.spokePort b.1 b.2.1) (V.spokePort b.1 b.2.1) t=V.spokePort b.1 b.2.1 := by + unfold segmentPoint + rw [← add_smul] + simp + rw [he0] at he + have hx : V.spokePort b.1 b.2.1 ∈ + segment ℝ (V.vertices b.2.2.1 b.2.2.2.val.val) (V.vertices b.2.2.1 (b.2.2.2.val.val+1)) := by + rw [← Path.range_segment] + refine ⟨⟨s,hs⟩,?_⟩ + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using he + exact b.2.2.2.property (V.spokePort_piece_unique hnorm b.1 b.2.1 b.2.2.1 b.2.2.2.val hx) + have hevent (b : Bad) := eventually_moving_disjoint_segments + (V.vertices b.2.2.1 b.2.2.2.val.val) (V.vertices b.2.2.1 (b.2.2.2.val.val+1)) + (V.spokePort b.1 b.2.1) (V.spokePort b.1 b.2.1) (C.shiftedPort b.1 b.2.1) (C.tangentPort b.1 b.2.1) + (C.continuous_shiftedPort b.1 b.2.1).continuousAt (C.continuous_tangentPort b.1 b.2.1).continuousAt + (C.shiftedPort_zero b.1 b.2.1) (C.tangentPort_zero b.1 b.2.1) (hnot b) + have hex (b : Bad) := Metric.eventually_nhds_iff.mp (hevent b) + choose radius hpos hprop using hex + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun b _ => hpos b) + refine ⟨δ,hδ,?_⟩ + intro ε hε j f e i hi + exact hprop ⟨j,f,e,⟨i,hi⟩⟩ (by simpa [Real.dist_eq] using hε.trans (hbound ⟨j,f,e,⟨i,hi⟩⟩ (Finset.mem_univ _))) + +theorem exists_all_connector_track_radius [Fintype Vertex] [Fintype Edge] (hnorm : NoAdjacentCrossings D) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j (f : IncidentEdges graph j) e (i : Fin (V.pieces e)), + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (C.shiftedPort j f ε) (C.tangentPort j f ε) := by + obtain ⟨δ,hδ,hh⟩ := C.exists_nonincident_connector_radius hnorm + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall j f e i + by_cases hi : e=f.val ∧ i.val=V.spokeIndex j f + · rcases hi with ⟨rfl,hi⟩ + simpa only [hi] using C.connector_avoids_incident_piece j f ε hε + · exact hh ε hsmall j f e i hi + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Reconnection.lean b/lean/OAI/Combinatorics/CompleteCrossing/Reconnection.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6bd84f080e68d6633abdbc353539a72c8a2a22c --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Reconnection.lean @@ -0,0 +1,216 @@ +import OAI.Combinatorics.CompleteCrossing.Polygonalization +import OAI.Combinatorics.Crossing.CrossingReconnection + +namespace OAI + +/-! Crossing reconnection chords and avoidance of vertices and retained arcs. -/ + +section + +/-! The two actual disjoint chords used in an adjacent-crossing surgery disk. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : Paper170.AdmissibleDrawing graph} + +def reconnectionStart (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) (i : Bool) : Plane := + if i then C.portPoint (C.incomingPort p) else C.portPoint (C.incomingPort q) + +def reconnectionEnd (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) (i : Bool) : Plane := + if i then C.portPoint (C.outgoingPort q) else C.portPoint (C.outgoingPort p) + +theorem reconnection_endpoints_ne (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) (i : Bool) : + C.reconnectionStart p q i ≠ C.reconnectionEnd p q i := by + cases i + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort q p) + · exact C.portPoint_injective.ne (C.incomingPort_ne_outgoingPort p q) + +theorem crossingChord_meeting_segmentsCrossProperly (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hpq : p ≠ q) (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) + (hxq : x ∈ Set.range (C.crossingChord q)) : + SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨s,hs⟩ := hxp + obtain ⟨t,ht⟩ := hxq + have he : segmentPoint (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) s.val= + segmentPoint (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) t.val := by + simpa only [crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs.trans ht.symm + obtain ⟨hd,hsi,hti⟩ := C.crossing_chords_transverse_at_mark p q hpq hm s.val s.property t.val t.property he + exact ⟨hd,s.val,hsi,t.val,hti,he⟩ + +theorem reconnection_chords_disjoint (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) : + ∀ i j : Bool, i ≠ j → Disjoint + (segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i)) + (segment ℝ (C.reconnectionStart p q j) (C.reconnectionEnd p q j)) := by + have hh := crossing_reconnections_disjoint _ _ _ _ hcross + intro i j hij + cases i <;> cases j + · exact False.elim (hij rfl) + · exact hh + · exact hh.symm + · exact False.elim (hij rfl) + +theorem reconnection_endpoints_on_circle (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hm : C.innerMark p=C.innerMark q) (i : Bool) : + squaredLength (C.reconnectionStart p q i-(C.innerMark p).val)=C.radius^2 ∧ + squaredLength (C.reconnectionEnd p q i-(C.innerMark p).val)=C.radius^2 := by + cases i + · change squaredLength (C.portPoint (C.incomingPort q)-(C.innerMark p).val)=C.radius^2 ∧ + squaredLength (C.portPoint (C.outgoingPort p)-(C.innerMark p).val)=C.radius^2 + exact ⟨by simpa only [hm] using C.incomingPoint_on_circle q,C.outgoingPoint_on_circle p⟩ + · change squaredLength (C.portPoint (C.incomingPort p)-(C.innerMark p).val)=C.radius^2 ∧ + squaredLength (C.portPoint (C.outgoingPort q)-(C.innerMark p).val)=C.radius^2 + exact ⟨C.incomingPoint_on_circle p,by simpa only [hm] using C.outgoingPoint_on_circle q⟩ + +theorem reconnection_open_in_disk (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hm : C.innerMark p=C.innerMark q) (i : Bool) : + openSegmentTrace (C.reconnectionStart p q i) (C.reconnectionEnd p q i) ⊆ C.crossingDisk p := by + rintro x ⟨t,ht,rfl⟩ + exact round_chord_in_open_disk _ _ _ _ (C.reconnection_endpoints_on_circle p q hm i).1 + (C.reconnection_endpoints_on_circle p q hm i).2 (C.reconnection_endpoints_ne p q i) t ht + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! The new closed chords stay in their crossing disk and avoid all placed vertices. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.DrawingPassages +variable {D : Paper170.AdmissibleDrawing graph} + +theorem reconnection_segment_in_disk (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hm : C.innerMark p=C.innerMark q) (i : Bool) : + segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i) ⊆ + closedRoundDisk (C.innerMark p).val C.radius := by + intro x hx + rw [← Path.range_segment] at hx + obtain ⟨t,ht⟩ := hx + rw [← ht] + change squaredLength ((Path.segment _ _) t-(C.innerMark p).val) ≤ C.radius^2 + simp only [Path.segment_apply,AffineMap.lineMap_apply_module] + exact round_chord_in_disk _ _ _ _ (C.reconnection_endpoints_on_circle p q hm i).1 + (C.reconnection_endpoints_on_circle p q hm i).2 t.val t.property + +theorem reconnection_segment_avoids_vertices (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) + (hm : C.innerMark p=C.innerMark q) (v : Vertex → Plane) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) (i : Bool) (j : Vertex) : + v j ∉ segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i) := by + intro hx + have hn : C.innerMark p ≠ C.vertexMark j := by + intro he + exact crossing_not_vertex D.toFiniteIntersectionDrawing (C.innerMark p).val (C.innerMark_is_crossing p) j (congrArg Subtype.val he) + exact Set.disjoint_left.mp (C.disks_disjoint _ _ hn) + (C.reconnection_segment_in_disk p q hm i hx) (hv j).le + +end Paper170Geometry.DrawingPassages + +end +end + +section + +/-! Neither reconnection segment contains the actual point being removed. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +theorem segment_avoids_of_affine_positive (f : Plane → ℝ) (a b x : Plane) + (hf : ∀ t, f (segmentPoint a b t)=(1-t)*f a+t*f b) + (ha : 0 < f a) (hb : 0 < f b) (hx : f x=0) : x ∉ segment ℝ a b := by + intro h + rw [← Path.range_segment] at h + obtain ⟨t,ht⟩ := h + have ht' : segmentPoint a b t.val=x := by + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + have hp := convex_combination_pos (f a) (f b) t.val ha hb t.property + rw [← hf t.val,ht',hx] at hp + exact lt_irrefl 0 hp + +theorem crossing_reconnections_avoid_point (a b c d x : Plane) + (hd : det2 (b-a) (d-c) ≠ 0) (s t : ℝ) + (hs : s ∈ Set.Ioo (0 : ℝ) 1) (ht : t ∈ Set.Ioo (0 : ℝ) 1) + (hx : x=segmentPoint a b s) (hy : x=segmentPoint c d t) : + x ∉ segment ℝ c b ∧ x ∉ segment ℝ a d := by + let F := crossingCoordinates x (b-a) (d-c) + have hFa : F a=(-s,0) := by + simpa only [segmentPoint_zero,zero_sub] using crossingCoordinates_first_segment a b c d x s 0 hd hx + have hFb : F b=(1-s,0) := by + simpa only [segmentPoint_one] using crossingCoordinates_first_segment a b c d x s 1 hd hx + have hFc : F c=(0,-t) := by + simpa only [segmentPoint_zero,zero_sub] using crossingCoordinates_second_segment a b c d x t 0 hd hy + have hFd : F d=(0,1-t) := by + simpa only [segmentPoint_one] using crossingCoordinates_second_segment a b c d x t 1 hd hy + have hF (u v : Plane) (r : ℝ) : F (segmentPoint u v r)=segmentPoint (F u) (F v) r := + crossingCoordinates_affine x (b-a) (d-c) u v r + have hzero : F x=(0,0) := crossingCoordinates_origin x (b-a) (d-c) + constructor + · apply segment_avoids_of_affine_positive (fun z => (F z).1-(F z).2) c b x + · intro r + rw [hF] + dsimp [segmentPoint] + ring + · rw [hFc] + dsimp + linarith [ht.1] + · rw [hFb] + dsimp + linarith [hs.2] + · rw [hzero] + norm_num + · apply segment_avoids_of_affine_positive (fun z => (F z).2-(F z).1) a d x + · intro r + rw [hF] + dsimp [segmentPoint] + ring + · rw [hFa] + dsimp + linarith [hs.1] + · rw [hFd] + dsimp + linarith [ht.2] + · rw [hzero] + norm_num + +theorem DrawingPassages.reconnection_avoids_chord_meeting {D : Paper170.AdmissibleDrawing graph} + (C : DrawingPassages D.toFiniteIntersectionDrawing) (p q : C.InnerIndex) (hpq : p ≠ q) (x : Plane) + (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∈ C.crossingDisk p ∧ ∀ i : Bool, + x ∉ segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i) := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + obtain ⟨s,hs⟩ := hxp + obtain ⟨t,ht⟩ := hxq + have hs' : segmentPoint (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) s.val=x := by + simpa only [DrawingPassages.crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using hs + have ht' : segmentPoint (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q)) t.val=x := by + simpa only [DrawingPassages.crossingChord,Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + obtain ⟨hd,hsi,hti⟩ := C.crossing_chords_transverse_at_mark p q hpq hm s.val s.property t.val t.property + (hs'.trans ht'.symm) + constructor + · change squaredLength (x-(C.innerMark p).val) < C.radius^2 + rw [← hs] + exact C.crossingChord_interior_in_disk p s hsi + · have ha := crossing_reconnections_avoid_point _ _ _ _ x hd s.val t.val hsi hti hs'.symm ht'.symm + intro i + cases i + · exact ha.1 + · exact ha.2 + +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Refinement.lean b/lean/OAI/Combinatorics/CompleteCrossing/Refinement.lean new file mode 100644 index 0000000000000000000000000000000000000000..673de36183ec9ec2774bc2e4004a4675f17e7783 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Refinement.lean @@ -0,0 +1,492 @@ +import OAI.Combinatorics.CompleteCrossing.Angles +import OAI.Combinatorics.CompleteCrossing.Tracks +import OAI.Combinatorics.Crossing.AffinePathHalves +import OAI.Combinatorics.Crossing.SubdivisionSegments +import Mathlib.Algebra.BigOperators.Fin + +namespace OAI + +/-! Matching refined crossing pieces and arc directions with truncated angle coordinates. -/ + +section + +noncomputable section +open Set Zarankiewicz +namespace Paper170Geometry +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +theorem normalized_piece_vertex_not_crossing (N : Paper170.NormalizedDrawing graph) + (e : Edge) (i : ℕ) (hi : i ≤ (N.polygonal e).pieces) : + (N.polygonal e).vertices i ∉ Paper170.crossingPoints N.toContinuousDrawing := by + have he := (Paper170.toZarankiewiczParametrization (N.polygonal e)).vertices_at + (⟨i, by omega⟩ : Fin ((N.polygonal e).pieces+1)) + change (N.polygonal e).vertices i = _ at he + rw [he] + exact N.crossings_not_knots e _ + +theorem normalized_crossing_unique_piece (N : Paper170.NormalizedDrawing graph) + (e : Edge) (x : Plane) (hx : x ∈ Paper170.crossingPoints N.toContinuousDrawing) + (hxe : x ∈ Paper170.edgeInterior N.toContinuousDrawing e) : + ∃!i : Fin (N.polygonal e).pieces, + x ∈ openSegmentTrace ((N.polygonal e).vertices i.val) ((N.polygonal e).vertices (i.val+1)) := by + obtain ⟨t, ht, rfl⟩ := hxe + have hn (i : Fin ((N.polygonal e).pieces+1)) : t ≠ (N.polygonal e).knot i := by + intro he + exact N.crossings_not_knots e i (he ▸ hx) + obtain ⟨i, hi⟩ := parametrization_knot_interval (N.polygonal e) t ht hn + have hmem : N.edge e t ∈ openSegmentTrace ((N.polygonal e).vertices i.val) + ((N.polygonal e).vertices (i.val+1)) := by + rw [← parametrization_open_piece] + exact ⟨t,hi,rfl⟩ + refine ⟨i,hmem,?_⟩ + intro j hj + rw [← parametrization_open_piece] at hj + obtain ⟨s,hs,he⟩ := hj + have hst : s=t := N.edge_injective e he + subst s + apply le_antisymm + · by_contra h + have hij : i.succ ≤ j.castSucc := by change i.val+1 ≤ j.val; exact lt_of_not_ge h + exact hi.2.not_ge (((N.polygonal e).increasing.monotone hij).trans hs.1.le) + · by_contra h + have hji : j.succ ≤ i.castSucc := by change j.val+1 ≤ i.val; exact lt_of_not_ge h + exact hs.2.not_ge (((N.polygonal e).increasing.monotone hji).trans hi.1.le) + +theorem openSegmentTrace_of_mem_segment_avoiding (a b x : Plane) (S : Set Plane) + (hx : x∈S) (ha : a∉S) (hb : b∉S) (hseg : x∈segment ℝ a b) : + x∈openSegmentTrace a b := by + rw [← Path.range_segment] at hseg + obtain ⟨t,ht⟩ := hseg + have he : segmentPoint a b t.val=x := by + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + exact ⟨t.val,segment_parameter_strict_of_avoids_endpoints a b x S hx ha hb t.val t.property he,he⟩ + +theorem minimum_crossing_piece_unique [Fintype Vertex] (N : Paper170.NormalizedDrawing graph) + (V : VertexTruncation N.toContinuousDrawing) (e : Edge) (x : Plane) + (hx : x ∈ Paper170.crossingPoints N.toContinuousDrawing) + (i j : Fin (V.chain e).pieces) + (hi : x∈segment ℝ ((V.chain e).vertices i.val) ((V.chain e).vertices (i.val+1))) + (hj : x∈segment ℝ ((V.chain e).vertices j.val) ((V.chain e).vertices (j.val+1))) : i=j := by + suffices hh : ∀ i j : Fin (V.chain e).pieces, i by omega + | 1, i, hi => by + have he : i=0 := by omega + subst i + refine ⟨0,1,by norm_num,?_⟩ + intro t + simp only [polygonalArcPath,intervalSegment_zero_one,Path.segment_apply, + AffineMap.lineMap_apply_module,segmentPoint] + | n+2, i, hi => by + by_cases hprev : i graph.loopless e (N.vertex_injective he) + have hγseg : ∀t : unitInterval, + N.edge e (intervalSegment ((N.polygonal e).knot k.castSucc) ((N.polygonal e).knot k.succ) t) = + Paper170.segmentPoint ((N.polygonal e).vertices k.val) ((N.polygonal e).vertices (k.val+1)) t.val := + (Paper170.toZarankiewiczParametrization (N.polygonal e)).segment_formula k + have hηseg : ∀t : unitInterval, (V.chain e).path (intervalSegment a b t) = + Paper170.segmentPoint ((V.chain e).vertices i.val) ((V.chain e).vertices (i.val+1)) t.val := hseg + obtain ⟨r,hr,he⟩ := Paper170.path_segments_direction_of_mem (N.edge e) (V.chain e).path + (N.edge_injective e) ((V.chain e).minimum_path_injective hend (V.minimal e)) + (drawing_chain_range_eq N.toContinuousDrawing e (V.chain e)).symm + ((N.polygonal e).knot k.castSucc) ((N.polygonal e).knot k.succ) a b + ((N.polygonal e).increasing Fin.castSucc_lt_succ) hab + ((N.polygonal e).vertices k.val) ((N.polygonal e).vertices (k.val+1)) + ((V.chain e).vertices i.val) ((V.chain e).vertices (i.val+1)) hγseg hηseg x hxk hxfull + refine ⟨(V.chain e).truncatedScale V.radius i.val * r, + mul_pos ((V.chain e).truncatedScale_pos V.radius V.radius_pos (V.short e).1 (V.short e).2 i.val) hr, ?_⟩ + change trackDirection ((V.chain e).truncatedVertices V.radius) i.val = _ + rw [(V.chain e).truncated_direction V.radius i.val i.isLt] + change (V.chain e).truncatedScale V.radius i.val • + ((V.chain e).vertices (i.val+1)-(V.chain e).vertices i.val) = _ + rw [he,smul_smul] + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Set Zarankiewicz +namespace Paper170Geometry +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +theorem minimum_first_direction (N : Paper170.NormalizedDrawing graph) + (V : VertexTruncation N.toContinuousDrawing) (e : Edge) : + ∃r : ℝ, 0 < r ∧ (V.chain e).vertices 1 - (V.chain e).vertices 0 = + r • ((N.polygonal e).vertices 1 - (N.polygonal e).vertices 0) := by + let k : Fin (N.polygonal e).pieces := ⟨0, (N.polygonal e).positive⟩ + obtain ⟨a,b,hab,hseg⟩ := polygonalArcPath_piece_interval (V.chain e).vertices + (V.chain e).pieces 0 (V.pieces_pos e) + have hend : N.vertex (graph.src e) ≠ N.vertex (graph.dst e) := + fun he => graph.loopless e (N.vertex_injective he) + apply Paper170.path_segments_direction (N.edge e) (V.chain e).path + (N.edge_injective e) ((V.chain e).minimum_path_injective hend (V.minimal e)) + (drawing_chain_range_eq N.toContinuousDrawing e (V.chain e)).symm + ((N.polygonal e).knot k.castSucc) ((N.polygonal e).knot k.succ) a b + ((N.polygonal e).increasing Fin.castSucc_lt_succ) hab + ((N.polygonal e).vertices 0) ((N.polygonal e).vertices 1) + ((V.chain e).vertices 0) ((V.chain e).vertices 1) + ((Paper170.toZarankiewiczParametrization (N.polygonal e)).segment_formula k) + hseg 0 0 (by norm_num) (by norm_num) + simpa [Paper170.segmentPoint] using + (N.polygonal e).vertices_first.trans (V.chain e).first.symm + +theorem minimum_last_direction (N : Paper170.NormalizedDrawing graph) + (V : VertexTruncation N.toContinuousDrawing) (e : Edge) : + ∃r : ℝ, 0 < r ∧ (V.chain e).vertices ((V.chain e).pieces-1) - + (V.chain e).vertices (V.chain e).pieces = + r • ((N.polygonal e).vertices ((N.polygonal e).pieces-1) - + (N.polygonal e).vertices (N.polygonal e).pieces) := by + have hn : 0 < (N.polygonal e).pieces := (N.polygonal e).positive + have hv : 0 < (V.chain e).pieces := V.pieces_pos e + let k : Fin (N.polygonal e).pieces := ⟨(N.polygonal e).pieces-1, by omega⟩ + obtain ⟨a,b,hab,hseg⟩ := polygonalArcPath_piece_interval (V.chain e).vertices + (V.chain e).pieces ((V.chain e).pieces-1) (by omega) + have hend : N.vertex (graph.src e) ≠ N.vertex (graph.dst e) := + fun he => graph.loopless e (N.vertex_injective he) + have hnk : k.val+1 = (N.polygonal e).pieces := by dsimp [k]; omega + have hvk : (V.chain e).pieces-1+1 = (V.chain e).pieces := by omega + have hγseg := (Paper170.toZarankiewiczParametrization (N.polygonal e)).segment_formula k + change ∀t, N.edge e (intervalSegment ((N.polygonal e).knot k.castSucc) + ((N.polygonal e).knot k.succ) t) = + Paper170.segmentPoint ((N.polygonal e).vertices k.val) + ((N.polygonal e).vertices (k.val+1)) t.val at hγseg + rw [hnk] at hγseg + rw [hvk] at hseg + exact Paper170.path_final_segments_direction (N.edge e) (V.chain e).path + (N.edge_injective e) ((V.chain e).minimum_path_injective hend (V.minimal e)) + (drawing_chain_range_eq N.toContinuousDrawing e (V.chain e)).symm + ((N.polygonal e).knot k.castSucc) ((N.polygonal e).knot k.succ) a b + ((N.polygonal e).increasing Fin.castSucc_lt_succ) hab + ((N.polygonal e).vertices k.val) ((N.polygonal e).vertices (N.polygonal e).pieces) + ((V.chain e).vertices ((V.chain e).pieces-1)) ((V.chain e).vertices (V.chain e).pieces) + hγseg hseg ((N.polygonal e).vertices_last.trans (V.chain e).last.symm) + +/-- The truncation port lies on the positive ray of the original outward spoke. -/ +theorem spokePort_pos_mul_outward (N : Paper170.NormalizedDrawing graph) + (V : VertexTruncation N.toContinuousDrawing) (j : Vertex) (e : IncidentEdges graph j) : + ∃r : ℝ, 0 < r ∧ V.spokePort j e - N.vertex j = r • Paper170.outwardSpoke N j e.val := by + by_cases hsrc : j = graph.src e.val + · obtain ⟨r,hr,he⟩ := minimum_first_direction N V e.val + have hp := radialPort_parameter_between ((V.chain e.val).vertices 0) + ((V.chain e.val).vertices 1) V.radius V.radius_pos (V.weak_short e.val).1 + refine ⟨(V.radius / Real.sqrt (squaredLength + ((V.chain e.val).vertices 1 - (V.chain e.val).vertices 0))) * r, + mul_pos hp.1 hr, ?_⟩ + change drawingSpokePort N.toContinuousDrawing V.chain V.radius j e - N.vertex j = _ + rw [drawingSpokePort, ite_eq_left hsrc, PolygonalChain.startPort] + have hcenter : N.vertex j = (V.chain e.val).vertices 0 := by + exact (congrArg N.vertex hsrc).trans (V.chain e.val).first.symm + rw [hcenter, radialPort_sub, he, smul_smul, Paper170.outwardSpoke, ite_eq_left hsrc.symm] + · have hdst : j = graph.dst e.val := e.property.resolve_left hsrc + obtain ⟨r,hr,he⟩ := minimum_last_direction N V e.val + have hshort : V.radius^2 < squaredLength + ((V.chain e.val).vertices ((V.chain e.val).pieces-1) - + (V.chain e.val).vertices (V.chain e.val).pieces) := by + rw [squaredLength_sub_comm] + exact (V.weak_short e.val).2 + have hp := radialPort_parameter_between ((V.chain e.val).vertices (V.chain e.val).pieces) + ((V.chain e.val).vertices ((V.chain e.val).pieces-1)) V.radius V.radius_pos hshort + refine ⟨(V.radius / Real.sqrt (squaredLength + ((V.chain e.val).vertices ((V.chain e.val).pieces-1) - + (V.chain e.val).vertices (V.chain e.val).pieces))) * r, mul_pos hp.1 hr, ?_⟩ + change drawingSpokePort N.toContinuousDrawing V.chain V.radius j e - N.vertex j = _ + rw [drawingSpokePort, ite_eq_right hsrc, PolygonalChain.endPort] + have hcenter : N.vertex j = (V.chain e.val).vertices (V.chain e.val).pieces := by + exact (congrArg N.vertex hdst).trans (V.chain e.val).last.symm + rw [hcenter, radialPort_sub, he, smul_smul, Paper170.outwardSpoke, + ite_eq_right (Ne.symm hsrc)] + +end Paper170Geometry + +end +end + +section + +/-! Circle coordinates chosen with the very same cuts and local orders as the +original normalized drawing. -/ +noncomputable section +open Set Zarankiewicz +namespace Paper170Geometry +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +theorem exists_truncatedSpokeCoordinates_compatible (N : Paper170.NormalizedDrawing graph) + (V : VertexTruncation N.toContinuousDrawing) (O : Paper170.SpokeOrders N) : + ∃C : TruncatedSpokeCoordinates V, ∀j (e f : IncidentEdges graph j), + orderSign (C.node j e) (C.node j f) = Paper170.spokeComparison O j e.val f.val := by + classical + let p (j : Vertex) (e : IncidentEdges graph j) : Plane := + V.radius⁻¹ • (V.spokePort j e-N.vertex j) + have hinc (j : Vertex) (e : IncidentEdges graph j) : + graph.src e.val=j ∨ graph.dst e.val=j := e.property.imp Eq.symm Eq.symm + have hp (j : Vertex) (e : IncidentEdges graph j) : Paper170.squaredLength (p j e)=1 := by + change squaredLength (V.radius⁻¹ • (V.spokePort j e-N.vertex j))=1 + rw [squaredLength_smul,V.spokePort_circle,inv_pow, + inv_mul_cancel₀ (pow_ne_zero 2 V.radius_pos.ne')] + have hangle (j : Vertex) (e : IncidentEdges graph j) : + Paper170.spokeAngle (O.cut j) (p j e)= + Paper170.spokeAngle (O.cut j) (Paper170.outwardSpoke N j e.val) := by + dsimp only [p] + rw [Paper170.spokeAngle_smul _ _ (inv_pos.mpr V.radius_pos)] + obtain ⟨r,hr,he⟩ := spokePort_pos_mul_outward N V j e + rw [he,Paper170.spokeAngle_smul _ _ hr] + have hex (j : Vertex) (e : IncidentEdges graph j) : + ∃t : ℝ, circlePoint t=Paper170.angleRotation (O.cut j) (p j e) := by + apply Paper170.angleRotation_parameter _ _ (hp j e) + rw [hangle] + exact O.cut_avoids j ⟨e.val,hinc j e⟩ + choose node hnode using hex + have hpoint (j : Vertex) (e : IncidentEdges graph j) : + similarityPoint (N.vertex j) (Paper170.angleCoordinateFrame (O.cut j) V.radius) + (circlePoint (node j e))=V.spokePort j e := by + rw [hnode] + exact Paper170.angleCoordinateFrame_point _ _ V.radius_pos _ _ + let C : TruncatedSpokeCoordinates V := { + frame := fun j => Paper170.angleCoordinateFrame (O.cut j) V.radius + frame_ne_zero := fun j => Paper170.angleCoordinateFrame_ne_zero _ _ V.radius_pos + frame_length := fun j => Paper170.angleCoordinateFrame_length (O.cut j) V.radius + node := node + node_injective := by + intro j e f he + apply V.spokePort_injective (normalized_noAdjacent N) j + rw [← hpoint j e,← hpoint j f,he] + point_eq := hpoint } + refine ⟨C,?_⟩ + have harg (j : Vertex) (e : IncidentEdges graph j) : + Paper170.spokeAngle (O.cut j) (Paper170.outwardSpoke N j e.val) = + Complex.arg (Paper170.complexPoint (circlePoint (node j e))) := by + rw [hnode,Paper170.angleRotation_complex] + exact (hangle j e).symm + have hlt (j : Vertex) (e f : IncidentEdges graph j) : + @LT.lt _ (O.order j).toLT ⟨e.val,hinc j e⟩ ⟨f.val,hinc j f⟩ ↔ node j e < node j f := by + rw [O.compatible,harg j e,harg j f,Paper170.circlePoint_arg_lt] + intro j e f + change orderSign (node j e) (node j f)=_ + unfold Paper170.spokeComparison + rw [dite_eq_left (hinc j e),dite_eq_left (hinc j f)] + simp only [orderSign,hlt] + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Set Zarankiewicz +open scoped BigOperators +namespace Paper170Geometry +variable {Vertex Edge : Type} [Fintype Vertex] {graph : Paper170.Graph Vertex Edge} + +/-- The only remaining geometric input is equality of the local oriented crossing signs. -/ +theorem signedIntersection_eq_of_matching_signs (N : Paper170.NormalizedDrawing graph) + (V : VertexTruncation N.toContinuousDrawing) (e f : Edge) (hef : e≠f) + (hmatch : ∀ (i : Fin (V.pieces e)) (j : Fin (V.pieces f)) + (k : Fin (N.polygonal e).pieces) (l : Fin (N.polygonal f).pieces) (x : Plane), + x∈openSegmentTrace (V.vertices e i.val) (V.vertices e (i.val+1)) → + x∈openSegmentTrace (V.vertices f j.val) (V.vertices f (j.val+1)) → + x∈openSegmentTrace ((N.polygonal e).vertices k.val) ((N.polygonal e).vertices (k.val+1)) → + x∈openSegmentTrace ((N.polygonal f).vertices l.val) ((N.polygonal f).vertices (l.val+1)) → + segmentCrossingSign (V.vertices e i.val) (V.vertices e (i.val+1)) + (V.vertices f j.val) (V.vertices f (j.val+1)) = + segmentCrossingSign ((N.polygonal e).vertices k.val) ((N.polygonal e).vertices (k.val+1)) + ((N.polygonal f).vertices l.val) ((N.polygonal f).vertices (l.val+1))) : + V.signedIntersection e f=Paper170.interiorIntersection N e f := by + classical + let A := Fin (V.pieces e) × Fin (V.pieces f) + let B := Fin (N.polygonal e).pieces × Fin (N.polygonal f).pieces + let F : A → ℝ := fun a => segmentCrossingSign + (V.vertices e a.1.val) (V.vertices e (a.1.val+1)) + (V.vertices f a.2.val) (V.vertices f (a.2.val+1)) + let G : B → ℝ := fun b => segmentCrossingSign + ((N.polygonal e).vertices b.1.val) ((N.polygonal e).vertices (b.1.val+1)) + ((N.polygonal f).vertices b.2.val) ((N.polygonal f).vertices (b.2.val+1)) + let R : A → B → Prop := fun a b => ∃x : Plane, + x∈openSegmentTrace (V.vertices e a.1.val) (V.vertices e (a.1.val+1)) ∧ + x∈openSegmentTrace (V.vertices f a.2.val) (V.vertices f (a.2.val+1)) ∧ + x∈openSegmentTrace ((N.polygonal e).vertices b.1.val) ((N.polygonal e).vertices (b.1.val+1)) ∧ + x∈openSegmentTrace ((N.polygonal f).vertices b.2.val) ((N.polygonal f).vertices (b.2.val+1)) + have hsame (a : A) (b : B) (h : R a b) : F a=G b := by + obtain ⟨x,hx₁,hx₂,hx₃,hx₄⟩ := h + exact hmatch a.1 a.2 b.1 b.2 x hx₁ hx₂ hx₃ hx₄ + have hF : ∀a, F a≠0 → ∃!b, G b≠0 ∧ R a b := by + intro a ha + have hproper := (segmentCrossingSign_ne_zero_iff _ _ _ _).mp ha + obtain ⟨s,hs,t,ht,he⟩ := hproper.2 + let x := segmentPoint (V.vertices e a.1.val) (V.vertices e (a.1.val+1)) s + have hx₁ : x∈openSegmentTrace (V.vertices e a.1.val) (V.vertices e (a.1.val+1)) := ⟨s,hs,rfl⟩ + have hx₂ : x∈openSegmentTrace (V.vertices f a.2.val) (V.vertices f (a.2.val+1)) := ⟨t,ht,he.symm⟩ + have hxe := V.range_subset_edgeInterior e (V.piece_subset_range e a.1.val a.1.isLt + (openSegmentTrace_subset_segment _ _ hx₁)) + have hxf := V.range_subset_edgeInterior f (V.piece_subset_range f a.2.val a.2.isLt + (openSegmentTrace_subset_segment _ _ hx₂)) + have hx : x∈Paper170.crossingPoints N.toContinuousDrawing := ⟨e,f,hef,hxe,hxf⟩ + obtain ⟨i,hi,hu⟩ := normalized_crossing_unique_piece N e x hx hxe + obtain ⟨j,hj,hv⟩ := normalized_crossing_unique_piece N f x hx hxf + have hR : R a (i,j) := ⟨x,hx₁,hx₂,hi,hj⟩ + refine ⟨(i,j),⟨?_,hR⟩,?_⟩ + · rwa [← hsame a (i,j) hR] + · rintro b ⟨_,y,hy₁,hy₂,hy₃,hy₄⟩ + have hyx : y=x := openSegments_inter_subsingleton _ _ _ _ hproper.1 ⟨hy₁,hy₂⟩ ⟨hx₁,hx₂⟩ + subst y + exact Prod.ext (hu b.1 hy₃) (hv b.2 hy₄) + have hG : ∀b, G b≠0 → ∃!a, F a≠0 ∧ R a b := by + intro b hb + have hproper := (segmentCrossingSign_ne_zero_iff _ _ _ _).mp hb + obtain ⟨s,hs,t,ht,he⟩ := hproper.2 + let x := segmentPoint ((N.polygonal e).vertices b.1.val) ((N.polygonal e).vertices (b.1.val+1)) s + have hx₃ : x∈openSegmentTrace ((N.polygonal e).vertices b.1.val) + ((N.polygonal e).vertices (b.1.val+1)) := ⟨s,hs,rfl⟩ + have hx₄ : x∈openSegmentTrace ((N.polygonal f).vertices b.2.val) + ((N.polygonal f).vertices (b.2.val+1)) := ⟨t,ht,he.symm⟩ + have hxe : x∈Paper170.edgeInterior N.toContinuousDrawing e := + (N.polygonal e).segment_mem_interior N.toContinuousDrawing e b.1 s hs + have hxf : x∈Paper170.edgeInterior N.toContinuousDrawing f := by + rw [show x=segmentPoint ((N.polygonal f).vertices b.2.val) + ((N.polygonal f).vertices (b.2.val+1)) t from he] + exact (N.polygonal f).segment_mem_interior N.toContinuousDrawing f b.2 t ht + have hx : x∈Paper170.crossingPoints N.toContinuousDrawing := ⟨e,f,hef,hxe,hxf⟩ + obtain ⟨i,hi,hu⟩ := truncated_crossing_unique_piece N V e x hx hxe + obtain ⟨j,hj,hv⟩ := truncated_crossing_unique_piece N V f x hx hxf + have hR : R (i,j) b := ⟨x,hi,hj,hx₃,hx₄⟩ + refine ⟨(i,j),⟨?_,hR⟩,?_⟩ + · rwa [hsame (i,j) b hR] + · rintro a ⟨_,y,hy₁,hy₂,hy₃,hy₄⟩ + have hyx : y=x := openSegments_inter_subsingleton _ _ _ _ hproper.1 ⟨hy₃,hy₄⟩ ⟨hx₃,hx₄⟩ + subst y + exact Prod.ext (hu a.1 hy₁) (hv a.2 hy₂) + have hsum : ∑a, F a = ∑b, G b := + sum_eq_sum_of_unique_match F G R hF hG (fun a b _ _ h => hsame a b h) + rw [VertexTruncation.signedIntersection,ite_eq_right hef,Paper170.interiorIntersection,ite_eq_right hef] + dsimp only [A,B,F,G] at hsum + simp only [Fintype.sum_prod_type] at hsum + simp only [Paper170.segmentIntersection_eq_segmentCrossingSign] + change polygonIntersection (V.vertices e) (V.vertices f) (V.pieces e) (V.pieces f) = + polygonIntersection (N.polygonal e).vertices (N.polygonal f).vertices + (N.polygonal e).pieces (N.polygonal f).pieces + simpa only [polygonIntersection_eq_fin_sum] using hsum + +end Paper170Geometry + +end +end + +section + +/-! The cycle engine computes the signed intersection of the original, arbitrary +normalized subdivision, independently of the minimal-chain presentation. -/ +noncomputable section +open Set Zarankiewicz +namespace Paper170Geometry.VertexTruncation +variable {Vertex Edge : Type} [Fintype Vertex] {graph : Paper170.Graph Vertex Edge} + +theorem signedIntersection_eq_interiorIntersection (N : Paper170.NormalizedDrawing graph) + (V : VertexTruncation N.toContinuousDrawing) (e f : Edge) : + V.signedIntersection e f = Paper170.interiorIntersection N e f := by + classical + by_cases hef : e=f + · subst f + rw [V.signedIntersection_self] + simp [Paper170.interiorIntersection] + · apply signedIntersection_eq_of_matching_signs N V e f hef + intro i j k l x hxi hxj hxk hxl + have hxe := V.range_subset_edgeInterior e (V.piece_subset_range e i.val i.isLt + (openSegmentTrace_subset_segment _ _ hxi)) + have hxf := V.range_subset_edgeInterior f (V.piece_subset_range f j.val j.isLt + (openSegmentTrace_subset_segment _ _ hxj)) + have hx : x∈Paper170.crossingPoints N.toContinuousDrawing := ⟨e,f,hef,hxe,hxf⟩ + obtain ⟨r,hr,he⟩ := truncated_direction_pos_mul_original N V e i k x hx hxi hxk + obtain ⟨s,hs,hf⟩ := truncated_direction_pos_mul_original N V f j l x hx hxj hxl + exact segmentCrossingSign_eq_of_pos_directions _ _ _ _ _ _ _ _ x r s hr hs he hf hxi hxj hxk hxl + +end Paper170Geometry.VertexTruncation + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Residues.lean b/lean/OAI/Combinatorics/CompleteCrossing/Residues.lean new file mode 100644 index 0000000000000000000000000000000000000000..a035355752ec247bf4a851d60aeaee0e3680a464 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Residues.lean @@ -0,0 +1,319 @@ +import OAI.Combinatorics.CompleteCrossing.Hill +import Mathlib.Data.Fintype.Card +import Mathlib.Data.Nat.ModEq +import Mathlib.Data.Nat.Prime.Basic + +namespace OAI + +/-! Residue fibers, same-page residues, and parity counts. -/ + +section + +noncomputable section +namespace Paper170 + +theorem sameColorResidues_eq_intervals {n k : ℕ} (hn : 3 ≤ n) + (hk : k ≤ n / 2) : + sameColorResidues n k = + Finset.Ico 0 (n / 2 - k) ∪ Finset.Ico (n / 2) (n - k) := by + ext r + simp only [sameColorResidues, Finset.mem_filter, Finset.mem_range, + residueColor, decide_eq_decide, Finset.mem_union, Finset.mem_Ico] + by_cases hr : r < n + · rw [Nat.mod_eq_of_lt hr] + by_cases hrs : r + k < n + · rw [Nat.mod_eq_of_lt hrs] + omega + · rw [Nat.mod_eq_sub_mod (by omega : n ≤ r + k), + Nat.mod_eq_of_lt (by omega : r + k - n < n)] + omega + · omega + +theorem sameColorResidues_eq_intervals_large {n k : ℕ} (hn : 3 ≤ n) + (hk : n / 2 < k) (hkn : k < n) : + sameColorResidues n k = + Finset.Ico (n - k) (n / 2) ∪ Finset.Ico (n + n / 2 - k) n := by + ext r + simp only [sameColorResidues, Finset.mem_filter, Finset.mem_range, + residueColor, decide_eq_decide, Finset.mem_union, Finset.mem_Ico] + by_cases hr : r < n + · rw [Nat.mod_eq_of_lt hr] + by_cases hrs : r + k < n + · rw [Nat.mod_eq_of_lt hrs] + omega + · rw [Nat.mod_eq_sub_mod (by omega : n ≤ r + k), + Nat.mod_eq_of_lt (by omega : r + k - n < n)] + omega + · omega + +theorem sameColorResidues_card {n k : ℕ} (hn : 3 ≤ n) (hk : 2 ≤ k) + (hkn : k ≤ n - 2) : + (sameColorResidues n k).card = n - 2 * min k (n - k) := by + by_cases hh : k ≤ n / 2 + · rw [sameColorResidues_eq_intervals hn hh] + have hd : Disjoint (Finset.Ico 0 (n / 2 - k)) (Finset.Ico (n / 2) (n - k)) := by + apply Finset.disjoint_left.mpr + simp only [Finset.mem_Ico] + omega + rw [Finset.card_union_of_disjoint hd, Nat.card_Ico, Nat.card_Ico, + min_eq_left (by omega : k ≤ n - k)] + omega + · rw [sameColorResidues_eq_intervals_large hn (by omega) (by omega)] + have hd : Disjoint (Finset.Ico (n - k) (n / 2)) (Finset.Ico (n + n / 2 - k) n) := by + apply Finset.disjoint_left.mpr + simp only [Finset.mem_Ico] + omega + rw [Finset.card_union_of_disjoint hd, Nat.card_Ico, Nat.card_Ico, + min_eq_right (by omega : n - k ≤ k)] + omega + +@[simp] theorem residueColor_mod (n r : ℕ) : residueColor n (r % n) = residueColor n r := by + simp [residueColor] + +theorem residueColor_add_half {m : ℕ} (hm : 0 < m) (r : ℕ) : + residueColor (2 * m) (r + m) = !residueColor (2 * m) r := by + have hr := Nat.mod_lt r (by omega : 0 < 2 * m) + simp only [residueColor, Nat.mul_div_right m (by decide : 0 < 2)] + rw [Nat.add_mod, Nat.mod_eq_of_lt (by omega : m < 2 * m)] + by_cases hh : r % (2 * m) < m + · rw [Nat.mod_eq_of_lt (by omega : r % (2 * m) + m < 2 * m)] + simp [hh, show ¬r % (2 * m) + m < m by omega] + · rw [Nat.mod_eq_sub_mod (by omega : 2 * m ≤ r % (2 * m) + m), + Nat.mod_eq_of_lt (by omega : r % (2 * m) + m - 2 * m < 2 * m)] + simp [hh, show r % (2 * m) + m - 2 * m < m by omega] + +theorem sameColorResidues_half_shift {m k r : ℕ} (hm : 0 < m) + (hr : r < 2 * m) : + r ∈ sameColorResidues (2 * m) k ↔ + (r + m) % (2 * m) ∈ sameColorResidues (2 * m) k := by + simp only [sameColorResidues, Finset.mem_filter, Finset.mem_range, hr, + Nat.mod_lt _ (by omega : 0 < 2 * m), true_and, residueColor_mod] + rw [show residueColor (2 * m) ((r + m) % (2 * m) + k) = + residueColor (2 * m) (r + k + m) by simp [residueColor, Nat.add_mod, Nat.add_right_comm]] + rw [residueColor_add_half hm, residueColor_add_half hm] + simp + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +theorem residueFiber_card_odd {n b r : ℕ} (hn : Odd n) (hr : r < n) : + (residueFiber n b r).card = 1 := by + let f : Fin n → Fin n := fun a => ⟨(2 * a.val + b) % n, Nat.mod_lt _ (by omega)⟩ + have hi : Function.Injective f := by + intro a c h + have hmod : Nat.ModEq n (2 * a.val + b) (2 * c.val + b) := congrArg Fin.val h + have he := (hmod.add_right_cancel' b).cancel_left_of_coprime hn.coprime_two_right + apply Fin.ext + simpa only [Nat.ModEq, Nat.mod_eq_of_lt a.isLt, Nat.mod_eq_of_lt c.isLt] using he + obtain ⟨a, ha⟩ := (Finite.surjective_of_injective hi) ⟨r, hr⟩ + have hset : residueFiber n b r = {a.val} := by + ext c + simp only [residueFiber, Finset.mem_filter, Finset.mem_range, Finset.mem_singleton] + constructor + · rintro ⟨hc, hcr⟩ + have he : f ⟨c, hc⟩ = f a := by + rw [ha] + exact Fin.ext hcr + exact congrArg Fin.val (hi he) + · rintro rfl + exact ⟨a.isLt, congrArg Fin.val ha⟩ + rw [hset, Finset.card_singleton] + +theorem add_mod_inj {n a c b : ℕ} (ha : a < n) (hc : c < n) + (h : (a + b) % n = (c + b) % n) : a = c := by + have he := Nat.ModEq.add_right_cancel' b h + simpa only [Nat.ModEq, Nat.mod_eq_of_lt ha, Nat.mod_eq_of_lt hc] using he + +theorem add_mod_surj {n r : ℕ} (hr : r < n) (b : ℕ) : + ∃ a < n, (a + b) % n = r := by + let f : Fin n → Fin n := fun a => ⟨(a.val + b) % n, Nat.mod_lt _ (by omega)⟩ + have hi : Function.Injective f := by + intro a c h + exact Fin.ext (add_mod_inj a.isLt c.isLt (congrArg Fin.val h)) + obtain ⟨a, ha⟩ := (Finite.surjective_of_injective hi) ⟨r, hr⟩ + exact ⟨a.val, a.isLt, congrArg Fin.val ha⟩ + +theorem doubled_residue {m a b r : ℕ} : + (2 * a + b) % (2 * m) = r ↔ + (a + b / 2) % m = r / 2 ∧ b % 2 = r % 2 := by + have hh : (2 * a + b) % (2 * m) = b % 2 + 2 * ((a + b / 2) % m) := by + rw [Nat.mod_mul] + congr 1 + · omega + · rw [show (2 * a + b) / 2 = a + b / 2 by omega] + rw [hh] + omega + +theorem residueFiber_card_even {m b r : ℕ} (hm : 0 < m) (hr : r < 2 * m) : + (residueFiber (2 * m) b r).card = if r % 2 = b % 2 then 2 else 0 := by + by_cases hp : r % 2 = b % 2 + · rw [ite_eq_left hp] + obtain ⟨a, ha, har⟩ := add_mod_surj (show r / 2 < m by omega) (b / 2) + have hset : residueFiber (2 * m) b r = {a, a + m} := by + ext c + simp only [residueFiber, Finset.mem_filter, Finset.mem_range, + Finset.mem_insert, Finset.mem_singleton, doubled_residue] + constructor + · rintro ⟨hc, hcr, _⟩ + have he : c % m = a := add_mod_inj (Nat.mod_lt _ hm) ha + (by simpa only [Nat.add_mod, Nat.mod_mod] using hcr.trans har.symm) + by_cases hcm : c < m + · left + simpa only [Nat.mod_eq_of_lt hcm] using he + · right + rw [Nat.mod_eq_sub_mod (by omega : m ≤ c), + Nat.mod_eq_of_lt (by omega : c - m < m)] at he + omega + · rintro (rfl | rfl) + · exact ⟨by omega, har, hp.symm⟩ + · refine ⟨by omega, ?_, hp.symm⟩ + simpa only [Nat.add_right_comm a m (b / 2), Nat.add_mod_right] using har + rw [hset, Finset.card_insert_of_notMem (by simp; omega), Finset.card_singleton] + · rw [ite_eq_right hp] + apply Finset.card_eq_zero.mpr + apply Finset.eq_empty_iff_forall_notMem.mpr + intro a + simp only [residueFiber, Finset.mem_filter, Finset.mem_range, doubled_residue] + rintro ⟨_, _, he⟩ + exact hp he.symm + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +theorem parity_balance_of_involution (s : Finset ℕ) (f : ℕ → ℕ) (c : ℕ) + (hmap : ∀ r ∈ s, f r ∈ s) (hinv : ∀ r ∈ s, f (f r) = r) + (hpar : ∀ r ∈ s, (f r + c) % 2 ≠ (r + c) % 2) : + (s.filter (fun r => (r + c) % 2 = 0)).card = + (s.filter (fun r => (r + c) % 2 = 1)).card := by + apply Finset.card_nbij' f f + · intro r hr + obtain ⟨hs, he⟩ := Finset.mem_filter.mp hr + exact Finset.mem_filter.mpr ⟨hmap r hs, by have := hpar r hs; omega⟩ + · intro r hr + obtain ⟨hs, he⟩ := Finset.mem_filter.mp hr + exact Finset.mem_filter.mpr ⟨hmap r hs, by have := hpar r hs; omega⟩ + · intro r hr + exact hinv r (Finset.mem_filter.mp hr).1 + · intro r hr + exact hinv r (Finset.mem_filter.mp hr).1 + +theorem interval_parity_balance {a b : ℕ} (heven : Even (b - a)) (c : ℕ) : + ((Finset.Ico a b).filter (fun r => (r + c) % 2 = 0)).card = + ((Finset.Ico a b).filter (fun r => (r + c) % 2 = 1)).card := by + obtain ⟨t, ht⟩ := heven + let f : ℕ → ℕ := fun r => if (r - a) % 2 = 0 then r + 1 else r - 1 + apply parity_balance_of_involution (Finset.Ico a b) f c + · intro r hr + simp only [Finset.mem_Ico] at hr ⊢ + dsimp [f] + split_ifs <;> omega + · intro r hr + simp only [Finset.mem_Ico] at hr + dsimp [f] + split_ifs <;> omega + · intro r hr + simp only [Finset.mem_Ico] at hr + dsimp [f] + split_ifs <;> omega + +theorem firstGapParity_balance {k : ℕ} (hk : Odd k) (b : ℕ) : + (firstGapParity k b 0).card = (firstGapParity k b 1).card := by + have heven : Even (k - 1) := by + rw [Nat.even_iff] + obtain ⟨t, ht⟩ := hk + omega + have heq : Finset.Icc 1 (k - 1) = Finset.Ico 1 k := by + ext r + simp only [Finset.mem_Icc, Finset.mem_Ico] + obtain ⟨t, ht⟩ := hk + omega + simpa only [firstGapParity, heq] using interval_parity_balance heven b + +theorem parity_balance_union (s t : Finset ℕ) (hd : Disjoint s t) + (hs : (s.filter (fun r => r % 2 = 0)).card = (s.filter (fun r => r % 2 = 1)).card) + (ht : (t.filter (fun r => r % 2 = 0)).card = (t.filter (fun r => r % 2 = 1)).card) : + ((s ∪ t).filter (fun r => r % 2 = 0)).card = + ((s ∪ t).filter (fun r => r % 2 = 1)).card := by + have hdis (p : ℕ) : Disjoint (s.filter (fun r => r % 2 = p)) + (t.filter (fun r => r % 2 = p)) := hd.mono (Finset.filter_subset _ _) (Finset.filter_subset _ _) + simp only [Finset.filter_union, Finset.card_union_of_disjoint (hdis 0), + Finset.card_union_of_disjoint (hdis 1), hs, ht] + +theorem sameColorResidues_parity_balance {m k : ℕ} (hm : 0 < m) + (hk : 2 ≤ k) (hkn : k ≤ 2 * m - 2) (hparity : Odd m ∨ Even k) : + (sameColorResiduesParity (2 * m) k 0).card = + (sameColorResiduesParity (2 * m) k 1).card := by + by_cases hmo : Odd m + · obtain ⟨t, ht⟩ := hmo + let f : ℕ → ℕ := fun r => if r < m then r + m else r - m + have hform (r : ℕ) (hr : r < 2 * m) : f r = (r + m) % (2 * m) := by + dsimp [f] + split_ifs with h + · rw [Nat.mod_eq_of_lt (by omega)] + · rw [Nat.mod_eq_sub_mod (by omega), Nat.mod_eq_of_lt (by omega)] + omega + apply parity_balance_of_involution (sameColorResidues (2 * m) k) f 0 + · intro r hr + have hrl : r < 2 * m := (Finset.mem_filter.mp hr).1 |> Finset.mem_range.mp + rw [hform r hrl] + exact (sameColorResidues_half_shift hm hrl).mp hr + · intro r hr + have hrl : r < 2 * m := (Finset.mem_filter.mp hr).1 |> Finset.mem_range.mp + dsimp [f] + split_ifs <;> omega + · intro r hr + have hrl : r < 2 * m := (Finset.mem_filter.mp hr).1 |> Finset.mem_range.mp + dsimp [f] + split_ifs <;> omega + · have hme : Even m := Nat.not_odd_iff_even.mp hmo + have hke : Even k := hparity.resolve_left hmo + have hm₂ : 3 ≤ 2 * m := by omega + have even_diff (a b : ℕ) (ha : Even a) (hb : Even b) : Even (a - b) := by + rw [Nat.even_iff] at * + omega + unfold sameColorResiduesParity + by_cases hhalf : k ≤ m + · rw [sameColorResidues_eq_intervals hm₂ (by simpa using hhalf)] + simp only [Nat.mul_div_right m (by decide : 0 < 2)] + apply parity_balance_union + · apply Finset.disjoint_left.mpr + simp only [Finset.mem_Ico] + omega + · simpa using interval_parity_balance (a := 0) (b := m - k) + (by simpa using even_diff m k hme hke) 0 + · have he : Even (2 * m - k - m) := by + apply even_diff _ _ (even_diff _ _ (by simp) hke) hme + simpa using interval_parity_balance he 0 + · rw [sameColorResidues_eq_intervals_large hm₂ (by simpa using Nat.lt_of_not_ge hhalf) (by omega)] + simp only [Nat.mul_div_right m (by decide : 0 < 2)] + apply parity_balance_union + · apply Finset.disjoint_left.mpr + simp only [Finset.mem_Ico] + omega + · have he : Even (m - (2 * m - k)) := even_diff _ _ hme (even_diff _ _ (by simp) hke) + simpa using interval_parity_balance he 0 + · have he : Even (2 * m - (2 * m + m - k)) := + even_diff _ _ (by simp) (even_diff _ _ + (by simpa only [two_mul, add_assoc] using hme.add hme |>.add hme) hke) + simpa using interval_parity_balance he 0 + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/SpokePorts.lean b/lean/OAI/Combinatorics/CompleteCrossing/SpokePorts.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce24586405bcd9d2234cfce42b9c6486dcbb9649 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/SpokePorts.lean @@ -0,0 +1,416 @@ +import OAI.Combinatorics.CompleteCrossing.LocalGeometry +import OAI.Combinatorics.Crossing.ChainPieceInteriors +import OAI.Combinatorics.Crossing.ChainTracePieces +import OAI.Combinatorics.Crossing.DrawingSpokePorts +import OAI.Combinatorics.Crossing.IncidentSpokePorts +import OAI.Combinatorics.Crossing.MinimumChainVertexPieces +import OAI.Combinatorics.Crossing.ShortVertexRadius +import OAI.Combinatorics.Crossing.VertexPieceClearance +import OAI.Combinatorics.Crossing.VertexSpokeBounds +import OAI.Combinatorics.Crossing.VertexTraceDisks + +namespace OAI + +/-! Chain pieces near vertices, incident spoke ports, and short vertex radii. -/ + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem drawing_chain_piece_vertex (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i < P.pieces) (j : Vertex) + (hx : D.vertex j ∈ segment ℝ (P.vertices i) (P.vertices (i+1))) : + (j=(graph.src e) ∧ i=0) ∨ (j=(graph.dst e) ∧ i+1=P.pieces) := by + obtain ⟨t,ht⟩ := P.inside i hi hx + rcases drawing_edge_vertex_parameter D e t j ht with ⟨_,he⟩ | ⟨_,he⟩ + · have hx0 : P.vertices 0 ∈ segment ℝ (P.vertices i) (P.vertices (i+1)) := by + simpa only [P.first,he] using hx + have hh := P.minimum_vertex_piece_index hmin i 0 hi (by omega) hx0 + exact Or.inl ⟨he,by omega⟩ + · have hxN : P.vertices P.pieces ∈ segment ℝ (P.vertices i) (P.vertices (i+1)) := by + simpa only [P.last,he] using hx + have hh := P.minimum_vertex_piece_index hmin i P.pieces hi (by omega) hxN + exact Or.inr ⟨he,by omega⟩ + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem drawing_chain_range_eq (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) : + Set.range P.path=Set.range (D.edge e) := + path_range_eq_of_subset (D.edge e) P.path (D.edge_injective e) P.path_range_subset + +theorem drawing_chain_pieces_pos (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) : + 0 < P.pieces := by + apply P.pieces_pos_of_ne + intro h + exact graph.loopless e (D.vertex_injective h) + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem drawing_chain_piece_open_subset_interior (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i < P.pieces) : + openSegmentTrace (P.vertices i) (P.vertices (i+1)) ⊆ Paper170.edgeInterior D e := by + intro x hx + have hseg := openSegmentTrace_subset_segment _ _ hx + have hne := openSegmentTrace_ne_endpoints _ _ + (P.minimum_vertices_ne hmin i (i+1) (by omega) (by omega)) x hx + apply edgeInterior_of_range_not_vertices D e x (P.inside i hi hseg) + intro j hj + have hvertex : D.vertex j ∈ segment ℝ (P.vertices i) (P.vertices (i+1)) := hj ▸ hseg + rcases drawing_chain_piece_vertex D e P hmin i hi j hvertex with ⟨he,hii⟩ | ⟨he,hii⟩ + · apply hne.1 + calc + x = D.vertex j := hj + _ = D.vertex ((graph.src e)) := congrArg D.vertex he + _ = P.vertices i := by simpa only [hii] using P.first.symm + · apply hne.2 + calc + x = D.vertex j := hj + _ = D.vertex ((graph.dst e)) := congrArg D.vertex he + _ = P.vertices (i+1) := by simpa only [hii] using P.last.symm + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem exists_vertex_piece_clearance [Fintype Vertex] [Fintype Edge] (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) : + ∃ r : ℝ, 0 < r ∧ + (∀ j k, j ≠ k → Disjoint (closedRoundDisk (D.vertex j) r) (closedRoundDisk (D.vertex k) r)) ∧ + (∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) + (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) := by + classical + let Bad := Σ j : Vertex, Σ e : Edge, + {i : Fin (P e).pieces // ¬ ((j=(graph.src e) ∧ i.val=0) ∨ + (j=(graph.dst e) ∧ i.val+1=(P e).pieces))} + let K : Bad → Set Plane := fun t => + segment ℝ ((P t.2.1).vertices t.2.2.val.val) ((P t.2.1).vertices (t.2.2.val.val+1)) + have hK (t : Bad) : IsCompact (K t) := by + dsimp [K] + rw [← Path.range_segment] + exact isCompact_range (Path.segment _ _).continuous + have hnot (t : Bad) : D.vertex t.1 ∉ K t := by + intro hx + exact t.2.2.property (drawing_chain_piece_vertex D t.2.1 (P t.2.1) + (hmin t.2.1) t.2.2.val.val t.2.2.val.isLt t.1 hx) + obtain ⟨ρ,hρ,hclear⟩ := exists_round_disk_clearance (fun t : Bad => D.vertex t.1) K hK hnot + obtain ⟨σ,hσ,hdis⟩ := exists_disjoint_round_disks D.vertex D.vertex_injective + refine ⟨min ρ σ,lt_min hρ hσ,?_,?_⟩ + · intro j k hjk + exact (hdis j k hjk).mono + (closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_right _ _)) + (closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_right _ _)) + · intro j e i hi + exact (hclear ⟨j,e,⟨i,hi⟩⟩).mono_left + (closedRoundDisk_mono _ (le_of_lt (lt_min hρ hσ)) (min_le_left _ _)) + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem drawing_chain_startPort_interior (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) (hshort : r^2 < squaredLength (P.vertices 1-P.vertices 0)) : + P.startPort r ∈ Paper170.edgeInterior D e := by + exact drawing_chain_piece_open_subset_interior D e P hmin 0 (drawing_chain_pieces_pos D e P) + (radialPort_mem_openSegment _ _ r hr hshort) + +theorem drawing_chain_endPort_interior (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + P.endPort r ∈ Paper170.edgeInterior D e := by + have hp := drawing_chain_pieces_pos D e P + have hs : r^2 < squaredLength (P.vertices (P.pieces-1)-P.vertices P.pieces) := by + rwa [squaredLength_sub_comm] + have hx := openSegmentTrace_reverse_mem _ _ _ (radialPort_mem_openSegment _ _ r hr hs) + apply drawing_chain_piece_open_subset_interior D e P hmin (P.pieces-1) (by omega) + simpa only [PolygonalChain.endPort,show P.pieces-1+1=P.pieces by omega] using hx + +theorem drawing_chain_startPort_circle (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) (r : ℝ) : + squaredLength (P.startPort r-D.vertex ((graph.src e)))=r^2 := by + have hp := drawing_chain_pieces_pos D e P + have h := radialPort_on_circle (P.vertices 0) (P.vertices 1) + (P.minimum_vertices_ne hmin 0 1 (by omega) hp) r + simpa only [PolygonalChain.startPort,P.first] using h + +theorem drawing_chain_endPort_circle (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) (r : ℝ) : + squaredLength (P.endPort r-D.vertex ((graph.dst e)))=r^2 := by + have hp := drawing_chain_pieces_pos D e P + have h := radialPort_on_circle (P.vertices P.pieces) (P.vertices (P.pieces-1)) + (Ne.symm (P.minimum_vertices_ne hmin (P.pieces-1) P.pieces (by omega) (by omega))) r + simpa only [PolygonalChain.endPort,P.last] using h + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem exists_vertex_trace_disks [Fintype Vertex] [Fintype Edge] (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) : + ∃ r : ℝ, 0 < r ∧ + (∀ j k, j ≠ k → Disjoint (closedRoundDisk (D.vertex j) r) (closedRoundDisk (D.vertex k) r)) ∧ + (∀ j e x, x ∈ closedRoundDisk (D.vertex j) r → + (x ∈ Set.range (D.edge e) ↔ + (j=(graph.src e) ∧ x ∈ segment ℝ ((P e).vertices 0) ((P e).vertices 1)) ∨ + (j=(graph.dst e) ∧ x ∈ segment ℝ ((P e).vertices ((P e).pieces-1)) ((P e).vertices (P e).pieces)))) := by + classical + obtain ⟨r,hr,hdis,hclear⟩ := exists_vertex_piece_clearance D P hmin + refine ⟨r,hr,hdis,?_⟩ + intro j e x hxd + have hpos := drawing_chain_pieces_pos D e (P e) + constructor + · intro hx + rw [← drawing_chain_range_eq D e (P e)] at hx + obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece (P e).vertices (P e).pieces hpos x hx + have hinc : (j=(graph.src e) ∧ i=0) ∨ (j=(graph.dst e) ∧ i+1=(P e).pieces) := by + by_contra h + exact Set.disjoint_left.mp (hclear j e ⟨i,hi⟩ h) hxd hxi + rcases hinc with ⟨hj,hii⟩ | ⟨hj,hii⟩ + · exact Or.inl ⟨hj,by simpa only [hii] using hxi⟩ + · have hlast : i=(P e).pieces-1 := by omega + exact Or.inr ⟨hj,by simpa only [hlast,show (P e).pieces-1+1=(P e).pieces by omega] using hxi⟩ + · rintro (⟨hj,hx⟩ | ⟨hj,hx⟩) + · exact (P e).inside 0 hpos hx + · have hi : (P e).pieces-1 < (P e).pieces := by omega + apply (P e).inside ((P e).pieces-1) hi + simpa only [show (P e).pieces-1+1=(P e).pieces by omega] using hx + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +def IncidentEdges (graph : Paper170.Graph Vertex Edge) (j : Vertex) := + {e : Edge // j=(graph.src e) ∨ j=(graph.dst e)} + +instance incidentEdgesFintype [Fintype Edge] (j : Vertex) : Fintype (IncidentEdges graph j) := by + classical + unfold IncidentEdges + infer_instance + +theorem incident_edges_adjacent (j : Vertex) (e f : IncidentEdges graph j) : + graph.src e.val=graph.src f.val ∨ graph.src e.val=graph.dst f.val ∨ + graph.dst e.val=graph.src f.val ∨ graph.dst e.val=graph.dst f.val := by + rcases e.property with he | he <;> rcases f.property with hf | hf + · exact Or.inl (he.symm.trans hf) + · exact Or.inr (Or.inl (he.symm.trans hf)) + · exact Or.inr (Or.inr (Or.inl (he.symm.trans hf))) + · exact Or.inr (Or.inr (Or.inr (he.symm.trans hf))) + +def drawingSpokePort (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (r : ℝ) (j : Vertex) (e : IncidentEdges graph j) : Plane := + if j=graph.src e.val then (P e.val).startPort r else (P e.val).endPort r + +theorem drawingSpokePort_interior (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (j : Vertex) (e : IncidentEdges graph j) : + drawingSpokePort D P r j e ∈ Paper170.edgeInterior D e.val := by + unfold drawingSpokePort + split_ifs + · exact drawing_chain_startPort_interior D e.val (P e.val) (hmin e.val) r hr (hshort e.val).1 + · exact drawing_chain_endPort_interior D e.val (P e.val) (hmin e.val) r hr (hshort e.val).2 + +theorem drawingSpokePort_circle (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (j : Vertex) (e : IncidentEdges graph j) : + squaredLength (drawingSpokePort D P r j e-D.vertex j)=r^2 := by + unfold drawingSpokePort + split_ifs with h + · simpa only [h] using drawing_chain_startPort_circle D e.val (P e.val) (hmin e.val) r + · have he := e.property.resolve_left h + simpa only [he] using drawing_chain_endPort_circle D e.val (P e.val) (hmin e.val) r + +theorem drawingSpokePort_injective (D : Paper170.AdmissibleDrawing graph) (hnorm : NoAdjacentCrossings D) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (j : Vertex) : Function.Injective (drawingSpokePort D.toContinuousDrawing P r j) := by + intro e f heq + by_contra hne + have hef : e.val ≠ f.val := fun h => hne (Subtype.ext h) + have hp := drawingSpokePort_interior D.toContinuousDrawing P hmin r hr hshort j e + have hq := drawingSpokePort_interior D.toContinuousDrawing P hmin r hr hshort j f + rw [← heq] at hq + have hh : drawingSpokePort D.toContinuousDrawing P r j e ∈ + Paper170.edgeInterior D.toContinuousDrawing e.val ∩ Paper170.edgeInterior D.toContinuousDrawing f.val := ⟨hp,hq⟩ + rw [hnorm.eq_empty e.val f.val hef (incident_edges_adjacent j e f)] at hh + exact hh + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem exists_vertex_spoke_bound [Fintype Edge] (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (ρ : ℝ) (hρ : 0 < ρ) : + ∃ r : ℝ, 0 < r ∧ r ≤ ρ ∧ ∀ e, + r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1)) := by + let L : Edge → ℝ := fun e => + min (squaredLength ((P e).vertices 1-(P e).vertices 0)) + (squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + have hL (e : Edge) : 0 < L e := by + have hp := drawing_chain_pieces_pos D e (P e) + have hlast := (P e).minimum_piece_ne_zero (hmin e) ((P e).pieces-1) (by omega) + rw [show (P e).pieces-1+1=(P e).pieces by omega] at hlast + exact lt_min (squaredLength_pos _ ((P e).minimum_piece_ne_zero (hmin e) 0 hp)) + (squaredLength_pos _ hlast) + obtain ⟨r,hr,hrρ,hbound⟩ := exists_small_squared_radius ρ hρ L hL + exact ⟨r,hr,hrρ,fun e => ⟨(hbound e).trans_le (min_le_left _ _), + (hbound e).trans_le (min_le_right _ _)⟩⟩ + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem exists_short_vertex_radius [Fintype Edge] (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (ρ : ℝ) (hρ : 0 < ρ) : + ∃ r : ℝ, 0 < r ∧ r ≤ ρ ∧ ∀ e, + 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1)) := by + obtain ⟨s,hs,hsρ,hbound⟩ := exists_vertex_spoke_bound D P hmin ρ hρ + refine ⟨s/2,by positivity,by linarith,?_⟩ + intro e + obtain ⟨hfirst,hlast⟩ := hbound e + constructor <;> nlinarith + +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Subdivision.lean b/lean/OAI/Combinatorics/CompleteCrossing/Subdivision.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8f42e7e179196920a92e1e60b841dd0237d1e98 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Subdivision.lean @@ -0,0 +1,219 @@ +import OAI.Combinatorics.CompleteCrossing.Plane +import OAI.Combinatorics.Crossing.FiniteAffineCover + +namespace OAI + +/-! Affine polygonal subdivisions and chain parametrizations. -/ + +section + +noncomputable section +open Set +open Zarankiewicz +open scoped Classical +namespace Paper170 + +/-- An affine cover retaining its actual interval endpoints. -/ +structure AffineCoverData {a b : Plane} (γ : Path a b) where + intervals : Finset (unitInterval × unitInterval) + ordered : ∀ ab ∈ intervals, ab.1 < ab.2 + cover : ∀ t : unitInterval, ∃ ab ∈ intervals, ab.1 ≤ t ∧ t ≤ ab.2 + affine : ∀ ab ∈ intervals, ∀ t : unitInterval, + γ (intervalSegment ab.1 ab.2 t) = Zarankiewicz.segmentPoint (γ ab.1) (γ ab.2) t.val + +def AffineCoverData.segment (a b : Plane) : AffineCoverData (Path.segment a b) where + intervals := {(0,1)} + ordered := by + intro ab hab + have h : ab = (0,1) := Finset.mem_singleton.mp hab + subst ab + norm_num + cover := fun t => ⟨(0,1), Finset.mem_singleton_self _, t.property⟩ + affine := by + intro ab hab t + have h : ab = (0,1) := Finset.mem_singleton.mp hab + subst ab + simp only [intervalSegment_zero_one, Path.source, Path.target, Path.segment_apply, + AffineMap.lineMap_apply_module, Zarankiewicz.segmentPoint] + +def AffineCoverData.trans {a b c : Plane} {γ : Path a b} {η : Path b c} + (S : AffineCoverData γ) (T : AffineCoverData η) : AffineCoverData (γ.trans η) where + intervals := S.intervals.image (fun ab => (intervalLeft ab.1, intervalLeft ab.2)) ∪ + T.intervals.image (fun ab => (intervalRight ab.1, intervalRight ab.2)) + ordered := by + intro ab hab + rcases Finset.mem_union.mp hab with hab | hab + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + exact intervalLeft_strictMono (S.ordered cd hcd) + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + exact intervalRight_strictMono (T.ordered cd hcd) + cover := by + intro t + by_cases ht : t.val ≤ 1/2 + · let u : unitInterval := ⟨2*t.val, by constructor <;> linarith [t.property.1]⟩ + obtain ⟨ab,hab,ha,hb⟩ := S.cover u + have hu : intervalLeft u=t := by apply Subtype.ext; change (2*t.val)/2=t.val; ring + refine ⟨(intervalLeft ab.1,intervalLeft ab.2), + Finset.mem_union_left _ (Finset.mem_image.mpr ⟨ab,hab,rfl⟩), ?_, ?_⟩ + · change intervalLeft ab.1 ≤ t + rw [←hu] + exact intervalLeft_strictMono.monotone ha + · change t ≤ intervalLeft ab.2 + rw [←hu] + exact intervalLeft_strictMono.monotone hb + · let u : unitInterval := ⟨2*t.val-1, by constructor <;> linarith [t.property.2]⟩ + obtain ⟨ab,hab,ha,hb⟩ := T.cover u + have hu : intervalRight u=t := by apply Subtype.ext; change (1+(2*t.val-1))/2=t.val; ring + refine ⟨(intervalRight ab.1,intervalRight ab.2), + Finset.mem_union_right _ (Finset.mem_image.mpr ⟨ab,hab,rfl⟩), ?_, ?_⟩ + · change intervalRight ab.1 ≤ t + rw [←hu] + exact intervalRight_strictMono.monotone ha + · change t ≤ intervalRight ab.2 + rw [←hu] + exact intervalRight_strictMono.monotone hb + affine := by + intro ab hab t + rcases Finset.mem_union.mp hab with hab | hab + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + rw [intervalSegment_left, path_trans_intervalLeft, path_trans_intervalLeft, path_trans_intervalLeft] + exact S.affine cd hcd t + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + rw [intervalSegment_right, path_trans_intervalRight, path_trans_intervalRight, path_trans_intervalRight] + exact T.affine cd hcd t + +lemma AffineCoverData.trans_endpoints {a b c : Plane} {γ : Path a b} {η : Path b c} + (S : AffineCoverData γ) (T : AffineCoverData η) (B : Set Plane) + (hS : ∀ ab ∈ S.intervals, γ ab.1 ∈ B ∧ γ ab.2 ∈ B) + (hT : ∀ ab ∈ T.intervals, η ab.1 ∈ B ∧ η ab.2 ∈ B) : + ∀ ab ∈ (S.trans T).intervals, (γ.trans η) ab.1 ∈ B ∧ (γ.trans η) ab.2 ∈ B := by + intro ab hab + rcases Finset.mem_union.mp hab with hab | hab + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + simpa only [path_trans_intervalLeft] using hS cd hcd + · obtain ⟨cd,hcd,rfl⟩ := Finset.mem_image.mp hab + simpa only [path_trans_intervalRight] using hT cd hcd + +lemma AffineCoverData.subdivision {a b : Plane} {γ : Path a b} + (S : AffineCoverData γ) (B : Set Plane) (ha : a ∈ B) (hb : b ∈ B) + (hS : ∀ ab ∈ S.intervals, γ ab.1 ∈ B ∧ γ ab.2 ∈ B) : + ∃ P : PolygonalParametrization γ, ∀ i, γ (P.knot i) ∈ B := by + let T : Finset unitInterval := insert 0 (insert 1 (S.intervals.image Prod.fst ∪ S.intervals.image Prod.snd)) + obtain ⟨k, _, t, ht, h0, h1, hR⟩ := exists_sorted_unitInterval_finset T (by simp [T]) (by simp [T]) + have hleft (ab : unitInterval × unitInterval) (hab : ab ∈ S.intervals) : ab.1 ∈ range t := by + rw [hR] + exact Finset.mem_insert_of_mem (Finset.mem_insert_of_mem + (Finset.mem_union_left _ (Finset.mem_image.mpr ⟨ab,hab,rfl⟩))) + have hright (ab : unitInterval × unitInterval) (hab : ab ∈ S.intervals) : ab.2 ∈ range t := by + rw [hR] + exact Finset.mem_insert_of_mem (Finset.mem_insert_of_mem + (Finset.mem_union_right _ (Finset.mem_image.mpr ⟨ab,hab,rfl⟩))) + let P : Zarankiewicz.PolygonalParametrization γ := { + pieces := k + knot := t + increasing := ht + first := h0 + last := h1 + affine := by + intro i u + let mid : unitInterval := ⟨1/2, by norm_num⟩ + let z := intervalSegment (t i.castSucc) (t i.succ) mid + have hz : t i.castSucc < z ∧ z < t i.succ := + intervalSegment_strict_between _ _ mid (ht (by change i.val < i.val+1; omega)) (by + constructor <;> change (_ : ℝ) < _ <;> norm_num [mid]) + obtain ⟨ab,hab,ha,hb⟩ := S.cover z + have hlo : ab.1 ≤ t i.castSucc := by + by_contra hn + obtain ⟨j,hj⟩ := hleft ab hab + exact strictMono_no_between_successors t ht i j + ⟨by rw [hj]; exact lt_of_not_ge hn, by rw [hj]; exact ha.trans_lt hz.2⟩ + have hhi : t i.succ ≤ ab.2 := by + by_contra hn + obtain ⟨j,hj⟩ := hright ab hab + exact strictMono_no_between_successors t ht i j + ⟨by rw [hj]; exact hz.1.trans_le hb, by rw [hj]; exact lt_of_not_ge hn⟩ + have hle : t i.castSucc ≤ t i.succ := ht.monotone (by change i.val ≤ i.val+1; omega) + exact path_affine_restrict γ ab.1 ab.2 (S.ordered ab hab) (S.affine ab hab) + (t i.castSucc) (t i.succ) ⟨hlo,hle.trans hhi⟩ ⟨hlo.trans hle,hhi⟩ u } + refine ⟨ofZarankiewiczParametrization P, ?_⟩ + intro i + have hi : t i ∈ T := by + change t i ∈ (T : Set unitInterval) + rw [←hR] + exact ⟨i,rfl⟩ + simp only [T, Finset.mem_insert, Finset.mem_union, Finset.mem_image] at hi + rcases hi with hi | hi | ⟨ab,hab,hi⟩ | ⟨ab,hab,hi⟩ + · change γ (t i) ∈ B + simpa [hi] using ha + · change γ (t i) ∈ B + simpa [hi] using hb + · change γ (t i) ∈ B + simpa only [←hi] using (hS ab hab).1 + · change γ (t i) ∈ B + simpa only [←hi] using (hS ab hab).2 + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open Zarankiewicz +open scoped Classical +namespace Paper170 + +lemma polygonalArcPath_safe_cover (v : ℕ → Plane) (B : Set Plane) (n : ℕ) + (hn : 0 < n) (hv : ∀ i, i ≤ n → v i ∈ B) : + ∃ S : AffineCoverData (polygonalArcPath v n), + ∀ ab ∈ S.intervals, polygonalArcPath v n ab.1 ∈ B ∧ polygonalArcPath v n ab.2 ∈ B := by + induction n using Nat.strong_induction_on with + | h n ih => + cases n with + | zero => omega + | succ n => + cases n with + | zero => + refine ⟨AffineCoverData.segment (v 0) (v 1), ?_⟩ + intro ab hab + have he : ab = (0,1) := Finset.mem_singleton.mp hab + subst ab + exact ⟨by simpa only [polygonalArcPath, Path.source] using hv 0 (by omega), + by simpa only [polygonalArcPath, Path.target] using hv 1 le_rfl⟩ + | succ n => + obtain ⟨S,hS⟩ := ih (n+1) (by omega) (by omega) (fun i hi => hv i (by omega)) + let T := AffineCoverData.segment (v (n+1)) (v (n+2)) + refine ⟨S.trans T, S.trans_endpoints T B hS ?_⟩ + intro ab hab + have he : ab = (0,1) := Finset.mem_singleton.mp hab + subst ab + exact ⟨by simpa only [Path.source] using hv (n+1) (by omega), + by simpa only [Path.target] using hv (n+2) le_rfl⟩ + +def PolygonalParametrization.cast {a b c d : Plane} {γ : Path a b} + (P : PolygonalParametrization γ) (ha : c = a) (hb : d = b) : + PolygonalParametrization (γ.cast ha hb) where + pieces := P.pieces + positive := P.positive + knot := P.knot + increasing := P.increasing + first := P.first + last := P.last + affine := P.affine + +lemma chain_subdivision_avoiding {O : Set Plane} {a b : Plane} + (P : PolygonalChain O a b) (hP : 0 < P.pieces) (B : Set Plane) + (hv : ∀ i, i ≤ P.pieces → P.vertices i ∈ B) : + ∃ Q : PolygonalParametrization P.path, ∀ i, P.path (Q.knot i) ∈ B := by + obtain ⟨S,hS⟩ := polygonalArcPath_safe_cover P.vertices B P.pieces hP hv + obtain ⟨Q,hQ⟩ := S.subdivision B (hv 0 (Nat.zero_le _)) (hv _ le_rfl) hS + exact ⟨Q.cast P.first.symm P.last.symm, hQ⟩ + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Support.lean b/lean/OAI/Combinatorics/CompleteCrossing/Support.lean new file mode 100644 index 0000000000000000000000000000000000000000..473912fc82cad238eba839a980c674c3fb24119f --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Support.lean @@ -0,0 +1,130 @@ +import OAI.Combinatorics.CompleteCrossing.Polynomials +import Mathlib.LinearAlgebra.BilinearForm.Orthogonal + +namespace OAI + +/-! The support form, injectivity criterion, and support-space dimension. -/ + +section + +noncomputable section +open scoped BigOperators Classical +open MvPolynomial +namespace Paper170 + +theorem collision_nonzero_on_support {n : ℕ} (node : Fin n → ℝ) + (hn : Function.Injective node) (J : CrossingTensor n) (a : SupportCoord J) : + evalFour (node a.val.1.1) (node a.val.1.2) (node a.val.2.1) (node a.val.2.2) + collisionFactor ≠ 0 := by + rcases (Finset.mem_filter.mp a.property).2 with ⟨_, _, h02, h03, h12, h13, _⟩ + simpa [evalFour, collisionFactor, Matrix.cons_val_two, Matrix.cons_val_three] using + mul_ne_zero (mul_ne_zero (mul_ne_zero (sub_ne_zero.mpr (hn.ne h02)) + (sub_ne_zero.mpr (hn.ne h03))) (sub_ne_zero.mpr (hn.ne h12))) + (sub_ne_zero.mpr (hn.ne h13)) + +lemma support_diagonal_nonzero {n : ℕ} (node : Fin n → ℝ) + (hn : Function.Injective node) (J : CrossingTensor n) (a : SupportCoord J) : + supportDiagonal node J a ≠ 0 := by + rcases (Finset.mem_filter.mp a.property).2 with ⟨h01, h23, _, _, _, _, hJ⟩ + have hc := collision_nonzero_on_support node hn J a + have hf : evalFour (node a.val.1.1) (node a.val.1.2) (node a.val.2.1) + (node a.val.2.2) fullDifference ≠ 0 := by + simpa [fullDifference, evalFour, Matrix.cons_val_two, Matrix.cons_val_three] using + mul_ne_zero (mul_ne_zero (sub_ne_zero.mpr (hn.ne (ne_of_lt h01))) + (sub_ne_zero.mpr (hn.ne (ne_of_lt h23)))) hc + exact mul_ne_zero (mul_ne_zero (mul_ne_zero (mul_ne_zero (mul_ne_zero hJ + (weight_nonzero node hn _)) (weight_nonzero node hn _)) + (weight_nonzero node hn _)) (weight_nonzero node hn _)) hf + +theorem support_bilinear_nondegenerate {n : ℕ} (node : Fin n → ℝ) + (hn : Function.Injective node) (J : CrossingTensor n) : + (supportBilinear node J).Nondegenerate := by + apply LinearMap.BilinForm.nondegenerate_toBilin'_iff_det_ne_zero.mpr + rw [Matrix.det_diagonal] + exact Finset.prod_ne_zero_iff.mpr fun a _ => support_diagonal_nonzero node hn J a + +theorem isotropic_dimension {ι : Type*} [Fintype ι] + (B : LinearMap.BilinForm ℝ (ι → ℝ)) (hB : B.Nondegenerate) + (W : Submodule ℝ (ι → ℝ)) (hW : W ≤ B.orthogonal W) : + 2 * Module.finrank ℝ W ≤ Fintype.card ι := by + have hle := Submodule.finrank_mono hW + rw [LinearMap.BilinForm.finrank_orthogonal hB] at hle + have hdim := Submodule.finrank_le W + have hv : Module.finrank ℝ (ι → ℝ) = Fintype.card ι := by simp + rw [hv] at hle hdim + omega + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +@[simp] lemma evalFour_mul (x u y v : ℝ) (P Q : Poly4) : + evalFour x u y v (P * Q) = evalFour x u y v P * evalFour x u y v Q := + map_mul (MvPolynomial.aeval ![x, u, y, v]) P Q + +lemma support_evaluation_injective_of_collision {n s : ℕ} (hs : 2 ≤ s) + (node : Fin n → ℝ) (hn : Function.Injective node) (J : CrossingTensor n) + (hdiv : ∀ P : endpointSymmetricSpace s, + supportEvaluation s node J P = 0 → collisionFactor ∣ P.val) : + Function.Injective (supportEvaluation s node J) := by + have hzero : ∀ d (P : endpointSymmetricSpace s), P.val.degreeOf 0 = d → + supportEvaluation s node J P = 0 → P.val = 0 := by + intro d + induction d using Nat.strong_induction_on with + | h d ih => + intro P hd hP + by_contra hP0 + obtain ⟨Q, hQ0, heq, hQmem, _, hQdeg⟩ := collision_quotient s hs P.val + P.property hP0 (hdiv P hP) + have hQ : supportEvaluation s node J ⟨Q, hQmem⟩ = 0 := by + funext a + have hp := congrFun hP a + change evalFour (node a.val.1.1) (node a.val.1.2) + (node a.val.2.1) (node a.val.2.2) P.val = 0 at hp + rw [heq, evalFour_mul] at hp + exact (mul_eq_zero.mp hp).resolve_left (collision_nonzero_on_support node hn J a) + exact hQ0 (ih (Q.degreeOf 0) (by omega) ⟨Q, hQmem⟩ rfl hQ) + rw [← LinearMap.ker_eq_bot, LinearMap.ker_eq_bot'] + intro P hP + exact Subtype.ext (hzero _ P rfl hP) + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +lemma support_cardinality_of_injective_isotropic {n s : ℕ} (hs : 2 ≤ s) + (node : Fin n → ℝ) (hn : Function.Injective node) (J : CrossingTensor n) + (hi : Function.Injective (supportEvaluation s node J)) + (ho : ∀ P Q : endpointSymmetricSpace s, + supportBilinear node J (supportEvaluation s node J P) (supportEvaluation s node J Q) = 0) : + 2 * (Nat.choose s 2) ^ 2 ≤ (supportedPairs J).card := by + let := symmetric_space_finite s + let f := supportEvaluation s node J + have hr : f.range ≤ (supportBilinear node J).orthogonal f.range := by + rintro _ ⟨P, rfl⟩ _ ⟨Q, rfl⟩ + exact ho Q P + have hd := isotropic_dimension (supportBilinear node J) + (support_bilinear_nondegenerate node hn J) f.range hr + have he : Module.finrank ℝ f.range = Module.finrank ℝ (endpointSymmetricSpace s) := + (LinearEquiv.ofInjective f hi).finrank_eq.symm + rw [he, symmetric_space_dimension s hs, Fintype.card_coe] at hd + exact hd + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/SurgeryIntersections.lean b/lean/OAI/Combinatorics/CompleteCrossing/SurgeryIntersections.lean new file mode 100644 index 0000000000000000000000000000000000000000..17f8079634afab4708fff74601ccad1db28bd70b --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/SurgeryIntersections.lean @@ -0,0 +1,565 @@ +import OAI.Combinatorics.CompleteCrossing.AdjacentSurgery + +namespace OAI + +/-! Surgery intersection containment, strict crossing reduction, and admissibility. -/ + +section + +/-! Actual new chords cannot meet any third normalized edge, including at ports. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry + +theorem segment_disjoint_of_open_containment (a b : Plane) (U S : Set Plane) + (hin : openSegmentTrace a b ⊆ U) (hout : Disjoint S U) + (ha : a ∉ S) (hb : b ∉ S) : Disjoint (segment ℝ a b) S := by + apply Set.disjoint_left.mpr + intro x hx hs + rcases segment_endpoint_or_open a b x hx with rfl | rfl | hx + · exact ha hs + · exact hb hs + · exact Set.disjoint_left.mp hout hs (hin hx) + +namespace PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem assembled_port_not_mem_other_edge (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (e : Edge) (r : C.Port) (her : e ≠ r.1.1) : + C.portPoint r ∉ Set.range (E.assembledEdge v e) := + fun hx => her (E.assembled_port_unique_edge v hv e r hx) + +theorem reconnection_other_edge_disjoint (E : PolygonalExterior C) + (v : Vertex → Plane) (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (p q : C.InnerIndex) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (i : Bool) (e : Edge) (hep : e ≠ p.1) (heq : e ≠ q.1) : + Disjoint (segment ℝ (C.reconnectionStart p q i) (C.reconnectionEnd p q i)) + (Set.range (E.assembledEdge v e)) := by + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ + (C.reconnection_open_in_disk p q hm i) + (E.assembled_other_edge_avoids_crossingDisk v hv p q hpq hm e hep heq) + · cases i + · exact E.assembled_port_not_mem_other_edge v hv e (C.incomingPort q) heq + · exact E.assembled_port_not_mem_other_edge v hv e (C.incomingPort p) hep + · cases i + · exact E.assembled_port_not_mem_other_edge v hv e (C.outgoingPort p) hep + · exact E.assembled_port_not_mem_other_edge v hv e (C.outgoingPort q) heq + +end PolygonalExterior +end Paper170Geometry + +end +end + +section + +/-! Each new chord avoids the retained cuts assigned to the other switched walk. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem forward_chord_disjoint_opposite_prefix + (Kq : ExteriorCrossingCut C P q) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + Disjoint (segment ℝ (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).take Kq.first.val))) := by + have hqp : q.1 ≠ p.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he.symm hm) + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ (C.reconnection_open_in_disk p q hm true) + · simpa only [DrawingPassages.crossingDisk,hm] using Kq.prefix_outside + · intro hx + exact E.assembled_port_not_mem_other_edge v hv q.1 (C.incomingPort p) hqp (Kq.prefix_subset_edge hx) + · exact Kq.outgoing_not_prefix + +theorem forward_chord_disjoint_opposite_suffix + (Kp : ExteriorCrossingCut C P p) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + Disjoint (segment ℝ (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort q))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop Kp.last.val))) := by + have hpqe : p.1 ≠ q.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm) + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ + (C.reconnection_open_in_disk p q hm true) Kp.suffix_outside + · exact Kp.incoming_not_suffix + · intro hx + exact E.assembled_port_not_mem_other_edge v hv p.1 (C.outgoingPort q) hpqe (Kp.suffix_subset_edge hx) + +theorem backward_chord_disjoint_opposite_prefix + (Kp : ExteriorCrossingCut C P p) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + Disjoint (segment ℝ (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take Kp.first.val))) := by + have hpqe : p.1 ≠ q.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm) + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ + (C.reconnection_open_in_disk p q hm false) Kp.prefix_outside + · intro hx + exact E.assembled_port_not_mem_other_edge v hv p.1 (C.incomingPort q) hpqe (Kp.prefix_subset_edge hx) + · exact Kp.outgoing_not_prefix + +theorem backward_chord_disjoint_opposite_suffix + (Kq : ExteriorCrossingCut C P q) (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) : + Disjoint (segment ℝ (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort p))) + (Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).drop Kq.last.val))) := by + have hqp : q.1 ≠ p.1 := fun he => hpq (C.innerIndex_eq_of_edge_mark p q he.symm hm) + apply segment_disjoint_of_open_containment _ _ (C.crossingDisk p) _ (C.reconnection_open_in_disk p q hm false) + · simpa only [DrawingPassages.crossingDisk,hm] using Kq.suffix_outside + · exact Kq.incoming_not_suffix + · intro hx + exact E.assembled_port_not_mem_other_edge v hv q.1 (C.outgoingPort p) hqp (Kq.suffix_subset_edge hx) + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Exact retained-track cases for intersections of the two actual rerouted paths. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem reconnected_paths_meeting_cases + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (x : Plane) (hx : x ∈ Set.range (reconnectedForwardPath Kp Kq hm)) + (hy : x ∈ Set.range (reconnectedBackwardPath Kp Kq hm)) : + (x ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).take Kp.first.val)) ∧ + x ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).take Kq.first.val))) ∨ + (x ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P p.1).drop Kp.last.val)) ∧ + x ∈ Set.range (graphWalkPath id ((drawingEdgeWalk P q.1).drop Kq.last.val))) := by + have hFP := E.forward_chord_disjoint_opposite_prefix v hvinj hv hdet P Kq hpq hm + have hFS := E.forward_chord_disjoint_opposite_suffix v hvinj hv hdet P Kp hpq hm + have hBP := E.backward_chord_disjoint_opposite_prefix v hvinj hv hdet P Kp hpq hm + have hBS := E.backward_chord_disjoint_opposite_suffix v hvinj hv hdet P Kq hpq hm + have hchord := C.reconnection_chords_disjoint p q hcross true false (by decide) + rcases reconnectedForwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · rcases reconnectedBackwardPath_trace Kp Kq hm hy with (hy | hy) | hy + · exact Or.inl ⟨hx,hy⟩ + · exact False.elim (Set.disjoint_left.mp hBP hy hx) + · exact False.elim (Set.disjoint_left.mp Kp.prefix_suffix_disjoint hx hy) + · rcases reconnectedBackwardPath_trace Kp Kq hm hy with (hy | hy) | hy + · exact False.elim (Set.disjoint_left.mp hFP hx hy) + · exact False.elim (Set.disjoint_left.mp hchord hx hy) + · exact False.elim (Set.disjoint_left.mp hFS hx hy) + · rcases reconnectedBackwardPath_trace Kp Kq hm hy with (hy | hy) | hy + · exact False.elim (Set.disjoint_left.mp Kq.prefix_suffix_disjoint hy hx) + · exact False.elim (Set.disjoint_left.mp hBS hy hx) + · exact Or.inr ⟨hy,hx⟩ + +theorem reconnected_paths_meeting_old_edges + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (x : Plane) (hx : x ∈ Set.range (reconnectedForwardPath Kp Kq hm)) + (hy : x ∈ Set.range (reconnectedBackwardPath Kp Kq hm)) : + x ∈ Set.range (E.assembledEdge v p.1) ∧ x ∈ Set.range (E.assembledEdge v q.1) := by + rcases E.reconnected_paths_meeting_cases v hvinj hv hdet P Kp Kq hpq hm hcross x hx hy with h | h + · exact ⟨Kp.prefix_subset_edge h.1,Kq.prefix_subset_edge h.2⟩ + · exact ⟨Kp.suffix_subset_edge h.1,Kq.suffix_subset_edge h.2⟩ + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Every contact of rerouted edges is carried by the original drawing tracks. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem reconnectedForwardPath_meeting_other + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (e : Edge) (hep : e ≠ p.1) (heq : e ≠ q.1) + (x : Plane) (hx : x ∈ Set.range (reconnectedForwardPath Kp Kq hm)) + (hy : x ∈ Set.range (E.assembledEdge v e)) : + x ∈ Set.range (E.assembledEdge v p.1) ∨ x ∈ Set.range (E.assembledEdge v q.1) := by + rcases reconnectedForwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · exact Or.inl (Kp.prefix_subset_edge hx) + · exact False.elim (Set.disjoint_left.mp (E.reconnection_other_edge_disjoint v hv p q hpq hm true e hep heq) hx hy) + · exact Or.inr (Kq.suffix_subset_edge hx) + +theorem reconnectedBackwardPath_meeting_other + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) + (e : Edge) (hep : e ≠ p.1) (heq : e ≠ q.1) + (x : Plane) (hx : x ∈ Set.range (reconnectedBackwardPath Kp Kq hm)) + (hy : x ∈ Set.range (E.assembledEdge v e)) : + x ∈ Set.range (E.assembledEdge v p.1) ∨ x ∈ Set.range (E.assembledEdge v q.1) := by + rcases reconnectedBackwardPath_trace Kp Kq hm hx with (hx | hx) | hx + · exact Or.inr (Kq.prefix_subset_edge hx) + · exact False.elim (Set.disjoint_left.mp (E.reconnection_other_edge_disjoint v hv p q hpq hm false e hep heq) hx hy) + · exact Or.inl (Kp.suffix_subset_edge hx) + +theorem adjacentSurgeryRoutes_meeting_other + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (e : Edge) (hep : e ≠ p.1) (heq : e ≠ q.1) + (x : Plane) (hx : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj) ∨ + x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) + (hy : x ∈ Set.range (E.assembledEdge v e)) : + x ∈ Set.range (E.assembledEdge v p.1) ∨ x ∈ Set.range (E.assembledEdge v q.1) := by + have hf := E.reconnectedForwardPath_meeting_other v hvinj hv hdet P Kp Kq hpq hm e hep heq x + have hb := E.reconnectedBackwardPath_meeting_other v hvinj hv hdet P Kp Kq hpq hm e hep heq x + rcases hx with hx | hx + · unfold adjacentSurgeryRouteP at hx + split at hx + · exact hb hx hy + · exact hf hx hy + · unfold adjacentSurgeryRouteQ at hx + split at hx + · exact hf hx hy + · exact hb hx hy + +theorem adjacentSurgeryRoutes_meeting_each_other + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (x : Plane) (hx : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj)) + (hy : x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) : + x ∈ Set.range (E.assembledEdge v p.1) ∧ x ∈ Set.range (E.assembledEdge v q.1) := by + have hh := E.reconnected_paths_meeting_old_edges v hvinj hv hdet P Kp Kq hpq hm hcross x + by_cases h : (graph.src p.1)=(graph.src q.1) + · simp only [adjacentSurgeryRouteP,adjacentSurgeryRouteQ,dite_eq_left h] at hx hy + exact hh hy hx + · simp only [adjacentSurgeryRouteP,adjacentSurgeryRouteQ,dite_eq_right h] at hx hy + exact hh hx hy + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Every actual spatial crossing of the surgery drawing was already a crossing before surgery. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem adjacentSurgeryDrawing_crossings_subset + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) : + Paper170.crossingPoints (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) ⊆ + Paper170.crossingPoints (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing := by + let B := (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing + let A := adjacentSurgeryDrawing Kp Kq hm hadj hv hemb + intro x hx + obtain ⟨e,f,hef,hxe,hxf⟩ := hx + have havoid : ∀ j, x ≠ B.vertex j := edgeInterior_not_vertex A e x hxe + have hpair (hx : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj)) + (hy : x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) : x ∈ Paper170.crossingPoints B := by + have hh := E.adjacentSurgeryRoutes_meeting_each_other v hvinj hv hdet P Kp Kq hpq hm hadj hcross x hx hy + exact crossing_of_ranges_not_vertices B p.1 q.1 + (fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm)) x hh.1 hh.2 havoid + have hmixed (g : Edge) (hgp : g ≠ p.1) (hgq : g ≠ q.1) + (hx : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj) ∨ + x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) + (hy : x ∈ Set.range (B.edge g)) : x ∈ Paper170.crossingPoints B := by + rcases E.adjacentSurgeryRoutes_meeting_other v hvinj hv hdet P Kp Kq hpq hm hadj g hgp hgq x hx hy with h | h + · exact crossing_of_ranges_not_vertices B p.1 g (Ne.symm hgp) x h hy havoid + · exact crossing_of_ranges_not_vertices B q.1 g (Ne.symm hgq) x h hy havoid + have hcases (g : Edge) (hg : x ∈ Set.range (A.edge g)) := + B.replaceTwoRoutes_range_cases p.1 q.1 (adjacentSurgeryRouteP Kp Kq hm hadj) + (adjacentSurgeryRouteQ Kp Kq hm hadj) g x hg + rcases hcases e (edgeInterior_subset_range A e hxe) with ⟨hep,hx⟩ | ⟨heq,hx⟩ | ⟨hep,heq,hx⟩ + · rcases hcases f (edgeInterior_subset_range A f hxf) with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · exact False.elim (hef (hep.trans hfp.symm)) + · exact hpair hx hy + · exact hmixed f hfp hfq (Or.inl hx) hy + · rcases hcases f (edgeInterior_subset_range A f hxf) with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · exact hpair hy hx + · exact False.elim (hef (heq.trans hfq.symm)) + · exact hmixed f hfp hfq (Or.inr hx) hy + · rcases hcases f (edgeInterior_subset_range A f hxf) with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · exact hmixed e hep heq (Or.inl hy) hx + · exact hmixed e hep heq (Or.inr hy) hx + · exact crossing_of_ranges_not_vertices B e f hef x hx hy havoid + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! A strict decrease of the actual spatial crossing set; properness of the new drawing is still separate. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + {p q : C.InnerIndex} + +theorem crossingChord_meeting_is_assembled_crossing (hpq : p ≠ q) (x : Plane) + (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + x ∈ Paper170.crossingPoints (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + have hxin := (C.reconnection_avoids_chord_meeting p q hpq x hxp hxq).1 + have hxinq : x ∈ C.crossingDisk q := by + simpa only [DrawingPassages.crossingDisk,hm] using hxin + apply crossing_of_ranges_not_vertices (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing + p.1 q.1 (fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm)) x + ((E.assembled_range_in_crossingDisk v hv p x hxin).mpr hxp) + ((E.assembled_range_in_crossingDisk v hv q x hxinq).mpr hxq) + intro j he + exact Set.disjoint_left.mp (C.crossingDisk_disjoint_vertex_disk p j) hxin (he.symm ▸ (hv j).le) + +theorem adjacentSurgeryDrawing_strict_crossing_ncard + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + (Paper170.crossingPoints (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb)).Finite ∧ + (Paper170.crossingPoints (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb)).ncard < + (Paper170.crossingPoints (E.assembledAdmissible v hvinj hv hdet).toContinuousDrawing).ncard := by + have hcross := C.crossingChord_meeting_segmentsCrossProperly p q hpq x hxp hxq + have hsub := E.adjacentSurgeryDrawing_crossings_subset v hvinj hv hdet P Kp Kq hpq hm hadj hcross hemb + have hfinite := (E.assembledAdmissible v hvinj hv hdet).crossings_finite + have hremoved := adjacentSurgeryDrawing_avoids_crossing Kp Kq hm hpq hadj hv hemb x hxp hxq (by + intro e hep heq hx + exact Set.disjoint_left.mp (E.assembled_other_edge_avoids_crossingDisk v hv p q hpq hm e hep heq) + hx (C.reconnection_avoids_chord_meeting p q hpq x hxp hxq).1) + have hnot : x ∉ Paper170.crossingPoints (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) := by + rintro ⟨e,f,hef,hxe,hxf⟩ + exact hremoved e (edgeInterior_subset_range _ e hxe) + refine ⟨hfinite.subset hsub,Set.ncard_lt_ncard ⟨hsub,?_⟩ hfinite⟩ + intro hrev + exact hnot (hrev (E.crossingChord_meeting_is_assembled_crossing v hvinj hv hdet hpq x hxp hxq)) + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! The actual surgery drawing has no triple interior contacts. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +theorem adjacentSurgeryDrawing_no_triples + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hcross : SegmentsCrossProperly (C.portPoint (C.incomingPort p)) (C.portPoint (C.outgoingPort p)) + (C.portPoint (C.incomingPort q)) (C.portPoint (C.outgoingPort q))) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (e f g : Edge) (hef : e ≠ f) (heg : e ≠ g) (hfg : f ≠ g) : + Paper170.edgeInterior (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) e ∩ + Paper170.edgeInterior (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) f ∩ + Paper170.edgeInterior (adjacentSurgeryDrawing Kp Kq hm hadj hv hemb) g = ∅ := by + let B := E.assembledAdmissible v hvinj hv hdet + let A := adjacentSurgeryDrawing Kp Kq hm hadj hv hemb + apply Set.eq_empty_iff_forall_notMem.mpr + intro x hx + obtain ⟨⟨hxe,hxf⟩,hxg⟩ := hx + have havoid : ∀ j, x ≠ B.vertex j := edgeInterior_not_vertex A e x hxe + have hthree (a b c : Edge) (hab : a ≠ b) (hac : a ≠ c) (hbc : b ≠ c) + (ha : x ∈ Set.range (B.edge a)) (hb : x ∈ Set.range (B.edge b)) + (hc : x ∈ Set.range (B.edge c)) : False := by + have hmem : x ∈ Paper170.edgeInterior B.toContinuousDrawing a ∩ Paper170.edgeInterior B.toContinuousDrawing b ∩ + Paper170.edgeInterior B.toContinuousDrawing c := + ⟨⟨edgeInterior_of_range_not_vertices _ a x ha havoid, + edgeInterior_of_range_not_vertices _ b x hb havoid⟩,edgeInterior_of_range_not_vertices _ c x hc havoid⟩ + rw [B.no_triples a b c hab hac hbc] at hmem + exact hmem + have htwo (a : Edge) (hap : a ≠ p.1) (haq : a ≠ q.1) + (hp : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj)) + (hq : x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) + (ha : x ∈ Set.range (B.edge a)) : False := by + have hh := E.adjacentSurgeryRoutes_meeting_each_other v hvinj hv hdet P Kp Kq hpq hm hadj hcross x hp hq + exact hthree p.1 q.1 a (fun he => hpq (C.innerIndex_eq_of_edge_mark p q he hm)) + (Ne.symm hap) (Ne.symm haq) hh.1 hh.2 ha + have hone (a b : Edge) (hab : a ≠ b) + (hap : a ≠ p.1) (haq : a ≠ q.1) (hbp : b ≠ p.1) (hbq : b ≠ q.1) + (hh : x ∈ Set.range (adjacentSurgeryRouteP Kp Kq hm hadj) ∨ + x ∈ Set.range (adjacentSurgeryRouteQ Kp Kq hm hadj)) + (ha : x ∈ Set.range (B.edge a)) (hb : x ∈ Set.range (B.edge b)) : False := by + rcases E.adjacentSurgeryRoutes_meeting_other v hvinj hv hdet P Kp Kq hpq hm hadj a hap haq x hh ha with hp | hq + · exact hthree p.1 a b (Ne.symm hap) (Ne.symm hbp) hab hp ha hb + · exact hthree q.1 a b (Ne.symm haq) (Ne.symm hbq) hab hq ha hb + have hcases (a : Edge) (ha : x ∈ Set.range (A.edge a)) := + B.toContinuousDrawing.replaceTwoRoutes_range_cases p.1 q.1 (adjacentSurgeryRouteP Kp Kq hm hadj) + (adjacentSurgeryRouteQ Kp Kq hm hadj) a x ha + have hec := hcases e (edgeInterior_subset_range A e hxe) + have hfc := hcases f (edgeInterior_subset_range A f hxf) + have hgc := hcases g (edgeInterior_subset_range A g hxg) + rcases hec with ⟨hep,hx⟩ | ⟨heq,hx⟩ | ⟨hep,heq,hx⟩ + · rcases hfc with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · exact hef (hep.trans hfp.symm) + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact heg (hep.trans hgp.symm) + · exact hfg (hfq.trans hgq.symm) + · exact htwo g hgp hgq hx hy hz + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact heg (hep.trans hgp.symm) + · exact htwo f hfp hfq hx hz hy + · exact hone f g hfg hfp hfq hgp hgq (Or.inl hx) hy hz + · rcases hfc with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact hfg (hfp.trans hgp.symm) + · exact heg (heq.trans hgq.symm) + · exact htwo g hgp hgq hy hx hz + · exact hef (heq.trans hfq.symm) + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact htwo f hfp hfq hz hx hy + · exact heg (heq.trans hgq.symm) + · exact hone f g hfg hfp hfq hgp hgq (Or.inr hx) hy hz + · rcases hfc with ⟨hfp,hy⟩ | ⟨hfq,hy⟩ | ⟨hfp,hfq,hy⟩ + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact hfg (hfp.trans hgp.symm) + · exact htwo e hep heq hy hz hx + · exact hone e g heg hep heq hgp hgq (Or.inl hy) hx hz + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact htwo e hep heq hz hy hx + · exact hfg (hfq.trans hgq.symm) + · exact hone e g heg hep heq hgp hgq (Or.inr hy) hx hz + · rcases hgc with ⟨hgp,hz⟩ | ⟨hgq,hz⟩ | ⟨hgp,hgq,hz⟩ + · exact hone e f hef hep heq hfp hfq (Or.inl hz) hx hy + · exact hone e f hef hep heq hfp hfq (Or.inr hz) hx hy + · exact hthree e f g hef heg hfg hx hy hz + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! The constructed surgery drawing satisfies exactly the proved weaker normalization input. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + (E : PolygonalExterior C) (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (P : ∀ e, PolygonalParametrization ((E.assembledAdmissible v hvinj hv hdet).edge e)) + {p q : C.InnerIndex} + +def adjacentSurgeryFiniteDrawing + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + FiniteIntersectionDrawing graph where + toContinuousDrawing := adjacentSurgeryDrawing Kp Kq hm hadj hv hemb + crossings_finite := (E.adjacentSurgeryDrawing_strict_crossing_ncard v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq).1 + no_triples := E.adjacentSurgeryDrawing_no_triples v hvinj hv hdet P Kp Kq hpq hm hadj + (C.crossingChord_meeting_segmentsCrossProperly p q hpq x hxp hxq) hemb + +theorem adjacentSurgeryFiniteDrawing_count_lt + (Kp : ExteriorCrossingCut C P p) (Kq : ExteriorCrossingCut C P q) + (hpq : p ≠ q) (hm : C.innerMark p=C.innerMark q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (hemb : StraightEdgeEmbedding (crossingSurgeryGraph C P p q) id) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + finiteCrossingCount (E.adjacentSurgeryFiniteDrawing v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq) < + Paper170.crossingCount (E.assembledAdmissible v hvinj hv hdet) := by + rw [finiteCrossingCount_eq_ncard] + have h := (E.adjacentSurgeryDrawing_strict_crossing_ncard v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq).2 + exact h.trans_eq (Set.ncard_eq_toFinset_card _ (E.assembledAdmissible v hvinj hv hdet).crossings_finite) + +end Paper170Geometry.PolygonalExterior + +end +end + +section + +/-! Strict adjacent-crossing improvement with actual admissibility restored by proved normalization. -/ +noncomputable section +open Zarankiewicz +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.PolygonalExterior +variable {D : Paper170.AdmissibleDrawing graph} {C : DrawingPassages D.toFiniteIntersectionDrawing} + +theorem exists_admissible_adjacent_surgery [Fintype Vertex] [Fintype Edge] (E : PolygonalExterior C) + (v : Vertex → Plane) (hvinj : Function.Injective v) + (hv : ∀ j, squaredLength (v j-D.vertex j) < C.radius^2) + (hdet : ∀ j (p q : C.PortsAt (C.vertexMark j)), p ≠ q → + det2 (C.portPoint p.val-v j) (C.portPoint q.val-v j) ≠ 0) + (p q : C.InnerIndex) (hpq : p ≠ q) (hadj : (graph.src p.1)=(graph.src q.1) ∨ (graph.dst p.1)=(graph.dst q.1)) + (x : Plane) (hxp : x ∈ Set.range (C.crossingChord p)) (hxq : x ∈ Set.range (C.crossingChord q)) : + ∃ A : Paper170.AdmissibleDrawing graph, (∀ e, HasFiniteAffineCover (A.edge e)) ∧ + Paper170.crossingCount A < Paper170.crossingCount (E.assembledAdmissible v hvinj hv hdet) := by + have hm := C.chord_meeting_marks_eq p q hxp hxq + have hcross := C.crossingChord_meeting_segmentsCrossProperly p q hpq x hxp hxq + obtain ⟨P,hmark,hport⟩ := E.exists_assembled_port_subdivision v hvinj hv hdet + obtain ⟨Kp⟩ := E.nonempty_exteriorCrossingCut v hvinj hv hdet P hport p + obtain ⟨Kq⟩ := E.nonempty_exteriorCrossingCut v hvinj hv hdet P hport q + have hemb := crossingSurgeryGraph_embedding C P hmark hport p q hm hcross + let B := E.adjacentSurgeryFiniteDrawing v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq + obtain ⟨A,hpoly,hcount⟩ := finite_intersection_normalization B + exact ⟨A,hpoly,hcount.trans_lt + (E.adjacentSurgeryFiniteDrawing_count_lt v hvinj hv hdet P Kp Kq hpq hm hadj hemb x hxp hxq)⟩ + +end Paper170Geometry.PolygonalExterior + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Tensor.lean b/lean/OAI/Combinatorics/CompleteCrossing/Tensor.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ce3e40dab07409d80cc0fa0a85d6b0aa69a9bbe --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Tensor.lean @@ -0,0 +1,602 @@ +import OAI.Combinatorics.CompleteCrossing.AlgebraDefs +import OAI.Combinatorics.CompleteCrossing.CycleSpace +import OAI.Combinatorics.CompleteCrossing.Plane + +namespace OAI + +/-! Geometric crossing tensors, local orders, supports, and bilinear chain pairings. -/ + +section + +/-! Algebraic consequences of the actual signed-intersection definition. -/ +noncomputable section +open Set +open scoped BigOperators Classical + +namespace Paper170 +variable {V E : Type} {G : Graph V E} + +theorem interiorIntersection_swap (N : NormalizedDrawing G) (e f : E) : + interiorIntersection N f e = -interiorIntersection N e f := by + by_cases h : e = f + · subst f + simp [interiorIntersection] + · simp only [interiorIntersection, h, Ne.symm h, ite_false] + rw [Finset.sum_comm] + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro i _ + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro j _ + exact segmentIntersection_swap _ _ _ _ + +theorem spokeComparison_swap {N : NormalizedDrawing G} (O : SpokeOrders N) + (v : V) (e f : E) : spokeComparison O v f e = -spokeComparison O v e f := by + by_cases he : G.src e = v ∨ G.dst e = v + · by_cases hf : G.src f = v ∨ G.dst f = v + · let : LinearOrder (G.IncidentEdge v) := O.order v + rcases lt_trichotomy (⟨e,he⟩ : G.IncidentEdge v) ⟨f,hf⟩ with h | h | h + · simp [spokeComparison, he, hf, h, not_lt.mpr h.le] + · simp [spokeComparison, he, hf, h] + · simp [spokeComparison, he, hf, h, not_lt.mpr h.le] + · simp [spokeComparison, he, hf] + · simp [spokeComparison, he] + +variable [Fintype V] + +theorem cycle_intersection_skew {V E : Type} [Fintype V] [Fintype E] (G : Graph V E) + (N : NormalizedDrawing G) (O : SpokeOrders N) (e f : E) : + cycleIntersection O f e = -cycleIntersection O e f := by + have hs : (∑ v, endpointSign G v f * endpointSign G v e * spokeComparison O v f e) = + -(∑ v, endpointSign G v e * endpointSign G v f * spokeComparison O v e f) := by + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro v _ + rw [spokeComparison_swap] + ring + unfold cycleIntersection + rw [interiorIntersection_swap, hs] + ring + +variable [Fintype E] + +theorem edgePairing_neg_left (J : E → E → ℝ) (z z' : E → ℝ) : + edgePairing J (-z) z' = -edgePairing J z z' := by + simp [edgePairing, Finset.sum_neg_distrib] + +theorem edgePairing_neg_right (J : E → E → ℝ) (z z' : E → ℝ) : + edgePairing J z (-z') = -edgePairing J z z' := by + simp [edgePairing, Finset.sum_neg_distrib] + +theorem edgePairing_swap (J : E → E → ℝ) (hJ : ∀ e f, J f e = -J e f) + (z z' : E → ℝ) : edgePairing J z' z = -edgePairing J z z' := by + unfold edgePairing + rw [Finset.sum_comm, ← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro e _ + rw [← Finset.sum_neg_distrib] + apply Finset.sum_congr rfl + intro f _ + rw [hJ] + ring + +theorem completeEdgeVector_self {n : ℕ} (i : Fin n) : completeEdgeVector i i = 0 := by + funext e + have h : ¬(e.val.1 = i ∧ e.val.2 = i) := by + rintro ⟨h1,h2⟩ + exact (ne_of_lt e.property) (h1.trans h2.symm) + simp [completeEdgeVector, h] + +theorem completeEdgeVector_reverse {n : ℕ} (i p : Fin n) : + completeEdgeVector p i = -completeEdgeVector i p := by + funext e + by_cases h : e.val.1 = i ∧ e.val.2 = p + · have hn : ¬(e.val.1 = p ∧ e.val.2 = i) := by + rintro ⟨h1,h2⟩ + exact (ne_of_lt e.property) (h.1.trans h2.symm) + simp only [completeEdgeVector, Pi.neg_apply, ite_eq_left h, ite_eq_right hn] + · by_cases hr : e.val.1 = p ∧ e.val.2 = i + · simp only [completeEdgeVector, Pi.neg_apply, ite_eq_right h, ite_eq_left hr, neg_neg] + · simp only [completeEdgeVector, Pi.neg_apply, ite_eq_right h, ite_eq_right hr, neg_zero] + +theorem raw_cycle_symmetries {n : ℕ} (N : NormalizedDrawing (completeGraph n)) + (O : SpokeOrders N) : + (∀ i k q, rawCycleIntersection O i i k q = 0) ∧ + (∀ i p k, rawCycleIntersection O i p k k = 0) ∧ + (∀ i p k q, rawCycleIntersection O p i k q = -rawCycleIntersection O i p k q) ∧ + (∀ i p k q, rawCycleIntersection O i p q k = -rawCycleIntersection O i p k q) ∧ + (∀ i p k q, rawCycleIntersection O k q i p = -rawCycleIntersection O i p k q) := by + refine ⟨?_,?_,?_,?_,?_⟩ + · intro i k q + simp [rawCycleIntersection, completeEdgeVector_self, edgePairing] + · intro i p k + simp [rawCycleIntersection, completeEdgeVector_self, edgePairing] + · intro i p k q + unfold rawCycleIntersection + rw [completeEdgeVector_reverse i p, edgePairing_neg_left] + · intro i p k q + unfold rawCycleIntersection + rw [completeEdgeVector_reverse k q, edgePairing_neg_right] + · intro i p k q + exact edgePairing_swap _ (cycle_intersection_skew _ N O) _ _ + +end Paper170 + +end +end + +section + +/-! Every nonzero independent-edge coefficient is witnessed by an actual crossing point. -/ +noncomputable section +open Set +open scoped BigOperators Classical +namespace Paper170 + +theorem completeEdgeVector_endpoints {n : ℕ} (e : CompleteEdge n) : + completeEdgeVector e.val.1 e.val.2 = Pi.single e 1 := by + funext f + by_cases h : f = e + · subst f + simp only [completeEdgeVector, and_self, ite_true, Pi.single_eq_same] + · have hne : ¬(f.val.1 = e.val.1 ∧ f.val.2 = e.val.2) := by + rintro ⟨h1,h2⟩ + exact h (Subtype.ext (Prod.ext h1 h2)) + have hrev : ¬(f.val.1 = e.val.2 ∧ f.val.2 = e.val.1) := by + rintro ⟨h1,h2⟩ + have hf := f.property + rw [h1,h2] at hf + exact lt_asymm e.property hf + simp only [completeEdgeVector, ite_eq_right hne, ite_eq_right hrev, Pi.single_eq_of_ne h] + +theorem rawCycleIntersection_endpoints {n : ℕ} {N : NormalizedDrawing (completeGraph n)} + (O : SpokeOrders N) (e f : CompleteEdge n) : + rawCycleIntersection O e.val.1 e.val.2 f.val.1 f.val.2 = cycleIntersection O e f := by + rw [rawCycleIntersection, completeEdgeVector_endpoints, completeEdgeVector_endpoints] + simp [edgePairing, Pi.single_apply, ite_mul, mul_ite] + +theorem independent_cycleIntersection {n : ℕ} {N : NormalizedDrawing (completeGraph n)} + (O : SpokeOrders N) (e f : CompleteEdge n) + (h11 : e.val.1 ≠ f.val.1) (h12 : e.val.1 ≠ f.val.2) + (h21 : e.val.2 ≠ f.val.1) (h22 : e.val.2 ≠ f.val.2) : + cycleIntersection O e f = interiorIntersection N e f := by + have hs : (∑ v, endpointSign (completeGraph n) v e * + endpointSign (completeGraph n) v f * spokeComparison O v e f) = 0 := by + apply Finset.sum_eq_zero + intro v _ + by_cases he1 : e.val.1 = v + · have hf1 : f.val.1 ≠ v := fun h => h11 (he1.trans h.symm) + have hf2 : f.val.2 ≠ v := fun h => h12 (he1.trans h.symm) + simp [endpointSign, completeGraph, hf1, hf2] + · by_cases he2 : e.val.2 = v + · have hf1 : f.val.1 ≠ v := fun h => h21 (he2.trans h.symm) + have hf2 : f.val.2 ≠ v := fun h => h22 (he2.trans h.symm) + simp [endpointSign, completeGraph, hf1, hf2] + · simp [endpointSign, completeGraph, he1, he2] + simp [cycleIntersection, hs] + +theorem interiorIntersection_ne_zero_crossing {V E : Type} {G : Graph V E} + (N : NormalizedDrawing G) (e f : E) (h : interiorIntersection N e f ≠ 0) : + (Paper170Geometry.pairCrossings N.toAdmissibleDrawing e f).Nonempty := by + have hef : e ≠ f := by + intro he + subst f + exact h (by simp [interiorIntersection]) + rw [interiorIntersection, ite_eq_right hef] at h + obtain ⟨i,hi,hi'⟩ := Finset.exists_ne_zero_of_sum_ne_zero h + obtain ⟨j,hj,hij⟩ := Finset.exists_ne_zero_of_sum_ne_zero hi' + have hc : ∃ s ∈ Ioo (0 : ℝ) 1, ∃ t ∈ Ioo (0 : ℝ) 1, + segmentPoint ((N.polygonal e).vertices i) ((N.polygonal e).vertices (i+1)) s = + segmentPoint ((N.polygonal f).vertices j) ((N.polygonal f).vertices (j+1)) t := by + by_contra hn + exact hij (by unfold segmentIntersection; rw [ite_eq_right hn]) + obtain ⟨s,hs,t,ht,hst⟩ := hc + let x := segmentPoint ((N.polygonal e).vertices i) ((N.polygonal e).vertices (i+1)) s + have he : x ∈ edgeInterior N.toContinuousDrawing e := + (N.polygonal e).segment_mem_interior N.toContinuousDrawing e ⟨i,Finset.mem_range.mp hi⟩ s hs + have hf : x ∈ edgeInterior N.toContinuousDrawing f := by + rw [show x = _ from hst] + exact (N.polygonal f).segment_mem_interior N.toContinuousDrawing f + ⟨j,Finset.mem_range.mp hj⟩ t ht + refine ⟨x, Finset.mem_filter.mpr ⟨?_,hef,he,hf⟩⟩ + exact N.crossings_finite.mem_toFinset.mpr ⟨e,f,hef,he,hf⟩ + +theorem signed_support_bound {n : ℕ} (N : NormalizedDrawing (completeGraph n)) + (O : SpokeOrders N) : + (supportedPairs (rawCycleIntersection O)).card ≤ 2 * crossingCount N.toAdmissibleDrawing := by + let W := ↥(supportedPairs (rawCycleIntersection O)) + let e : W → CompleteEdge n := fun w => ⟨w.val.1,(Finset.mem_filter.mp w.property).2.1⟩ + let f : W → CompleteEdge n := fun w => ⟨w.val.2,(Finset.mem_filter.mp w.property).2.2.1⟩ + have hc (w : W) : (Paper170Geometry.pairCrossings N.toAdmissibleDrawing (e w) (f w)).Nonempty := by + obtain ⟨_,_,_,h11,h12,h21,h22,hJ⟩ := Finset.mem_filter.mp w.property + apply interiorIntersection_ne_zero_crossing + have hr := rawCycleIntersection_endpoints O (e w) (f w) + rw [independent_cycleIntersection O (e w) (f w) h11 h12 h21 h22] at hr + exact fun hz => hJ (hr.trans hz) + choose x hx using hc + let φ : W → (Σ a : CompleteEdge n, Σ b : CompleteEdge n, + ↥(Paper170Geometry.pairCrossings N.toAdmissibleDrawing a b)) := + fun w => ⟨e w,f w,⟨x w,hx w⟩⟩ + have hφ : Function.Injective φ := by + intro a b hab + apply Subtype.ext + exact congrArg (fun z => (z.1.val,z.2.1.val)) hab + have hcard := Fintype.card_le_of_injective φ hφ + have hs := Paper170Geometry.sum_pairCrossings_card N.toAdmissibleDrawing + simpa only [W, Fintype.card_coe, Fintype.card_sigma, hs] using hcard + +end Paper170 + +end +end + +section + +/-! The local order in the tensor is the actual order of outward incident edges. -/ +noncomputable section +open Set +open scoped BigOperators Classical +namespace Paper170 +variable {V E : Type} {G : Graph V E} + +theorem Graph.common_endpoint_unique (G : Graph V E) (e f : E) (hef : e ≠ f) + (i v : V) (hei : G.src e = i ∨ G.dst e = i) (hfi : G.src f = i ∨ G.dst f = i) + (hev : G.src e = v ∨ G.dst e = v) (hfv : G.src f = v ∨ G.dst f = v) : v = i := by + by_contra hvi + apply hef + apply G.simple e f + rcases hei with hei | hei <;> rcases hfi with hfi | hfi <;> + rcases hev with hev | hev <;> rcases hfv with hfv | hfv <;> simp_all + +theorem endpointSign_eq_zero (G : Graph V E) (v : V) (e : E) + (h : ¬(G.src e = v ∨ G.dst e = v)) : endpointSign G v e = 0 := by + simp [endpointSign, (not_or.mp h).1, (not_or.mp h).2] + +theorem endpointSign_sq (G : Graph V E) (v : V) (e : E) + (h : G.src e = v ∨ G.dst e = v) : endpointSign G v e ^ 2 = 1 := by + rcases h with h | h + · simp [endpointSign, h] + · by_cases hs : G.src e = v <;> simp [endpointSign, hs, h] + +theorem adjacent_interiorIntersection_eq_zero (N : NormalizedDrawing G) (e f : E) + (hef : e ≠ f) (i : V) (he : G.src e = i ∨ G.dst e = i) + (hf : G.src f = i ∨ G.dst f = i) : interiorIntersection N e f = 0 := by + have hadj : G.src e = G.src f ∨ G.src e = G.dst f ∨ + G.dst e = G.src f ∨ G.dst e = G.dst f := by + rcases he with he | he <;> rcases hf with hf | hf <;> simp_all + by_contra hn + obtain ⟨x,hx⟩ := interiorIntersection_ne_zero_crossing N e f hn + obtain ⟨_,_,hxe,hxf⟩ := Finset.mem_filter.mp hx + exact Set.disjoint_left.mp (N.no_adjacent e f hef hadj) hxe hxf + +theorem cycleIntersection_incident [Fintype V] (N : NormalizedDrawing G) + (O : SpokeOrders N) (e f : E) (hef : e ≠ f) (i : V) + (he : G.src e = i ∨ G.dst e = i) (hf : G.src f = i ∨ G.dst f = i) : + cycleIntersection O e f = (1 / 2 : ℝ) * + (endpointSign G i e * endpointSign G i f * spokeComparison O i e f) := by + have hs : (∑ v, endpointSign G v e * endpointSign G v f * spokeComparison O v e f) = + endpointSign G i e * endpointSign G i f * spokeComparison O i e f := by + apply Finset.sum_eq_single i + · intro v _ hvi + by_cases hev : G.src e = v ∨ G.dst e = v + · by_cases hfv : G.src f = v ∨ G.dst f = v + · exact False.elim (hvi (G.common_endpoint_unique e f hef i v he hf hev hfv)) + · rw [endpointSign_eq_zero G v f hfv] + ring + · rw [endpointSign_eq_zero G v e hev] + ring + · simp + simp only [cycleIntersection, hs, adjacent_interiorIntersection_eq_zero N e f hef i he hf, + zero_add] + +def completeIncidentEdge {n : ℕ} (i : Fin n) (p : {j : Fin n // j ≠ i}) : + (completeGraph n).IncidentEdge i := + if h : i < p.val then ⟨⟨(i,p.val),h⟩,Or.inl rfl⟩ + else ⟨⟨(p.val,i),lt_of_le_of_ne (le_of_not_gt h) p.property⟩,Or.inr rfl⟩ + +theorem completeIncidentEdge_neighbor {n : ℕ} (i : Fin n) (p : {j : Fin n // j ≠ i}) : + (if (completeIncidentEdge i p).val.val.1 = i then + (completeIncidentEdge i p).val.val.2 else (completeIncidentEdge i p).val.val.1) = p.val := by + by_cases h : i < p.val <;> simp [completeIncidentEdge, h, p.property] + +theorem completeIncidentEdge_injective {n : ℕ} (i : Fin n) : + Function.Injective (completeIncidentEdge i) := by + intro p q hpq + apply Subtype.ext + have h := congrArg (fun e : (completeGraph n).IncidentEdge i => + if e.val.val.1 = i then e.val.val.2 else e.val.val.1) hpq + simpa only [completeIncidentEdge_neighbor] using h + +theorem completeEdgeVector_incident {n : ℕ} (i : Fin n) (p : {j : Fin n // j ≠ i}) : + completeEdgeVector i p.val = + endpointSign (completeGraph n) i (completeIncidentEdge i p).val • + Pi.single (completeIncidentEdge i p).val 1 := by + by_cases h : i < p.val + · simpa [completeIncidentEdge, h, endpointSign, completeGraph] using + completeEdgeVector_endpoints (⟨(i,p.val),h⟩ : CompleteEdge n) + · have hp : p.val < i := lt_of_le_of_ne (le_of_not_gt h) p.property + have he := completeEdgeVector_reverse p.val i + rw [show completeEdgeVector p.val i = Pi.single (⟨(p.val,i),hp⟩ : CompleteEdge n) 1 from + completeEdgeVector_endpoints ⟨(p.val,i),hp⟩] at he + simpa [completeIncidentEdge, h, endpointSign, completeGraph, p.property] using he + +theorem edgePairing_smul_smul [Fintype E] (J : E → E → ℝ) (a b : ℝ) (z z' : E → ℝ) : + edgePairing J (a • z) (b • z') = (a*b) * edgePairing J z z' := by + simp only [edgePairing, Pi.smul_apply, smul_eq_mul, Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + apply Finset.sum_congr rfl + intro f _ + ring + +theorem halfOrder_self {ι : Type} (order : LinearOrder ι) (p : ι) : + halfOrder order p p = 0 := by + let _ : LinearOrder ι := order + simp [halfOrder] + +theorem complete_local_orders {n : ℕ} (N : NormalizedDrawing (completeGraph n)) + (O : SpokeOrders N) : + ∃ orders : ∀ i : Fin n, LinearOrder {j : Fin n // j ≠ i}, + ∀ i (p q : {j : Fin n // j ≠ i}), + rawCycleIntersection O i p.val i q.val = halfOrder (orders i) p q := by + let orders (i : Fin n) : LinearOrder {j : Fin n // j ≠ i} := + @LinearOrder.lift' _ _ (O.order i) (completeIncidentEdge i) (completeIncidentEdge_injective i) + refine ⟨orders,?_⟩ + intro i p q + by_cases hpq : p = q + · subst q + have hh := (raw_cycle_symmetries N O).2.2.2.2 i p.val i p.val + have hz : rawCycleIntersection O i p.val i p.val = 0 := by linarith + rw [hz] + exact (halfOrder_self (orders i) p).symm + · let e := completeIncidentEdge i p + let f := completeIncidentEdge i q + have hef : e.val ≠ f.val := fun h => + hpq (completeIncidentEdge_injective i (Subtype.ext h)) + rw [rawCycleIntersection, completeEdgeVector_incident, completeEdgeVector_incident, + edgePairing_smul_smul] + have hsingle : edgePairing (cycleIntersection O) (Pi.single e.val 1) (Pi.single f.val 1) = + cycleIntersection O e.val f.val := by + simp [edgePairing, Pi.single_apply, ite_mul, mul_ite] + change (endpointSign (completeGraph n) i e.val * endpointSign (completeGraph n) i f.val) * + edgePairing (cycleIntersection O) (Pi.single e.val 1) (Pi.single f.val 1) = _ + rw [hsingle, cycleIntersection_incident N O e.val f.val hef i e.property f.property] + calc + _ = (1/2 : ℝ) * (endpointSign (completeGraph n) i e.val ^ 2) * + (endpointSign (completeGraph n) i f.val ^ 2) * spokeComparison O i e.val f.val := by ring + _ = (1/2 : ℝ) * spokeComparison O i e.val f.val := by + rw [endpointSign_sq _ _ _ e.property, endpointSign_sq _ _ _ f.property] + ring + _ = halfOrder (orders i) p q := by + unfold spokeComparison + rw [dite_eq_left e.property, dite_eq_left f.property] + change (1/2 : ℝ) * + (if @LT.lt _ (O.order i).toLT e f then 1 + else if @LT.lt _ (O.order i).toLT f e then -1 else 0) = + (if @LT.lt _ (O.order i).toLT e f then 1/2 + else if @LT.lt _ (O.order i).toLT f e then -(1/2) else 0) + split_ifs <;> ring + +end Paper170 + +end +end + +section + +/-! The directed complete-graph chains and the chosen unoriented edge representatives agree. -/ +noncomputable section +open scoped BigOperators Classical +namespace Paper170 +variable {V E A : Type} [Fintype E] [Fintype A] + +theorem boundary_sum (G : Graph V E) (w : A → E → ℝ) (v : V) : + boundary G (fun e => ∑ a, w a e) v = ∑ a, boundary G (w a) v := by + simp only [boundary,Finset.sum_mul] + exact Finset.sum_comm + +theorem boundary_mul (G : Graph V E) (c : ℝ) (w : E → ℝ) (v : V) : + boundary G (fun e => c*w e) v = c*boundary G w v := by + simp only [boundary,Finset.mul_sum,mul_assoc] + +theorem edgePairing_sum_left (J : E → E → ℝ) (w : A → E → ℝ) (z : E → ℝ) : + edgePairing J (fun e => ∑ a, w a e) z = ∑ a, edgePairing J (w a) z := by + simp only [edgePairing,Finset.sum_mul] + simp_rw [Finset.sum_comm (f := fun f a => w a _ * z f * J _ f)] + exact Finset.sum_comm + +theorem edgePairing_sum_right (J : E → E → ℝ) (z : E → ℝ) (w : A → E → ℝ) : + edgePairing J z (fun e => ∑ a, w a e) = ∑ a, edgePairing J z (w a) := by + simp only [edgePairing,Finset.mul_sum,Finset.sum_mul] + simp_rw [Finset.sum_comm (f := fun f a => z _ * w a f * J _ f)] + exact Finset.sum_comm + +theorem edgePairing_mul_left (J : E → E → ℝ) (c : ℝ) (z w : E → ℝ) : + edgePairing J (fun e => c*z e) w = c*edgePairing J z w := by + simp only [edgePairing,Finset.mul_sum,mul_assoc] + +theorem edgePairing_mul_right (J : E → E → ℝ) (c : ℝ) (z w : E → ℝ) : + edgePairing J z (fun e => c*w e) = c*edgePairing J z w := by + simp only [edgePairing,Finset.mul_sum] + apply Finset.sum_congr rfl + intro e _ + apply Finset.sum_congr rfl + intro f _ + ring + +omit [Fintype E] [Fintype A] in +theorem boundary_completeEdgeVector {n : ℕ} (i p v : Fin n) : + boundary (completeGraph n) (completeEdgeVector i p) v = + (if p=v then 1 else 0) - (if i=v then 1 else 0) := by + rcases lt_trichotomy i p with hip | rfl | hpi + · let e : CompleteEdge n := ⟨(i,p),hip⟩ + have hs := completeEdgeVector_endpoints e + change completeEdgeVector i p = Pi.single e 1 at hs + rw [hs] + simp [boundary,Pi.single_apply,completeGraph,e] + exact congrArg₂ (fun x y : ℝ => x-y) + (ite_cond_congr rfl) (ite_cond_congr rfl) + · rw [completeEdgeVector_self] + simp [boundary] + · let e : CompleteEdge n := ⟨(p,i),hpi⟩ + have hs := completeEdgeVector_endpoints e + change completeEdgeVector p i = Pi.single e 1 at hs + rw [completeEdgeVector_reverse,hs] + simp [boundary,Pi.single_apply,completeGraph,e] + exact congrArg₂ (fun x y : ℝ => x-y) + (ite_cond_congr rfl) (ite_cond_congr rfl) + +def liftedChain {n : ℕ} (z : Fin n → Fin n → ℝ) : CompleteEdge n → ℝ := + fun e => ∑ i, ∑ p, z i p * completeEdgeVector i p e + +omit [Fintype E] [Fintype A] in +theorem boundary_liftedChain {n : ℕ} (z : Fin n → Fin n → ℝ) (v : Fin n) : + boundary (completeGraph n) (liftedChain z) v = chainBoundary z v := by + unfold liftedChain + rw [boundary_sum] + simp_rw [boundary_sum,boundary_mul,boundary_completeEdgeVector,mul_sub] + simp [chainBoundary,Finset.sum_sub_distrib] + +omit [Fintype E] [Fintype A] in +theorem chainPairing_rawCycleIntersection {n : ℕ} {N : NormalizedDrawing (completeGraph n)} + (O : SpokeOrders N) (z z' : Fin n → Fin n → ℝ) : + chainPairing (rawCycleIntersection O) z z' = + edgePairing (cycleIntersection O) (liftedChain z) (liftedChain z') := by + unfold liftedChain + simp_rw [edgePairing_sum_left,edgePairing_sum_right,edgePairing_mul_left,edgePairing_mul_right] + unfold chainPairing rawCycleIntersection + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro p _ + apply Finset.sum_congr rfl + intro k _ + apply Finset.sum_congr rfl + intro q _ + ring + +end Paper170 + +end +end + +section + +/-! A bilinear edge pairing is determined on real cycles by oriented simple cycles. -/ +noncomputable section +open scoped BigOperators +namespace Paper170 +variable {V E : Type} [Fintype E] + +theorem edgePairing_add_left (J : E → E → ℝ) (x y z : E → ℝ) : + edgePairing J (x+y) z = edgePairing J x z + edgePairing J y z := by + simp [edgePairing,add_mul,Finset.sum_add_distrib] + +theorem edgePairing_add_right (J : E → E → ℝ) (x y z : E → ℝ) : + edgePairing J x (y+z) = edgePairing J x y + edgePairing J x z := by + simp [edgePairing,mul_add,add_mul,Finset.sum_add_distrib] + +theorem edgePairing_smul_left (J : E → E → ℝ) (c : ℝ) (x y : E → ℝ) : + edgePairing J (c•x) y = c*edgePairing J x y := + edgePairing_mul_left J c x y + +theorem edgePairing_smul_right (J : E → E → ℝ) (c : ℝ) (x y : E → ℝ) : + edgePairing J x (c•y) = c*edgePairing J x y := + edgePairing_mul_right J c x y + +theorem edgePairing_eq_zero_of_simple_cycles [Fintype V] (G : Graph V E) + (J : E → E → ℝ) + (hcycles : ∀ C C' : SimpleCycle G, edgePairing J C.edgeChain C'.edgeChain = 0) + (z z' : E → ℝ) (hz : ∀ v, boundary G z v = 0) (hz' : ∀ v, boundary G z' v = 0) : + edgePairing J z z' = 0 := by + have hy := (simple_cycles_span G z').mp hz' + have hright (C : SimpleCycle G) : edgePairing J C.edgeChain z' = 0 := by + clear hz' + induction hy using Submodule.span_induction with + | mem y hy => + obtain ⟨C',rfl⟩ := hy + exact hcycles C C' + | zero => simp [edgePairing] + | add x y _ _ hx hy => rw [edgePairing_add_right,hx,hy,add_zero] + | smul c x _ hx => rw [edgePairing_smul_right,hx,mul_zero] + have hx := (simple_cycles_span G z).mp hz + clear hz + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨C,rfl⟩ := hx + exact hright C + | zero => simp [edgePairing] + | add x y _ _ hx hy => rw [edgePairing_add_left,hx,hy,add_zero] + | smul c x _ hx => rw [edgePairing_smul_left,hx,mul_zero] + +end Paper170 + +end +end + +section + +/-! Traversal sums of a simple cycle agree with the frozen edge-chain bilinear pairing. -/ +noncomputable section +open scoped BigOperators Classical +namespace Paper170 +open Paper170Geometry +variable {V E : Type} {G : Graph V E} + +namespace SimpleCycle + +theorem cyclicDart_coe (C : SimpleCycle G) (i : Fin C.length) : C.cyclicDart i = C.dart i := by + exact congrArg C.dart (Fin.ext (Nat.mod_eq_of_lt i.isLt)) + +theorem edgeChain_eq_dart_sum (C : SimpleCycle G) : + C.edgeChain = fun e => ∑ i, dartSign (C.dart i) * (Pi.single (C.edge i) (1 : ℝ) : E → ℝ) e := by + funext e + unfold edgeChain + apply Finset.sum_congr rfl + intro i _ + by_cases h : C.edge i = e + · subst e + simp [dart_sign] + · simp [h] + +end SimpleCycle + +variable [Fintype E] + +theorem edgePairing_single_single (J : E → E → ℝ) (e f : E) (a b : ℝ) : + edgePairing J (Pi.single e a) (Pi.single f b) = a*b*J e f := by + simp [edgePairing,Pi.single_apply] + +theorem edgePairing_simple_cycles (J : E → E → ℝ) (C C' : SimpleCycle G) : + edgePairing J C.edgeChain C'.edgeChain = + ∑ i, ∑ j, dartSign (C.dart i) * dartSign (C'.dart j) * J (C.edge i) (C'.edge j) := by + rw [C.edgeChain_eq_dart_sum,C'.edgeChain_eq_dart_sum] + simp_rw [edgePairing_sum_left,edgePairing_sum_right,edgePairing_mul_left, + edgePairing_mul_right,edgePairing_single_single] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + ring + +theorem edgePairing_simple_cycles_range (J : E → E → ℝ) (C C' : SimpleCycle G) : + edgePairing J C.edgeChain C'.edgeChain = + ∑ i ∈ Finset.range C.length, ∑ j ∈ Finset.range C'.length, + dartSign (C.cyclicDart i) * dartSign (C'.cyclicDart j) * + J (C.cyclicDart i).edge (C'.cyclicDart j).edge := by + rw [edgePairing_simple_cycles] + rw [← Fin.sum_univ_eq_sum_range] + apply Finset.sum_congr rfl + intro i _ + rw [← Fin.sum_univ_eq_sum_range] + apply Finset.sum_congr rfl + intro j _ + simp only [SimpleCycle.cyclicDart_coe,SimpleCycle.dart_edge] + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Tracks.lean b/lean/OAI/Combinatorics/CompleteCrossing/Tracks.lean new file mode 100644 index 0000000000000000000000000000000000000000..97ea2a7d0eba2c5d7134da87f70185e8926d3939 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Tracks.lean @@ -0,0 +1,609 @@ +import OAI.Combinatorics.CompleteCrossing.Truncation +import OAI.Combinatorics.Crossing.CircleOffsetLine +import OAI.Combinatorics.Crossing.FiniteMovingPoints +import OAI.Combinatorics.Crossing.PolygonalWalks +import OAI.Combinatorics.Crossing.TangentTrackIdentity + +namespace OAI + +/-! Truncated spoke coordinates, endpoint connections, and stable signed track intersections. -/ + +section + +/-! Fixed graph-edge directions at both endpoint circles, including the incoming right-vertex direction. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry + +def drawingSpokeDirection (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (j : Vertex) (e : IncidentEdges graph j) : Plane := + if j=(graph.src e.val) then trackDirection (P e.val).vertices 0 + else trackDirection (P e.val).vertices ((P e.val).pieces-1) + +theorem drawingSpokeDirection_ne_zero (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (j : Vertex) (e : IncidentEdges graph j) : drawingSpokeDirection D P j e ≠ 0 := by + have hp := drawing_chain_pieces_pos D e.val (P e.val) + unfold drawingSpokeDirection + split_ifs + · exact (P e.val).minimum_piece_ne_zero (hmin e.val) 0 hp + · exact (P e.val).minimum_piece_ne_zero (hmin e.val) ((P e.val).pieces-1) (by omega) + +theorem drawingSpokeDirection_port_parallel (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (r : ℝ) (j : Vertex) (e : IncidentEdges graph j) + (hpos : 0 < (P e.val).pieces) : + det2 (drawingSpokeDirection D P j e) (drawingSpokePort D P r j e-D.vertex j)=0 := by + unfold drawingSpokeDirection drawingSpokePort + split_ifs with h + · have hc : D.vertex j=(P e.val).vertices 0 := (congrArg D.vertex h).trans (P e.val).first.symm + rw [hc] + change det2 ((P e.val).vertices 1-(P e.val).vertices 0) + (radialPort ((P e.val).vertices 0) ((P e.val).vertices 1) r-(P e.val).vertices 0)=0 + rw [radialPort_sub,det2_smul_right,det2_self,mul_zero] + · have he := e.property.resolve_left h + have hc : D.vertex j=(P e.val).vertices (P e.val).pieces := + (congrArg D.vertex he).trans (P e.val).last.symm + rw [hc] + simp only [trackDirection,PolygonalChain.endPort, + show (P e.val).pieces-1+1=(P e.val).pieces by omega,radialPort_sub,det2_smul_right] + have hn : (P e.val).vertices ((P e.val).pieces-1)-(P e.val).vertices (P e.val).pieces = + -((P e.val).vertices (P e.val).pieces-(P e.val).vertices ((P e.val).pieces-1)) := by abel + rw [hn,det2_neg_right,det2_self,neg_zero,mul_zero] + +theorem drawingSpokeScale_ne_zero (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) (j : Vertex) (e : IncidentEdges graph j) : + circleTrackScale (drawingSpokeDirection D P j e) (drawingSpokePort D P r j e-D.vertex j) ≠ 0 := by + have hw : drawingSpokePort D P r j e-D.vertex j ≠ 0 := by + intro hh + have hc := drawingSpokePort_circle D P hmin r j e + rw [hh] at hc + have hz : squaredLength (0 : Plane)=0 := by simp [squaredLength] + rw [hz] at hc + nlinarith + exact circleTrackScale_ne_zero _ _ (drawingSpokeDirection_ne_zero D P hmin j e) hw + (drawingSpokeDirection_port_parallel D P r j e (drawing_chain_pieces_pos D e.val (P e.val))) + +end Paper170Geometry + +end +end + +section + +/-! The actual endpoint directions of truncated tracks, with their common fixed edge orientation. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +def spokePort (j : Vertex) (e : IncidentEdges graph j) : Plane := + drawingSpokePort D V.chain V.radius j e + +def spokeIndex (j : Vertex) (e : IncidentEdges graph j) : ℕ := + if j=(graph.src e.val) then 0 else V.pieces e.val-1 + +def spokeDirection (j : Vertex) (e : IncidentEdges graph j) : Plane := + trackDirection (V.vertices e.val) (V.spokeIndex j e) + +theorem spokeIndex_lt (j : Vertex) (e : IncidentEdges graph j) : + V.spokeIndex j e < V.pieces e.val := by + have hp := V.pieces_pos e.val + unfold spokeIndex + split_ifs <;> omega + +theorem spokeDirection_ne_zero (j : Vertex) (e : IncidentEdges graph j) : + V.spokeDirection j e ≠ 0 := V.direction_ne_zero e.val _ (V.spokeIndex_lt j e) + +theorem spokeDirection_eq_scale (j : Vertex) (e : IncidentEdges graph j) : + V.spokeDirection j e = + (V.chain e.val).truncatedScale V.radius (V.spokeIndex j e) • + drawingSpokeDirection D V.chain j e := by + change trackDirection ((V.chain e.val).truncatedVertices V.radius) (V.spokeIndex j e)=_ + rw [(V.chain e.val).truncated_direction V.radius _ (V.spokeIndex_lt j e)] + congr 1 + unfold spokeIndex drawingSpokeDirection + split_ifs <;> rfl + +theorem spokePort_circle (j : Vertex) (e : IncidentEdges graph j) : + squaredLength (V.spokePort j e-D.vertex j)=V.radius^2 := + drawingSpokePort_circle D V.chain V.minimal V.radius j e + +theorem spokePort_ne_center (j : Vertex) (e : IncidentEdges graph j) : + V.spokePort j e-D.vertex j ≠ 0 := by + intro h + have hc := V.spokePort_circle j e + rw [h] at hc + have hz : squaredLength (0 : Plane)=0 := by simp [squaredLength] + rw [hz] at hc + nlinarith [V.radius_pos] + +theorem spokeDirection_parallel (j : Vertex) (e : IncidentEdges graph j) : + det2 (V.spokeDirection j e) (V.spokePort j e-D.vertex j)=0 := by + rw [V.spokeDirection_eq_scale,det2_smul_left] + have hp := drawingSpokeDirection_port_parallel D V.chain V.radius j e (V.pieces_pos e.val) + change det2 (drawingSpokeDirection D V.chain j e) (V.spokePort j e-D.vertex j)=0 at hp + rw [hp,mul_zero] + +def spokeScale (j : Vertex) (e : IncidentEdges graph j) : ℝ := + circleTrackScale (V.spokeDirection j e) (V.spokePort j e-D.vertex j) + +theorem spokeScale_ne_zero (j : Vertex) (e : IncidentEdges graph j) : + V.spokeScale j e ≠ 0 := + circleTrackScale_ne_zero _ _ (V.spokeDirection_ne_zero j e) + (V.spokePort_ne_center j e) (V.spokeDirection_parallel j e) + +theorem spokePort_injective {A : Paper170.AdmissibleDrawing graph} + (V : VertexTruncation A.toContinuousDrawing) (hnorm : NoAdjacentCrossings A) + (j : Vertex) : Function.Injective (V.spokePort j) := + drawingSpokePort_injective A hnorm V.chain V.minimal V.radius V.radius_pos V.weak_short j + +end Paper170Geometry.VertexTruncation + +end +end + +section + +/-! One perturbation radius preserves every actual distinct-edge segment crossing and its sign. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.VertexTruncation +variable {D : Paper170.AdmissibleDrawing graph} + +theorem exists_distinct_edge_shift_radius [Fintype Vertex] [Fintype Edge] (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, |t| < δ → ∀ e f : Edge, e ≠ f → + ∀ i : Fin (V.pieces e), ∀ j : Fin (V.pieces f), + SegmentPairTransverse (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices f) (V.pieces f) t j.val) + (shiftedTrack (V.vertices f) (V.pieces f) t (j.val+1)) ∧ + segmentCrossingSign (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices f) (V.pieces f) t j.val) + (shiftedTrack (V.vertices f) (V.pieces f) t (j.val+1)) = + segmentCrossingSign (V.vertices e i.val) (V.vertices e (i.val+1)) + (V.vertices f j.val) (V.vertices f (j.val+1)) := by + classical + let Pair := Σ e : Edge, Σ f : {f : Edge // e ≠ f}, + Fin (V.pieces e) × Fin (V.pieces f.val) + let a : Pair → Plane := fun k => V.vertices k.1 k.2.2.1.val + let b : Pair → Plane := fun k => V.vertices k.1 (k.2.2.1.val+1) + let c : Pair → Plane := fun k => V.vertices k.2.1.val k.2.2.2.val + let d : Pair → Plane := fun k => V.vertices k.2.1.val (k.2.2.2.val+1) + let qc : Pair → Plane := fun k => trackOffset (V.vertices k.2.1.val) (V.pieces k.2.1.val) k.2.2.2.val + let qd : Pair → Plane := fun k => trackOffset (V.vertices k.2.1.val) (V.pieces k.2.1.val) (k.2.2.2.val+1) + have hh (k : Pair) : SegmentPairTransverse (a k) (b k) (c k) (d k) := + V.pair_transverse hnorm hstraight htrans k.1 k.2.1.val k.2.1.property k.2.2.1 k.2.2.2 + obtain ⟨δ,hδ,hstable⟩ := exists_shifted_segment_pairs_radius a b c d qc qd hh + refine ⟨δ,hδ,?_⟩ + intro t ht e f hef i j + exact hstable t ht ⟨e,⟨f,hef⟩,i,j⟩ + +end Paper170Geometry.VertexTruncation + +end +end + +section + +/-! One actual oriented circle chart at each vertex, chosen before any cycle or pair of chords. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry +variable {D : Paper170.ContinuousDrawing graph} + +structure TruncatedSpokeCoordinates (V : VertexTruncation D) where + frame : Vertex → Plane + frame_ne_zero : ∀ j, frame j ≠ 0 + frame_length : ∀ j, squaredLength (frame j)=V.radius^2 + node : ∀ j, IncidentEdges graph j → ℝ + node_injective : ∀ j, Function.Injective (node j) + point_eq : ∀ j e, similarityPoint (D.vertex j) (frame j) (circlePoint (node j e))=V.spokePort j e + +theorem nonempty_truncatedSpokeCoordinates [Fintype Edge] {A : Paper170.AdmissibleDrawing graph} + (V : VertexTruncation A.toContinuousDrawing) (hnorm : NoAdjacentCrossings A) : + Nonempty (TruncatedSpokeCoordinates V) := by + have hex (j : Vertex) := exists_finite_circle_coordinates + (A.vertex j) V.radius V.radius_pos (V.spokePort j) + (V.spokePort_injective hnorm j) (V.spokePort_circle j) + choose u hu hlen node hnode hpoint using hex + exact ⟨⟨u,hu,hlen,node,hnode,hpoint⟩⟩ + +namespace TruncatedSpokeCoordinates +variable {V : VertexTruncation D} (C : TruncatedSpokeCoordinates V) + +def shiftedPort (j : Vertex) (e : IncidentEdges graph j) (ε : ℝ) : Plane := + similarityPoint (D.vertex j) (C.frame j) + (circleOffset (circlePoint (C.node j e)) (V.spokeScale j e*ε)) + +def tangentPort (_C : TruncatedSpokeCoordinates V) (j : Vertex) (e : IncidentEdges graph j) (ε : ℝ) : Plane := + V.spokePort j e+ε • normalShift (V.spokeDirection j e) + +theorem tangentPort_eq (j : Vertex) (e : IncidentEdges graph j) (ε : ℝ) : + C.tangentPort j e ε = similarityPoint (D.vertex j) (C.frame j) + (circleTangentOffset (circlePoint (C.node j e)) (V.spokeScale j e*ε)) := by + have hh := tangentOffset_eq_normalShift (D.vertex j) (C.frame j) (circlePoint (C.node j e)) + (V.spokeDirection j e) (V.spokeDirection_ne_zero j e) + (by simpa only [C.point_eq] using V.spokePort_ne_center j e) + (by simpa only [C.point_eq] using V.spokeDirection_parallel j e) ε + simpa only [C.point_eq,VertexTruncation.spokeScale,tangentPort] using hh.symm + +theorem shiftedPort_level (j : Vertex) (e : IncidentEdges graph j) (ε : ℝ) : + det2 (V.spokeDirection j e) (C.shiftedPort j e ε-V.spokePort j e)=ε := by + have hh := circleOffset_track_level (D.vertex j) (C.frame j) (circlePoint (C.node j e)) + (V.spokeDirection j e) (V.spokeDirection_ne_zero j e) + (by simpa only [C.point_eq] using V.spokePort_ne_center j e) + (by simpa only [C.point_eq] using V.spokeDirection_parallel j e) ε + simpa only [C.point_eq,VertexTruncation.spokeScale,shiftedPort] using hh + +theorem shiftedPort_circle (j : Vertex) (e : IncidentEdges graph j) (ε : ℝ) + (hε : |V.spokeScale j e*ε| ≤ 1) : + squaredLength (C.shiftedPort j e ε-D.vertex j)=V.radius^2 := by + unfold shiftedPort + rw [similarityPoint_squaredLength,circleOffset_on_circle _ (circlePoint_on_unit_circle _) _ hε, + mul_one,C.frame_length] + +theorem connector_strictly_outside (j : Vertex) (e : IncidentEdges graph j) (ε : ℝ) + (hε : |V.spokeScale j e*ε| < 1) (hne : ε ≠ 0) (t : ℝ) (ht : 0 hpos e) + refine ⟨min δ₀ δ₁,lt_min hδ₀ hδ₁,?_⟩ + intro t ht hsmall e f i j + by_cases hef : e=f + · subst f + have hno := hself e t ht ((hsmall.trans_le (min_le_right _ _)).trans (hbound e (Finset.mem_univ _))) i j + refine ⟨?_,?_⟩ + · intro s hs u hu he + exact False.elim (hno ⟨s,hs,u,hu,he⟩) + · have hp : ¬ SegmentsCrossProperly (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices e) (V.pieces e) t j.val) + (shiftedTrack (V.vertices e) (V.pieces e) t (j.val+1)) := + fun h => hno (closedSegmentsMeet_of_proper _ _ _ _ h) + simp [segmentCrossingSign,hp] + · obtain ⟨hT,hS⟩ := hother t (hsmall.trans_le (min_le_left _ _)) e f hef i j + exact ⟨hT,by simpa only [ite_eq_right hef] using hS⟩ + +theorem exists_uniform_track_intersections [Fintype Vertex] [Fintype Edge] (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, t ≠ 0 → |t| < δ → ∀ e f : Edge, + polygonIntersection (V.vertices e) (shiftedTrack (V.vertices f) (V.pieces f) t) (V.pieces e) (V.pieces f) = + if e=f then 0 else polygonIntersection (V.vertices e) (V.vertices f) (V.pieces e) (V.pieces f) := by + classical + obtain ⟨δ,hδ,hh⟩ := V.exists_all_edge_shift_radius hnorm hstraight htrans + refine ⟨δ,hδ,?_⟩ + intro t ht hsmall e f + by_cases hef : e=f + · rw [ite_eq_left hef] + unfold polygonIntersection + apply Finset.sum_eq_zero + intro i hi + apply Finset.sum_eq_zero + intro j hj + simpa only [ite_eq_left hef] using + (hh t ht hsmall e f ⟨i,Finset.mem_range.mp hi⟩ ⟨j,Finset.mem_range.mp hj⟩).2 + · rw [ite_eq_right hef] + unfold polygonIntersection + apply Finset.sum_congr rfl + intro i hi + apply Finset.sum_congr rfl + intro j hj + simpa only [ite_eq_right hef] using + (hh t ht hsmall e f ⟨i,Finset.mem_range.mp hi⟩ ⟨j,Finset.mem_range.mp hj⟩).2 + +end Paper170Geometry.VertexTruncation + +end +end + +section + +/-! The ends of each actual shifted track are precisely the ends of its two circle connectors. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +def leftIncident (_V : VertexTruncation D) (e : Edge) : IncidentEdges graph ((graph.src e)) := ⟨e,Or.inl rfl⟩ +def rightIncident (_V : VertexTruncation D) (e : Edge) : IncidentEdges graph ((graph.dst e)) := ⟨e,Or.inr rfl⟩ + +theorem vertices_first (e : Edge) : V.vertices e 0=V.startPort e := + (V.chain e).truncatedVertices_first V.radius + +theorem vertices_last (e : Edge) : V.vertices e (V.pieces e)=V.endPort e := + (V.chain e).truncatedVertices_last (V.pieces_pos e) V.radius + +theorem spokePort_left (e : Edge) : + V.spokePort ((graph.src e)) (V.leftIncident e)=V.startPort e := by + simp [spokePort,drawingSpokePort,leftIncident,startPort] + +theorem spokePort_right (e : Edge) : + V.spokePort ((graph.dst e)) (V.rightIncident e)=V.endPort e := by + simp [spokePort,drawingSpokePort,rightIncident,endPort,(graph.loopless e).symm] + +theorem shiftedTrack_first (C : TruncatedSpokeCoordinates V) (e : Edge) (ε : ℝ) : + shiftedTrack (V.vertices e) (V.pieces e) ε 0= + C.tangentPort ((graph.src e)) (V.leftIncident e) ε := by + simp [shiftedTrack,trackOffset,TruncatedSpokeCoordinates.tangentPort,spokeDirection, + spokeIndex,leftIncident,V.vertices_first,spokePort,drawingSpokePort,startPort] + +theorem shiftedTrack_last (C : TruncatedSpokeCoordinates V) (e : Edge) (ε : ℝ) : + shiftedTrack (V.vertices e) (V.pieces e) ε (V.pieces e)= + C.tangentPort ((graph.dst e)) (V.rightIncident e) ε := by + have hn : V.pieces e ≠ 0 := ne_of_gt (V.pieces_pos e) + simp [shiftedTrack,trackOffset,hn,TruncatedSpokeCoordinates.tangentPort,spokeDirection, + spokeIndex,rightIncident,V.vertices_last,spokePort,drawingSpokePort,endPort,(graph.loopless e).symm] + +end Paper170Geometry.VertexTruncation + +end +end + +section + +/-! Every original/shifted vertex endpoint is distinct for either sufficiently small nonzero displacement. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem continuous_shiftedPort (j : Vertex) (e : IncidentEdges graph j) : + Continuous (C.shiftedPort j e) := by + change Continuous (fun ε : ℝ => similarityPoint (D.vertex j) (C.frame j) + (circleOffset (circlePoint (C.node j e)) (V.spokeScale j e*ε))) + dsimp [similarityPoint,circleOffset,rotateQuarter] + fun_prop + +theorem shiftedPort_zero (j : Vertex) (e : IncidentEdges graph j) : + C.shiftedPort j e 0=V.spokePort j e := by + simp only [shiftedPort,mul_zero,circleOffset_zero,C.point_eq] + +theorem shiftedPort_ne_original (j : Vertex) (e : IncidentEdges graph j) + (ε : ℝ) (hε : ε ≠ 0) : C.shiftedPort j e ε ≠ V.spokePort j e := by + intro he + have hh := C.shiftedPort_level j e ε + rw [he,sub_self] at hh + have hz : det2 (V.spokeDirection j e) (0 : Plane)=0 := by simp [det2] + rw [hz] at hh + exact hε hh.symm + +theorem exists_endpoint_separation_radius [Fintype Edge] (j : Vertex) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → + (∀ e f : IncidentEdges graph j, V.spokePort j e ≠ C.shiftedPort j f ε) ∧ + Function.Injective (fun e : IncidentEdges graph j => C.shiftedPort j e ε) := by + have hinj : Function.Injective (fun e : IncidentEdges graph j => C.shiftedPort j e 0) := by + intro e f he + have hh : circlePoint (C.node j e)=circlePoint (C.node j f) := by + apply similarityPoint_injective (D.vertex j) (C.frame j) (C.frame_ne_zero j) + simpa only [shiftedPort,mul_zero,circleOffset_zero] using he + exact C.node_injective j (circlePoint_injective hh) + obtain ⟨δ,hδ,hh⟩ := finite_moving_points_separation (C.shiftedPort j) + (C.continuous_shiftedPort j) hinj + refine ⟨δ,hδ,?_⟩ + intro ε hε hsmall + constructor + · intro e f + by_cases hef : e=f + · subst f + exact (C.shiftedPort_ne_original j e ε hε).symm + · simpa only [C.shiftedPort_zero] using (hh ε hsmall e f hef).1 + · intro e f he + by_contra hef + exact (hh ε hsmall e f hef).2 he + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Signed intersections are actual segment-traversal sums; their support is controlled by spatial crossing points. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.VertexTruncation +open scoped BigOperators +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +theorem piece_subset_range (e : Edge) (i : ℕ) (hi : i (graph.src g)) he))) + · have hn : V.pieces e=V.pieces f.val := congrArg V.pieces he + omega + +end Paper170Geometry.VertexTruncation + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Triangle.lean b/lean/OAI/Combinatorics/CompleteCrossing/Triangle.lean new file mode 100644 index 0000000000000000000000000000000000000000..c25654bc489bfa890511ab7b7d4347ff259798b4 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Triangle.lean @@ -0,0 +1,285 @@ +import OAI.Combinatorics.CompleteCrossing.Interpolation +import Mathlib.Data.Finset.Prod +import Mathlib.Data.Set.Finite.Basic +import Mathlib.LinearAlgebra.FiniteDimensional.Lemmas + +namespace OAI + +/-! Even triangular interpolation and unisolvence. -/ + +section + +/-! The even two-triangle set, as actual ordered interpolation coordinates. -/ +noncomputable section +namespace Paper170 + +theorem mem_evenTriangle (s : ℕ) (p q : Fin (2*s)) : + (p,q) ∈ evenTriangle s ↔ + (p.val < s ∧ q < p) ∨ (s ≤ p.val ∧ p < q) := by + simp [evenTriangle] + +def evenTriangleOffDiagEquiv (s : ℕ) : + EvenTriangleCoord s ≃ ↥((Finset.univ : Finset (Fin s)).offDiag) where + toFun pq := by + obtain ⟨⟨p,q⟩, hpq⟩ := pq + have hpq := (mem_evenTriangle s p q).mp hpq + by_cases h : p.val < s + · exact ⟨(⟨p.val, h⟩, ⟨q.val, by rcases hpq with hq | hq <;> omega⟩), by + simp only [Finset.mem_offDiag, Finset.mem_univ, true_and, ne_eq, Fin.mk.injEq] + rcases hpq with hq | hq <;> omega⟩ + · exact ⟨(⟨p.val-s, by omega⟩, ⟨q.val-s, by omega⟩), by + simp only [Finset.mem_offDiag, Finset.mem_univ, true_and, ne_eq, Fin.mk.injEq] + rcases hpq with hq | hq <;> omega⟩ + invFun pq := by + obtain ⟨⟨p,q⟩, hpq⟩ := pq + have hpq : p ≠ q := (Finset.mem_offDiag.mp hpq).2.2 + by_cases h : q < p + · exact ⟨(⟨p.val, by omega⟩, ⟨q.val, by omega⟩), + (mem_evenTriangle s _ _).mpr (Or.inl ⟨p.isLt,h⟩)⟩ + · exact ⟨(⟨p.val+s, by omega⟩, ⟨q.val+s, by omega⟩), + (mem_evenTriangle s _ _).mpr (Or.inr ⟨by change s ≤ p.val+s; omega,by + have hpq := Fin.val_ne_of_ne hpq + change p.val+s < q.val+s + omega⟩)⟩ + left_inv pq := by + obtain ⟨⟨p,q⟩, hpq⟩ := pq + have hpq := (mem_evenTriangle s p q).mp hpq + apply Subtype.ext + dsimp + split_ifs with h h' h' + · rfl + · change ¬q.val < p.val at h' + simp only [Fin.lt_def] at hpq + omega + · change q.val-s < p.val-s at h' + simp only [Fin.lt_def] at hpq + omega + · apply Prod.ext <;> apply Fin.ext <;> dsimp <;> + simp only [Fin.lt_def] at hpq <;> omega + right_inv pq := by + obtain ⟨⟨p,q⟩, hpq⟩ := pq + apply Subtype.ext + dsimp + split_ifs with h h' h' + · rfl + · change ¬p.val < s at h' + omega + · change p.val+s < s at h' + omega + · apply Prod.ext <;> apply Fin.ext <;> dsimp <;> omega + +theorem even_triangle_card (s : ℕ) : (evenTriangle s).card = s*(s-1) := by + have hc := Fintype.card_congr (evenTriangleOffDiagEquiv s) + simp only [EvenTriangleCoord, Fintype.card_coe] at hc + rw [Finset.offDiag_card, Finset.card_univ, Fintype.card_fin] at hc + simpa only [Nat.mul_sub_left_distrib, mul_one] using hc + +end Paper170 + +end +end + +section + +/-! Even-node interpolation by adjoining one fresh node to the checked odd-node theorem. -/ +noncomputable section +open PolynomialModule +open Zarankiewicz +namespace Paper170 + +theorem biBounded_mulRoot {r s : ℕ} {P : BiPoly} (hP : BiBounded r s P) (t : ℝ) : + BiBounded (r+1) s (mulRoot t P) := by + refine ⟨bounded_mulRoot t hP.1, ?_⟩ + intro a + cases a with + | zero => + rw [mulRoot_coeff_zero] + exact (boundedSpace s).smul_mem _ (hP.2 0) + | succ a => + rw [mulRoot_coeff_succ] + exact bounded_sub (hP.2 a) ((boundedSpace s).smul_mem _ (hP.2 (a+1))) + +theorem insertNode_injective {n : ℕ} (r : Fin (n+1)) (node : Fin n → ℝ) + (hn : Function.Injective node) (t : ℝ) (ht : ∀i, node i ≠ t) : + Function.Injective (Fin.insertNth r t node) := by + intro a b + refine Fin.succAboveCases r ?_ (fun a => ?_) a + · refine Fin.succAboveCases r ?_ (fun b => ?_) b + · intro + rfl + · simp only [Fin.insertNth_apply_same, Fin.insertNth_apply_succAbove] + intro h + exact (ht b h.symm).elim + · refine Fin.succAboveCases r ?_ (fun b => ?_) b + · simp only [Fin.insertNth_apply_same, Fin.insertNth_apply_succAbove] + intro h + exact (ht a h).elim + · simp only [Fin.insertNth_apply_succAbove] + intro h + exact congrArg r.succAbove (hn h) + +theorem oddTriangle_unisolvent_fin (s : ℕ) (node : Fin (2*s+1) → ℝ) + (hn : Function.Injective node) (P : BiPoly) (hP : BiBounded s s P) + (hv : ∀a b : Fin (2*s+1), + (b < a ∧ a.val ≤ s) ∨ (s < a.val ∧ a < b) → biEval (node a) (node b) P = 0) : + P = 0 := by + let x : ℕ → ℝ := fun k => if h : 1 ≤ k ∧ k ≤ 2*s+1 then node ⟨k-1,by omega⟩ else 0 + have hx : Set.InjOn x (Set.Icc 1 (2*s+1)) := by + intro a ha b hb he + simp only [Set.mem_Icc] at ha hb + simp only [x, dite_eq_left ha, dite_eq_left hb] at he + have := congrArg Fin.val (hn he) + dsimp at this + omega + apply twoTriangle_unisolvent s x hx P hP + intro a b hab + rw [mem_twoTriangle] at hab + have ha : 1 ≤ a ∧ a ≤ 2*s+1 := by omega + have hb : 1 ≤ b ∧ b ≤ 2*s+1 := by omega + simp only [x, dite_eq_left ha, dite_eq_left hb] + apply hv + change (b-1 < a-1 ∧ a-1 ≤ s) ∨ (s < a-1 ∧ a-1 < b-1) + omega + +theorem evenTriangle_unisolvent_first (s : ℕ) (hs : 2 ≤ s) + (node : Fin (2*s) → ℝ) (hn : Function.Injective node) + (P : BiPoly) (hP : BiBounded s (s-1) P) + (hv : ∀a b, (a,b) ∈ evenTriangle s → biEval (node a) (node b) P = 0) : P = 0 := by + obtain ⟨t,ht⟩ := (Set.finite_range node).exists_notMem + have hnt : ∀i, node i ≠ t := fun i h => ht ⟨i,h⟩ + let x : Fin (2*s+1) → ℝ := Fin.insertNth (0 : Fin (2*s+1)) t node + let Q := swapBi (mulRoot t (swapBi P)) + have hQ : BiBounded s s Q := by + have hb := biBounded_swap (biBounded_mulRoot (biBounded_swap hP) t) + simpa only [Nat.sub_add_cancel (by omega : 1 ≤ s)] using hb + have hev (u v : ℝ) : biEval u v Q = (v-t)*biEval u v P := by + simp only [Q, biEval_swap, biEval_mulRoot] + have hzero : Q = 0 := by + apply oddTriangle_unisolvent_fin s x (insertNode_injective _ node hn t hnt) Q hQ + intro a b + refine Fin.succAboveCases (0 : Fin (2*s+1)) ?_ (fun a => ?_) a + · intro h + have : False := by simp only [Fin.lt_def, Fin.val_zero] at h; omega + exact this.elim + · refine Fin.succAboveCases (0 : Fin (2*s+1)) ?_ (fun b => ?_) b + · intro _ + simp only [hev, x, Fin.insertNth_apply_same, sub_self, zero_mul] + · intro hab + simp only [x, Fin.insertNth_apply_succAbove, hev] + rw [hv a b] + · exact mul_zero _ + · rw [mem_evenTriangle] + simp only [Fin.succAbove_zero, Fin.val_succ, Fin.lt_def] at hab + simp only [Fin.lt_def] + omega + have hroot : mulRoot t (swapBi P) = 0 := by + apply swapBi.injective + simpa only [map_zero] using hzero + have hpzero := eq_zero_of_mulRoot_eq_zero t (s-1) (swapBi P) (biBounded_swap hP).1 hroot + apply swapBi.injective + simpa only [map_zero] using hpzero + +theorem evenTriangle_unisolvent_second (s : ℕ) (hs : 2 ≤ s) + (node : Fin (2*s) → ℝ) (hn : Function.Injective node) + (P : BiPoly) (hP : BiBounded (s-1) s P) + (hv : ∀a b, (a,b) ∈ evenTriangle s → biEval (node a) (node b) P = 0) : P = 0 := by + obtain ⟨t,ht⟩ := (Set.finite_range node).exists_notMem + have hnt : ∀i, node i ≠ t := fun i h => ht ⟨i,h⟩ + let r : Fin (2*s+1) := ⟨s,by omega⟩ + let x : Fin (2*s+1) → ℝ := Fin.insertNth r t node + have hQ : BiBounded s s (mulRoot t P) := by + simpa only [Nat.sub_add_cancel (by omega : 1 ≤ s)] using biBounded_mulRoot hP t + apply eq_zero_of_mulRoot_eq_zero t (s-1) P hP.1 + apply oddTriangle_unisolvent_fin s x (insertNode_injective r node hn t hnt) _ hQ + intro a b + refine Fin.succAboveCases r ?_ (fun a => ?_) a + · intro _ + simp only [biEval_mulRoot, x, Fin.insertNth_apply_same, sub_self, zero_mul] + · refine Fin.succAboveCases r ?_ (fun b => ?_) b + · intro hab + have : False := by + simp only [Fin.lt_def, r] at hab + omega + exact this.elim + · intro hab + simp only [x, Fin.insertNth_apply_succAbove, biEval_mulRoot] + rw [hv a b] + · exact mul_zero _ + · rw [mem_evenTriangle] + simp only [Fin.lt_def, r, Fin.succAbove, Fin.val_castSucc] at hab + simp only [Fin.lt_def] + split_ifs at hab <;> simp only [Fin.val_castSucc, Fin.val_succ] at hab <;> omega + +end Paper170 + +end +end + +section + +/-! Bijective interpolation on both even-node degree rectangles. -/ +noncomputable section +namespace Paper170 + +theorem evenTriangle_vanish_first (s : ℕ) (hs : 2 ≤ s) + (node : Fin (2*s) → ℝ) (hn : Function.Injective node) + (P : Poly2) (hP : P ∈ rectangle (s-1) (s-2)) + (hv : ∀a b, (a,b) ∈ evenTriangle s → evalTwo (node a) (node b) P = 0) : P = 0 := by + apply toBiPolynomial.injective + rw [map_zero] + apply evenTriangle_unisolvent_first s hs node hn (toBiPolynomial P) + · convert toBiPolynomial_bounded (s-1) (s-2) P hP using 1 <;> omega + · intro a b hab + rw [toBiPolynomial_eval] + exact hv a b hab + +theorem evenTriangle_vanish_second (s : ℕ) (hs : 2 ≤ s) + (node : Fin (2*s) → ℝ) (hn : Function.Injective node) + (P : Poly2) (hP : P ∈ rectangle (s-2) (s-1)) + (hv : ∀a b, (a,b) ∈ evenTriangle s → evalTwo (node a) (node b) P = 0) : P = 0 := by + apply toBiPolynomial.injective + rw [map_zero] + apply evenTriangle_unisolvent_second s hs node hn (toBiPolynomial P) + · convert toBiPolynomial_bounded (s-2) (s-1) P hP using 1 <;> omega + · intro a b hab + rw [toBiPolynomial_eval] + exact hv a b hab + +theorem triangleEvaluation_bijective_of_unisolvent (s a b : ℕ) (node : Fin (2*s) → ℝ) + (hdim : (a+1)*(b+1) = s*(s-1)) + (hv : ∀P ∈ rectangle a b, + (∀i j, (i,j) ∈ evenTriangle s → evalTwo (node i) (node j) P = 0) → P=0) : + Function.Bijective (triangleEvaluation s a b node) := by + let := rectangle_finite a b + have hi : Function.Injective (triangleEvaluation s a b node) := by + rw [← LinearMap.ker_eq_bot, LinearMap.ker_eq_bot'] + intro P hP + apply Subtype.ext + apply hv P.val P.property + intro i j hij + exact congrFun hP ⟨(i,j),hij⟩ + refine ⟨hi, (LinearMap.injective_iff_surjective_of_finrank_eq_finrank ?_).mp hi⟩ + rw [rectangle_dimension, Module.finrank_fintype_fun_eq_card] + have hc : Fintype.card (EvenTriangleCoord s) = s*(s-1) := by + rw [Fintype.card_coe, even_triangle_card] + rw [hc,hdim] + +theorem two_triangle_interpolation (s : ℕ) (hs : 2 ≤ s) + (node : Fin (2*s) → ℝ) (hn : Function.Injective node) : + Function.Bijective (triangleEvaluation s (s-1) (s-2) node) ∧ + Function.Bijective (triangleEvaluation s (s-2) (s-1) node) := by + constructor + · apply triangleEvaluation_bijective_of_unisolvent + · congr 1 <;> omega + · exact evenTriangle_vanish_first s hs node hn + · apply triangleEvaluation_bijective_of_unisolvent + · rw [Nat.mul_comm] + congr 1 <;> omega + · exact evenTriangle_vanish_second s hs node hn + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/TriangleFactors.lean b/lean/OAI/Combinatorics/CompleteCrossing/TriangleFactors.lean new file mode 100644 index 0000000000000000000000000000000000000000..29f96ca717f88dcbb67635409dd0112030d3a832 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/TriangleFactors.lean @@ -0,0 +1,395 @@ +import OAI.Combinatorics.CompleteCrossing.Triangle +import Mathlib.Algebra.MvPolynomial.Funext +import Mathlib.Order.Interval.Finset.Fin + +namespace OAI + +/-! Triangular evaluation indices, division, and determinant factorization. -/ + +section + +noncomputable section +open scoped Classical +namespace Paper170 + +def triangleMiddleEmbedding (s : ℕ) (hs : 2≤s) (p : Fin (2*(s-1))) : Fin (2*s) := + ⟨if p.val omega⟩ + +def triangleEndEmbedding (s : ℕ) (hs : 2≤s) (p : Fin (2*(s-1))) : Fin (2*s) := + ⟨p.val+1, by omega⟩ + +theorem triangleMiddleEmbedding_strictMono (s : ℕ) (hs : 2≤s) : + StrictMono (triangleMiddleEmbedding s hs) := by + intro p q hpq + change (if p.val omega + +theorem triangleEndEmbedding_strictMono (s : ℕ) (hs : 2≤s) : + StrictMono (triangleEndEmbedding s hs) := by + intro p q hpq + change p.val+1 omega + +theorem triangleEndEmbedding_avoids (s : ℕ) (hs : 2≤s) (p : Fin (2*(s-1))) : + (triangleEndEmbedding s hs p).val ≠ 0 ∧ + (triangleEndEmbedding s hs p).val ≠ 2*s-1 := by + dsimp [triangleEndEmbedding] + omega + +theorem evenTriangle_delete_middle (s : ℕ) (hs : 2≤s) (p q : Fin (2*(s-1))) : + (triangleMiddleEmbedding s hs p,triangleMiddleEmbedding s hs q)∈evenTriangle s ↔ + (p,q)∈evenTriangle (s-1) := by + simp only [mem_evenTriangle,triangleMiddleEmbedding,Fin.lt_def] + split_ifs <;> omega + +theorem evenTriangle_delete_ends (s : ℕ) (hs : 2≤s) (p q : Fin (2*(s-1))) : + (triangleEndEmbedding s hs p,triangleEndEmbedding s hs q)∈evenTriangle s ↔ + (p,q)∈evenTriangle (s-1) := by + simp only [mem_evenTriangle,triangleEndEmbedding,Fin.lt_def] + omega + +theorem evenTriangle_middle_left_row (s : ℕ) (hs : 2≤s) (q : Fin (2*s)) : + (⟨s-1,by omega⟩,q)∈evenTriangle s ↔ q.val omega + +theorem triangleEndEmbedding_range (s : ℕ) (hs : 2≤s) (i : Fin (2*s)) : + (∃p, triangleEndEmbedding s hs p=i) ↔ i.val≠0 ∧ i.val≠2*s-1 := by + constructor + · rintro ⟨p,rfl⟩ + exact triangleEndEmbedding_avoids s hs p + · intro h + refine ⟨⟨i.val-1,by omega⟩,?_⟩ + apply Fin.ext + dsimp [triangleEndEmbedding] + omega + +theorem evenTriangle_middle_left_card (s : ℕ) (hs : 2≤s) : + (Finset.univ.filter (fun q : Fin (2*s) => (⟨s-1,by omega⟩,q)∈evenTriangle s)).card=s-1 := by + have he : Finset.univ.filter (fun q : Fin (2*s) => (⟨s-1,by omega⟩,q)∈evenTriangle s)= + Finset.Iio (⟨s-1,by omega⟩ : Fin (2*s)) := by + ext q + simp only [Finset.mem_filter,Finset.mem_univ,true_and,Finset.mem_Iio, + evenTriangle_middle_left_row s hs,Fin.lt_def] + rw [he,Fin.card_Iio] + +theorem evenTriangle_middle_right_card (s : ℕ) (hs : 2≤s) : + (Finset.univ.filter (fun q : Fin (2*s) => (⟨s,by omega⟩,q)∈evenTriangle s)).card=s-1 := by + have he : Finset.univ.filter (fun q : Fin (2*s) => (⟨s,by omega⟩,q)∈evenTriangle s)= + Finset.Ioi (⟨s,by omega⟩ : Fin (2*s)) := by + ext q + simp only [Finset.mem_filter,Finset.mem_univ,true_and,Finset.mem_Ioi, + evenTriangle_middle_right_row s hs,Fin.lt_def] + rw [he,Fin.card_Ioi] + dsimp + omega + +theorem evenTriangle_first_column_card (s : ℕ) (hs : 2≤s) : + (Finset.univ.filter (fun p : Fin (2*s) => (p,⟨0,by omega⟩)∈evenTriangle s)).card=s-1 := by + have he : Finset.univ.filter (fun p : Fin (2*s) => (p,⟨0,by omega⟩)∈evenTriangle s)= + Finset.Ioo (⟨0,by omega⟩ : Fin (2*s)) ⟨s,by omega⟩ := by + ext p + simp only [Finset.mem_filter,Finset.mem_univ,true_and,Finset.mem_Ioo, + evenTriangle_first_column s hs,Fin.lt_def] + rw [he,Fin.card_Ioo] + simp + +theorem evenTriangle_last_column_card (s : ℕ) (hs : 2≤s) : + (Finset.univ.filter (fun p : Fin (2*s) => (p,⟨2*s-1,by omega⟩)∈evenTriangle s)).card=s-1 := by + have he : Finset.univ.filter (fun p : Fin (2*s) => (p,⟨2*s-1,by omega⟩)∈evenTriangle s)= + Finset.Ico (⟨s,by omega⟩ : Fin (2*s)) ⟨2*s-1,by omega⟩ := by + ext p + simp only [Finset.mem_filter,Finset.mem_univ,true_and,Finset.mem_Ico, + evenTriangle_last_column s hs,Fin.le_def,Fin.lt_def] + rw [he,Fin.card_Ico] + dsimp + omega + +theorem evenTriangle_two : evenTriangle 2 = {((1 : Fin 4),0),(2,3)} := by + ext ⟨p,q⟩ + fin_cases p <;> fin_cases q <;> decide + +theorem evenTriangle_two_distinct_coordinates (node : Fin 4 → ℝ) + (hn : Function.Injective node) : node 1≠node 2 ∧ node 0≠node 3 := by + constructor <;> exact hn.ne (by decide) + +end Paper170 + +end +end + +section + +/-! The literal row and column elimination used in the even-node proof. -/ +noncomputable section +open PolynomialModule Zarankiewicz +namespace Paper170 + +theorem mem_rectangle_of_toBiPolynomial_bounded (a b : ℕ) (P : Poly2) + (hP : BiBounded (a+1) (b+1) (toBiPolynomial P)) : P∈rectangle a b := by + rw [rectangle_membership] + constructor + · rw [MvPolynomial.degreeOf_le_iff] + intro m hm + by_contra h + have hz := hP.1 (m 0) (by omega) + have hc : biCoeff (toBiPolynomial P) (m 0) (m 1)=0 := by + simp [biCoeff,hz] + rw [toBiPolynomial_coeff] at hc + have he : exponentPair.symm (m 0,m 1)=m := exponentPair.symm_apply_apply m + rw [he] at hc + exact (MvPolynomial.mem_support_iff.mp hm) hc + · rw [MvPolynomial.degreeOf_le_iff] + intro m hm + by_contra h + have hc := hP.2 (m 0) (m 1) (by omega) + change biCoeff (toBiPolynomial P) (m 0) (m 1)=0 at hc + rw [toBiPolynomial_coeff] at hc + have he : exponentPair.symm (m 0,m 1)=m := exponentPair.symm_apply_apply m + rw [he] at hc + exact (MvPolynomial.mem_support_iff.mp hm) hc + +theorem bi_factor_two_rows (r s : ℕ) (P : BiPoly) + (hP : BiBounded (r+2) s P) (a b : ℝ) (hab : a≠b) + (ha : eval a P=0) (hb : eval b P=0) : + ∃R : BiPoly, BiBounded r s R ∧ mulRoot a (mulRoot b R)=P := by + obtain ⟨Q,hQ,hQP⟩ := bi_factor_row (r+1) s P hP a ha + have hbQ : eval b Q=0 := by + rw [←hQP,eval_mulRoot] at hb + exact (smul_eq_zero.mp hb).resolve_left (sub_ne_zero.mpr hab.symm) + obtain ⟨R,hR,hRQ⟩ := bi_factor_row r s Q hQ b hbQ + exact ⟨R,hR,by rw [hRQ,hQP]⟩ + +theorem evenTriangle_middle_rows_zero (s : ℕ) (hs : 2≤s) + (node : Fin (2*s)→ℝ) (hn : Function.Injective node) + (P : BiPoly) (hP : BiBounded s (s-1) P) + (hv : ∀p q, (p,q)∈evenTriangle s → biEval (node p) (node q) P=0) : + eval (node ⟨s-1,by omega⟩) P=0 ∧ eval (node ⟨s,by omega⟩) P=0 := by + constructor + · let f : Fin (s-1)→Fin (2*s) := fun i => ⟨i.val,by omega⟩ + apply eq_zero_of_node_roots (node ∘ f) (hn.comp (by + intro i j h + exact Fin.ext (show i.val=j.val from congrArg (fun x : Fin (2*s) => x.val) h))) Finset.univ + · simpa only [Finset.card_univ,Fintype.card_fin] using + bounded_eval_outer hP (node ⟨s-1,by omega⟩) + · intro i _ + apply hv + rw [evenTriangle_middle_left_row s hs] + exact i.isLt + · let f : Fin (s-1)→Fin (2*s) := fun i => ⟨s+1+i.val,by omega⟩ + apply eq_zero_of_node_roots (node ∘ f) (hn.comp (by + intro i j h + apply Fin.ext + have := congrArg Fin.val h + dsimp [f] at this + omega)) Finset.univ + · simpa only [Finset.card_univ,Fintype.card_fin] using + bounded_eval_outer hP (node ⟨s,by omega⟩) + · intro i _ + apply hv + rw [evenTriangle_middle_right_row s hs] + dsimp [f] + omega + +theorem evenTriangle_end_columns_zero (s : ℕ) (hs : 2≤s) + (node : Fin (2*s)→ℝ) (hn : Function.Injective node) + (P : BiPoly) (hP : BiBounded (s-1) s P) + (hv : ∀p q, (p,q)∈evenTriangle s → biEval (node p) (node q) P=0) : + eval (node ⟨0,by omega⟩) (swapBi P)=0 ∧ + eval (node ⟨2*s-1,by omega⟩) (swapBi P)=0 := by + constructor + · let f : Fin (s-1)→Fin (2*s) := fun i => ⟨i.val+1,by omega⟩ + apply eq_zero_of_node_roots (node ∘ f) (hn.comp (by + intro i j h + apply Fin.ext + have := congrArg Fin.val h + dsimp [f] at this + omega)) Finset.univ + · simpa only [Finset.card_univ,Fintype.card_fin] using + bounded_eval_outer (biBounded_swap hP) (node ⟨0,by omega⟩) + · intro i _ + change biEval _ _ (swapBi P)=0 + rw [biEval_swap] + apply hv + rw [evenTriangle_first_column s hs] + dsimp [f] + omega + · let f : Fin (s-1)→Fin (2*s) := fun i => ⟨s+i.val,by omega⟩ + apply eq_zero_of_node_roots (node ∘ f) (hn.comp (by + intro i j h + apply Fin.ext + have := congrArg Fin.val h + dsimp [f] at this + omega)) Finset.univ + · simpa only [Finset.card_univ,Fintype.card_fin] using + bounded_eval_outer (biBounded_swap hP) (node ⟨2*s-1,by omega⟩) + · intro i _ + change biEval _ _ (swapBi P)=0 + rw [biEval_swap] + apply hv + rw [evenTriangle_last_column s hs] + dsimp [f] + omega + +end Paper170 + +end +end + +section + +noncomputable section +open PolynomialModule Zarankiewicz MvPolynomial +namespace Paper170 + +theorem evalTwo_ext {P Q : Poly2} (h : ∀u v, evalTwo u v P=evalTwo u v Q) : P=Q := by + apply MvPolynomial.funext + intro t + have ht : t = ![t 0,t 1] := by ext i; fin_cases i <;> rfl + rw [ht] + exact h (t 0) (t 1) + +theorem evenTriangle_row_factorization (s : ℕ) (hs : 3≤s) + (node : Fin (2*s)→ℝ) (hn : Function.Injective node) + (P : Poly2) (hP : P∈rectangle (s-1) (s-2)) + (hv : ∀p q, (p,q)∈evenTriangle s → evalTwo (node p) (node q) P=0) : + ∃R : Poly2, R∈rectangle (s-3) (s-2) ∧ + P=(X 0-C (node ⟨s-1,by omega⟩))*(X 0-C (node ⟨s,by omega⟩))*R ∧ + ∀p q, (p,q)∈evenTriangle (s-1) → + evalTwo (node (triangleMiddleEmbedding s (by omega) p)) + (node (triangleMiddleEmbedding s (by omega) q)) R=0 := by + have hB : BiBounded s (s-1) (toBiPolynomial P) := by + convert toBiPolynomial_bounded (s-1) (s-2) P hP using 1 <;> omega + have hV : ∀p q, (p,q)∈evenTriangle s → + biEval (node p) (node q) (toBiPolynomial P)=0 := by + simpa only [toBiPolynomial_eval] using hv + obtain ⟨hleft,hright⟩ := evenTriangle_middle_rows_zero s (by omega) node hn _ hB hV + obtain ⟨Q,hQ,hQP⟩ := bi_factor_two_rows (s-2) (s-1) (toBiPolynomial P) + (by convert hB using 1; omega) (node ⟨s-1,by omega⟩) (node ⟨s,by omega⟩) + (hn.ne (by intro h; have := congrArg Fin.val h; dsimp at this; omega)) hleft hright + let R := toBiPolynomial.symm Q + have hR : R∈rectangle (s-3) (s-2) := by + apply mem_rectangle_of_toBiPolynomial_bounded + dsimp [R] + rw [LinearEquiv.apply_symm_apply] + convert hQ using 1 <;> omega + have hf : P=(X 0-C (node ⟨s-1,by omega⟩))*(X 0-C (node ⟨s,by omega⟩))*R := by + apply evalTwo_ext + intro u v + rw [←toBiPolynomial_eval,hQP.symm,biEval_mulRoot,biEval_mulRoot] + have hQR : biEval u v Q=evalTwo u v R := by + rw [←toBiPolynomial_eval] + simp only [R,LinearEquiv.apply_symm_apply] + rw [hQR] + simp [evalTwo,mul_assoc] + refine ⟨R,hR,hf,?_⟩ + intro p q hpq + have hzero := hv (triangleMiddleEmbedding s (by omega) p) + (triangleMiddleEmbedding s (by omega) q) + ((evenTriangle_delete_middle s (by omega) p q).mpr hpq) + rw [hf] at hzero + have ha := triangleMiddleEmbedding_avoids s (by omega) p + have h₁ : node (triangleMiddleEmbedding s (by omega) p)-node ⟨s-1,by omega⟩≠0 := + sub_ne_zero.mpr (hn.ne (by intro h; exact ha.1 (congrArg Fin.val h))) + have h₂ : node (triangleMiddleEmbedding s (by omega) p)-node ⟨s,by omega⟩≠0 := + sub_ne_zero.mpr (hn.ne (by intro h; exact ha.2 (congrArg Fin.val h))) + change (MvPolynomial.aeval _ _) = 0 at hzero + simp only [map_mul,map_sub,MvPolynomial.aeval_X,MvPolynomial.aeval_C, + Matrix.cons_val_zero,Algebra.algebraMap_self,RingHom.id_apply] at hzero + exact (mul_eq_zero.mp hzero).resolve_left (mul_ne_zero h₁ h₂) + +theorem evenTriangle_column_factorization (s : ℕ) (hs : 3≤s) + (node : Fin (2*s)→ℝ) (hn : Function.Injective node) + (P : Poly2) (hP : P∈rectangle (s-2) (s-1)) + (hv : ∀p q, (p,q)∈evenTriangle s → evalTwo (node p) (node q) P=0) : + ∃R : Poly2, R∈rectangle (s-2) (s-3) ∧ + P=(X 1-C (node ⟨0,by omega⟩))*(X 1-C (node ⟨2*s-1,by omega⟩))*R ∧ + ∀p q, (p,q)∈evenTriangle (s-1) → + evalTwo (node (triangleEndEmbedding s (by omega) p)) + (node (triangleEndEmbedding s (by omega) q)) R=0 := by + have hB : BiBounded (s-1) s (toBiPolynomial P) := by + convert toBiPolynomial_bounded (s-2) (s-1) P hP using 1 <;> omega + have hV : ∀p q, (p,q)∈evenTriangle s → + biEval (node p) (node q) (toBiPolynomial P)=0 := by + simpa only [toBiPolynomial_eval] using hv + obtain ⟨hleft,hright⟩ := evenTriangle_end_columns_zero s (by omega) node hn _ hB hV + obtain ⟨Q,hQ,hQP⟩ := bi_factor_two_rows (s-2) (s-1) (swapBi (toBiPolynomial P)) + (by convert biBounded_swap hB using 1; omega) + (node ⟨0,by omega⟩) (node ⟨2*s-1,by omega⟩) + (hn.ne (by intro h; have := congrArg Fin.val h; dsimp at this; omega)) hleft hright + let R := toBiPolynomial.symm (swapBi Q) + have hR : R∈rectangle (s-2) (s-3) := by + apply mem_rectangle_of_toBiPolynomial_bounded + dsimp [R] + rw [LinearEquiv.apply_symm_apply] + convert biBounded_swap hQ using 1 <;> omega + have hf : P=(X 1-C (node ⟨0,by omega⟩))*(X 1-C (node ⟨2*s-1,by omega⟩))*R := by + apply evalTwo_ext + intro u v + rw [←toBiPolynomial_eval,←biEval_swap (toBiPolynomial P),hQP.symm, + biEval_mulRoot,biEval_mulRoot] + have hQR : biEval v u Q=evalTwo u v R := by + rw [←toBiPolynomial_eval] + simp only [R,LinearEquiv.apply_symm_apply,biEval_swap] + rw [hQR] + simp [evalTwo,mul_assoc] + refine ⟨R,hR,hf,?_⟩ + intro p q hpq + have hzero := hv (triangleEndEmbedding s (by omega) p) + (triangleEndEmbedding s (by omega) q) + ((evenTriangle_delete_ends s (by omega) p q).mpr hpq) + rw [hf] at hzero + have ha := triangleEndEmbedding_avoids s (by omega) q + have h₁ : node (triangleEndEmbedding s (by omega) q)-node ⟨0,by omega⟩≠0 := + sub_ne_zero.mpr (hn.ne (by intro h; exact ha.1 (congrArg Fin.val h))) + have h₂ : node (triangleEndEmbedding s (by omega) q)-node ⟨2*s-1,by omega⟩≠0 := + sub_ne_zero.mpr (hn.ne (by intro h; exact ha.2 (congrArg Fin.val h))) + change (MvPolynomial.aeval _ _) = 0 at hzero + simp only [map_mul,map_sub,MvPolynomial.aeval_X,MvPolynomial.aeval_C, + Matrix.cons_val_one,Matrix.cons_val_zero,Algebra.algebraMap_self,RingHom.id_apply] at hzero + exact (mul_eq_zero.mp hzero).resolve_left (mul_ne_zero h₁ h₂) + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/Truncation.lean b/lean/OAI/Combinatorics/CompleteCrossing/Truncation.lean new file mode 100644 index 0000000000000000000000000000000000000000..59010abd93db5127b8d35c604efa8b052493fcde --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/Truncation.lean @@ -0,0 +1,705 @@ +import OAI.Combinatorics.CompleteCrossing.SpokePorts +import OAI.Combinatorics.Crossing.PolygonalParametrizationCover +import OAI.Combinatorics.Crossing.ReducedCrossingCorners +import OAI.Combinatorics.Crossing.ReducedCrossingTransversality +import OAI.Combinatorics.Crossing.TruncatedCrossingCorners +import OAI.Combinatorics.Crossing.TruncatedCrossingRetention +import OAI.Combinatorics.Crossing.TruncatedDrawingDisks +import OAI.Combinatorics.Crossing.TruncatedDrawingInteriors +import OAI.Combinatorics.Crossing.TruncatedSegmentTransversality +import OAI.Combinatorics.Crossing.TruncatedTraceDecomposition +import OAI.Combinatorics.Crossing.VertexDisksCrossingFree +import OAI.Combinatorics.Crossing.VertexTruncation +import OAI.Combinatorics.Crossing.VertexTruncationGeometry + +namespace OAI + +/-! Vertex-disk truncation, retained crossings, reduced corners, and transverse segments. -/ + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} [Fintype Vertex] {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem LocallyStraightAt.exists_trace_line (D : Paper170.ContinuousDrawing graph) + (e : Edge) (x : Plane) (hx : x ∈ Paper170.edgeInterior D e) + (h : LocallyStraightAt D e x) : + ∃ d : Plane, d ≠ 0 ∧ ∃ U : Set Plane, IsOpen U ∧ x ∈ U ∧ + ∀ z ∈ U, z ∈ Set.range (D.edge e) → det2 d (z-x)=0 := by + obtain ⟨a,b,hab,hxab,U,hU,hxU,htrace⟩ := h.exists_line + let V : Set Plane := Set.range D.vertex + have hV : IsClosed V := (Set.finite_range D.vertex).isClosed + have hxV : x ∉ V := by + rintro ⟨j,hj⟩ + exact edgeInterior_not_vertex D e x hx j hj.symm + refine ⟨b-a,sub_ne_zero.mpr (Ne.symm hab),U ∩ Vᶜ,hU.inter hV.isOpen_compl,⟨hxU,hxV⟩,?_⟩ + intro z hz hze + have hzi : z ∈ Paper170.edgeInterior D e := edgeInterior_of_range_not_vertices D e z hze (by + intro j hj + exact hz.2 ⟨j,hj.symm⟩) + exact det2_of_common_openSegment a b x z hxab ((htrace z hz.1).mp hzi) + +theorem minimum_bend_not_locallyStraight (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i+2 ≤ P.pieces) (hx : P.vertices (i+1) ∈ Paper170.edgeInterior D e) : + ¬ LocallyStraightAt D e (P.vertices (i+1)) := by + intro h + obtain ⟨d,hd,U,hU,hxU,hh⟩ := LocallyStraightAt.exists_trace_line D e _ hx h + apply P.minimum_bend_det_ne_zero hmin i hi + apply bend_det_zero_of_local_line _ _ _ d hd U hU hxU + intro z hz hseg + apply hh z hz + rcases hseg with hseg | hseg + · exact P.inside i (by omega) hseg + · exact P.inside (i+1) (by omega) hseg + +theorem minimum_bend_not_crossing (D : Paper170.AdmissibleDrawing graph) + (hstraight : LocallyStraightCrossings D) (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i+2 ≤ P.pieces) : P.vertices (i+1) ∉ Paper170.crossingPoints D.toContinuousDrawing := by + rintro ⟨f,g,hfg,hf,hg⟩ + have hx : P.vertices (i+1) ∈ Paper170.edgeInterior D.toContinuousDrawing e := + edgeInterior_of_range_not_vertices D.toContinuousDrawing e _ (P.vertex_mem (i+1) (by omega)) + (edgeInterior_not_vertex D.toContinuousDrawing f _ hf) + apply minimum_bend_not_locallyStraight D.toContinuousDrawing e P hmin i hi hx + by_cases hef : e=f + · subst f + exact (hstraight.at_crossing e g hfg _ hx hg).1 + · exact (hstraight.at_crossing e f hef _ hx hf).1 + +theorem minimum_vertices_not_crossing (D : Paper170.AdmissibleDrawing graph) + (hstraight : LocallyStraightCrossings D) (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i ≤ P.pieces) : P.vertices i ∉ Paper170.crossingPoints D.toContinuousDrawing := by + by_cases h0 : i=0 + · subst i + rw [P.first] + rintro ⟨f,g,hfg,hf,hg⟩ + exact edgeInterior_not_vertex D.toContinuousDrawing f _ hf ((graph.src e)) rfl + by_cases hn : i=P.pieces + · subst i + rw [P.last] + rintro ⟨f,g,hfg,hf,hg⟩ + exact edgeInterior_not_vertex D.toContinuousDrawing f _ hf ((graph.dst e)) rfl + have h := minimum_bend_not_crossing D hstraight e P hmin (i-1) (by omega) + simpa only [show i-1+1=i by omega] using h + +theorem minimum_piece_crossing_open (D : Paper170.AdmissibleDrawing graph) + (hstraight : LocallyStraightCrossings D) (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ Q : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ Q.pieces) + (i : ℕ) (hi : i < P.pieces) (x : Plane) (hx : x ∈ Paper170.crossingPoints D.toContinuousDrawing) + (hseg : x ∈ segment ℝ (P.vertices i) (P.vertices (i+1))) : + x ∈ openSegmentTrace (P.vertices i) (P.vertices (i+1)) := by + rw [← Path.range_segment] at hseg + obtain ⟨t,ht⟩ := hseg + have ht0 : t ≠ 0 := by + intro h + subst t + simp only [Path.source] at ht + exact minimum_vertices_not_crossing D hstraight e P hmin i (by omega) (ht.symm ▸ hx) + have ht1 : t ≠ 1 := by + intro h + subst t + simp only [Path.target] at ht + exact minimum_vertices_not_crossing D hstraight e P hmin (i+1) (by omega) (ht.symm ▸ hx) + refine ⟨t.val,⟨?_,?_⟩,?_⟩ + · exact lt_of_le_of_ne t.property.1 (fun h => ht0 (Subtype.ext h.symm)) + · exact lt_of_le_of_ne t.property.2 (fun h => ht1 (Subtype.ext h)) + · simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint] using ht + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem truncated_piece_vertex_disk_cases (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (j : Vertex) (e : Edge) (i : Fin (P e).pieces) (x : Plane) + (hx : x ∈ segment ℝ ((P e).truncatedVertices r i.val) ((P e).truncatedVertices r (i.val+1))) : + (j=(graph.src e) ∧ x=(P e).startPort r) ∨ + (j=(graph.dst e) ∧ x=(P e).endPort r) ∨ r^2 < squaredLength (x-D.vertex j) := by + have hp := drawing_chain_pieces_pos D e (P e) + by_cases hfirst : j=(graph.src e) ∧ i.val=0 + · have hh := (P e).truncated_first_exterior (hmin e) hp r hr (hshort e).1 (hshort e).2 + (by simpa only [hfirst.2] using hx) + rcases Set.mem_insert_iff.mp hh with he | he + · exact Or.inl ⟨hfirst.1,he⟩ + · right; right + simpa only [Set.mem_ofPred_eq,(P e).first,hfirst.1] using he + by_cases hlast : j=(graph.dst e) ∧ i.val+1=(P e).pieces + · have hi : i.val=(P e).pieces-1 := by omega + have hh := (P e).truncated_last_exterior (hmin e) hp r hr (hshort e).1 (hshort e).2 + (by simpa only [hi,show (P e).pieces-1+1=(P e).pieces by omega] using hx) + rcases Set.mem_insert_iff.mp hh with he | he + · exact Or.inr (Or.inl ⟨hlast.1,he⟩) + · right; right + simpa only [Set.mem_ofPred_eq,(P e).last,hlast.1] using he + · right; right + have hs : r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) := by nlinarith [(hshort e).1,sq_nonneg r] + have ht : r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1)) := by + nlinarith [(hshort e).2,sq_nonneg r] + have hxi := (P e).truncated_piece_subset r hr hs ht i.val i.isLt hx + by_contra h + exact Set.disjoint_left.mp (hclear j e i (fun h => h.elim hfirst hlast)) (le_of_not_gt h) hxi + +theorem truncated_path_vertex_disk_cases (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (j : Vertex) (e : Edge) (x : Plane) + (hx : x ∈ Set.range (polygonalArcPath ((P e).truncatedVertices r) (P e).pieces)) : + (j=(graph.src e) ∧ x=(P e).startPort r) ∨ + (j=(graph.dst e) ∧ x=(P e).endPort r) ∨ r^2 < squaredLength (x-D.vertex j) := by + obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece ((P e).truncatedVertices r) (P e).pieces + (drawing_chain_pieces_pos D e (P e)) x hx + exact truncated_piece_vertex_disk_cases D P hmin r hr hshort hclear j e ⟨i,hi⟩ x hxi + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} [Fintype Vertex] {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem LocallyTransverseCrossings.exists_trace_lines (D : Paper170.AdmissibleDrawing graph) + (h : LocallyTransverseCrossings D) (e f : Edge) (hef : e ≠ f) + (x : Plane) (hxe : x ∈ Paper170.edgeInterior D.toContinuousDrawing e) + (hxf : x ∈ Paper170.edgeInterior D.toContinuousDrawing f) : + ∃ d k : Plane, det2 d k ≠ 0 ∧ ∃ U : Set Plane, IsOpen U ∧ x ∈ U ∧ + (∀ z ∈ U, z ∈ Set.range (D.edge e) → det2 d (z-x)=0) ∧ + (∀ z ∈ U, z ∈ Set.range (D.edge f) → det2 k (z-x)=0) := by + obtain ⟨a,b,c,d,hdet,hxab,hxcd,U,hU,hxU,htraceE,htraceF⟩ := h.at_crossing e f hef x hxe hxf + let V : Set Plane := Set.range D.vertex + have hV : IsClosed V := (Set.finite_range D.vertex).isClosed + have hxV : x ∉ V := by + rintro ⟨j,hj⟩ + exact edgeInterior_not_vertex D.toContinuousDrawing e x hxe j hj.symm + refine ⟨b-a,d-c,hdet,U ∩ Vᶜ,hU.inter hV.isOpen_compl,⟨hxU,hxV⟩,?_,?_⟩ + · intro z hz hze + have hzi := edgeInterior_of_range_not_vertices D.toContinuousDrawing e z hze (by + intro j hj + exact hz.2 ⟨j,hj.symm⟩) + exact det2_of_common_openSegment a b x z hxab ((htraceE z hz.1).mp hzi) + · intro z hz hzf + have hzi := edgeInterior_of_range_not_vertices D.toContinuousDrawing f z hzf (by + intro j hj + exact hz.2 ⟨j,hj.symm⟩) + exact det2_of_common_openSegment c d x z hxcd ((htraceF z hz.1).mp hzi) + +theorem minimum_piece_det_at_crossing (D : Paper170.AdmissibleDrawing graph) + (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (e f : Edge) (hef : e ≠ f) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (Q : PolygonalChain (Set.range (D.edge f)) (D.vertex ((graph.src f))) (D.vertex ((graph.dst f)))) + (hP : ∀ R : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) + (D.vertex ((graph.dst e))), P.pieces ≤ R.pieces) + (hQ : ∀ R : PolygonalChain (Set.range (D.edge f)) (D.vertex ((graph.src f))) + (D.vertex ((graph.dst f))), Q.pieces ≤ R.pieces) + (i j : ℕ) (hi : i < P.pieces) (hj : j < Q.pieces) (x : Plane) + (hxe : x ∈ Paper170.edgeInterior D.toContinuousDrawing e) (hxf : x ∈ Paper170.edgeInterior D.toContinuousDrawing f) + (hxp : x ∈ segment ℝ (P.vertices i) (P.vertices (i+1))) + (hxq : x ∈ segment ℝ (Q.vertices j) (Q.vertices (j+1))) : + det2 (P.vertices (i+1)-P.vertices i) (Q.vertices (j+1)-Q.vertices j) ≠ 0 := by + have hx : x ∈ Paper170.crossingPoints D.toContinuousDrawing := ⟨e,f,hef,hxe,hxf⟩ + have hpo := minimum_piece_crossing_open D hstraight e P hP i hi x hx hxp + have hqo := minimum_piece_crossing_open D hstraight f Q hQ j hj x hx hxq + obtain ⟨d,k,hdk,U,hU,hxU,hlineP,hlineQ⟩ := + LocallyTransverseCrossings.exists_trace_lines D htrans e f hef x hxe hxf + have hd := segment_direction_of_local_line_at_interior _ _ x d hpo U hU hxU + (fun z hz hs => hlineP z hz (P.inside i hi hs)) + have hk := segment_direction_of_local_line_at_interior _ _ x k hqo U hU hxU + (fun z hz hs => hlineQ z hz (Q.inside j hj hs)) + exact det2_ne_zero_of_parallel_nonzero d k _ _ hdk + (P.minimum_piece_ne_zero hP i hi) (Q.minimum_piece_ne_zero hQ j hj) hd hk + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem drawing_edge_trace_decomposition (D : Paper170.ContinuousDrawing graph) + (e : Edge) + (P : PolygonalChain (Set.range (D.edge e)) (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (r : ℝ) (hr : 0 < r) + (hfirst : r^2 < squaredLength (P.vertices 1-P.vertices 0)) + (hlast : r^2 < squaredLength (P.vertices P.pieces-P.vertices (P.pieces-1))) : + Set.range (D.edge e)= + segment ℝ (D.vertex ((graph.src e))) (P.startPort r) ∪ + Set.range (polygonalArcPath (P.truncatedVertices r) P.pieces) ∪ + segment ℝ (P.endPort r) (D.vertex ((graph.dst e))) := by + have hp := drawing_chain_pieces_pos D e P + have hs : segment ℝ (D.vertex ((graph.src e))) (P.startPort r) ⊆ Set.range (D.edge e) := by + have hx := openSegmentTrace_subset_segment _ _ (radialPort_mem_openSegment (P.vertices 0) (P.vertices 1) r hr hfirst) + have hh := ((convex_segment (𝕜 := ℝ) _ _).segment_subset (left_mem_segment ℝ _ _) hx).trans (P.inside 0 hp) + simpa only [PolygonalChain.startPort,P.first] using hh + have ht : segment ℝ (P.endPort r) (D.vertex ((graph.dst e))) ⊆ Set.range (D.edge e) := by + have hlen : r^2 < squaredLength (P.vertices (P.pieces-1)-P.vertices P.pieces) := by + rwa [squaredLength_sub_comm] + have hx := openSegmentTrace_subset_segment _ _ + (openSegmentTrace_reverse_mem _ _ _ (radialPort_mem_openSegment _ _ r hr hlen)) + have hinside := P.inside (P.pieces-1) (by omega) + rw [show P.pieces-1+1=P.pieces by omega] at hinside + have hh := ((convex_segment (𝕜 := ℝ) _ _).segment_subset hx (right_mem_segment ℝ _ _)).trans hinside + simpa only [PolygonalChain.endPort,P.last] using hh + let T := P.truncated hp r hr hfirst hlast + let G := ((Path.segment (D.vertex ((graph.src e))) (P.startPort r)).trans T.path).trans + (Path.segment (P.endPort r) (D.vertex ((graph.dst e)))) + have hG : Set.range G ⊆ Set.range (D.edge e) := by + dsimp [G] + rw [Path.trans_range,Path.trans_range,Path.range_segment,Path.range_segment] + exact Set.union_subset (Set.union_subset hs T.path_range_subset) ht + have he := path_range_eq_of_subset (D.edge e) G (D.edge_injective e) hG + calc + Set.range (D.edge e) = Set.range G := he.symm + _ = _ := by + dsimp [G] + rw [Path.trans_range,Path.trans_range,Path.range_segment,Path.range_segment] + rfl + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem vertex_disks_crossing_free (D : Paper170.AdmissibleDrawing graph) (hnorm : NoAdjacentCrossings D) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (r : ℝ) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (j : Vertex) : + Disjoint (closedRoundDisk (D.vertex j) r) (Paper170.crossingPoints D.toContinuousDrawing) := by + apply Set.disjoint_left.mpr + rintro x hxd ⟨e,f,hef,hxe,hxf⟩ + have hincident (g : Edge) (hxg : x ∈ Paper170.edgeInterior D.toContinuousDrawing g) : + j=(graph.src g) ∨ j=(graph.dst g) := by + have hx := edgeInterior_subset_range D.toContinuousDrawing g hxg + rw [← drawing_chain_range_eq D.toContinuousDrawing g (P g)] at hx + obtain ⟨i,hi,hxi⟩ := polygonalArcPath_range_piece (P g).vertices (P g).pieces + (drawing_chain_pieces_pos D.toContinuousDrawing g (P g)) x hx + by_contra h + have hbad : ¬ ((j=(graph.src g) ∧ i=0) ∨ (j=(graph.dst g) ∧ i+1=(P g).pieces)) := + fun hh => h (hh.elim (fun hh => Or.inl hh.1) (fun hh => Or.inr hh.1)) + exact Set.disjoint_left.mp (hclear j g ⟨i,hi⟩ hbad) hxd hxi + have hadj := incident_edges_adjacent j ⟨e,hincident e hxe⟩ ⟨f,hincident f hxf⟩ + have hh : x ∈ Paper170.edgeInterior D.toContinuousDrawing e ∩ Paper170.edgeInterior D.toContinuousDrawing f := ⟨hxe,hxf⟩ + rw [hnorm.eq_empty e f hef hadj] at hh + exact hh + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem crossing_mem_truncated_edge (D : Paper170.AdmissibleDrawing graph) (hnorm : NoAdjacentCrossings D) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e : Edge) (x : Plane) (hx : x ∈ Paper170.crossingPoints D.toContinuousDrawing) + (hxe : x ∈ Paper170.edgeInterior D.toContinuousDrawing e) : + x ∈ Set.range (polygonalArcPath ((P e).truncatedVertices r) (P e).pieces) := by + have hh := edgeInterior_subset_range D.toContinuousDrawing e hxe + rw [drawing_edge_trace_decomposition D.toContinuousDrawing e (P e) r hr (hshort e).1 (hshort e).2] at hh + rcases hh with (hs | hm) | ht + · have hmem := center_segment_in_disk (D.vertex ((graph.src e))) ((P e).startPort r) r + (drawing_chain_startPort_circle D.toContinuousDrawing e (P e) (hmin e) r) hs + exact False.elim (Set.disjoint_left.mp (vertex_disks_crossing_free D hnorm P r hclear ((graph.src e))) hmem hx) + · exact hm + · have ht' : x ∈ segment ℝ (D.vertex ((graph.dst e))) ((P e).endPort r) := by + simpa only [segment_symm ℝ ((P e).endPort r) (D.vertex ((graph.dst e)))] using ht + have hmem := center_segment_in_disk (D.vertex ((graph.dst e))) ((P e).endPort r) r + (drawing_chain_endPort_circle D.toContinuousDrawing e (P e) (hmin e) r) ht' + exact False.elim (Set.disjoint_left.mp (vertex_disks_crossing_free D hnorm P r hclear ((graph.dst e))) hmem hx) + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem truncated_range_subset_edgeInterior (D : Paper170.ContinuousDrawing graph) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e : Edge) : + Set.range (polygonalArcPath ((P e).truncatedVertices r) (P e).pieces) ⊆ Paper170.edgeInterior D e := by + intro x hx + have hs : r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) := by nlinarith [(hshort e).1,sq_nonneg r] + have ht : r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1)) := by + nlinarith [(hshort e).2,sq_nonneg r] + apply edgeInterior_of_range_not_vertices D e x + · exact ((P e).truncated (drawing_chain_pieces_pos D e (P e)) r hr hs ht).path_range_subset hx + · intro j he + rcases truncated_path_vertex_disk_cases D P hmin r hr hshort hclear j e x hx with ⟨hj,hp⟩ | ⟨hj,hp⟩ | hout + · have hpi := drawing_chain_startPort_interior D e (P e) (hmin e) r hr hs + exact edgeInterior_not_vertex D e _ hpi j (hp.symm.trans he) + · have hpi := drawing_chain_endPort_interior D e (P e) (hmin e) r hr ht + exact edgeInterior_not_vertex D e _ hpi j (hp.symm.trans he) + · rw [he,sub_self] at hout + have hz : squaredLength (0 : Plane)=0 := by simp [squaredLength] + rw [hz] at hout + exact (sq_nonneg r).not_gt hout + +theorem truncated_edge_intersections_eq (D : Paper170.AdmissibleDrawing graph) (hnorm : NoAdjacentCrossings D) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e f : Edge) (hef : e ≠ f) : + Set.range (polygonalArcPath ((P e).truncatedVertices r) (P e).pieces) ∩ + Set.range (polygonalArcPath ((P f).truncatedVertices r) (P f).pieces) = + Paper170.edgeInterior D.toContinuousDrawing e ∩ Paper170.edgeInterior D.toContinuousDrawing f := by + have hweak (g : Edge) : + r^2 < squaredLength ((P g).vertices 1-(P g).vertices 0) ∧ + r^2 < squaredLength ((P g).vertices (P g).pieces-(P g).vertices ((P g).pieces-1)) := by + constructor <;> nlinarith [(hshort g).1,(hshort g).2,sq_nonneg r] + ext x + constructor + · rintro ⟨hx,hy⟩ + exact ⟨truncated_range_subset_edgeInterior D.toContinuousDrawing P hmin r hr hshort hclear e hx, + truncated_range_subset_edgeInterior D.toContinuousDrawing P hmin r hr hshort hclear f hy⟩ + · rintro ⟨hx,hy⟩ + have hc : x ∈ Paper170.crossingPoints D.toContinuousDrawing := ⟨e,f,hef,hx,hy⟩ + exact ⟨crossing_mem_truncated_edge D hnorm P hmin r hr hweak hclear e x hc hx, + crossing_mem_truncated_edge D hnorm P hmin r hr hweak hclear f x hc hy⟩ + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} [Fintype Vertex] {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem truncated_vertices_not_crossing (D : Paper170.AdmissibleDrawing graph) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e : Edge) (i : ℕ) (hi : i ≤ (P e).pieces) : + (P e).truncatedVertices r i ∉ Paper170.crossingPoints D.toContinuousDrawing := by + by_cases h0 : i=0 + · subst i + rw [(P e).truncatedVertices_first] + intro hx + have hc := (drawing_chain_startPort_circle D.toContinuousDrawing e (P e) (hmin e) r).le + exact Set.disjoint_left.mp (vertex_disks_crossing_free D hnorm P r hclear ((graph.src e))) hc hx + by_cases hn : i=(P e).pieces + · subst i + rw [(P e).truncatedVertices_last (drawing_chain_pieces_pos D.toContinuousDrawing e (P e))] + intro hx + have hc := (drawing_chain_endPort_circle D.toContinuousDrawing e (P e) (hmin e) r).le + exact Set.disjoint_left.mp (vertex_disks_crossing_free D hnorm P r hclear ((graph.dst e))) hc hx + · simp only [PolygonalChain.truncatedVertices,ite_eq_right h0,ite_eq_right hn] + exact minimum_vertices_not_crossing D hstraight e (P e) (hmin e) i hi + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} [Fintype Vertex] {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +theorem truncated_segment_pair_transverse (D : Paper170.AdmissibleDrawing graph) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) + (htrans : LocallyTransverseCrossings D) + (P : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e)))) + (hmin : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (P e).pieces ≤ Q.pieces) + (r : ℝ) (hr : 0 < r) + (hshort : ∀ e, 4*r^2 < squaredLength ((P e).vertices 1-(P e).vertices 0) ∧ + 4*r^2 < squaredLength ((P e).vertices (P e).pieces-(P e).vertices ((P e).pieces-1))) + (hclear : ∀ j e (i : Fin (P e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(P e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) r) (segment ℝ ((P e).vertices i.val) ((P e).vertices (i.val+1)))) + (e f : Edge) (hef : e ≠ f) (i : Fin (P e).pieces) (j : Fin (P f).pieces) : + SegmentPairTransverse ((P e).truncatedVertices r i.val) ((P e).truncatedVertices r (i.val+1)) + ((P f).truncatedVertices r j.val) ((P f).truncatedVertices r (j.val+1)) := by + intro s hs t ht he + let x := segmentPoint ((P e).truncatedVertices r i.val) ((P e).truncatedVertices r (i.val+1)) s + have hxe : x ∈ segment ℝ ((P e).truncatedVertices r i.val) ((P e).truncatedVertices r (i.val+1)) := by + rw [← Path.range_segment] + exact ⟨⟨s,hs⟩,by simp only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint,x]⟩ + have hxf : x ∈ segment ℝ ((P f).truncatedVertices r j.val) ((P f).truncatedVertices r (j.val+1)) := by + rw [← Path.range_segment] + refine ⟨⟨t,ht⟩,?_⟩ + simpa only [Path.segment_apply,AffineMap.lineMap_apply_module,x,segmentPoint] using he.symm + have hie := truncated_range_subset_edgeInterior D.toContinuousDrawing P hmin r hr hshort hclear e + (polygonalArcPath_piece_subset_range _ _ i.val i.isLt hxe) + have hif := truncated_range_subset_edgeInterior D.toContinuousDrawing P hmin r hr hshort hclear f + (polygonalArcPath_piece_subset_range _ _ j.val j.isLt hxf) + have hcross : x ∈ Paper170.crossingPoints D.toContinuousDrawing := ⟨e,f,hef,hie,hif⟩ + have hcorner := truncated_vertices_not_crossing D hnorm hstraight P hmin r hclear + have hsi := segment_parameter_strict_of_avoids_endpoints _ _ x _ hcross + (hcorner e i.val (by omega)) (hcorner e (i.val+1) (by omega)) s hs rfl + have hti := segment_parameter_strict_of_avoids_endpoints _ _ x _ hcross + (hcorner f j.val (by omega)) (hcorner f (j.val+1) (by omega)) t ht he.symm + refine ⟨?_,hsi,hti⟩ + have hweak (g : Edge) : + r^2 < squaredLength ((P g).vertices 1-(P g).vertices 0) ∧ + r^2 < squaredLength ((P g).vertices (P g).pieces-(P g).vertices ((P g).pieces-1)) := by + constructor <;> nlinarith [(hshort g).1,(hshort g).2,sq_nonneg r] + have hde := minimum_piece_det_at_crossing D hstraight htrans e f hef (P e) (P f) (hmin e) (hmin f) + i.val j.val i.isLt j.isLt x hie hif + ((P e).truncated_piece_subset r hr (hweak e).1 (hweak e).2 i.val i.isLt hxe) + ((P f).truncated_piece_subset r hr (hweak f).1 (hweak f).2 j.val j.isLt hxf) + change det2 (trackDirection ((P e).truncatedVertices r) i.val) (trackDirection ((P f).truncatedVertices r) j.val) ≠ 0 + rw [(P e).truncated_direction r i.val i.isLt,(P f).truncated_direction r j.val j.isLt, + det2_smul_left,det2_smul_right] + exact mul_ne_zero (ne_of_gt ((P e).truncatedScale_pos r hr (hshort e).1 (hshort e).2 i.val)) + (mul_ne_zero (ne_of_gt ((P f).truncatedScale_pos r hr (hshort f).1 (hshort f).2 j.val)) hde) + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry +structure VertexTruncation (D : Paper170.ContinuousDrawing graph) where + chain : ∀ e : Edge, PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))) + minimal : ∀ e, ∀ Q : PolygonalChain (Set.range (D.edge e)) + (D.vertex ((graph.src e))) (D.vertex ((graph.dst e))), (chain e).pieces ≤ Q.pieces + radius : ℝ + radius_pos : 0 < radius + short : ∀ e, 4*radius^2 < squaredLength ((chain e).vertices 1-(chain e).vertices 0) ∧ + 4*radius^2 < squaredLength ((chain e).vertices (chain e).pieces-(chain e).vertices ((chain e).pieces-1)) + disks_disjoint : ∀ j k, j ≠ k → + Disjoint (closedRoundDisk (D.vertex j) radius) (closedRoundDisk (D.vertex k) radius) + piece_clearance : ∀ j e (i : Fin (chain e).pieces), + ¬ ((j=(graph.src e) ∧ i.val=0) ∨ (j=(graph.dst e) ∧ i.val+1=(chain e).pieces)) → + Disjoint (closedRoundDisk (D.vertex j) radius) + (segment ℝ ((chain e).vertices i.val) ((chain e).vertices (i.val+1))) + +theorem nonempty_vertexTruncation [Fintype Vertex] [Fintype Edge] (D : Paper170.ContinuousDrawing graph) + (hpoly : ∀ e, HasFiniteAffineCover (D.edge e)) : Nonempty (VertexTruncation D) := by + classical + have hex (e : Edge) := exists_reduced_polygonalChain (D.edge e) (D.edge_injective e) (hpoly e) + choose P htrace hinj hpos hdir hbend hmin using hex + obtain ⟨ρ,hρ,hdis,hclear⟩ := exists_vertex_piece_clearance D P hmin + obtain ⟨r,hr,hrρ,hshort⟩ := exists_short_vertex_radius D P hmin ρ hρ + refine ⟨⟨P,hmin,r,hr,hshort,?_,?_⟩⟩ + · intro j k hjk + exact (hdis j k hjk).mono (closedRoundDisk_mono _ hr.le hrρ) (closedRoundDisk_mono _ hr.le hrρ) + · intro j e i hi + exact (hclear j e i hi).mono_left (closedRoundDisk_mono _ hr.le hrρ) + +namespace VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +def pieces (e : Edge) : ℕ := (V.chain e).pieces + +def vertices (e : Edge) : ℕ → Plane := (V.chain e).truncatedVertices V.radius + +def startPort (e : Edge) : Plane := (V.chain e).startPort V.radius + +def endPort (e : Edge) : Plane := (V.chain e).endPort V.radius + +theorem pieces_pos (e : Edge) : 0 < V.pieces e := drawing_chain_pieces_pos D e (V.chain e) + +theorem weak_short (e : Edge) : + V.radius^2 < squaredLength ((V.chain e).vertices 1-(V.chain e).vertices 0) ∧ + V.radius^2 < squaredLength ((V.chain e).vertices (V.chain e).pieces-(V.chain e).vertices ((V.chain e).pieces-1)) := by + constructor <;> nlinarith [(V.short e).1,(V.short e).2,sq_nonneg V.radius] + +def path (e : Edge) : Path (V.startPort e) (V.endPort e) := + ((V.chain e).truncated (V.pieces_pos e) V.radius V.radius_pos (V.weak_short e).1 (V.weak_short e).2).path + +theorem path_injective (e : Edge) : Function.Injective (V.path e) := + (V.chain e).truncated_path_injective (V.minimal e) (V.pieces_pos e) V.radius V.radius_pos + (V.short e).1 (V.short e).2 + +theorem path_hasFiniteAffineCover (e : Edge) : HasFiniteAffineCover (V.path e) := + ((V.chain e).truncated (V.pieces_pos e) V.radius V.radius_pos (V.weak_short e).1 (V.weak_short e).2).hasFiniteAffineCover + +theorem range_subset_edgeInterior (e : Edge) : Set.range (V.path e) ⊆ Paper170.edgeInterior D e := + truncated_range_subset_edgeInterior D V.chain V.minimal V.radius V.radius_pos V.short V.piece_clearance e + +theorem direction_ne_zero (e : Edge) (i : ℕ) (hi : i < V.pieces e) : + trackDirection (V.vertices e) i ≠ 0 := + (V.chain e).truncated_direction_ne_zero (V.minimal e) V.radius V.radius_pos (V.short e).1 (V.short e).2 i hi + +end VertexTruncation + +end Paper170Geometry + +end +end + +section + +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} + +namespace Paper170Geometry.VertexTruncation +theorem offset_avoidance {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) (e : Edge) : + ∃ δ : ℝ, 0 < δ ∧ ∀ t : ℝ, t ≠ 0 → |t| < δ → ∀ i j : Fin (V.pieces e), + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (shiftedTrack (V.vertices e) (V.pieces e) t j.val) + (shiftedTrack (V.vertices e) (V.pieces e) t (j.val+1)) := + (V.chain e).truncated_offset_avoidance (V.minimal e) V.radius V.radius_pos (V.short e).1 (V.short e).2 + +theorem edge_intersections_eq {D : Paper170.AdmissibleDrawing graph} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (e f : Edge) (hef : e ≠ f) : + Set.range (V.path e) ∩ Set.range (V.path f)=Paper170.edgeInterior D.toContinuousDrawing e ∩ Paper170.edgeInterior D.toContinuousDrawing f := + truncated_edge_intersections_eq D hnorm V.chain V.minimal V.radius V.radius_pos V.short V.piece_clearance e f hef + +theorem pair_transverse [Fintype Vertex] {D : Paper170.AdmissibleDrawing graph} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) (htrans : LocallyTransverseCrossings D) + (e f : Edge) (hef : e ≠ f) (i : Fin (V.pieces e)) (j : Fin (V.pieces f)) : + SegmentPairTransverse (V.vertices e i.val) (V.vertices e (i.val+1)) + (V.vertices f j.val) (V.vertices f (j.val+1)) := + truncated_segment_pair_transverse D hnorm hstraight htrans V.chain V.minimal V.radius V.radius_pos + V.short V.piece_clearance e f hef i j + +theorem crossing_free_disks {D : Paper170.AdmissibleDrawing graph} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (j : Vertex) : + Disjoint (closedRoundDisk (D.vertex j) V.radius) (Paper170.crossingPoints D.toContinuousDrawing) := + vertex_disks_crossing_free D hnorm V.chain V.radius V.piece_clearance j + +theorem vertices_not_crossing [Fintype Vertex] {D : Paper170.AdmissibleDrawing graph} (V : VertexTruncation D.toContinuousDrawing) + (hnorm : NoAdjacentCrossings D) (hstraight : LocallyStraightCrossings D) + (e : Edge) (i : ℕ) (hi : i ≤ V.pieces e) : V.vertices e i ∉ Paper170.crossingPoints D.toContinuousDrawing := + truncated_vertices_not_crossing D hnorm hstraight V.chain V.minimal V.radius V.piece_clearance e i hi + +theorem vertex_disk_cases {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + (j : Vertex) (e : Edge) (x : Plane) (hx : x ∈ Set.range (V.path e)) : + (j=(graph.src e) ∧ x=V.startPort e) ∨ (j=(graph.dst e) ∧ x=V.endPort e) ∨ + V.radius^2 < squaredLength (x-D.vertex j) := + truncated_path_vertex_disk_cases D V.chain V.minimal V.radius V.radius_pos V.short V.piece_clearance j e x hx + +end Paper170Geometry.VertexTruncation + +namespace Paper170Geometry + +theorem normalized_vertexTruncation [Fintype Vertex] [Fintype Edge] + (N : Paper170.NormalizedDrawing graph) : Nonempty (VertexTruncation N.toContinuousDrawing) := + nonempty_vertexTruncation N.toContinuousDrawing (fun e => + (Paper170.toZarankiewiczParametrization (N.polygonal e)).hasFiniteAffineCover) + +end Paper170Geometry + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/TwoPage.lean b/lean/OAI/Combinatorics/CompleteCrossing/TwoPage.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ee0357ae48f6a2bf2fa08be14cc4ccbaca6ee8d --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/TwoPage.lean @@ -0,0 +1,247 @@ +import OAI.Combinatorics.CompleteCrossing.CirclePlacement +import Mathlib.Data.Fin.VecNotation +import Mathlib.Tactic + +namespace OAI + +/-! Counting actual crossing points of the explicit two-page drawing. -/ + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +lemma twoPage_meeting_chords {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) + (e f : CompleteEdge n) (x : Plane) + (he : x ∈ edgeInterior D.toContinuousDrawing e) + (hf : x ∈ edgeInterior D.toContinuousDrawing f) : + residueColor n (e.val.1.val + e.val.2.val) = residueColor n (f.val.1.val + f.val.2.val) ∧ + ∃ y, y ∈ chordInterior C.point e ∩ chordInterior C.point f ∧ + x = if residueColor n (e.val.1.val + e.val.2.val) then y else inversion y := by + rw [twoPage_edgeInterior C D hD e] at he + rw [twoPage_edgeInterior C D hD f] at hf + cases hec : residueColor n (e.val.1.val + e.val.2.val) <;> + cases hfc : residueColor n (f.val.1.val + f.val.2.val) + · simp only [hec, Bool.false_eq_true, ↓reduceIte] at he + simp only [hfc, Bool.false_eq_true, ↓reduceIte] at hf + obtain ⟨y, hy, rfl⟩ := he + obtain ⟨z, hz, hzy⟩ := hf + have hzy' : z = y := inversion_involutive.injective hzy + subst z + exact ⟨rfl, y, ⟨hy, hz⟩, rfl⟩ + · simp only [hec, Bool.false_eq_true, ↓reduceIte] at he + simp only [hfc, ↓reduceIte] at hf + have h1 := C.inverted_chord_outside e he + have h2 := C.chord_inside f hf + linarith + · simp only [hec, ↓reduceIte] at he + simp only [hfc, Bool.false_eq_true, ↓reduceIte] at hf + have h1 := C.chord_inside e he + have h2 := C.inverted_chord_outside f hf + linarith + · simp only [hec, ↓reduceIte] at he + simp only [hfc, ↓reduceIte] at hf + exact ⟨rfl, x, ⟨he, hf⟩, rfl⟩ + +lemma chord_meeting_alternates {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) (hef : e ≠ f) (y : Plane) + (hy : y ∈ chordInterior C.point e ∩ chordInterior C.point f) : + ((e.val.1 < f.val.1 ∧ f.val.1 < e.val.2 ∧ e.val.2 < f.val.2) ∨ + (f.val.1 < e.val.1 ∧ e.val.1 < f.val.2 ∧ f.val.2 < e.val.2)) ∧ + y = lineIntersectionPoint (C.point e.val.1) (C.point e.val.2) + (C.point f.val.1) (C.point f.val.2) := by + rw [circle_chord_intersection C e f hef] at hy + split_ifs at hy with h + · exact ⟨h, hy⟩ + · exact hy.elim + +lemma twoPage_meeting_alternates {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) + (e f : CompleteEdge n) (hef : e ≠ f) (x : Plane) + (he : x ∈ edgeInterior D.toContinuousDrawing e) + (hf : x ∈ edgeInterior D.toContinuousDrawing f) : + residueColor n (e.val.1.val + e.val.2.val) = residueColor n (f.val.1.val + f.val.2.val) ∧ + ((e.val.1 < f.val.1 ∧ f.val.1 < e.val.2 ∧ e.val.2 < f.val.2) ∨ + (f.val.1 < e.val.1 ∧ e.val.1 < f.val.2 ∧ f.val.2 < e.val.2)) ∧ + x = if residueColor n (e.val.1.val + e.val.2.val) then + lineIntersectionPoint (C.point e.val.1) (C.point e.val.2) (C.point f.val.1) (C.point f.val.2) + else inversion (lineIntersectionPoint (C.point e.val.1) (C.point e.val.2) + (C.point f.val.1) (C.point f.val.2)) := by + obtain ⟨hc, y, hy, hx⟩ := twoPage_meeting_chords C D hD e f x he hf + obtain ⟨ho, rfl⟩ := chord_meeting_alternates C e f hef y hy + exact ⟨hc, ho, hx⟩ + +lemma pagePoint_mem_edge {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) + (e : CompleteEdge n) (y : Plane) (hy : y ∈ chordInterior C.point e) : + (if residueColor n (e.val.1.val + e.val.2.val) then y else inversion y) ∈ + edgeInterior D.toContinuousDrawing e := by + rw [twoPage_edgeInterior C D hD] + cases h : residueColor n (e.val.1.val + e.val.2.val) + · exact ⟨y, hy, rfl⟩ + · exact hy + +lemma ordered_chord_meeting {n : ℕ} (C : CircleConfiguration n) + (e f : CompleteEdge n) + (ho : e.val.1 < f.val.1 ∧ f.val.1 < e.val.2 ∧ e.val.2 < f.val.2) : + lineIntersectionPoint (C.point e.val.1) (C.point e.val.2) + (C.point f.val.1) (C.point f.val.2) ∈ chordInterior C.point e ∩ chordInterior C.point f := by + have hef : e ≠ f := by intro h; subst f; exact (lt_irrefl _ ho.1) + rw [circle_chord_intersection C e f hef, ite_eq_left (Or.inl ho)] + exact Set.mem_singleton _ + +end Paper170 + +end +end + +section + +noncomputable section +open Set +open scoped Classical +namespace Paper170 + +def tupleFirstEdge {n : ℕ} (v : Fin 4 → Fin n) (hv : StrictMono v) : CompleteEdge n := + ⟨(v 0, v 2), hv (by decide)⟩ + +def tupleSecondEdge {n : ℕ} (v : Fin 4 → Fin n) (hv : StrictMono v) : CompleteEdge n := + ⟨(v 1, v 3), hv (by decide)⟩ + +lemma tuple_edges_ne {n : ℕ} (v : Fin 4 → Fin n) (hv : StrictMono v) : + tupleFirstEdge v hv ≠ tupleSecondEdge v hv := by + intro h + exact (ne_of_lt (hv (by decide : (0 : Fin 4) < 1))) + (congrArg (fun e => e.val.1) h) + +lemma tuple_point_membership {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) + (v : Fin 4 → Fin n) (hv : v ∈ crossingTuples n) : + let hm := (Finset.mem_filter.mp hv).2.1 + crossingTuplePoint C v ∈ edgeInterior D.toContinuousDrawing (tupleFirstEdge v hm) ∧ + crossingTuplePoint C v ∈ edgeInterior D.toContinuousDrawing (tupleSecondEdge v hm) := by + let hm := (Finset.mem_filter.mp hv).2.1 + have hc := (Finset.mem_filter.mp hv).2.2 + have hy := ordered_chord_meeting C (tupleFirstEdge v hm) (tupleSecondEdge v hm) + ⟨hm (by decide : (0 : Fin 4) < 1), hm (by decide : (1 : Fin 4) < 2), + hm (by decide : (2 : Fin 4) < 3)⟩ + constructor + · exact pagePoint_mem_edge C D hD (tupleFirstEdge v hm) _ hy.1 + · have h := pagePoint_mem_edge C D hD (tupleSecondEdge v hm) _ hy.2 + change (if residueColor n ((v 1).val + (v 3).val) then _ else _) ∈ _ at h + rw [← hc] at h + exact h + +lemma ordered_pair_tuple {n : ℕ} (C : CircleConfiguration n) (e f : CompleteEdge n) + (ho : e.val.1 < f.val.1 ∧ f.val.1 < e.val.2 ∧ e.val.2 < f.val.2) + (hc : residueColor n (e.val.1.val + e.val.2.val) = residueColor n (f.val.1.val + f.val.2.val)) : + ∃ v ∈ crossingTuples n, crossingTuplePoint C v = + if residueColor n (e.val.1.val + e.val.2.val) then + lineIntersectionPoint (C.point e.val.1) (C.point e.val.2) (C.point f.val.1) (C.point f.val.2) + else inversion (lineIntersectionPoint (C.point e.val.1) (C.point e.val.2) + (C.point f.val.1) (C.point f.val.2)) := by + let v : Fin 4 → Fin n := ![e.val.1, f.val.1, e.val.2, f.val.2] + refine ⟨v, Finset.mem_filter.mpr ⟨Finset.mem_univ _, ?_, ?_⟩, rfl⟩ + · apply Fin.strictMono_iff_lt_succ.mpr + intro i + fin_cases i + · exact ho.1 + · exact ho.2.1 + · exact ho.2.2 + · exact hc + +lemma crossingTuplePoint_surjOn {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) : + SurjOn (crossingTuplePoint C) (crossingTuples n : Set (Fin 4 → Fin n)) + (crossingPoints D.toContinuousDrawing) := by + rintro x ⟨e, f, hef, he, hf⟩ + obtain ⟨hc, ho, hx⟩ := twoPage_meeting_alternates C D hD e f hef x he hf + rcases ho with ho | ho + · obtain ⟨v, hv, hp⟩ := ordered_pair_tuple C e f ho hc + exact ⟨v, hv, hp.trans hx.symm⟩ + · obtain ⟨_, _, hx'⟩ := twoPage_meeting_alternates C D hD f e hef.symm x hf he + obtain ⟨v, hv, hp⟩ := ordered_pair_tuple C f e ho hc.symm + exact ⟨v, hv, hp.trans hx'.symm⟩ + +lemma crossingTuplePoint_injOn {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) : + InjOn (crossingTuplePoint C) (crossingTuples n : Set (Fin 4 → Fin n)) := by + intro v hv w hw hpoint + let hv' := (Finset.mem_filter.mp hv).2.1 + let hw' := (Finset.mem_filter.mp hw).2.1 + have hpv := tuple_point_membership C D hD v hv + have hpw := tuple_point_membership C D hD w hw + rw [← hpoint] at hpw + have hinc := Paper170Geometry.crossing_incident_iff D (crossingTuplePoint C v) + (tupleFirstEdge v hv') (tupleSecondEdge v hv') (tuple_edges_ne v hv') hpv.1 hpv.2 + have he := (hinc (tupleFirstEdge w hw')).mp hpw.1 + have hf := (hinc (tupleSecondEdge w hw')).mp hpw.2 + rcases he with he | he <;> rcases hf with hf | hf + · exact (tuple_edges_ne w hw' (he.trans hf.symm)).elim + · have h0 := congrArg (fun e => e.val.1) he + have h2 := congrArg (fun e => e.val.2) he + have h1 := congrArg (fun e => e.val.1) hf + have h3 := congrArg (fun e => e.val.2) hf + funext i + fin_cases i + · exact h0.symm + · exact h1.symm + · exact h2.symm + · exact h3.symm + · have h0 : w 0 = v 1 := congrArg (fun e => e.val.1) he + have h1 : w 1 = v 0 := congrArg (fun e => e.val.1) hf + have hlt := hw' (by decide : (0 : Fin 4) < 1) + rw [h0, h1] at hlt + exact (lt_asymm (hv' (by decide : (0 : Fin 4) < 1)) hlt).elim + · exact (tuple_edges_ne w hw' (he.trans hf.symm)).elim + +theorem two_page_crossing_bijection {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) : + BijOn (crossingTuplePoint C) (crossingTuples n : Set (Fin 4 → Fin n)) + (crossingPoints D.toContinuousDrawing) := by + refine ⟨?_, crossingTuplePoint_injOn C D hD, crossingTuplePoint_surjOn C D hD⟩ + intro v hv + have hp := tuple_point_membership C D hD v hv + exact ⟨_, _, tuple_edges_ne _ _, hp.1, hp.2⟩ + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +theorem two_page_crossing_count {n : ℕ} (C : CircleConfiguration n) + (D : AdmissibleDrawing (completeGraph n)) (hD : TwoPageDrawing C D) : + crossingCount D = (crossingTuples n).card := by + have h := (two_page_crossing_bijection C D hD).ncard_eq + simpa [crossingCount, Set.ncard_eq_toFinset_card _ D.crossings_finite] using h.symm + +end Paper170 + +end +end + +section + +noncomputable section +namespace Paper170 + +theorem complete_graph_upper_drawing (n : ℕ) : + ∃ D : AdmissibleDrawing (completeGraph n), crossingCount D = (crossingTuples n).card := by + obtain ⟨C⟩ := circle_configuration_exists n + obtain ⟨D, hD⟩ := two_page_drawing_exists C + exact ⟨D, two_page_crossing_count C D hD⟩ + +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/VertexChords.lean b/lean/OAI/Combinatorics/CompleteCrossing/VertexChords.lean new file mode 100644 index 0000000000000000000000000000000000000000..0706c199bdfe4446ed1ba83a3a5265199f0eb887 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/VertexChords.lean @@ -0,0 +1,301 @@ +import OAI.Combinatorics.CompleteCrossing.RadialTracks +import OAI.Combinatorics.Crossing.DiskSegments +import OAI.Combinatorics.Crossing.FiniteScaledRadius +import OAI.Combinatorics.Crossing.RoundCircleChords +import OAI.Combinatorics.Crossing.RoundDiskChords +import OAI.Combinatorics.Crossing.SegmentTraversalReversal + +namespace OAI + +/-! Uniform spoke radii, vertex chords, and separation from exterior tracks. -/ + +section + +/-! Common physical radii for every vertex of the actual drawing, fixed before any cycle choices. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem port_injective (C : TruncatedSpokeCoordinates V) (j : Vertex) : Function.Injective (V.spokePort j) := by + intro e f he + apply C.node_injective j + apply circlePoint_injective + apply similarityPoint_injective (D.vertex j) (C.frame j) (C.frame_ne_zero j) + simpa only [C.point_eq] using he + +theorem exists_uniform_endpoint_radius [Fintype Vertex] [Fintype Edge] : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, ε ≠ 0 → |ε|<δ → ∀ j : Vertex, + (∀ e f : IncidentEdges graph j, V.spokePort j e ≠ C.shiftedPort j f ε) ∧ + Function.Injective (fun e : IncidentEdges graph j => C.shiftedPort j e ε) := by + classical + choose radius hpos hprop using C.exists_endpoint_separation_radius + obtain ⟨δ,hδ,hbound⟩ := finite_positive_lower_bound Finset.univ radius (fun j _ => hpos j) + exact ⟨δ,hδ,fun ε hε hsmall j => hprop j ε hε (hsmall.trans (hbound j (Finset.mem_univ _)))⟩ + +theorem exists_uniform_scale_radius [Fintype Vertex] [Fintype Edge] (_C : TruncatedSpokeCoordinates V) : + ∃ δ : ℝ, 0<δ ∧ ∀ ε : ℝ, |ε|<δ → ∀ j (e : IncidentEdges graph j), |V.spokeScale j e*ε|<1 := by + let Spoke := Σ j : Vertex, IncidentEdges graph j + obtain ⟨δ,hδ,hbound⟩ := finite_scaled_radius + (fun s : Spoke => V.spokeScale s.1 s.2) (fun _ => (1 : ℝ)) (by intro s; norm_num) + exact ⟨δ,hδ,fun ε hε j e => hbound ε hε ⟨j,e⟩⟩ + +theorem exists_uniform_average_radius [Fintype Vertex] [Fintype Edge] : + ∃ δ : ℝ, 0<δ ∧ ∀ t : ℝ, 0 hpos j) + exact ⟨δ,hδ,fun t ht hsmall j => hprop j t ht (hsmall.trans (hbound j (Finset.mem_univ _)))⟩ + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Actual local chords have transverse meetings and avoid the exterior connector seams. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry.TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem shifted_chords_transverse (j : Vertex) (a b c d : IncidentEdges graph j) + (ε : ℝ) (hsmall : ∀ e : IncidentEdges graph j, |V.spokeScale j e*ε|≤1) + (hsep : ∀ e f : IncidentEdges graph j, V.spokePort j e ≠ C.shiftedPort j f ε) + (hinj : Function.Injective (fun e : IncidentEdges graph j => C.shiftedPort j e ε)) + (hab : a ≠ b) (hcd : c ≠ d) : + SegmentPairTransverse (V.spokePort j a) (V.spokePort j b) (C.shiftedPort j c ε) (C.shiftedPort j d ε) := + round_circle_chords_transverse (D.vertex j) _ _ _ _ V.radius + (V.spokePort_circle j a) (V.spokePort_circle j b) + (C.shiftedPort_circle j c ε (hsmall c)) (C.shiftedPort_circle j d ε (hsmall d)) + ((C.port_injective j).ne hab) (hinj.ne hcd) (hsep a c) (hsep a d) (hsep b c) (hsep b d) + +theorem chord_connector_disjoint (j : Vertex) (a b e : IncidentEdges graph j) + (ε : ℝ) (hne : ε ≠ 0) (hsmall : |V.spokeScale j e*ε|<1) (hab : a ≠ b) + (ha : V.spokePort j a ≠ C.shiftedPort j e ε) (hb : V.spokePort j b ≠ C.shiftedPort j e ε) : + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) (C.shiftedPort j e ε) (C.tangentPort j e ε) := by + have hunit (f : IncidentEdges graph j) : squaredLength (circlePoint (C.node j f))=1 := circlePoint_on_unit_circle _ + have haq : circlePoint (C.node j a) ≠ circleOffset (circlePoint (C.node j e)) (V.spokeScale j e*ε) := by + intro he + apply ha + rw [← C.point_eq j a] + exact congrArg (similarityPoint (D.vertex j) (C.frame j)) he + have hbq : circlePoint (C.node j b) ≠ circleOffset (circlePoint (C.node j e)) (V.spokeScale j e*ε) := by + intro he + apply hb + rw [← C.point_eq j b] + exact congrArg (similarityPoint (D.vertex j) (C.frame j)) he + have hd := unit_chord_connector_disjoint (circlePoint (C.node j a)) (circlePoint (C.node j b)) + (circlePoint (C.node j e)) (hunit a) (hunit b) (hunit e) + (fun he => hab (C.node_injective j (circlePoint_injective he))) + (V.spokeScale j e*ε) hsmall (mul_ne_zero (V.spokeScale_ne_zero j e) hne) haq hbq + rintro ⟨s,hs,t,ht,he⟩ + apply hd + refine ⟨s,hs,t,ht,?_⟩ + apply similarityPoint_injective (D.vertex j) (C.frame j) (C.frame_ne_zero j) + simpa only [similarityPoint_segment,C.point_eq,← C.tangentPort_eq,shiftedPort] using he + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +section + +/-! Original exterior tracks avoid every shifted vertex chord, including at boundary seams. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry +namespace VertexTruncation +variable {D : Paper170.ContinuousDrawing graph} (V : VertexTruncation D) + +theorem track_in_disk_is_port (j : Vertex) (e : Edge) (x : Plane) + (hx : x ∈ Set.range (V.path e)) (hmem : x ∈ closedRoundDisk (D.vertex j) V.radius) : + ∃ f : IncidentEdges graph j, x=V.spokePort j f := by + rcases V.vertex_disk_cases j e x hx with ⟨hj,he⟩ | ⟨hj,he⟩ | hout + · refine ⟨⟨e,Or.inl hj⟩,?_⟩ + simpa only [spokePort,drawingSpokePort,ite_eq_left hj,startPort] using he + · have hnot : j ≠ (graph.src e) := by + intro hh + exact (graph.loopless e) (hh.symm.trans hj) + refine ⟨⟨e,Or.inr hj⟩,?_⟩ + simpa only [spokePort,drawingSpokePort,ite_eq_right hnot,endPort] using he + · exact False.elim (not_lt_of_ge hmem hout) + +end VertexTruncation +namespace TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem track_shifted_chord_disjoint (j : Vertex) (c d : IncidentEdges graph j) + (ε : ℝ) (hc : |V.spokeScale j c*ε|≤1) (hd : |V.spokeScale j d*ε|≤1) + (hsep : ∀ f g : IncidentEdges graph j, V.spokePort j f ≠ C.shiftedPort j g ε) + (e : Edge) (i : Fin (V.pieces e)) : + ¬ ClosedSegmentsMeet (V.vertices e i.val) (V.vertices e (i.val+1)) + (C.shiftedPort j c ε) (C.shiftedPort j d ε) := by + intro hmeet + obtain ⟨x,hx,hy⟩ := (closedSegmentsMeet_iff_nonempty_inter _ _ _ _).mp hmeet + have hcirclec := C.shiftedPort_circle j c ε hc + have hcircled := C.shiftedPort_circle j d ε hd + have hmem := round_chord_subset_closed_disk (D.vertex j) _ _ V.radius hcirclec hcircled hy + obtain ⟨f,hf⟩ := V.track_in_disk_is_port j e x (V.piece_subset_range e i.val i.isLt hx) hmem + have hboundary : squaredLength (x-D.vertex j)=V.radius^2 := by rw [hf,V.spokePort_circle] + rcases round_chord_boundary_endpoints (D.vertex j) _ _ x V.radius hcirclec hcircled hy hboundary with h | h + · exact hsep f c (hf.symm.trans h) + · exact hsep f d (hf.symm.trans h) + +end TruncatedSpokeCoordinates +end Paper170Geometry + +end +end + +section + +/-! All disk/exterior and different-disk segment interactions are genuinely disjoint. -/ +noncomputable section +open Zarankiewicz +open scoped Classical +variable {Vertex Edge : Type} {graph : Paper170.Graph Vertex Edge} +namespace Paper170Geometry + +theorem round_chord_exterior_disjoint (z a b c d : Plane) (r : ℝ) + (ha : squaredLength (a-z)=r^2) (hb : squaredLength (b-z)=r^2) + (hout : segment ℝ c d ⊆ {x | r^2 < squaredLength (x-z)}) : ¬ ClosedSegmentsMeet a b c d := by + intro hh + obtain ⟨x,hx,hy⟩ := (closedSegmentsMeet_iff_nonempty_inter _ _ _ _).mp hh + have hle := round_chord_subset_closed_disk z a b r ha hb hx + have hlt : r^2 < squaredLength (x-z) := hout hy + change squaredLength (x-z) ≤ r^2 at hle + exact not_lt_of_ge hle hlt + +namespace TruncatedSpokeCoordinates +variable {D : Paper170.ContinuousDrawing graph} {V : VertexTruncation D} + (C : TruncatedSpokeCoordinates V) + +theorem different_vertex_chords_disjoint (j k : Vertex) (hjk : j ≠ k) + (a b : IncidentEdges graph j) (c d : IncidentEdges graph k) (ε : ℝ) + (hc : |V.spokeScale k c*ε|≤1) (hd : |V.spokeScale k d*ε|≤1) : + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) (C.shiftedPort k c ε) (C.shiftedPort k d ε) := by + apply not_closedSegmentsMeet_of_disjoint + exact (V.disks_disjoint j k hjk).mono + (round_chord_subset_closed_disk _ _ _ _ (V.spokePort_circle j a) (V.spokePort_circle j b)) + (round_chord_subset_closed_disk _ _ _ _ (C.shiftedPort_circle k c ε hc) (C.shiftedPort_circle k d ε hd)) + +theorem chord_connector_disjoint_all_passages (j : Vertex) (a b f : IncidentEdges graph j) + (ε : ℝ) (hne : ε ≠ 0) (hsmall : |V.spokeScale j f*ε|<1) + (ha : V.spokePort j a ≠ C.shiftedPort j f ε) (hb : V.spokePort j b ≠ C.shiftedPort j f ε) : + ¬ ClosedSegmentsMeet (V.spokePort j a) (V.spokePort j b) (C.shiftedPort j f ε) (C.tangentPort j f ε) := by + rintro ⟨s,hs,t,ht,he⟩ + have hx : segmentPoint (V.spokePort j a) (V.spokePort j b) s ∈ segment ℝ (V.spokePort j a) (V.spokePort j b) := by + rw [← Path.range_segment] + exact ⟨⟨s,hs⟩,by simp only [Path.segment_apply,AffineMap.lineMap_apply_module,segmentPoint]⟩ + have hinside := round_chord_subset_closed_disk (D.vertex j) _ _ V.radius + (V.spokePort_circle j a) (V.spokePort_circle j b) hx + by_cases htp : 0 (hs j e).le) (hsep j).1 (hsep j).2 hab hcd + · exact segmentPairTransverse_of_not_meet _ _ _ _ + (C.different_vertex_chords_disjoint j k hjk a b c d ε (hs k c).le (hs k d).le) + · intro j k hjk a b c d + exact C.different_vertex_chords_disjoint j k hjk a b c d ε (hs k c).le (hs k d).le + +end Paper170Geometry.TruncatedSpokeCoordinates + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/CompleteCrossing/VertexEvaluation.lean b/lean/OAI/Combinatorics/CompleteCrossing/VertexEvaluation.lean new file mode 100644 index 0000000000000000000000000000000000000000..a20276e99a8881b2197e8ed559a36267db7091c7 --- /dev/null +++ b/lean/OAI/Combinatorics/CompleteCrossing/VertexEvaluation.lean @@ -0,0 +1,405 @@ +import OAI.Combinatorics.CompleteCrossing.OrderPairing +import OAI.Combinatorics.CompleteCrossing.Polynomials + +namespace OAI + +/-! Vertex specialization, local interpolation tests, and kernel vanishing. -/ + +section + +/-! Evaluation symmetries and genuine degree bounds after fixing a vertex. -/ +noncomputable section +open scoped BigOperators +namespace Paper170 + +theorem evalFour_swapFirst (P : Poly4) (x u y v : ℝ) : + evalFour x u y v (swapFirstPair P) = evalFour u x y v P := by + induction P using MvPolynomial.induction_on with + | C r => simp [swapFirstPair, evalFour] + | add P Q hP hQ => simpa using congrArg₂ (·+·) hP hQ + | mul_X P i hP => + simp only [swapFirstPair, AlgHom.toLinearMap_apply, map_mul, MvPolynomial.rename_X] at hP ⊢ + change MvPolynomial.aeval ![x,u,y,v] _ = MvPolynomial.aeval ![u,x,y,v] _ + change MvPolynomial.aeval ![x,u,y,v] _ = MvPolynomial.aeval ![u,x,y,v] _ at hP + simp only [map_mul] + rw [hP] + fin_cases i <;> simp [Equiv.swap_apply_def, Fin.ext_iff] + +theorem evalFour_swapSecond (P : Poly4) (x u y v : ℝ) : + evalFour x u y v (swapSecondPair P) = evalFour x u v y P := by + induction P using MvPolynomial.induction_on with + | C r => simp [swapSecondPair, evalFour] + | add P Q hP hQ => simpa using congrArg₂ (·+·) hP hQ + | mul_X P i hP => + simp only [swapSecondPair, AlgHom.toLinearMap_apply, map_mul, MvPolynomial.rename_X] at hP ⊢ + change MvPolynomial.aeval ![x,u,y,v] _ = MvPolynomial.aeval ![x,u,v,y] _ + change MvPolynomial.aeval ![x,u,y,v] _ = MvPolynomial.aeval ![x,u,v,y] _ at hP + simp only [map_mul] + rw [hP] + fin_cases i <;> simp [Equiv.swap_apply_def, Fin.ext_iff] + +theorem vertexSpecialization_monomial (x : ℝ) (m : Fin 4 →₀ ℕ) (c : ℝ) : + vertexSpecialization x (MvPolynomial.monomial m c) = + MvPolynomial.C (c*x^m 0*x^m 2) * MvPolynomial.X 0^m 1 * MvPolynomial.X 1^m 3 := by + simp only [vertexSpecialization, MvPolynomial.aeval_monomial, MvPolynomial.algebraMap_eq] + rw [Finsupp.prod_fintype] + · simp [Fin.prod_univ_four] + ring + · intro i + simp + +theorem vertexSpecialization_rectangle (s : ℕ) (P : endpointSymmetricSpace s) (x : ℝ) : + vertexSpecialization x P.val ∈ rectangle (s-2) (s-2) := by + have hp := ((symmetric_space_membership s P.val).mp P.property).1 + have hb (k : Fin 2) : (vertexSpecialization x P.val).degreeOf k ≤ s-2 := by + rw [P.val.as_sum, map_sum] + apply (MvPolynomial.degreeOf_sum_le k _ _).trans + apply Finset.sup_le + intro m hm + rw [vertexSpecialization_monomial] + have h1 := MvPolynomial.degreeOf_le_iff.mp (hp 1) m hm + have h3 := MvPolynomial.degreeOf_le_iff.mp (hp 3) m hm + have hmul := MvPolynomial.degreeOf_mul_le k + (MvPolynomial.C (P.val.coeff m*x^m 0*x^m 2)*MvPolynomial.X 0^m 1) + (MvPolynomial.X 1^m 3) + have hC := MvPolynomial.degreeOf_C_mul_le (MvPolynomial.X 0^m 1 : Poly2) k + (P.val.coeff m*x^m 0*x^m 2) + have hpow0 := MvPolynomial.degreeOf_pow_le k (MvPolynomial.X 0 : Poly2) (m 1) + have hpow1 := MvPolynomial.degreeOf_pow_le k (MvPolynomial.X 1 : Poly2) (m 3) + fin_cases k <;> norm_num [MvPolynomial.degreeOf_X, Fin.ext_iff] at hpow0 hpow1 hmul hC ⊢ <;> omega + exact (rectangle_membership _ _ _).mpr ⟨hb 0,hb 1⟩ + +theorem neighbor_nodePolynomial {n : ℕ} (node : Fin n → ℝ) (i : Fin n) : + Zarankiewicz.nodePolynomial (fun p : {j : Fin n // j ≠ i} => node p.val) = + omittedNodePolynomial node i := by + classical + unfold Zarankiewicz.nodePolynomial omittedNodePolynomial + exact (Finset.prod_subtype (Finset.univ.erase i) (by simp) + (fun j => Polynomial.X-Polynomial.C (node j))).symm + +theorem neighbor_nodeWeight {n : ℕ} (node : Fin n → ℝ) (hn : Function.Injective node) + (i : Fin n) (p : {j : Fin n // j ≠ i}) : + nodeWeight (fun q : {j : Fin n // j ≠ i} => node q.val) p = + (node p.val-node i)*nodeWeight node p.val := by + classical + rw [omitted_node_weight node hn i p.val p.property.symm] + unfold nodeWeight Zarankiewicz.derivativeAtNode + rw [neighbor_nodePolynomial] + +theorem sum_away {n : ℕ} (i : Fin n) (f : Fin n → ℝ) (hi : f i=0) : + (∑j, f j) = ∑j : {j : Fin n // j ≠ i}, f j.val := by + classical + rw [← Finset.sum_erase_add _ _ (Finset.mem_univ i), hi, add_zero] + exact Finset.sum_subtype (Finset.univ.erase i) (by simp) f + +end Paper170 + +end +end + +section + +/-! The kernel vanishes on every orientation of an independent supported edge pair. -/ +noncomputable section +namespace Paper170 + +theorem kernel_ordered_eval_zero {n s : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (P : endpointSymmetricSpace s) (hP : supportEvaluation s node J P = 0) + {i p k q : Fin n} (hip : i simp + exact congrArg (fun f : Poly2 →ₐ[ℝ] ℝ => f B) h + +theorem evalFour_localTestPolynomial (x u y v : ℝ) (P : Poly4) + (U V : Polynomial ℝ) (B : Poly2) : + evalFour x u y v (localTestPolynomial P U V B) = + evalFour x u y v P * (u-v) * (u-y) * (v-x) * + U.eval x * V.eval y * evalTwo u v B := by + have hm (Q R : Poly4) : evalFour x u y v (Q*R) = evalFour x u y v Q*evalFour x u y v R := + map_mul (MvPolynomial.aeval ![x,u,y,v]) Q R + simp only [localTestPolynomial, hm, evalFour_liftUnivariate, evalFour_liftBivariate13] + simp [evalFour] + +def vertexTestSummand {n : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) (H : Poly4) + (i p k q : Fin n) : ℝ := + J i p k q * nodeWeight node i * nodeWeight node p * nodeWeight node k * nodeWeight node q * + evalFour (node i) (node p) (node k) (node q) H + +theorem vertexTestSummand_offDiagonal {n s : ℕ} (node : Fin n → ℝ) (J : CrossingTensor n) + (hloopLeft : ∀i k q, J i i k q=0) (hloopRight : ∀i p k, J i p k k=0) + (hreverseLeft : ∀i p k q, J p i k q = -J i p k q) + (hreverseRight : ∀i p k q, J i p q k = -J i p k q) + (P : endpointSymmetricSpace s) (hP : supportEvaluation s node J P=0) + (U V : Polynomial ℝ) (B : Poly2) (i p k q : Fin n) (hik : i≠k) : + vertexTestSummand node J (localTestPolynomial P.val U V B) i p k q = 0 := by + by_cases hip : i=p + · subst p + simp [vertexTestSummand, hloopLeft] + by_cases hkq : k=q + · subst q + simp [vertexTestSummand, hloopRight] + by_cases hpq : p=q + · subst q + simp [vertexTestSummand, evalFour_localTestPolynomial] + by_cases hpk : p=k + · subst k + simp [vertexTestSummand, evalFour_localTestPolynomial] + by_cases hiq : i=q + · subst q + simp [vertexTestSummand, evalFour_localTestPolynomial] + by_cases hJ : J i p k q=0 + · simp [vertexTestSummand, hJ] + have hz := kernel_independent_eval_zero node J hreverseLeft hreverseRight P hP + hip hkq hik hiq hpk hpq hJ + simp [vertexTestSummand, evalFour_localTestPolynomial, hz] + +theorem orderPairing_weight_form {ι : Type*} [Fintype ι] (node : ι → ℝ) + (order : LinearOrder ι) (A B : Poly2) : + orderPairing node order A B = ∑p, ∑q, + halfOrder order p q * (node p-node q) * nodeWeight node p * nodeWeight node q * + evalTwo (node p) (node q) A * evalTwo (node p) (node q) B := by + simp only [orderPairing, weightedPairing, nodeWeight, div_eq_mul_inv, mul_inv] + apply Finset.sum_congr rfl + intro p _ + apply Finset.sum_congr rfl + intro q _ + ring + +theorem vertexTestSummand_diagonal {n : ℕ} (node : Fin n → ℝ) + (hn : Function.Injective node) (J : CrossingTensor n) + (orders : ∀i : Fin n, LinearOrder {j : Fin n // j≠i}) + (hlocal : ∀i (p q : {j : Fin n // j≠i}), J i p.val i q.val=halfOrder (orders i) p q) + (P : Poly4) (U V : Polynomial ℝ) (B : Poly2) (i : Fin n) + (p q : {j : Fin n // j≠i}) : + vertexTestSummand node J (localTestPolynomial P U V B) i p.val i q.val = + (nodeWeight node i)^2 * U.eval (node i) * V.eval (node i) * + (halfOrder (orders i) p q * (node p.val-node q.val) * + nodeWeight (fun j : {j : Fin n // j≠i} => node j.val) p * + nodeWeight (fun j : {j : Fin n // j≠i} => node j.val) q * + evalTwo (node p.val) (node q.val) (vertexSpecialization (node i) P) * + evalTwo (node p.val) (node q.val) B) := by + rw [vertexTestSummand, evalFour_localTestPolynomial, hlocal] + rw [neighbor_nodeWeight node hn, neighbor_nodeWeight node hn, vertex_eval] + ring + +theorem polynomialTest_local_reduction {n s : ℕ} (node : Fin n → ℝ) + (hn : Function.Injective node) (J : CrossingTensor n) + (orders : ∀i : Fin n, LinearOrder {j : Fin n // j≠i}) + (hloopLeft : ∀i k q, J i i k q=0) (hloopRight : ∀i p k, J i p k k=0) + (hreverseLeft : ∀i p k q, J p i k q = -J i p k q) + (hreverseRight : ∀i p k q, J i p q k = -J i p k q) + (hlocal : ∀i (p q : {j : Fin n // j≠i}), J i p.val i q.val=halfOrder (orders i) p q) + (P : endpointSymmetricSpace s) (hP : supportEvaluation s node J P=0) + (U V : Polynomial ℝ) (B : Poly2) : + polynomialTest node J (localTestPolynomial P.val U V B) = + ∑i, (nodeWeight node i)^2 * U.eval (node i) * V.eval (node i) * + orderPairing (fun j : {j : Fin n // j≠i} => node j.val) (orders i) + (vertexSpecialization (node i) P.val) B := by + change (∑i, ∑p, ∑k, ∑q, vertexTestSummand node J (localTestPolynomial P.val U V B) i p k q)=_ + apply Finset.sum_congr rfl + intro i _ + have hk (p : Fin n) : + (∑k, ∑q, vertexTestSummand node J (localTestPolynomial P.val U V B) i p k q) = + ∑q, vertexTestSummand node J (localTestPolynomial P.val U V B) i p i q := by + apply Finset.sum_eq_single i + · intro k _ hki + apply Finset.sum_eq_zero + intro q _ + exact vertexTestSummand_offDiagonal node J hloopLeft hloopRight hreverseLeft hreverseRight + P hP U V B i p k q hki.symm + · simp + simp_rw [hk] + rw [sum_away i _ (by simp [vertexTestSummand,hloopLeft])] + have hq (p : {j : Fin n // j≠i}) : + (∑q, vertexTestSummand node J (localTestPolynomial P.val U V B) i p.val i q) = + ∑q : {j : Fin n // j≠i}, vertexTestSummand node J (localTestPolynomial P.val U V B) i p.val i q.val := + sum_away i _ (by simp [vertexTestSummand,hloopRight]) + simp_rw [hq, vertexTestSummand_diagonal node hn J orders hlocal] + rw [orderPairing_weight_form] + simp only [Finset.mul_sum] + +end Paper170 + +end +end + +section + +/-! Lagrange isolation of each vertex and the full kernel vertex-vanishing theorem. -/ +noncomputable section +open scoped BigOperators +namespace Paper170 + +def vertexPairingFunctional {n : ℕ} (node : Fin n → ℝ) + (orders : ∀i : Fin n, LinearOrder {j : Fin n // j≠i}) (P : Poly4) (B : Poly2) : + Polynomial ℝ →ₗ[ℝ] ℝ := + ∑i, ((nodeWeight node i)^2 * + orderPairing (fun j : {j : Fin n // j≠i} => node j.val) (orders i) + (vertexSpecialization (node i) P) B) • (Polynomial.aeval (node i)).toLinearMap + +theorem vertexPairingFunctional_apply {n : ℕ} (node : Fin n → ℝ) + (orders : ∀i : Fin n, LinearOrder {j : Fin n // j≠i}) (P : Poly4) (B : Poly2) + (W : Polynomial ℝ) : + vertexPairingFunctional node orders P B W = + ∑i, (nodeWeight node i)^2 * W.eval (node i) * + orderPairing (fun j : {j : Fin n // j≠i} => node j.val) (orders i) + (vertexSpecialization (node i) P) B := by + simp only [vertexPairingFunctional, LinearMap.sum_apply, LinearMap.smul_apply, + AlgHom.toLinearMap_apply, Polynomial.aeval_def, Algebra.algebraMap_self, Polynomial.eval₂_id, smul_eq_mul] + apply Finset.sum_congr rfl + intro i _ + ring + +section CrossingTensor +variable {s : ℕ} (hs : 2 ≤ s) (node : Fin (2*s+1) → ℝ) + (hnode : Function.Injective node) (J : CrossingTensor (2*s+1)) + (orders : ∀i : Fin (2*s+1), LinearOrder {j : Fin (2*s+1) // j≠i}) + (hloopLeft : ∀i k q, J i i k q=0) (hloopRight : ∀i p k, J i p k k=0) + (hreverseLeft : ∀i p k q, J p i k q = -J i p k q) + (hreverseRight : ∀i p k q, J i p q k = -J i p k q) + (hskew : ∀i p k q, J k q i p = -J i p k q) + (hlocal : ∀i (p q : {j : Fin (2*s+1) // j≠i}), J i p.val i q.val=halfOrder (orders i) p q) + (htests : ∀H ∈ box4 (2*s-1), polynomialTest node J H=0) + +include hs hnode hloopLeft hloopRight hreverseLeft hreverseRight hlocal htests in +theorem vertexPairingFunctional_zero (P : endpointSymmetricSpace s) + (hP : supportEvaluation s node J P=0) (B : Poly2) (hB : B∈rectangle (s-1) (s-1)) + (W : Polynomial ℝ) (hW : W∈Polynomial.degreeLT ℝ (2*s+1)) : + vertexPairingFunctional node orders P.val B W=0 := by + have hspan : Submodule.span ℝ {Q : Polynomial ℝ | ∃U V : Polynomial ℝ, + U.natDegree≤s ∧ V.natDegree≤s ∧ Q=U*V} ≤ + LinearMap.ker (vertexPairingFunctional node orders P.val B) := by + rw [Submodule.span_le] + rintro Q ⟨U,V,hU,hV,rfl⟩ + change vertexPairingFunctional node orders P.val B (U*V)=0 + have hz := htests (localTestPolynomial P.val U V B) (local_test_degree s hs P.val P.property U V hU hV B hB) + rw [polynomialTest_local_reduction node hnode J orders hloopLeft hloopRight + hreverseLeft hreverseRight hlocal P hP U V B] at hz + rw [vertexPairingFunctional_apply] + convert hz using 1 + apply Finset.sum_congr rfl + intro i _ + rw [Polynomial.eval_mul] + ring + rw [products_span_degree] at hspan + exact hspan hW + +include hs hnode hloopLeft hloopRight hreverseLeft hreverseRight hlocal htests in +theorem kernel_local_pairing_zero (P : endpointSymmetricSpace s) + (hP : supportEvaluation s node J P=0) (i : Fin (2*s+1)) (B : Poly2) + (hB : B∈rectangle (s-1) (s-1)) : + orderPairing (fun j : {j : Fin (2*s+1) // j≠i} => node j.val) (orders i) + (vertexSpecialization (node i) P.val) B = 0 := by + classical + let W := Lagrange.basis Finset.univ node i + have hW : W∈Polynomial.degreeLT ℝ (2*s+1) := by + apply Polynomial.mem_degreeLT.mpr + rw [Lagrange.degree_basis hnode.injOn (Finset.mem_univ i)] + simp only [Finset.card_univ, Fintype.card_fin, Nat.add_sub_cancel_right] + exact_mod_cast (show 2*s < 2*s+1 by omega) + have hz := vertexPairingFunctional_zero hs node hnode J orders hloopLeft hloopRight + hreverseLeft hreverseRight hlocal htests P hP B hB W hW + rw [vertexPairingFunctional_apply] at hz + have heq : (∑j, (nodeWeight node j)^2 * W.eval (node j) * + orderPairing (fun k : {k : Fin (2*s+1) // k≠j} => node k.val) (orders j) + (vertexSpecialization (node j) P.val) B) = + (nodeWeight node i)^2 * + orderPairing (fun j : {j : Fin (2*s+1) // j≠i} => node j.val) (orders i) + (vertexSpecialization (node i) P.val) B := by + rw [Finset.sum_eq_single i] + · rw [show W.eval (node i)=1 from Lagrange.eval_basis_self hnode.injOn (Finset.mem_univ i), mul_one] + · intro j _ hji + rw [show W.eval (node j)=0 from Lagrange.eval_basis_of_ne hji.symm (Finset.mem_univ j)] + simp + · simp + rw [heq] at hz + exact (mul_eq_zero.mp hz).resolve_left (pow_ne_zero 2 (weight_nonzero node hnode i)) + +include hs hnode orders hloopLeft hloopRight hreverseLeft hreverseRight hskew hlocal htests in +theorem kernel_vertex_vanishing (P : endpointSymmetricSpace s) + (hP : supportEvaluation s node J P=0) : ∀i, vertexSpecialization (node i) P.val=0 := by + have hlocal' : ∀j (p q : {j' : Fin (2*s+1) // j'≠j}), + J j p.val j q.val=halfOrder (orders j) p q := by + intro j p q + by_cases hpq : p=q + · subst q + have hh := hskew j p.val j p.val + have hz : J j p.val j p.val=0 := by linarith + have hpp := @lt_irrefl _ (orders j).toPartialOrder.toPreorder p + simp only [hz,halfOrder,ite_eq_right hpp] + · exact hlocal j p q + intro i + apply order_detector s hs (by simp [Fintype.card_subtype_compl]) + (fun j : {j : Fin (2*s+1) // j≠i} => node j.val) + (hnode.comp Subtype.val_injective) (orders i) _ (vertexSpecialization_rectangle s P (node i)) + intro B hB + exact kernel_local_pairing_zero hs node hnode J orders hloopLeft hloopRight + hreverseLeft hreverseRight hlocal' htests P hP i B hB + +end CrossingTensor +end Paper170 + +end +end + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/AlgorithmStatements.lean b/lean/OAI/Combinatorics/ContingencyTables/AlgorithmStatements.lean new file mode 100644 index 0000000000000000000000000000000000000000..950e99864e8379d9f9c2317f4f987f545c8eeaa6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/AlgorithmStatements.lean @@ -0,0 +1,125 @@ +import OAI.Combinatorics.ContingencyTables.Model +import OAI.Combinatorics.MatchingCount.Model + +namespace OAI + +/-! +# Main algorithm statements for result 200 + +The samplers and counter use a finite transition table, independent fair +bits, binary inputs and explicit bit-operation runtime bounds. No counting or sampling oracle is part of the machine. +The exact sampler's expected runtime uses a summable tail series, avoiding +the default value of an undefined infinite sum. +-/ + +namespace ContingencyTables.Algorithms + +open scoped BigOperators +open Filter + +abbrev Machine := MatchingFPRAS.RandomMachine +abbrev Symbol := MatchingFPRAS.Symbol + +def encodeMatrix {m n : ℕ} (X : Fin m → Fin n → ℕ) : List Symbol := + ((List.ofFn fun i => (List.ofFn fun j => MatchingFPRAS.encodeNat (X i j)).flatten)).flatten + +def encodeMargins {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : List Symbol := + MatchingFPRAS.encodeNat m ++ MatchingFPRAS.encodeNat n ++ + (List.ofFn fun i => MatchingFPRAS.encodeNat (r i)).flatten ++ + (List.ofFn fun j => MatchingFPRAS.encodeNat (c j)).flatten + +def encodeSamplingInput {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (k : ℕ) : List Symbol := + encodeMargins r c ++ MatchingFPRAS.encodeNat k + +def encodeCountingInput {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (ε δ : ℚ) : List Symbol := + encodeMargins r c ++ encodeMatrix b ++ MatchingFPRAS.encodeRat ε ++ MatchingFPRAS.encodeRat δ + +/-- The tape alphabet has positive cardinality. -/ +theorem alphabetSize_neZero : NeZero (8 : ℕ) := inferInstance + +/-- A halted tape contains the row-major binary matrix encoding. -/ +def OutputsTable (A : Machine) (input : List Symbol) {t m n : ℕ} + (bits : Fin t → Bool) (X : Fin m → Fin n → ℕ) : Prop := + (MatchingFPRAS.run A input bits).state = none ∧ + @Turing.Tape.right₀ MatchingFPRAS.Symbol (@Fin.instInhabited 8 alphabetSize_neZero) + (MatchingFPRAS.run A input bits).tape = + @Turing.ListBlank.mk Symbol (@Fin.instInhabited 8 alphabetSize_neZero) (encodeMatrix X) + +noncomputable def tableMass (A : Machine) (input : List Symbol) (t : ℕ) + {m n : ℕ} (X : Fin m → Fin n → ℕ) : ℝ := by + classical + exact ((Finset.univ.filter fun bits : Fin t → Bool => OutputsTable A input bits X).card : ℝ) / + (2 : ℝ) ^ t + +noncomputable def haltMass (A : Machine) (input : List Symbol) (t : ℕ) : ℝ := by + classical + exact ((Finset.univ.filter fun bits : Fin t → Bool => + (MatchingFPRAS.run A input bits).state = none).card : ℝ) / (2 : ℝ) ^ t + +def samplingSize (n : ℕ) {m : ℕ} (r : Fin m → ℕ) (k : ℕ) : ℕ := + m + n + Nat.clog 2 ((∑ i, r i) + 1) + k + 1 + +/-- Paper 200-01, Theorem main(i): bounded runtime on every random tape +and total variation at most `2⁻ᵏ`, with freely varying dimensions. -/ +def BoundedSamplingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → ∀ k : ℕ, 1 ≤ k → + let input := encodeSamplingInput r c k + let t := C * (samplingSize n r k) ^ d + (∀ bits : Fin t → Bool, ∃ X : Table r c, OutputsTable A input bits X.val) ∧ + (∑ X : Table r c, + |tableMass A input t X.val - (Fintype.card (Table r c) : ℝ)⁻¹|) / 2 ≤ + ((2 : ℝ) ^ k)⁻¹ + +/-- Paper 200-01, Theorem main(ii): every halted output is feasible, each +table has limiting mass `1/|Ω|`, termination has probability one, and the +expected number of bit operations is bounded by a uniform polynomial. -/ +def ExactSamplingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → + let input := encodeMargins r c + let tail : ℕ → ℝ := fun t => 1 - haltMass A input t + (∀ t (bits : Fin t → Bool), (MatchingFPRAS.run A input bits).state = none → + ∃ X : Table r c, OutputsTable A input bits X.val) ∧ + (∀ X : Table r c, Tendsto (fun t => tableMass A input t X.val) atTop + (nhds ((Fintype.card (Table r c) : ℝ)⁻¹))) ∧ + Tendsto (haltMass A input) atTop (nhds 1) ∧ + Summable tail ∧ + tsum tail ≤ C * (samplingSize n r 0) ^ d + +noncomputable def count {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) : ℕ := Fintype.card (BoundedTable r c b) + +def countingTime (C d : ℕ) {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (ε δ : ℚ) : ℕ := + C * ((encodeCountingInput r c b ε δ).length + ⌈ε⁻¹⌉₊ + + Nat.clog 2 ⌈δ⁻¹⌉₊ + 1) ^ d + +noncomputable def goodCountingTapes (A : Machine) {m n : ℕ} + (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) + (ε δ : ℚ) (t : ℕ) : Finset (Fin t → Bool) := by + classical + exact Finset.univ.filter fun bits => ∃ q : ℚ, + MatchingFPRAS.Outputs A (encodeCountingInput r c b ε δ) bits q ∧ + (1 - ε) * count r c b ≤ q ∧ q ≤ (1 + ε) * count r c b + +/-- Paper 200-02, Theorem main. The input length includes the rational +accuracy parameters, and infeasible inputs always produce exactly zero. -/ +def CountingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ), 0 < m → 0 < n → + ∀ (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → + ∀ ε δ : ℚ, 0 < ε → ε < 1 → 0 < δ → δ < 1 → + let input := encodeCountingInput r c b ε δ + let t := countingTime C d r c b ε δ + (∀ bits : Fin t → Bool, ∃ q : ℚ, 0 ≤ q ∧ MatchingFPRAS.Outputs A input bits q) ∧ + (count r c b = 0 → ∀ bits : Fin t → Bool, MatchingFPRAS.Outputs A input bits 0) ∧ + ((goodCountingTapes A r c b ε δ t).card : ℚ) / (2 : ℚ) ^ t ≥ 1 - δ + +end ContingencyTables.Algorithms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/AnnealingMultipliers.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/AnnealingMultipliers.lean new file mode 100644 index 0000000000000000000000000000000000000000..4cec3577390d5535dcb86e3238880f0dc743ed91 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/AnnealingMultipliers.lean @@ -0,0 +1,88 @@ +import Mathlib + +namespace OAI + +/-! +# The companion's multiplier update from empirical type counts + +The old multiplier cancels from the update relative to the current ideal +multiplier. Relative accuracy of two positive type means, followed by the +proved adjacent-parameter factor two, gives the required factor four at +the next parameter. This is deterministic algebra of the actual update. +-/ + +namespace ContingencyTables.AnnealingMultipliers + +variable {eta p q ph qh w ideal nextIdeal : ℝ} + +theorem empirical_positive (hp : 0 linarith + +/-- The concrete update w*(observed plain count)/(observed defect count) +is good for the next parameter. Earlier multiplier errors do not compound. -/ +theorem update_good (hp : 0 nlinarith [hnext.1,hnext.2] + +end ContingencyTables.AnnealingMultipliers + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionAnnealing.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionAnnealing.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b0de3f7dab027d69ef2cf22c09b1d27d0447593 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionAnnealing.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestPenaltyBound +import OAI.Combinatorics.ContingencyTables.Transport.PairedLabels + +namespace OAI + +/-! +# Adjacent actual companion weights and ideal multipliers + +The parameter step is 1/(H/A). Its factor-two bounds are proved from +the literal forest penalty bound, then passed to the actual labelled +weights and their exact transversal/defect totals. +-/ + +namespace ContingencyTables.CompanionAnnealing + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication ForestPenaltyBound LabelledFactorial +open TwoLiftStates BalancedBox + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def scale (A : Instance I J) : ℝ := 10*(A.d:ℝ)^2*((A.W:ℝ)+1) + +lemma scale_positive (A : Instance I J) : 0< scale A := by + have hd : (0:ℝ)< A.d := by + exact_mod_cast (show 0< A.d by have := A.hd; omega) + unfold scale + positivity + +/-- The source's j*A/H parameter is exactly j/(H/A), for its literal +integer H=10*A*d²*(W+1). The arbitrary positive penalty coefficient +therefore cancels from every adjacent-phase estimate below. -/ +lemma source_parameter (A : Instance I J) (coefficient j : ℕ) (hc : 0< coefficient) : + (j:ℝ)*(coefficient:ℝ)/((10*coefficient*A.d^2*(A.W+1):ℕ):ℝ)= + (j:ℝ)/scale A := by + have hcR : (coefficient:ℝ)≠0 := Nat.cast_ne_zero.mpr (Nat.ne_of_gt hc) + have hQ : scale A≠0 := (scale_positive A).ne' + have he : ((10*coefficient*A.d^2*(A.W+1):ℕ):ℝ)=(coefficient:ℝ)*scale A := by + unfold scale + push_cast + ring + rw [he] + field_simp [hcR,hQ] + +noncomputable def weight (A : Instance I J) (j : ℕ) : Set (Labels A×Bool) → ℝ := + f A ((j:ℝ)/scale A) + +theorem count_adjacent (A : Instance I J) (j : ℕ) (z : View A → ℕ) + (hz : InBox (bounds A) z) : + (1/2)*h A ((j:ℝ)/scale A) z≤ h A (((j+1:ℕ):ℝ)/scale A) z ∧ + h A (((j+1:ℕ):ℝ)/scale A) z≤ h A ((j:ℝ)/scale A) z := by + let K (k : ℕ) (a : ForestAssignmentSplit.FreeIndex A.small A.T A.b) : ℝ := + (2:ℝ)^(-((k:ℝ)/scale A)*penalty A z a) + have hterm (a : ForestAssignmentSplit.FreeIndex A.small A.T A.b) : + (1/2)*K j a≤ K (j+1) a ∧ K (j+1) a≤ K j a := by + have hp := penalty_bound A z hz a + have hQ := scale_positive A + have hPQ0 : 0≤ penalty A z a/scale A := div_nonneg hp.1 hQ.le + have hPQ1 : penalty A z a/scale A≤1 := (div_le_one hQ).mpr hp.2 + have hlo : (1/2:ℝ)≤(2:ℝ)^(-(penalty A z a/scale A)) := by + calc + _ = (2:ℝ)^(-1:ℝ) := by norm_num + _ ≤ _ := Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + have hup : (2:ℝ)^(-(penalty A z a/scale A))≤1 := by + calc + _ ≤ (2:ℝ)^(0:ℝ) := Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + _ = _ := by norm_num + have he : K (j+1) a=K j a*(2:ℝ)^(-(penalty A z a/scale A)) := by + unfold K + rw [← Real.rpow_add (by norm_num : (0:ℝ)<2)] + congr 1 + push_cast + ring + have hK : 0≤ K j a := (Real.rpow_pos_of_pos (by norm_num) _).le + rw [he] + constructor + · nlinarith [mul_le_mul_of_nonneg_left hlo hK] + · nlinarith [mul_le_mul_of_nonneg_left hup hK] + change (1/2)*(∑ a, K j a)≤(∑ a, K (j+1) a) ∧ (∑ a, K (j+1) a)≤∑ a, K j a + constructor + · rw [Finset.mul_sum] + exact Finset.sum_le_sum (fun a _ => (hterm a).1) + · exact Finset.sum_le_sum (fun a _ => (hterm a).2) + +theorem weight_positive (A : Instance I J) (j : ℕ) (S : Set (Labels A×Bool)) : + 0< weight A j S := by + exact div_pos (mul_pos (h_positive A _ _) (FactorialSignatures.factorialProduct_positive _)) + (CompanionFactorialApplication.denominator_positive A) + +theorem weight_adjacent (A : Instance I J) (j : ℕ) (S : Set (Labels A×Bool)) : + (1/2)*weight A j S≤ weight A (j+1) S ∧ weight A (j+1) S≤ weight A j S := by + have hz : InBox (bounds A) (groupCount (group (labelCell A)) S) := by + rw [← label_capacity] + exact SliceFactorial.groupCount_inBox _ _ + have h := count_adjacent A j _ hz + have hc : 0≤ FactorialSignatures.factorialProduct (groupCount (group (labelCell A)) S)/ + CompanionFactorialApplication.denominator A := + (div_pos (FactorialSignatures.factorialProduct_positive _) + (CompanionFactorialApplication.denominator_positive A)).le + unfold weight f firstLift + simp only [mul_div_assoc] + constructor + · nlinarith [mul_le_mul_of_nonneg_right h.1 hc] + · exact mul_le_mul_of_nonneg_right h.2 hc + +theorem total_adjacent (A : Instance I J) (j : ℕ) + (ps : List ((Labels A×Bool)×(Labels A×Bool))) (S : Set (Labels A×Bool)) : + (1/2)*slotTotal ps (weight A j) S≤ slotTotal ps (weight A (j+1)) S ∧ + slotTotal ps (weight A (j+1)) S≤ slotTotal ps (weight A j) S := by + constructor + · rw [← slotTotal_scale] + exact slotTotal_mono _ _ _ (fun T => (weight_adjacent A j T).1) _ + · exact slotTotal_mono _ _ _ (fun T => (weight_adjacent A j T).2) _ + +theorem ideal_adjacent (A : Instance I J) (j : ℕ) + (p r : (Labels A×Bool)×(Labels A×Bool)) (hp : p∈pairs) (hr : r∈pairs) (hpr : p≠r) : + (slotTotal pairs (weight A j) ∅/slotDefect pairs (weight A j) ∅ p r)/2≤ + slotTotal pairs (weight A (j+1)) ∅/slotDefect pairs (weight A (j+1)) ∅ p r ∧ + slotTotal pairs (weight A (j+1)) ∅/slotDefect pairs (weight A (j+1)) ∅ p r≤ + 2*(slotTotal pairs (weight A j) ∅/slotDefect pairs (weight A j) ∅ p r) := by + have h0 := slotTotal_pos pairs _ (weight_positive A j) ∅ PairedLabels.fresh + have hd0 := slotDefect_pos pairs _ (weight_positive A j) ∅ PairedLabels.fresh p r hp hr hpr + have hd1 := slotDefect_pos pairs _ (weight_positive A (j+1)) ∅ PairedLabels.fresh p r hp hr hpr + have ha := total_adjacent A j pairs ∅ + have hb' : (1/2)*slotDefect pairs (weight A j) ∅ p r≤ slotDefect pairs (weight A (j+1)) ∅ p r ∧ + slotDefect pairs (weight A (j+1)) ∅ p r≤ slotDefect pairs (weight A j) ∅ p r := by + unfold slotDefect + constructor + · rw [← slotTotal_scale] + exact slotTotal_mono _ _ _ (fun S => (weight_adjacent A j S).1) _ + · exact slotTotal_mono _ _ _ (fun S => (weight_adjacent A j S).2) _ + constructor + · rw [div_div,div_le_div_iff₀ (mul_pos hd0 (by norm_num)) hd1] + nlinarith [mul_nonneg h0.le (sub_nonneg.mpr hb'.2),mul_nonneg hd0.le (sub_nonneg.mpr ha.1)] + · rw [← mul_div_assoc,div_le_div_iff₀ hd1 hd0] + nlinarith [mul_nonneg hd0.le (sub_nonneg.mpr ha.2),mul_nonneg h0.le (sub_nonneg.mpr hb'.1)] + +end ContingencyTables.CompanionAnnealing + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionArithmeticProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionArithmeticProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b37a016fa51a7f739a2e86dd30efd1acda5a90b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionArithmeticProposal.lean @@ -0,0 +1,218 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinaryExchangeProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBooleanPhase +import OAI.Combinatorics.ContingencyTables.Machines.ListWordProgram +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent + +namespace OAI + +/-! # An explicit coordinate-list proposal for the companion chain + +Only ordered coordinates are enumerated. The arithmetic binary-profile +program generates the possible exchanges, after which the actual chain +state predicate removes disallowed states. A dyadic list index has exactly +the same proposal law as the abstract injection. +-/ + +namespace ContingencyTables.CompanionArithmeticProposal +open CommonBasesFPRAS ProfilePrograms FirstSuccess ResidualMixture FairBits +open CompanionFactorialApplication CompanionBooleanPhase TwoLiftStates +open scoped BigOperators Classical + +noncomputable section + +section Coordinates +variable {Γ : Type*} [Fintype Γ] {n : ℕ} (e : Γ ≃ Fin n) + +def coordinateSet (S : Set Γ) : Set (Fin n) := e.symm ⁻¹' S + +def physicalSet (S : Set (Fin n)) : Set Γ := e ⁻¹' S + +omit [Fintype Γ] in +@[simp] lemma physical_coordinate (S : Set Γ) : physicalSet e (coordinateSet e S)=S := by + ext a + simp [physicalSet,coordinateSet] + +omit [Fintype Γ] in +@[simp] lemma coordinate_physical (S : Set (Fin n)) : coordinateSet e (physicalSet e S)=S := by + ext a + simp [physicalSet,coordinateSet] + +omit [Fintype Γ] in +lemma adjacent_preimage {Δ : Type*} [Fintype Δ] (f : Γ ≃ Δ) (S T : Set Δ) + (h : ExchangeAdjacent S T) : ExchangeAdjacent (f ⁻¹' S) (f ⁻¹' T) := by + obtain ⟨B,a,b,hab,ha,hb,rfl,rfl⟩ := h + refine ⟨f ⁻¹' B,f.symm a,f.symm b,fun he => hab (f.symm.injective he),?_,?_,?_,?_⟩ + · simpa using ha + · simpa using hb + · ext x + simp only [Set.mem_preimage,Set.mem_insert_iff] + rw [←f.eq_symm_apply] + · ext x + simp only [Set.mem_preimage,Set.mem_insert_iff] + rw [←f.eq_symm_apply] + +lemma adjacent_coordinate_iff (S T : Set Γ) : + ExchangeAdjacent (coordinateSet e S) (coordinateSet e T) ↔ ExchangeAdjacent S T := by + constructor + · intro h + have hh : ExchangeAdjacent (physicalSet e (coordinateSet e S)) + (physicalSet e (coordinateSet e T)) := adjacent_preimage e _ _ h + simpa only [physical_coordinate] using hh + · exact adjacent_preimage e.symm S T + +def encodeSet (S : Set Γ) : List ℕ := List.ofFn (setProfile (coordinateSet e S)) + +def decodeSet (xs : List ℕ) : Set Γ := {a | xs.getD (e a).val 0=1} + +omit [Fintype Γ] in +@[simp] lemma decode_encode (S : Set Γ) : decodeSet e (encodeSet e S)=S := by + ext a + simp only [decodeSet,Set.mem_ofPred_eq,encodeSet,getD_setProfile,setProfile, + coordinateSet,Set.mem_preimage,Equiv.symm_apply_apply] + by_cases ha : a∈S <;> simp [ha] + +omit [Fintype Γ] in +lemma encode_injective : Function.Injective (encodeSet e) := by + intro S T he + have hd := congrArg (decodeSet e) he + simpa only [decode_encode] using hd + +omit [Fintype Γ] in +lemma encode_physical (U : Set (Fin n)) : + encodeSet e (physicalSet e U)=List.ofFn (setProfile U) := by + simp only [encodeSet,coordinate_physical] + +omit [Fintype Γ] in +lemma decode_profile (U : Set (Fin n)) : + decodeSet e (List.ofFn (setProfile U))=physicalSet e U := by + rw [←encode_physical e U,decode_encode] + +/-- The executable integer update enumerates exactly the set exchanges. -/ +theorem mem_raw_codes (S : Set Γ) (xs : List ℕ) : + xs∈binaryExchanges (encodeSet e S) ↔ + ∃ T : Set Γ,ExchangeAdjacent S T ∧ xs=encodeSet e T := by + rw [encodeSet,mem_binaryExchanges_setProfile] + constructor + · rintro ⟨i,j,hi,hj,rfl⟩ + let U := insert i (coordinateSet e S\{j}) + have hU : ExchangeAdjacent (coordinateSet e S) U := + exchangedSet_adjacent _ (⟨j,hj⟩,⟨i,hi⟩) + refine ⟨physicalSet e U,?_,(encode_physical e U).symm⟩ + apply (adjacent_coordinate_iff e S _).mp + simpa only [coordinate_physical] using hU + · rintro ⟨T,hST,rfl⟩ + obtain ⟨j,hj,i,hi,he⟩ := ((adjacent_coordinate_iff e S T).mpr hST).move + exact ⟨i,j,hi,hj,by rw [encodeSet,he]⟩ + +def neighborSets (S : Set Γ) : List (Set Γ) := + (binaryExchanges (encodeSet e S)).map (decodeSet e) + +lemma mem_neighborSets (S T : Set Γ) : T∈neighborSets e S ↔ ExchangeAdjacent S T := by + simp only [neighborSets,List.mem_map,mem_raw_codes] + constructor + · rintro ⟨xs,⟨U,hU,rfl⟩,he⟩ + have he' : U=T := by simpa only [decode_encode] using he + exact he' ▸ hU + · intro h + exact ⟨encodeSet e T,⟨T,h,rfl⟩,decode_encode e T⟩ + +lemma neighborSets_nodup (S : Set Γ) : (neighborSets e S).Nodup := by + apply (binaryExchanges_nodup (coordinateSet e S)).map_on + intro xs hxs ys hys he + obtain ⟨T,hT,rfl⟩ := (mem_raw_codes e S xs).mp hxs + obtain ⟨U,hU,rfl⟩ := (mem_raw_codes e S ys).mp hys + simpa only [decode_encode] using congrArg (encodeSet e) he + +/-- The state filter is applied after the quadratic coordinate scan. -/ +def neighborStates (gs : List (Γ×Γ)) (S : ChainIndex gs) : List (ChainIndex gs) := + (neighborSets e S.val).filterMap (fun T => if h : ChainState gs T then some ⟨T,h⟩ else none) + +omit [Fintype Γ] in +lemma stateFilter_eq_some (gs : List (Γ×Γ)) (T : Set Γ) (U : ChainIndex gs) : + (if h : ChainState gs T then some (⟨T,h⟩ : ChainIndex gs) else none)=some U ↔ T=U.val := by + by_cases h : ChainState gs T + · simp only [dite_eq_left h,Option.some.injEq] + exact Subtype.ext_iff + · simp only [dite_eq_right h,reduceCtorEq,false_iff] + intro he + exact h (he.symm ▸ U.property) + +lemma mem_neighborStates (gs : List (Γ×Γ)) (S T : ChainIndex gs) : + T∈neighborStates e gs S ↔ ExchangeAdjacent S.val T.val := by + simp only [neighborStates,List.mem_filterMap,stateFilter_eq_some] + constructor + · rintro ⟨U,hU,rfl⟩ + exact (mem_neighborSets e S.val T.val).mp hU + · intro h + exact ⟨T.val,(mem_neighborSets e S.val T.val).mpr h,rfl⟩ + +lemma neighborStates_nodup (gs : List (Γ×Γ)) (S : ChainIndex gs) : + (neighborStates e gs S).Nodup := by + apply List.Nodup.filterMap _ (neighborSets_nodup e S.val) + intro T U V hT hU + have hTV := (stateFilter_eq_some gs T V).mp (Option.mem_def.mp hT) + have hUV := (stateFilter_eq_some gs U V).mp (Option.mem_def.mp hU) + exact hTV.trans hUV.symm + +end Coordinates + +variable {I J : Type} [Fintype I] [Fintype J] + +def coordinateEquiv (A : Instance I J) : (Labels A×Bool) ≃ Fin (Fintype.card (Labels A×Bool)) := + Fintype.equivFin _ + +def neighbors (A : Instance I J) (S : State A) : List (State A) := + neighborStates (coordinateEquiv A) pairs S + +@[simp] theorem mem_neighbors (A : Instance I J) (S T : State A) : + T∈neighbors A S ↔ ExchangeAdjacent S.val T.val := + mem_neighborStates _ _ _ _ + +theorem neighbors_nodup (A : Instance I J) (S : State A) : (neighbors A S).Nodup := + neighborStates_nodup _ _ _ + +theorem neighbors_length (A : Instance I J) (S : State A) : + (neighbors A S).length≤2^proposalBits A := by + have he : (neighbors A S).toFinset=Finset.univ.filter (fun T : State A => ExchangeAdjacent S.val T.val) := by + ext T + simp only [List.mem_toFinset,Finset.mem_filter,Finset.mem_univ,true_and,mem_neighbors] + rw [←List.toFinset_card_of_nodup (neighbors_nodup A S),he] + simpa only [Fintype.card_subtype] using proposal_codes A S + +/-- The selection stage is the actual binary list-index program. -/ +def proposal (A : Instance I J) (S : State A) (bits : Fin (proposalBits A) → Bool) : Option (State A) := + listWordChoice (neighbors A S,List.ofFn bits) + +theorem proposal_mass (A : Instance I J) (S T : State A) : + (mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) (proposal A S)).mass (some T)= + if ExchangeAdjacent S.val T.val then 1/(2:ℚ)^proposalBits A else 0 := by + exact (listWordChoice_mass (neighbors A S) (neighbors_nodup A S) + (proposalBits A) (neighbors_length A S) T).trans (by simp only [mem_neighbors]) + +/-- The explicit arithmetic enumeration changes no proposal probabilities, +including the unused-code outcome. -/ +theorem proposal_law (A : Instance I J) (S : State A) : + mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) (proposal A S)= + mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) + (CompanionBooleanPhase.proposal A S) := by + let p := mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) (proposal A S) + let q := mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) + (CompanionBooleanPhase.proposal A S) + have hs (T : State A) : p.mass (some T)=q.mass (some T) := + (proposal_mass A S T).trans (CompanionBooleanPhase.proposal_mass A S T).symm + change p=q + apply RationalLaw.ext + funext T + cases T with + | some T => exact hs T + | none => + have hp := p.total + have hq := q.total + simp only [Fintype.sum_option] at hp hq + simp_rw [hs] at hp + linarith + +end +end ContingencyTables.CompanionArithmeticProposal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionArithmeticStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionArithmeticStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..903fcee0c3dbe091d38cee96d96dd7830fe9b68b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionArithmeticStep.lean @@ -0,0 +1,143 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionArithmeticProposal +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrajectory + +namespace OAI + +/-! # Coordinate arithmetic for the companion proposal + +The arithmetic and abstract proposals consume equal fixed word lengths. +Oracle and acceptance words are disjoint, and their full one-step laws +agree, giving the same trajectory error bound. +-/ + +namespace ContingencyTables.CompanionArithmeticStep +open CommonBasesFPRAS FirstSuccess ResidualMixture FairBits GridBoundary +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle +open CompanionBooleanPhase RealKernelApproximation +open scoped BigOperators Classical + +noncomputable section + +private def regroup (L P Q : Type*) : (L×(P×Q)) ≃ P×(L×Q) where + toFun b := (b.2.1,(b.1,b.2.2)) + invFun b := (b.2.1,(b.1,b.2.2)) + left_inv _ := rfl + right_inv _ := rfl + +private lemma word_finish_law {B P Q X Z : Type*} + [Fintype B] [Fintype P] [Fintype Q] [Fintype X] [Fintype Z] + [Nonempty B] [Nonempty P] [Nonempty Q] [DecidableEq X] [DecidableEq Z] + (E : B ≃ P×Q) (draw : P → X) (finish : X → Q → Z) : + mapLaw (uniformLaw (α := B)) (fun b => finish (draw (E b).1) (E b).2)= + bindLaw (mapLaw (uniformLaw (α := P)) draw) + (fun x => mapLaw (uniformLaw (α := Q)) (finish x)) := by + have he := map_equiv E (uniformLaw (α := B)) (fun b : P×Q => finish (draw b.1) b.2) + rw [uniform_equiv,←uniform_product] at he + exact he.symm.trans (mapLaw_product_finish _ _ draw finish) + +variable {I J : Type} [Fintype I] [Fintype J] + +abbrev RestWord (A : Instance I J) (C K j k : ℕ) (xi : ℚ) := + (Fin 1 → Bool)×((WeightWord A C K j xi×WeightWord A C K j xi)×(Fin k → Bool)) + +def wordSplit (A : Instance I J) (C K j k : ℕ) (xi : ℚ) : + (Fin (stepBits A C K j k xi) → Bool) ≃ + ((Fin (proposalBits A) → Bool)×RestWord A C K j k xi) := + (stepWordEquiv A C K j k xi).trans (regroup _ _ _) + +def finish (A : Instance I J) (C K j k : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) (U : Option (State A)) (rest : RestWord A C K j k xi) : State A := + if rest.1 0 then S else + match U with + | none => S + | some T => + if rationalThresholdAccept k + (CompanionOracleAcceptance.acceptance A C K j hK hW xi v w S.val T.val rest.2.1) + rest.2.2 then T else S + +def step (A : Instance I J) (C K j k : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) (bits : Fin (stepBits A C K j k xi) → Bool) : State A := + let b := wordSplit A C K j k xi bits + finish A C K j k hK hW xi v w S (CompanionArithmeticProposal.proposal A S b.1) b.2 + +private lemma source_step_eq_finish (A : Instance I J) (C K j k : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) : + (fun bits => finish A C K j k hK hW xi v w S + (CompanionBooleanPhase.proposal A S (wordSplit A C K j k xi bits).1) + (wordSplit A C K j k xi bits).2)= + CompanionBooleanPhase.step A C K j k hK hW xi v w S := by + funext bits + simp only [finish,wordSplit,regroup,CompanionBooleanPhase.step,Equiv.trans_apply,Equiv.coe_fn_mk] + by_cases hlazy : (stepWordEquiv A C K j k xi bits).1 0 = true + · simp only [hlazy,ite_true] + · simp only [hlazy] + cases CompanionBooleanPhase.proposal A S + (stepWordEquiv A C K j k xi bits).2.1 with + | none => simp only + | some T => + simp only + by_cases haccept : rationalThresholdAccept k + (CompanionOracleAcceptance.acceptance A C K j hK hW xi v w S.val T.val + (stepWordEquiv A C K j k xi bits).2.2.1) + (stepWordEquiv A C K j k xi bits).2.2.2 + · simp only [haccept,ite_true] + · simp only [haccept,ite_false] + +/-- Exact equality of complete one-step laws, including all holding +probability. Weight calls and the acceptance coin have not been reused. -/ +theorem step_law (A : Instance I J) (C K j k : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) : + mapLaw (uniformLaw (α := Fin (stepBits A C K j k xi) → Bool)) + (step A C K j k hK hW xi v w S)= + transitionLaw A C K j k hK hW xi v w S := by + have hnew := word_finish_law (wordSplit A C K j k xi) + (CompanionArithmeticProposal.proposal A S) (finish A C K j k hK hW xi v w S) + have hold := word_finish_law (wordSplit A C K j k xi) + (CompanionBooleanPhase.proposal A S) (finish A C K j k hK hW xi v w S) + change mapLaw _ (fun bits => finish A C K j k hK hW xi v w S + (CompanionArithmeticProposal.proposal A S (wordSplit A C K j k xi bits).1) + (wordSplit A C K j k xi bits).2)=_ + rw [hnew,CompanionArithmeticProposal.proposal_law] + rw [source_step_eq_finish] at hold + exact hold.symm + +/-- The full recorded finite-word path therefore retains the proved +joint-history distribution, rather than merely its terminal marginal. -/ +def recordedWalk (A : Instance I J) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) (bits : Fin (n*stepBits A C K j k xi) → Bool) : PathState (State A) N := + wordWalk (fun a b => pathPut a (step A C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n (oracleWalkWordEquiv n (stepBits A C K j k xi) bits) + +theorem recordedWalk_law (A : Instance I J) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : CompanionRationalUpdates.Pair A → CompanionRationalUpdates.Pair A → ℚ) + (S : State A) : + mapLaw (uniformLaw (α := Fin (n*stepBits A C K j k xi) → Bool)) + (recordedWalk A C K j k N n hK hW xi v w S)= + pathLaw A C K j k N n hK hW xi v w S := by + unfold recordedWalk pathLaw + rw [←map_equiv (oracleWalkWordEquiv n (stepBits A C K j k xi)),uniform_equiv] + rw [show mapLaw (uniformLaw (α := Fin n → Fin (stepBits A C K j k xi) → Bool)) + (wordWalk (fun a b => pathPut a (step A C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n)= + wordWalkLaw (fun a b => pathPut a (step A C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n from rfl,wordWalkLaw_eq] + congr 1 + funext a + rw [←mapLaw_comp,step_law] + rfl + +end +end ContingencyTables.CompanionArithmeticStep + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBinIntervals.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBinIntervals.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed438c646d0cdcf669faad367524c91f4c79b4b7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBinIntervals.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleJointLaw +import OAI.Combinatorics.ContingencyTables.Transport.FiniteScaledDraw +import OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts + +namespace OAI + +/-! # Explicit integer intervals inside the companion evaluator bins -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def intervalSize (K N beta : ℕ) : ℕ := + FairBits.endpoint K N (beta+1)-FairBits.endpoint K N beta + +/-- Each offset is sent to its integer by adding the exact lower ceiling +endpoint. This is the actual source interval, not a cardinality-only choice. -/ +def intervalEquiv (K N beta : ℕ) (hK : 0 < K) (hN : 0 < N) (hb : beta < K) : + Fin (intervalSize K N beta) ≃ {z : ℕ // z∈FairBits.fiber K N beta} where + toFun x := ⟨FairBits.endpoint K N beta+x.val,by + rw [FairBits.fiber_eq_interval hK hN hb,Finset.mem_Ico] + have hh := x.isLt + unfold intervalSize at hh + omega⟩ + invFun x := ⟨x.val-FairBits.endpoint K N beta,by + have hx : FairBits.endpoint K N beta ≤ x.val ∧ + x.val < FairBits.endpoint K N (beta+1) := by + simpa only [FairBits.fiber_eq_interval hK hN hb,Finset.mem_Ico] using x.property + unfold intervalSize + omega⟩ + left_inv x := by apply Fin.ext; simp + right_inv x := by + apply Subtype.ext + have hx : FairBits.endpoint K N beta ≤ x.val ∧ + x.val < FairBits.endpoint K N (beta+1) := by + simpa only [FairBits.fiber_eq_interval hK hN hb,Finset.mem_Ico] using x.property + dsimp only + omega + +def binSize (A : Instance I J) (K : ℕ) (v : Grid (I := Fin (dimension A)) K) + (i : Fin (dimension A)) : ℕ := + intervalSize K (freeRange A (index A i)) (naturalBin A v (index A i)) + +theorem binSize_positive (A : Instance I J) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (dimension A)) K) (i : Fin (dimension A)) : + 0 < binSize A K v i := by + have hp := CompanionBinPopulation.coordinate_nonempty K (freeRange A (index A i)) A.d + (naturalBin A v (index A i)) hK A.hd (by + have hb := (A.hlarge (index A i).val.1 (index A i).val.2 (index A i).property.1).1 + unfold freeRange + omega) (naturalBin_lt A v (index A i)) + have hc := Finset.card_pos.mpr hp + have hN : 0 < freeRange A (index A i) := Nat.succ_pos _ + rw [FairBits.fiber_card hK hN (naturalBin_lt A v (index A i))] at hc + exact hc + +def binOffsetsEquiv (A : Instance I J) (K : ℕ) (hK : 0 < K) + (v : Grid (I := Fin (dimension A)) K) : + ((i : Fin (dimension A)) → Fin (binSize A K v i)) ≃ {f // f∈integerFiber A K hK v} := + (Equiv.piCongrRight (fun i => intervalEquiv K (freeRange A (index A i)) + (naturalBin A v (index A i)) hK (Nat.succ_pos _) (naturalBin_lt A v (index A i)))).trans + ((Equiv.piCongrLeft (fun t : FreeCell A.small A.T => + {z : ℕ // z∈FairBits.fiber K (freeRange A t) (naturalBin A v t)}) (index A)).trans + (integerFiberEquiv A K hK v).symm) + +def binOffsetValue (A : Instance I J) (K : ℕ) (hK : 0 < K) + (v : Grid (I := Fin (dimension A)) K) + (x : (i : Fin (dimension A)) → Fin (binSize A K v i)) : FreeIndex A.small A.T A.b := + (binOffsetsEquiv A K hK v x).val + +lemma binOffsetValue_mem (A : Instance I J) (K : ℕ) (hK : 0 < K) + (v : Grid (I := Fin (dimension A)) K) + (x : (i : Fin (dimension A)) → Fin (binSize A K v i)) : + binOffsetValue A K hK v x∈integerFiber A K hK v := (binOffsetsEquiv A K hK v x).property + +def exactBinLaw (A : Instance I J) (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) : RationalLaw (FreeIndex A.small A.T A.b) := + mapLaw (piLaw (fun i => FairBits.uniformIntLaw (binSize A K v i) (binSize_positive A K hK hW v i))) + (binOffsetValue A K hK v) + +def approximateBinLaw (A : Instance I J) (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (h : ℕ) : RationalLaw (FreeIndex A.small A.T A.b) := + mapLaw (piLaw (fun i => FairBits.scaledLaw (binSize A K v i) + (FairBits.offsetBitLength (binSize A K v i) h A.d) (binSize_positive A K hK hW v i))) + (binOffsetValue A K hK v) + +theorem exactBinLaw_mass (A : Instance I J) (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (f : FreeIndex A.small A.T A.b) : + (exactBinLaw A K hK hW v).mass f= + if integerBin A K hK f=v then 1/((integerFiber A K hK v).card:ℚ) else 0 := by + let : ∀ i : Fin (dimension A),Nonempty (Fin (binSize A K v i)) := + fun i => ⟨⟨0,binSize_positive A K hK hW v i⟩⟩ + let : Nonempty {f // f∈integerFiber A K hK v} := + ⟨⟨(integerFiber_nonempty A K hK hW v).choose,(integerFiber_nonempty A K hK hW v).choose_spec⟩⟩ + have hi (i : Fin (dimension A)) : + FairBits.uniformIntLaw (binSize A K v i) (binSize_positive A K hK hW v i)= + uniformLaw (α := Fin (binSize A K v i)) := by + apply RationalLaw.ext + funext x + simp only [FairBits.uniformIntLaw,uniformLaw,uniformMass,Fintype.card_fin] + unfold exactBinLaw + simp_rw [hi] + rw [pi_uniformLaw] + change (mapLaw (uniformLaw (α := (i : Fin (dimension A)) → Fin (binSize A K v i))) + (fun x => (binOffsetsEquiv A K hK v x).val)).mass f=_ + rw [←FairBits.map_equiv (binOffsetsEquiv A K hK v),FairBits.uniform_equiv] + change (∑ x : {g // g∈integerFiber A K hK v}, + if x.val=f then (1:ℚ)/Fintype.card {g // g∈integerFiber A K hK v} else 0)=_ + rw [Fintype.card_coe] + by_cases hf : integerBin A K hK f=v + · rw [ite_eq_left hf] + let g : {g // g∈integerFiber A K hK v} := ⟨f,by simp only [integerFiber,Finset.mem_filter, + Finset.mem_univ,true_and,hf]⟩ + have he (x : {g // g∈integerFiber A K hK v}) : x.val=f ↔ x=g := by + exact ⟨fun h => Subtype.ext h,fun h => congrArg Subtype.val h⟩ + simp_rw [he] + simp + · rw [ite_eq_right hf] + apply Finset.sum_eq_zero + intro x _ + have hxf : x.val≠f := by + intro he + have hx := (Finset.mem_filter.mp x.property).2 + rw [he] at hx + exact hf hx + simp only [hxf,ite_false] + +/-- The explicitly shifted bounded quotient draws have a uniform error +bound for every bin, including the case of no free coordinates. -/ +theorem approximateBinLaw_variation (A : Instance I J) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (dimension A)) K) (h : ℕ) : + variation (approximateBinLaw A K hK hW v h) (exactBinLaw A K hK hW v) ≤ + (A.d:ℚ)/(2:ℚ)^(4*(h+A.d)) := by + apply (variation_map _ _ (binOffsetValue A K hK v)).trans + exact FairBits.dense_offset_product_variation (dimension A) h A.d (binSize A K v) + (binSize_positive A K hK hW v) (ForestScaledPenalty.free_card_le A) + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBinPopulation.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBinPopulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..c393ed2102fd1f66316e78cc52757dfb39c1afcc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBinPopulation.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FairBits +import Mathlib.Algebra.Order.Ring.Pow +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Algebra.Order.BigOperators.GroupWithZero.Finset +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +import Mathlib.Data.Fintype.Pi +import Mathlib.Data.Fintype.BigOperators + +namespace OAI + +/-! # Exact integer bin populations for the companion weight evaluator -/ + +namespace ContingencyTables.CompanionBinPopulation + +open scoped BigOperators Classical + +variable {C : Type*} [Fintype C] + +def coordinatePopulation (B N v : ℕ) : ℚ := B*(FairBits.fiber B N v).card/(N:ℚ) + +def population (B : ℕ) (N : C → ℕ) (v : C → ℕ) : ℚ := + ∏ c,coordinatePopulation B (N c) (v c) + +abbrev Assignments (B : ℕ) (N : C → ℕ) (v : C → ℕ) := + (c : C) → {z : ℕ // z ∈ FairBits.fiber B (N c) (v c)} + +lemma assignment_card (B : ℕ) (N : C → ℕ) (v : C → ℕ) : + Fintype.card (Assignments B N v)=∏ c,(FairBits.fiber B (N c) (v c)).card := by + simp only [Assignments,Fintype.card_pi,Fintype.card_coe] + +/-- The product formula is exactly B^e times the integer bin population +divided by the total number of free assignments. -/ +lemma population_eq_card (B : ℕ) (N : C → ℕ) (v : C → ℕ) : + population B N v=(B:ℚ)^Fintype.card C*(Fintype.card (Assignments B N v):ℚ)/ + (∏ c,(N c:ℚ)) := by + rw [assignment_card] + simp only [population,coordinatePopulation,Finset.prod_div_distrib,Finset.prod_mul_distrib, + Finset.prod_const,Finset.card_univ,Nat.cast_prod] + +lemma coordinate_error (B N d v : ℕ) (hB : 0 < B) (hd : 1 ≤ d) + (hN : 100*d*B ≤ N) (hv : v < B) : + |coordinatePopulation B N v-1| ≤ 1/(100*(d:ℚ)) := by + have hdQ : (0:ℚ) < d := by exact_mod_cast (show 0 < d by omega) + have hNpos : 0 < N := lt_of_lt_of_le (by positivity) hN + have hNQ : (0:ℚ) < N := by exact_mod_cast hNpos + have hBQ : (0:ℚ) < B := by exact_mod_cast hB + have hsize : (100:ℚ)*d*B ≤ N := by exact_mod_cast hN + have heq : coordinatePopulation B N v-1= + ((B:ℚ)/N)*(((FairBits.fiber B N v).card:ℚ)-(N:ℚ)/B) := by + unfold coordinatePopulation + field_simp [hNQ.ne',hBQ.ne'] + rw [heq,abs_mul,abs_of_nonneg (div_nonneg hBQ.le hNQ.le)] + calc + _ ≤ ((B:ℚ)/N)*1 := mul_le_mul_of_nonneg_left + (FairBits.fiber_card_error hB hNpos hv).le (by positivity) + _ = (B:ℚ)/N := mul_one _ + _ ≤ _ := by + rw [div_le_div_iff₀ hNQ (by positivity : (0:ℚ) < 100*d)] + nlinarith + +private lemma reverse_bernoulli (u : ℚ) (hu : 0 ≤ u) (n : ℕ) : + (1+u)^n*(1-(n:ℚ)*u) ≤ 1 := by + induction n with + | zero => simp + | succ n ih => + have haux : (1+u)*(1-((n:ℚ)+1)*u) ≤ 1-(n:ℚ)*u := by + nlinarith [mul_nonneg (show (0:ℚ) ≤ n+1 by positivity) (sq_nonneg u)] + calc + _ = (1+u)^n*((1+u)*(1-((n:ℚ)+1)*u)) := by + rw [pow_succ,Nat.cast_add,Nat.cast_one] + ring + _ ≤ (1+u)^n*(1-(n:ℚ)*u) := + mul_le_mul_of_nonneg_left haux (by positivity) + _ ≤ 1 := ih + +/-- The source's alpha_v lies between one half and two, including the +empty-coordinate product. No large interval is enumerated to establish +the bound; its exact cardinality is the proved ceiling difference. -/ +theorem population_bounds (B d : ℕ) (N : C → ℕ) (v : C → ℕ) + (hB : 0 < B) (hd : 1 ≤ d) (hcard : Fintype.card C ≤ d) + (hN : ∀ c,100*d*B ≤ N c) (hv : ∀ c,v c < B) : + 1/2 ≤ population B N v ∧ population B N v ≤ 2 := by + let u : ℚ := 1/(100*(d:ℚ)) + have hdQ : (1:ℚ) ≤ d := by exact_mod_cast hd + have hu : 0 ≤ u := by dsimp only [u]; positivity + have hu1 : u ≤ 1/100 := by + dsimp only [u] + rw [div_le_div_iff₀ (by positivity : (0:ℚ)<100*d) (by norm_num : (0:ℚ)<100)] + linarith + have hcountQ : (Fintype.card C:ℚ) ≤ d := by exact_mod_cast hcard + have hsum : (Fintype.card C:ℚ)*u ≤ 1/100 := by + dsimp only [u] + rw [← mul_div_assoc,div_le_div_iff₀ (by positivity : (0:ℚ)<100*d) (by norm_num : (0:ℚ)<100)] + linarith + have hfactor (c : C) : 1-u ≤ coordinatePopulation B (N c) (v c) ∧ + coordinatePopulation B (N c) (v c) ≤ 1+u := by + have hh := abs_le.mp (coordinate_error B (N c) d (v c) hB hd (hN c) (hv c)) + constructor <;> linarith + have hpos (c : C) : 0 ≤ coordinatePopulation B (N c) (v c) := by + unfold coordinatePopulation + positivity + have hlo : (1-u)^Fintype.card C ≤ population B N v := by + unfold population + calc + _ = ∏ _c : C,(1-u) := by simp + _ ≤ _ := Finset.prod_le_prod₀ (fun _ _ => by linarith) (fun c _ => (hfactor c).1) + have hup : population B N v ≤ (1+u)^Fintype.card C := by + unfold population + calc + _ ≤ ∏ _c : C,(1+u) := Finset.prod_le_prod₀ (fun c _ => hpos c) (fun c _ => (hfactor c).2) + _ = _ := by simp + have hbern := one_add_mul_le_pow (show (-2:ℚ) ≤ -u by linarith) (Fintype.card C) + have hreverse := reverse_bernoulli u hu (Fintype.card C) + have hpower : 0 ≤ (1+u)^Fintype.card C := by positivity + constructor + · have hh : 1-(Fintype.card C:ℚ)*u ≤ (1-u)^Fintype.card C := by + simpa only [mul_neg,sub_eq_add_neg] using hbern + linarith + · nlinarith + +theorem coordinate_nonempty (B N d v : ℕ) (hB : 0 < B) (hd : 1 ≤ d) + (hN : 100*d*B ≤ N) (hv : v < B) : (FairBits.fiber B N v).Nonempty := by + have hh := (abs_le.mp (coordinate_error B N d v hB hd hN hv)).1 + have hdQ : (1:ℚ) ≤ d := by exact_mod_cast hd + have hu : 1/(100*(d:ℚ)) < 1 := by + rw [div_lt_one (by positivity : (0:ℚ) < 100*d)] + linarith + have hp : 0 < coordinatePopulation B N v := by linarith + apply Finset.card_pos.mp + by_contra hzero + have hz : (FairBits.fiber B N v).card=0 := by omega + simp only [coordinatePopulation,hz,Nat.cast_zero,mul_zero,zero_div] at hp + exact lt_irrefl _ hp + +end ContingencyTables.CompanionBinPopulation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBooleanKernel.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBooleanKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..f26c2aaca089a35b0a37a6b05ac8383fb220e2f0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBooleanKernel.lean @@ -0,0 +1,338 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBooleanPhase +import OAI.Combinatorics.ContingencyTables.Counting.CompanionConcentration +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments +import OAI.Combinatorics.ContingencyTables.Transport.FiniteChainSlowdown +import OAI.Combinatorics.ContingencyTables.Transport.RealPathApproximation + +namespace OAI + +/-! # The actual Boolean phase row and its Metropolis comparison + +The unused proposal words produce precisely a holding slowdown. Fresh +weight estimates and the independent bounded coin contribute only their +proved row error; no sampler-implementation hypothesis is used. +-/ + +namespace ContingencyTables.CompanionBooleanPhase + +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle +open CompanionRationalUpdates CompanionOracleAcceptance CompanionConcentration +open CommonBasesFPRAS FirstSuccess FairBits TwoLiftStates GridBoundary ResidualMixture +open FiniteLawMoments RealKernelApproximation +open scoped BigOperators Classical + +noncomputable section + +private lemma word_probability {X Y : Type*} [Fintype X] [Fintype Y] [Nonempty X] + [DecidableEq Y] (draw : X → Y) (y : Y) : + uniformAverage (fun x => if draw x=y then (1:ℝ) else 0)= + ((mapLaw (uniformLaw (α := X)) draw).mass y:ℝ) := by + rw [word_expectation draw (fun z => if z=y then (1:ℝ) else 0)] + simp [expectation] + +private lemma independent_decision {A B C D : Type*} + [Fintype A] [Fintype B] [Fintype C] [Fintype D] + (P : A → Prop) (Q : B → Prop) (R : C → D → Prop) + [DecidablePred P] [DecidablePred Q] [∀ c d,Decidable (R c d)] : + uniformAverage (fun z : A×(B×(C×D)) => + if P z.1 ∧ Q z.2.1 ∧ R z.2.2.1 z.2.2.2 then (1:ℝ) else 0)= + uniformAverage (fun a => if P a then (1:ℝ) else 0)* + uniformAverage (fun b => if Q b then (1:ℝ) else 0)* + uniformAverage (fun c => uniformAverage (fun d => if R c d then (1:ℝ) else 0)) := by + have he (z : A×(B×(C×D))) : + (if P z.1 ∧ Q z.2.1 ∧ R z.2.2.1 z.2.2.2 then (1:ℝ) else 0)= + (if P z.1 then 1 else 0)* + ((if Q z.2.1 then 1 else 0)*(if R z.2.2.1 z.2.2.2 then 1 else 0)) := by + by_cases hp : P z.1 <;> by_cases hq : Q z.2.1 <;> + by_cases hr : R z.2.2.1 z.2.2.2 <;> simp [hp,hq,hr] + have hs : (∑ a : A,∑ b : B,∑ c : C,∑ d : D, + (if P a then (1:ℝ) else 0)*((if Q b then 1 else 0)*(if R c d then 1 else 0)))= + (∑ a : A,if P a then (1:ℝ) else 0)*(∑ b : B,if Q b then (1:ℝ) else 0)* + (∑ c : C,∑ d : D,if R c d then (1:ℝ) else 0) := by + symm + simp only [Finset.sum_mul,mul_assoc] + simp only [Finset.mul_sum] + simp only [he,uniformAverage,Fintype.sum_prod_type,Fintype.card_prod,Nat.cast_mul, + ←Finset.sum_div] + rw [hs] + ring + +private lemma lazy_probability : + uniformAverage (fun b : Fin 1 → Bool => if b 0=false then (1:ℝ) else 0)=1/2 := by + rw [uniformAverage_fin_succ] + simp only [Fin.cons_zero,uniformAverage_const] + norm_num [uniformAverage] + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Every nontrivial output probability factors into its lazy bit, +unique neighbor code, and the actual rounded two-oracle acceptance. -/ +theorem transition_mass (A : Instance I J) (C : ℕ) (hC : 0 + (rationalThresholdMass k + (acceptance A C K j hK hW xi v w S.val T.val b):ℝ)) + else 0 := by + have hp : uniformAverage (fun b : Fin (proposalBits A) → Bool => + if proposal A S b=some T then (1:ℝ) else 0)= + if ExchangeAdjacent S.val T.val then 1/(2:ℝ)^proposalBits A else 0 := by + rw [word_probability,proposal_mass] + split_ifs <;> simp + have ha (b : WeightWord A C K j xi×WeightWord A C K j xi) : + uniformAverage (fun coin : Fin k → Bool => + if rationalThresholdAccept k + (acceptance A C K j hK hW xi v w S.val T.val b) coin then (1:ℝ) else 0)= + (rationalThresholdMass k + (acceptance A C K j hK hW xi v w S.val T.val b):ℝ) := by + exact rationalThreshold_expectation k _ + (acceptance_bounds A C hC K j hK hW hB hj xi hx0 hx1 v w hw S.val T.val b).1 + (acceptance_bounds A C hC K j hK hW hB hj xi hx0 hx1 v w hw S.val T.val b).2 + calc + _ = uniformAverage (fun bits => if step A C K j k hK hW xi v w S bits=T then (1:ℝ) else 0) := + (word_probability _ T).symm + _ = uniformAverage (fun b : (Fin 1 → Bool)×((Fin (proposalBits A) → Bool)× + ((WeightWord A C K j xi×WeightWord A C K j xi)×(Fin k → Bool))) => + if b.1 0=false ∧ proposal A S b.2.1=some T ∧ + rationalThresholdAccept k + (acceptance A C K j hK hW xi v w S.val T.val b.2.2.1) b.2.2.2 + then (1:ℝ) else 0) := by + simp_rw [step_eq_iff A C K j k hK hW xi v w S T hST] + have he := uniformAverage_equiv (stepWordEquiv A C K j k xi) + (fun b : (Fin 1 → Bool)×((Fin (proposalBits A) → Bool)× + ((WeightWord A C K j xi×WeightWord A C K j xi)×(Fin k → Bool))) => + if b.1 0=false ∧ proposal A S b.2.1=some T ∧ + rationalThresholdAccept k + (acceptance A C K j hK hW xi v w S.val T.val b.2.2.1) b.2.2.2 + then (1:ℝ) else 0) + convert he using 1 + _ = _ := by + rw [independent_decision (fun b : Fin 1 → Bool => b 0=false) + (fun b : Fin (proposalBits A) → Bool => proposal A S b=some T) + (fun b coin => rationalThresholdAccept k + (acceptance A C K j hK hW xi v w S.val T.val b) coin),lazy_probability,hp] + simp_rw [ha] + split_ifs <;> ring + +/-- The exact target row is the source Metropolis chain, slowed by its +dyadic neighbor-code padding. The stationary distribution is unchanged. -/ +def referenceChain (A : Instance I J) (j : ℕ) (hp : 0 (w p q:ℝ)) (CompanionAnnealing.weight A j) + (fun p q => by exact_mod_cast hw p q) (CompanionAnnealing.weight_positive A j) + +private lemma chain_eq {X : Type*} [Fintype X] (C D : FiniteChain X) + (hP : C.P=D.P) (hpi : C.π=D.π) : C=D := by + cases C + cases D + dsimp only at hP hpi + cases hP + cases hpi + rfl + +/-- The degree completion used to prove the signature and concentration +theorems leaves every state and transition of the literal chain intact. -/ +theorem referenceChain_eq_completed (A : Instance I J) (j : ℕ) + (hp : 0 (w p q:ℝ)) + (DegreeCompletion.completeDegree (CompanionAnnealing.weight A j) + (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) + (fun p q => by exact_mod_cast hw p q) + (DegreeCompletion.completeDegree_positive _ _ (actual_degree A j).1) := by + have he (U : State A) : + chainWeight pairs (fun p q => (w p q:ℝ)) + (DegreeCompletion.completeDegree (CompanionAnnealing.weight A j) + (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) U.val= + chainWeight pairs (fun p q => (w p q:ℝ)) (CompanionAnnealing.weight A j) U.val := by + simp only [chainWeight,DegreeCompletion.completeDegree, + U.property.ncard PairedLabels.fresh PairedLabels.cover,ite_true] + apply chain_eq + · funext S T + dsimp only [referenceChain,metropolisChain,FiniteChain.ofMoves] + simp only [metropolisMove,he] + · funext S + dsimp only [referenceChain,metropolisChain,FiniteChain.ofMoves] + rw [ObservableBounds.chainTotal_completion _ _ _ PairedLabels.fresh PairedLabels.cover,he] + +def targetChain (A : Instance I J) (j : ℕ) (hp : 0 p y-q y) (Finset.univ.erase x) + have he := Finset.sum_erase_add (Finset.univ : Finset X) (fun y => |p y-q y|) + (Finset.mem_univ x) + rw [hd,abs_neg] at he + unfold distance + linarith + +private lemma average_abs {X : Type*} [Fintype X] (f : X → ℝ) : + |uniformAverage f|≤uniformAverage (fun x => |f x|) := by + unfold uniformAverage + rw [abs_div,abs_of_nonneg (show (0:ℝ)≤Fintype.card X from Nat.cast_nonneg _)] + exact div_le_div_of_nonneg_right (Finset.abs_sum_le_sum_abs f Finset.univ) + (Nat.cast_nonneg _) + +/-- The complete transition row loses at most half the acceptance error. +The diagonal is controlled by conservation of probability, rather than +an additional independent error assumption. -/ +theorem row_distance (A : Instance I J) (C : ℕ) (hC : 0 ((transitionLaw A C K j k hK hW xi v w S).mass T:ℝ)) + ((targetChain A j hp w hw).P S)≤(6*(xi:ℝ)+1/(2:ℝ)^k)/2 := by + let e : ℝ := 6*(xi:ℝ)+1/(2:ℝ)^k + let a : ℝ := 1/(2*(2:ℝ)^proposalBits A) + have he : 0≤e := by dsimp only [e]; positivity + have ha : 0≤a := by dsimp only [a]; positivity + have hpnt (T : State A) (hST : S≠T) : + |((transitionLaw A C K j k hK hW xi v w S).mass T:ℝ)- + (targetChain A j hp w hw).P S T|≤ + if ExchangeAdjacent S.val T.val then a*e else 0 := by + rw [transition_mass A C hC K j k hK hW hB hj xi hx0 + (by linarith) v w hw S T hST,target_mass A j hp w hw S T hST] + by_cases h : ExchangeAdjacent S.val T.val + · simp only [h,ite_true] + rw [←mul_sub,abs_mul,abs_of_nonneg ha] + apply mul_le_mul_of_nonneg_left _ ha + rw [←uniformAverage_sub_const] + exact (average_abs _).trans + (average_acceptance_error A C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v w hw S.val T.val) + · simp [h] + have hm : (∑ T,((transitionLaw A C K j k hK hW xi v w S).mass T:ℝ))= + ∑ T,(targetChain A j hp w hw).P S T := by + rw [(targetChain A j hp w hw).stochastic] + exact_mod_cast (transitionLaw A C K j k hK hW xi v w S).total + have hc : ((Finset.univ.filter (fun T : State A => ExchangeAdjacent S.val T.val)).card:ℝ)≤ + (2:ℝ)^proposalBits A := by + have hh := proposal_codes A S + rw [Fintype.card_subtype] at hh + exact_mod_cast hh + calc + _ ≤ ∑ T∈Finset.univ.erase S, + |((transitionLaw A C K j k hK hW xi v w S).mass T:ℝ)- + (targetChain A j hp w hw).P S T| := distance_le_off_diagonal _ _ S hm + _ ≤ ∑ T∈Finset.univ.erase S, + if ExchangeAdjacent S.val T.val then a*e else 0 := by + apply Finset.sum_le_sum + intro T hT + exact hpnt T (Finset.mem_erase.mp hT).1.symm + _ ≤ ∑ T : State A,if ExchangeAdjacent S.val T.val then a*e else 0 := by + apply Finset.sum_le_sum_of_subset_of_nonneg (Finset.erase_subset _ _) + intro T _ _ + split_ifs <;> positivity + _ = ((Finset.univ.filter (fun T : State A => ExchangeAdjacent S.val T.val)).card:ℝ)*(a*e) := by + rw [←Finset.sum_filter] + simp + _ ≤ (2:ℝ)^proposalBits A*(a*e) := mul_le_mul_of_nonneg_right hc (mul_nonneg ha he) + _ = e/2 := by dsimp only [a]; field_simp + +def pathLaw (A : Instance I J) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) : + RationalLaw (PathState (State A) N) := + walkLaw (liftRational (transitionLaw A C K j k hK hW xi v w) + (fun a : PathState (State A) N => pathRead a) + (fun (a : PathState (State A) N) (T : State A) => pathPut a T)) (pathInitial N S) n + +def targetPathMass (A : Instance I J) (j : ℕ) (hp : 0 pathRead a) + (fun (a : PathState (State A) N) (T : State A) => pathPut a T)).power n).P (pathInitial N S) + +/-- The error controls the whole recorded phase history, not merely its +last state. Every step uses a disjoint fresh oracle/acceptance word. -/ +theorem path_distance_bound (A : Instance I J) (C : ℕ) (hC : 0 ((pathLaw A C K j k N n hK hW xi v w S).mass b:ℝ)) + (targetPathMass A j hp w hw N n S)≤n*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + unfold pathLaw targetPathMass + apply walk_distance + intro a + apply (lifted_row_distance (transitionLaw A C K j k hK hW xi v w) + (targetChain A j hp w hw).kernel + (fun a : PathState (State A) N => pathRead a) + (fun (a : PathState (State A) N) (T : State A) => pathPut a T) a).trans + exact row_distance A C hC K j k hK hW hB hj xi hx0 hx1 hPL hCheeger v hp w hw (pathRead a) + +/-- The same finite step word records the newly sampled state, so the +history law is physically realized by the concatenated step words. -/ +def recordedWalk (A : Instance I J) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) + (bits : Fin (n*stepBits A C K j k xi) → Bool) : PathState (State A) N := + wordWalk (fun a b => pathPut a (step A C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n (oracleWalkWordEquiv n (stepBits A C K j k xi) bits) + +theorem recordedWalk_law (A : Instance I J) (C K j k N n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) : + mapLaw (uniformLaw (α := Fin (n*stepBits A C K j k xi) → Bool)) + (recordedWalk A C K j k N n hK hW xi v w S)= + walkLaw (liftRational (transitionLaw A C K j k hK hW xi v w) pathRead pathPut) + (pathInitial N S) n := by + unfold recordedWalk + rw [←map_equiv (oracleWalkWordEquiv n (stepBits A C K j k xi)),uniform_equiv] + rw [show mapLaw (uniformLaw (α := Fin n → Fin (stepBits A C K j k xi) → Bool)) + (wordWalk (fun a b => pathPut a (step A C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n)=wordWalkLaw + (fun a b => pathPut a (step A C K j k hK hW xi v w (pathRead a) b)) + (pathInitial N S) n from rfl,wordWalkLaw_eq] + apply congrArg (fun Q => walkLaw Q (pathInitial N S) n) + funext a + exact (mapLaw_comp (uniformLaw (α := Fin (stepBits A C K j k xi) → Bool)) + (step A C K j k hK hW xi v w (pathRead a)) (pathPut a)).symm + +end + +end ContingencyTables.CompanionBooleanPhase + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBooleanPhase.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBooleanPhase.lean new file mode 100644 index 0000000000000000000000000000000000000000..1aba84796b84c3d82521c788a4e61770cdfb2035 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBooleanPhase.lean @@ -0,0 +1,161 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleAcceptance +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawDecidableEq +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordWalk + +namespace OAI + +/-! # The companion phase walk driven by disjoint bounded Boolean words -/ + +namespace ContingencyTables.CompanionBooleanPhase + +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle CompanionRationalUpdates +open CommonBasesFPRAS FirstSuccess FairBits TwoLiftStates GridBoundary ResidualMixture +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +abbrev State (A : Instance I J) := ChainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) + +def proposalBits (A : Instance I J) : ℕ := Nat.clog 2 (Fintype.card (Labels A)^2) + +lemma proposal_codes (A : Instance I J) (S : State A) : + Fintype.card {T : State A // ExchangeAdjacent S.val T.val} ≤ 2^proposalBits A := by + rw [Fintype.card_subtype] + have hh := chain_neighbors_card pairs PairedLabels.fresh PairedLabels.cover S + simp only [PairedLabels.length] at hh + exact hh.trans (Nat.le_pow_clog (by decide) _) + +/-- Each valid exchange neighbor has one code. Every unused code holds +the current state; the full transition has another independent lazy bit. -/ +def proposal (A : Instance I J) (S : State A) (bits : Fin (proposalBits A) → Bool) : Option (State A) := + subsetBitDraw (fun T : State A => ExchangeAdjacent S.val T.val) + (proposalBits A) (proposal_codes A S) bits + +lemma proposal_mass (A : Instance I J) (S T : State A) : + (mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) (proposal A S)).mass (some T)= + if ExchangeAdjacent S.val T.val then 1/(2:ℚ)^proposalBits A else 0 := by + exact subsetBitDraw_mass_decidableEq (inferInstance : DecidableEq (Option (State A))) + (fun T : State A => ExchangeAdjacent S.val T.val) (proposalBits A) (proposal_codes A S) T + +def stepBits (A : Instance I J) (C K j k : ℕ) (xi : ℚ) : ℕ := + 1+(proposalBits A+((medianEstimatorBits A C K j xi xi+ + medianEstimatorBits A C K j xi xi)+k)) + +def stepWordEquiv (A : Instance I J) (C K j k : ℕ) (xi : ℚ) : + (Fin (stepBits A C K j k xi) → Bool) ≃ + ((Fin 1 → Bool)×((Fin (proposalBits A) → Bool)× + ((WeightWord A C K j xi×WeightWord A C K j xi)×(Fin k → Bool)))) := + (splitWordEquiv _ _).trans (Equiv.prodCongr (Equiv.refl _) + ((splitWordEquiv _ _).trans (Equiv.prodCongr (Equiv.refl _) + ((splitWordEquiv _ _).trans (Equiv.prodCongr (splitWordEquiv _ _) (Equiv.refl _)))))) + +/-- The realized step evaluates the current and proposed weights from +separate words, then uses a third independent word for its rational coin. -/ +def step (A : Instance I J) (C K j k : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : State A) (bits : Fin (stepBits A C K j k xi) → Bool) : State A := + let b := stepWordEquiv A C K j k xi bits + if b.1 0 then S else + match proposal A S b.2.1 with + | none => S + | some T => + if rationalThresholdAccept k + (CompanionOracleAcceptance.acceptance A C K j hK hW xi v w S.val T.val b.2.2.1) b.2.2.2 + then T else S + +/-- A nontrivial move uses exactly its proposal code and the fresh +acceptance experiment. Failed codes and the independent holding bit +contribute only to the diagonal. -/ +theorem step_eq_iff (A : Instance I J) (C K j k : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S T : State A) (hST : S ≠ T) (bits : Fin (stepBits A C K j k xi) → Bool) : + step A C K j k hK hW xi v w S bits=T ↔ + (stepWordEquiv A C K j k xi bits).1 0=false ∧ + proposal A S (stepWordEquiv A C K j k xi bits).2.1=some T ∧ + rationalThresholdAccept k + (CompanionOracleAcceptance.acceptance A C K j hK hW xi v w S.val T.val + (stepWordEquiv A C K j k xi bits).2.2.1) + (stepWordEquiv A C K j k xi bits).2.2.2 := by + dsimp only [step] + generalize stepWordEquiv A C K j k xi bits = b + cases b.1 0 with + | true => simp [hST] + | false => + cases proposal A S b.2.1 with + | none => simp [hST] + | some U => + by_cases hUT : U=T + · subst U + simp [hST] + · by_cases ha : rationalThresholdAccept k + (CompanionOracleAcceptance.acceptance A C K j hK hW xi v w S.val U.val b.2.2.1) b.2.2.2 + · simp [hUT,ha] + · simp [hST,hUT,ha] + +def transitionLaw (A : Instance I J) (C K j k : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) : + RationalLaw (State A) := + mapLaw (uniformLaw (α := Fin (stepBits A C K j k xi) → Bool)) + (step A C K j k hK hW xi v w S) + +def walk (A : Instance I J) (C K j k n : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) + (bits : Fin (n*stepBits A C K j k xi) → Bool) : State A := + wordWalk (step A C K j k hK hW xi v w) S n + (oracleWalkWordEquiv n (stepBits A C K j k xi) bits) + +/-- The actual flattened word gives independent repeated transitions; +its law follows from the finite-word walk construction. -/ +theorem walk_law (A : Instance I J) (C K j k n : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) (S : State A) : + mapLaw (uniformLaw (α := Fin (n*stepBits A C K j k xi) → Bool)) + (walk A C K j k n hK hW xi v w S)= + walkLaw (transitionLaw A C K j k hK hW xi v w) S n := by + unfold walk + rw [←map_equiv (oracleWalkWordEquiv n (stepBits A C K j k xi)),uniform_equiv] + exact wordWalkLaw_eq _ _ _ + +private lemma dyadic_size_le_twice (n : ℕ) (hn : 0 < n) : 2^Nat.clog 2 n ≤ 2*n := by + by_cases h1 : n=1 + · subst n + norm_num + have hgt : 1 < n := by omega + have hm : 0 < Nat.clog 2 n := Nat.clog_pos (by decide) hgt + have hp := Nat.pow_pred_clog_lt_self (by decide : 1<2) hgt + have he : Nat.clog 2 n=(Nat.clog 2 n).pred+1 := (Nat.succ_pred_eq_of_pos hm).symm + calc + _ = 2*2^(Nat.clog 2 n).pred := by + conv_lhs => rw [he,pow_succ] + ring + _ ≤ 2*n := Nat.mul_le_mul_left 2 hp.le + +def slowdown (A : Instance I J) : ℝ := + (Fintype.card (Labels A):ℝ)^2/(2:ℝ)^proposalBits A + +/-- The unused proposal codes slow the source chain by at most two; +they do not change its stationary law. -/ +theorem slowdown_bounds (A : Instance I J) (hp : 0 < Fintype.card (Labels A)) : + (1/2:ℝ) ≤ slowdown A ∧ slowdown A ≤ 1 := by + have hn : 0 < Fintype.card (Labels A)^2 := pow_pos hp _ + have hl := dyadic_size_le_twice (Fintype.card (Labels A)^2) hn + have hu := Nat.le_pow_clog (by decide : 1<2) (Fintype.card (Labels A)^2) + have hlR : (2:ℝ)^proposalBits A ≤ 2*(Fintype.card (Labels A):ℝ)^2 := by exact_mod_cast hl + have huR : (Fintype.card (Labels A):ℝ)^2 ≤ (2:ℝ)^proposalBits A := by exact_mod_cast hu + unfold slowdown + constructor + · rw [le_div_iff₀ (by positivity : (0:ℝ)<2^proposalBits A)] + linarith + · exact (div_le_one (by positivity)).mpr huR + +end + +end ContingencyTables.CompanionBooleanPhase + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBoundedWalkProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBoundedWalkProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ab769178e382b3a01f96dea776818e11fb1ceec --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBoundedWalkProgram.lean @@ -0,0 +1,186 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisWordProgram +import OAI.Combinatorics.ContingencyTables.Transport.BoundedProfileWalk + +namespace OAI + +/-! # Polynomial iteration of the physical companion transition + +Clipping is redundant on the encoded binary chain states. It gives a +uniform bound on malformed inputs, so repeated calls remain polynomial. +-/ + +namespace ContingencyTables.CompanionBoundedWalkProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial + +abbrev Fixed := (CompanionMetropolisProgram.Frame × ℕ) × List ℕ +abbrev State := Fixed × List ℕ + +def transitionInput (z : List Bool × State) : CompanionMetropolisWordProgram.Input := + ((z.2.1.1,z.2.2),z.1) +def transitionInputRealizer : Realizer transitionInput := + pair (pair (composition (composition second first) first) (composition second second)) first +lemma polynomial_transitionInput : PolynomialTime transitionInputRealizer := + polynomial_pair (polynomial_pair (by tree_poly) (polynomial_composition polynomial_second polynomial_second)) + polynomial_first + +def candidate (z : List Bool × State) : List ℕ := CompanionMetropolisWordProgram.output (transitionInput z) +def candidateRealizer : Realizer candidate := + composition (f := transitionInput) (g := CompanionMetropolisWordProgram.output) + transitionInputRealizer CompanionMetropolisWordProgram.outputRealizer +lemma polynomial_candidate : PolynomialTime candidateRealizer := + polynomial_composition polynomial_transitionInput CompanionMetropolisWordProgram.polynomial_output + +def bound (z : List Bool × State) : ℕ := z.2.1.2.length +def boundRealizer : Realizer bound := + composition (composition (composition second first) second) listLength +lemma polynomial_bound : PolynomialTime boundRealizer := + polynomial_composition (polynomial_composition (polynomial_composition + polynomial_second polynomial_first) polynomial_second) polynomial_listLength + +attribute [local irreducible] candidate + +def next (z : List Bool × State) : List ℕ := ProfilePrograms.capView ((bound z,1),candidate z) +def nextRealizer : Realizer next := + composition (f := fun z : List Bool × State => ((bound z,1),candidate z)) + (g := ProfilePrograms.capView) (pair (pair boundRealizer (constant 1)) candidateRealizer) + ProfilePrograms.capViewRealizer +lemma polynomial_next : PolynomialTime nextRealizer := + polynomial_composition (polynomial_pair (polynomial_pair polynomial_bound (polynomial_constant 1)) + polynomial_candidate) ProfilePrograms.polynomial_capView + +def advance (z : List Bool × State) : State := (z.2.1,next z) +def advanceRealizer : Realizer advance := pair (composition second first) nextRealizer +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) polynomial_next + +lemma advance_fixed (word : List Bool) (state : State) : (advance (word,state)).1=state.1 := rfl + +lemma advance_weight (word : List Bool) (state : State) (S : ℕ) (hs : weight state.1 ≤ S) : + weight (advance (word,state)) ≤ 10*(S+1) := by + have hb : state.1.2.length ≤ S := + (list_length_le_weight _).trans ((weight_snd state.1).trans hs) + have hn := ProfilePrograms.capView_weight state.1.2.length 1 (candidate (word,state)) + change weight (next (word,state)) ≤ _ at hn + norm_num only [Nat.size_one] at hn + change weight (state.1,next (word,state)) ≤ _ + rw [weight_prod] + omega + +def walk (z : State × List (List Bool)) : State := + z.2.foldl (fun state bits => advance (bits,state)) z.1 +def walkRealizer : Realizer walk := composition (pair second first) (fold advanceRealizer) + +lemma fold_fixed (words : List (List Bool)) (state : State) : + (words.foldl (fun state bits => advance (bits,state)) state).1=state.1 := by + induction words generalizing state with + | nil => rfl + | cons word words ih => exact ih _ + +lemma fold_weight (words : List (List Bool)) (state : State) (S : ℕ) (hs : weight state ≤ S) : + weight (words.foldl (fun state bits => advance (bits,state)) state) ≤ 10*(S+1) := by + induction words using List.reverseRecOn with + | nil => simpa using hs.trans (by omega : S ≤ 10*(S+1)) + | append_singleton words word _ => + rw [List.foldl_append] + simp only [List.foldl_cons,List.foldl_nil] + apply advance_weight + rw [fold_fixed] + exact (weight_fst state).trans hs + +theorem polynomial_walk : PolynomialTime walkRealizer := by + apply polynomial_composition (polynomial_pair polynomial_second polynomial_first) + apply polynomial_fold polynomial_advance (10*(X+1)) + intro words state pre post _ + simp only [eval_mul,eval_ofNat,eval_add,eval_X,eval_one] + exact fold_weight pre state (weight (words,state)) (weight_snd (words,state)) + +abbrev RecordState := State × List (List ℕ) + +def recordAdvance (z : List Bool × RecordState) : RecordState := + let nextState := advance (z.1,z.2.1) + (nextState,nextState.2::z.2.2) +def recordAdvanceRealizer : Realizer recordAdvance := by + let nxt : Realizer (fun z : List Bool × RecordState => advance (z.1,z.2.1)) := + composition (f := fun z : List Bool × RecordState => (z.1,z.2.1)) (g := advance) + (pair first (composition second first)) advanceRealizer + exact pair nxt (composition (pair (composition nxt second) (composition second second)) listCons) +lemma polynomial_recordAdvance : PolynomialTime recordAdvanceRealizer := by + unfold recordAdvanceRealizer + have hn : PolynomialTime (composition + (f := fun z : List Bool × RecordState => (z.1,z.2.1)) (g := advance) + (pair first (composition second first)) advanceRealizer) := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) polynomial_advance + exact polynomial_pair hn (polynomial_composition (polynomial_pair + (polynomial_composition hn polynomial_second) (polynomial_composition polynomial_second polynomial_second)) + polynomial_listCons) + +lemma recordFold_bounds_fixed (words : List (List Bool)) (state : RecordState) (S : ℕ) + (hfixed : weight state.1.1 ≤ S) (hcurrent : weight state.1 ≤ 10*(S+1)) : + let out := words.foldl (fun state bits => recordAdvance (bits,state)) state + out.1.1=state.1.1 ∧ weight out.1 ≤ 10*(S+1) ∧ + weight out.2 ≤ weight state.2+words.length*(10*(S+1)+1) := by + induction words generalizing state with + | nil => exact ⟨rfl,hcurrent,by simp⟩ + | cons word words ih => + have hn := advance_weight word state.1 S hfixed + have hh := ih (recordAdvance (word,state)) hfixed hn + simp only [List.foldl_cons] + dsimp only at hh ⊢ + refine ⟨hh.1,hh.2.1,?_⟩ + have hb : weight (advance (word,state.1)).2 ≤ 10*(S+1) := (weight_snd _).trans hn + simp only [recordAdvance,weight_cons,List.length_cons] at hh ⊢ + simp only [Nat.add_mul,Nat.one_mul] at * + omega + +lemma recordFold_weight (words : List (List Bool)) (state : RecordState) (S : ℕ) + (hw : words.length ≤ S) (hs : weight state ≤ S) : + weight (words.foldl (fun state bits => recordAdvance (bits,state)) state) ≤ 30*(S+1)^2 := by + have hc : weight state.1 ≤ S := (weight_fst state).trans hs + have hf : weight state.1.1 ≤ S := (weight_fst state.1).trans hc + have hh : weight state.2 ≤ S := (weight_snd state).trans hs + have hb := recordFold_bounds_fixed words state S hf (hc.trans (by omega)) + dsimp only at hb + rw [weight_prod] + have hmul : words.length*(10*(S+1)+1) ≤ S*(10*(S+1)+1) := + Nat.mul_le_mul_right _ hw + nlinarith [hb.2.1,hb.2.2] + +def recordWalk (z : RecordState × List (List Bool)) : RecordState := + z.2.foldl (fun state bits => recordAdvance (bits,state)) z.1 +def recordWalkRealizer : Realizer recordWalk := + composition (pair second first) (fold recordAdvanceRealizer) +theorem polynomial_recordWalk : PolynomialTime recordWalkRealizer := by + apply polynomial_composition (polynomial_pair polynomial_second polynomial_first) + apply polynomial_fold polynomial_recordAdvance (30*(X+1)^2) + intro words state pre post he + simp only [eval_mul,eval_ofNat,eval_add,eval_X,eval_one,eval_pow] + apply recordFold_weight pre state (weight (words,state)) + · have hp : pre.length ≤ words.length := by rw [he,List.length_append]; omega + exact hp.trans ((list_length_le_weight words).trans (weight_fst (words,state))) + · exact weight_snd (words,state) + +def initialRecord (state : State) : RecordState := (state,[state.2]) +def initialRecordRealizer : Realizer initialRecord := + pair identity (composition (pair second (constant ([] : List (List ℕ)))) listCons) +lemma polynomial_initialRecord : PolynomialTime initialRecordRealizer := + polynomial_pair polynomial_identity (polynomial_composition + (polynomial_pair polynomial_second (polynomial_constant [])) polynomial_listCons) + +def history (z : State × List (List Bool)) : List (List ℕ) := + (recordWalk (initialRecord z.1,z.2)).2.reverse +def historyRealizer : Realizer history := + composition (f := fun z : State × List (List Bool) => (initialRecord z.1,z.2)) + (g := fun z : RecordState × List (List Bool) => (recordWalk z).2.reverse) + (pair (composition first initialRecordRealizer) second) + (composition (composition recordWalkRealizer second) reverse) +theorem polynomial_history : PolynomialTime historyRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_initialRecord) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_recordWalk polynomial_second) + polynomial_reverse) + +end ContingencyTables.CompanionBoundedWalkProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBoundedWalkSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBoundedWalkSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d215ead3f00dc662df7f9c62b4e2b53bf16f419 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionBoundedWalkSemantics.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBoundedWalkProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisWordSemantics +import OAI.Combinatorics.ContingencyTables.Machines.FiniteEncodedHistory + +namespace OAI + +/-! # The bounded physical recorder preserves the complete phase history -/ + +namespace ContingencyTables.CompanionBoundedWalkProgram + +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionOracleDensity CompanionWeightOracle +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram CommonBasesFPRAS +open CompanionBooleanPhase (State) +open FiniteObservableTransport TwoLiftStates GridBoundary +open scoped Classical + +def codeStep (fixed : Fixed) (code : List ℕ) (bits : List Bool) : List ℕ := + next (bits,(fixed,code)) + +lemma recordFold_eq (fixed : Fixed) (words : List (List Bool)) (code : List ℕ) + (past : List (List ℕ)) : + words.foldl (fun state bits => recordAdvance (bits,state)) ((fixed,code),past)= + let out := words.foldl (fun state bits => + let d := codeStep fixed state.1 bits; (d,d::state.2)) (code,past) + ((fixed,out.1),out.2) := by + induction words generalizing code past with + | nil => rfl + | cons word words ih => + simpa only [List.foldl_cons,recordAdvance,advance,codeStep] using + ih (next (word,(fixed,code))) (next (word,(fixed,code))::past) + +lemma history_eq_trace (fixed : Fixed) (code : List ℕ) (words : List (List Bool)) : + history ((fixed,code),words)=traceStates (codeStep fixed) code words := by + unfold history recordWalk initialRecord + rw [recordFold_eq] + exact traceStates_fold (codeStep fixed) words code + +noncomputable section +variable {m n : ℕ} + +lemma cap_encode (A : Instance (Fin m) (Fin n)) (S T : Set (Labels A × Bool)) : + ProfilePrograms.capView (((encodeSet (coordinateOrder A) S).length,1), + encodeSet (coordinateOrder A) T)=encodeSet (coordinateOrder A) T := by + apply ProfilePrograms.capView_eq + · simp only [encodeSet,List.length_ofFn] + · intro a ha + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp ha + unfold ProfilePrograms.setProfile + split_ifs <;> omega + +/-- The all-input clipping has no effect on a valid encoded transition; +in particular its full row law agrees with the reference phase step. -/ +theorem codeStep_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S₀ S : CompanionBooleanPhase.State A) : + let cfg := RootedLabelWeightProgram.config A C K j xi xi z v degree depth + let fixed : Fixed := (((cfg,matrixCode w),k),encodeSet (coordinateOrder A) S₀.val) + SameLaw (fun bits : Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool => + codeStep fixed (encodeSet (coordinateOrder A) S.val) (List.ofFn bits)) + (fun bits => encodeSet (coordinateOrder A) + (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) C K j k hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S bits).val) := by + dsimp only + have h := CompanionMetropolisWordProgram.sameLaw_flat A C K j k hC hj hK hW hB + xi hxi z v degree depth hdegree hdepth w S + have hm := h.map (fun code => ProfilePrograms.capView + (((encodeSet (coordinateOrder A) S₀.val).length,1),code)) + intro phi + simpa only [codeStep,next,bound,candidate,transitionInput,CompanionMetropolisWordProgram.packed, + cap_encode] using hm phi + +/-- The physical list recorder and the full reference state history have +the same law, before any first-return scan or phase statistic is applied. -/ +theorem history_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : CompanionBooleanPhase.State A) (N : ℕ) : + let cfg := RootedLabelWeightProgram.config A C K j xi xi z v degree depth + let fixed : Fixed := (((cfg,matrixCode w),k),encodeSet (coordinateOrder A) S.val) + SameLaw (fun words : Fin N → (Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool) => + history ((fixed,encodeSet (coordinateOrder A) S.val),List.ofFn (fun i => List.ofFn (words i)))) + (fun words : Fin N → (Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool) => (traceStates + (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) C K j k hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w)) S (List.ofFn words)).map + (fun T => encodeSet (coordinateOrder A) T.val)) := by + dsimp only + let cfg := RootedLabelWeightProgram.config A C K j xi xi z v degree depth + let fixed : Fixed := (((cfg,matrixCode w),k),encodeSet (coordinateOrder A) S.val) + have ht := traceStates_sameLaw + (fun code bits => codeStep fixed code (List.ofFn bits)) + (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) C K j k hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w)) + (fun T : CompanionBooleanPhase.State A => encodeSet (coordinateOrder A) T.val) + (codeStep_sameLaw A C K j k hC hj hK hW hB xi hxi z v degree depth hdegree hdepth w S) S N + intro phi + rw [show (fun words : Fin N → (Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool) => + phi (history ((fixed,encodeSet (coordinateOrder A) S.val),List.ofFn (fun i => List.ofFn (words i)))))= + (fun words => phi (traceStates (fun code bits => codeStep fixed code (List.ofFn bits)) + (encodeSet (coordinateOrder A) S.val) (List.ofFn words))) by + funext words + rw [history_eq_trace] + have hm : List.ofFn (fun i => List.ofFn (words i))=(List.ofFn words).map List.ofFn := by + rw [List.map_ofFn] + rfl + rw [hm,traceStates_map]] + exact ht phi + +end +end ContingencyTables.CompanionBoundedWalkProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalEncoding.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..f157ab1cf440fd6fa2e6aab5be16ecdcf5dcf0c9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalEncoding.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CanonicalInitialEncoding +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialDraw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOrderedProposal + +namespace OAI + +/-! # A common explicit encoding for initialization and proposals + +Cells follow `cellEnum`, their copies follow increasing finite indices, +and each copy contributes its false and true coordinates consecutively. +The polynomial initializer computes exactly this encoding of the actual +initial draw. The same order may therefore be used by the proposal scan. +-/ + +namespace ContingencyTables.CompanionCanonicalEncoding + +open CommonBasesFPRAS TwoLiftStates CompanionFactorialApplication +open InitialTransversals InitialFactorialBits CompanionInitialDraw +open CompanionArithmeticProposal CompanionOrderedProposal +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def copyEquiv (A : Instance I J) : Labels A ≃ Copy (cellCapacity A) := + Equiv.sigmaCongrLeft' (cellEnum A) + +def pairEquiv (A : Instance I J) : (Labels A×Bool) ≃ (Copy (cellCapacity A)×Bool) := + Equiv.prodCongr (copyEquiv A) (Equiv.refl Bool) + +def coordinateOrder (A : Instance I J) : (Labels A×Bool) ≃ + Fin (CanonicalInitialEncoding.pairOrder (cellCapacity A)).length := + (pairEquiv A).trans (CanonicalInitialEncoding.coordinateEquiv (cellCapacity A)) + +lemma encodeSet_reindex (A : Instance I J) (S : Set (Labels A×Bool)) : + encodeSet (coordinateOrder A) S= + encodeSet (CanonicalInitialEncoding.coordinateEquiv (cellCapacity A)) + ((pairEquiv A).symm ⁻¹' S) := rfl + +/-- Reindexing the physical initial draw gives the independent cell +choices used by the actual list initializer. -/ +lemma initial_preimage (A : Instance I J) (B : ℕ) + (bits : Fin (initialBits A B) → Bool) : + (pairEquiv A).symm ⁻¹' (draw A B bits).val.val= + encode (cellCapacity A) (drawChoices (cellCapacity A) B bits) := by + ext p + rcases p with ⟨⟨i,k⟩,side⟩ + have hc := Equiv.piCongrLeft'_symm_apply_apply + (fun s : SmallCell A => Finset (Fin (A.b s.val.1 s.val.2))) + (cellEnum A) (drawChoices (cellCapacity A) B bits) i + cases side + · change k∈(choiceEquiv (fun s : SmallCell A => A.b s.val.1 s.val.2) + (cellEnum A) (drawChoices (cellCapacity A) B bits)) ((cellEnum A).symm i) ↔ + k∈drawChoices (cellCapacity A) B bits i + exact Iff.of_eq (congrArg (fun S => k∈S) hc) + · change k∉(choiceEquiv (fun s : SmallCell A => A.b s.val.1 s.val.2) + (cellEnum A) (drawChoices (cellCapacity A) B bits)) ((cellEnum A).symm i) ↔ + k∉drawChoices (cellCapacity A) B bits i + exact Iff.of_eq (congrArg (fun S => k∉S) hc) + +/-- The polynomial binary initializer emits precisely the code of the +literal `PlainIndex` output with its distributional error bound. -/ +theorem initialCode_eq (A : Instance I J) (B : ℕ) (hB : 0 s.1 (g.symm a.1.1) (g.symm b.1.1)),s.2⟩ + +@[simp] theorem project_extend (s : Canonical (p := p)) : + project A g (extend A g s)=s := by + apply Prod.ext + · funext i j + simp only [project,extend,CompanionPhaseFinishProgram.storedView,pair,Equiv.symm_apply_apply] + · rfl + +theorem project_eq_iff (s t : Stored A) : + project A g s=project A g t ↔ Agree A s.multiplier t.multiplier ∧ s.estimate=t.estimate := by + constructor + · intro h + constructor + · intro a b + have he := congrFun (congrFun (congrArg Prod.fst h) (g.symm a)) (g.symm b) + simpa only [project,CompanionPhaseFinishProgram.storedView,Equiv.apply_symm_apply] using he + · exact congrArg Prod.snd h + · rintro ⟨hw,he⟩ + apply Prod.ext + · funext i j + exact hw (g i) (g j) + · exact he + +theorem extend_project_agree (s : Stored A) : + Agree A (extend A g (project A g s)).multiplier s.multiplier := by + intro a b + simp only [extend,project,CompanionPhaseFinishProgram.storedView,pair,Equiv.apply_symm_apply] + +theorem learn_agree (w w' : Pair A→Pair A→ℚ) (hw : Agree A w w') + (states : List (Set (Labels A×Bool))) : + Agree A (rationalLearn pairs w states) (rationalLearn pairs w' states) := by + intro a b + by_cases h : pair a∈(pairs : List (Pair A)) ∧ pair b∈(pairs : List (Pair A)) ∧ pair a≠pair b + · simp only [rationalLearn,h,hw a b] + · simp only [rationalLearn,h,ite_false,hw a b] + +theorem update_project_eq (R : RootedCompletion.Selection A.T) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (s t : Stored A) (h : project A g s=project A g t) + (states : Fin N→Set (Labels A×Bool)) (bits : Fin (phaseBits A C K j N xi)→Bool) : + (RootedPhaseWords.update A R C K j N hK hW xi v s states bits).map (project A g)= + (RootedPhaseWords.update A R C K j N hK hW xi v t states bits).map (project A g) := by + obtain ⟨hw,he⟩ := (project_eq_iff A g s t).mp h + unfold RootedPhaseWords.update + split_ifs + · simp only [Option.map_some] + apply congrArg Option.some + apply (project_eq_iff A g _ _).mpr + exact ⟨learn_agree A s.multiplier t.multiplier hw _,congrArg (fun e => e*_) he⟩ + · rfl + +theorem trial_project_eq (R : RootedCompletion.Selection A.T) (C K j k N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (s t : Stored A) (h : project A g s=project A g t) + (S : CompanionBooleanPhase.State A) (bits : RootedPhaseTrial.TrialWords A C K j k N xi) : + (RootedPhaseTrial.trial A R C K j k N hK hW xi v s S bits).map (project A g)= + (RootedPhaseTrial.trial A R C K j k N hK hW xi v t S bits).map (project A g) := by + have hw := ((project_eq_iff A g s t).mp h).1 + unfold RootedPhaseTrial.trial + rw [observedStates_eq A R C K j k N hK hW xi v s.multiplier t.multiplier hw] + exact update_project_eq A g R C K j (N+1) hK hW xi v s t h _ _ + +theorem restart_project_eq (R : RootedCompletion.Selection A.T) + (C K H L j k n N h : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (w w' : ℕ→Pair A→Pair A→ℚ) (e e' : ℚ) + (hw : ∀ i,i ≤ j → Agree A (w i) (w' i)) (he : e=e') + (bits : RootedRestartTrial.Words A C K H L j k n N h xi) : + (RootedRestartTrial.run A R C K H L j k n N h hK hW xi v w e bits).map (project A g)= + (RootedRestartTrial.run A R C K H L j k n N h hK hW xi v w' e' bits).map (project A g) := by + have hi := RootedRestartWords.initializedStages_agree A R C K H L k n h j hK hW xi v w w' + (fun i hi => hw (i+1) (by omega)) bits.1 + unfold RootedRestartTrial.run + rw [hi] + exact trial_project_eq A g R C K j k N hK hW xi v ⟨w j,e⟩ ⟨w' j,e'⟩ + ((project_eq_iff A g _ _).mpr ⟨hw j le_rfl,he⟩) _ _ + +theorem lookup_project_eq (history history' : List (Stored A)) + (h : history.map (project A g)=history'.map (project A g)) (i : ℕ) : + project A g (RootedStoredHistory.lookup A history i)= + project A g (RootedStoredHistory.lookup A history' i) := by + cases i with + | zero => rfl + | succ i => + have he := congrArg (fun xs : List (Canonical (p := p)) => + xs.getD i (project A g (RootedStoredEstimate.initialStored A))) h + simpa only [RootedStoredHistory.lookup,List.getD_map] using he + +private theorem project_getD (a b : Option (Stored A)) (s t : Stored A) + (h : a.map (project A g)=b.map (project A g)) (he : project A g s=project A g t) : + project A g (a.getD s)=project A g (b.getD t) := by + cases a <;> cases b <;> simp_all + +theorem step_project_eq (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (history history' : List (Stored A)) + (hh : history.map (project A g)=history'.map (project A g)) (bits : RootedPhaseHistory.Word A s) : + project A g (RootedPhaseHistory.step A R s history bits)= + project A g (RootedPhaseHistory.step A R s history' bits) := by + have hlen : history.length=history'.length := by + simpa only [List.length_map] using congrArg List.length hh + have hold := lookup_project_eq A g history history' hh history'.length + dsimp only [RootedPhaseHistory.step] + rw [hlen] + split_ifs with hj + · apply project_getD A g _ _ _ _ _ hold + apply restart_project_eq A g R s.C s.K s.H s.L history'.length s.k s.n s.N s.h + s.hK s.hW s.xi s.v + · intro i _ + exact ((project_eq_iff A g _ _).mp (lookup_project_eq A g history history' hh i)).1 + · exact ((project_eq_iff A g _ _).mp hold).2 + · exact hold + +def canonicalStep (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (history : List (Canonical (p := p))) (bits : RootedPhaseHistory.Word A s) : Canonical (p := p) := + project A g (RootedPhaseHistory.step A R s (history.map (extend A g)) bits) + +theorem step_project (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (history : List (Stored A)) (bits : RootedPhaseHistory.Word A s) : + project A g (RootedPhaseHistory.step A R s history bits)= + canonicalStep A g R s (history.map (project A g)) bits := by + apply step_project_eq A g R s history ((history.map (project A g)).map (extend A g)) + simp only [List.map_map,Function.comp_def,project_extend] + +end +end ContingencyTables.CompanionCanonicalHistory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalHistoryLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalHistoryLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0c4334904af006fa219ff12b87d907bd27862db --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalHistoryLaw.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalHistory +import OAI.Combinatorics.ContingencyTables.Transport.FiniteProjectedHistory +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingWords + +namespace OAI + +/-! # The complete source estimator factors through canonical stored entries -/ +namespace ContingencyTables.CompanionCanonicalHistory +open CompanionFactorialApplication CommonBasesFPRAS GridBoundary FiniteObservableTransport +open CompanionPhaseWords (Stored) +open scoped Classical +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] +variable (A : Instance I J) {p : ℕ} (g : Fin p ≃ Labels A) + +def sourceAdvance (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (history : List (Stored A)) (bits : RootedPhaseHistory.Word A s) : List (Stored A) := + history++[RootedPhaseHistory.step A R s history bits] + +def canonicalAdvance (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (history : List (Canonical (p := p))) (bits : RootedPhaseHistory.Word A s) : List (Canonical (p := p)) := + history++[canonicalStep A g R s history bits] + +lemma advance_project (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (history : List (Stored A)) (bits : RootedPhaseHistory.Word A s) : + (sourceAdvance A R s history bits).map (project A g)= + canonicalAdvance A g R s (history.map (project A g)) bits := by + simp only [sourceAdvance,canonicalAdvance,List.map_append,List.map_singleton,step_project] + +lemma fold_project (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (words : List (RootedPhaseHistory.Word A s)) (history : List (Stored A)) : + (words.foldl (sourceAdvance A R s) history).map (project A g)= + words.foldl (canonicalAdvance A g R s) (history.map (project A g)) := by + induction words generalizing history with + | nil => rfl + | cons word words ih => + rw [List.foldl_cons,List.foldl_cons,ih,advance_project] + +def canonicalDecoded (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (words : List (RootedPhaseHistory.Word A s)) : List (Canonical (p := p)) := + words.foldl (canonicalAdvance A g R s) [] + +theorem decoded_project (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (words : List (RootedPhaseHistory.Word A s)) : + (RootedPhaseHistory.decoded A R s words).map (project A g)=canonicalDecoded A g R s words := + fold_project A g R s words [] + +theorem decoded_sameLaw (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (N : ℕ) : + SameLaw (fun words : Fin N→RootedPhaseHistory.Word A s => + (RootedPhaseHistory.decoded A R s (List.ofFn words)).map (project A g)) + (fun words : Fin N→RootedPhaseHistory.Word A s => canonicalDecoded A g R s (List.ofFn words)) := by + apply projected_foldl_sameLaw (sourceAdvance A R s) (canonicalAdvance A g R s) + (List.map (project A g)) (fun _ => True) (fun _ _ _ => trivial) ?_ [] trivial N + intro history _ phi + apply congrArg uniformAverage + funext bits + change phi ((sourceAdvance A R s history bits).map (project A g)) = _ + rw [advance_project] + +def canonicalLookup (history : List (Canonical (p := p))) : ℕ→Canonical (p := p) + | 0 => project A g (RootedStoredEstimate.initialStored A) + | i+1 => history.getD i (project A g (RootedStoredEstimate.initialStored A)) + +lemma lookup_project (history : List (Stored A)) (i : ℕ) : + project A g (RootedStoredHistory.lookup A history i)= + canonicalLookup A g (history.map (project A g)) i := by + cases i with + | zero => rfl + | succ i => exact (List.getD_map history (RootedStoredEstimate.initialStored A) + (project A g)).symm + +def canonicalEstimate (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (words : Fin s.H→RootedPhaseHistory.Word A s) : ℚ := + (canonicalLookup A g (canonicalDecoded A g R s (List.ofFn words)) s.H).2 + +theorem estimate_project (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (words : Fin s.H→RootedPhaseHistory.Word A s) : + RootedCountingWords.estimate A R s words=canonicalEstimate A g R s words := by + change (project A g (RootedStoredHistory.lookup A + (RootedPhaseHistory.decoded A R s (List.ofFn words)) s.H)).2=_ + rw [lookup_project,decoded_project] + rfl + +theorem estimate_sameLaw (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) : + SameLaw (RootedCountingWords.estimate A R s) (canonicalEstimate A g R s) := by + intro phi + apply congrArg uniformAverage + funext words + rw [estimate_project] + +theorem flatEstimate_sameLaw (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) : + SameLaw (RootedCountingWords.flatEstimate A R s) (canonicalEstimate A g R s) := by + intro phi + have h := uniformAverage_equiv (gridWordEquiv s.H (RootedPhaseHistory.totalWidth A s)) + (fun words => phi (RootedCountingWords.estimate A R s words)) + exact h.trans (estimate_sameLaw A g R s phi) + +end +end ContingencyTables.CompanionCanonicalHistory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalPhaseLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalPhaseLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a5e6983faafd0fd2f7891551ca2c56ecaf7c7ca --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalPhaseLaw.lean @@ -0,0 +1,264 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseLaw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterWidths +import OAI.Combinatorics.ContingencyTables.Counting.CompanionHistoryReadback + +namespace OAI + +/-! # The projected law of one complete physical counting phase -/ +namespace ContingencyTables.CompanionCanonicalPhaseLaw +open MatchingFPRAS CommonBasesFPRAS FirstSuccess FairBits FiniteObservableTransport +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram CompanionCanonicalHistory +open CompanionHistoryReadback CompanionStoredRepresentation CompanionOracleDensity +open CompanionRationalUpdates TwoLiftStates GridBoundary +open scoped Classical +noncomputable section + +lemma prefix_sameLaw {Z : Type*} {k N : ℕ} (hk : k ≤ N) (f : (Fin k→Bool)→Z) : + SameLaw (fun bits : Fin N→Bool => f (prefixWord hk bits)) f := by + intro phi + have he := uniformAverage_equiv (paddingWordEquiv hk) + (fun p : (Fin k→Bool)×(Fin (N-k)→Bool) => phi (f p.1)) + simp only [paddingWordEquiv_fst] at he + rw [uniformAverage_prod] at he + simpa only [uniformAverage_const] using he + +def canonicalResult {I J : Type} [Fintype I] [Fintype J] + (A : Instance I J) {p : ℕ} (g : Fin p ≃ Labels A) + (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (history : List (Canonical (p := p))) (j : ℕ) + (bits : RootedRestartTrial.Words A s.C s.K s.H s.L j s.k s.n s.N s.h s.xi) : + Canonical (p := p) := + let hs := history.map (extend A g) + let old := RootedStoredHistory.lookup A hs j + project A g ((RootedRestartTrial.run A R s.C s.K s.H s.L j s.k s.n s.N s.h + s.hK s.hW s.xi s.v (fun i => (RootedStoredHistory.lookup A hs i).multiplier) + old.estimate bits).getD old) + +theorem canonicalStep_sameLaw {I J : Type} [Fintype I] [Fintype J] + (A : Instance I J) {p : ℕ} (g : Fin p ≃ Labels A) + (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (history : List (Canonical (p := p))) (hj : history.length < s.H) : + SameLaw (fun bits : RootedPhaseHistory.Word A s => canonicalStep A g R s history bits) + (canonicalResult A g R s history history.length) := by + let f := fun bits : Fin (RootedPhaseHistory.width A s history.length)→Bool => + canonicalResult A g R s history history.length (RootedPhaseHistory.split A s history.length bits) + have hp := prefix_sameLaw (RootedPhaseHistory.width_le A s history.length hj) f + intro phi + have he := uniformAverage_equiv (RootedPhaseHistory.split A s history.length) + (fun bits => phi (canonicalResult A g R s history history.length bits)) + have hf (bits : RootedPhaseHistory.Word A s) : + canonicalStep A g R s history bits= + f (prefixWord (RootedPhaseHistory.width_le A s history.length hj) bits) := by + unfold canonicalStep RootedPhaseHistory.step + rw [show (history.map (extend A g)).length=history.length from List.length_map _] + rw [dite_eq_left hj] + rfl + simp_rw [hf] + exact (hp phi).trans he + +private theorem project_getD {I J : Type} [Fintype I] [Fintype J] + (A : Instance I J) {p : ℕ} (g : Fin p ≃ Labels A) + (a b : Option (CompanionPhaseWords.Stored A)) (s t : CompanionPhaseWords.Stored A) + (h : a.map (project A g)=b.map (project A g)) (he : project A g s=project A g t) : + project A g (a.getD s)=project A g (b.getD t) := by + cases a <;> cases b <;> simp_all + +variable {m n : ℕ} + +def rawSettings (A : Instance (Fin m) (Fin n)) (C K H N R L : ℕ) + (epsilon : TreeFraction.Fraction) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : RootedPhaseHistory.Settings A where + C := C + K := K + H := H + L := L + k := CountingPhaseParametersProgram.precision (CompanionInitializedRestartProgram.parameters A H + (CompanionTargetMixing.restartTime A H L) N R L epsilon) + n := R + N := CountingPhaseParametersProgram.observations (CompanionInitializedRestartProgram.parameters A H + (CompanionTargetMixing.restartTime A H L) N R L epsilon) + h := CountingPhaseSchedule.initialPrecision H + hK := hK + hW := hW + xi := TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A H (CompanionTargetMixing.restartTime A H L) N R L epsilon)) + v := RootedCatalogGrid.gridEquiv A K v + +theorem rawSettings_eq (A : Instance (Fin m) (Fin n)) (s : RootedPhaseHistory.Settings A) + (N : ℕ) (epsilon : TreeFraction.Fraction) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) s.K) + (hk : CountingPhaseParametersProgram.precision + (CompanionInitializedRestartProgram.parameters A s.H + (CompanionTargetMixing.restartTime A s.H s.L) N s.n s.L epsilon)=s.k) + (hN : CountingPhaseParametersProgram.observations + (CompanionInitializedRestartProgram.parameters A s.H + (CompanionTargetMixing.restartTime A s.H s.L) N s.n s.L epsilon)=s.N) + (hh : CountingPhaseSchedule.initialPrecision s.H=s.h) + (hxi : TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A s.H + (CompanionTargetMixing.restartTime A s.H s.L) N s.n s.L epsilon))=s.xi) + (hv : RootedCatalogGrid.gridEquiv A s.K v=s.v) : + rawSettings A s.C s.K s.H N s.n s.L epsilon s.hK s.hW v=s := by + cases s + dsimp only at hk hN hh hxi hv ⊢ + unfold rawSettings + congr 1 + +def sourceStored (A : Instance (Fin m) (Fin n)) + (initial : CompanionPhaseFinishProgram.Stored) (history : List CompanionPhaseFinishProgram.Stored) + (i : ℕ) : CompanionPhaseWords.Stored A := + ⟨sourceWeights A (matrixAt (CanonicalInitialEncoding.copyOrder (capacities A)).length initial history i), + TreeFraction.val (estimateAt initial history i)⟩ + +lemma sourceStored_project (A : Instance (Fin m) (Fin n)) + (initial : CompanionPhaseFinishProgram.Stored) (history : List CompanionPhaseFinishProgram.Stored) + (i : ℕ) : + project A (pairLabels A) (sourceStored A initial history i)= + CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + (lookup initial history i) := by + apply Prod.ext + · funext a b + simp only [project,CompanionPhaseFinishProgram.storedView,sourceStored,sourceWeights,pair, + Equiv.symm_apply_apply,matrixAt,entries,CompanionPhaseFinishProgram.view] + · rfl + +lemma sourceStored_lookup (A : Instance (Fin m) (Fin n)) + (initial : CompanionPhaseFinishProgram.Stored) (history : List CompanionPhaseFinishProgram.Stored) + (hi : CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + initial=project A (pairLabels A) (RootedStoredEstimate.initialStored A)) (i : ℕ) : + project A (pairLabels A) (sourceStored A initial history i)= + project A (pairLabels A) (RootedStoredHistory.lookup A + ((history.map (CompanionPhaseFinishProgram.view + (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))).map (extend A (pairLabels A))) i) := by + rw [sourceStored_project,view_lookup,CompanionCanonicalHistory.lookup_project] + simp only [List.map_map,Function.comp_def,project_extend] + rw [hi] + rfl + +def readbackResult (A : Instance (Fin m) (Fin n)) (s : RootedPhaseHistory.Settings A) + (initial : CompanionPhaseFinishProgram.Stored) (history : List CompanionPhaseFinishProgram.Stored) + (bits : RootedRestartTrial.Words A s.C s.K s.H s.L history.length s.k s.n s.N s.h s.xi) : + Canonical (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) := + let old := sourceStored A initial history history.length + project A (pairLabels A) ((RootedRestartTrial.run A (RootedCompletion.rowColumn A.T) + s.C s.K s.H s.L history.length s.k s.n s.N s.h s.hK s.hW s.xi s.v + (fun i => (sourceStored A initial history i).multiplier) old.estimate bits).getD old) + +lemma readbackResult_eq (A : Instance (Fin m) (Fin n)) (s : RootedPhaseHistory.Settings A) + (initial : CompanionPhaseFinishProgram.Stored) (history : List CompanionPhaseFinishProgram.Stored) + (hi : CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + initial=project A (pairLabels A) (RootedStoredEstimate.initialStored A)) + (bits : RootedRestartTrial.Words A s.C s.K s.H s.L history.length s.k s.n s.N s.h s.xi) : + readbackResult A s initial history bits= + canonicalResult A (pairLabels A) (RootedCompletion.rowColumn A.T) s + (history.map (CompanionPhaseFinishProgram.view + (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))) history.length bits := by + let hs := (history.map (CompanionPhaseFinishProgram.view + (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))).map (extend A (pairLabels A)) + have hp (i : ℕ) := sourceStored_lookup A initial history hi i + have ho := restart_project_eq A (pairLabels A) (RootedCompletion.rowColumn A.T) + s.C s.K s.H s.L history.length s.k s.n s.N s.h s.hK s.hW s.xi s.v + (fun i => (sourceStored A initial history i).multiplier) + (fun i => (RootedStoredHistory.lookup A hs i).multiplier) + (sourceStored A initial history history.length).estimate + (RootedStoredHistory.lookup A hs history.length).estimate + (fun i _ => ((project_eq_iff A (pairLabels A) _ _).mp (hp i)).1) + (((project_eq_iff A (pairLabels A) _ _).mp (hp history.length)).2) bits + exact project_getD A (pairLabels A) _ _ _ _ ho (hp history.length) + +theorem output_sameLaw (A : Instance (Fin m) (Fin n)) (C K H N R L W : ℕ) + (epsilon : TreeFraction.Fraction) (hC : 0 < C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A H + (CompanionTargetMixing.restartTime A H L) N R L epsilon))) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (initial : CompanionPhaseFinishProgram.Stored) (history : List CompanionPhaseFinishProgram.Stored) + (hj : history.length < H) (hphase : history.length+1 ≤ rationalHeight A C) + (hwidth : RootedPhaseHistory.totalWidth A (rawSettings A C K H N R L epsilon hK hW v) ≤ W) + (hdegree : ∀ i,i ≤ history.length+1 → PowerOfTwoApproximation.rootDegree + (roundingTolerance (innerTolerance + ((rawSettings A C K H N R L epsilon hK hW v).xi/2) i)) ≤ W) + (hdepth : ∀ i,i ≤ history.length+1 → PowerOfTwoApproximation.depth + (roundingTolerance (innerTolerance + ((rawSettings A C K H N R L epsilon hK hW v).xi/2) i)) ≤ W) + (hinit : StoredRep (CanonicalInitialEncoding.copyOrder (capacities A)).length initial) + (hh : ∀ q∈history,StoredRep (CanonicalInitialEncoding.copyOrder (capacities A)).length q) + (hi : CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + initial=project A (pairLabels A) (RootedStoredEstimate.initialStored A)) : + let s := rawSettings A C K H N R L epsilon hK hW v + SameLaw (fun bits : Fin W→Bool => + CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + (CompanionOuterPhaseProgram.output + (((CompanionRestartInitializer.data A C K H + (CompanionTargetMixing.restartTime A H L) N R L epsilon z v,initial),history),List.ofFn bits))) + (fun bits : RootedPhaseHistory.Word A s => canonicalStep A (pairLabels A) + (RootedCompletion.rowColumn A.T) s + (history.map (CompanionPhaseFinishProgram.view + (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))) bits) := by + dsimp only + let s := rawSettings A C K H N R L epsilon hK hW v + let j := history.length + let t := CompanionTargetMixing.restartTime A H L + let reserve := List.replicate W false + let padding := W-RootedPhaseHistory.width A s j + let w := matrixAt (CanonicalInitialEncoding.copyOrder (capacities A)).length initial history + let E := estimateAt initial history + let view := CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + have hbound : RootedPhaseHistory.width A s j ≤ W := + (RootedPhaseHistory.width_le A s j hj).trans hwidth + have hsize : CompanionOuterPhaseProgram.phaseWordWidth A C K H t N R L j + epsilon z v reserve padding=W := by + have h := CompanionOuterWidths.phaseWidth_source A s N j epsilon z v reserve padding + rfl rfl rfl rfl + change CompanionOuterPhaseProgram.phaseWordWidth A C K H t N R L j + epsilon z v reserve padding=RootedPhaseHistory.width A s j+padding at h + exact h.trans (Nat.add_sub_of_le hbound) + have hw (a b : LabelIndex A) : TreeFraction.val (w j a b)= + (sourceStored A initial history j).multiplier (pair (pairLabels A a)) (pair (pairLabels A b)) := by + simp only [sourceStored,sourceWeights,pair,Equiv.symm_apply_apply] + rfl + have hbase := CompanionOuterPhaseProgram.output_sameLaw A C K H t N R L j padding + hC hphase hK hW hB epsilon hxi z v reserve + (by simpa only [reserve,List.length_replicate] using hsize.symm) + (fun i hi => by rw [List.length_replicate]; exact hdegree i hi) + (fun i hi => by rw [List.length_replicate]; exact hdepth i hi) + (sourceStored A initial history j) w E hw rfl + have hsource : SameLaw + (fun bits : Fin (CompanionOuterPhaseProgram.phaseWordWidth A C K H t N R L j + epsilon z v reserve padding)→Bool => view + (CompanionOuterPhaseProgram.output + (CompanionOuterPhaseProgram.data A C K H t N R L j epsilon z v w E (List.ofFn bits)))) + (readbackResult A s initial history) := hbase + have hp := SameLaw.word_length hsize + (fun bs => view (CompanionOuterPhaseProgram.output + (CompanionOuterPhaseProgram.data A C K H t N R L j epsilon z v w E bs))) + (readbackResult A s initial history) hsource + have hphysical : SameLaw + (fun bits : Fin W→Bool => view (CompanionOuterPhaseProgram.output + (((CompanionRestartInitializer.data A C K H t N R L epsilon z v,initial),history),List.ofFn bits))) + (readbackResult A s initial history) := by + intro phi + have hd (bits : Fin W→Bool) : + CompanionOuterPhaseProgram.data A C K H t N R L j epsilon z v w E (List.ofFn bits)= + (((CompanionRestartInitializer.data A C K H t N R L epsilon z v,initial),history),List.ofFn bits) := + outer_data_readback A C K H t N R L epsilon z v initial history hinit hh _ + simpa only [hd] using hp phi + have href : SameLaw (readbackResult A s initial history) + (canonicalResult A (pairLabels A) (RootedCompletion.rowColumn A.T) s + (history.map view) j) := by + intro phi + apply congrArg uniformAverage + funext bits + rw [readbackResult_eq A s initial history hi bits] + have hc := canonicalStep_sameLaw A (pairLabels A) (RootedCompletion.rowColumn A.T) s + (history.map view) (by rw [List.length_map]; exact hj) + rw [List.length_map] at hc + intro phi + exact (hphysical phi).trans ((href phi).trans (hc phi).symm) + +end +end ContingencyTables.CompanionCanonicalPhaseLaw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalPhaseSupport.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalPhaseSupport.lean new file mode 100644 index 0000000000000000000000000000000000000000..441290b208d2a246337e5053cc143293fdcadcc7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCanonicalPhaseSupport.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalPhaseLaw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSupport + +namespace OAI + +/-! # Representation preservation for every executed counting phase + +The restart support statement is obtained from its actual finite-word law. +The remaining trajectory and observation words may be unused padding for +that law; their presence still supplies the required precision markers. +-/ +namespace ContingencyTables.CompanionCanonicalPhaseSupport +open MatchingFPRAS CommonBasesFPRAS FiniteObservableTransport +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionEvaluatedWeightProgram CompanionStoredRepresentation CompanionHistoryReadback +open CompanionCanonicalPhaseLaw CompanionOracleDensity GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma restart_prefix_le (A : Instance (Fin m) (Fin n)) (C K H N R L W j : ℕ) + (epsilon : TreeFraction.Fraction) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (hj : j < H) + (hwidth : RootedPhaseHistory.totalWidth A (rawSettings A C K H N R L epsilon hK hW v) ≤ W) : + CompanionComputedInitial.wordLength A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + CompanionRestartProgram.sumBits A C K j + (CompanionInitializedRestartProgram.parameters A H + (CompanionTargetMixing.restartTime A H L) N R L epsilon) ≤ W := by + let s := rawSettings A C K H N R L epsilon hK hW v + calc + _ = RootedRestartWords.initialStageBits A C K H L s.k R s.h j s.xi := + CompanionOuterWidths.initialWidth_eq A C K H N R L j epsilon + _ ≤ RootedPhaseHistory.width A s j := Nat.le_add_right _ _ + _ ≤ RootedPhaseHistory.totalWidth A s := RootedPhaseHistory.width_le A s j hj + _ ≤ W := hwidth + +theorem output_rep (A : Instance (Fin m) (Fin n)) (C K H N R L W : ℕ) + (epsilon : TreeFraction.Fraction) (hC : 0 < C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A H + (CompanionTargetMixing.restartTime A H L) N R L epsilon))) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (initial : CompanionPhaseFinishProgram.Stored) (history : List CompanionPhaseFinishProgram.Stored) + (hj : history.length < H) (hphase : history.length+1 ≤ rationalHeight A C) + (hwidth : RootedPhaseHistory.totalWidth A (rawSettings A C K H N R L epsilon hK hW v) ≤ W) + (hdegree : ∀ i,i ≤ history.length+1 → PowerOfTwoApproximation.rootDegree + (roundingTolerance (innerTolerance + ((rawSettings A C K H N R L epsilon hK hW v).xi/2) i)) ≤ W) + (hdepth : ∀ i,i ≤ history.length+1 → PowerOfTwoApproximation.depth + (roundingTolerance (innerTolerance + ((rawSettings A C K H N R L epsilon hK hW v).xi/2) i)) ≤ W) + (hinit : StoredRep (CanonicalInitialEncoding.copyOrder (capacities A)).length initial) + (hh : ∀ q∈history,StoredRep (CanonicalInitialEncoding.copyOrder (capacities A)).length q) + (bits : Fin W→Bool) : + StoredRep (CanonicalInitialEncoding.copyOrder (capacities A)).length + (CompanionOuterPhaseProgram.output + (((CompanionRestartInitializer.data A C K H + (CompanionTargetMixing.restartTime A H L) N R L epsilon z v,initial),history),List.ofFn bits)) := by + let t := CompanionTargetMixing.restartTime A H L + let j := history.length + let p := CompanionInitializedRestartProgram.parameters A H t N R L epsilon + let a := wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H)) + let b := CompanionRestartProgram.sumBits A C K j p + let padding := W-(a+b) + let w := matrixAt (CanonicalInitialEncoding.copyOrder (capacities A)).length initial history + let E := estimateAt initial history + have hprefix : a+b ≤ W := restart_prefix_le A C K H N R L W j epsilon hK hW v hj hwidth + have hlen : a+(b+padding)=W := by + rw [←Nat.add_assoc] + exact Nat.add_sub_of_le hprefix + have hl := CompanionInitializedRestartProgram.output_padded_sameLaw A C K H t N R L j padding + hC (by omega) hK hW hB epsilon hxi z v w (fun i => E (i.val+1)) + (fun i => by + unfold CompanionRestartStageProgram.oracleData + rw [RootedOracleConfigProgram.rootDegree_data] + exact (hdegree (i.val+1) (by omega)).trans_eq hlen.symm) + (fun i => by + unfold CompanionRestartStageProgram.oracleData + rw [RootedOracleConfigProgram.depth_data] + exact (hdepth (i.val+1) (by omega)).trans_eq hlen.symm) + have hl' := SameLaw.word_length hlen + (fun bs => CompanionInitializedRestartProgram.output + (CompanionInitializedRestartProgram.data A C K H t N R L j epsilon z v w + (fun i => E (i.val+1)) bs)) _ hl + obtain ⟨sourceBits,hs⟩ := hl'.exists_preimage bits + have hd := outer_data_readback A C K H t N R L epsilon z v initial history hinit hh (List.ofFn bits) + apply CompanionInitializedRestartProgram.outer_output_rep_of_supported A _ hinit hh + refine ⟨CompanionInitializedRestartProgram.model A C K H t N R L j epsilon hK hW v w sourceBits,?_⟩ + rw [←hd] + change CompanionInitializedRestartProgram.output + (CompanionOuterPhaseProgram.restartInput + (CompanionOuterPhaseProgram.data A C K H t N R L j epsilon z v w E (List.ofFn bits)))=_ + rw [CompanionOuterPhaseProgram.restartInput_data] + exact hs.symm + +end +end ContingencyTables.CompanionCanonicalPhaseSupport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCappedReturn.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCappedReturn.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac344d821458dbe85d97a66726081c923f0aa0c9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCappedReturn.lean @@ -0,0 +1,189 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTraceWords + +namespace OAI + +/-! # Total bounded trace steps + +If a capped return search misses its target, the finite-word experiment +keeps its starting plain state. Its error against the exact trace is the +cap loss plus the error of the recorded Boolean walk. +-/ + +namespace ContingencyTables.CompanionCappedReturn + +open CommonBasesFPRAS CompanionTraceWords CompanionPhaseTrajectory +open CompanionFactorialApplication CompanionBooleanPhase CompanionOracleDensity +open CompanionWeightOracle CompanionRationalUpdates TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +variable {X : Type*} + +def returnDefault (B : X → Prop) (x : FiniteChain.Inside B) (xs : List X) : + FiniteChain.Inside B := (firstHit B xs.tail).getD x + +private lemma returnDefault_value (B : X → Prop) (x : FiniteChain.Inside B) + (phi : FiniteChain.Inside B → ℝ) (xs : List X) : + phi (returnDefault B x xs)=returnValue B phi xs+ + phi x*eventIndicator (firstHit B xs.tail=none) := by + unfold returnDefault returnValue + cases firstHit B xs.tail <;> simp [DrawTree.optionValue,eventIndicator] + +variable [Fintype X] + +/-- The missing cap mass is assigned to the starting state, exactly. -/ +theorem returnDefault_expectation (C : FiniteChain X) (B : X → Prop) + (Q : KilledKernel (FiniteChain.Outside B)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) + (phi : FiniteChain.Inside B → ℝ) (n : ℕ) (x : FiniteChain.Inside B) : + C.pathExpectation (n+1) x.val (fun xs => phi (returnDefault B x xs))= + (∑ y,C.cappedTrace B Q n x y*phi y)+ + phi x*(1-∑ y,C.cappedTrace B Q n x y) := by + calc + _ = C.pathExpectation (n+1) x.val (fun xs => returnValue B phi xs+ + phi x*eventIndicator (firstHit B xs.tail=none)) := by + apply C.pathExpectation_congr + exact returnDefault_value B x phi + _ = _ := by + rw [C.pathExpectation_add,C.pathExpectation_mul, + inside_return_expectation C B Q hQ, + return_failure_expectation C B Q hQ] + +/-- Bounded observations lose at most the exact omitted return mass. -/ +theorem returnDefault_error (C : FiniteChain X) (B : X → Prop) + (Q : KilledKernel (FiniteChain.Outside B)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) + (phi : FiniteChain.Inside B → ℝ) (hphi : ∀ y,0≤phi y ∧ phi y≤1) + (n : ℕ) (x : FiniteChain.Inside B) : + |C.pathExpectation (n+1) x.val (fun xs => phi (returnDefault B x xs))- + (∑ y,C.traceMatrix B Q x y*phi y)|≤ + 1-∑ y,C.cappedTrace B Q n x y := by + let loss : ℝ := 1-∑ y,C.cappedTrace B Q n x y + have hloss : 0≤loss := sub_nonneg.mpr (C.cappedTrace_substochastic B Q hQ n x) + have hdiff (y : FiniteChain.Inside B) : + 0≤C.traceMatrix B Q x y-C.cappedTrace B Q n x y := + sub_nonneg.mpr (C.cappedTrace_le B Q n x y) + have hmass : (∑ y,(C.traceMatrix B Q x y-C.cappedTrace B Q n x y))=loss := by + rw [Finset.sum_sub_distrib,C.traceMatrix_stochastic B Q hQ] + have he0 : 0≤∑ y,(C.traceMatrix B Q x y-C.cappedTrace B Q n x y)*phi y := + Finset.sum_nonneg (fun y _ => mul_nonneg (hdiff y) (hphi y).1) + have he1 : (∑ y,(C.traceMatrix B Q x y-C.cappedTrace B Q n x y)*phi y)≤loss := by + calc + _ ≤ ∑ y,(C.traceMatrix B Q x y-C.cappedTrace B Q n x y)*1 := + Finset.sum_le_sum (fun y _ => mul_le_mul_of_nonneg_left (hphi y).2 (hdiff y)) + _ = loss := by simpa only [mul_one] using hmass + have hkeep0 : 0≤phi x*loss := mul_nonneg (hphi x).1 hloss + have hkeep1 : phi x*loss≤loss := by + simpa only [one_mul] using mul_le_mul_of_nonneg_right (hphi x).2 hloss + have heq : C.pathExpectation (n+1) x.val (fun xs => phi (returnDefault B x xs))- + (∑ y,C.traceMatrix B Q x y*phi y)= + phi x*loss-∑ y,(C.traceMatrix B Q x y-C.cappedTrace B Q n x y)*phi y := by + rw [returnDefault_expectation C B Q hQ] + simp only [sub_mul,Finset.sum_sub_distrib] + dsimp only [loss] + ring + rw [heq] + exact abs_le.mpr ⟨by linarith,by linarith⟩ + +theorem returnDefault_event_upper (C : FiniteChain X) (B : X → Prop) + (Q : KilledKernel (FiniteChain.Outside B)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) + (E : FiniteChain.Inside B → Prop) (n : ℕ) (x : FiniteChain.Inside B) : + C.pathExpectation (n+1) x.val (fun xs => eventIndicator (E (returnDefault B x xs)))≤ + (∑ y,C.traceMatrix B Q x y*eventIndicator (E y))+ + (1-∑ y,C.cappedTrace B Q n x y) := by + have h := returnDefault_error C B Q hQ (fun y => eventIndicator (E y)) + (by intro y; by_cases he : E y <;> simp [eventIndicator,he]) n x + have hu := (le_abs_self _).trans h + linarith + +/-- The cap error is small on a warm input law even when a pointwise +return-time bound would be too expensive. -/ +theorem warm_returnDefault_error (C : FiniteChain X) (B : X → Prop) + [Nonempty (FiniteChain.Inside B)] + (Q : KilledKernel (FiniteChain.Outside B)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) + (phi : FiniteChain.Inside B → ℝ) (hphi : ∀ y,0≤phi y ∧ phi y≤1) + (n : ℕ) (hn : 0 phi (returnDefault B x xs))- + (∑ y,C.traceMatrix B Q x y*phi y)|)≤U/C.insideMass B/(n:ℝ) := by + have hloss := C.cappedTrace_warm_loss B Q hQ n U nu hnu hwarm + have hnR : (0:ℝ) mul_le_mul_of_nonneg_left + (returnDefault_error C B Q hQ phi hphi n x) (hnu x)) + +variable {I J : Type} [Fintype I] [Fintype J] + +/-- A concrete total draw: a missing capped return keeps the input. -/ +def returnWordDefault (A : Instance I J) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) + (bits : Fin ((n+1)*stepBits A C K j k xi) → Bool) : PlainIndex (pairs : List (Pair A)) := + (returnWord A C K j k (n+1) hK hW xi v w S.val bits).getD S + +private theorem returnWordDefault_to_path (A : Instance I J) (C : ℕ) (hC : 0 + eventIndicator (E (returnWordDefault A C K j k n hK hW xi v w S bits)))≤ + (targetChain A j hp w hw).pathExpectation (n+1) S.val + (fun xs => eventIndicator (E (returnDefault (plainPredicate pairs) S xs)))+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + exact arithmetic_recorded_event_bound A C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw (n+1) S.val + (fun xs => E (returnDefault (plainPredicate pairs) S xs)) + +private theorem target_returnDefault_bound (A : Instance I J) (j : ℕ) + (hp : 0 eventIndicator (E (returnDefault (plainPredicate pairs) S xs)))≤ + (∑ T,(targetChain A j hp w hw).traceMatrix (plainPredicate pairs) + (targetKilled A j hp w hw) S T*eventIndicator (E T))+ + (1-∑ T,(targetChain A j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A j hp w hw) n S T) := by + exact returnDefault_event_upper (targetChain A j hp w hw) (plainPredicate pairs) + (targetKilled A j hp w hw) (targetKilled_matches A j hp w hw) E n S + +/-- The implemented total return step is compared to the exact trace, +with its cap loss left explicit for subsequent warm-law averaging. -/ +theorem returnWordDefault_event (A : Instance I J) (C : ℕ) (hC : 0 + eventIndicator (E (returnWordDefault A C K j k n hK hW xi v w S bits)))≤ + (∑ T,(targetChain A j hp w hw).traceMatrix (plainPredicate pairs) + (targetKilled A j hp w hw) S T*eventIndicator (E T))+ + (1-∑ T,(targetChain A j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A j hp w hw) n S T)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + have he := returnWordDefault_to_path A C hC K j k n hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw S E + have ht := target_returnDefault_bound A j hp w hw n S E + have hb := _root_.add_le_add ht + (le_refl (((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))) + exact he.trans hb + +end +end ContingencyTables.CompanionCappedReturn + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCappedReturnProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCappedReturnProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..5755bc9d3f7f4e1e52722c787f2043fe8bfa0492 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCappedReturnProgram.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCappedReturn +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTraceProgram + +namespace OAI + +/-! # Binary program for a total capped return + +The strict return scan is followed by the supplied initial code on a +missing return. Both operations have polynomial binary realizers. +-/ + +namespace ContingencyTables.CompanionCappedReturnProgram + +open CommonBasesFPRAS MatchingFPRAS.TreeTyped ProfilePrograms +open CompanionFactorialApplication CompanionBooleanPhase CompanionChainValidator +open CompanionCappedReturn CompanionTraceProgram CompanionTraceWords CompanionPhaseTrajectory +open CompanionArithmeticProposal CompanionRationalUpdates GridBoundary +open scoped Classical + +def optionDefault (z : List ℕ×Option (List ℕ)) : List ℕ := z.2.getD z.1 + +def optionDefaultRealizer : Realizer optionDefault := + (optionCases identity second).recode id optionDefault (fun _ => rfl) + (by rintro ⟨d,o⟩; cases o <;> rfl) + +theorem polynomial_optionDefault : PolynomialTime optionDefaultRealizer := by + unfold optionDefaultRealizer + apply polynomial_recode + exact polynomial_optionCases polynomial_identity polynomial_second + +abbrev TotalReturnInput := ReturnInput×List ℕ + +def totalReturnCode (z : TotalReturnInput) : List ℕ := + (returnCode z.1).getD z.2 + +def totalReturnCodeRealizer : Realizer totalReturnCode := + composition (pair second (composition first returnCodeRealizer)) optionDefaultRealizer + +theorem polynomial_totalReturnCode : PolynomialTime totalReturnCodeRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_returnCode)) polynomial_optionDefault + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +/-- The binary result is the encoding of the same defaulted first return. -/ +theorem totalReturnCode_encode (A : Instance I J) + (S : PlainIndex (TwoLiftStates.pairs : List (Pair A))) (xs : List (State A)) : + totalReturnCode ((pairCatalog A,xs.map (fun T => encodeSet (coordinateEquiv A) T.val)), + encodeSet (coordinateEquiv A) S.val.val)= + encodeSet (coordinateEquiv A) + (returnDefault (plainPredicate TwoLiftStates.pairs) S xs).val.val := by + unfold totalReturnCode + rw [returnCode_encode] + unfold returnDefault + cases firstHit (plainPredicate TwoLiftStates.pairs) xs.tail <;> rfl + +/-- In particular the program computes the literal finite-word return +experiment, not an independently specified trace sampler. -/ +theorem totalReturnCode_recorded (A : Instance I J) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (w : Pair A → Pair A → ℚ) + (S : PlainIndex (TwoLiftStates.pairs : List (Pair A))) + (bits : Fin ((n+1)*stepBits A C K j k xi) → Bool) : + totalReturnCode ((pairCatalog A, + (historyPrefix (CompanionArithmeticStep.recordedWalk A C K j k (n+1) (n+1) + hK hW xi v w S.val bits)).map (fun T => encodeSet (coordinateEquiv A) T.val)), + encodeSet (coordinateEquiv A) S.val.val)= + encodeSet (coordinateEquiv A) + (returnWordDefault A C K j k n hK hW xi v w S bits).val.val := by + exact totalReturnCode_encode A S _ + +end +end ContingencyTables.CompanionCappedReturnProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCellCatalogProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCellCatalogProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..e057ebb5d05d75541fc998b522dd705505286328 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCellCatalogProgram.lean @@ -0,0 +1,154 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinaryExchangeProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFactorialApplication + +namespace OAI + +/-! # Computing the companion's retained small-cell capacities + +The program scans the rectangular cell list determined by the two +margin-list lengths, then tests the binary cell bound against W. It +does not enumerate up to the numeric value of a capacity. +-/ + +namespace ContingencyTables.CompanionCellCatalog + +open MatchingFPRAS.TreeTyped ProfilePrograms DensePrograms + +abbrev Input := ((List ℕ×List ℕ)×MatrixCode)×ℕ + +def entry (z : Input×(ℕ×ℕ)) : ℕ := matrixEntry (z.1.1.2,z.2) + +def entryRealizer : Realizer entry := + composition (pair (composition (composition first first) second) second) matrixEntryRealizer + +lemma polynomial_entry : PolynomialTime entryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_second) polynomial_matrixEntry + +def retainedTest (z : Input×(ℕ×ℕ)) : Bool := decide (entry z retainedTest (z,a)) + +def catalogRealizer : Realizer catalog := + composition (pair identity + (composition (composition first first) cellPairsRealizer)) (filterWith retainedTestRealizer) + +theorem polynomial_catalog : PolynomialTime catalogRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_cellPairs)) (polynomial_filterWith polynomial_retainedTest) + +def capacities (z : Input) : List ℕ := (catalog z).map (fun a => entry (z,a)) + +def capacitiesRealizer : Realizer capacities := + composition (pair identity catalogRealizer) (mapWith entryRealizer) + +theorem polynomial_capacities : PolynomialTime capacitiesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_catalog) + (polynomial_mapWith polynomial_entry) + +lemma catalog_nodup (z : Input) : (catalog z).Nodup := + (cellPairs_nodup z.1.1.1 z.1.1.2).filter _ + +noncomputable section +open CompanionFactorialApplication +open scoped Classical +variable {m n : ℕ} + +def input (A : Instance (Fin m) (Fin n)) : Input := + (((List.ofFn (fun i => (A.r i).toNat),List.ofFn (fun j => (A.c j).toNat)), + matrixCode A.b),A.W) + +lemma small_iff_bound (A : Instance (Fin m) (Fin n)) (i : Fin m) (j : Fin n) : + A.small i j=true ↔ A.b i j (A.r i).toNat), + List.ofFn (fun j => (A.c j).toNat)) ∧ retainedTest (input A,ij)=true) ↔ _ + rw [mem_cellPairs] + simp only [List.length_ofFn] + constructor + · rintro ⟨⟨hi,hj⟩,hb⟩ + let i : Fin m := ⟨ij.1,hi⟩ + let j : Fin n := ⟨ij.2,hj⟩ + have he : A.b i j (a.val.1.val,a.val.2.val)) h + rw [catalogCell_coordinates,catalogCell_coordinates] at he + exact Fin.ext ((catalog_nodup (input A)).getElem_inj_iff.mp he) + · intro a + have hm : (a.val.1.val,a.val.2.val)∈catalog (input A) := + (mem_catalog_input A _).mpr ⟨a,rfl⟩ + obtain ⟨i,hi,hval⟩ := List.mem_iff_getElem.mp hm + refine ⟨⟨i,hi⟩,?_⟩ + have he := (catalogCell_coordinates A ⟨i,hi⟩).trans hval + apply Subtype.ext + exact Prod.ext (Fin.ext (congrArg Prod.fst he)) (Fin.ext (congrArg Prod.snd he)) + +def cellEquiv (A : Instance (Fin m) (Fin n)) : + Fin (catalog (input A)).length ≃ SmallCell A := + Equiv.ofBijective (catalogCell A) (catalogCell_bijective A) + +lemma capacities_eq (A : Instance (Fin m) (Fin n)) : + capacities (input A)=List.ofFn (fun i => A.b ((cellEquiv A) i).val.1 ((cellEquiv A) i).val.2) := by + apply List.ext_getElem + · simp only [capacities,List.length_map,List.length_ofFn] + · intro i hi hj + have hi' : i<(catalog (input A)).length := by simpa only [List.length_ofFn] using hj + simp only [capacities,List.getElem_map,List.getElem_ofFn] + have he := catalogCell_coordinates A ⟨i,hi'⟩ + change entry (input A,(catalog (input A))[i]'hi')= + A.b (catalogCell A ⟨i,hi'⟩).val.1 (catalogCell A ⟨i,hi'⟩).val.2 + rw [←he] + exact entry_input A _ _ + +end +end ContingencyTables.CompanionCellCatalog + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionChainValidator.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionChainValidator.lean new file mode 100644 index 0000000000000000000000000000000000000000..a1623e6420f3c36983391ea7babd7db289847bb0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionChainValidator.lean @@ -0,0 +1,169 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionArithmeticProposal +import OAI.Combinatorics.ContingencyTables.Sampling.SmallPatternProgram + +namespace OAI + +/-! # Polynomial validation of paired binary states + +The bounded-profile arithmetic test specializes to width one. +Thus the companion's state filter is a concrete list program on the two +coordinates of every labelled pair. +-/ + +namespace ContingencyTables.CompanionChainValidator +open CommonBasesFPRAS TwoLiftStates ProfilePrograms +open MatchingFPRAS.TreeTyped +open scoped BigOperators Classical + +noncomputable section + +variable {P : Type*} [Fintype P] + +omit [Fintype P] in +lemma single_iff_occupancy (S : Set (P×Bool)) (p : P) : + PairSingle (pair p) S ↔ occupancy S p=1 := by + unfold PairSingle TwoLiftStates.pair occupancy + by_cases h0 : (p,false)∈S <;> by_cases h1 : (p,true)∈S <;> simp [h0,h1] + +omit [Fintype P] in +lemma empty_iff_occupancy (S : Set (P×Bool)) (p : P) : + PairEmpty (pair p) S ↔ occupancy S p=0 := by + unfold PairEmpty TwoLiftStates.pair occupancy + by_cases h0 : (p,false)∈S <;> by_cases h1 : (p,true)∈S <;> simp [h0,h1] + +omit [Fintype P] in +lemma full_iff_occupancy (S : Set (P×Bool)) (p : P) : + PairFull (pair p) S ↔ occupancy S p=2 := by + unfold PairFull TwoLiftStates.pair occupancy + by_cases h0 : (p,false)∈S <;> by_cases h1 : (p,true)∈S <;> simp [h0,h1] + +lemma plain_iff_occupancy (S : Set (P×Bool)) : + PlainState pairs S ↔ ∀ p,occupancy S p=1 := by + constructor + · intro h p + exact (single_iff_occupancy S p).mp (h (pair p) (pair_mem p)) + · intro h p hp + obtain ⟨q,_,rfl⟩ := List.mem_map.mp hp + exact (single_iff_occupancy S q).mpr (h q) + +lemma defect_iff_occupancy (S : Set (P×Bool)) (p q : P) : + DefectState pairs (pair p) (pair q) S ↔ p≠q ∧ + ∀ i,occupancy S i+(if i=p then 1 else 0)=1+(if i=q then 1 else 0) := by + constructor + · intro h + exact ⟨fun he => h.2.2.1 (congrArg pair he),defect_occupancy S p q h⟩ + · rintro ⟨hpq,h⟩ + refine ⟨pair_mem p,pair_mem q,fun he => hpq (pair_injective he),?_,?_,?_⟩ + · apply (empty_iff_occupancy S p).mpr + have hh := h p + simp only [ite_true,hpq,ite_false] at hh + omega + · apply (full_iff_occupancy S q).mpr + have hh := h q + simp only [ite_true,Ne.symm hpq,ite_false,Nat.add_zero] at hh + omega + · intro t ht htp htq + obtain ⟨i,_,rfl⟩ := List.mem_map.mp ht + apply (single_iff_occupancy S i).mpr + have hip : i≠p := fun he => htp (congrArg pair he) + have hiq : i≠q := fun he => htq (congrArg pair he) + simpa only [hip,hiq,ite_false,Nat.add_zero] using h i + +lemma chain_iff_occupancy (S : Set (P×Bool)) : + ChainState pairs S ↔ (∀ i,occupancy S i=1) ∨ + ∃ p q : P,p≠q ∧ ∀ i,occupancy S i+(if i=p then 1 else 0)=1+(if i=q then 1 else 0) := by + constructor + · rintro (h|⟨p,q,h⟩) + · exact Or.inl ((plain_iff_occupancy S).mp h) + · obtain ⟨a,_,rfl⟩ := List.mem_map.mp h.1 + obtain ⟨b,_,rfl⟩ := List.mem_map.mp h.2.1 + exact Or.inr ⟨a,b,(defect_iff_occupancy S a b).mp h⟩ + · rintro (h|⟨p,q,h⟩) + · exact Or.inl ((plain_iff_occupancy S).mpr h) + · exact Or.inr ⟨pair p,pair q,(defect_iff_occupancy S p q).mpr h⟩ + +/-- Width one is exactly the companion's labelled paired-state test. -/ +theorem paired_pattern_iff {m : ℕ} (e : Fin m ≃ P) (S : Set (P×Bool)) : + patternTest ((List.ofFn (fun i => if (e i,false)∈S then 1 else 0), + List.ofFn (fun i => if (e i,true)∈S then 1 else 0)),1)=true ↔ ChainState pairs S := by + rw [patternTest_ofFn,chain_iff_occupancy] + change (∀ i,occupancy S (e i)=1) ∨ + (∃ p q : Fin m,p≠q ∧ ∀ i,occupancy S (e i)+(if i=p then 1 else 0)= + 1+(if i=q then 1 else 0)) ↔ _ + constructor + · rintro (h|⟨p,q,hpq,h⟩) + · exact Or.inl (fun i => by simpa using h (e.symm i)) + · refine Or.inr ⟨e p,e q,fun he => hpq (e.injective he),?_⟩ + intro i + simpa only [Equiv.apply_symm_apply,e.symm_apply_eq] using h (e.symm i) + · rintro (h|⟨p,q,hpq,h⟩) + · exact Or.inl (fun i => h (e i)) + · refine Or.inr ⟨e.symm p,e.symm q,fun he => hpq (e.symm.injective he),?_⟩ + intro i + simpa only [←e.eq_symm_apply] using h (e i) + +end + +abbrev ValidatorInput := List (ℕ×ℕ)×List ℕ + +def pairFirstLookup : Realizer (fun z : List ℕ×(ℕ×ℕ) => z.1.getD z.2.1 0) := + composition (pair first (composition second first)) (getDFast 0) + +def pairSecondLookup : Realizer (fun z : List ℕ×(ℕ×ℕ) => z.1.getD z.2.2 0) := + composition (pair first (composition second second)) (getDFast 0) + +lemma polynomial_pairFirstLookup : PolynomialTime pairFirstLookup := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) (polynomial_getDFast 0) + +lemma polynomial_pairSecondLookup : PolynomialTime pairSecondLookup := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_second)) (polynomial_getDFast 0) + +def pairedStateTest (z : ValidatorInput) : Bool := + patternTest (((z.1.map (fun ij => z.2.getD ij.1 0)), + (z.1.map (fun ij => z.2.getD ij.2 0))),1) + +def pairedStateTestRealizer : Realizer pairedStateTest := + composition (pair (pair + (composition (pair second first) (mapWith pairFirstLookup)) + (composition (pair second first) (mapWith pairSecondLookup))) (constant 1)) patternTestRealizer + +theorem polynomial_pairedStateTest : PolynomialTime pairedStateTestRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_pairFirstLookup)) + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_pairSecondLookup))) (polynomial_constant 1)) polynomial_patternTest + +noncomputable section +open CompanionFactorialApplication CompanionArithmeticProposal +variable {I J : Type} [Fintype I] [Fintype J] + +def labelEquiv (A : Instance I J) : Fin (Fintype.card (Labels A)) ≃ Labels A := + (Fintype.equivFin _).symm + +def pairCatalog (A : Instance I J) : List (ℕ×ℕ) := + List.ofFn (fun i => ((coordinateEquiv A (labelEquiv A i,false)).val, + (coordinateEquiv A (labelEquiv A i,true)).val)) + +/-- This list program checks the literal companion state, with no +feasibility oracle or whole-state enumeration. -/ +theorem pairedStateTest_encode (A : Instance I J) (S : Set (Labels A×Bool)) : + pairedStateTest (pairCatalog A,encodeSet (coordinateEquiv A) S)=true ↔ ChainState pairs S := by + unfold pairedStateTest pairCatalog + simp only [List.map_ofFn] + change patternTest ((List.ofFn (fun i : Fin (Fintype.card (Labels A)) => + (encodeSet (coordinateEquiv A) S).getD + (coordinateEquiv A (labelEquiv A i,false)).val 0), + List.ofFn (fun i : Fin (Fintype.card (Labels A)) => + (encodeSet (coordinateEquiv A) S).getD + (coordinateEquiv A (labelEquiv A i,true)).val 0)),1)=true ↔ _ + simp only [encodeSet,getD_setProfile,setProfile,coordinateSet,Set.mem_preimage, + Equiv.symm_apply_apply] + exact paired_pattern_iff (labelEquiv A) S + +end +end ContingencyTables.CompanionChainValidator + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCodeBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCodeBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..57c5b84db8d90d0e9a40ea357eb52f918875c9e4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCodeBounds.lean @@ -0,0 +1,93 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseProgram + +namespace OAI + +/-! # Encoded profile bounds independent of learned multiplier sizes -/ +namespace ContingencyTables.CompanionCodeBounds +open MatchingFPRAS MatchingFPRAS.TreeTyped + +lemma restart_next (i : ℕ) (s : CompanionRestartProgram.State) : + weight (CompanionRestartProgram.next (i,s)) ≤ 6*s.1.1.2.length+1 := by + simpa only [CompanionRestartProgram.next,CompanionRestartProgram.bound,Nat.size_one, Nat.reduceMul,Nat.reduceAdd,Nat.mul_comm] using + ProfilePrograms.capView_weight s.1.1.2.length 1 (CompanionRestartProgram.candidate (i,s)) + +lemma restart_fold (is : List ℕ) (s : CompanionRestartProgram.State) : + weight ((is.foldl (fun s i => CompanionRestartProgram.advance (i,s)) s).2) ≤ + max (weight s.2) (6*s.1.1.2.length+1) := by + induction is using List.reverseRecOn with + | nil => exact le_max_left _ _ + | append_singleton is i _ => + rw [List.foldl_append] + simp only [List.foldl_cons,List.foldl_nil] + apply (restart_next _ _).trans + rw [CompanionRestartProgram.fold_fixed] + exact le_max_right _ _ + +lemma restart_output (z : CompanionRestartProgram.Input) : + weight (CompanionRestartProgram.output z) ≤ 7*weight z.1.2+1 := by + have h := restart_fold (CompanionRestartProgram.indices z) (z,z.1.2) + change weight (CompanionRestartProgram.output z) ≤ _ at h + dsimp only at h + have hl := list_length_le_weight z.1.2 + exact h.trans (max_le (by omega) (by omega)) + +lemma initialized_output (z : CompanionInitializedRestartProgram.Input) : + weight (CompanionInitializedRestartProgram.output z) ≤ + 7*weight (CompanionInitializedRestartProgram.initialCode z)+1 := + restart_output (CompanionInitializedRestartProgram.prepare z) + +lemma walk_next (bits : List Bool) (s : CompanionBoundedWalkProgram.State) : + weight (CompanionBoundedWalkProgram.next (bits,s)) ≤ 6*s.1.2.length+1 := by + simpa only [CompanionBoundedWalkProgram.next,CompanionBoundedWalkProgram.bound,Nat.size_one,Nat.reduceMul,Nat.reduceAdd,Nat.mul_comm] using + ProfilePrograms.capView_weight s.1.2.length 1 (CompanionBoundedWalkProgram.candidate (bits,s)) + +lemma record_bound (words : List (List Bool)) (s : CompanionBoundedWalkProgram.RecordState) + (B : ℕ) (hc : weight s.1.2 ≤ B) (hf : 6*s.1.1.2.length+1 ≤ B) + (hh : ∀ code∈s.2,weight code ≤ B) : + let out := words.foldl (fun s bits => CompanionBoundedWalkProgram.recordAdvance (bits,s)) s + (∀ code∈out.2,weight code ≤ B) ∧ out.2.length=s.2.length+words.length := by + induction words generalizing s with + | nil => exact ⟨hh,by simp⟩ + | cons word words ih => + have hn := (walk_next word s.1).trans hf + have h := ih (CompanionBoundedWalkProgram.recordAdvance (word,s)) hn hf (by + intro code hcode + rcases List.mem_cons.mp hcode with he | he + · subst code; exact hn + · exact hh code he) + exact ⟨h.1,by simpa only [List.foldl_cons,CompanionBoundedWalkProgram.recordAdvance, + List.length_cons,Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using h.2⟩ + +lemma history_bound (s : CompanionBoundedWalkProgram.State) (words : List (List Bool)) + (B : ℕ) (hc : weight s.2 ≤ B) (hf : 6*s.1.2.length+1 ≤ B) : + (∀ code∈CompanionBoundedWalkProgram.history (s,words),weight code ≤ B) ∧ + (CompanionBoundedWalkProgram.history (s,words)).length=words.length+1 := by + have h := record_bound words (s,[s.2]) B hc hf (by simpa only [List.mem_singleton] using + fun code he => he ▸ hc) + constructor + · intro code hcode + exact h.1 code (List.mem_reverse.mp hcode) + · simpa only [CompanionBoundedWalkProgram.history,CompanionBoundedWalkProgram.recordWalk, + CompanionBoundedWalkProgram.initialRecord,List.length_reverse,List.length_cons,List.length_nil, + Nat.add_comm] using h.2 + +lemma trajectory_length (z : CompanionTrajectoryProgram.Input) : + (CompanionTrajectoryProgram.output z).length ≤ z.2.length+1 := by + let s := z.1.1 + let words := CompanionFlatReturnProgram.words z + have h := history_bound s words (weight s.2+6*s.1.2.length+1) (by omega) (by omega) + have hlen : (CompanionTrajectoryProgram.output z).length=words.length+1 := h.2 + have hl : words.length ≤ z.2.length := by + unfold words CompanionFlatReturnProgram.words DensePrograms.wordChunks DensePrograms.completeWordRows + simp only [List.length_take,List.length_map,List.length_range] + exact (min_le_right _ _).trans (Nat.div_le_self _ _) + omega + +lemma trajectory_codes (z : CompanionTrajectoryProgram.Input) (B : ℕ) + (hc : weight z.1.1.2 ≤ B) (hf : 6*z.1.1.1.2.length+1 ≤ B) : + ∀ code∈CompanionTrajectoryProgram.output z,weight code ≤ B := + (history_bound z.1.1 (CompanionFlatReturnProgram.words z) B hc hf).1 + +end ContingencyTables.CompanionCodeBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionComputedInitial.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionComputedInitial.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e0abac8a1a90e2a4492b49a701be62710a7f249 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionComputedInitial.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCellCatalogProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalEncoding + +namespace OAI + +/-! # Initialization from the computed small-cell catalog + +The proof-level equivalence follows the actual catalog program. It is +used only to identify the output of the binary list initializer with a +paired transversal and to transfer its distributional error bound. +-/ + +namespace ContingencyTables.CompanionComputedInitial + +open MatchingFPRAS.TreeTyped CompanionFactorialApplication +open InitialTransversals InitialFactorialBits CompanionInitialDraw +open FirstSuccess ResidualMixture TwoLiftStates CommonBasesFPRAS +open CompanionArithmeticProposal +open scoped BigOperators Classical + +abbrev ProgramInput := (CompanionCellCatalog.Input×ℕ)×List Bool + +def initialProgram (z : ProgramInput) : List ℕ := + CanonicalInitialEncoding.initialCode ((CompanionCellCatalog.capacities z.1.1,z.1.2),z.2) + +def initialProgramRealizer : Realizer initialProgram := + composition (pair (pair + (composition (composition first first) CompanionCellCatalog.capacitiesRealizer) + (composition first second)) second) CanonicalInitialEncoding.initialCodeRealizer + +theorem polynomial_initialProgram : PolynomialTime initialProgramRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + CompanionCellCatalog.polynomial_capacities) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second) + CanonicalInitialEncoding.polynomial_initialCode + +noncomputable section +variable {m n : ℕ} (A : Instance (Fin m) (Fin n)) + +def cellOrder : SmallCell A ≃ Fin (CompanionCellCatalog.catalog (CompanionCellCatalog.input A)).length := + (CompanionCellCatalog.cellEquiv A).symm + +def capacities (i : Fin (CompanionCellCatalog.catalog (CompanionCellCatalog.input A)).length) : ℕ := + A.b ((cellOrder A).symm i).val.1 ((cellOrder A).symm i).val.2 + +def wordLength (B : ℕ) : ℕ := bitCount (capacities A) B + +def initialDraw (B : ℕ) (bits : Fin (wordLength A B) → Bool) : + PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) := + indexEquiv A (transversalDraw (fun s : SmallCell A => A.b s.val.1 s.val.2) + (cellOrder A) B bits) + +def copyOrder : Labels A ≃ Copy (capacities A) := Equiv.sigmaCongrLeft' (cellOrder A) + +def pairOrder : (Labels A×Bool) ≃ (Copy (capacities A)×Bool) := + Equiv.prodCongr (copyOrder A) (Equiv.refl Bool) + +def coordinateOrder : (Labels A×Bool) ≃ Fin (CanonicalInitialEncoding.pairOrder (capacities A)).length := + (pairOrder A).trans (CanonicalInitialEncoding.coordinateEquiv (capacities A)) + +lemma encodeSet_reindex (S : Set (Labels A×Bool)) : + encodeSet (coordinateOrder A) S= + encodeSet (CanonicalInitialEncoding.coordinateEquiv (capacities A)) + ((pairOrder A).symm ⁻¹' S) := rfl + +lemma draw_preimage (B : ℕ) (bits : Fin (wordLength A B) → Bool) : + (pairOrder A).symm ⁻¹' (initialDraw A B bits).val.val= + encode (capacities A) (drawChoices (capacities A) B bits) := by + ext p + rcases p with ⟨⟨i,k⟩,side⟩ + have hc := Equiv.piCongrLeft'_symm_apply_apply + (fun s : SmallCell A => Finset (Fin (A.b s.val.1 s.val.2))) + (cellOrder A) (drawChoices (capacities A) B bits) i + cases side + · change k∈(choiceEquiv (fun s : SmallCell A => A.b s.val.1 s.val.2) + (cellOrder A) (drawChoices (capacities A) B bits)) ((cellOrder A).symm i) ↔ + k∈drawChoices (capacities A) B bits i + exact Iff.of_eq (congrArg (fun S => k∈S) hc) + · change k∉(choiceEquiv (fun s : SmallCell A => A.b s.val.1 s.val.2) + (cellOrder A) (drawChoices (capacities A) B bits)) ((cellOrder A).symm i) ↔ + k∉drawChoices (capacities A) B bits i + exact Iff.of_eq (congrArg (fun S => k∉S) hc) + +/-- The complete program computes the semantic initializer with the +coordinate order recovered from the program's own catalog. -/ +theorem initialProgram_eq (B : ℕ) (hB : 0 + (A.hsmall _ _ ((cellOrder A).symm i).property).le) + exact hh.trans (Nat.mul_le_mul_right B + (Nat.mul_le_mul_right (A.W+1) (catalog_count_le A))) + +/-- The computed-order initializer has the same μ₀ reference law and +error guarantee as the abstract-order initializer. -/ +theorem initialDraw_error (B : ℕ) : + variation (mapLaw (uniformLaw (α := Fin (wordLength A B) → Bool)) (initialDraw A B)) + (idealLaw A)≤(A.d:ℚ)*(3*A.W+1)/(2*(2:ℚ)^B) := by + unfold initialDraw wordLength capacities + have he := mapLaw_equiv_output (indexEquiv A) + (uniformLaw (α := Fin (bitCount + (fun i => A.b ((cellOrder A).symm i).val.1 ((cellOrder A).symm i).val.2) B) → Bool)) + (transversalDraw (fun s : SmallCell A => A.b s.val.1 s.val.2) (cellOrder A) B) + rw [he,idealLaw,variation_equiv] + have ht := transversalDraw_error (fun s : SmallCell A => A.b s.val.1 s.val.2) + (cellOrder A) B A.W (fun s => (A.hsmall _ _ s.property).le) + apply ht.trans + apply div_le_div_of_nonneg_right _ (by positivity) + apply mul_le_mul_of_nonneg_right _ (by positivity) + exact_mod_cast catalog_count_le A + +theorem initialDraw_precision (h : ℕ) : + variation (mapLaw (uniformLaw (α := Fin (wordLength A (precision A h)) → Bool)) + (initialDraw A (precision A h))) (idealLaw A)≤1/(2:ℚ)^h := + (initialDraw_error A (precision A h)).trans (precision_error A h) + +end +end ContingencyTables.CompanionComputedInitial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionComputedProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionComputedProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c13f06e8471116929b92adea3759acf8962f378 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionComputedProposal.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionComputedInitial +import OAI.Combinatorics.ContingencyTables.Machines.PairedCatalogProgram + +namespace OAI + +/-! # The companion proposal with computed metadata + +The executable proposal receives only a binary profile and fresh bits. +It computes the consecutive-pair catalog itself and scans coordinate +exchanges. Its semantic law is the same ordered proposal law. +-/ + +namespace ContingencyTables.CompanionComputedProposal + +open MatchingFPRAS.TreeTyped CompanionFactorialApplication CompanionComputedInitial +open CompanionArithmeticProposal CompanionOrderedProposal CompanionNeighborProgram +open CompanionBooleanPhase +open scoped Classical + +def proposalProgram (z : List ℕ×List Bool) : Option (List ℕ) := + codeProposal ((PairedCatalogProgram.catalog z.1,z.1),z.2) + +def catalogInputRealizer : Realizer (fun z : List ℕ×List Bool => PairedCatalogProgram.catalog z.1) := + composition (f := fun z : List ℕ×List Bool => z.1) (g := PairedCatalogProgram.catalog) + first PairedCatalogProgram.catalogRealizer + +def proposalProgramRealizer : Realizer proposalProgram := + composition (f := fun z : List ℕ×List Bool => ((PairedCatalogProgram.catalog z.1,z.1),z.2)) + (g := codeProposal) (pair (pair catalogInputRealizer first) second) codeProposalRealizer + +theorem polynomial_proposalProgram : PolynomialTime proposalProgramRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first PairedCatalogProgram.polynomial_catalog) + polynomial_first) polynomial_second) polynomial_codeProposal + +noncomputable section +variable {m n : ℕ} (A : Instance (Fin m) (Fin n)) + +def pairLabels : Fin (CanonicalInitialEncoding.copyOrder (capacities A)).length ≃ Labels A := + (PairedCatalogProgram.labelOrder (capacities A)).trans (copyOrder A).symm + +lemma pair_coordinate (i : Fin (CanonicalInitialEncoding.copyOrder (capacities A)).length) + (side : Bool) : + coordinateOrder A (pairLabels A i,side)= + CanonicalInitialEncoding.coordinateEquiv (capacities A) + (PairedCatalogProgram.labelOrder (capacities A) i,side) := by + simp [coordinateOrder,pairOrder,pairLabels] + +lemma generated_catalog (S : Set (Labels A×Bool)) : + PairedCatalogProgram.catalog (encodeSet (coordinateOrder A) S)= + orderedCatalog A (pairLabels A) (coordinateOrder A) := by + have he : encodeSet (coordinateOrder A) S= + encodeSet (CanonicalInitialEncoding.coordinateEquiv (capacities A)) + ((pairOrder A).symm ⁻¹' S) := rfl + rw [he,PairedCatalogProgram.catalog_encode] + unfold orderedCatalog + apply congrArg List.ofFn + funext i + rw [pair_coordinate,pair_coordinate] + +/-- Every proposed code is the encoding of the actual ordered proposal +state, and unused binary indices give precisely the same `none` result. -/ +theorem proposalProgram_eq (S : State A) (bits : Fin (proposalBits A) → Bool) : + proposalProgram (encodeSet (coordinateOrder A) S.val,List.ofFn bits)= + (orderedProposal A (coordinateOrder A) S bits).map + (fun T => encodeSet (coordinateOrder A) T.val) := by + unfold proposalProgram + rw [generated_catalog] + exact codeProposal_ordered A (pairLabels A) (coordinateOrder A) S bits + +end +end ContingencyTables.CompanionComputedProposal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionConcentration.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionConcentration.lean new file mode 100644 index 0000000000000000000000000000000000000000..0de5d3ebe7a88ba5d7fdd68ec8d300c2f6b3c33e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionConcentration.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierUpdate +import OAI.Combinatorics.ContingencyTables.Transport.ObservableTrajectory + +namespace OAI + +/-! # Concentration of the literal companion phase observables -/ + +namespace ContingencyTables.CompanionConcentration + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication CompanionAnnealing CompanionMultiplierUpdate +open TwoLiftStates BinaryContraction DegreeCompletion ObservableBounds + +variable {I J : Type*} [Fintype I] [Fintype J] + +private lemma observable_constant_nonnegative (p q : ℝ) (hp : 0 ≤ p) (hq : 0 ≤ q) : + 0 ≤ observableConstant p q := by + unfold observableConstant + positivity + +private lemma bounded_variance_factor (p K v N : ℝ) (hK : 0 ≤ K) + (hN : 0 ≤ N) (hv : v ≤ 1) : + 2*(10*p^2)*K*v/N ≤ 20*p^2*K/N := by + apply div_le_div_of_nonneg_right _ hN + nlinarith [mul_le_mul_of_nonneg_left hv (show 0 ≤ 2*(10*p^2)*K by positivity)] + +lemma pairs_ne_nil (A : Instance I J) (hp : 0< Fintype.card (Labels A)) : + (pairs : List ((Labels A×Bool)×(Labels A×Bool)))≠[] := by + apply List.ne_nil_of_length_pos + simpa only [PairedLabels.length] using hp + +lemma actual_degree (A : Instance I J) (j : ℕ) : + DegreePositive (weight A j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length ∧ + OmissionProperty (weight A j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length := by + have hs := first_properties A ((j:ℝ)/scale A) (div_nonneg (Nat.cast_nonneg j) (scale_positive A).le) + simpa only [weight,PairedLabels.length] using hs + +lemma square_width_one_le (A : Instance I J) : (1:ℝ)≤(A.W:ℝ)^2 := by + have hW : (2:ℝ)≤ A.W := by exact_mod_cast A.hW + nlinarith + +/-- Every actual phase observable has the source's mean-square bound +20 p² Kobs/N under a 10 p²-warm start of its original labelled chain. -/ +theorem bounded_MSE (A : Instance I J) (j : ℕ) (hp : 0< Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A j) w) (o : PhaseObservables (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) + (nu : ChainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) + (hwarm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs w (weight A j) S.val/chainTotal pairs w (weight A j)) + (N : ℕ) (hN : 0< N) : + let C := metropolisChain pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w + (completeDegree (weight A j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) + hw.positive (completeDegree_positive _ _ (actual_degree A j).1) + let G := fun S : ChainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) => + phaseObservable pairs (ratio A j) o S.val + (∑ S,nu S*C.squareMoment (fun S => G S-C.mean G) N S)/(N:ℝ)^2≤ + 20*(Fintype.card (Labels A):ℝ)^2* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/N := by + let gs : List ((Labels A×Bool)×(Labels A×Bool)) := pairs + let F := completeDegree (weight A j) gs.length + have hF := completeDegree_positive (weight A j) gs.length (actual_degree A j).1 + let C := metropolisChain gs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w F hw.positive hF + let G : Set (Labels A×Bool) → ℝ := phaseObservable gs (ratio A j) o + have hG : ∀ S,0≤ G S ∧ G S≤1 := by + intro S + exact phaseObservable_bounded gs (ratio A j) + (fun T _ => ⟨by linarith [(ratio_bounds A j T).1],(ratio_bounds A j T).2⟩) o S + have h := ObservableTrajectory.omission_chain_timeAverage gs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover w (weight A j) G hw.positive (actual_degree A j).1 (actual_degree A j).2 + ((A.W:ℝ)^2) (square_width_one_le A) (phaseObservable_class gs (ratio A j) o) + hw.lower hw.upper (10*(Fintype.card (Labels A):ℝ)^2) (by positivity) nu hwarm N hN + have hv := C.variance_le_one (fun S => G S.val) (fun S => hG S.val) + change C.variance (fun S => G S.val)≤1 at hv + rw [metropolisChain_variance,chainVariance_completion gs (weight A j) G w + PairedLabels.fresh PairedLabels.cover] at hv + have hm : C.mean (fun S => G S.val)=chainMean gs w (weight A j) G := by + rw [metropolisChain_mean,chainMean_completion gs (weight A j) G w + PairedLabels.fresh PairedLabels.cover] + change (∑ S,nu S*C.squareMoment (fun S => G S.val-C.mean (fun T => G T.val)) N S)/(N:ℝ)^2≤ _ + rw [hm] + calc + _ ≤ 2*(10*(Fintype.card (Labels A):ℝ)^2)*ObservableBounds.observableConstant gs.length ((A.W:ℝ)^2)* + chainVariance gs w (weight A j) G/N := h + _ ≤ 20*(Fintype.card (Labels A):ℝ)^2*observableConstant gs.length ((A.W:ℝ)^2)/N := + bounded_variance_factor _ _ _ _ + (observable_constant_nonnegative _ _ (Nat.cast_nonneg _) (sq_nonneg _)) (Nat.cast_nonneg _) hv + _ = _ := by simp only [gs,PairedLabels.length] + +/-- The source's finite union bound for all actual phase observables. +The warm-start hypothesis is the restart endpoint condition, rather than +an independent phase-concentration assumption. -/ +theorem phase_failure (A : Instance I J) (j : ℕ) (hp : 0< Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A j) w) + (nu : ChainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) + (hnu : ∀ S,0≤ nu S) + (hwarm : ∀ S,nu S≤(10*(Fintype.card (Labels A):ℝ)^2)* + chainWeight pairs w (weight A j) S.val/chainTotal pairs w (weight A j)) + (N : ℕ) (hN : 0< N) (eta : ℝ) (heta : 0< eta) : + let C := metropolisChain pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w + (completeDegree (weight A j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) + hw.positive (completeDegree_positive _ _ (actual_degree A j).1) + C.pathProbability nu (N-1) (fun l => ∃ o : PhaseObservables (pairs : List ((Labels A×Bool)×(Labels A×Bool))), + eta*C.mean (fun S => phaseObservable pairs (ratio A j) o S.val)< + |FiniteChain.pathSum (fun S => phaseObservable pairs (ratio A j) o S.val) l/(N:ℝ)- + C.mean (fun S => phaseObservable pairs (ratio A j) o S.val)|)≤ + 16000*(Fintype.card (Labels A):ℝ)^8* + ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)/((N:ℝ)*eta^2) := by + let gs : List ((Labels A×Bool)×(Labels A×Bool)) := pairs + let F := completeDegree (weight A j) gs.length + have hF := completeDegree_positive (weight A j) gs.length (actual_degree A j).1 + let C := metropolisChain gs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w F hw.positive hF + let p : ℝ := Fintype.card (Labels A) + let K := ObservableBounds.observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) + have hpR : 0< p := by dsimp only [p]; exact_mod_cast hp + have hK : 0≤ K := observable_constant_nonnegative _ _ (Nat.cast_nonneg _) (sq_nonneg _) + have hNR : (0:ℝ)< N := by exact_mod_cast hN + have hmean (o : PhaseObservables gs) : + 1/(20*p^2)≤ C.mean (fun S => phaseObservable gs (ratio A j) o S.val) := by + rw [metropolisChain_mean,chainMean_completion gs (weight A j) + (phaseObservable gs (ratio A j) o) w PairedLabels.fresh PairedLabels.cover] + have hh := phaseObservable_mean_lower gs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + w (weight A j) (ratio A j) hw.positive (weight_positive A j) + (fun S _ => (ratio_bounds A j S).1) hw.lower hw.upper o + simpa only [p,gs,PairedLabels.length] using hh + have hb := C.relative_union_bound nu hnu + (fun o S => phaseObservable gs (ratio A j) o S.val) + (1/(20*p^2)) eta (20*p^2*K/N) (by positivity) heta (by positivity) hmean N hN + (fun o => bounded_MSE A j hp w hw o nu hwarm N hN) + have hJ : (Fintype.card (PhaseObservables gs):ℝ)≤2*p^2 := by + have hc := phaseObservables_card gs PairedLabels.fresh (pairs_ne_nil A hp) + simp only [gs,PairedLabels.length] at hc + dsimp only [p,gs] + exact_mod_cast hc + apply hb.trans + calc + _ ≤ (2*p^2)*(20*p^2*K/N)/(eta*(1/(20*p^2)))^2 := + div_le_div_of_nonneg_right (mul_le_mul_of_nonneg_right hJ (by positivity)) (sq_nonneg _) + _ = 16000*p^8*K/((N:ℝ)*eta^2) := by + field_simp [hpR.ne',heta.ne',hNR.ne'] + ring + +end ContingencyTables.CompanionConcentration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCorrectionArithmetic.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCorrectionArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..478de74abf1021f739061dc4e42f9bfba3ddaf37 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCorrectionArithmetic.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleDraw +import OAI.Combinatorics.ContingencyTables.Transport.PowerOfTwoApproximation + +namespace OAI + +/-! # Rational evaluation of the literal integer-population correction -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def rationalIntegerPoint (A : Instance I J) (C : ℕ) (f : FreeIndex A.small A.T A.b) : + Fin (dimension A) → ℚ := fun i => + (rationalBinWidth A C:ℚ)*(f (index A i)).val/freeRange A (index A i) + +lemma rationalIntegerPoint_cast (A : Instance I J) (C : ℕ) (f : FreeIndex A.small A.T A.b) + (i : Fin (dimension A)) : + (rationalIntegerPoint A C f i:ℝ)=integerPoint A C f i := by + simp only [rationalIntegerPoint,Rat.cast_div,Rat.cast_mul,Rat.cast_natCast,rationalBinWidth_cast, + integerPoint,ForestScaledPenalty.integerCube,freeRange,Nat.cast_add,Nat.cast_one] + push_cast + rfl + +def correctionExponent (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : ℚ := + (gridExponent A C a z (integerBin A K hK f):ℚ)- + (a:ℚ)/rationalHeight A C*rationalD A C z (rationalIntegerPoint A C f) + +lemma correctionExponent_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : + (correctionExponent A C a z K hK f:ℝ)= + (gridExponent A C a z (integerBin A K hK f):ℝ)- + (a:ℝ)/height A C*D A C z (integerPoint A C f) := by + simp only [correctionExponent,Rat.cast_sub,Rat.cast_natCast,Rat.cast_mul,Rat.cast_div, + rationalHeight_cast,rationalD_cast,rationalIntegerPoint_cast] + +/-- The exponent passed to numerical approximation is a bounded rational, +although the original capacities may be arbitrarily large. -/ +theorem correctionExponent_bounds (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hB : (K:ℝ)=binWidth A C) (f : FreeIndex A.small A.T A.b) : + -2 ≤ correctionExponent A C a z K hK f ∧ correctionExponent A C a z K hK f ≤ 2 := by + have hCR : (0:ℝ) < C := by exact_mod_cast hC + have haHR : (a:ℝ) ≤ height A C := by rw [←rationalHeight_cast]; exact_mod_cast haH + have hd := exponent_change A C a hCR (Nat.cast_nonneg _) haHR z + (realCorner (integerBin A K hK f)) (integerPoint A C f) 1 (by norm_num) + (fun i => by simpa only [abs_sub_comm] using integerPoint_distance A C K hK hB f i) + have he := gridExponent_eq_floor A C a z (integerBin A K hK f) + have hlo := Int.floor_le ((a:ℝ)/height A C*D A C z (realCorner (integerBin A K hK f))) + have hhi := Int.lt_floor_add_one ((a:ℝ)/height A C*D A C z (realCorner (integerBin A K hK f))) + rw [←he] at hlo hhi + have hbounds : (-2:ℝ) ≤ (correctionExponent A C a z K hK f:ℝ) ∧ + (correctionExponent A C a z K hK f:ℝ) ≤ 2 := by + rw [correctionExponent_cast] + simp only [Int.cast_natCast] at hlo hhi + rcases abs_le.mp hd with ⟨hl,hu⟩ + constructor <;> linarith + constructor + · exact_mod_cast hbounds.1 + · exact_mod_cast hbounds.2 + +def rationalPopulation (A : Instance I J) (K : ℕ) (hK : 0 < K) + (f : FreeIndex A.small A.T A.b) : ℚ := + (K:ℚ)^dimension A*(integerFiber A K hK (integerBin A K hK f)).card/assignmentCount A + +lemma rationalPopulation_positive (A : Instance I J) (K : ℕ) (hK : 0 < K) + (f : FreeIndex A.small A.T A.b) : 0 < rationalPopulation A K hK f := by + unfold rationalPopulation + apply div_pos + · exact mul_pos (pow_pos (by exact_mod_cast hK) _) (by exact_mod_cast ownFiber_positive A K hK f) + · exact_mod_cast assignmentCount_positive A + +lemma correction_eq_population_power (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : + correction A C a z K hK f=(rationalPopulation A K hK f:ℝ)* + (2:ℝ)^(correctionExponent A C a z K hK f:ℝ) := by + have hV : gridWeight A C a z (integerBin A K hK f)= + (2:ℝ)^(-(gridExponent A C a z (integerBin A K hK f):ℝ)) := by + unfold gridWeight V DenseWeights.binWeight + rw [←gridExponent_eq_floor] + simp only [Int.cast_natCast] + have hr : rho A C a z (integerPoint A C f)/gridWeight A C a z (integerBin A K hK f)= + (2:ℝ)^(correctionExponent A C a z K hK f:ℝ) := by + rw [hV,correctionExponent_cast] + unfold rho DenseWeights.density + rw [←Real.rpow_sub (by norm_num : (0:ℝ)<2)] + congr 1 + ring + unfold correction + rw [mul_div_assoc,hr] + congr 1 + simp only [rationalPopulation,Rat.cast_div,Rat.cast_mul,Rat.cast_pow,Rat.cast_natCast] + +def computedCorrection (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (sigma : ℚ) (f : FreeIndex A.small A.T A.b) : ℚ := + rationalPopulation A K hK f* + PowerOfTwoApproximation.approximate (correctionExponent A C a z K hK f) sigma + +/-- A deterministic pointwise relative-error guarantee for the actual +rational correction returned on every integer assignment. -/ +theorem computedCorrection_error (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hB : (K:ℝ)=binWidth A C) + (sigma : ℚ) (hsigma : 0 < sigma) (f : FreeIndex A.small A.T A.b) : + |(computedCorrection A C a z K hK sigma f:ℝ)-correction A C a z K hK f| ≤ + (sigma:ℝ)*correction A C a z K hK f := by + have hb := correctionExponent_bounds A C a hC haH z K hK hB f + have he := PowerOfTwoApproximation.approximate_error _ sigma hb.1 hb.2 hsigma + have hp : (0:ℝ) ≤ rationalPopulation A K hK f := by + exact_mod_cast (rationalPopulation_positive A K hK f).le + rw [correction_eq_population_power] + simp only [computedCorrection,Rat.cast_mul] + rw [←mul_sub,abs_mul,abs_of_nonneg hp] + exact (mul_le_mul_of_nonneg_left he hp).trans_eq (by ring) + +/-- Positivity and a uniform range hold on all executions, independently +of the statistical event used by the estimator. -/ +theorem computedCorrection_bounds (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (sigma : ℚ) (hsigma : 0 < sigma) (hsigmaHalf : sigma ≤ 1/2) + (f : FreeIndex A.small A.T A.b) : + (1/16:ℝ) ≤ computedCorrection A C a z K hK sigma f ∧ + (computedCorrection A C a z K hK sigma f:ℝ) ≤ 8 := by + have haHR : (a:ℝ) ≤ height A C := by rw [←rationalHeight_cast]; exact_mod_cast haH + have hb := correction_bounds A C a (by exact_mod_cast hC) (Nat.cast_nonneg _) haHR z K hK hW hB f + have he := computedCorrection_error A C a hC haH z K hK hB sigma hsigma f + have hsR : (sigma:ℝ) ≤ 1/2 := by + simpa only [Rat.cast_div,Rat.cast_one,Rat.cast_ofNat] using + (Rat.cast_le (K := ℝ)).mpr hsigmaHalf + have hprod : (sigma:ℝ)*correction A C a z K hK f ≤ (1/2)*correction A C a z K hK f := + mul_le_mul_of_nonneg_right hsR (by linarith [hb.1]) + rcases abs_le.mp he with ⟨hl,hu⟩ + constructor <;> nlinarith + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCorrectionSamples.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCorrectionSamples.lean new file mode 100644 index 0000000000000000000000000000000000000000..8459b4845dc3dd8f3a8230df38bc05276500a9bc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionCorrectionSamples.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCorrectionArithmetic +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawRelativeError +import OAI.Combinatorics.ContingencyTables.Transport.FiniteBiasedAverages + +namespace OAI + +/-! # Confidence for the actual rational correction samples -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteLawMoments FiniteIndependentAverages +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def correctionMean (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) : ℝ := + expectation (stationaryIntegerLaw A C a z K hK hW) (correction A C a z K (by omega)) + +lemma correctionMean_eq (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) : + correctionMean A C a z K hK hW= + ∑ f : FreeIndex A.small A.T A.b, + correctedMass A C a z K (by omega) f*correction A C a z K (by omega) f := by + unfold correctionMean expectation + simp_rw [stationaryIntegerLaw_cast] + +lemma correctionMean_bounds (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) : + 1/8 ≤ correctionMean A C a z K hK hW ∧ correctionMean A C a z K hK hW ≤ 4 := by + have haHR : (a:ℝ) ≤ height A C := by rw [←rationalHeight_cast]; exact_mod_cast haH + exact expectation_bounds _ _ _ _ (correction_bounds A C a (by exact_mod_cast hC) + (Nat.cast_nonneg _) haHR z K (by omega) hW hB) + +def correctionSample (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (sigma : ℚ) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) + (bits : Fin (oracleIntegerBits A C n h) → Bool) : ℚ := + computedCorrection A C a z K (by omega) sigma (oracleIntegerDraw A C a z K hK hW v n h bits) + +lemma correctionSample_mean (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (sigma : ℚ) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) : + uniformAverage (fun bits => (correctionSample A C a z K hK hW sigma v n h bits:ℝ))= + expectation (sampledIntegerLaw A C a z K hK hW v n h) + (fun f => (computedCorrection A C a z K (by omega) sigma f:ℝ)) := by + unfold correctionSample + rw [word_expectation (oracleIntegerDraw A C a z K hK hW v n h) + (fun f => (computedCorrection A C a z K (by omega) sigma f:ℝ)),oracleIntegerDraw_law] + +/-- Both finite sampling error and deterministic rational power error +are bounded relative to the literal correction mean. -/ +theorem correctionSample_mean_bias (A : Instance I J) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q h : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (sigma : ℚ) (hsigma : 0 < sigma) (hsigmaHalf : sigma ≤ 1/2) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + |uniformAverage (fun bits => + (correctionSample A C a z K hK hW sigma v (oracleTime A C K Q theta) h bits:ℝ))- + correctionMean A C a z K hK hW| ≤ + 16*(theta/(8*Q)+(A.d:ℝ)/(2:ℝ)^(4*(h+A.d)))+ + (sigma:ℝ)*correctionMean A C a z K hK hW := by + let g := fun f => (computedCorrection A C a z K (by omega) sigma f:ℝ) + let p := sampledIntegerLaw A C a z K hK hW v (oracleTime A C K Q theta) h + let q := stationaryIntegerLaw A C a z K hK hW + have hsample : |expectation p g-expectation q g| ≤ + 16*(theta/(8*Q)+(A.d:ℝ)/(2:ℝ)^(4*(h+A.d))) := by + have he := expectation_difference p q g 8 (fun f => by + have hh := computedCorrection_bounds A C a hC haH z K (by omega) hW hB sigma hsigma hsigmaHalf f + rw [abs_of_nonneg (by dsimp only [g]; linarith [hh.1])] + exact hh.2) + have hv := sampledIntegerLaw_variation A C a theta hC haH htheta z hz K Q h hK hQ hW + hB.le hPL hCheeger v + exact he.trans (by nlinarith) + have hround : |expectation q g-correctionMean A C a z K hK hW| ≤ + (sigma:ℝ)*correctionMean A C a z K hK hW := + expectation_relative_error q (correction A C a z K (by omega)) g sigma + (computedCorrection_error A C a hC haH z K (by omega) hB sigma hsigma) + rw [correctionSample_mean] + calc + _ ≤ |expectation p g-expectation q g|+|expectation q g-correctionMean A C a z K hK hW| := by + simpa only [sub_add_sub_cancel] using abs_add_le + (expectation p g-expectation q g) (expectation q g-correctionMean A C a z K hK hW) + _ ≤ _ := add_le_add hsample hround + +/-- Independent finite words give confidence for the computed correction; +the displayed arithmetic tolerances are discharged by the outer schedule. -/ +theorem correctionSamples_failure (A : Instance I J) (C a : ℕ) (theta delta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) (hdelta : 0 < delta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q h N : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hW : 100*A.d*K ≤ A.W) (hN : 0 < N) + (hB : (K:ℝ)=binWidth A C) (sigma : ℚ) (hsigma : 0 < sigma) (hsigmaHalf : sigma ≤ 1/2) + (hsigmaDelta : (sigma:ℝ) ≤ delta/4) + (hnoise : theta/(8*Q)+(A.d:ℝ)/(2:ℝ)^(4*(h+A.d)) ≤ delta/1024) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : Fin N → (Fin (oracleIntegerBits A C (oracleTime A C K Q theta) h) → Bool) => + if delta*correctionMean A C a z K hK hW < + |sampleAverage (fun bits => + (correctionSample A C a z K hK hW sigma v (oracleTime A C K Q theta) h bits:ℝ)) N draws- + correctionMean A C a z K hK hW| then (1:ℝ) else 0) ≤ 16384/(N*delta^2) := by + let g := fun bits => + (correctionSample A C a z K hK hW sigma v (oracleTime A C K Q theta) h bits:ℝ) + have hg bits : 0 ≤ g bits ∧ g bits ≤ 8 := by + have hh := computedCorrection_bounds A C a hC haH z K (by omega) hW hB sigma hsigma hsigmaHalf + (oracleIntegerDraw A C a z K hK hW v (oracleTime A C K Q theta) h bits) + exact ⟨by dsimp only [g,correctionSample]; linarith [hh.1],hh.2⟩ + have hb := correctionMean_bounds A C a hC haH z K hK hW hB + have hmu : 0 < correctionMean A C a z K hK hW := by linarith [hb.1] + have herr := correctionSample_mean_bias A C a theta hC haH htheta z hz K Q h hK hQ hW hB sigma + hsigma hsigmaHalf hPL hCheeger v + have hround := mul_le_mul_of_nonneg_right hsigmaDelta hmu.le + have hbias : |uniformAverage g-correctionMean A C a z K hK hW| ≤ + delta*correctionMean A C a z K hK hW/2 := by + have hnoise' := mul_le_mul_of_nonneg_left hnoise (by norm_num : (0:ℝ) ≤ 16) + have hlo := mul_le_mul_of_nonneg_left hb.1 hdelta.le + dsimp only [g] + nlinarith + have hh := biased_target_failure g 8 _ delta hg hmu hdelta hbias N hN + apply hh.trans + have hNR : (0:ℝ) < N := by exact_mod_cast hN + have hs : (delta/8)^2 ≤ (delta*correctionMean A C a z K hK hW)^2 := by + apply (sq_le_sq₀ (by positivity) (mul_nonneg hdelta.le hmu.le)).mpr + nlinarith [hb.1] + calc + 4*8^2/((N:ℝ)*(delta*correctionMean A C a z K hK hW)^2) ≤ 256/(N*(delta/8)^2) := + div_le_div₀ (by norm_num) (by norm_num) (by positivity) (mul_le_mul_of_nonneg_left hs hNR.le) + _ = _ := by field_simp [hNR.ne',hdelta.ne']; ring + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorAmplification.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorAmplification.lean new file mode 100644 index 0000000000000000000000000000000000000000..f59643fbbeda74494711ed4a5ce0859001ead84a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorAmplification.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorWords +import OAI.Combinatorics.ContingencyTables.Transport.FiniteMedianConfidence + +namespace OAI + +/-! # Logarithmic confidence amplification of the actual weight estimator -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteMedianConfidence +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Each complete estimator uses constant confidence; the requested +failure probability changes only the number of independent medians. -/ +def medianEstimatorBits (A : Instance I J) (C K j : ℕ) (epsilon delta : ℚ) : ℕ := + repetitionCount delta * estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1 + +def medianEstimate (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (epsilon delta : ℚ) + (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (medianEstimatorBits A C K j epsilon delta) → Bool) : ℚ := + rationalMedian (List.ofFn (fun i : Fin (repetitionCount delta) => + wordEstimate A C z K hK hW j (epsilon/2) 1 v + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) bits i))) + +theorem medianEstimate_success (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon delta : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hd : 0 < delta) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + 1-(delta:ℝ) ≤ uniformAverage (fun bits : Fin (medianEstimatorBits A C K j epsilon delta) → Bool => + if (1-(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z ≤ + (medianEstimate A C z K hK hW j epsilon delta v bits:ℝ) ∧ + (medianEstimate A C z K hK hW j epsilon delta v bits:ℝ) ≤ + (1+(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z + then (1:ℝ) else 0) := by + have heh0 : 0 < epsilon/2 := by positivity + have heh1 : epsilon/2 < 1 := by linarith + have ht : 0 < h A ((j:ℝ)*C/height A C) z := h_positive A _ _ + have heR : (0:ℝ) < epsilon := by exact_mod_cast he0 + have hbase := wordEstimate_failure A C hC z hz K hK hW hB j hj (epsilon/2) 1 heh0 heh1 + (by norm_num) hPL hCheeger v + have hbad : uniformAverage (fun bits : Fin (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) → Bool => + if (wordEstimate A C z K hK hW j (epsilon/2) 1 v bits:ℝ) < + (1-(epsilon:ℝ)/2)*h A ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ)/2)*h A ((j:ℝ)*C/height A C) z < + (wordEstimate A C z K hK hW j (epsilon/2) 1 v bits:ℝ) + then (1:ℝ) else 0) ≤ 5/16 := by + have hh : (1:ℝ)/4 ≤ 5/16 := by norm_num + apply le_trans ?_ hh + simpa only [Rat.cast_div,Rat.cast_ofNat,Rat.cast_one] using hbase + have hm := median_confidence_real + (wordEstimate A C z K hK hW j (epsilon/2) 1 v) + ((1-(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z) + ((1-(epsilon:ℝ)/2)*h A ((j:ℝ)*C/height A C) z) + ((1+(epsilon:ℝ)/2)*h A ((j:ℝ)*C/height A C) z) + ((1+(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z) + (by nlinarith) (by nlinarith) delta hd hbad + let test := fun xs : Fin (repetitionCount delta) → + (Fin (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) → Bool) => + if (1-(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z ≤ + (rationalMedian (List.ofFn (fun i => wordEstimate A C z K hK hW j (epsilon/2) 1 v (xs i))):ℝ) ∧ + (rationalMedian (List.ofFn (fun i => wordEstimate A C z K hK hW j (epsilon/2) 1 v (xs i))):ℝ) ≤ + (1+(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z + then (1:ℝ) else 0 + have he := uniformAverage_equiv + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1)) test + change 1-(delta:ℝ) ≤ uniformAverage (fun bits => test + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) bits)) + exact hm.trans_eq he.symm + +/-- Amplification also preserves the proved range on every word, +including statistically unsuccessful words. -/ +theorem medianEstimate_range (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon delta : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (medianEstimatorBits A C K j epsilon delta) → Bool) : + (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ + (medianEstimate A C z K hK hW j epsilon delta v bits:ℝ) ∧ + (medianEstimate A C z K hK hW j epsilon delta v bits:ℝ) ≤ 8*assignmentCount A := by + let samples := List.ofFn (fun i : Fin (repetitionCount delta) => + wordEstimate A C z K hK hW j (epsilon/2) 1 v + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) bits i)) + have hmem := rationalMedian_mem samples (by + dsimp only [samples] + rw [List.length_ofFn] + exact repetitionCount_pos delta) + obtain ⟨i,hi⟩ := List.mem_ofFn.mp hmem + have hr := wordEstimate_range A C hC z hz K hK hW hB j hj (epsilon/2) 1 + (by positivity) (by linarith) (by norm_num) v + (oracleWalkWordEquiv (repetitionCount delta) + (estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1) bits i) + change _ ≤ (rationalMedian samples:ℝ) ∧ (rationalMedian samples:ℝ) ≤ _ + rw [←hi] + exact hr + +/-- The exact bit budget grows linearly with the binary confidence +parameter, rather than with its reciprocal. -/ +lemma medianEstimatorBits_eq (A : Instance I J) (C K j : ℕ) (epsilon delta : ℚ) : + medianEstimatorBits A C K j epsilon delta = + 64*(delta.den.bits.length+1) * + estimatorWordBits A C K j (innerTolerance (epsilon/2) j) 1 := rfl + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorConfidence.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorConfidence.lean new file mode 100644 index 0000000000000000000000000000000000000000..776886ddfc86fc6b9e4d8166349107d9820b00f1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorConfidence.lean @@ -0,0 +1,150 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleEstimator + +namespace OAI + +/-! # Confidence of the complete bounded-word weight estimator -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteIndependentAverages +open scoped BigOperators Classical + +noncomputable section + +lemma average_fintype_irrel {X : Type*} (s t : Fintype X) (f : X → ℝ) : + @uniformAverage X s f=@uniformAverage X t f := by + cases Subsingleton.elim s t + rfl + +variable {I J : Type*} [Fintype I] [Fintype J] + +def badFactor (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (delta failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) (i : Option (Fin j)) + (draws : EstimatorInput A C K j delta failure) : Prop := + (delta:ℝ)*targetFactor A C z K hK hW j i < + |(observedFactor A C z K hK hW j delta failure v draws i:ℝ)-targetFactor A C z K hK hW j i| + +lemma factor_failure (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (delta failure : ℚ) (hd0 : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (i : Option (Fin j)) : + uniformAverage (fun draws : EstimatorInput A C K j delta failure => + if badFactor A C z K hK hW j delta failure v i draws then (1:ℝ) else 0) ≤ + (failure:ℝ)/(4*((j:ℝ)+1)) := by + let : Nonempty (Fin j → RatioBlock A C K j delta failure) := ⟨fun _ _ _ _ => false⟩ + let : Nonempty (CorrectionBlock A C K j delta failure) := ⟨fun _ _ => false⟩ + cases i with + | none => + simp only [badFactor,observedFactor,targetFactor,rationalAverage_cast] + convert scheduled_correction_failure A C j j hC hj delta failure hd0 hd1 hf z hz K hK hW hB hPL hCheeger v using 1 + rw [uniformAverage_prod] + dsimp only + convert uniformAverage_const (X := Fin j → RatioBlock A C K j delta failure) + (uniformAverage (fun draws : CorrectionBlock A C K j delta failure => + if (delta:ℝ)*correctionMean A C j z K hK hW < + |sampleAverage (fun bits => (correctionSample A C j z K hK hW (roundingTolerance delta) v + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta) bits:ℝ)) + (sampleCount j delta failure) draws-correctionMean A C j z K hK hW| then 1 else 0)) using 1 + | some a => + simp only [badFactor,observedFactor,targetFactor,rationalAverage_cast] + convert scheduled_ratio_failure A C a.val j hC (by omega) delta failure hd0 hf z hz K hK hB hPL hCheeger v using 1 + rw [uniformAverage_prod] + dsimp only + have hc (x : Fin j → RatioBlock A C K j delta failure) := + uniformAverage_const (X := CorrectionBlock A C K j delta failure) + (if (delta:ℝ)*ratioMean A C a.val z K < + |sampleAverage (fun bits => (ratioSample A C a.val z v (oracleTime A C K 1 delta) bits:ℝ)) + (sampleCount j delta failure) (x a)-ratioMean A C a.val z K| then 1 else 0) + simp_rw [hc] + convert uniformAverage_coordinate (X := fun _ : Fin j => RatioBlock A C K j delta failure) a (fun draws : RatioBlock A C K j delta failure => + if (delta:ℝ)*ratioMean A C a.val z K < + |sampleAverage (fun bits => (ratioSample A C a.val z v (oracleTime A C K 1 delta) bits:ℝ)) + (sampleCount j delta failure) draws-ratioMean A C a.val z K| then 1 else 0) using 1 + exact average_fintype_irrel _ _ _ + +/-- All ratio and correction block failures share one explicit budget. +The statement concerns the actual bounded Boolean experiment. -/ +theorem goodEstimate_failure (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (delta failure : ℚ) (hd0 : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : EstimatorInput A C K j delta failure => + if ¬GoodEstimate A C z K hK hW j delta failure v draws then (1:ℝ) else 0) ≤ (failure:ℝ)/4 := by + have he (draws : EstimatorInput A C K j delta failure) : + (¬GoodEstimate A C z K hK hW j delta failure v draws) ↔ + ∃ i,badFactor A C z K hK hW j delta failure v i draws := by + simp only [GoodEstimate,badFactor,not_forall,not_le] + simp_rw [he] + calc + _ ≤ ∑ i : Option (Fin j),uniformAverage (fun draws : EstimatorInput A C K j delta failure => + if badFactor A C z K hK hW j delta failure v i draws then (1:ℝ) else 0) := + uniform_union_bound _ + _ ≤ ∑ _i : Option (Fin j),(failure:ℝ)/(4*((j:ℝ)+1)) := + Finset.sum_le_sum (fun i _ => factor_failure A C hC z hz K hK hW hB j hj delta failure + hd0 hd1 hf hPL hCheeger v i) + _ = _ := by + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_option,Fintype.card_fin,nsmul_eq_mul, + Nat.cast_add,Nat.cast_one] + field_simp + +lemma innerTolerance_pos (epsilon : ℚ) (j : ℕ) (he : 0 < epsilon) : + 0 < innerTolerance epsilon j := by unfold innerTolerance; positivity + +lemma innerTolerance_lt_one (epsilon : ℚ) (j : ℕ) (he : epsilon < 1) : + innerTolerance epsilon j < 1 := by + unfold innerTolerance + rw [div_lt_iff₀ (by positivity : (0:ℚ)<200*(j+1))] + have hj : (0:ℚ) ≤ j := Nat.cast_nonneg _ + nlinarith + +/-- A concrete rational estimator with bounded independent Boolean input +has the required relative-error guarantee for the original h-value. -/ +theorem estimateValue_failure (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hf : 0 < failure) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : EstimatorInput A C K j (innerTolerance epsilon j) failure => + if (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) < + (1-(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z < + (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) + then (1:ℝ) else 0) ≤ (failure:ℝ)/4 := by + have ht : 0 ≤ h A ((j:ℝ)*C/height A C) z := (h_positive A _ _).le + have heR : (0:ℝ) < epsilon := by exact_mod_cast he0 + have hp (draws : EstimatorInput A C K j (innerTolerance epsilon j) failure) : + (if (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) < + (1-(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z < + (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) + then (1:ℝ) else 0) ≤ + if ¬GoodEstimate A C z K hK hW j (innerTolerance epsilon j) failure v draws then 1 else 0 := by + by_cases hg : GoodEstimate A C z K hK hW j (innerTolerance epsilon j) failure v draws + · have ha := goodEstimate_accuracy A C hC z hz K hK hW hB j hj epsilon failure he0 he1 v draws hg + have hn : ¬((estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) < + (1-(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z < + (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ)) := by + rintro (hb|hb) <;> nlinarith + simp only [hn,hg,not_true_eq_false,ite_false,le_refl] + · simp only [hg,not_false_eq_true,ite_true] + split_ifs <;> norm_num + exact (uniformAverage_mono _ _ hp).trans + (goodEstimate_failure A C hC z hz K hK hW hB j hj (innerTolerance epsilon j) failure + (innerTolerance_pos epsilon j he0) (innerTolerance_lt_one epsilon j he1) hf hPL hCheeger v) + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorRange.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorRange.lean new file mode 100644 index 0000000000000000000000000000000000000000..491935ee98d5f39ee157eb22254348e25461ebd6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorRange.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleEstimator + +namespace OAI + +/-! # Output range on every execution of the finite-word estimator -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteIndependentAverages +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma rationalAverage_bounds {X : Type*} (g : X → ℚ) (N : ℕ) (hN : 0 < N) + (L U : ℝ) (hg : ∀ x,L ≤ (g x:ℝ) ∧ (g x:ℝ) ≤ U) (draws : Fin N → X) : + L ≤ (rationalAverage g N draws:ℝ) ∧ (rationalAverage g N draws:ℝ) ≤ U := by + have hNR : (0:ℝ) < N := by exact_mod_cast hN + have hl := Finset.sum_le_sum (s := Finset.univ) (fun i _ => (hg (draws i)).1) + have hu := Finset.sum_le_sum (s := Finset.univ) (fun i _ => (hg (draws i)).2) + simp only [Finset.sum_const,Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] at hl hu + simp only [rationalAverage,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast] + exact ⟨(le_div_iff₀ hNR).mpr (by linarith),(div_le_iff₀ hNR).mpr (by linarith)⟩ + +lemma observed_ratio_bounds (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (delta failure : ℚ) (hd : 0 < delta) (hf : 0 < failure) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) (a : Fin j) : + 1/2 ≤ (observedFactor A C z K hK hW j delta failure v draws (some a):ℝ) ∧ + (observedFactor A C z K hK hW j delta failure v draws (some a):ℝ) ≤ 1 := by + apply rationalAverage_bounds _ _ (sampleCount_positive j delta failure hd hf) + intro bits + rw [ratioSample_cast] + exact ratioObservable_bounds A C (by exact_mod_cast hC) a.val z hz hB.le _ + +lemma observed_correction_bounds (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (j : ℕ) (hj : j ≤ rationalHeight A C) (delta failure : ℚ) (hd : 0 < delta) (hd1 : delta < 1) + (hf : 0 < failure) (v : Grid (I := Fin (dimension A)) K) + (draws : EstimatorInput A C K j delta failure) : + 1/16 ≤ (observedFactor A C z K hK hW j delta failure v draws none:ℝ) ∧ + (observedFactor A C z K hK hW j delta failure v draws none:ℝ) ≤ 8 := by + apply rationalAverage_bounds _ _ (sampleCount_positive j delta failure hd hf) + intro bits + apply computedCorrection_bounds A C j hC hj z K (by omega) hW hB (roundingTolerance delta) + · unfold roundingTolerance + positivity + · unfold roundingTolerance + linarith + +/-- These bounds hold for every Boolean input, including executions on +which the empirical averages are statistically inaccurate. -/ +theorem estimateValue_range (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (delta failure : ℚ) (hd : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : + (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ (estimateValue A C z K hK hW j delta failure v draws:ℝ) ∧ + (estimateValue A C z K hK hW j delta failure v draws:ℝ) ≤ 8*assignmentCount A := by + let r := fun a : Fin j => (observedFactor A C z K hK hW j delta failure v draws (some a):ℝ) + let q := (observedFactor A C z K hK hW j delta failure v draws none:ℝ) + have hr := observed_ratio_bounds A C hC z hz K hK hW hB j delta failure hd hf v draws + have hq := observed_correction_bounds A C hC z K hK hW hB j hj delta failure hd hd1 hf v draws + have hrlow : (1/2:ℝ)^j ≤ ∏ a,r a := by + have hh := Finset.prod_le_prod₀ (s := Finset.univ) + (fun _ _ => by norm_num : ∀ a : Fin j,a∈Finset.univ → (0:ℝ) ≤ 1/2) + (fun a _ => (hr a).1) + simpa only [Finset.prod_const,Finset.card_univ,Fintype.card_fin] using hh + have hrup : (∏ a,r a) ≤ 1 := by + have hh := Finset.prod_le_prod₀ (s := Finset.univ) + (fun a _ => show (0:ℝ) ≤ r a from (by have h := (hr a).1; linarith)) (fun a _ => (hr a).2) + simpa only [Finset.prod_const_one] using hh + have hr0 : (0:ℝ) ≤ ∏ a,r a := Finset.prod_nonneg (fun a _ => by have h := (hr a).1; linarith) + have hq0 : 0 ≤ q := by dsimp only [q]; linarith [hq.1] + have hlow : (1/16:ℝ)*(1/2:ℝ)^j ≤ q*(∏ a,r a) := + mul_le_mul hq.1 hrlow (by positivity) hq0 + have hupp : q*(∏ a,r a) ≤ 8 := by + calc + _ ≤ 8*1 := mul_le_mul hq.2 hrup hr0 (by norm_num) + _ = _ := by norm_num + have hMf : (0:ℝ) ≤ assignmentCount A := Nat.cast_nonneg _ + have he : (estimateValue A C z K hK hW j delta failure v draws:ℝ)= + (assignmentCount A:ℝ)*(q*∏ a,r a) := by + simp only [estimateValue,Rat.cast_mul,Rat.cast_natCast,Rat.cast_prod,Fintype.prod_option] + rfl + rw [he] + constructor + · have hh := mul_le_mul_of_nonneg_left hlow hMf + nlinarith + · have hh := mul_le_mul_of_nonneg_left hupp hMf + nlinarith + +theorem estimateValue_positive (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (delta failure : ℚ) (hd : 0 < delta) (hd1 : delta < 1) (hf : 0 < failure) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : + 0 < estimateValue A C z K hK hW j delta failure v draws := by + have hMf : (0:ℝ) < assignmentCount A := by exact_mod_cast assignmentCount_positive A + have hh := (estimateValue_range A C hC z hz K hK hW hB j hj delta failure hd hd1 hf v draws).1 + have hp : (0:ℝ) < (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 := by positivity + exact_mod_cast lt_of_lt_of_le hp hh + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a46e34957b58c0350cc60d4552777ee574f7a8a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEstimatorWords.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorConfidence +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorRange + +namespace OAI + +/-! # A single Boolean word for the literal companion weight estimator -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteIndependentAverages FairBits +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- The complete input length, with one independent walk for each ratio +sample and one walk plus integer-bin draw for each correction sample. -/ +def estimatorWordBits (A : Instance I J) (C K j : ℕ) (delta failure : ℚ) : ℕ := + j*(sampleCount j delta failure * + (oracleTime A C K 1 delta * oracleStepBits A C)) + + sampleCount j delta failure * + oracleIntegerBits A C (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta) + +lemma estimatorWordBits_eq (A : Instance I J) (C K j : ℕ) (delta failure : ℚ) : + estimatorWordBits A C K j delta failure = sampleCount j delta failure * + (j*oracleTime A C K 1 delta*oracleStepBits A C + + oracleTime A C K 1 (correctionTheta delta)*oracleStepBits A C + + binWordBits A (offsetAccuracy A delta)) := by + unfold estimatorWordBits oracleIntegerBits + ring + +def ratioBlockWordEquiv (A : Instance I J) (C K j : ℕ) (delta failure : ℚ) : + (Fin (sampleCount j delta failure * + (oracleTime A C K 1 delta * oracleStepBits A C)) → Bool) ≃ + RatioBlock A C K j delta failure := + (oracleWalkWordEquiv (sampleCount j delta failure) + (oracleTime A C K 1 delta * oracleStepBits A C)).trans + (Equiv.piCongrRight (fun _ => + oracleWalkWordEquiv (oracleTime A C K 1 delta) (oracleStepBits A C))) + +/-- This equivalence partitions, rather than reuses, the random bits of +all the individual experiments in the estimator. -/ +def estimatorWordEquiv (A : Instance I J) (C K j : ℕ) (delta failure : ℚ) : + (Fin (estimatorWordBits A C K j delta failure) → Bool) ≃ + EstimatorInput A C K j delta failure := + (splitWordEquiv _ _).trans (Equiv.prodCongr + ((oracleWalkWordEquiv j (sampleCount j delta failure * + (oracleTime A C K 1 delta * oracleStepBits A C))).trans + (Equiv.piCongrRight (fun _ => ratioBlockWordEquiv A C K j delta failure))) + (oracleWalkWordEquiv (sampleCount j delta failure) + (oracleIntegerBits A C (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)))) + +def wordEstimate (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (epsilon failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (estimatorWordBits A C K j (innerTolerance epsilon j) failure) → Bool) : ℚ := + estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v + (estimatorWordEquiv A C K j (innerTolerance epsilon j) failure bits) + +/-- The single fixed-length word has exactly the independent-product law. -/ +theorem wordEstimate_failure (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hf : 0 < failure) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun bits : Fin (estimatorWordBits A C K j (innerTolerance epsilon j) failure) → Bool => + if (wordEstimate A C z K hK hW j epsilon failure v bits:ℝ) < + (1-(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z < + (wordEstimate A C z K hK hW j epsilon failure v bits:ℝ) + then (1:ℝ) else 0) ≤ (failure:ℝ)/4 := by + let test := fun draws : EstimatorInput A C K j (innerTolerance epsilon j) failure => + if (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) < + (1-(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z ∨ + (1+(epsilon:ℝ))*h A ((j:ℝ)*C/height A C) z < + (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) + then (1:ℝ) else 0 + have he := uniformAverage_equiv + (estimatorWordEquiv A C K j (innerTolerance epsilon j) failure) test + change uniformAverage (fun bits => test + (estimatorWordEquiv A C K j (innerTolerance epsilon j) failure bits)) ≤ _ + exact he.trans_le + (estimateValue_failure A C hC z hz K hK hW hB j hj epsilon failure he0 he1 hf hPL hCheeger v) + +theorem wordEstimate_range (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) (hf : 0 < failure) + (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (estimatorWordBits A C K j (innerTolerance epsilon j) failure) → Bool) : + (assignmentCount A:ℝ)*(1/2:ℝ)^j/16 ≤ + (wordEstimate A C z K hK hW j epsilon failure v bits:ℝ) ∧ + (wordEstimate A C z K hK hW j epsilon failure v bits:ℝ) ≤ 8*assignmentCount A := + estimateValue_range A C hC z hz K hK hW hB j hj (innerTolerance epsilon j) failure + (innerTolerance_pos epsilon j he0) (innerTolerance_lt_one epsilon j he1) hf v _ + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEvaluatedWeightLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEvaluatedWeightLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2f8fe0f573efe5f52ccac3dec343c9089ac961f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEvaluatedWeightLaw.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEvaluatedWeightProgram +import OAI.Combinatorics.ContingencyTables.Machines.FractionMetropolisProgram +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableReindex + +namespace OAI + +/-! # Fixed-width laws for the two physical Metropolis weight calls -/ + +namespace ContingencyTables.CompanionEvaluatedWeightProgram + +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial +open CompanionArithmeticProposal CompanionOracleDensity CompanionWeightOracle +open CompanionMultiplierMatrixProgram GridBoundary CommonBasesFPRAS FiniteObservableTransport +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma queryWidth (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + repetitionCount xi*RootedEstimatorLayoutProgram.wordWidth + (RootedEstimatorMedianProgram.context A C K j xi z v)=medianEstimatorBits A C K j xi xi := by + rw [RootedEstimatorMedianProgram.context,RootedEstimatorWordProgram.scheduledWordWidth] + rfl + +theorem sameLaw_fixed (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A × Bool)) : + SameLaw (fun bits : WeightWord A C K j xi => + TreeFraction.val (output (((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w), + encodeSet (coordinateOrder A) S),List.ofFn bits))) + (RootedOracleAcceptance.evaluatedWeight A (RootedCompletion.rowColumn A.T) C K j hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S) := by + exact SameLaw.word_length (queryWidth A C K j xi (CompanionWeightOracle.profile A S) v) + (fun bs => TreeFraction.val (output + (((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w), + encodeSet (coordinateOrder A) S),bs))) _ + (sameLaw_evaluated A C K j hC hj hK hW hB xi hxi z v degree depth hdegree hdepth w S) + +theorem acceptance_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S T : Set (Labels A × Bool)) : + SameLaw (fun b : (WeightWord A C K j xi × WeightWord A C K j xi) × (Fin k → Bool) => + FractionMetropolisProgram.accept + ((output (((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w), + encodeSet (coordinateOrder A) S),List.ofFn b.1.1), + output (((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w), + encodeSet (coordinateOrder A) T),List.ofFn b.1.2)),List.ofFn b.2)) + (fun b : (WeightWord A C K j xi × WeightWord A C K j xi) × (Fin k → Bool) => + decide (FairBits.rationalThresholdAccept k + (RootedOracleAcceptance.acceptance A (RootedCompletion.rowColumn A.T) C K j hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S T b.1) b.2)) := by + exact FractionMetropolisProgram.sameLaw_accept _ _ _ _ + (sameLaw_fixed A C K j hC hj hK hW hB xi hxi z v degree depth hdegree hdepth w S) + (sameLaw_fixed A C K j hC hj hK hW hB xi hxi z v degree depth hdegree hdepth w T) k + +end +end ContingencyTables.CompanionEvaluatedWeightProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEvaluatedWeightProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEvaluatedWeightProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c4017e35b70a738812f65b50009b5bf4b08e66e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionEvaluatedWeightProgram.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionStateMultiplierProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedLabelWeightProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleAcceptance + +namespace OAI + +/-! # The executed multiplier times labelled weight + +Both factors are computed from the supplied current state. The matrix +lookup and the oracle consume no hidden finite-state enumeration. +-/ + +namespace ContingencyTables.CompanionEvaluatedWeightProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped +open CompanionMultiplierMatrixProgram + +abbrev Frame := RootedLabelWeightProgram.Config × FractionMatrix +abbrev Input := (Frame × List ℕ) × List Bool + +def multiplierInput (z : Input) : CompanionStateMultiplierProgram.Input := + (z.1.1.2,(PairedCatalogProgram.catalog z.1.2,z.1.2)) +def multiplierInputRealizer : Realizer multiplierInput := + pair (composition (composition first first) second) + (pair (composition (f := fun z : Input => z.1.2) (g := PairedCatalogProgram.catalog) + (composition first second) PairedCatalogProgram.catalogRealizer) (composition first second)) +lemma polynomial_multiplierInput : PolynomialTime multiplierInputRealizer := + polynomial_pair (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_pair (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + PairedCatalogProgram.polynomial_catalog) (polynomial_composition polynomial_first polynomial_second)) + +def multiplier (z : Input) : TreeFraction.Fraction := + CompanionStateMultiplierProgram.output (multiplierInput z) +def multiplierRealizer : Realizer multiplier := + composition (f := multiplierInput) (g := CompanionStateMultiplierProgram.output) + multiplierInputRealizer CompanionStateMultiplierProgram.outputRealizer +lemma polynomial_multiplier : PolynomialTime multiplierRealizer := + polynomial_composition polynomial_multiplierInput CompanionStateMultiplierProgram.polynomial_output + +def weightInput (z : Input) : RootedLabelWeightProgram.Input := (z.1.1.1,(z.1.2,z.2)) +def weightInputRealizer : Realizer weightInput := + pair (composition (composition first first) first) (pair (composition first second) second) +lemma polynomial_weightInput : PolynomialTime weightInputRealizer := + polynomial_pair (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second) + +attribute [local irreducible] weightInput RootedLabelWeightProgram.output + +def weight (z : Input) : TreeFraction.Fraction := RootedLabelWeightProgram.output (weightInput z) +def weightRealizer : Realizer weight := + composition (f := weightInput) (g := RootedLabelWeightProgram.output) + weightInputRealizer RootedLabelWeightProgram.outputRealizer +lemma polynomial_weight : PolynomialTime weightRealizer := + polynomial_composition polynomial_weightInput RootedLabelWeightProgram.polynomial_output + +attribute [local irreducible] multiplier weight + +def output (z : Input) : TreeFraction.Fraction := TreeFraction.mul (multiplier z,weight z) +def outputRealizer : Realizer output := + composition (f := fun z : Input => (multiplier z,weight z)) (g := TreeFraction.mul) + (pair multiplierRealizer weightRealizer) TreeFraction.mulRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair polynomial_multiplier polynomial_weight) TreeFraction.polynomial_mul + +attribute [local irreducible] output + +noncomputable section +open CompanionRationalUpdates +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal GridBoundary CompanionOracleDensity CommonBasesFPRAS TwoLiftStates +open FiniteObservableTransport +open scoped Classical +variable {m n : ℕ} + +abbrev LabelIndex (A : Instance (Fin m) (Fin n)) := + Fin (CanonicalInitialEncoding.copyOrder (capacities A)).length + +def sourceWeights (A : Instance (Fin m) (Fin n)) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (a b : Pair A) : ℚ := + TreeFraction.val (w ((pairLabels A).symm a.1.1) ((pairLabels A).symm b.1.1)) + +lemma multiplier_code (A : Instance (Fin m) (Fin n)) + (cfg : RootedLabelWeightProgram.Config) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : Set (Labels A × Bool)) (bits : List Bool) : + TreeFraction.val (multiplier (((cfg,matrixCode w),encodeSet (coordinateOrder A) S),bits))= + CommonBasesFPRAS.rationalMultiplier pairs (sourceWeights A w) S := by + unfold multiplier multiplierInput + rw [CompanionComputedProposal.generated_catalog] + exact CompanionStateMultiplierProgram.output_code A (pairLabels A) (coordinateOrder A) S w + +/-- Arbitrary observables of the executed weighted query agree with the +proved mathematical oracle, including outcomes on its failure event. -/ +theorem sameLaw_evaluated (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A × Bool)) : + SameLaw (fun bits : Fin (repetitionCount xi*RootedEstimatorLayoutProgram.wordWidth + (RootedEstimatorMedianProgram.context A C K j xi (CompanionWeightOracle.profile A S) v)) → Bool => + TreeFraction.val (output (((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w), + encodeSet (coordinateOrder A) S),List.ofFn bits))) + (RootedOracleAcceptance.evaluatedWeight A (RootedCompletion.rowColumn A.T) C K j hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S) := by + have hw := RootedLabelWeightProgram.sameLaw_weight A C K j hC hj hK hW hB xi hxi z v + degree depth hdegree hdepth S + intro phi + have he (bits : Fin (repetitionCount xi*RootedEstimatorLayoutProgram.wordWidth + (RootedEstimatorMedianProgram.context A C K j xi (CompanionWeightOracle.profile A S) v)) → Bool) : + TreeFraction.val (output (((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w), + encodeSet (coordinateOrder A) S),List.ofFn bits))= + CommonBasesFPRAS.rationalMultiplier pairs (sourceWeights A w) S * + TreeFraction.val (RootedLabelWeightProgram.output + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth, + (encodeSet (coordinateOrder A) S,List.ofFn bits))) := by + rw [output,TreeFraction.mul_val,multiplier_code] + unfold weight weightInput + rfl + simp_rw [he] + exact hw (fun q => phi (CommonBasesFPRAS.rationalMultiplier pairs (sourceWeights A w) S*q)) + +end +end ContingencyTables.CompanionEvaluatedWeightProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFactorialApplication.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFactorialApplication.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3f3b4e06af30cf88f346e18c7c9be4791496e2c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFactorialApplication.lean @@ -0,0 +1,228 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestCountIdentification +import OAI.Combinatorics.ContingencyTables.Transport.SliceFactorial +import OAI.Combinatorics.ContingencyTables.Transport.TwoLiftStates +import OAI.Combinatorics.ContingencyTables.Transport.NestedReindex + +namespace OAI + +/-! +# The companion's literal completion count gives both labelled factorial signatures + +The labels below are actual copies of the retained small cells. Their +fiber cardinalities are the capacities, so the original first and dual +factorial displays and the W² chain-state comparison have no abstract +signature or completion hypothesis. +-/ + +namespace ContingencyTables.CompanionFactorialApplication + +open scoped BigOperators Classical Matrix +open SimpleGraph CommonBasesFPRAS +open ForestCapacity GraphIntegralCompletion ForestCountIdentification +open LargePairEnumeration BalancedBox LabelledFactorial + +variable (I J : Type*) [Fintype I] [Fintype J] + +/-- Actual tightened bounded margins, a maximum large-cell forest, and +one feasible baseline table determine the completion counts and +factorial signatures. -/ +structure Instance where + small : I → J → Bool + b : I → J → ℕ + T : SimpleGraph (I⊕J) + hTG : T≤cellGraph small + hT : T.IsAcyclic + hmax : ∀ F : SimpleGraph (I⊕J), F≤cellGraph small → F.IsAcyclic → + MaximumForest.weight F (capacity b)≤MaximumForest.weight T (capacity b) + r : I → ℤ + c : J → ℤ + X : I → J → ℤ + d : ℕ + W : ℕ + hd : 1≤d + hcard : Fintype.card I*Fintype.card J≤d + hW : 2≤W + hlarge : ∀ i j, small i j=false → W≤b i j ∧ 1≤b i j + hsmall : ∀ i j, small i j=true → b i j A.small a.1 a.2)) (k : Fin n) : + 2≤ForestLiteralCount.width A.T A.d A.b (e k).val.1 (e k).val.2 := by + have hb := (A.hlarge _ _ (e k).property).2 + by_cases ht : A.T.Adj (.inl (e k).val.1) (.inr (e k).val.2) + · simp only [ForestLiteralCount.width,ht,ite_true] + have hd := A.hd + have hdb : 0 A.small a.1 a.2)) (z : View A → ℕ) + (hz : InBox (bounds A) z) : + h A alpha z=ForestLargeMarginal.largeMarginal (fun a : I×J => A.small a.1 a.2) A.T A.b + (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) + A.r A.c alpha e z := + sourceMarginal_eq_largeMarginal A.small A.b A.T A.hTG A.hT A.hmax A.r A.c A.X A.d A.W alpha + A.hd A.hcard A.hlarge A.hsmall A.hX A.hXr A.hXc e z hz + +/-- The original free-assignment count has its actual raw removal slice. -/ +theorem h_removal (A : Instance I J) (alpha : ℝ) (ha : 0≤alpha) (R : ℕ) : + RemovalSlice (h A alpha) (bounds A) R := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => A.small a.1 a.2))).symm + have hs := ForestLargeMarginal.largeMarginal_removal + (fun a : I×J => A.small a.1 a.2) A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha e (bounds A) R ha (large_width A e) + intro z hz ht + rw [NestedReindex.removal_congr_box _ _ (bounds A) z hz (count_identity A alpha e)] + convert hs z hz ht using 1 + +/-- The globally reflected count supplies the dual addition input. -/ +theorem h_reflected (A : Instance I J) (alpha : ℝ) (ha : 0≤alpha) (R : ℕ) : + RemovalSlice (fun z => h A alpha (IntegerReflection.reflect (bounds A) z)) (bounds A) R := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => A.small a.1 a.2))).symm + have hs := ForestLargeMarginal.largeMarginal_reflected + (fun a : I×J => A.small a.1 a.2) A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha e (bounds A) R ha (large_width A e) + intro z hz ht + rw [NestedReindex.removal_congr_box _ _ (bounds A) z hz (by + intro x _ + apply count_identity A alpha e + intro u + exact Nat.sub_le _ _)] + convert hs z hz ht using 1 + +@[reducible] def Labels (A : Instance I J) := Σ s : SmallCell A, Fin (A.b s.val.1 s.val.2) + +@[reducible] def labelCell (A : Instance I J) (p : Labels A) : SmallCell A := p.1 + +lemma label_width (A : Instance I J) (s : SmallCell A) : + TwoLiftStates.width (labelCell A) s=A.b s.val.1 s.val.2 := by + rw [TwoLiftStates.width_eq_sum] + rw [Fintype.sum_sigma] + have hinner (x : SmallCell A) : + (∑ k : Fin (A.b x.val.1 x.val.2), if labelCell A ⟨x,k⟩=s then 1 else 0)= + if x=s then A.b x.val.1 x.val.2 else 0 := by + by_cases hx : x=s + · subst x + have he : ∀ k : Fin (A.b s.val.1 s.val.2), labelCell A ⟨s,k⟩=s := fun _ => rfl + simp [he] + · have he : ∀ k : Fin (A.b x.val.1 x.val.2), labelCell A ⟨x,k⟩≠s := fun _ => hx + simp [he,hx] + convert (show (∑ x : SmallCell A, if x=s then A.b x.val.1 x.val.2 else 0)= + A.b s.val.1 s.val.2 by simp) using 1 + apply Finset.sum_congr rfl + intro x _ + convert hinner x using 1 + apply Finset.sum_congr rfl + intro k _ + by_cases hk : labelCell A ⟨x,k⟩=s <;> simp [hk] + +lemma label_capacity (A : Instance I J) : + groupCount (TwoLiftStates.group (labelCell A)) Set.univ=bounds A := by + funext u + rcases u with ⟨s,t⟩ + rw [TwoLiftStates.groupCount_eq_viewCount] + unfold TwoLiftStates.viewCount + simp only [Set.mem_univ,and_true] + have he : (∑ p : Labels A, if labelCell A p=s then 1 else 0)= + TwoLiftStates.width (labelCell A) s := by + rw [TwoLiftStates.width_eq_sum] + apply Finset.sum_congr rfl + intro p _ + by_cases hp : labelCell A p=s <;> simp [hp] + exact he.trans (label_width A s) + +noncomputable def denominator (A : Instance I J) := TwoLiftStates.denominator (labelCell A) + +lemma denominator_positive (A : Instance I J) : 0 h_positive A alpha z) + · have hs : @RemovalSlice (View A) _ (Classical.decEq _) + (h A alpha) (groupCount (TwoLiftStates.group (labelCell A)) Set.univ) + (Fintype.card (Labels A)) := by + rw [label_capacity] + convert h_removal A alpha ha _ using 1 + convert SliceFactorial.firstLift_omission_slice (TwoLiftStates.group (labelCell A)) + (h A alpha) (denominator A) (Fintype.card (Labels A)) (denominator_positive A) + (fun z => (h_positive A alpha z).le) hs using 1 + +/-- The dual factorial lift retains positivity and has its actual +addition signature from the globally reflected raw count. -/ +theorem second_properties (A : Instance I J) (alpha : ℝ) (ha : 0≤alpha) : + BinaryContraction.DegreePositive (g A alpha) (Fintype.card (Labels A)) ∧ + BinaryContraction.AdditionProperty (g A alpha) (Fintype.card (Labels A)) := by + change BinaryContraction.DegreePositive + (secondLift (TwoLiftStates.group (labelCell A)) (h A alpha) (denominator A)) _ ∧ + BinaryContraction.AdditionProperty + (secondLift (TwoLiftStates.group (labelCell A)) (h A alpha) (denominator A)) _ + constructor + · intro S _ + exact div_pos + (mul_pos (h_positive A alpha _) (FactorialSignatures.factorialProduct_positive _)) + (denominator_positive A) + · have hs : @RemovalSlice (View A) _ (Classical.decEq _) + (fun z => h A alpha (IntegerReflection.reflect + (groupCount (TwoLiftStates.group (labelCell A)) Set.univ) z)) + (groupCount (TwoLiftStates.group (labelCell A)) Set.univ) + (Fintype.card (Labels A×Bool)-Fintype.card (Labels A)) := by + rw [label_capacity] + convert h_reflected A alpha ha _ using 1 + convert ReflectedSlices.secondLift_addition_reflected_slice (TwoLiftStates.group (labelCell A)) + (h A alpha) (denominator A) (Fintype.card (Labels A)) + (by simp only [Fintype.card_prod,Fintype.card_bool]; omega) + (denominator_positive A) (fun z => (h_positive A alpha z).le) hs using 1 + +/-- The actual paired-label chain has the required pointwise q=W² +comparison, with the source count appearing identically in both lifts. -/ +theorem chain_comparison (A : Instance I J) (alpha : ℝ) (S : Set (Labels A×Bool)) + (hS : CommonBasesFPRAS.ChainState TwoLiftStates.pairs S) : + (1/(A.W:ℝ)^2)*f A alpha S≤g A alpha S ∧ g A alpha S≤(A.W:ℝ)^2*f A alpha S := by + apply TwoLiftStates.chain_lifts_compare (labelCell A) (h A alpha) S hS A.W + (by have hW := A.hW; omega) + · intro s + rw [label_width] + exact A.hsmall _ _ s.property + · exact (h_positive A alpha _).le + +end ContingencyTables.CompanionFactorialApplication + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFarMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFarMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..b90e74d3cc914d70f0edfd7c5de4738b0467a762 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFarMass.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhysicalNormalizer + +namespace OAI + +/-! # The actual far-penalty terminal mass is exponentially small -/ + +namespace ContingencyTables.CompanionFarMass + +open scoped BigOperators Classical +open CompanionFactorialApplication CompanionPhysicalNormalizer TreeMarginalSignature +open BalancedCellFibres ForestPenaltyApplication + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def actualWeight (A : Instance I J) (alpha : ℝ) (a : Profiles (cellWidth A)) : ℝ := + physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha (BalancedCellFibres.profile (cellWidth A) a) + +noncomputable def actualPenalty (A : Instance I J) (a : Profiles (cellWidth A)) : ℝ := + penalty A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c (BalancedCellFibres.profile (cellWidth A) a) + +lemma weight_at_large_penalty (A : Instance I J) (alpha : ℝ) (K : ℕ) + (a : Profiles (cellWidth A)) (ha : 4*(K:ℝ) ≤ alpha*actualPenalty A a) : + actualWeight A alpha a ≤ (2:ℝ)^(-(4*K:ℕ):ℝ) := by + unfold actualWeight + rw [exact_eq] + split_ifs + · apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + change -alpha*actualPenalty A a ≤ -((4*K:ℕ):ℝ) + push_cast + linarith + · exact (Real.rpow_pos_of_pos (by norm_num : (0:ℝ) < 2) _).le + +/-- The true expanded physical box has at most 2^K summands, so the +entire terminal region whose penalty is at least 4K contributes at most +2^(-3K). Neither a table-count approximation nor an oracle is assumed. -/ +theorem far_mass_le (A : Instance I J) (alpha : ℝ) (B K : ℕ) + (hW : 20*A.d ≤ A.W) (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) : + (∑ a : Profiles (cellWidth A),if 4*(K:ℝ) ≤ alpha*actualPenalty A a + then actualWeight A alpha a else 0) ≤ (2:ℝ)^(-(3*K:ℕ):ℝ) := by + have hcard : Fintype.card (Profiles (cellWidth A)) ≤ 2^K := + ForestBoxCardinality.cardinality_le_two_pow A hW B K hB hBK + have hcardR : (Fintype.card (Profiles (cellWidth A)):ℝ) ≤ (2:ℝ)^K := by exact_mod_cast hcard + have hp : 0 ≤ (2:ℝ)^(-(4*K:ℕ):ℝ) := (Real.rpow_pos_of_pos (by norm_num) _).le + calc + _ ≤ ∑ _a : Profiles (cellWidth A),(2:ℝ)^(-(4*K:ℕ):ℝ) := by + apply Finset.sum_le_sum + intro a _ + split_ifs with ha + · exact weight_at_large_penalty A alpha K a ha + · exact hp + _ = (Fintype.card (Profiles (cellWidth A)):ℝ)*(2:ℝ)^(-(4*K:ℕ):ℝ) := by simp + _ ≤ (2:ℝ)^K*(2:ℝ)^(-(4*K:ℕ):ℝ) := mul_le_mul_of_nonneg_right hcardR hp + _ = _ := by + rw [← Real.rpow_natCast,← Real.rpow_add (by norm_num : (0:ℝ) < 2)] + congr 1 + push_cast + ring + +end ContingencyTables.CompanionFarMass + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFlatReturnProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFlatReturnProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d82530ac969cdfbe78e37fa3e8fd8a80956d18c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFlatReturnProgram.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTransitionWidth +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOrderedReturn +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBoundedWalkSemantics +import OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram + +namespace OAI + +/-! # A bounded flat word for the actual capped-return program -/ + +namespace ContingencyTables.CompanionFlatReturnProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +abbrev Input := (CompanionBoundedWalkProgram.State × ℕ) × List Bool + +def widthInput (z : Input) : CompanionMetropolisWordProgram.Input := + ((z.1.1.1.1,z.1.1.2),[]) +def widthInputRealizer : Realizer widthInput := + pair (pair (composition (composition (composition first first) first) first) + (composition (composition first first) second)) (constant []) +lemma polynomial_widthInput : PolynomialTime widthInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second)) + (polynomial_constant []) + +def width (z : Input) : ℕ := CompanionTransitionWidth.width (widthInput z) +def widthRealizer : Realizer width := + composition (f := widthInput) (g := CompanionTransitionWidth.width) + widthInputRealizer CompanionTransitionWidth.widthRealizer +lemma polynomial_width : PolynomialTime widthRealizer := + polynomial_composition polynomial_widthInput CompanionTransitionWidth.polynomial_width + +def words (z : Input) : List (List Bool) := (wordChunks (width z,z.2)).take z.1.2 +def wordsRealizer : Realizer words := + composition (f := fun z : Input => (wordChunks (width z,z.2),z.1.2)) + (g := fun p : List (List Bool) × ℕ => p.1.take p.2) + (pair (composition (f := fun z : Input => (width z,z.2)) (g := wordChunks) + (pair widthRealizer second) wordChunksRealizer) (composition first second)) takeFast +lemma polynomial_words : PolynomialTime wordsRealizer := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_width polynomial_second) polynomial_wordChunks) + (polynomial_composition polynomial_first polynomial_second)) polynomial_takeFast + +def returnInput (z : Input) : CompanionOrderedReturn.Input := (z.1.1,words z) +def returnInputRealizer : Realizer returnInput := + pair (composition first first) wordsRealizer +lemma polynomial_returnInput : PolynomialTime returnInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_words + +def output (z : Input) : List ℕ := CompanionOrderedReturn.output (returnInput z) +def outputRealizer : Realizer output := + composition (f := returnInput) (g := CompanionOrderedReturn.output) + returnInputRealizer CompanionOrderedReturn.outputRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_returnInput CompanionOrderedReturn.polynomial_output + +noncomputable section +open CommonBasesFPRAS CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionOracleDensity CompanionWeightOracle +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram FiniteObservableTransport +open CompanionTraceWords CompanionCappedReturn TwoLiftStates GridBoundary +open scoped Classical +variable {m n : ℕ} + +def stateData (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : CompanionBooleanPhase.State A) : CompanionBoundedWalkProgram.State := + let code := encodeSet (coordinateOrder A) S.val + let fixed : CompanionBoundedWalkProgram.Fixed := + (((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w),k),code) + (fixed,code) + +def data (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : CompanionBooleanPhase.State A) (bits : List Bool) : Input := + ((stateData A C K j k xi z v degree depth w S,N),bits) + +lemma words_data (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : CompanionBooleanPhase.State A) + (bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi) → Bool) : + words (data A C K j k N xi z v degree depth w S (List.ofFn bits))= + List.ofFn (fun i : Fin N => List.ofFn + (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi) bits i)) := by + unfold words width widthInput data stateData + dsimp only + change (wordChunks (CompanionTransitionWidth.width (CompanionMetropolisWordProgram.packed + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w) + k (encodeSet (coordinateOrder A) S.val) []),List.ofFn bits)).take N=_ + rw [CompanionTransitionWidth.width_config] + rw [wordChunks_ofFn (by unfold CompanionBooleanPhase.stepBits; omega)] + exact List.take_of_length_le (by simp only [List.length_ofFn]; exact le_rfl) + +/-- This law includes the computed return scan, missing-return fallback, +and the independent words of every step. -/ +theorem output_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) : + SameLaw (fun bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi) → Bool => + output (data A C K j k N xi z v degree depth w S.val (List.ofFn bits))) + (fun words : Fin N → (Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool) => + encodeSet (coordinateOrder A) + (returnDefault (plainPredicate pairs) S (traceStates + (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) C K j k hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w)) S.val (List.ofFn words))).val.val) := by + have hh := CompanionBoundedWalkProgram.history_sameLaw A C K j k hC hj hK hW hB xi hxi z v + degree depth hdegree hdepth w S.val N + have hm := hh.map (fun hist => CompanionCappedReturnProgram.totalReturnCode + ((PairedCatalogProgram.catalog (encodeSet (coordinateOrder A) S.val.val),hist), + encodeSet (coordinateOrder A) S.val.val)) + intro phi + let draw : (Fin N → (Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool)) → List ℕ := + fun words => CompanionOrderedReturn.output + (stateData A C K j k xi z v degree depth w S.val,List.ofFn (fun i => List.ofFn (words i))) + have he := uniformAverage_equiv (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi)) + (fun words => phi (draw words)) + have hc : (fun bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi) → Bool => + phi (output (data A C K j k N xi z v degree depth w S.val (List.ofFn bits))))= + (fun bits => phi (draw (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi) bits))) := by + funext bits + unfold output returnInput + rw [words_data] + rfl + rw [hc] + refine he.trans ((hm phi).trans ?_) + apply congrArg uniformAverage + funext words + dsimp only + rw [generated_catalog,CompanionOrderedReturn.totalReturnCode_ordered] + +end +end ContingencyTables.CompanionFlatReturnProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFractionSize.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFractionSize.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cf2f7bde39af92402c89983d41059dcae3150d0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionFractionSize.lean @@ -0,0 +1,72 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseFinishProgram + +namespace OAI + +/-! # Additive binary-size bounds for stored phase arithmetic -/ +namespace ContingencyTables.CompanionFractionSize +open MatchingFPRAS MatchingFPRAS.TreeTyped CompanionMultiplierProgram CompanionPhaseCounts + +lemma height_mul (a b : TreeFraction.Fraction) : + TreeFraction.height (TreeFraction.mul (a,b)) ≤ TreeFraction.height a+TreeFraction.height b+1 := by + have hn := TreeFraction.normalize_size_num (a.1*b.1,a.2*b.2) + have hd := TreeFraction.normalize_size_den (a.1*b.1,a.2*b.2) + have hnum := nat_size_mul a.1 b.1 + have hden := nat_size_mul a.2 b.2 + have ha := le_max_left a.1.size a.2.size + have ha' := le_max_right a.1.size a.2.size + have hb := le_max_left b.1.size b.2.size + have hb' := le_max_right b.1.size b.2.size + dsimp only at hn hd + change (TreeFraction.mul (a,b)).1.size ≤ _ at hn + change (TreeFraction.mul (a,b)).2.size ≤ _ at hd + unfold TreeFraction.height + apply max_le <;> omega + +lemma height_div (a b : TreeFraction.Fraction) : + TreeFraction.height (TreeFraction.div (a,b)) ≤ TreeFraction.height a+TreeFraction.height b+1 := by + have hn := TreeFraction.normalize_size_num (a.1*b.2,a.2*b.1) + have hd := TreeFraction.normalize_size_den (a.1*b.2,a.2*b.1) + have hnum := nat_size_mul a.1 b.2 + have hden := nat_size_mul a.2 b.1 + have ha := le_max_left a.1.size a.2.size + have ha' := le_max_right a.1.size a.2.size + have hb := le_max_left b.1.size b.2.size + have hb' := le_max_right b.1.size b.2.size + dsimp only at hn hd + change (TreeFraction.div (a,b)).1.size ≤ _ at hn + change (TreeFraction.div (a,b)).2.size ≤ _ at hd + unfold TreeFraction.height + apply max_le <;> omega + +lemma countRatio_height (z : DefectCountInput) : TreeFraction.height (countRatio z) ≤ z.1.2.length := by + have hp : plainCountCode z.1 ≤ z.1.2.length := List.length_filter_le _ _ + have hd : defectCountCode z ≤ z.1.2.length := List.length_filter_le _ _ + have hs (n : ℕ) : n.size ≤ n := Nat.size_le.mpr Nat.lt_two_pow_self + exact max_le ((hs _).trans hp) ((hs _).trans hd) + +lemma updateCode_height (z : UpdateInput) : + TreeFraction.height (updateCode z) ≤ TreeFraction.height z.2+z.1.1.2.length+1 := by + unfold updateCode + split_ifs + · omega + · exact (height_mul _ _).trans (Nat.add_le_add_right + (Nat.add_le_add_left (countRatio_height _) _) 1) + +lemma sum_height (xs : List TreeFraction.Fraction) (M : ℕ) + (hm : ∀ x∈xs,TreeFraction.height x ≤ M) : + TreeFraction.height (TreeFraction.sum xs) ≤ 1+xs.length*(M+2) := by + simpa only [TreeFraction.sum,TreeFraction.height,Nat.size_zero,Nat.size_one,Nat.zero_max] using + TreeFraction.fractionFold_height xs (0,1) M hm + +lemma term_height (z : CompanionPhaseFinishProgram.TermInput) (M : ℕ) + (h₁ : TreeFraction.height z.2.1 ≤ M) (h₂ : TreeFraction.height z.2.2 ≤ M) : + TreeFraction.height (CompanionPhaseFinishProgram.term z) ≤ 2*M+1 := by + unfold CompanionPhaseFinishProgram.term + split_ifs + · have h := height_div z.2.2 z.2.1 + omega + · norm_num [TreeFraction.height] + +end ContingencyTables.CompanionFractionSize + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionHistoryReadback.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionHistoryReadback.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ee0a0eb4d0ef26c3c690937b8efe2cbf165e655 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionHistoryReadback.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionStoredRepresentation +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalHistoryLaw + +namespace OAI + +/-! # Reading a represented physical history as source matrix data -/ +namespace ContingencyTables.CompanionHistoryReadback +open MatchingFPRAS CompanionMultiplierMatrixProgram CompanionStoredRepresentation +open CompanionFactorialApplication CompanionComputedInitial CompanionEvaluatedWeightProgram +open GridBoundary +open scoped Classical +noncomputable section + +abbrev Stored := CompanionPhaseFinishProgram.Stored + +def lookup (initial : Stored) (history : List Stored) : ℕ→Stored + | 0 => initial + | i+1 => history.getD i initial + +def matrixAt (p : ℕ) (initial : Stored) (history : List Stored) (i : ℕ) : + Fin p→Fin p→TreeFraction.Fraction := entries p (lookup initial history i).1 + +def estimateAt (initial : Stored) (history : List Stored) (i : ℕ) : TreeFraction.Fraction := + (lookup initial history i).2 + +lemma getD_rep {p : ℕ} (history : List Stored) (initial : Stored) + (hi : StoredRep p initial) (hh : ∀ s∈history,StoredRep p s) (i : ℕ) : + StoredRep p (history.getD i initial) := by + by_cases h : i < history.length + · rw [List.getD_eq_getElem _ _ h] + exact hh _ (List.getElem_mem h) + · rw [List.getD_eq_default _ _ (Nat.le_of_not_gt h)] + exact hi + +lemma lookup_rep {p : ℕ} (initial : Stored) (history : List Stored) + (hi : StoredRep p initial) (hh : ∀ s∈history,StoredRep p s) (i : ℕ) : + StoredRep p (lookup initial history i) := by + cases i with + | zero => exact hi + | succ i => exact getD_rep history initial hi hh i + +theorem lookup_readback {p : ℕ} (initial : Stored) (history : List Stored) + (hi : StoredRep p initial) (hh : ∀ s∈history,StoredRep p s) (i : ℕ) : + (matrixCode (matrixAt p initial history i),estimateAt initial history i)= + lookup initial history i := + stored_readback (lookup_rep initial history hi hh i) + +theorem initial_readback {p : ℕ} (initial : Stored) (history : List Stored) + (hi : StoredRep p initial) : + (matrixCode (matrixAt p initial history 0),estimateAt initial history 0)=initial := + stored_readback hi + +theorem history_readback {p : ℕ} (initial : Stored) (history : List Stored) + (hi : StoredRep p initial) (hh : ∀ s∈history,StoredRep p s) : + List.ofFn (fun i : Fin history.length => + (matrixCode (matrixAt p initial history (i.val+1)),estimateAt initial history (i.val+1)))= + history := by + apply List.ext_getElem + · exact List.length_ofFn + · intro i _ hj + simp only [List.getElem_ofFn] + have h := lookup_readback initial history hi hh (i+1) + change (matrixCode (matrixAt p initial history (i+1)),estimateAt initial history (i+1))= + history.getD i initial at h + rw [List.getD_eq_getElem _ _ hj] at h + exact h + +def viewLookup {Z : Type} (initial : Z) (history : List Z) : ℕ→Z + | 0 => initial + | i+1 => history.getD i initial + +theorem view_lookup (p : ℕ) (initial : Stored) (history : List Stored) (i : ℕ) : + CompanionPhaseFinishProgram.view (p := p) (lookup initial history i)= + viewLookup (CompanionPhaseFinishProgram.view (p := p) initial) + (history.map (CompanionPhaseFinishProgram.view (p := p))) i := by + cases i with + | zero => rfl + | succ i => exact (List.getD_map history initial + (CompanionPhaseFinishProgram.view (p := p))).symm + +theorem old_eq_lookup (fixed : CompanionOuterHistoryProgram.Fixed) (history : List Stored) + (bits : List Bool) : + CompanionOuterPhaseProgram.old ((fixed,history),bits)=lookup fixed.2 history history.length := by + cases history with + | nil => rfl + | cons s history => + change (s::history).getD history.length default=(s::history).getD history.length fixed.2 + rw [List.getD_eq_getElem _ _ (by simp : history.length < (s::history).length), + List.getD_eq_getElem _ _ (by simp : history.length < (s::history).length)] + +theorem view_old (p : ℕ) (fixed : CompanionOuterHistoryProgram.Fixed) (history : List Stored) + (bits : List Bool) : + CompanionPhaseFinishProgram.view (p := p) (CompanionOuterPhaseProgram.old ((fixed,history),bits))= + viewLookup (CompanionPhaseFinishProgram.view (p := p) fixed.2) + (history.map (CompanionPhaseFinishProgram.view (p := p))) history.length := by + rw [old_eq_lookup,view_lookup] + +theorem view_old_canonical {I J : Type} [Fintype I] [Fintype J] + (A : Instance I J) {p : ℕ} (g : Fin p ≃ Labels A) + (fixed : CompanionOuterHistoryProgram.Fixed) (history : List Stored) (bits : List Bool) + (hi : CompanionPhaseFinishProgram.view (p := p) fixed.2= + CompanionCanonicalHistory.project A g (RootedStoredEstimate.initialStored A)) : + CompanionPhaseFinishProgram.view (p := p) (CompanionOuterPhaseProgram.old ((fixed,history),bits))= + CompanionCanonicalHistory.canonicalLookup A g + (history.map (CompanionPhaseFinishProgram.view (p := p))) history.length := by + rw [view_old,hi] + rfl + +variable {m n : ℕ} + +theorem outer_data_readback (A : Instance (Fin m) (Fin n)) (C K H T N R L : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (initial : Stored) (history : List Stored) + (hi : StoredRep (CanonicalInitialEncoding.copyOrder (capacities A)).length initial) + (hh : ∀ s∈history,StoredRep (CanonicalInitialEncoding.copyOrder (capacities A)).length s) + (bits : List Bool) : + CompanionOuterPhaseProgram.data A C K H T N R L history.length epsilon z v + (matrixAt (CanonicalInitialEncoding.copyOrder (capacities A)).length initial history) + (estimateAt initial history) bits= + (((CompanionRestartInitializer.data A C K H T N R L epsilon z v,initial),history),bits) := by + unfold CompanionOuterPhaseProgram.data + rw [initial_readback initial history hi,history_readback initial history hi hh] + +end +end ContingencyTables.CompanionHistoryReadback + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionHistorySize.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionHistorySize.lean new file mode 100644 index 0000000000000000000000000000000000000000..1841a142056e16ca26abf35391fcae6af405437f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionHistorySize.lean @@ -0,0 +1,187 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseSize +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterHistoryProgram + +namespace OAI + +/-! # Polynomial stored size throughout the adaptive history fold -/ +namespace ContingencyTables.CompanionOuterHistoryProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial CompanionStoredSize + +private lemma getD_property {X : Type} (P : X→Prop) (xs : List X) (i : ℕ) (d : X) + (hx : ∀ x∈xs,P x) (hd : P d) : P (xs.getD i d) := by + rw [List.getD_eq_getElem?_getD] + cases he : xs[i]? with + | none => exact hd + | some x => exact hx x (List.mem_of_getElem? he) + +lemma old_property (P : Stored→Prop) (state : State) (bits : List Bool) + (hi : P state.1.2) (hs : ∀ s∈state.2,P s) (hd : P default) : + P (CompanionOuterPhaseProgram.old (state,bits)) := by + unfold CompanionOuterPhaseProgram.old + split_ifs + · exact hi + · exact getD_property P state.2 _ default hs hd + +lemma default_height (M : ℕ) : StoredHeight M (default : Stored) := by + constructor + · intro row hr + exact False.elim (List.not_mem_nil hr) + · change max (0:ℕ).size (0:ℕ).size ≤ M + simp only [Nat.size_zero,max_self,Nat.zero_le] + +lemma default_shape (R : ℕ) : StoredShape R (default : Stored) := by + exact ⟨Nat.zero_le _,fun row hr => False.elim (List.not_mem_nil hr)⟩ + +lemma fold_length (words : List (List Bool)) (state : State) : + (words.foldl (fun s bits => advance (bits,s)) state).2.length=state.2.length+words.length := by + induction words generalizing state with + | nil => simp + | cons word words ih => + simp only [List.foldl_cons] + rw [ih] + change (state.2++[next (word,state)]).length+words.length=state.2.length+(word::words).length + simp only [List.length_append,List.length_cons,List.length_nil] + omega + +lemma fold_fixed (words : List (List Bool)) (state : State) : + (words.foldl (fun s bits => advance (bits,s)) state).1=state.1 := by + induction words generalizing state with + | nil => rfl + | cons word words ih => exact ih _ + +lemma fold_bounds (p : Polynomial ℕ) + (hp : ∀ (z : CompanionOuterPhaseProgram.Input) (S M R : ℕ), + weight z.1.1.1 ≤ S → weight z.2 ≤ S → z.1.2.length ≤ S → 1 ≤ M → + StoredHeight M (CompanionOuterPhaseProgram.old z) → + StoredShape R (CompanionOuterPhaseProgram.old z) → p.eval S ≤ R → + StoredHeight (M+p.eval S) (CompanionOuterPhaseProgram.output z) ∧ + StoredShape R (CompanionOuterPhaseProgram.output z)) + (words : List (List Bool)) (state : State) (S M R : ℕ) + (hprep : weight state.1.1 ≤ S) (hwords : ∀ bits∈words,weight bits ≤ S) + (hlen : state.2.length+words.length ≤ S) (hM : 1 ≤ M) + (hi : StoredHeight M state.1.2) (hs : ∀ s∈state.2,StoredHeight M s) + (hri : StoredShape R state.1.2) (hrs : ∀ s∈state.2,StoredShape R s) + (hR : p.eval S ≤ R) : + let out := words.foldl (fun s bits => advance (bits,s)) state + StoredHeight (M+words.length*p.eval S) out.1.2 ∧ + (∀ s∈out.2,StoredHeight (M+words.length*p.eval S) s) ∧ + StoredShape R out.1.2 ∧ (∀ s∈out.2,StoredShape R s) := by + induction words generalizing state M with + | nil => simpa only [List.foldl_nil,List.length_nil,Nat.zero_mul,Nat.add_zero] using ⟨hi,hs,hri,hrs⟩ + | cons word words ih => + have hmold := old_property (StoredHeight M) state word hi hs (default_height M) + have hrold := old_property (StoredShape R) state word hri hrs (default_shape R) + have hn := hp (state,word) S M R hprep (hwords word (by simp)) (by + change state.2.length ≤ S + simp only [List.length_cons] at hlen + omega) hM hmold hrold hR + have hnew : ∀ s∈(advance (word,state)).2,StoredHeight (M+p.eval S) s := by + intro s hmem + rcases List.mem_append.mp hmem with hmem | hmem + · exact height_mono (Nat.le_add_right _ _) (hs s hmem) + · have he := List.mem_singleton.mp hmem + subst s + exact hn.1 + have hrnew : ∀ s∈(advance (word,state)).2,StoredShape R s := by + intro s hmem + rcases List.mem_append.mp hmem with hmem | hmem + · exact hrs s hmem + · have he := List.mem_singleton.mp hmem + subst s + exact hn.2 + have hh := ih (advance (word,state)) (M+p.eval S) hprep + (fun bits hb => hwords bits (by simp [hb])) + (by simpa only [advance,List.length_append,List.length_singleton,List.length_cons,List.length_nil, + Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using hlen) + (by omega) (height_mono (Nat.le_add_right _ _) hi) hnew hri hrnew + simpa only [List.foldl_cons,List.length_cons,Nat.add_mul,Nat.one_mul, + Nat.add_assoc,Nat.add_comm,Nat.add_left_comm] using hh + + +/-- The loop's live representation has a fixed polynomial bound even on +malformed inputs; the only changing numeric values are additive-height fractions. -/ +theorem polynomial_historyFold : PolynomialTime (fold advanceRealizer) := by + obtain ⟨p,hp⟩ := CompanionPhaseSize.phase_bounds + let s : Polynomial ℕ := 2*X+1 + let r : Polynomial ℕ := s+p.comp s + let h : Polynomial ℕ := s+s*(p.comp s) + let w : Polynomial ℕ := r*(r*(8*h+4)+2)+8*h+5 + let out : Polynomial ℕ := 2+s+s*(w+1) + apply polynomial_fold polynomial_advance out + intro words state pre post he + let B := weight (words,state) + let S := 2*B+1 + let R := S+p.eval S + let M := S+S*p.eval S + have hstate : weight state ≤ B := weight_snd (words,state) + have hwords : weight words ≤ B := weight_fst (words,state) + have hpre : pre.length ≤ B := + (list_length_le_weight pre).trans ((weight_prefix he).trans hwords) + have histlen : state.2.length ≤ B := + (list_length_le_weight _).trans ((weight_snd state).trans hstate) + have hprep : weight state.1.1 ≤ S := + ((weight_fst state.1).trans ((weight_fst state).trans hstate)).trans (by dsimp [S]; omega) + have hmem : ∀ bits∈pre,weight bits ≤ S := by + intro bits hb + have hb' : bits∈words := by rw [he]; exact List.mem_append_left post hb + exact ((weight_mem hb').trans hwords).trans (by dsimp [S]; omega) + have hn : state.2.length+pre.length ≤ S := by dsimp [S]; omega + have hinit : StoredHeight S state.1.2 := + height_mono (by have := (weight_snd state.1).trans ((weight_fst state).trans hstate); dsimp [S]; omega) + (height_of_weight _) + have hinits : ∀ x∈state.2,StoredHeight S x := by + intro x hx + have hxw := (weight_mem hx).trans ((weight_snd state).trans hstate) + exact height_mono (by dsimp [S]; omega) (height_of_weight x) + have hrinit : StoredShape R state.1.2 := + shape_mono (by have := (weight_snd state.1).trans ((weight_fst state).trans hstate); dsimp [R,S]; omega) + (shape_of_weight _) + have hrinits : ∀ x∈state.2,StoredShape R x := by + intro x hx + have hxw := (weight_mem hx).trans ((weight_snd state).trans hstate) + exact shape_mono (by dsimp [R,S]; omega) (shape_of_weight x) + have hp' : ∀ (z : CompanionOuterPhaseProgram.Input) (S M R : ℕ), + weight z.1.1.1 ≤ S → weight z.2 ≤ S → z.1.2.length ≤ S → 1 ≤ M → + StoredHeight M (CompanionOuterPhaseProgram.old z) → + StoredShape R (CompanionOuterPhaseProgram.old z) → p.eval S ≤ R → + StoredHeight (M+p.eval S) (CompanionOuterPhaseProgram.output z) ∧ + StoredShape R (CompanionOuterPhaseProgram.output z) := hp + have hb := fold_bounds p hp' pre state S S R hprep hmem hn (by dsimp [S]; omega) + hinit hinits hrinit hrinits (by dsimp [R]; omega) + let result := pre.foldl (fun s bits => advance (bits,s)) state + have hm : S+pre.length*p.eval S ≤ M := by + have hle : pre.length ≤ S := by dsimp [S]; omega + exact Nat.add_le_add_left (Nat.mul_le_mul_right _ hle) S + have hstored : ∀ x∈result.2,weight x ≤ R*(R*(8*M+4)+2)+8*M+5 := by + intro x hx + exact weight_of_bounds x R M (hb.2.2.2 x hx) (height_mono hm (hb.2.1 x hx)) + have hw := weight_map_bound (f := id) (as := result.2) hstored + simp only [List.map_id] at hw + have hlen : result.2.length ≤ S := (fold_length pre state).trans_le hn + have hw' : weight result.2 ≤ S*(R*(R*(8*M+4)+2)+8*M+5+1)+1 := + hw.trans (by gcongr) + have hf : weight result.1 ≤ S := by + change weight ((pre.foldl (fun s bits => advance (bits,s)) state).1) ≤ S + rw [fold_fixed] + exact ((weight_fst state).trans hstate).trans (by dsimp [S]; omega) + change weight result ≤ out.eval B + conv_lhs => rw [show result=(result.1,result.2) from rfl,weight_prod] + have hout : out.eval B=2+S+S*(R*(R*(8*M+4)+2)+8*M+5+1) := by + simp only [out,w,r,h,s,R,M,S,eval_add,eval_mul,eval_ofNat,eval_X,eval_one,eval_comp] + rw [hout] + omega + +lemma polynomial_run : PolynomialTime runRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_pair polynomial_first (polynomial_constant []))) polynomial_historyFold + +lemma polynomial_storedHistory : PolynomialTime storedHistoryRealizer := + polynomial_composition polynomial_run polynomial_second + +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair (polynomial_pair polynomial_first polynomial_storedHistory) + (polynomial_constant [])) CompanionOuterPhaseProgram.polynomial_old + +end ContingencyTables.CompanionOuterHistoryProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..41d4c0ff5339c8e3c11e1674bf599933b960fde8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialDraw.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Machines.InitialFactorialBits +import OAI.Combinatorics.ContingencyTables.Transport.RealKernelApproximation + +namespace OAI + +/-! # Actual bounded-word initialization of the companion trace + +The output is in the literal `PlainIndex` used by the trace chain. Its +ideal rational law is exactly the source's phase-zero law; the bounded +word implementation is within 2^(-h), with an explicit word length. +-/ + +namespace ContingencyTables.CompanionInitialDraw + +open CommonBasesFPRAS ResidualMixture FirstSuccess TwoLiftStates +open CompanionFactorialApplication InitialFactorialLaw InitialFactorialBits +open RealKernelApproximation +open scoped BigOperators Classical +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def cellEnum (A : Instance I J) : SmallCell A ≃ Fin (Fintype.card (SmallCell A)) := + Fintype.equivFin (SmallCell A) + +def cellCapacity (A : Instance I J) (i : Fin (Fintype.card (SmallCell A))) : ℕ := + A.b ((cellEnum A).symm i).val.1 ((cellEnum A).symm i).val.2 + +def indexEquiv (A : Instance I J) : + {S : Set (Labels A×Bool) // PlainState pairs S} ≃ + PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) where + toFun S := ⟨⟨S.val,Or.inl S.property⟩,S.property⟩ + invFun S := ⟨S.val.val,S.property⟩ + left_inv _ := rfl + right_inv _ := rfl + +def idealLaw (A : Instance I J) : + RationalLaw (PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) := + equivLaw (indexEquiv A) (companionLaw A) + +theorem idealLaw_mass (A : Instance I J) + (S : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + ((idealLaw A).mass S:ℝ)=CompanionWarmStart.law A 0 S.val.val := + companionLaw_mass A ((indexEquiv A).symm S) + +def initialBits (A : Instance I J) (B : ℕ) : ℕ := bitCount (cellCapacity A) B + +def draw (A : Instance I J) (B : ℕ) (bits : Fin (initialBits A B) → Bool) : + PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) := + indexEquiv A (transversalDraw (fun s : SmallCell A => A.b s.val.1 s.val.2) + (cellEnum A) B bits) + +lemma cellCount_bound (A : Instance I J) : Fintype.card (SmallCell A)≤A.d := by + exact (Fintype.card_le_of_injective (fun s : SmallCell A => s.val) Subtype.val_injective).trans + (by simpa only [Fintype.card_prod] using A.hcard) + +lemma cellCapacity_bound (A : Instance I J) (i : Fin (Fintype.card (SmallCell A))) : + cellCapacity A i≤A.W := + (A.hsmall _ _ ((cellEnum A).symm i).property).le + +theorem initialBits_bound (A : Instance I J) (B : ℕ) : + initialBits A B≤A.d*(A.W+1)*B := by + have hh := bitCount_bound (cellCapacity A) B A.W (cellCapacity_bound A) + exact hh.trans (Nat.mul_le_mul_right B + (Nat.mul_le_mul_right (A.W+1) (cellCount_bound A))) + +theorem draw_error (A : Instance I J) (B : ℕ) : + variation (mapLaw (uniformLaw (α := Fin (initialBits A B) → Bool)) (draw A B)) + (idealLaw A)≤(A.d:ℚ)*(3*A.W+1)/(2*(2:ℚ)^B) := by + unfold draw initialBits cellCapacity + have he := mapLaw_equiv_output (indexEquiv A) + (uniformLaw (α := Fin (bitCount + (fun i => A.b ((cellEnum A).symm i).val.1 ((cellEnum A).symm i).val.2) B) → Bool)) + (transversalDraw (fun s : SmallCell A => A.b s.val.1 s.val.2) (cellEnum A) B) + rw [he,idealLaw,variation_equiv] + have ht := transversalDraw_error (fun s : SmallCell A => A.b s.val.1 s.val.2) + (cellEnum A) B A.W (fun s => (A.hsmall _ _ s.property).le) + apply ht.trans + apply div_le_div_of_nonneg_right _ (by positivity) + apply mul_le_mul_of_nonneg_right _ (by positivity) + exact_mod_cast cellCount_bound A + +def precision (A : Instance I J) (h : ℕ) : ℕ := + Nat.clog 2 (A.d*(3*A.W+1)+1)+h + +lemma precision_error (A : Instance I J) (h : ℕ) : + (A.d:ℚ)*(3*A.W+1)/(2*(2:ℚ)^precision A h)≤1/(2:ℚ)^h := by + have hc : A.d*(3*A.W+1)≤2^Nat.clog 2 (A.d*(3*A.W+1)+1) := + (Nat.le_succ _).trans (Nat.le_pow_clog (by decide) _) + have hcr : (A.d:ℚ)*(3*A.W+1)≤(2:ℚ)^Nat.clog 2 (A.d*(3*A.W+1)+1) := by + exact_mod_cast hc + unfold precision + rw [pow_add] + apply (div_le_div_iff₀ (by positivity) (by positivity)).mpr + have hp := mul_le_mul_of_nonneg_right hcr (show 0≤(2:ℚ)^h by positivity) + have hp0 : 0≤(2:ℚ)^Nat.clog 2 (A.d*(3*A.W+1)+1)*(2:ℚ)^h := by positivity + nlinarith [pow_pos (by norm_num : (0:ℚ)<2) h] + +/-- The implemented initial word is compared directly to the literal +phase-zero law, so later restart estimates need no initializer oracle. -/ +theorem initial_distance (A : Instance I J) (h : ℕ) : + distance (fun S => ((mapLaw (uniformLaw (α := Fin (initialBits A (precision A h)) → Bool)) + (draw A (precision A h))).mass S:ℝ)) + (fun S => CompanionWarmStart.law A 0 S.val.val)≤1/(2:ℝ)^h := by + have hh := (draw_error A (precision A h)).trans (precision_error A h) + have he : distance + (fun S => ((mapLaw (uniformLaw (α := Fin (initialBits A (precision A h)) → Bool)) + (draw A (precision A h))).mass S:ℝ)) + (fun S => CompanionWarmStart.law A 0 S.val.val)= + (variation (mapLaw (uniformLaw (α := Fin (initialBits A (precision A h)) → Bool)) + (draw A (precision A h))) (idealLaw A):ℝ) := by + simp_rw [←idealLaw_mass A] + simp only [distance,variation,Rat.cast_div,Rat.cast_sum,Rat.cast_abs,Rat.cast_sub,Rat.cast_ofNat] + rw [he] + have hc : (variation (mapLaw (uniformLaw (α := Fin (initialBits A (precision A h)) → Bool)) + (draw A (precision A h))) (idealLaw A):ℝ)≤((1/(2:ℚ)^h:ℚ):ℝ) := Rat.cast_le.mpr hh + simpa only [Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] using hc + +end +end ContingencyTables.CompanionInitialDraw + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..e0a4394ffac9061740a70e4fb67c701bbab88430 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialMatrixProgram.lean @@ -0,0 +1,156 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionLabelMetadataProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierMatrixProgram + +namespace OAI + +/-! # Executing the initial canonical multiplier matrix -/ + +namespace ContingencyTables.CompanionInitialMatrixProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped CompanionMultiplierMatrixProgram + +abbrev Metadata := ℕ × ℕ + +def numerator (z : Metadata × Metadata) : ℕ := 6*(z.1.2+1) +def numeratorRealizer : Realizer numerator := + composition (f := fun z : Metadata × Metadata => (6,z.1.2+1)) + (g := fun p : ℕ × ℕ => p.1*p.2) + (pair (constant 6) (composition (composition first second) successor)) multiply +lemma polynomial_numerator : PolynomialTime numeratorRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 6) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_successor)) polynomial_multiply + +def denominator (z : Metadata × Metadata) : ℕ := z.2.2+2 +def denominatorRealizer : Realizer denominator := + composition (f := fun z : Metadata × Metadata => (z.2.2,2)) + (g := fun p : ℕ × ℕ => p.1+p.2) + (pair (composition second second) (constant 2)) add +lemma polynomial_denominator : PolynomialTime denominatorRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_constant 2)) polynomial_add + +def sameCell (z : Metadata × Metadata) : Bool := decide (z.1.1=z.2.1) +def sameCellRealizer : Realizer sameCell := + composition (pair (composition first first) (composition second first)) natEqual +lemma polynomial_sameCell : PolynomialTime sameCellRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) polynomial_natEqual + +def entry (z : Metadata × Metadata) : TreeFraction.Fraction := + if sameCell z then (6,1) else TreeFraction.normalize (numerator z,denominator z) +def entryRealizer : Realizer entry := + choose sameCellRealizer (constant (6,1)) + (composition (pair numeratorRealizer denominatorRealizer) TreeFraction.normalizeRealizer) +lemma polynomial_entry : PolynomialTime entryRealizer := + polynomial_choose polynomial_sameCell (polynomial_constant (6,1)) + (polynomial_composition (polynomial_pair polynomial_numerator polynomial_denominator) + TreeFraction.polynomial_normalize) + +def row (z : List Metadata × Metadata) : List TreeFraction.Fraction := + z.1.map (fun b => entry (z.2,b)) +def rowRealizer : Realizer row := composition (pair second first) (mapWith entryRealizer) +lemma polynomial_row : PolynomialTime rowRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_entry) + +def matrix (xs : List Metadata) : FractionMatrix := xs.map (fun a => row (xs,a)) +def matrixRealizer : Realizer matrix := composition (pair identity identity) (mapWith rowRealizer) +lemma polynomial_matrix : PolynomialTime matrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_identity) + (polynomial_mapWith polynomial_row) + +def output (z : PairedProfileProgram.Input) : FractionMatrix := + matrix (CompanionLabelMetadataProgram.output z) +def outputRealizer : Realizer output := + composition (f := CompanionLabelMetadataProgram.output) (g := matrix) + CompanionLabelMetadataProgram.outputRealizer matrixRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition CompanionLabelMetadataProgram.polynomial_output polynomial_matrix + +lemma entry_val (a b : Metadata) : + TreeFraction.val (entry (a,b))= + if a.1=b.1 then 6 else 6*((a.2:ℚ)+1)/((b.2:ℚ)+2) := by + unfold entry sameCell + by_cases h : a.1=b.1 + · simp only [h,decide_true,ite_true,TreeFraction.val,Nat.cast_ofNat,Nat.cast_one,div_one] + · simp only [h,decide_false,Bool.false_eq_true,ite_false] + rw [TreeFraction.normalize_val] + simp only [TreeFraction.val,numerator,denominator,Nat.cast_mul,Nat.cast_add,Nat.cast_ofNat,Nat.cast_one] + +lemma matrix_ofFn {p : ℕ} (f : Fin p → Metadata) : + matrix (List.ofFn f)=matrixCode (fun i j => entry (f i,f j)) := by + simp only [matrix,row,matrixCode,List.map_ofFn,Function.comp_def] + +noncomputable section +open CanonicalInitialEncoding InitialTransversals CompanionArithmeticProposal +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionRationalUpdates TwoLiftStates +open scoped Classical + +variable {q : ℕ} (b : Fin q → ℕ) + +def metadataAt (i : Fin (CanonicalInitialEncoding.copyOrder b).length) : Metadata := + ((PairedCatalogProgram.labelOrder b i).1.val,b (PairedCatalogProgram.labelOrder b i).1) + +lemma metadata_code (S : Set (Copy b × Bool)) : + CompanionLabelMetadataProgram.output (List.ofFn b,encodeSet (coordinateEquiv b) S)= + List.ofFn (metadataAt b) := by + rw [CompanionLabelMetadataProgram.output_encode] + let f : Copy b → Metadata := fun p => (p.1.val,b p.1) + change (copyOrder b).map f=List.ofFn (fun i => f ((copyOrder b)[i.val])) + exact (List.ofFn_getElem_eq_map (copyOrder b) f).symm + +theorem output_code (S : Set (Copy b × Bool)) : + output (List.ofFn b,encodeSet (coordinateEquiv b) S)= + matrixCode (fun i j => entry (metadataAt b i,metadataAt b j)) := by + rw [output,metadata_code,matrix_ofFn] + +variable {m n : ℕ} (A : Instance (Fin m) (Fin n)) + +def initialEntries (i j : Fin (CanonicalInitialEncoding.copyOrder (capacities A)).length) : TreeFraction.Fraction := + entry (metadataAt (capacities A) i,metadataAt (capacities A) j) + +lemma pairLabels_cell (i : Fin (CanonicalInitialEncoding.copyOrder (capacities A)).length) : + cellOrder A (pairLabels A i).1=(PairedCatalogProgram.labelOrder (capacities A) i).1 := by + change cellOrder A ((cellOrder A).symm (PairedCatalogProgram.labelOrder (capacities A) i).1)=_ + exact (cellOrder A).apply_symm_apply _ + +lemma metadata_cell_iff (i j : Fin (CanonicalInitialEncoding.copyOrder (capacities A)).length) : + (metadataAt (capacities A) i).1=(metadataAt (capacities A) j).1 ↔ + (pairLabels A i).1=(pairLabels A j).1 := by + constructor + · intro h + apply (cellOrder A).injective + rw [pairLabels_cell,pairLabels_cell] + exact Fin.ext h + · intro h + have he := congrArg (fun s => (cellOrder A s).val) h + simpa only [pairLabels_cell,metadataAt] using he + +lemma metadata_capacity (i : Fin (CanonicalInitialEncoding.copyOrder (capacities A)).length) : + (metadataAt (capacities A) i).2=A.b (pairLabels A i).1.val.1 (pairLabels A i).1.val.2 := by + change capacities A (PairedCatalogProgram.labelOrder (capacities A) i).1=_ + rw [←pairLabels_cell] + unfold capacities + rw [Equiv.symm_apply_apply] + +theorem initialEntries_val (i j : Fin (CanonicalInitialEncoding.copyOrder (capacities A)).length) : + TreeFraction.val (initialEntries A i j)= + CompanionRationalUpdates.initial A (pair (pairLabels A i)) (pair (pairLabels A j)) := by + unfold initialEntries + rw [entry_val] + simp only [CompanionRationalUpdates.initial,TwoLiftStates.pair] + simp only [metadata_cell_iff,metadata_capacity] + by_cases h : (pairLabels A i).1=(pairLabels A j).1 <;> simp only [h,ite_true,ite_false] + +theorem output_physical (S : Set (Labels A × Bool)) : + output (List.ofFn (capacities A),encodeSet (coordinateOrder A) S)= + matrixCode (initialEntries A) := by + rw [encodeSet_reindex,output_code] + rfl + +end +end ContingencyTables.CompanionInitialMatrixProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialStoredProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialStoredProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1232cb488ce7908f20bd2d61cfc740815c38cd8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialStoredProgram.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialMatrixProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedStoredEstimate +import OAI.Combinatorics.ContingencyTables.Rooted.RootedForestCatalog + +namespace OAI + +/-! # The literal initial count and stored multiplier matrix + +The integer count is the product of the free-cell ranges and the small-cell +ranges. Both lists come from the executed forest and cell catalogs. +-/ +namespace ContingencyTables.CompanionInitialStoredProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms ProfilePrograms + +abbrev Input := RootedForestCatalog.Data × PairedProfileProgram.Input + +def rangeAt (z : RootedForestCatalog.Data×(ℕ×ℕ)) : ℕ := matrixEntry (z.1.2,z.2)+1 +def rangeAtRealizer : Realizer rangeAt := + composition (f := fun z : RootedForestCatalog.Data×(ℕ×ℕ) => matrixEntry (z.1.2,z.2)) + (g := Nat.succ) + (composition (f := fun z : RootedForestCatalog.Data×(ℕ×ℕ) => (z.1.2,z.2)) + (g := matrixEntry) (pair (composition first second) second) matrixEntryRealizer) successor +lemma polynomial_rangeAt : PolynomialTime rangeAtRealizer := + polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_matrixEntry) polynomial_successor + +def freeRanges (d : RootedForestCatalog.Data) : List ℕ := + (RootedForestCatalog.catalog (d,false)).map (fun ij => rangeAt (d,ij)) +def freeRangesRealizer : Realizer freeRanges := + composition (f := fun d : RootedForestCatalog.Data => (d,RootedForestCatalog.catalog (d,false))) + (g := fun p : RootedForestCatalog.Data×List (ℕ×ℕ) => p.2.map (fun ij => rangeAt (p.1,ij))) + (pair identity (composition (f := fun d : RootedForestCatalog.Data => (d,false)) + (g := RootedForestCatalog.catalog) (pair identity (constant false)) RootedForestCatalog.catalogRealizer)) + (mapWith rangeAtRealizer) +lemma polynomial_freeRanges : PolynomialTime freeRangesRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant false)) + RootedForestCatalog.polynomial_catalog)) (polynomial_mapWith polynomial_rangeAt) + +def freeProduct (d : RootedForestCatalog.Data) : ℕ := (freeRanges d).prod +def freeProductRealizer : Realizer freeProduct := + composition (f := freeRanges) (g := List.prod) freeRangesRealizer listProd +lemma polynomial_freeProduct : PolynomialTime freeProductRealizer := + polynomial_composition polynomial_freeRanges polynomial_listProd + +def smallProduct (xs : List ℕ) : ℕ := (xs.map Nat.succ).prod +def smallProductRealizer : Realizer smallProduct := composition (map successor) listProd +lemma polynomial_smallProduct : PolynomialTime smallProductRealizer := + polynomial_composition (polynomial_map polynomial_successor) polynomial_listProd + +def total (z : Input) : TreeFraction.Fraction := + (freeProduct z.1*smallProduct z.2.1,1) +def totalRealizer : Realizer total := + pair (composition (f := fun z : Input => (freeProduct z.1,smallProduct z.2.1)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (f := fun z : Input => z.1) (g := freeProduct) first freeProductRealizer) + (composition (f := fun z : Input => z.2.1) (g := smallProduct) + (composition second first) smallProductRealizer)) multiply) (constant 1) +lemma polynomial_total : PolynomialTime totalRealizer := + polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_freeProduct) + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_smallProduct)) polynomial_multiply) (polynomial_constant 1) + +def output (z : Input) : CompanionMultiplierMatrixProgram.FractionMatrix×TreeFraction.Fraction := + (CompanionInitialMatrixProgram.output z.2,total z) +def outputRealizer : Realizer output := + pair (composition (f := fun z : Input => z.2) (g := CompanionInitialMatrixProgram.output) + second CompanionInitialMatrixProgram.outputRealizer) totalRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_pair (polynomial_composition polynomial_second + CompanionInitialMatrixProgram.polynomial_output) polynomial_total + +noncomputable section +open CompanionFactorialApplication CompanionComputedInitial ForestAssignmentSplit +open CompanionArithmeticProposal +open scoped BigOperators Classical +variable {m n : ℕ} (A : Instance (Fin m) (Fin n)) + +def data (S : Set (Labels A×Bool)) : Input := + (RootedForestCatalog.data A,(List.ofFn (capacities A),encodeSet (coordinateOrder A) S)) + +lemma rangeAt_data (ij : Fin m×Fin n) : + rangeAt (RootedForestCatalog.data A,(ij.1.val,ij.2.val))=A.b ij.1 ij.2+1 := by + unfold rangeAt RootedForestCatalog.data + rw [matrixEntry_code] + +lemma freeRanges_data : freeRanges (RootedForestCatalog.data A)= + List.ofFn (fun i => A.b (RootedForestCatalog.freeEquiv A i).val.1 + (RootedForestCatalog.freeEquiv A i).val.2+1) := by + unfold freeRanges + conv_lhs => rw [←List.ofFn_get (RootedForestCatalog.catalog (RootedForestCatalog.data A,false))] + rw [List.map_ofFn] + apply congrArg List.ofFn + funext i + dsimp only [Function.comp_apply,List.get_eq_getElem] + have h := RootedForestCatalog.catalogCell_coordinates A false i + change ((RootedForestCatalog.freeEquiv A i).val.1.val, + (RootedForestCatalog.freeEquiv A i).val.2.val)=_ at h + rw [←h] + exact rangeAt_data A _ + +theorem total_data (S : Set (Labels A×Bool)) : + TreeFraction.val (total (data A S))=RootedStoredEstimate.initialTotal A := by + unfold total data freeProduct smallProduct + rw [freeRanges_data] + simp only [List.prod_ofFn,List.map_ofFn,TreeFraction.val,Nat.cast_one,div_one, + Nat.cast_mul,Nat.cast_prod] + unfold RootedStoredEstimate.initialTotal + congr 1 + · exact Fintype.prod_equiv (RootedForestCatalog.freeEquiv A) _ _ (fun _ => rfl) + · exact Fintype.prod_equiv (cellOrder A).symm _ _ (fun _ => rfl) + +theorem output_matrix (S : Set (Labels A×Bool)) : + (output (data A S)).1=CompanionMultiplierMatrixProgram.matrixCode + (CompanionInitialMatrixProgram.initialEntries A) := + CompanionInitialMatrixProgram.output_physical A S + +end +end ContingencyTables.CompanionInitialStoredProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialization.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..18685ac21d169e41db23ebf3f103733ce073e054 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitialization.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFactorialApplication +import OAI.Combinatorics.ContingencyTables.Transport.InitialTransversals + +namespace OAI + +/-! # Exact initial normalizer for the literal companion completion count -/ + +namespace ContingencyTables.CompanionInitialization + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication LabelledFactorial TwoLiftStates + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def freeTotal (A : Instance I J) : ℝ := + ∏ a : ForestAssignmentSplit.FreeCell A.small A.T, + ((A.b a.val.1 a.val.2+1:ℕ):ℝ) + +theorem h_zero (A : Instance I J) (z : View A → ℕ) : h A 0 z=freeTotal A := + ForestCountIdentification.sourceMarginal_zero A.small A.T A.d A.b A.r A.c z + +theorem denominator_eq (A : Instance I J) : + CompanionFactorialApplication.denominator A= + InitialTransversals.denominator (fun s : SmallCell A => A.b s.val.1 s.val.2) := by + unfold CompanionFactorialApplication.denominator TwoLiftStates.denominator InitialTransversals.denominator + simp_rw [label_width] + +/-- C(0) is derived for the actual source f, using the finite +paired-transversal enumeration and the literal free-completion count. -/ +theorem total_zero (A : Instance I J) : + slotTotal pairs (f A 0) ∅=freeTotal A*∏ s : SmallCell A, ((A.b s.val.1 s.val.2:ℝ)+1) := by + have he : f A 0=firstLift (group (labelCell A)) (fun _ => freeTotal A) + (CompanionFactorialApplication.denominator A) := by + funext S + unfold f firstLift + rw [h_zero] + rw [he,denominator_eq] + convert InitialTransversals.slotTotal_constant + (fun s : SmallCell A => A.b s.val.1 s.val.2) (freeTotal A) using 1 + congr 1 + +end ContingencyTables.CompanionInitialization + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartJoint.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartJoint.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb155b10294e6fd4ce64b42d63c366401867f1b2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartJoint.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartLaw +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordJointPadding + +namespace OAI + +/-! # Joint restart law with the unused trajectory and query suffix -/ +namespace ContingencyTables.CompanionInitializedRestartProgram +open MatchingFPRAS CommonBasesFPRAS FirstSuccess FairBits FiniteObservableTransport +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionEvaluatedWeightProgram +open CompanionOracleDensity TwoLiftStates GridBoundary +open scoped BigOperators Classical +noncomputable section +variable {m n : ℕ} + +def jointModel (A : Instance (Fin m) (Fin n)) (C K H T N R L j padding : ℕ) + (epsilon : TreeFraction.Fraction) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (bits : Fin (CompanionInitialDraw.initialBits A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) → Bool) : + PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))×(Fin padding → Bool) := + let B := CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H) + let widths := CompanionRestartProgram.sourceWidth A C K (parameters A H T N R L epsilon) + let blocks := splitWordEquiv (CompanionInitialDraw.initialBits A B) + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding) bits + let tail := splitWordEquiv (CompanionRestartProgram.sumBits A C K j + (parameters A H T N R L epsilon)) padding blocks.2 + (varyingWalk widths + (CompanionRestartProgram.sourceStep A C K (parameters A H T N R L epsilon) hK hW v w) + (CompanionInitialDraw.draw A B blocks.1) j (varyingWordEquiv widths j tail.1),tail.2) + +theorem output_joint_sameLaw (A : Instance (Fin m) (Fin n)) (C K H T N R L j padding : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (epsilon : TreeFraction.Fraction) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise (parameters A H T N R L epsilon))) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (estimates : Fin j → TreeFraction.Fraction) + (hdegree : ∀ i : Fin j,RootedOracleConfigProgram.rootDegree + (CompanionRestartStageProgram.oracleData A C K (i.val+1) (parameters A H T N R L epsilon) z v + (List.replicate (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) false)) ≤ + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) + (hdepth : ∀ i : Fin j,RootedOracleConfigProgram.depth + (CompanionRestartStageProgram.oracleData A C K (i.val+1) (parameters A H T N R L epsilon) z v + (List.replicate (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) false)) ≤ + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) : + SameLaw (fun bits : Fin (wordLength A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) → Bool => + (output (data A C K H T N R L j epsilon z v w estimates (List.ofFn bits)), + (splitWordEquiv (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)) + padding (splitWordEquiv + (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))) + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding) bits).2).2)) + (fun bits => + (encodeSet (coordinateOrder A) (jointModel A C K H T N R L j padding epsilon hK hW v w bits).1.val.val, + (jointModel A C K H T N R L j padding epsilon hK hW v w bits).2)) := by + let B := CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H) + let p := parameters A H T N R L epsilon + let n := CompanionRestartProgram.sumBits A C K j p + let reserve := List.replicate (wordLength A B+(n+padding)) false + let stageList := CompanionRestartProgram.stagesData A C K j p z v reserve w + let init := fun bits : Fin (wordLength A B) → Bool => CompanionRestartInitializer.output + (CompanionRestartInitializer.data A C K H T N R L epsilon z v,List.ofFn bits) + let realInit := CompanionInitialDraw.draw A B + let encode := fun S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) => + encodeSet (coordinateOrder A) S.val.val + let run := fun code (bits : Fin (n+padding) → Bool) => + (CompanionRestartProgram.output ((stageList,code),List.ofFn bits),(splitWordEquiv n padding bits).2) + let sourceRun := fun S (bits : Fin n → Bool) => encode (varyingWalk + (CompanionRestartProgram.sourceWidth A C K p) + (CompanionRestartProgram.sourceStep A C K p hK hW v w) S j + (varyingWordEquiv (CompanionRestartProgram.sourceWidth A C K p) j bits)) + let realRun := fun S (bits : Fin (n+padding) → Bool) => + (sourceRun S (splitWordEquiv n padding bits).1,(splitWordEquiv n padding bits).2) + have hi : SameLaw init (fun bits => encode (realInit bits)) := + CompanionRestartInitializer.output_sameLaw A C K H T N R L epsilon z v + have hs : ∀ S,SameLaw (run (encode S)) (realRun S) := by + intro S + have hn := CompanionRestartProgram.widthSum_data A C K j p z v reserve w S.val.val + have hh := CompanionRestartProgram.output_native_sameLaw A C K j hC hj hK hW hB p hxi z v reserve + (fun i => by simpa only [reserve,List.length_replicate] using hdegree i) + (fun i => by simpa only [reserve,List.length_replicate] using hdepth i) w S + exact restart_append_joint_sameLaw (CompanionRestartProgram.baseData A C K j p z v reserve w S.val.val) + n n hn (sourceRun S) hh padding + have hf := flat_encoded_bind (wordLength A B) (n+padding) (CompanionInitialDraw.initialBits A B) (n+padding) + init realInit encode run realRun hi hs + intro phi + have h := hf phi + have he : (fun bits : Fin (wordLength A B+(n+padding)) → Bool => + (output (data A C K H T N R L j epsilon z v w estimates (List.ofFn bits)), + (splitWordEquiv n padding (splitWordEquiv (wordLength A B) (n+padding) bits).2).2))= + (fun bits => run (init (splitWordEquiv (wordLength A B) (n+padding) bits).1) + (splitWordEquiv (wordLength A B) (n+padding) bits).2) := by + funext bits + apply Prod.ext + · exact output_split A C K H T N R L j (n+padding) epsilon z v w estimates bits + · rfl + rw [he] + exact h + +theorem jointModel_sameLaw (A : Instance (Fin m) (Fin n)) (C K H T N R L j padding : ℕ) + (epsilon : TreeFraction.Fraction) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) : + SameLaw (fun bits => + (encodeSet (coordinateOrder A) (jointModel A C K H T N R L j padding epsilon hK hW v w bits).1.val.val, + (jointModel A C K H T N R L j padding epsilon hK hW v w bits).2)) + (fun bits : + (Fin (CompanionInitialDraw.initialBits A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)) → Bool)× + (Fin padding → Bool) => + (encodeSet (coordinateOrder A) (model A C K H T N R L j epsilon hK hW v w bits.1).val.val,bits.2)) := by + let B := CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H) + let p := parameters A H T N R L epsilon + let widths := CompanionRestartProgram.sourceWidth A C K p + exact nested_word_joint (CompanionInitialDraw.initialBits A B) + (CompanionRestartProgram.sumBits A C K j p) padding + (fun initBits stageBits => encodeSet (coordinateOrder A) + (varyingWalk widths (CompanionRestartProgram.sourceStep A C K p hK hW v w) + (CompanionInitialDraw.draw A B initBits) j (varyingWordEquiv widths j stageBits)).val.val) + + +end +end ContingencyTables.CompanionInitializedRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..e75a5d5f87b8ca329bf4c1a636d53eec512f0be8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartLaw.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartNativeLaw +import OAI.Combinatorics.ContingencyTables.Machines.FiniteEncodedBind +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartPadding + +namespace OAI + +/-! # Exact law of the complete executed initializer and restart prefix -/ +namespace ContingencyTables.CompanionInitializedRestartProgram +open MatchingFPRAS CommonBasesFPRAS FirstSuccess FairBits FiniteObservableTransport +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionEvaluatedWeightProgram +open CompanionOracleDensity TwoLiftStates GridBoundary +open scoped BigOperators Classical +noncomputable section +variable {m n : ℕ} + +def parameters (A : Instance (Fin m) (Fin n)) (H T N R L : ℕ) + (epsilon : TreeFraction.Fraction) : CountingPhaseParametersProgram.Input := + ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon) + +def model (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (bits : Fin (CompanionInitialDraw.initialBits A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)) → Bool) : + PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) := + let B := CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H) + let widths := CompanionRestartProgram.sourceWidth A C K (parameters A H T N R L epsilon) + let split := splitWordEquiv (CompanionInitialDraw.initialBits A B) + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)) bits + varyingWalk widths + (CompanionRestartProgram.sourceStep A C K (parameters A H T N R L epsilon) hK hW v w) + (CompanionInitialDraw.draw A B split.1) j (varyingWordEquiv widths j split.2) + + /-- The actual list program has the complete finite-word law, including + every initialization bias, rejected return and fallback. -/ +theorem output_padded_sameLaw (A : Instance (Fin m) (Fin n)) (C K H T N R L j padding : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (epsilon : TreeFraction.Fraction) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise (parameters A H T N R L epsilon))) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (estimates : Fin j → TreeFraction.Fraction) + (hdegree : ∀ i : Fin j,RootedOracleConfigProgram.rootDegree + (CompanionRestartStageProgram.oracleData A C K (i.val+1) (parameters A H T N R L epsilon) z v + (List.replicate (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) false)) ≤ + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) + (hdepth : ∀ i : Fin j,RootedOracleConfigProgram.depth + (CompanionRestartStageProgram.oracleData A C K (i.val+1) (parameters A H T N R L epsilon) z v + (List.replicate (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) false)) ≤ + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) : + SameLaw (fun bits : Fin (wordLength A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) → Bool => + output (data A C K H T N R L j epsilon z v w estimates (List.ofFn bits))) + (fun bits => encodeSet (coordinateOrder A) (model A C K H T N R L j epsilon hK hW v w bits).val.val) := by + let B := CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H) + let p := parameters A H T N R L epsilon + let n := CompanionRestartProgram.sumBits A C K j p + let reserve := List.replicate (wordLength A B+(n+padding)) false + let stageList := CompanionRestartProgram.stagesData A C K j p z v reserve w + let init := fun bits : Fin (wordLength A B) → Bool => CompanionRestartInitializer.output + (CompanionRestartInitializer.data A C K H T N R L epsilon z v,List.ofFn bits) + let realInit := CompanionInitialDraw.draw A B + let encode := fun S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) => + encodeSet (coordinateOrder A) S.val.val + let run := fun code (bits : Fin (n+padding) → Bool) => + CompanionRestartProgram.output ((stageList,code),List.ofFn bits) + let realRun := fun S (bits : Fin n → Bool) => encode (varyingWalk + (CompanionRestartProgram.sourceWidth A C K p) + (CompanionRestartProgram.sourceStep A C K p hK hW v w) S j + (varyingWordEquiv (CompanionRestartProgram.sourceWidth A C K p) j bits)) + have hi : SameLaw init (fun bits => encode (realInit bits)) := + CompanionRestartInitializer.output_sameLaw A C K H T N R L epsilon z v + have hs : ∀ S,SameLaw (run (encode S)) (realRun S) := by + intro S + have hn := CompanionRestartProgram.widthSum_data A C K j p z v reserve w S.val.val + have hh := CompanionRestartProgram.output_native_sameLaw A C K j hC hj hK hW hB p hxi z v reserve + (fun i => by simpa only [reserve,List.length_replicate] using hdegree i) + (fun i => by simpa only [reserve,List.length_replicate] using hdepth i) w S + exact restart_append_sameLaw (CompanionRestartProgram.baseData A C K j p z v reserve w S.val.val) + n hn (realRun S) hh padding + have hf := flat_encoded_bind (wordLength A B) (n+padding) (CompanionInitialDraw.initialBits A B) n + init realInit encode run realRun hi hs + intro phi + have h := hf phi + have he : (fun bits : Fin (wordLength A B+(n+padding)) → Bool => + output (data A C K H T N R L j epsilon z v w estimates (List.ofFn bits)))= + (fun bits => run (init (splitWordEquiv (wordLength A B) (n+padding) bits).1) + (splitWordEquiv (wordLength A B) (n+padding) bits).2) := by + funext bits + exact output_split A C K H T N R L j (n+padding) epsilon z v w estimates bits + rw [he] + exact h + + /-- When the supplied restart time is the computed paper schedule, + the reference experiment is precisely initializedStages. -/ +theorem model_eq_initializedStages (A : Instance (Fin m) (Fin n)) (C K H N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (bits : Fin (RootedRestartWords.initialStageBits A C K H L + (CountingPhaseParametersProgram.precision + (parameters A H (CompanionTargetMixing.restartTime A H L) N R L epsilon)) + R (CountingPhaseSchedule.initialPrecision H) j + (TreeFraction.val (CountingPhaseParametersProgram.noise + (parameters A H (CompanionTargetMixing.restartTime A H L) N R L epsilon)))) → Bool) : + model A C K H (CompanionTargetMixing.restartTime A H L) N R L j epsilon hK hW v w bits= + RootedRestartWords.initializedStages A (RootedCompletion.rowColumn A.T) C K H L + (CountingPhaseParametersProgram.precision + (parameters A H (CompanionTargetMixing.restartTime A H L) N R L epsilon)) + R (CountingPhaseSchedule.initialPrecision H) j hK hW + (TreeFraction.val (CountingPhaseParametersProgram.noise + (parameters A H (CompanionTargetMixing.restartTime A H L) N R L epsilon))) + (RootedCatalogGrid.gridEquiv A K v) (fun i => sourceWeights A (w i)) bits := rfl + +end +end ContingencyTables.CompanionInitializedRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b2d551ce1f986b045af0efc28dcfa78f89dc614 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartProgram.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartInitializer +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseFinishProgram + +namespace OAI + +/-! # Initialization and all stored-multiplier restart stages + +Past entries are stored in chronological order. Entry i contains the +multiplier for restart phase i+1. Initialization and restart stages take +disjoint slices of the supplied word. +-/ +namespace ContingencyTables.CompanionInitializedRestartProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial + +abbrev Prepared := CompanionPhaseContextProgram.Prepared +abbrev Stored := CompanionPhaseFinishProgram.Stored +abbrev Input := (Prepared×List Stored)×List Bool + +def reserve (z : Input) : List Bool := z.2.map (fun _ => false) +def reserveRealizer : Realizer reserve := composition second (map (constant false)) +lemma polynomial_reserve : PolynomialTime reserveRealizer := + polynomial_composition polynomial_second (polynomial_map (polynomial_constant false)) + +def indices (z : Input) : List ℕ := List.range z.1.2.length +def indicesRealizer : Realizer indices := + composition (composition (composition first second) listLength) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.2).trans ((weight_snd z.1).trans (weight_fst z)) + +def stageAt (z : Input×ℕ) : CompanionRestartProgram.Stage := + (((z.1.1.1,z.2+1),reserve z.1),(z.1.1.2.getD z.2 default).1) +def stageAtRealizer : Realizer stageAt := by + let prepared : Realizer (fun z : Input×ℕ => z.1.1.1) := composition (composition first first) first + let phase : Realizer (fun z : Input×ℕ => z.2+1) := composition second successor + let marker : Realizer (fun z : Input×ℕ => reserve z.1) := + composition (f := fun z : Input×ℕ => z.1) (g := reserve) first reserveRealizer + let stored : Realizer (fun z : Input×ℕ => z.1.1.2.getD z.2 (default : Stored)) := + composition (f := fun z : Input×ℕ => (z.1.1.2,z.2)) + (g := fun p : List Stored×ℕ => p.1.getD p.2 default) + (pair (composition (composition first first) second) second) (getDFast default) + exact pair (pair (pair prepared phase) marker) (composition (f := fun z : Input×ℕ => + z.1.1.2.getD z.2 (default : Stored)) (g := Prod.fst) stored first) +lemma polynomial_stageAt : PolynomialTime stageAtRealizer := by + unfold stageAtRealizer + apply polynomial_pair + · exact polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + (polynomial_composition polynomial_second polynomial_successor)) + (polynomial_composition polynomial_first polynomial_reserve) + · exact polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_second) (polynomial_getDFast default)) polynomial_first + +def stages (z : Input) : List CompanionRestartProgram.Stage := + (indices z).map (fun i => stageAt (z,i)) +def stagesRealizer : Realizer stages := composition (pair identity indicesRealizer) (mapWith stageAtRealizer) +lemma polynomial_stages : PolynomialTime stagesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_stageAt) + +def initialWidth (z : Input) : ℕ := CompanionRestartInitializer.width z.1.1 +def initialWidthRealizer : Realizer initialWidth := + composition (f := fun z : Input => z.1.1) (g := CompanionRestartInitializer.width) + (composition first first) CompanionRestartInitializer.widthRealizer +lemma polynomial_initialWidth : PolynomialTime initialWidthRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) + CompanionRestartInitializer.polynomial_width + +def initialInput (z : Input) : CompanionRestartInitializer.Input := + (z.1.1,z.2.take (initialWidth z)) +def initialInputRealizer : Realizer initialInput := + pair (composition first first) + (composition (f := fun z : Input => (z.2,initialWidth z)) + (g := fun p : List Bool×ℕ => p.1.take p.2) (pair second initialWidthRealizer) takeFast) +lemma polynomial_initialInput : PolynomialTime initialInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_pair polynomial_second polynomial_initialWidth) polynomial_takeFast) + +def initialCode (z : Input) : List ℕ := CompanionRestartInitializer.output (initialInput z) +def initialCodeRealizer : Realizer initialCode := + composition (f := initialInput) (g := CompanionRestartInitializer.output) + initialInputRealizer CompanionRestartInitializer.outputRealizer +lemma polynomial_initialCode : PolynomialTime initialCodeRealizer := + polynomial_composition polynomial_initialInput CompanionRestartInitializer.polynomial_output + +attribute [local irreducible] stages initialCode initialWidth + +def prepare (z : Input) : CompanionRestartProgram.Input := + ((stages z,initialCode z),z.2.drop (initialWidth z)) +def prepareRealizer : Realizer prepare := + pair (pair stagesRealizer initialCodeRealizer) + (composition (f := fun z : Input => (z.2,initialWidth z)) + (g := fun p : List Bool×ℕ => p.1.drop p.2) (pair second initialWidthRealizer) dropFast) +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair polynomial_stages polynomial_initialCode) + (polynomial_composition (polynomial_pair polynomial_second polynomial_initialWidth) polynomial_dropFast) + +def output (z : Input) : List ℕ := CompanionRestartProgram.output (prepare z) +def outputRealizer : Realizer output := + composition (f := prepare) (g := CompanionRestartProgram.output) + prepareRealizer CompanionRestartProgram.outputRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare CompanionRestartProgram.polynomial_output + +end ContingencyTables.CompanionInitializedRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5ee6aa97b02d543da07c71791c328b518ae5de2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionInitializedRestartSemantics.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartDataLaw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartScheduleSemantics + +namespace OAI + +/-! # Literal inputs and disjoint slices of initialized restarts -/ +namespace ContingencyTables.CompanionInitializedRestartProgram +open MatchingFPRAS CommonBasesFPRAS FairBits DensePrograms +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram +open CompanionOracleDensity GridBoundary +open scoped BigOperators Classical +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (estimates : Fin j → TreeFraction.Fraction) (bits : List Bool) : Input := + ((CompanionRestartInitializer.data A C K H T N R L epsilon z v, + List.ofFn (fun i : Fin j => (matrixCode (w (i.val+1)),estimates i))),bits) + +lemma stages_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (estimates : Fin j → TreeFraction.Fraction) (bits : List Bool) : + stages (data A C K H T N R L j epsilon z v w estimates bits)= + CompanionRestartProgram.stagesData A C K j + ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon) z v (List.replicate bits.length false) w := by + unfold stages indices data + rw [List.length_ofFn,DirectedBFSCode.range_eq_map] + simp only [List.map_map,Function.comp_def] + rw [←List.ofFn_eq_map] + apply congrArg List.ofFn + funext i + unfold stageAt reserve + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some, + List.map_const'] + rfl + +lemma initialWidth_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (estimates : Fin j → TreeFraction.Fraction) (bits : List Bool) : + initialWidth (data A C K H T N R L j epsilon z v w estimates bits)= + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H)) := + CompanionRestartInitializer.width_data A C K H T N R L epsilon z v + + /-- Exact physical splitting: the initializer sees the first block, + the restart loop sees the remaining block, and all markers are fixed. -/ +theorem output_split (A : Instance (Fin m) (Fin n)) (C K H T N R L j s : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (estimates : Fin j → TreeFraction.Fraction) + (bits : Fin (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+s) → Bool) : + output (data A C K H T N R L j epsilon z v w estimates (List.ofFn bits))= + CompanionRestartProgram.output + ((CompanionRestartProgram.stagesData A C K j + ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon) z v + (List.replicate (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+s) false) w, + CompanionRestartInitializer.output + (CompanionRestartInitializer.data A C K H T N R L epsilon z v, + List.ofFn (splitWordEquiv + (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))) s bits).1)), + List.ofFn (splitWordEquiv + (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))) s bits).2) := by + unfold output prepare initialCode initialInput + rw [stages_data,initialWidth_data,List.length_ofFn] + dsimp only [data] + rw [ofFn_split_take,ofFn_split_drop] + +end +end ContingencyTables.CompanionInitializedRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionLabelMetadataProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionLabelMetadataProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..550cf3abe9c12e1ba6a83d9482c7e7105ab5bb62 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionLabelMetadataProgram.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PairedFactorialProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionComputedProposal +import OAI.Combinatorics.ContingencyTables.Transport.DirectedBFSCode + +namespace OAI + +/-! # Recovering each paired label's cell and capacity + +The multiplicities come from the actual bounded profile blocks. A +large numeric capacity never causes an allocation beyond the supplied +profile code. On a canonical code, the resulting order is exactly the +copy order used by the initializer and arithmetic proposals. +-/ + +namespace ContingencyTables.CompanionLabelMetadataProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial +open PairedProfileProgram PairedFactorialProgram + +abbrev Input := PairedProfileProgram.Input + +def indices (z : ℕ × List ℕ) : List ℕ := List.range (pairCount z.2) +def indicesRealizer : Realizer indices := + composition (composition second pairCountRealizer) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_second polynomial_pairCount) X + intro z + simpa only [Function.comp_apply,eval_X,pairCount] using + (Nat.div_le_self z.2.length 2).trans ((list_length_le_weight z.2).trans (weight_snd z)) + +def labelRow (z : ℕ × List ℕ) : List (ℕ × ℕ) := + (indices z).map (fun _ => (z.1,pairCount z.2)) +def labelRowRealizer : Realizer labelRow := + composition (pair identity indicesRealizer) + (mapWith (pair (composition first first) (composition (composition first second) pairCountRealizer))) +lemma polynomial_labelRow : PolynomialTime labelRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_pairCount))) + +def rowInput (z : Input × ℕ) : ℕ × List ℕ := + (z.2,(rows z.1).getD z.2 []) +def rowInputRealizer : Realizer rowInput := + pair second (composition (pair + (composition (f := fun z : Input × ℕ => z.1) (g := rows) first rowsRealizer) + second) (getDFast [])) +lemma polynomial_rowInput : PolynomialTime rowInputRealizer := + polynomial_pair polynomial_second (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_rows) polynomial_second) (polynomial_getDFast [])) + +def indexedRow (z : Input × ℕ) : List (ℕ × ℕ) := labelRow (rowInput z) +def indexedRowRealizer : Realizer indexedRow := + composition (f := rowInput) (g := labelRow) rowInputRealizer labelRowRealizer +lemma polynomial_indexedRow : PolynomialTime indexedRowRealizer := + polynomial_composition polynomial_rowInput polynomial_labelRow + +def output (z : Input) : List (ℕ × ℕ) := + ((NaturalBlockProgram.indices z).map (fun i => indexedRow (z,i))).flatten +def outputRealizer : Realizer output := + composition (composition (pair identity NaturalBlockProgram.indicesRealizer) + (mapWith indexedRowRealizer)) flatten +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_composition (polynomial_pair polynomial_identity + NaturalBlockProgram.polynomial_indices) (polynomial_mapWith polynomial_indexedRow)) polynomial_flatten + +lemma labelRow_eq (i : ℕ) (xs : List ℕ) : + labelRow (i,xs)=List.replicate (xs.length/2) (i,xs.length/2) := by + simp only [labelRow,indices,pairCount,List.map_const',List.length_range] + +noncomputable section +open CanonicalInitialEncoding InitialTransversals PairedProfileSemantics +open CompanionArithmeticProposal CompanionFactorialApplication +open scoped Classical +variable {q : ℕ} (b : Fin q → ℕ) + +lemma indexedRow_encode (S : Set (Copy b × Bool)) (i : Fin q) : + indexedRow ((List.ofFn b,encodeSet (coordinateEquiv b) S),i.val)= + List.replicate (b i) (i.val,b i) := by + unfold indexedRow rowInput + rw [rows_encode] + have he : (cellRows b S).getD i.val []=interleave (List.ofFn (fun k : Fin (b i) => + (if (⟨i,k⟩,false) ∈ S then 1 else 0,if (⟨i,k⟩,true) ∈ S then 1 else 0))) := by + simp [cellRows,List.getD_eq_getElem?_getD] + rw [he] + rw [labelRow_eq,interleave_length,List.length_ofFn] + simp only [Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + +lemma output_encode (S : Set (Copy b × Bool)) : + output (List.ofFn b,encodeSet (coordinateEquiv b) S)= + (copyOrder b).map (fun p => (p.1.val,b p.1)) := by + unfold output NaturalBlockProgram.indices + rw [List.length_ofFn] + have he : (List.range q).map (fun i => indexedRow ((List.ofFn b,encodeSet (coordinateEquiv b) S),i))= + List.ofFn (fun i : Fin q => List.replicate (b i) (i.val,b i)) := by + conv_rhs => rw [List.ofFn_eq_map] + rw [DirectedBFSCode.range_eq_map] + simp only [List.map_map,Function.comp_def] + change (List.finRange q).map (fun i => indexedRow ((List.ofFn b,encodeSet (coordinateEquiv b) S),i.val)) = + (List.finRange q).map (fun i => List.replicate (b i) (i.val,b i)) + apply List.map_congr_left + intro i _ + exact indexedRow_encode b S i + rw [he] + simp only [copyOrder,List.sigma,List.map_flatMap,List.map_map,List.ofFn_eq_map, + List.flatten_eq_flatMap,List.flatMap_map,Function.comp_def,id_eq] + apply List.flatMap_congr + intro i _ + simp only [List.map_const',List.length_finRange] + +end +end ContingencyTables.CompanionLabelMetadataProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..2681fced3d51a3ac6e6ae503dd17eff81b7d934f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisLaw.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEvaluatedWeightLaw +import OAI.Combinatorics.ContingencyTables.Transport.FiniteMetropolisTransport +import OAI.Combinatorics.ContingencyTables.Rooted.RootedBooleanPhase + +namespace OAI + +/-! # The actual computed proposal and two oracle calls have the phase law -/ + +namespace ContingencyTables.CompanionMetropolisProgram + +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionBooleanPhase (State) +open CompanionArithmeticProposal CompanionOrderedProposal CompanionOracleDensity CompanionWeightOracle +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram CommonBasesFPRAS +open FiniteObservableTransport TwoLiftStates GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +abbrev Fields (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) (xi : ℚ) := + (Fin 1 → Bool) × ((Fin (CompanionBooleanPhase.proposalBits A) → Bool) × + ((WeightWord A C K j xi × WeightWord A C K j xi) × (Fin k → Bool))) + +def programInput (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) (xi : ℚ) + (cfg : RootedLabelWeightProgram.Config) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : State A) (b : Fields A C K j k xi) : Input := + (((cfg,matrixCode w),encodeSet (coordinateOrder A) S.val), + (b.1 0,(List.ofFn b.2.1,((List.ofFn b.2.2.1.1,List.ofFn b.2.2.1.2),List.ofFn b.2.2.2)))) + +def codeAccept (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) (xi : ℚ) + (cfg : RootedLabelWeightProgram.Config) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S T : State A) + (b : (WeightWord A C K j xi × WeightWord A C K j xi) × (Fin k → Bool)) : Bool := + FractionMetropolisProgram.accept + ((CompanionEvaluatedWeightProgram.output (((cfg,matrixCode w),encodeSet (coordinateOrder A) S.val),List.ofFn b.1.1), + CompanionEvaluatedWeightProgram.output (((cfg,matrixCode w),encodeSet (coordinateOrder A) T.val),List.ofFn b.1.2)), + List.ofFn b.2) + +lemma output_programInput (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) (xi : ℚ) + (cfg : RootedLabelWeightProgram.Config) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : State A) (b : Fields A C K j k xi) : + output (programInput A C K j k xi cfg w S b)= + encodeSet (coordinateOrder A) + (if b.1 0 then S else proposedMove S (orderedProposal A (coordinateOrder A) S b.2.1) + (codeAccept A C K j k xi cfg w S) b.2.2).val := by + cases hb : b.1 0 with + | true => simp only [output,programInput,hb,ite_true] + | false => + cases hp : orderedProposal A (coordinateOrder A) S b.2.1 with + | none => + simp only [output,programInput,hb,Bool.false_eq_true,ite_false,accepted,acceptanceInput, + currentValue,targetValue,currentInput,targetInput,candidate,proposed, + CompanionComputedProposal.proposalProgram_eq,hp,Option.map_none,Option.getD_none,proposedMove] + split_ifs <;> simp_all + | some T => + simp only [output,programInput,hb,Bool.false_eq_true,ite_false,accepted,acceptanceInput, + currentValue,targetValue,currentInput,targetInput,candidate,proposed, + CompanionComputedProposal.proposalProgram_eq,hp,Option.map_some,Option.getD_some,proposedMove, + codeAccept] + split_ifs <;> simp_all + +/-- Every computed step has the complete reference phase-step law. The +proposal and both query outcomes are transported, including failures. -/ +theorem sameLaw_fields (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : State A) : + SameLaw (fun b : Fields A C K j k xi => output (programInput A C K j k xi + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth) w S b)) + (fun b : Fields A C K j k xi => encodeSet (coordinateOrder A) + (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) C K j k hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S + ((CompanionBooleanPhase.stepWordEquiv A C K j k xi).symm b)).val) := by + let cfg := RootedLabelWeightProgram.config A C K j xi xi z v degree depth + let refAccept := fun T : State A => fun b : + (WeightWord A C K j xi × WeightWord A C K j xi) × (Fin k → Bool) => + decide (FairBits.rationalThresholdAccept k + (RootedOracleAcceptance.acceptance A (RootedCompletion.rowColumn A.T) C K j hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S.val T.val b.1) b.2) + have hp : SameLaw (orderedProposal A (coordinateOrder A) S) (CompanionBooleanPhase.proposal A S) := + SameLaw.of_mapLaw_eq _ _ (orderedProposal_law A (coordinateOrder A) S) + have ha (T : State A) : SameLaw (codeAccept A C K j k xi cfg w S T) (refAccept T) := + acceptance_sameLaw A C K j k hC hj hK hW hB xi hxi z v degree depth hdegree hdepth w S.val T.val + have hm := proposedMove_sameLaw S _ _ _ _ hp ha + have hh := (holding_sameLaw S _ _ hm).map (fun T : State A => encodeSet (coordinateOrder A) T.val) + intro phi + have hleft : (fun b : Fields A C K j k xi => phi (output (programInput A C K j k xi cfg w S b)))= + (fun b : Fields A C K j k xi => phi (encodeSet (coordinateOrder A) + (if b.1 0 then S else proposedMove S (orderedProposal A (coordinateOrder A) S b.2.1) + (codeAccept A C K j k xi cfg w S) b.2.2).val)) := by + funext b + rw [output_programInput] + rw [hleft] + have he := hh phi + refine he.trans ?_ + apply congrArg uniformAverage + funext b + apply congrArg phi + unfold RootedBooleanPhase.step + dsimp only + simp only [Equiv.apply_symm_apply] + cases hb : b.1 0 <;> cases hp : CompanionBooleanPhase.proposal A S b.2.1 + all_goals simp only [proposedMove,Bool.false_eq_true,ite_false,ite_true,refAccept, + decide_eq_true_eq] + +end +end ContingencyTables.CompanionMetropolisProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..24e06d6b8b5f88fee3f7798f2220055a19899235 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisProgram.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEvaluatedWeightProgram +import OAI.Combinatorics.ContingencyTables.Machines.FractionMetropolisProgram + +namespace OAI + +/-! # One physical companion-chain step with independent word fields + +The proposed state is computed by the quadratic arithmetic candidate +list. Two disjoint words evaluate the current and candidate states, and +a third field supplies the rational acceptance coin. +-/ + +namespace ContingencyTables.CompanionMetropolisProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev Frame := CompanionEvaluatedWeightProgram.Frame +abbrev Words := Bool × (List Bool × ((List Bool × List Bool) × List Bool)) +abbrev Input := (Frame × List ℕ) × Words + +def proposed (z : Input) : Option (List ℕ) := + CompanionComputedProposal.proposalProgram (z.1.2,z.2.2.1) +def proposedRealizer : Realizer proposed := + composition (f := fun z : Input => (z.1.2,z.2.2.1)) + (g := CompanionComputedProposal.proposalProgram) + (pair (composition first second) (composition (composition second second) first)) + CompanionComputedProposal.proposalProgramRealizer +lemma polynomial_proposed : PolynomialTime proposedRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) polynomial_first)) + CompanionComputedProposal.polynomial_proposalProgram + +private def defaultCode (z : List ℕ × Option (List ℕ)) : List ℕ := z.2.getD z.1 +private def defaultCodeRealizer : Realizer defaultCode := + (optionCases identity second).recode id defaultCode (fun _ => rfl) + (by rintro ⟨d,o⟩; cases o <;> rfl) +private lemma polynomial_defaultCode : PolynomialTime defaultCodeRealizer := by + unfold defaultCodeRealizer + apply polynomial_recode + exact polynomial_optionCases polynomial_identity polynomial_second + +def candidate (z : Input) : List ℕ := (proposed z).getD z.1.2 +def candidateRealizer : Realizer candidate := + composition (f := fun z : Input => (z.1.2,proposed z)) + (g := defaultCode) (pair (composition first second) proposedRealizer) defaultCodeRealizer +lemma polynomial_candidate : PolynomialTime candidateRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_proposed) polynomial_defaultCode + +attribute [local irreducible] candidate + +def currentInput (z : Input) : CompanionEvaluatedWeightProgram.Input := (z.1,z.2.2.2.1.1) +def currentInputRealizer : Realizer currentInput := + pair first (composition (composition (composition (composition second second) second) first) first) +lemma polynomial_currentInput : PolynomialTime currentInputRealizer := + polynomial_pair polynomial_first (polynomial_composition + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_second polynomial_second) polynomial_second) polynomial_first) polynomial_first) + +def targetInput (z : Input) : CompanionEvaluatedWeightProgram.Input := + ((z.1.1,candidate z),z.2.2.2.1.2) +def targetInputRealizer : Realizer targetInput := + pair (pair (composition first first) candidateRealizer) + (composition (composition (composition (composition second second) second) first) second) +lemma polynomial_targetInput : PolynomialTime targetInputRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_candidate) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_second polynomial_second) polynomial_second) polynomial_first) polynomial_second) + +attribute [local irreducible] currentInput targetInput CompanionEvaluatedWeightProgram.output + +def currentValue (z : Input) : TreeFraction.Fraction := CompanionEvaluatedWeightProgram.output (currentInput z) +def currentValueRealizer : Realizer currentValue := + composition (f := currentInput) (g := CompanionEvaluatedWeightProgram.output) + currentInputRealizer CompanionEvaluatedWeightProgram.outputRealizer +lemma polynomial_currentValue : PolynomialTime currentValueRealizer := + polynomial_composition polynomial_currentInput CompanionEvaluatedWeightProgram.polynomial_output + +def targetValue (z : Input) : TreeFraction.Fraction := CompanionEvaluatedWeightProgram.output (targetInput z) +def targetValueRealizer : Realizer targetValue := + composition (f := targetInput) (g := CompanionEvaluatedWeightProgram.output) + targetInputRealizer CompanionEvaluatedWeightProgram.outputRealizer +lemma polynomial_targetValue : PolynomialTime targetValueRealizer := + polynomial_composition polynomial_targetInput CompanionEvaluatedWeightProgram.polynomial_output + +attribute [local irreducible] currentValue targetValue + +def acceptanceInput (z : Input) : FractionMetropolisProgram.Input := + ((currentValue z,targetValue z),z.2.2.2.2) +def acceptanceInputRealizer : Realizer acceptanceInput := + pair (pair currentValueRealizer targetValueRealizer) + (composition (composition (composition second second) second) second) +lemma polynomial_acceptanceInput : PolynomialTime acceptanceInputRealizer := + polynomial_pair (polynomial_pair polynomial_currentValue polynomial_targetValue) + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_second polynomial_second) polynomial_second) polynomial_second) + +def accepted (z : Input) : Bool := FractionMetropolisProgram.accept (acceptanceInput z) +def acceptedRealizer : Realizer accepted := + composition (f := acceptanceInput) (g := FractionMetropolisProgram.accept) + acceptanceInputRealizer FractionMetropolisProgram.acceptRealizer +lemma polynomial_accepted : PolynomialTime acceptedRealizer := + polynomial_composition polynomial_acceptanceInput FractionMetropolisProgram.polynomial_accept + +attribute [local irreducible] accepted + +def output (z : Input) : List ℕ := if z.2.1 then z.1.2 else if accepted z then candidate z else z.1.2 +def outputRealizer : Realizer output := + choose (composition second first) (composition first second) + (choose acceptedRealizer candidateRealizer (composition first second)) +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_choose (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition polynomial_first polynomial_second) + (polynomial_choose polynomial_accepted polynomial_candidate + (polynomial_composition polynomial_first polynomial_second)) + +lemma output_hold (z : Input) (h : z.2.1=true) : output z=z.1.2 := by + simp only [output,h,ite_true] + +end ContingencyTables.CompanionMetropolisProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisWordProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisWordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce207d7d594e734c1b00d05e8c2914f17a96180b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisWordProgram.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram + +namespace OAI + +/-! # Bounded slicing of one flat companion transition word -/ + +namespace ContingencyTables.CompanionMetropolisWordProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +/-- The fixed frame, the acceptance precision, current code, and fresh word. -/ +abbrev Input := ((CompanionMetropolisProgram.Frame × ℕ) × List ℕ) × List Bool + +def proposalWidth (z : Input) : ℕ := Nat.clog 2 ((z.1.2.length/2)^2) +def proposalWidthRealizer : Realizer proposalWidth := by + let p : Realizer (fun z : Input => z.1.2.length/2) := + composition (f := fun z : Input => (z.1.2.length,2)) + (g := fun ab : ℕ × ℕ => ab.1/ab.2) + (pair (composition (composition first second) listLength) (constant 2)) quotient + exact composition (f := fun z : Input => (z.1.2.length/2)^2) (g := Nat.clog 2) + ((composition (pair p p) multiply).congr (fun z => (pow_two _).symm)) ceilLogTwoRealizer +lemma polynomial_proposalWidth : PolynomialTime proposalWidthRealizer := by + unfold proposalWidthRealizer + apply polynomial_composition _ polynomial_ceilLogTwo + apply polynomial_congr + apply polynomial_composition _ polynomial_multiply + apply polynomial_pair + all_goals exact (polynomial_composition + (polynomial_pair (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_listLength) (polynomial_constant 2)) polynomial_quotient) + +def context (z : Input) : RootedEstimatorLayoutProgram.Context := z.1.1.1.1.1.1 +def contextRealizer : Realizer context := + composition (composition (composition (composition (composition first first) first) first) first) first +lemma polynomial_context : PolynomialTime contextRealizer := by + unfold contextRealizer + exact polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_first) polynomial_first) polynomial_first + +def queryWidth (z : Input) : ℕ := z.1.1.1.1.1.2*RootedEstimatorLayoutProgram.wordWidth (context z) +def queryWidthRealizer : Realizer queryWidth := + composition (f := fun z : Input => + (z.1.1.1.1.1.2,RootedEstimatorLayoutProgram.wordWidth (context z))) + (g := fun ab : ℕ × ℕ => ab.1*ab.2) + (pair (composition (composition (composition (composition (composition first first) first) first) first) second) + (composition (f := context) (g := RootedEstimatorLayoutProgram.wordWidth) + contextRealizer RootedEstimatorLayoutProgram.wordWidthRealizer)) multiply +lemma polynomial_queryWidth : PolynomialTime queryWidthRealizer := + polynomial_composition (polynomial_pair (by tree_poly) + (polynomial_composition polynomial_context RootedEstimatorLayoutProgram.polynomial_wordWidth)) polynomial_multiply + +attribute [local irreducible] context queryWidth proposalWidth + +/-- Offsets are computed in binary; the physical `take`/`drop` calls remain +bounded by the supplied word on every malformed input. -/ +def firstOffset (z : Input) : ℕ := 1+proposalWidth z +def firstOffsetRealizer : Realizer firstOffset := + composition (f := fun z : Input => (1,proposalWidth z)) (g := fun p : ℕ × ℕ => p.1+p.2) + (pair (constant 1) proposalWidthRealizer) TreeTyped.add +lemma polynomial_firstOffset : PolynomialTime firstOffsetRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 1) polynomial_proposalWidth) polynomial_add + +def secondOffset (z : Input) : ℕ := firstOffset z+queryWidth z +attribute [local irreducible] firstOffset + +def secondOffsetRealizer : Realizer secondOffset := + composition (f := fun z : Input => (firstOffset z,queryWidth z)) (g := fun p : ℕ × ℕ => p.1+p.2) + (pair firstOffsetRealizer queryWidthRealizer) TreeTyped.add +lemma polynomial_secondOffset : PolynomialTime secondOffsetRealizer := + polynomial_composition (polynomial_pair polynomial_firstOffset polynomial_queryWidth) polynomial_add + +def coinOffset (z : Input) : ℕ := secondOffset z+queryWidth z +attribute [local irreducible] secondOffset + +def coinOffsetRealizer : Realizer coinOffset := + composition (f := fun z : Input => (secondOffset z,queryWidth z)) (g := fun p : ℕ × ℕ => p.1+p.2) + (pair secondOffsetRealizer queryWidthRealizer) TreeTyped.add +lemma polynomial_coinOffset : PolynomialTime coinOffsetRealizer := + polynomial_composition (polynomial_pair polynomial_secondOffset polynomial_queryWidth) polynomial_add + +private def slice (start count : Input → ℕ) (z : Input) : List Bool := + (z.2.drop (start z)).take (count z) +private def sliceRealizer {start count : Input → ℕ} + (S : Realizer start) (C : Realizer count) : Realizer (slice start count) := + composition (pair (composition (pair second S) dropFast) C) takeFast +private lemma polynomial_slice {start count : Input → ℕ} + (S : Realizer start) (C : Realizer count) (hS : PolynomialTime S) (hC : PolynomialTime C) : + PolynomialTime (sliceRealizer S C) := + polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_pair polynomial_second hS) polynomial_dropFast) hC) polynomial_takeFast + +def fields (z : Input) : CompanionMetropolisProgram.Words := + (z.2.getD 0 false, + (slice (fun _ => 1) proposalWidth z, + ((slice firstOffset queryWidth z,slice secondOffset queryWidth z), + slice coinOffset (fun z => z.1.1.2) z))) +def fieldsRealizer : Realizer fields := + pair (composition (pair second (constant 0)) (getDFast false)) + (pair (sliceRealizer (constant 1) proposalWidthRealizer) + (pair (pair (sliceRealizer firstOffsetRealizer queryWidthRealizer) + (sliceRealizer secondOffsetRealizer queryWidthRealizer)) + (sliceRealizer coinOffsetRealizer (composition (composition first first) second)))) +lemma polynomial_fields : PolynomialTime fieldsRealizer := + polynomial_pair (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant 0)) + (polynomial_getDFast false)) + (polynomial_pair (polynomial_slice _ _ (polynomial_constant 1) polynomial_proposalWidth) + (polynomial_pair (polynomial_pair + (polynomial_slice _ _ polynomial_firstOffset polynomial_queryWidth) + (polynomial_slice _ _ polynomial_secondOffset polynomial_queryWidth)) + (polynomial_slice _ _ polynomial_coinOffset (by tree_poly)))) + +def stepInput (z : Input) : CompanionMetropolisProgram.Input := ((z.1.1.1,z.1.2),fields z) +def stepInputRealizer : Realizer stepInput := + pair (pair (composition (composition first first) first) (composition first second)) fieldsRealizer +lemma polynomial_stepInput : PolynomialTime stepInputRealizer := + polynomial_pair (polynomial_pair (by tree_poly) (polynomial_composition polynomial_first polynomial_second)) + polynomial_fields + +attribute [local irreducible] stepInput + +def output (z : Input) : List ℕ := CompanionMetropolisProgram.output (stepInput z) +def outputRealizer : Realizer output := + composition (f := stepInput) (g := CompanionMetropolisProgram.output) + stepInputRealizer CompanionMetropolisProgram.outputRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_stepInput CompanionMetropolisProgram.polynomial_output + +end ContingencyTables.CompanionMetropolisWordProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisWordSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisWordSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..64643f43e366238f12c123e783ac678f9059f4d9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMetropolisWordSemantics.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisWordProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisLaw +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordSlices + +namespace OAI + +/-! # The flat physical transition has the proved phase-step law -/ + +namespace ContingencyTables.CompanionMetropolisWordProgram + +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionOracleDensity CompanionWeightOracle +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram CommonBasesFPRAS +open CompanionBooleanPhase (State) +open FiniteObservableTransport TwoLiftStates GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def packed (frame : CompanionMetropolisProgram.Frame) (k : ℕ) (code : List ℕ) (bits : List Bool) : Input := + (((frame,k),code),bits) + +lemma fields_ofFn (frame : CompanionMetropolisProgram.Frame) (k p q : ℕ) (code : List ℕ) + (bits : Fin (1+(p+((q+q)+k))) → Bool) + (hp : proposalWidth (packed frame k code (List.ofFn bits))=p) + (hq : queryWidth (packed frame k code (List.ofFn bits))=q) : + fields (packed frame k code (List.ofFn bits))= + ((FiniteWordSlices.split p q k bits).1 0, + (List.ofFn (FiniteWordSlices.split p q k bits).2.1, + ((List.ofFn (FiniteWordSlices.split p q k bits).2.2.1.1, + List.ofFn (FiniteWordSlices.split p q k bits).2.2.1.2), + List.ofFn (FiniteWordSlices.split p q k bits).2.2.2))) := by + let inp := packed frame k code (List.ofFn bits) + change ((List.ofFn bits).getD 0 false, + (((List.ofFn bits).drop 1).take (proposalWidth inp), + ((((List.ofFn bits).drop (1+proposalWidth inp)).take (queryWidth inp), + ((List.ofFn bits).drop (1+proposalWidth inp+queryWidth inp)).take (queryWidth inp)), + ((List.ofFn bits).drop (1+proposalWidth inp+queryWidth inp+queryWidth inp)).take k)))=_ + change proposalWidth inp=p at hp + change queryWidth inp=q at hq + rw [hp,hq,FiniteWordSlices.holding_bit,FiniteWordSlices.first_slice, + FiniteWordSlices.current_slice,FiniteWordSlices.target_slice,FiniteWordSlices.coin_slice] + +lemma proposalWidth_code (A : Instance (Fin m) (Fin n)) + (frame : CompanionMetropolisProgram.Frame) (k : ℕ) (S : Set (Labels A × Bool)) (bits : List Bool) : + proposalWidth (packed frame k (encodeSet (coordinateOrder A) S) bits)= + CompanionBooleanPhase.proposalBits A := by + have hc := Fintype.card_congr (coordinateOrder A) + simp only [Fintype.card_prod,Fintype.card_bool,Fintype.card_fin] at hc + have hd : (CanonicalInitialEncoding.pairOrder (capacities A)).length/2=Fintype.card (Labels A) := by omega + simp only [proposalWidth,packed,encodeSet,List.length_ofFn,hd,CompanionBooleanPhase.proposalBits] + +lemma queryWidth_config (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : FractionMatrix) (code : List ℕ) (bits : List Bool) : + queryWidth (packed (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,w) k code bits)= + medianEstimatorBits A C K j xi xi := by + exact CompanionEvaluatedWeightProgram.queryWidth A C K j xi z v + +lemma output_ofFn (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : State A) (bits : Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool) : + output (packed (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w) + k (encodeSet (coordinateOrder A) S.val) (List.ofFn bits))= + CompanionMetropolisProgram.output (CompanionMetropolisProgram.programInput A C K j k xi + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth) w S + (CompanionBooleanPhase.stepWordEquiv A C K j k xi bits)) := by + have hf := fields_ofFn + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w) k + (CompanionBooleanPhase.proposalBits A) (medianEstimatorBits A C K j xi xi) + (encodeSet (coordinateOrder A) S.val) bits + (proposalWidth_code A _ k S.val _) (queryWidth_config A C K j k xi z v degree depth _ _ _) + have hi : stepInput (packed + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w) + k (encodeSet (coordinateOrder A) S.val) (List.ofFn bits))= + CompanionMetropolisProgram.programInput A C K j k xi + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth) w S + (CompanionBooleanPhase.stepWordEquiv A C K j k xi bits) := by + exact congrArg (fun fs => + (((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w), + encodeSet (coordinateOrder A) S.val),fs)) hf + exact congrArg CompanionMetropolisProgram.output hi + +/-- The actual polynomial flat-step implementation has exactly the +reference kernel used by the trajectory and return estimates. -/ +theorem sameLaw_flat (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : State A) : + SameLaw (fun bits : Fin (CompanionBooleanPhase.stepBits A C K j k xi) → Bool => + output (packed (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w) + k (encodeSet (coordinateOrder A) S.val) (List.ofFn bits))) + (fun bits => encodeSet (coordinateOrder A) + (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) C K j k hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S bits).val) := by + let f := fun b : CompanionMetropolisProgram.Fields A C K j k xi => + CompanionMetropolisProgram.output (CompanionMetropolisProgram.programInput A C K j k xi + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth) w S b) + let g := fun b : CompanionMetropolisProgram.Fields A C K j k xi => + encodeSet (coordinateOrder A) + (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) C K j k hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S + ((CompanionBooleanPhase.stepWordEquiv A C K j k xi).symm b)).val + have hfg : SameLaw f g := CompanionMetropolisProgram.sameLaw_fields A C K j k hC hj hK hW hB + xi hxi z v degree depth hdegree hdepth w S + intro phi + simp_rw [output_ofFn] + have hf := uniformAverage_equiv (CompanionBooleanPhase.stepWordEquiv A C K j k xi) + (fun b => phi (f b)) + have hg := uniformAverage_equiv (CompanionBooleanPhase.stepWordEquiv A C K j k xi) + (fun b => phi (g b)) + refine hf.trans ((hfg phi).trans ?_) + simpa only [g,Equiv.symm_apply_apply] using hg.symm + +end +end ContingencyTables.CompanionMetropolisWordProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMinMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMinMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..00a6684c751548bd3ea04115975e8542a51063bd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMinMass.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionWarmStart + +namespace OAI + +/-! # Binary-size minimum mass of the actual companion transversal law + +The factorial denominator cancels against the two complementary +factorials. The surviving binomial coefficient is bounded by 2^b, +giving the p+K exponent used in the paper's restart schedule. +-/ + +namespace ContingencyTables.InitialTransversals + +open scoped BigOperators Classical +open Nat InitialLocalChoices CommonBasesFPRAS LabelledFactorial TwoLiftStates + +lemma localWeight_lower (b : ℕ) (S : Finset (Fin b)) : + (1/2:ℝ)^b ≤ localWeight b 0 0 S := by + have hk : S.card ≤ b := by + simpa using S.card_le_univ + have hD : (0:ℝ) < b.factorial := by exact_mod_cast Nat.factorial_pos b + have hF : (b.choose S.card:ℝ)*(S.card.factorial:ℝ)*((b-S.card).factorial:ℝ)= + (b.factorial:ℝ) := by exact_mod_cast Nat.choose_mul_factorial_mul_factorial hk + have hprod : (b.choose S.card:ℝ)*localWeight b 0 0 S=1 := by + unfold localWeight + simp only [Nat.sub_zero,Nat.add_zero] + rw [← mul_div_assoc,← mul_assoc,hF,div_self hD.ne'] + have hlocal : 0 ≤ localWeight b 0 0 S := by + unfold localWeight + positivity + have hchoose : (b.choose S.card:ℝ) ≤ (2:ℝ)^b := by + exact_mod_cast Nat.choose_le_two_pow b S.card + have hm := mul_le_mul_of_nonneg_right hchoose hlocal + have hpow : (0:ℝ) < (2:ℝ)^b := by positivity + rw [hprod] at hm + rw [div_pow,one_pow,div_le_iff₀ hpow] + nlinarith + +variable {C : Type*} [Fintype C] + +/-- On every actual paired transversal, the constant-count factorial +display is at least M times 2 to the negative number of copy labels. -/ +theorem firstLift_plain_lower (b : C → ℕ) (M : ℝ) (hM : 0 ≤ M) + (S : Set (Copy b×Bool)) (hS : PlainState pairs S) : + M*(1/2:ℝ)^(∑ c,b c) ≤ + firstLift (group (cell b)) (fun _ => M) (denominator b) S := by + let T := plainEquivChoices b ⟨S,hS⟩ + have he : encode b T=S := congrArg Subtype.val ((plainEquivChoices b).symm_apply_apply ⟨S,hS⟩) + rw [← he,firstLift_encode] + apply mul_le_mul_of_nonneg_left _ hM + rw [← Finset.prod_pow_eq_pow_sum] + apply Finset.prod_le_prod₀ + · intro c _ + positivity + · intro c _ + exact localWeight_lower (b c) (T c) + +end ContingencyTables.InitialTransversals + +namespace ContingencyTables.CompanionMinMass + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication CompanionAnnealing CompanionInitialization +open CompanionWarmStart TwoLiftStates LabelledFactorial + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma label_card (A : Instance I J) : + Fintype.card (Labels A)=∑ s : SmallCell A,A.b s.val.1 s.val.2 := by + simp [Labels,Fintype.card_sigma] + +lemma initial_weight_lower (A : Instance I J) (S : Set (Labels A×Bool)) + (hS : PlainState pairs S) : + freeTotal A*(1/2:ℝ)^Fintype.card (Labels A) ≤ weight A 0 S := by + have hM : (0:ℝ) ≤ freeTotal A := + (Finset.prod_pos (fun _ _ => Nat.cast_pos.mpr (Nat.succ_pos _))).le + have hh := InitialTransversals.firstLift_plain_lower + (fun s : SmallCell A => A.b s.val.1 s.val.2) (freeTotal A) hM S hS + rw [← label_card] at hh + unfold weight f firstLift + simp only [Nat.cast_zero,zero_div] + rw [denominator_eq] + rw [h_zero] + convert hh using 1 + congr 1 + +/-- If the finite small-profile domain has at most 2^K points, every +actual phase-j transversal has mass at least 2^(-(j+p+K)). -/ +theorem law_lower (A : Instance I J) (K j : ℕ) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^K) + (S : Set (Labels A×Bool)) (hS : PlainState pairs S) : + (1/2:ℝ)^(j+Fintype.card (Labels A)+K) ≤ law A j S := by + have hM : (0:ℝ) < freeTotal A := + Finset.prod_pos (fun _ _ => Nat.cast_pos.mpr (Nat.succ_pos _)) + have hT := (total_bounds_zero A j).2 + have hT0 : total A 0=freeTotal A*∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1) := by + unfold total weight + simpa only [Nat.cast_zero,zero_div] using total_zero A + rw [hT0] at hT + have hupper : total A j ≤ freeTotal A*(2:ℝ)^K := + hT.trans (mul_le_mul_of_nonneg_left hB hM.le) + have hw := (weight_bounds_zero A j S).1 + have hi := initial_weight_lower A S hS + have hlower : freeTotal A*(1/2:ℝ)^(j+Fintype.card (Labels A)) ≤ weight A j S := by + rw [pow_add] + nlinarith [mul_le_mul_of_nonneg_left hi (show (0:ℝ) ≤ (1/2:ℝ)^j by positivity)] + have hpos := total_positive A j + unfold law + rw [le_div_iff₀ hpos,pow_add] + have hm := mul_le_mul_of_nonneg_left hupper + (show (0:ℝ) ≤ (1/2:ℝ)^(j+Fintype.card (Labels A))*(1/2:ℝ)^K by positivity) + have hcancel : (1/2:ℝ)^K*(2:ℝ)^K=1 := by + rw [← mul_pow] + norm_num + have he : ((1/2:ℝ)^(j+Fintype.card (Labels A))*(1/2:ℝ)^K)* + (freeTotal A*(2:ℝ)^K)=freeTotal A*(1/2:ℝ)^(j+Fintype.card (Labels A)) := by + calc + _ = freeTotal A*(1/2:ℝ)^(j+Fintype.card (Labels A))* + ((1/2:ℝ)^K*(2:ℝ)^K) := by ring + _ = _ := by rw [hcancel,mul_one] + rw [he] at hm + exact hm.trans hlower + +end ContingencyTables.CompanionMinMass + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierAgreement.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierAgreement.lean new file mode 100644 index 0000000000000000000000000000000000000000..1466955b56eb8421fe6dc29c8cb8bbec54482b7e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierAgreement.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnWords + +namespace OAI + +/-! # Only canonical pair entries affect the executed chain + +The finite matrix stores one entry per pair of labels. Values of the +mathematical multiplier on arbitrary noncanonical coordinate pairs +do not affect any weight call, acceptance decision, or capped return. +-/ + +namespace ContingencyTables.CompanionMultiplierAgreement + +open CommonBasesFPRAS CompanionFactorialApplication CompanionRationalUpdates +open CompanionOracleDensity CompanionWeightOracle TwoLiftStates GridBoundary +open CompanionBooleanPhase (State stepBits) +open scoped Classical + +noncomputable section + +lemma rationalMultiplier_congr {Γ : Type*} [Fintype Γ] [DecidableEq Γ] + (gs : List (Γ × Γ)) (w w' : (Γ × Γ) → (Γ × Γ) → ℚ) + (hw : ∀ p ∈ gs, ∀ q ∈ gs, w p q=w' p q) (S : Set Γ) : + rationalMultiplier gs w S=rationalMultiplier gs w' S := by + unfold rationalMultiplier + split_ifs with h + · exact hw _ h.choose_spec.choose_spec.1 _ h.choose_spec.choose_spec.2.1 + · rfl + +variable {I J : Type} [Fintype I] [Fintype J] + +def Agree (A : Instance I J) (w w' : Pair A → Pair A → ℚ) : Prop := + ∀ a b : Labels A, w (pair a) (pair b)=w' (pair a) (pair b) + +lemma agree_on_pairs (A : Instance I J) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + ∀ p ∈ (pairs : List (Pair A)), ∀ q ∈ (pairs : List (Pair A)), w p q=w' p q := by + intro p hp q hq + obtain ⟨a,_,rfl⟩ := List.mem_map.mp hp + obtain ⟨b,_,rfl⟩ := List.mem_map.mp hq + exact hw a b + +lemma multiplier_eq (A : Instance I J) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') (S : Set (Labels A × Bool)) : + rationalMultiplier pairs w S=rationalMultiplier pairs w' S := + rationalMultiplier_congr pairs w w' (agree_on_pairs A w w' hw) S + +lemma evaluatedWeight_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') (S : Set (Labels A × Bool)) (bits : WeightWord A C K j xi) : + RootedOracleAcceptance.evaluatedWeight A R C K j hK hW xi v w S bits= + RootedOracleAcceptance.evaluatedWeight A R C K j hK hW xi v w' S bits := by + unfold RootedOracleAcceptance.evaluatedWeight + rw [multiplier_eq A w w' hw] + +lemma acceptance_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + RootedOracleAcceptance.acceptance A R C K j hK hW xi v w= + RootedOracleAcceptance.acceptance A R C K j hK hW xi v w' := by + funext S T bits + unfold RootedOracleAcceptance.acceptance + rw [evaluatedWeight_eq A R C K j hK hW xi v w w' hw, + evaluatedWeight_eq A R C K j hK hW xi v w w' hw] + +lemma step_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j k : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + RootedBooleanPhase.step A R C K j k hK hW xi v w= + RootedBooleanPhase.step A R C K j k hK hW xi v w' := by + funext S bits + unfold RootedBooleanPhase.step + rw [acceptance_eq A R C K j hK hW xi v w w' hw] + +lemma arithmeticFinish_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j k : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + RootedArithmeticStep.finish A R C K j k hK hW xi v w= + RootedArithmeticStep.finish A R C K j k hK hW xi v w' := by + funext S U bits + unfold RootedArithmeticStep.finish + rw [acceptance_eq A R C K j hK hW xi v w w' hw] + +lemma arithmeticStep_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j k : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + RootedArithmeticStep.step A R C K j k hK hW xi v w= + RootedArithmeticStep.step A R C K j k hK hW xi v w' := by + funext S bits + unfold RootedArithmeticStep.step + rw [arithmeticFinish_eq A R C K j k hK hW xi v w w' hw] + +lemma recordedWalk_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j k N n : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + RootedArithmeticStep.recordedWalk A R C K j k N n hK hW xi v w= + RootedArithmeticStep.recordedWalk A R C K j k N n hK hW xi v w' := by + funext S bits + unfold RootedArithmeticStep.recordedWalk + rw [arithmeticStep_eq A R C K j k hK hW xi v w w' hw] + +lemma return_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j k n : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + RootedCappedReturn.returnWordDefault A R C K j k n hK hW xi v w= + RootedCappedReturn.returnWordDefault A R C K j k n hK hW xi v w' := by + funext S bits + unfold RootedCappedReturn.returnWordDefault RootedTraceWords.returnWord + rw [recordedWalk_eq A R C K j k (n+1) (n+1) hK hW xi v w w' hw] + +lemma returns_eq (A : Instance I J) (R : RootedCompletion.Selection A.T) + (C K j k n t : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w w' : Pair A → Pair A → ℚ) + (hw : Agree A w w') : + RootedReturnWords.booleanReturns A R C K j k n t hK hW xi v w= + RootedReturnWords.booleanReturns A R C K j k n t hK hW xi v w' := by + funext S bits + unfold RootedReturnWords.booleanReturns + rw [return_eq A R C K j k n hK hW xi v w w' hw] + +end +end ContingencyTables.CompanionMultiplierAgreement + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..cd897d9630f0d1de382a19ab7102b4b286d2f811 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierMatrixProgram.lean @@ -0,0 +1,260 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierProgram + +namespace OAI + +/-! # The full multiplier update and abort test as list programs + +Only the polynomial list of labelled pairs is traversed. Every matrix +entry is updated from the actual plain and defect counts of the stored +trajectory. The count check includes every off-diagonal labelled type. +-/ + +namespace ContingencyTables.CompanionMultiplierMatrixProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial +open CompanionPhaseCounts CompanionMultiplierProgram CompanionOrderedProposal CompanionTraceProgram +open CompanionFactorialApplication CompanionArithmeticProposal CompanionRationalUpdates +open CommonBasesFPRAS +open scoped Classical + +abbrev FractionMatrix := List (List TreeFraction.Fraction) +abbrev Input := ReturnInput×FractionMatrix + +def indices (z : ReturnInput) : List ℕ := List.range z.1.length + +def indicesRealizer : Realizer indices := composition (composition first listLength) range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1).trans (weight_fst z) + +def readEntry (z : FractionMatrix×(ℕ×ℕ)) : TreeFraction.Fraction := + (z.1.getD z.2.1 []).getD z.2.2 (0,1) + +def readEntryRealizer : Realizer readEntry := + composition (pair (composition (pair first (composition second first)) (getDFast [])) + (composition second second)) (getDFast (0,1)) + +lemma polynomial_readEntry : PolynomialTime readEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) (polynomial_getDFast [])) + (polynomial_composition polynomial_second polynomial_second)) (polynomial_getDFast (0,1)) + +def updateEntry (z : Input×(ℕ×ℕ)) : TreeFraction.Fraction := + updateCode ((z.1.1,z.2),readEntry (z.1.2,z.2)) + +def updateEntryRealizer : Realizer updateEntry := + composition (pair (pair (composition first first) second) + (composition (pair (composition first second) second) readEntryRealizer)) updateCodeRealizer + +lemma polynomial_updateEntry : PolynomialTime updateEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_readEntry)) polynomial_updateCode + +def rowEntry (z : (Input×ℕ)×ℕ) : TreeFraction.Fraction := + updateEntry (z.1.1,(z.1.2,z.2)) + +def rowEntryRealizer : Realizer rowEntry := + composition (pair (composition first first) (pair (composition first second) second)) + updateEntryRealizer + +lemma polynomial_rowEntry : PolynomialTime rowEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_updateEntry + +def updateRow (z : Input×ℕ) : List TreeFraction.Fraction := + (indices z.1.1).map (fun j => rowEntry (z,j)) + +def updateRowRealizer : Realizer updateRow := + composition (pair identity (composition (composition first first) indicesRealizer)) + (mapWith rowEntryRealizer) + +lemma polynomial_updateRow : PolynomialTime updateRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_indices)) (polynomial_mapWith polynomial_rowEntry) + +def updateMatrix (z : Input) : FractionMatrix := + (indices z.1).map (fun i => updateRow (z,i)) + +def updateMatrixRealizer : Realizer updateMatrix := + composition (pair identity (composition first indicesRealizer)) (mapWith updateRowRealizer) + +theorem polynomial_updateMatrix : PolynomialTime updateMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_indices)) + (polynomial_mapWith polynomial_updateRow) + +/-- Diagonal matrix entries do not name defect classes. -/ +def positiveEntry (z : DefectCountInput) : Bool := + decide (z.2.1=z.2.2 ∨ 0 simp [positiveEntry,h]) + +lemma polynomial_positiveEntry : PolynomialTime positiveEntryRealizer := by + unfold positiveEntryRealizer + apply polynomial_congr + exact polynomial_choose (polynomial_composition polynomial_second polynomial_natEqual) + (polynomial_constant true) + (polynomial_composition (polynomial_pair (polynomial_constant 0) polynomial_defectCount) + polynomial_less) + +def positiveRow (z : ReturnInput×ℕ) : Bool := + (indices z.1).all (fun j => positiveEntry (z.1,(z.2,j))) + +def positiveRowRealizer : Realizer positiveRow := + (composition (composition (pair identity (composition first indicesRealizer)) + (mapWith (composition (pair (composition first first) + (pair (composition first second) second)) positiveEntryRealizer))) all).congr (by + intro z + simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,positiveRow]) + +lemma polynomial_positiveRow : PolynomialTime positiveRowRealizer := by + unfold positiveRowRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_composition polynomial_first polynomial_indices)) + (polynomial_mapWith (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_positiveEntry))) polynomial_all + +def positiveCounts (z : ReturnInput) : Bool := + decide (0 positiveRow (z,i)) + +def positiveCountsRealizer : Realizer positiveCounts := + (composition (pair (composition (pair (constant 0) plainCountRealizer) less) + (composition (composition (pair identity indicesRealizer) (mapWith positiveRowRealizer)) all)) + boolAnd).congr (by + intro z + simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,positiveCounts]) + +theorem polynomial_positiveCounts : PolynomialTime positiveCountsRealizer := by + unfold positiveCountsRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 0) polynomial_plainCount) polynomial_less) + (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_positiveRow)) polynomial_all)) polynomial_boolAnd + +lemma positiveCounts_iff (z : ReturnInput) : + positiveCounts z=true ↔ 0 ?_⟩ + have hr : positiveRow (z,i)=true := List.all_eq_true.mp h i hi + have he : positiveEntry (z,(i,j))=true := List.all_eq_true.mp hr j hj + exact of_decide_eq_true he + · rintro ⟨hp,h⟩ + refine ⟨decide_eq_true hp,List.all_eq_true.mpr (fun i hi => ?_)⟩ + apply List.all_eq_true.mpr + intro j hj + exact decide_eq_true (h i hi j hj) + +noncomputable section +open TwoLiftStates +variable {I J : Type} [Fintype I] [Fintype J] +variable (A : Instance I J) {p m : ℕ} (g : Fin p ≃ Labels A) + (e : (Labels A×Bool) ≃ Fin m) + +def matrixCode (w : Fin p → Fin p → TreeFraction.Fraction) : FractionMatrix := + List.ofFn (fun i => List.ofFn (w i)) + +lemma readEntry_code (w : Fin p → Fin p → TreeFraction.Fraction) (i j : Fin p) : + readEntry (matrixCode w,(i.val,j.val))=w i j := by + simp only [readEntry,matrixCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + i.isLt,j.isLt,dite_true,Option.getD_some,Fin.eta] + +theorem updateEntry_code (states : List (Set (Labels A×Bool))) + (w : Fin p → Fin p → TreeFraction.Fraction) (i j : Fin p) : + updateEntry (((orderedCatalog A g e,states.map (encodeSet e)),matrixCode w),(i.val,j.val))= + updateCode (((orderedCatalog A g e,states.map (encodeSet e)),(i.val,j.val)),w i j) := by + simp only [updateEntry,readEntry_code] + +lemma positiveCounts_code (states : List (Set (Labels A×Bool))) : + positiveCounts (orderedCatalog A g e,states.map (encodeSet e))=true ↔ + CountsPositive A states := by + have he : positiveCounts (orderedCatalog A g e,states.map (encodeSet e))=true ↔ + 0 ?_⟩ + have hh := h i.val i.isLt j.val j.isLt + have hn : i.val≠j.val := fun h => hij (Fin.ext h) + simp only [hn,false_or] at hh + rw [defectCount_code A g e states i j] at hh + exact hh + · rintro ⟨hp,h⟩ + refine ⟨hp,fun i hi j hj => ?_⟩ + by_cases hij : i=j + · exact Or.inl hij + · right + have hh := h ⟨i,hi⟩ ⟨j,hj⟩ (fun he => hij (congrArg Fin.val he)) + rw [←defectCount_code A g e states ⟨i,hi⟩ ⟨j,hj⟩] at hh + exact hh + rw [he] + unfold CountsPositive + constructor + · rintro ⟨hp,h⟩ + refine ⟨hp,fun a ha b hb hab => ?_⟩ + obtain ⟨a',_,rfl⟩ := List.mem_map.mp ha + obtain ⟨b',_,rfl⟩ := List.mem_map.mp hb + obtain ⟨i,rfl⟩ := g.surjective a' + obtain ⟨j,rfl⟩ := g.surjective b' + exact h i j (fun he => hab (congrArg (fun k => pair (g k)) he)) + · rintro ⟨hp,h⟩ + refine ⟨hp,fun i j hij => ?_⟩ + exact h _ (pair_mem _) _ (pair_mem _) + (fun he => hij (g.injective (pair_injective he))) + +/-- The executable update contains exactly one entry for every ordered +pair of labels, in the same order as the executable proposal catalog. -/ +theorem updateMatrix_code (states : List (Set (Labels A×Bool))) + (w : Fin p → Fin p → TreeFraction.Fraction) : + updateMatrix ((orderedCatalog A g e,states.map (encodeSet e)),matrixCode w)= + matrixCode (fun i j => updateCode + (((orderedCatalog A g e,states.map (encodeSet e)),(i.val,j.val)),w i j)) := by + unfold updateMatrix matrixCode + have hi : indices (orderedCatalog A g e,states.map (encodeSet e))=List.range p := by + simp only [indices,orderedCatalog,List.length_ofFn] + rw [hi] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi' _ + have hip : i

plainCountCode z.1) := + composition (f := fun z : DefectCountInput => z.1) (g := plainCountCode) + first plainCountRealizer + +def countRatioRealizer : Realizer countRatio := + pair countPlainRealizer defectCountRealizer + +lemma polynomial_countRatio : PolynomialTime countRatioRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_plainCount) + polynomial_defectCount + +abbrev UpdateInput := DefectCountInput×TreeFraction.Fraction + +def updateCode (z : UpdateInput) : TreeFraction.Fraction := + if z.1.2.1=z.1.2.2 then z.2 else TreeFraction.mul (z.2,countRatio z.1) + +def diagonalRealizer : Realizer (fun z : UpdateInput => decide (z.1.2.1=z.1.2.2)) := + composition (pair (composition (composition first second) first) + (composition (composition first second) second)) natEqual + +lemma polynomial_diagonal : PolynomialTime diagonalRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second)) polynomial_natEqual + +def updateCodeRealizer : Realizer updateCode := + (choose diagonalRealizer second + (composition (pair second (composition first countRatioRealizer)) TreeFraction.mulRealizer)).congr + (by intro z; simp only [updateCode,Function.comp_apply,decide_eq_true_eq]) + +theorem polynomial_updateCode : PolynomialTime updateCodeRealizer := by + unfold updateCodeRealizer + apply polynomial_congr + exact polynomial_choose polynomial_diagonal polynomial_second + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_countRatio)) TreeFraction.polynomial_mul) + +lemma updateCode_value (z : UpdateInput) : + TreeFraction.val (updateCode z)= + if z.1.2.1=z.1.2.2 then TreeFraction.val z.2 + else TreeFraction.val z.2*(plainCountCode z.1.1:ℚ)/(defectCountCode z.1:ℚ) := by + unfold updateCode + split_ifs + · rfl + · rw [TreeFraction.mul_val] + simp only [countRatio,TreeFraction.val,mul_div_assoc] + +noncomputable section +open TwoLiftStates +variable {I J : Type} [Fintype I] [Fintype J] +variable (A : Instance I J) {p m : ℕ} (g : Fin p ≃ Labels A) + (e : (Labels A×Bool) ≃ Fin m) + +/-- This is the literal source multiplier update at a pair of actual +labels, not a surrogate recurrence on unrelated rational values. -/ +theorem updateCode_learn (states : List (Set (Labels A×Bool))) + (hlen : 0 g.injective (pair_injective h),fun h => congrArg (fun a => pair (g a)) h⟩ + simp only [hp,hq,true_and] + by_cases hij : i=j + · subst j + simp + · have hval : i.val≠j.val := fun h => hij (Fin.ext h) + have hpair : pair (g i)≠pair (g j) := fun h => hij (he.mp h) + simp only [hval,ite_false] + split_ifs with h + · rfl + · exact (h hpair).elim + +end +end ContingencyTables.CompanionMultiplierProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierUpdate.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierUpdate.lean new file mode 100644 index 0000000000000000000000000000000000000000..62070c30a8c09291f2ac6d058f25ee7b350b51af --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionMultiplierUpdate.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionAnnealing +import OAI.Combinatorics.ContingencyTables.Counting.AnnealingMultipliers + +namespace OAI + +/-! +# Actual companion empirical multiplier and counting updates + +The observables and empirical counts are those of the actual labelled +chain. The update cancels the preceding multiplier, and the next-parameter +comparison is derived from the literal bounded forest penalty. +-/ + +namespace ContingencyTables.CompanionMultiplierUpdate + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication CompanionAnnealing TwoLiftStates + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def ratio (A : Instance I J) (j : ℕ) (S : Set (Labels A×Bool)) : ℝ := + weight A (j+1) S/weight A j S + +lemma ratio_bounds (A : Instance I J) (j : ℕ) (S : Set (Labels A×Bool)) : + (1/2:ℝ)≤ ratio A j S ∧ ratio A j S≤1 := by + have h := weight_adjacent A j S + unfold ratio + constructor + · exact (le_div_iff₀ (weight_positive A j S)).mpr h.1 + · exact (div_le_one (weight_positive A j S)).mpr h.2 + +lemma ratio_mean (A : Instance I J) (j : ℕ) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) : + chainMean pairs w (weight A j) (plainObservable pairs (ratio A j))= + slotTotal pairs (weight A (j+1)) ∅/chainTotal pairs w (weight A j) := by + rw [plainObservable_mean pairs PairedLabels.fresh PairedLabels.cover] + congr 2 + funext S + unfold ratio + exact mul_div_cancel₀ _ (weight_positive A j S).ne' + +/-- The explicit observed-type-count update gives good multipliers for +j+1. Its only statistical hypothesis is relative accuracy of the actual +finite observations at phase j. -/ +theorem successful_phase_learns (A : Instance I J) (j : ℕ) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0< w p r) (eta : ℝ) (he0 : 0≤ eta) (he : eta≤1/4) + (l : List (Set (Labels A×Bool))) + (hacc : AccuratePhase pairs w (weight A j) (ratio A j) eta l) : + GoodMultipliers pairs (weight A (j+1)) (learnedMultipliers pairs w l) := by + have hZ := chainTotal_pos pairs PairedLabels.fresh PairedLabels.cover w + (weight A j) (weight_positive A j) hw + have hp0 : 0< chainMean pairs w (weight A j) (plainObservable pairs (fun _ => 1)) := by + rw [plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] + exact div_pos (slotTotal_pos pairs _ (weight_positive A j) ∅ PairedLabels.fresh) hZ + have hplain := accurate_plain pairs w (weight A j) (ratio A j) eta l hacc + have hp0h := AnnealingMultipliers.empirical_positive hp0 he hplain.1 + have hpt (p r : (Labels A×Bool)×(Labels A×Bool)) (hp : p∈pairs) (hr : r∈pairs) + (hpr : p≠r) : 0< chainMean pairs w (weight A j) (defectIndicator pairs p r) := by + rw [defectIndicator_mean pairs PairedLabels.fresh PairedLabels.cover _ _ p r hp hr hpr] + exact div_pos (mul_pos (hw p r) + (slotDefect_pos pairs _ (weight_positive A j) ∅ PairedLabels.fresh p r hp hr hpr)) hZ + have hpth (p r : (Labels A×Bool)×(Labels A×Bool)) (hp : p∈pairs) (hr : r∈pairs) + (hpr : p≠r) : 0< empirical (defectIndicator pairs p r) l := + AnnealingMultipliers.empirical_positive (hpt p r hp hr hpr) he + (accurate_defect pairs w (weight A j) (ratio A j) eta l hacc p r hp hr hpr).1 + have hb (p r : (Labels A×Bool)×(Labels A×Bool)) (hp : p∈pairs) (hr : r∈pairs) + (hpr : p≠r) : + (slotTotal pairs (weight A (j+1)) ∅/slotDefect pairs (weight A (j+1)) ∅ p r)/4≤ + learnedMultipliers pairs w l p r ∧ + learnedMultipliers pairs w l p r≤ + 4*(slotTotal pairs (weight A (j+1)) ∅/slotDefect pairs (weight A (j+1)) ∅ p r) := by + rw [learnedMultipliers,ite_eq_left ⟨hp,hr,hpr⟩] + have hu := AnnealingMultipliers.update_good hp0 (hpt p r hp hr hpr) (hw p r) + he0 he hplain (accurate_defect pairs w (weight A j) (ratio A j) eta l hacc p r hp hr hpr) + (by simpa only [mul_div_assoc] using (weight_mean_identity pairs PairedLabels.fresh + PairedLabels.cover (weight A j) (weight_positive A j) w hw p r hp hr hpr)) + (ideal_adjacent A j p r hp hr hpr) + simpa only [mul_div_assoc] using hu + refine ⟨?_,?_,?_⟩ + · intro p r + unfold learnedMultipliers + split_ifs with ht + · exact mul_pos (hw p r) (div_pos hp0h (hpth p r ht.1 ht.2.1 ht.2.2)) + · exact hw p r + · intro p hp r hr hpr + simpa only [div_div,mul_comm] using (hb p r hp hr hpr).1 + · intro p hp r hr hpr + simpa only [mul_div_assoc] using (hb p r hp hr hpr).2 + +/-- Relative accuracy of the actual counting and plain observations +bounds one logarithmic counting-ratio error by 4 eta. -/ +theorem successful_phase_ratio_log (A : Instance I J) (j : ℕ) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0< w p r) (eta : ℝ) (he0 : 0≤ eta) (he : eta≤1/4) + (l : List (Set (Labels A×Bool))) + (hacc : AccuratePhase pairs w (weight A j) (ratio A j) eta l) : + |Real.log (empiricalRatio pairs (ratio A j) l/ + (slotTotal pairs (weight A (j+1)) ∅/slotTotal pairs (weight A j) ∅))|≤4*eta := by + have hZ := chainTotal_pos pairs PairedLabels.fresh PairedLabels.cover w + (weight A j) (weight_positive A j) hw + have hC := slotTotal_pos pairs _ (weight_positive A j) ∅ PairedLabels.fresh + have hC' := slotTotal_pos pairs _ (weight_positive A (j+1)) ∅ PairedLabels.fresh + have hp : 0< chainMean pairs w (weight A j) (plainObservable pairs (ratio A j)) := by + rw [ratio_mean] + exact div_pos hC' hZ + have hq : 0< chainMean pairs w (weight A j) (plainObservable pairs (fun _ => 1)) := by + rw [plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] + exact div_pos hC hZ + have hph := relative_error_bounds _ _ _ (hacc (.inr ())) + simp only [phaseObservable] at hph + have hqh := accurate_plain pairs w (weight A j) (ratio A j) eta l hacc + have h := (AnnealingMultipliers.relative_ratio hp hq he0 he hph hqh).2.2.2 + rw [ratio_mean,plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] at h + unfold empiricalRatio + convert h using 2 + congr 1 + field_simp [hZ.ne',hC.ne',hC'.ne'] + +end ContingencyTables.CompanionMultiplierUpdate + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionNearMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionNearMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..eafb30ddbd2b5bab965aa3951ab0a38157ec98e3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionNearMass.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.TreeExteriorMass +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFarMass +import OAI.Combinatorics.ContingencyTables.Transport.WeightedCellFibres + +namespace OAI + +/-! # The actual narrow exterior region contributes at most 4 gamma K per tree cell -/ + +namespace ContingencyTables.CompanionNearMass + +open scoped BigOperators Classical +open CompanionFactorialApplication CompanionPhysicalNormalizer CompanionFarMass +open TreeMarginalSignature TreeExteriorPositions BalancedCellFibres ForestPenaltyApplication + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def cellPositions (A : Instance I J) (t : I×J) (gamma : ℝ) : + Finset (Fin (cellWidth A t+1)) := + positions (ForestLiteralCount.lower A.T A.d A.b t.1 t.2) (A.b t.1 t.2) + (cellWidth A t) (gamma*A.b t.1 t.2) + +noncomputable def nearMass (A : Instance I J) (alpha : ℝ) (t : I×J) (gamma : ℝ) : ℝ := + ∑ a : Profiles (cellWidth A),if a t ∈ cellPositions A t gamma then actualWeight A alpha a else 0 + +lemma nearMass_eq_fibres (A : Instance I J) (alpha : ℝ) (t : I×J) (gamma : ℝ) : + nearMass A alpha t gamma=∑ k ∈ cellPositions A t gamma,scalarExact A alpha t k.val := by + have hh := weighted_fibre_sum (cellWidth A) + (physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha) t + (fun k => if k ∈ cellPositions A t gamma then 1 else 0) + have hs : (∑ k : Fin (cellWidth A t+1), + if k ∈ cellPositions A t gamma then scalarExact A alpha t k.val else 0)=nearMass A alpha t gamma := by + simp_rw [exact_eq_fibre] + simpa only [nearMass,actualWeight,mul_ite,mul_one,mul_zero] using hh + rw [← hs] + simpa only [Finset.filter_mem_eq_inter,Finset.univ_inter] using + (Finset.sum_filter (s := Finset.univ) (fun k => k ∈ cellPositions A t gamma) + (fun k => scalarExact A alpha t k.val)).symm + +/-- This uses actual feasible endpoint tables, the proved raw marginal +signature and equality limit, and the exact count normalizer. -/ +theorem near_mass_bound (A : Instance I J) (alpha gamma : ℝ) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) (ha : 0 ≤ alpha) (hg : 0 < gamma) + (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) (hK : 0 < K) + (Y0 Y1 : I → J → ℤ) + (hY0 : ∀ i j,0 ≤ Y0 i j ∧ Y0 i j ≤ A.b i j) + (hY1 : ∀ i j,0 ≤ Y1 i j ∧ Y1 i j ≤ A.b i j) + (hr0 : ∀ i,(∑ j,Y0 i j)=A.r i) (hc0 : ∀ j,(∑ i,Y0 i j)=A.c j) + (hr1 : ∀ i,(∑ j,Y1 i j)=A.r i) (hc1 : ∀ j,(∑ i,Y1 i j)=A.c j) + (hy0 : Y0 t.1 t.2=0) (hy1 : Y1 t.1 t.2=(A.b t.1 t.2:ℤ)) : + nearMass A alpha t gamma/physicalMass A alpha ≤ 4*gamma*K := by + have hb : 0 < A.b t.1 t.2 := by have h := (A.hlarge _ _ (A.hTG ht)).2; omega + have hbR : (0:ℝ) < A.b t.1 t.2 := by exact_mod_cast hb + have hpoint (k : Fin (cellWidth A t+1)) (hk : k ∈ cellPositions A t gamma) : + scalarExact A alpha t k.val/physicalMass A alpha ≤ (2*K:ℝ)/A.b t.1 t.2 := by + have hh := (Finset.mem_filter.mp hk).2 + change (((ForestLiteralCount.lower A.T A.d A.b t.1 t.2+(k.val:ℤ)<0) ∧ _) ∨ + (((A.b t.1 t.2:ℤ) hpoint k hk) + _ = ((cellPositions A t gamma).card:ℝ)*((2*K:ℝ)/A.b t.1 t.2) := by simp + _ ≤ (2*(gamma*A.b t.1 t.2))*((2*K:ℝ)/A.b t.1 t.2) := + mul_le_mul_of_nonneg_right hcard (by positivity) + _ = _ := by field_simp [hbR.ne']; ring + +end ContingencyTables.CompanionNearMass + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionNeighborProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionNeighborProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..bfd8a1989a547c3f29ba69a4c095d80af4a0c37a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionNeighborProgram.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionChainValidator + +namespace OAI + +/-! # Executable valid-neighbor lists and their binary draw + +This composes the actual integer-exchange program with the paired-state +validator and the bounded list-index program. The output code is exactly +the encoding of the semantic proposal, including its failure outcome. +-/ + +namespace ContingencyTables.CompanionNeighborProgram +open CompanionChainValidator CompanionArithmeticProposal CompanionFactorialApplication +open CompanionBooleanPhase ProfilePrograms MatchingFPRAS.TreeTyped +open CommonBasesFPRAS +open scoped BigOperators Classical + +def validExchanges (z : ValidatorInput) : List (List ℕ) := + (binaryExchanges z.2).filter (fun xs => pairedStateTest (z.1,xs)) + +def validExchangesRealizer : Realizer validExchanges := + composition (pair first (composition second binaryExchangesRealizer)) + (filterWith pairedStateTestRealizer) + +theorem polynomial_validExchanges : PolynomialTime validExchangesRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_binaryExchanges)) + (polynomial_filterWith polynomial_pairedStateTest) + +def codeProposal (z : ValidatorInput×List Bool) : Option (List ℕ) := + listWordChoice (validExchanges z.1,z.2) + +def codeProposalRealizer : Realizer codeProposal := + composition (pair (composition first validExchangesRealizer) second) listWordChoiceRealizer + +/-- All loops traverse the supplied profile, pair catalog or quadratic +coordinate list. A large binary draw index never determines a loop. -/ +theorem polynomial_codeProposal : PolynomialTime codeProposalRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_validExchanges) polynomial_second) + polynomial_listWordChoice + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +lemma validExchanges_encode (A : Instance I J) (S : State A) : + validExchanges (pairCatalog A,encodeSet (coordinateEquiv A) S.val)= + (neighbors A S).map (fun T => encodeSet (coordinateEquiv A) T.val) := by + unfold validExchanges neighbors neighborStates neighborSets + rw [List.map_filterMap,List.filterMap_map,←List.filterMap_eq_filter] + apply List.filterMap_congr + intro xs hxs + obtain ⟨T,hT,rfl⟩ := (mem_raw_codes (coordinateEquiv A) S.val xs).mp hxs + simp only [Function.comp_apply,decode_encode] + by_cases h : ChainState TwoLiftStates.pairs T + · have hp : pairedStateTest (pairCatalog A,encodeSet (coordinateEquiv A) T)=true := + (pairedStateTest_encode A T).mpr h + simp only [dite_eq_left h,Option.map_some,Option.guard,hp,ite_true] + · have hp : pairedStateTest (pairCatalog A,encodeSet (coordinateEquiv A) T)=false := by + apply Bool.eq_false_iff.mpr + intro ht + exact h ((pairedStateTest_encode A T).mp ht) + simp only [dite_eq_right h,Option.map_none,Option.guard,hp,Bool.false_eq_true,ite_false] + +/-- The public binary program computes the exact semantic draw. -/ +theorem codeProposal_eq (A : Instance I J) (S : State A) + (bits : Fin (proposalBits A) → Bool) : + codeProposal ((pairCatalog A,encodeSet (coordinateEquiv A) S.val),List.ofFn bits)= + (CompanionArithmeticProposal.proposal A S bits).map + (fun T => encodeSet (coordinateEquiv A) T.val) := by + rw [codeProposal,validExchanges_encode] + simp only [listWordChoice,CompanionArithmeticProposal.proposal,List.getElem?_map] + +end +end ContingencyTables.CompanionNeighborProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservableApplication.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservableApplication.lean new file mode 100644 index 0000000000000000000000000000000000000000..77f452be027d455210b137f3921fa7bb2fafb66c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservableApplication.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFactorialApplication +import OAI.Combinatorics.ContingencyTables.Transport.PairedLabels +import OAI.Combinatorics.ContingencyTables.Transport.ComplementChain + +namespace OAI + +/-! +# Observable variance for the actual companion completion-count lifts + +The original chain uses the literal factorial lift of h_j. Its proved +omission and dual addition properties, with q=W², supply the paper's +transversal and observable bounds on the actual disjoint covering slots. +-/ + +namespace ContingencyTables.CompanionObservableApplication + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication TwoLiftStates +open ComplementChain ObservableBounds + +variable {I J : Type*} [Fintype I] [Fintype J] + +theorem transversal_variance (A : Instance I J) (alpha : ℝ) (ha : 0≤alpha) + (H : Set (Labels A×Bool) → ℝ) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r, 0 queryPair + (cs,(codes i,List.ofFn (gridWordEquiv N (blockWidth cs) bits i)))) := by + unfold output indices + simp only [List.length_ofFn] + apply List.ext_getElem + · simp + · intro i hi _ + have hi' : i < N := by simpa only [List.length_map,List.length_range] using hi + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn,indexedPair,indexedInput, + List.getD_eq_getElem?_getD,List.getElem?_ofFn,hi',dite_true,Option.getD_some] + have hw := wordChunk_ofFn bits ⟨i,hi'⟩ + exact congrArg (fun bs => queryPair (cs,(codes ⟨i,hi'⟩,bs))) hw + +def values (xs : List (Fraction×Fraction)) : List (ℚ×ℚ) := + xs.map (fun z => (TreeFraction.val z.1,TreeFraction.val z.2)) + +/-- Each trajectory position gets its own independent current and next query. -/ +theorem sameLaw {N : ℕ} {U V : Type*} [Fintype U] [Fintype V] + (cs : Config×Config) (codes : Fin N→List ℕ) (f : Fin N→U→ℚ) (g : Fin N→V→ℚ) + (hf : ∀ i,SameLaw (fun bits : Fin (queryWidth cs.1)→Bool => + TreeFraction.val (RootedLabelWeightProgram.output (cs.1,(codes i,List.ofFn bits)))) (f i)) + (hg : ∀ i,SameLaw (fun bits : Fin (queryWidth cs.2)→Bool => + TreeFraction.val (RootedLabelWeightProgram.output (cs.2,(codes i,List.ofFn bits)))) (g i)) : + SameLaw (fun bits : Fin (N*blockWidth cs)→Bool => + values (output (cs,(List.ofFn codes,List.ofFn bits)))) + (fun bits : Fin N→U×V => List.ofFn (fun i => (f i (bits i).1,g i (bits i).2))) := by + have h := (FiniteObservableTransport.indexed N _ _ (fun i => (hf i).prod (hg i))).map List.ofFn + let e : (Fin (N*blockWidth cs)→Bool) ≃ + (Fin N→(Fin (queryWidth cs.1)→Bool)×(Fin (queryWidth cs.2)→Bool)) := + (gridWordEquiv N (blockWidth cs)).trans (Equiv.piCongrRight (fun _ => splitWordEquiv _ _)) + intro phi + have he := uniformAverage_equiv e (fun xs => phi (List.ofFn (fun i => + (TreeFraction.val (RootedLabelWeightProgram.output (cs.1,(codes i,List.ofFn (xs i).1))), + TreeFraction.val (RootedLabelWeightProgram.output (cs.2,(codes i,List.ofFn (xs i).2))))))) + have hout : (fun bits : Fin (N*blockWidth cs)→Bool => + phi (values (output (cs,(List.ofFn codes,List.ofFn bits)))))= + (fun bits => phi (List.ofFn (fun i => + (TreeFraction.val (RootedLabelWeightProgram.output (cs.1,(codes i,List.ofFn (e bits i).1))), + TreeFraction.val (RootedLabelWeightProgram.output (cs.2,(codes i,List.ofFn (e bits i).2))))))) := by + funext bits + rw [output_ofFn] + simp only [values,List.map_ofFn,queryPair_ofFn] + rfl + rw [hout] + exact he.trans (h phi) + +variable {m n : ℕ} +lemma queryWidth_config (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : ℚ) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) : + queryWidth (RootedLabelWeightProgram.config A C K j xi xi z v degree depth)= + medianEstimatorBits A C K j xi xi := by + unfold queryWidth RootedLabelWeightProgram.config + exact CompanionEvaluatedWeightProgram.queryWidth A C K j xi z v + +lemma sameLaw_query (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (S : Set (Labels A×Bool)) : + SameLaw (fun bits : Fin (queryWidth + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth))→Bool => + TreeFraction.val (RootedLabelWeightProgram.output + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth, + (encodeSet (coordinateOrder A) S,List.ofFn bits)))) + (RootedWeightOracle.evaluate A (RootedCompletion.rowColumn A.T) C K hK hW j xi + (RootedCatalogGrid.gridEquiv A K v) S) := by + have h := RootedLabelWeightProgram.sameLaw_weight A C K j hC hj hK hW hB xi hxi z v + degree depth hdegree hdepth S + exact SameLaw.word_length + ((CompanionEvaluatedWeightProgram.queryWidth A C K j xi (profile A S) v).trans + (queryWidth_config A C K j xi z v degree depth).symm) (fun bs => TreeFraction.val (RootedLabelWeightProgram.output + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth, + (encodeSet (coordinateOrder A) S,bs)))) _ h + +/-- The two physical configurations used for observing one phase. -/ +def phaseConfigs (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : ℚ) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth nextDegree nextDepth : List Bool) : Config×Config := + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth, + RootedLabelWeightProgram.config A C K (j+1) xi xi z v nextDegree nextDepth) + +lemma blockWidth_phaseConfigs (A : Instance (Fin m) (Fin n)) (C K j : ℕ) (xi : ℚ) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth nextDegree nextDepth : List Bool) : + blockWidth (phaseConfigs A C K j xi z v degree depth nextDegree nextDepth)= + CompanionPhaseWords.observationBits A C K j xi := by + unfold blockWidth phaseConfigs CompanionPhaseWords.observationBits + rw [queryWidth_config,queryWidth_config] + +/-- All state observations use the exact selected-root oracle law, independently. -/ +theorem sameLaw_phase (A : Instance (Fin m) (Fin n)) (C K j N : ℕ) + (hC : 0 < C) (hj : j+1 ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth nextDegree nextDepth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (hnextDegree : nextDegree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) (j+1)))) + (hnextDepth : nextDepth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) (j+1)))) + (states : Fin N→Set (Labels A×Bool)) : + let cs := phaseConfigs A C K j xi z v degree depth nextDegree nextDepth + SameLaw (fun bits : Fin (N*blockWidth cs)→Bool => + values (output (cs,(List.ofFn (fun i => encodeSet (coordinateOrder A) (states i)),List.ofFn bits)))) + (fun bits : Fin N→WeightWord A C K j xi × WeightWord A C K (j+1) xi => + List.ofFn (fun i => + (RootedWeightOracle.evaluate A (RootedCompletion.rowColumn A.T) C K hK hW j xi + (RootedCatalogGrid.gridEquiv A K v) (states i) (bits i).1, + RootedWeightOracle.evaluate A (RootedCompletion.rowColumn A.T) C K hK hW (j+1) xi + (RootedCatalogGrid.gridEquiv A K v) (states i) (bits i).2))) := by + dsimp only + exact sameLaw _ _ _ _ + (fun i => sameLaw_query A C K j hC (by omega) hK hW hB xi hxi z v degree depth hdegree hdepth (states i)) + (fun i => sameLaw_query A C K (j+1) hC hj hK hW hB xi hxi z v nextDegree nextDepth hnextDegree hnextDepth (states i)) + +end +end ContingencyTables.CompanionObservationQueriesProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservationQueriesProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservationQueriesProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..5608de863d3be66d9810e6c51870ebeb275d81bc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservationQueriesProgram.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedLabelWeightProgram +import OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram + +namespace OAI + +/-! # Executed current and next weight queries along a supplied trajectory -/ +namespace ContingencyTables.CompanionObservationQueriesProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial DensePrograms + +abbrev Config := RootedLabelWeightProgram.Config +abbrev Fraction := TreeFraction.Fraction +abbrev Input := (Config×Config)×(List (List ℕ)×List Bool) +abbrev PairInput := (Config×Config)×(List ℕ×List Bool) + +def queryWidth (c : Config) : ℕ := c.1.2*RootedEstimatorLayoutProgram.wordWidth c.1.1 +def queryWidthRealizer : Realizer queryWidth := + composition (pair (composition first second) + (composition (f := fun c : Config => c.1.1) (g := RootedEstimatorLayoutProgram.wordWidth) + (composition first first) RootedEstimatorLayoutProgram.wordWidthRealizer)) multiply +lemma polynomial_queryWidth : PolynomialTime queryWidthRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + RootedEstimatorLayoutProgram.polynomial_wordWidth)) polynomial_multiply + +attribute [local irreducible] queryWidth + +abbrev blockWidth (cs : Config×Config) : ℕ := queryWidth cs.1+queryWidth cs.2 +def blockWidthRealizer : Realizer blockWidth := + composition (pair (composition (f := fun cs : Config×Config => cs.1) (g := queryWidth) first queryWidthRealizer) + (composition (f := fun cs : Config×Config => cs.2) (g := queryWidth) second queryWidthRealizer)) add +lemma polynomial_blockWidth : PolynomialTime blockWidthRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_queryWidth) + (polynomial_composition polynomial_second polynomial_queryWidth)) polynomial_add + + +def currentInput (z : PairInput) : RootedLabelWeightProgram.Input := + (z.1.1,(z.2.1,z.2.2.take (queryWidth z.1.1))) +def currentInputRealizer : Realizer currentInput := + pair (composition first first) + (pair (composition second first) + (composition (pair (composition second second) + (composition (f := fun z : PairInput => z.1.1) (g := queryWidth) + (composition first first) queryWidthRealizer)) takeFast)) +lemma polynomial_currentInput : PolynomialTime currentInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_queryWidth)) + polynomial_takeFast)) + +def nextInput (z : PairInput) : RootedLabelWeightProgram.Input := + (z.1.2,(z.2.1,(z.2.2.drop (queryWidth z.1.1)).take (queryWidth z.1.2))) +def nextInputRealizer : Realizer nextInput := + pair (composition first second) + (pair (composition second first) + (composition (pair + (composition (pair (composition second second) + (composition (f := fun z : PairInput => z.1.1) (g := queryWidth) + (composition first first) queryWidthRealizer)) dropFast) + (composition (f := fun z : PairInput => z.1.2) (g := queryWidth) + (composition first second) queryWidthRealizer)) takeFast)) +lemma polynomial_nextInput : PolynomialTime nextInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_queryWidth)) + polynomial_dropFast) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_queryWidth)) + polynomial_takeFast)) + +attribute [local irreducible] currentInput nextInput RootedLabelWeightProgram.output + +def queryPair (z : PairInput) : Fraction×Fraction := + (RootedLabelWeightProgram.output (currentInput z),RootedLabelWeightProgram.output (nextInput z)) +def queryPairRealizer : Realizer queryPair := + pair (composition (f := currentInput) (g := RootedLabelWeightProgram.output) + currentInputRealizer RootedLabelWeightProgram.outputRealizer) + (composition (f := nextInput) (g := RootedLabelWeightProgram.output) + nextInputRealizer RootedLabelWeightProgram.outputRealizer) +lemma polynomial_queryPair : PolynomialTime queryPairRealizer := + polynomial_pair (polynomial_composition polynomial_currentInput RootedLabelWeightProgram.polynomial_output) + (polynomial_composition polynomial_nextInput RootedLabelWeightProgram.polynomial_output) + +def indices (z : Input) : List ℕ := List.range z.2.1.length +def indicesRealizer : Realizer indices := + composition (composition (composition second first) listLength) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_listLength) X + intro z + simpa only [eval_X,Function.comp_apply] using + (list_length_le_weight z.2.1).trans ((weight_fst z.2).trans (weight_snd z)) + +def indexedInput (z : Input×ℕ) : PairInput := + (z.1.1,(z.1.2.1.getD z.2 [],wordChunk ((blockWidth z.1.1,z.1.2.2),z.2))) +def indexedInputRealizer : Realizer indexedInput := + pair (composition first first) + (pair (composition (pair (composition (composition first second) first) second) (getDFast [])) + (composition (f := fun z : Input×ℕ => ((blockWidth z.1.1,z.1.2.2),z.2)) (g := wordChunk) + (pair (pair (composition (f := fun z : Input×ℕ => z.1.1) (g := blockWidth) + (composition first first) blockWidthRealizer) (composition (composition first second) second)) second) + wordChunkRealizer)) +lemma polynomial_indexedInput : PolynomialTime indexedInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + polynomial_second) (polynomial_getDFast [])) + (polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_blockWidth) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_second) polynomial_wordChunk)) + +def indexedPair (z : Input×ℕ) : Fraction×Fraction := queryPair (indexedInput z) +def indexedPairRealizer : Realizer indexedPair := + composition (f := indexedInput) (g := queryPair) indexedInputRealizer queryPairRealizer +lemma polynomial_indexedPair : PolynomialTime indexedPairRealizer := + polynomial_composition polynomial_indexedInput polynomial_queryPair + +def output (z : Input) : List (Fraction×Fraction) := (indices z).map (fun i => indexedPair (z,i)) +def outputRealizer : Realizer output := + composition (pair identity indicesRealizer) (mapWith indexedPairRealizer) +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_indexedPair) + +end ContingencyTables.CompanionObservationQueriesProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservedUpdateLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservedUpdateLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..42a52f66031c0a639be79674509447b661f72018 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservedUpdateLaw.lean @@ -0,0 +1,134 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionObservedUpdateProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionObservationQueriesLaw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseFinishSemantics + +namespace OAI + +/-! # Observable law of the physically executed phase update -/ +namespace ContingencyTables.CompanionObservedUpdateProgram +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial +open CompanionArithmeticProposal CompanionOrderedProposal CompanionMultiplierMatrixProgram +open FiniteObservableTransport CompanionComputedProposal TwoLiftStates +open scoped Classical +noncomputable section +variable {m n N : ℕ} (A : Instance (Fin m) (Fin n)) + +abbrev LabelIndex := CompanionEvaluatedWeightProgram.LabelIndex A + +def data (cs : Configs) (states : Fin N→Set (Labels A×Bool)) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (E : TreeFraction.Fraction) + (bits : List Bool) : Input := + ((cs,(((orderedCatalog A (pairLabels A) (coordinateOrder A), + (List.ofFn states).map (encodeSet (coordinateOrder A))),matrixCode w),E)),bits) + +attribute [local irreducible] CompanionObservationQueriesProgram.output + CompanionPhaseFinishProgram.output CompanionPhaseFinishProgram.rationalResult + +theorem output_values (cs : Configs) (states : Fin N→Set (Labels A×Bool)) + (old : CompanionPhaseWords.Stored A) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (E : TreeFraction.Fraction) + (hw : ∀ i j,TreeFraction.val (w i j)=old.multiplier (pair (pairLabels A i)) (pair (pairLabels A j))) + (hE : TreeFraction.val E=old.estimate) + (bits : Fin (N*CompanionObservationQueriesProgram.blockWidth cs)→Bool) : + (output (data A cs states w E (List.ofFn bits))).map CompanionPhaseFinishProgram.view= + CompanionPhaseFinishProgram.rationalResult A (pairLabels A) states old + (CompanionObservationQueriesProgram.values (CompanionObservationQueriesProgram.output + (cs,(List.ofFn (fun i => encodeSet (coordinateOrder A) (states i)),List.ofFn bits)))) := by + have hq := CompanionObservationQueriesProgram.output_ofFn cs + (fun i => encodeSet (coordinateOrder A) (states i)) bits + have ho : output (data A cs states w E (List.ofFn bits))= + CompanionPhaseFinishProgram.output + ((((orderedCatalog A (pairLabels A) (coordinateOrder A), + (List.ofFn states).map (encodeSet (coordinateOrder A))),matrixCode w),E), + CompanionObservationQueriesProgram.output + (cs,(List.ofFn (fun i => encodeSet (coordinateOrder A) (states i)),List.ofFn bits))) := by + simp only [output,finishInput,queryInput,data,List.map_ofFn,Function.comp_def] + rw [ho,hq] + simpa only [CompanionPhaseFinishProgram.data,CompanionObservationQueriesProgram.values,List.map_ofFn,Function.comp_def] using + (CompanionPhaseFinishProgram.output_values A (pairLabels A) (coordinateOrder A) + states old w E (fun i => CompanionObservationQueriesProgram.queryPair + (cs,(encodeSet (coordinateOrder A) (states i),List.ofFn + (GridBoundary.gridWordEquiv N (CompanionObservationQueriesProgram.blockWidth cs) bits i)))) hw hE) + +theorem sameLaw {U V : Type*} [Fintype U] [Fintype V] + (cs : Configs) (states : Fin N→Set (Labels A×Bool)) + (old : CompanionPhaseWords.Stored A) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (E : TreeFraction.Fraction) + (hw : ∀ i j,TreeFraction.val (w i j)=old.multiplier (pair (pairLabels A i)) (pair (pairLabels A j))) + (hE : TreeFraction.val E=old.estimate) (f : Fin N→U→ℚ) (g : Fin N→V→ℚ) + (hf : ∀ i,SameLaw (fun bits : Fin (CompanionObservationQueriesProgram.queryWidth cs.1)→Bool => + TreeFraction.val (RootedLabelWeightProgram.output + (cs.1,(encodeSet (coordinateOrder A) (states i),List.ofFn bits)))) (f i)) + (hg : ∀ i,SameLaw (fun bits : Fin (CompanionObservationQueriesProgram.queryWidth cs.2)→Bool => + TreeFraction.val (RootedLabelWeightProgram.output + (cs.2,(encodeSet (coordinateOrder A) (states i),List.ofFn bits)))) (g i)) : + SameLaw (fun bits : Fin (N*CompanionObservationQueriesProgram.blockWidth cs)→Bool => + (output (data A cs states w E (List.ofFn bits))).map CompanionPhaseFinishProgram.view) + (fun bits : Fin N→U×V => CompanionPhaseFinishProgram.rationalResult A (pairLabels A) states old + (List.ofFn (fun i => (f i (bits i).1,g i (bits i).2)))) := by + have h := (CompanionObservationQueriesProgram.sameLaw cs + (fun i => encodeSet (coordinateOrder A) (states i)) f g hf hg).map + (CompanionPhaseFinishProgram.rationalResult A (pairLabels A) states old) + intro phi + simp_rw [output_values A cs states old w E hw hE] + exact h phi + +open GridBoundary CommonBasesFPRAS CompanionWeightOracle CompanionOracleDensity + +/-- The complete executed observation-and-update has the actual phase law. -/ +theorem sameLaw_phase (C K j : ℕ) + (hC : 0 < C) (hj : j+1 ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth nextDegree nextDepth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (hnextDegree : nextDegree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) (j+1)))) + (hnextDepth : nextDepth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) (j+1)))) + (states : Fin N→Set (Labels A×Bool)) (old : CompanionPhaseWords.Stored A) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (E : TreeFraction.Fraction) + (hw : ∀ i j,TreeFraction.val (w i j)=old.multiplier (pair (pairLabels A i)) (pair (pairLabels A j))) + (hE : TreeFraction.val E=old.estimate) : + let cs := CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth + SameLaw (fun bits : Fin (N*CompanionObservationQueriesProgram.blockWidth cs)→Bool => + (output (data A cs states w E (List.ofFn bits))).map CompanionPhaseFinishProgram.view) + (fun bits : Fin (CompanionPhaseWords.phaseBits A C K j N xi)→Bool => + (RootedPhaseWords.update A (RootedCompletion.rowColumn A.T) C K j N hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old states bits).map + (CompanionPhaseFinishProgram.storedView A (pairLabels A))) := by + let cs := CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth + let f := fun i : Fin N => RootedWeightOracle.evaluate A (RootedCompletion.rowColumn A.T) + C K hK hW j xi (RootedCatalogGrid.gridEquiv A K v) (states i) + let g := fun i : Fin N => RootedWeightOracle.evaluate A (RootedCompletion.rowColumn A.T) + C K hK hW (j+1) xi (RootedCatalogGrid.gridEquiv A K v) (states i) + have h := sameLaw A cs states old w E hw hE f g + (fun i => CompanionObservationQueriesProgram.sameLaw_query A C K j hC (by omega) + hK hW hB xi hxi z v degree depth hdegree hdepth (states i)) + (fun i => CompanionObservationQueriesProgram.sameLaw_query A C K (j+1) hC hj + hK hW hB xi hxi z v nextDegree nextDepth hnextDegree hnextDepth (states i)) + dsimp only + intro phi + have he := uniformAverage_equiv (CompanionPhaseWords.phaseWordEquiv A C K j N xi) + (fun xs => phi (CompanionPhaseFinishProgram.rationalResult A (pairLabels A) states old + (List.ofFn (fun i => (f i (xs i).1,g i (xs i).2))))) + have hr : CommonBasesFPRAS.uniformAverage + (fun bits : Fin (CompanionPhaseWords.phaseBits A C K j N xi)→Bool => + phi (CompanionPhaseFinishProgram.rationalResult A (pairLabels A) states old + (List.ofFn (fun i => + (f i (CompanionPhaseWords.phaseWordEquiv A C K j N xi bits i).1, + g i (CompanionPhaseWords.phaseWordEquiv A C K j N xi bits i).2)))))= + CommonBasesFPRAS.uniformAverage (fun bits : Fin (CompanionPhaseWords.phaseBits A C K j N xi)→Bool => + phi ((RootedPhaseWords.update A (RootedCompletion.rowColumn A.T) C K j N hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old states bits).map + (CompanionPhaseFinishProgram.storedView A (pairLabels A)))) := by + apply congrArg CommonBasesFPRAS.uniformAverage + funext bits + exact congrArg phi (CompanionPhaseFinishProgram.rationalResult_phase A (pairLabels A) + (RootedCompletion.rowColumn A.T) C K j hK hW xi (RootedCatalogGrid.gridEquiv A K v) old states bits) + exact (h phi).trans (he.symm.trans hr) + +end +end ContingencyTables.CompanionObservedUpdateProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservedUpdateProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservedUpdateProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3b0362435cc6a373a6080276cf8c143fc1ee08f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionObservedUpdateProgram.lean @@ -0,0 +1,53 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionObservationQueriesProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseFinishProgram + +namespace OAI + +/-! # Executing a phase update from its trajectory and fresh query word -/ +namespace ContingencyTables.CompanionObservedUpdateProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped +abbrev Base := (CompanionTraceProgram.ReturnInput×CompanionMultiplierMatrixProgram.FractionMatrix)×TreeFraction.Fraction +abbrev Configs := CompanionObservationQueriesProgram.Config×CompanionObservationQueriesProgram.Config +abbrev Input := (Configs×Base)×List Bool + +local instance : Codec Configs := inferInstance +local instance : Codec Base := inferInstance +local instance : Codec (Configs×Base) := inferInstance +local instance : Codec Input := inferInstance + +def queryInput (z : Input) : CompanionObservationQueriesProgram.Input := + (z.1.1,(z.1.2.1.1.2,z.2)) +def queryInputRealizer : Realizer queryInput := + pair (composition first first) + (pair (composition (composition (composition (composition first second) first) first) second) second) +lemma polynomial_queryInput : PolynomialTime queryInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + polynomial_first) polynomial_second) polynomial_second) + +attribute [local irreducible] queryInput + +def finishInput (z : Input) : CompanionPhaseFinishProgram.Input := + (z.1.2,CompanionObservationQueriesProgram.output (queryInput z)) +def finishInputRealizer : Realizer finishInput := + pair (composition first second) + (composition (f := queryInput) (g := CompanionObservationQueriesProgram.output) + queryInputRealizer CompanionObservationQueriesProgram.outputRealizer) +lemma polynomial_finishInput : PolynomialTime finishInputRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_queryInput CompanionObservationQueriesProgram.polynomial_output) + +attribute [local irreducible] finishInput + +def output (z : Input) : Option CompanionPhaseFinishProgram.Stored := + CompanionPhaseFinishProgram.output (finishInput z) +def outputRealizer : Realizer output := + composition (f := finishInput) (g := CompanionPhaseFinishProgram.output) + finishInputRealizer CompanionPhaseFinishProgram.outputRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_finishInput CompanionPhaseFinishProgram.polynomial_output + +end ContingencyTables.CompanionObservedUpdateProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleAcceptance.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..fea76a9be38f61c3c3316b098d2d86e49da2b6d6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleAcceptance.lean @@ -0,0 +1,217 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseOracleError +import OAI.Combinatorics.ContingencyTables.Transport.FiniteRationalThreshold + +namespace OAI + +/-! # Fresh approximate weight calls in one Metropolis acceptance decision -/ + +namespace ContingencyTables.CompanionOracleAcceptance + +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle CompanionRationalUpdates +open CompanionPhaseWords CommonBasesFPRAS GridBoundary FairBits TwoLiftStates +open scoped BigOperators Classical + +noncomputable section + +private lemma ratio_linear_bounds {u v uh vh e : ℝ} + (hu : 0 < u) (hv : 0 < v) (he0 : 0 ≤ e) (he1 : e ≤ 1/4) + (huh : (1-e)*u ≤ uh ∧ uh ≤ (1+e)*u) + (hvh : (1-e)*v ≤ vh ∧ vh ≤ (1+e)*v) : + (1-4*e)*(v/u) ≤ vh/uh ∧ vh/uh ≤ (1+4*e)*(v/u) := by + have huh0 := AnnealingMultipliers.empirical_positive hu he1 huh.1 + have ha0 : 0 ≤ 1-4*e := by linarith + have hp0 : 0 ≤ 1+4*e := by linarith + have hx : 0 < uh/u := div_pos huh0 hu + have hlo : 1-e ≤ uh/u := (le_div_iff₀ hu).mpr huh.1 + have hhi : uh/u ≤ 1+e := (div_le_iff₀ hu).mpr huh.2 + have hyl : 1-e ≤ vh/v := (le_div_iff₀ hv).mpr hvh.1 + have hyu : vh/v ≤ 1+e := (div_le_iff₀ hv).mpr hvh.2 + have hnorm : 1-4*e ≤ (vh/v)/(uh/u) ∧ (vh/v)/(uh/u) ≤ 1+4*e := by + constructor + · rw [le_div_iff₀ hx] + have hm := mul_le_mul_of_nonneg_left hhi ha0 + nlinarith [sq_nonneg e] + · rw [div_le_iff₀ hx] + have hm := mul_le_mul_of_nonneg_left hlo hp0 + have he : 0 ≤ 2*e-4*e^2 := by nlinarith + nlinarith + have hid : ((vh/v)/(uh/u))*(v/u)=vh/uh := by + field_simp [hu.ne',hv.ne',huh0.ne'] + constructor + · simpa only [hid] using mul_le_mul_of_nonneg_right hnorm.1 (div_pos hv hu).le + · simpa only [hid] using mul_le_mul_of_nonneg_right hnorm.2 (div_pos hv hu).le + +private lemma min_one_stability {a r s : ℝ} (ha0 : 0 ≤ a) (ha1 : a ≤ 1) + (h : (1-a)*r ≤ s ∧ s ≤ (1+a)*r) : |min 1 s-min 1 r| ≤ a := by + by_cases hr : r ≤ 1 <;> by_cases hs : s ≤ 1 + · rw [min_eq_right hs,min_eq_right hr,abs_le] + have hm := mul_nonneg ha0 (sub_nonneg.mpr hr) + constructor <;> nlinarith + · rw [min_eq_left (le_of_not_ge hs),min_eq_right hr,abs_le] + have hm := mul_nonneg ha0 (sub_nonneg.mpr hr) + constructor <;> nlinarith + · rw [min_eq_right hs,min_eq_left (le_of_not_ge hr),abs_le] + have hm := mul_nonneg (sub_nonneg.mpr ha1) (sub_nonneg.mpr (le_of_not_ge hr)) + constructor <;> nlinarith + · rw [min_eq_left (le_of_not_ge hs),min_eq_left (le_of_not_ge hr)] + simpa using ha0 + +variable {I J : Type*} [Fintype I] [Fintype J] + +def evaluatedWeight (A : Instance I J) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : Set (Labels A×Bool)) (bits : WeightWord A C K j xi) : ℚ := + rationalMultiplier pairs w S*evaluate A C K hK hW j xi v S bits + +def targetWeight (A : Instance I J) (j : ℕ) (w : Pair A → Pair A → ℚ) + (S : Set (Labels A×Bool)) : ℝ := + (rationalMultiplier pairs w S:ℝ)*CompanionAnnealing.weight A j S + +lemma targetWeight_eq (A : Instance I J) (j : ℕ) (w : Pair A → Pair A → ℚ) + (S : Set (Labels A×Bool)) : targetWeight A j w S= + chainWeight pairs (fun p q => (w p q:ℝ)) (CompanionAnnealing.weight A j) S := by + rw [targetWeight,rationalMultiplier_cast] + rfl + +lemma multiplier_positive (A : Instance I J) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S : Set (Labels A×Bool)) : 0 < rationalMultiplier pairs w S := by + unfold rationalMultiplier + split_ifs + · exact hw _ _ + · norm_num + +lemma targetWeight_positive (A : Instance I J) (j : ℕ) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S : Set (Labels A×Bool)) : 0 < targetWeight A j w S := by + apply mul_pos _ (CompanionAnnealing.weight_positive A j S) + exact_mod_cast multiplier_positive A w hw S + +def acceptance (A : Instance I J) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S T : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K j xi) : ℚ := + min 1 (evaluatedWeight A C K j hK hW xi v w T bits.2/ + evaluatedWeight A C K j hK hW xi v w S bits.1) + +def targetAcceptance (A : Instance I J) (j : ℕ) (w : Pair A → Pair A → ℚ) + (S T : Set (Labels A×Bool)) : ℝ := min 1 (targetWeight A j w T/targetWeight A j w S) + +lemma targetAcceptance_eq (A : Instance I J) (j : ℕ) (w : Pair A → Pair A → ℚ) + (S T : ChainIndex (Γ := Labels A×Bool) pairs) : targetAcceptance A j w S.val T.val= + metropolisAcceptance pairs (fun p q => (w p q:ℝ)) (CompanionAnnealing.weight A j) S T := by + simp only [targetAcceptance,targetWeight_eq,metropolisAcceptance] + +lemma evaluatedWeight_bounds (A : Instance I J) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S : Set (Labels A×Bool)) (bits : WeightWord A C K j xi) + (hg : accurateCall A C K j hK hW xi v S bits) : + (1-(xi:ℝ))*targetWeight A j w S ≤ (evaluatedWeight A C K j hK hW xi v w S bits:ℝ) ∧ + (evaluatedWeight A C K j hK hW xi v w S bits:ℝ) ≤ (1+(xi:ℝ))*targetWeight A j w S := by + have hm : (0:ℝ) ≤ rationalMultiplier pairs w S := by + exact_mod_cast (multiplier_positive A w hw S).le + have hlo := mul_le_mul_of_nonneg_left hg.1 hm + have hhi := mul_le_mul_of_nonneg_left hg.2 hm + simpa only [evaluatedWeight,targetWeight,Rat.cast_mul,mul_left_comm,mul_assoc] using And.intro hlo hhi + +/-- Relative errors in both weight calls cause an absolute acceptance +error at most four times the call tolerance, even across clipping at 1. -/ +theorem acceptance_error (A : Instance I J) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S T : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K j xi) + (hS : accurateCall A C K j hK hW xi v S bits.1) + (hT : accurateCall A C K j hK hW xi v T bits.2) : + |(acceptance A C K j hK hW xi v w S T bits:ℝ)-targetAcceptance A j w S T| ≤ 4*(xi:ℝ) := by + have hb := ratio_linear_bounds (targetWeight_positive A j w hw S) + (targetWeight_positive A j w hw T) (by exact_mod_cast hx0) + (by + have h4 : (4:ℝ)*(xi:ℝ) ≤ 1 := by + exact_mod_cast (show (4:ℚ)*xi ≤ 1 by linarith) + linarith) + (evaluatedWeight_bounds A C K j hK hW xi v w hw S bits.1 hS) + (evaluatedWeight_bounds A C K j hK hW xi v w hw T bits.2 hT) + have hh := min_one_stability (show (0:ℝ) ≤ 4*(xi:ℝ) by exact_mod_cast mul_nonneg (by norm_num : (0:ℚ)≤4) hx0) + (show 4*(xi:ℝ) ≤ 1 by exact_mod_cast (show 4*xi ≤ (1:ℚ) by linarith)) hb + simpa only [acceptance,targetAcceptance,Rat.cast_min,Rat.cast_one,Rat.cast_div] using hh + +lemma acceptance_bounds (A : Instance I J) (C : ℕ) (hC : 0 < C) (K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S T : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K j xi) : + 0 ≤ acceptance A C K j hK hW xi v w S T bits ∧ + acceptance A C K j hK hW xi v w S T bits ≤ 1 := by + have hpos (X : Set (Labels A×Bool)) (b : WeightWord A C K j xi) : + 0 < evaluatedWeight A C K j hK hW xi v w X b := + mul_pos (multiplier_positive A w hw X) + (evaluate_positive A C hC K hK hW hB j hj xi hx0 hx1 v X b) + exact ⟨le_min (by norm_num) (div_pos (hpos T bits.2) (hpos S bits.1)).le,min_le_left _ _⟩ + +lemma targetAcceptance_bounds (A : Instance I J) (j : ℕ) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S T : Set (Labels A×Bool)) : + 0 ≤ targetAcceptance A j w S T ∧ targetAcceptance A j w S T ≤ 1 := by + exact ⟨le_min (by norm_num) + (div_pos (targetWeight_positive A j w hw T) (targetWeight_positive A j w hw S)).le, + min_le_left _ _⟩ + +/-- This is the rounded acceptance probability of the implemented +decision, averaged over its two fresh independent weight-query words. -/ +theorem average_acceptance_error (A : Instance I J) (C : ℕ) (hC : 0 < C) (K j k : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi ≤ 1/4) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (S T : Set (Labels A×Bool)) : + uniformAverage (fun bits : WeightWord A C K j xi × WeightWord A C K j xi => + |(rationalThresholdMass k (acceptance A C K j hK hW xi v w S T bits):ℝ)- + targetAcceptance A j w S T|) ≤ 6*(xi:ℝ)+1/(2:ℝ)^k := by + let goodS := accurateCall A C K j hK hW xi v S + let goodT := accurateCall A C K j hK hW xi v T + have hx1' : xi < 1 := by linarith + have hbad : uniformAverage (fun bits : WeightWord A C K j xi × WeightWord A C K j xi => + if ¬(goodS bits.1 ∧ goodT bits.2) then (1:ℝ) else 0) ≤ (xi:ℝ)+(xi:ℝ) := by + have hs := accurateCall_failure A C hC K j hK hW hB hj xi hx0 hx1' hPL hCheeger v S + have ht := accurateCall_failure A C hC K j hK hW hB hj xi hx0 hx1' hPL hCheeger v T + exact @independent_pair_failure (WeightWord A C K j xi) (WeightWord A C K j xi) + inferInstance inferInstance inferInstance inferInstance goodS goodT (xi:ℝ) (xi:ℝ) hs ht + have hpoint (bits : WeightWord A C K j xi × WeightWord A C K j xi) : + |(rationalThresholdMass k (acceptance A C K j hK hW xi v w S T bits):ℝ)-targetAcceptance A j w S T| ≤ + (4*(xi:ℝ)+1/(2:ℝ)^k)+(if ¬(goodS bits.1 ∧ goodT bits.2) then 1 else 0) := by + let q := acceptance A C K j hK hW xi v w S T bits + have hq := acceptance_bounds A C hC K j hK hW hB hj xi hx0 hx1' v w hw S T bits + have hr := rationalThreshold_error k q hq.1 + have hnon : (0:ℝ) ≤ (q:ℝ)-(rationalThresholdMass k q:ℝ) := by exact_mod_cast sub_nonneg.mpr hr.2.1 + have hround : |(rationalThresholdMass k q:ℝ)-(q:ℝ)| ≤ 1/(2:ℝ)^k := by + rw [abs_sub_comm,abs_of_nonneg hnon] + have hc : ((q-rationalThresholdMass k q:ℚ):ℝ) ≤ ((1/(2:ℚ)^k:ℚ):ℝ) := + Rat.cast_le.mpr hr.2.2.le + simpa only [Rat.cast_sub,Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] using hc + have htriangle := abs_add_le ((rationalThresholdMass k q:ℝ)-(q:ℝ)) + ((q:ℝ)-targetAcceptance A j w S T) + have hcancel : (rationalThresholdMass k q:ℝ)-(q:ℝ)+((q:ℝ)-targetAcceptance A j w S T)= + (rationalThresholdMass k q:ℝ)-targetAcceptance A j w S T := by ring + rw [hcancel] at htriangle + by_cases hg : goodS bits.1 ∧ goodT bits.2 + · have herr := acceptance_error A C K j hK hW xi hx0.le hx1 v w hw S T bits hg.1 hg.2 + simpa [q,hg,add_comm] using htriangle.trans (add_le_add hround herr) + · have ht := targetAcceptance_bounds A j w hw S T + have hdiff : |(q:ℝ)-targetAcceptance A j w S T| ≤ 1 := by + have hqR : (0:ℝ) ≤ q ∧ (q:ℝ) ≤ 1 := by exact_mod_cast hq + exact abs_le.mpr ⟨by linarith,by linarith⟩ + simp only [hg,not_false_eq_true,ite_true] + have hxR : (0:ℝ) ≤ xi := by exact_mod_cast hx0.le + linarith [htriangle] + have hh := uniformAverage_mono _ _ hpoint + rw [uniformAverage_add,uniformAverage_const] at hh + linarith + +end + +end ContingencyTables.CompanionOracleAcceptance + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleBudget.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleBudget.lean new file mode 100644 index 0000000000000000000000000000000000000000..56bde1bd29c6a4c3412495072043337a13df66de --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleBudget.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleMixing + +namespace OAI + +/-! # The explicit finite mixing schedule of the companion evaluator -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma oracle_min_mass_exponential (A : Instance I J) (C a : ℝ) + (ha : 0 ≤ a) (haH : a ≤ height A C) {K : ℕ} (hK : 1 ≤ K) : + Real.exp (-(height A C+(A.d:ℝ)*K)) ≤ (2:ℝ)^(-a)/(K:ℝ)^dimension A := by + have hKR : (0:ℝ) < K := by exact_mod_cast (show 0 < K by omega) + have hl2 : Real.log 2 ≤ 1 := by + linarith [Real.log_le_sub_one_of_pos (by norm_num : (0:ℝ) < 2)] + have hlK : Real.log (K:ℝ) ≤ K := by + linarith [Real.log_le_sub_one_of_pos hKR] + have hdim : (dimension A:ℝ) ≤ A.d := by + exact_mod_cast ForestScaledPenalty.free_card_le A + have hsum : a*Real.log 2+(dimension A:ℝ)*Real.log (K:ℝ) ≤ + height A C+(A.d:ℝ)*K := by + have h1 := mul_le_mul_of_nonneg_left hl2 ha + have h2 := mul_le_mul_of_nonneg_left hlK (Nat.cast_nonneg (dimension A): (0:ℝ) ≤ dimension A) + have h3 := mul_le_mul_of_nonneg_right hdim hKR.le + linarith + have hpow : (K:ℝ)^dimension A=Real.exp ((dimension A:ℝ)*Real.log (K:ℝ)) := by + rw [Real.exp_nat_mul,Real.exp_log hKR] + rw [Real.rpow_def_of_pos (by norm_num : (0:ℝ)<2),hpow,←Real.exp_sub] + apply Real.exp_le_exp.mpr + linarith + +/-- The source uses a linear reciprocal-error allowance inside the +mixing time, avoiding any unimplemented logarithm computation. -/ +def oracleTime (A : Instance I J) (C : ℝ) (K Q : ℕ) (theta : ℝ) : ℕ := + ⌈mixingConstant A K*(height A C+(A.d:ℝ)*K+16*Q/theta+2)⌉₊ + +lemma oracle_time_error (A : Instance I J) (C a theta : ℝ) + (ha : 0 ≤ a) (haH : a ≤ height A C) (htheta : 0 < theta) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) : + Real.exp (-(oracleTime A C K Q theta:ℝ)/mixingConstant A K)/ + ((2:ℝ)^(-a)/(K:ℝ)^dimension A) ≤ theta/(8*Q) := by + have hM : 0 < mixingConstant A K := lt_of_lt_of_le (by norm_num) (mixingConstant_ge_one A hK) + have hQR : (0:ℝ) < Q := by exact_mod_cast hQ + have htime : height A C+(A.d:ℝ)*K+16*Q/theta+2 ≤ + (oracleTime A C K Q theta:ℝ)/mixingConstant A K := by + apply (le_div_iff₀ hM).mpr + rw [mul_comm] + exact Nat.le_ceil _ + have hr : (0:ℝ) < 16*Q/theta+2 := by positivity + have hexp : Real.exp (-(16*Q/theta+2)) ≤ 1/(16*Q/theta+2) := by + rw [Real.exp_neg] + have hh : 16*Q/theta+2 ≤ Real.exp (16*Q/theta+2) := by + linarith [Real.add_one_le_exp (16*Q/theta+2)] + simpa only [one_div] using one_div_le_one_div_of_le hr hh + have hrecip : 1/(16*Q/theta+2) ≤ theta/(8*Q) := by + rw [div_le_div_iff₀ hr (by positivity : (0:ℝ)<8*Q)] + have hcancel : (16*Q/theta)*theta=16*Q := div_mul_cancel₀ _ htheta.ne' + nlinarith + calc + _ ≤ Real.exp (-(oracleTime A C K Q theta:ℝ)/mixingConstant A K)/ + Real.exp (-(height A C+(A.d:ℝ)*K)) := + div_le_div_of_nonneg_left (Real.exp_pos _).le (Real.exp_pos _) + (oracle_min_mass_exponential A C a ha haH hK) + _ = Real.exp (-(oracleTime A C K Q theta:ℝ)/mixingConstant A K+ + (height A C+(A.d:ℝ)*K)) := by rw [←Real.exp_sub]; congr 1; ring + _ ≤ Real.exp (-(16*Q/theta+2)) := Real.exp_le_exp.mpr (by simp only [neg_div]; linarith) + _ ≤ theta/(8*Q) := hexp.trans hrecip + +/-- The actual dyadic Metropolis chain attains the per-draw error used +in the evaluator's union bound at the explicit finite source schedule. -/ +theorem oracleChain_scheduled_point_mixing (A : Instance I J) (C a theta : ℝ) + (hC : 0 < C) (ha : 0 ≤ a) (haH : a ≤ height A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v w : Grid (I := Fin (dimension A)) K) : + |(oracleChain A C a z hK).iterate (oracleTime A C K Q theta) + ((oracleChain A C a z hK).pointDensity w) v-1| ≤ theta/(8*Q) := + (oracleChain_point_mixing A C a hC ha haH z hz hK hKB hPL hCheeger _ v w).trans + (oracle_time_error A C a theta ha haH htheta K Q hK hQ) + +theorem oracleChain_scheduled_total_variation (A : Instance I J) (C a theta : ℝ) + (hC : 0 < C) (ha : 0 ≤ a) (haH : a ≤ height A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (w : Grid (I := Fin (dimension A)) K) : + let P := oracleChain A C a z hK + (∑ v, |P.π v*P.iterate (oracleTime A C K Q theta) (P.pointDensity w) v-P.π v|)/2 ≤ + theta/(8*Q) := by + let P := oracleChain A C a z hK + have hpoint (v : Grid (I := Fin (dimension A)) K) : + |P.π v*P.iterate (oracleTime A C K Q theta) (P.pointDensity w) v-P.π v| ≤ + P.π v*(theta/(8*Q)) := by + calc + _ = P.π v*|P.iterate (oracleTime A C K Q theta) (P.pointDensity w) v-1| := by + rw [←mul_sub_one,abs_mul,abs_of_pos (P.positive v)] + _ ≤ _ := mul_le_mul_of_nonneg_left + (oracleChain_scheduled_point_mixing A C a theta hC ha haH htheta z hz K Q hK hQ + hKB hPL hCheeger v w) (P.positive v).le + have hsum := Finset.sum_le_sum (fun v (_ : v∈Finset.univ) => hpoint v) + rw [←Finset.sum_mul,P.normalized,one_mul] at hsum + change _ ≤ theta/(8*Q) + have he : (0:ℝ) ≤ theta/(8*Q) := by positivity + linarith + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleChain.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..8beaa131b0ac95b42c39abf6f2a3301416603405 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleChain.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleCut +import OAI.Combinatorics.ContingencyTables.Dense.GridCutFlow +import OAI.Combinatorics.ContingencyTables.Dense.GridMetropolis + +namespace OAI + +/-! # The actual finite bin chain for the companion evaluator -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CommonBasesFPRAS GridBoundary CompanionFactorialApplication +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- The dyadic proposal is valid already at `d = 1`, including the +zero-dimensional grid. -/ +lemma proposal_bounds (d : ℕ) (hd : 1 ≤ d) : + 0 < binProposal d ∧ 1/(16*(d:ℝ)) ≤ binProposal d ∧ + binProposal d ≤ 1/(8*(d:ℝ)) := by + have hd0 : (0:ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hn : 1 < 8*d := by omega + have hlo := Nat.le_pow_clog (by decide : 1 < 2) (8*d) + have hpred := Nat.pow_pred_clog_lt_self (by decide : 1 < 2) hn + have hpos := Nat.clog_pos (by decide : 1 < 2) hn + have hhi : 2^Nat.clog 2 (8*d) ≤ 16*d := by + have he : 2^Nat.clog 2 (8*d) = 2^(Nat.clog 2 (8*d)).pred*2 := by + conv_lhs => rw [←Nat.succ_pred_eq_of_pos hpos] + exact pow_succ _ _ + rw [he] + omega + have hloR : 8*(d:ℝ) ≤ (2:ℝ)^Nat.clog 2 (8*d) := by exact_mod_cast hlo + have hhiR : (2:ℝ)^Nat.clog 2 (8*d) ≤ 16*(d:ℝ) := by exact_mod_cast hhi + refine ⟨by unfold binProposal; positivity,?_,?_⟩ + · exact one_div_le_one_div_of_le (by positivity) hhiR + · exact one_div_le_one_div_of_le (by positivity) hloR + +lemma proposal_degree (A : Instance I J) : + ((2*dimension A:ℕ):ℝ)*binProposal A.d ≤ 1/4 := by + have hd : (0:ℝ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + have he : (dimension A:ℝ) ≤ A.d := by exact_mod_cast ForestScaledPenalty.free_card_le A + calc + _ ≤ (2*(dimension A:ℝ))*(1/(8*(A.d:ℝ))) := by + push_cast + exact mul_le_mul_of_nonneg_left (proposal_bounds A.d A.hd).2.2 (by positivity) + _ ≤ (2*(A.d:ℝ))*(1/(8*(A.d:ℝ))) := by gcongr + _ = 1/4 := by field_simp; ring + +def gridWeight (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℝ := V A C a z (realCorner v) + +def oracleChain (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) : FiniteChain (Grid (I := Fin (dimension A)) K) := by + letI : Nonempty (Grid (I := Fin (dimension A)) K) := + ⟨fun _ => ⟨0,by constructor <;> omega⟩⟩ + exact MetropolisChain.chain (gridWeight A C a z) (fun _ => DenseWeights.binWeight_pos _ _ _) + Neighbor neighbor_symm (binProposal A.d) (proposal_bounds A.d A.hd).1.le + (2*dimension A) (fun v => by simpa using neighbor_degree v) + ((proposal_degree A).trans (by norm_num)) + +lemma oracleChain_pi (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v : Grid (I := Fin (dimension A)) K) : + (oracleChain A C a z hK).π v = gridWeight A C a z v/ + ∑ w : Grid (I := Fin (dimension A)) K,gridWeight A C a z w := rfl + +def cutConstant (A : Instance I J) (K : ℕ) : ℝ := binProposal A.d/(128*(A.d:ℝ)*K) + +private lemma corner_injective {q K : ℕ} : + Function.Injective (corner (I := Fin q) (K := K)) := by + intro a b h + funext i + exact Subtype.ext (congrFun h i) + +/-- All geometric cut obligations are discharged for the literal forest +penalty. Only finite-box PL and finite-chain Cheeger remain conditional. -/ +theorem oracleChain_poincare (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) : + ∀ f, (oracleChain A C a z hK).variance f ≤ + (2/(cutConstant A K)^2)*(oracleChain A C a z hK).energy f := by + classical + let : DecidableEq (Grid (I := Fin (dimension A)) K) := Classical.decEq _ + let : Nonempty (Grid (I := Fin (dimension A)) K) := + ⟨fun _ => ⟨0,by constructor <;> omega⟩⟩ + let w := gridWeight A C a z (K := K) + have hw : ∀ v,0 < w v := fun _ => DenseWeights.binWeight_pos _ _ _ + have hd : (0:ℝ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + have hKR : (0:ℝ) < K := by exact_mod_cast (show 0 < K by omega) + have hb := (proposal_bounds A.d A.hd).1 + have hk : 0 < cutConstant A K := by unfold cutConstant; positivity + apply MetropolisChain.poincare_of_weighted_cut w hw Neighbor neighbor_symm + (binProposal A.d) hb.le (2*dimension A) (fun v => by simpa using neighbor_degree v) + ((proposal_degree A).trans (by norm_num)) hCheeger (cutConstant A K) hk + intro S + change cutConstant A K*min (∑ v ∈ S,w v) (∑ v ∈ Sᶜ,w v) ≤ + binProposal A.d*(∑ v ∈ S,∑ u ∈ Sᶜ,if Neighbor v u then min (w v) (w u) else 0) + have hS : 0 ≤ ∑ v ∈ S,w v := Finset.sum_nonneg (fun _ _ => (hw _).le) + have hSc : 0 ≤ ∑ v ∈ Sᶜ,w v := Finset.sum_nonneg (fun _ _ => (hw _).le) + by_cases hs : S.Nonempty + · by_cases hsc : Sᶜ.Nonempty + · let Q : (Fin (dimension A) → ℤ) → Prop := fun x => ∃ v ∈ S,corner v=x + have hQ (v : Grid (I := Fin (dimension A)) K) : Q (corner v) ↔ v∈S := by + constructor + · rintro ⟨u,hu,he⟩ + exact corner_injective he ▸ hu + · intro hv + exact ⟨v,hv,rfl⟩ + have hne : Nonempty (Selected K Q) := by + obtain ⟨v,hv⟩ := hs + exact ⟨⟨v,(hQ v).mpr hv⟩⟩ + have hne' : Nonempty (Selected K (fun x => ¬Q x)) := by + obtain ⟨v,hv⟩ := hsc + exact ⟨⟨v,fun h => (Finset.mem_compl.mp hv) ((hQ v).mp h)⟩⟩ + have hcut := weighted_min_cut A C a hC ha haH z K hK hPL Q hne hne' + change (1/(128*(A.d:ℝ)*K))* + min (∑ v : Selected K Q,w v.val) (∑ v : Selected K (fun x => ¬Q x),w v.val) ≤ + ∑ e : CutEdge K Q,min (w e.val.1) (w e.val.2.1) at hcut + have hsum : (∑ v : Selected K Q,w v.val)=∑ v∈S,w v := by + rw [selected_sum_eq_filter Q w] + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext v + simp only [Finset.mem_filter,Finset.mem_univ,true_and,hQ] + have hsum' : (∑ v : Selected K (fun x => ¬Q x),w v.val)=∑ v∈Sᶜ,w v := by + rw [selected_sum_eq_filter (fun x => ¬Q x) w] + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext v + simp only [Finset.mem_filter,Finset.mem_univ,true_and,hQ,Finset.mem_compl] + rw [hsum,hsum'] at hcut + have hflow := cut_faces_le_neighbor_flow Q w (fun v => (hw v).le) + have hflow' : (∑ e : CutEdge K Q,min (w e.val.1) (w e.val.2.1)) ≤ + ∑ v∈S,∑ u∈Sᶜ,if Neighbor v u then min (w v) (w u) else 0 := by + convert hflow using 1 + apply Finset.sum_congr ?_ ?_ + · ext v + simp only [Finset.mem_filter,Finset.mem_univ,true_and,hQ] + · intro v _ + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext u + simp only [Finset.mem_filter,Finset.mem_univ,true_and,hQ,Finset.mem_compl] + calc + _ = binProposal A.d*((1/(128*(A.d:ℝ)*K))*min (∑ v∈S,w v) (∑ v∈Sᶜ,w v)) := by + unfold cutConstant + ring + _ ≤ _ := mul_le_mul_of_nonneg_left (hcut.trans hflow') hb.le + · have he : Sᶜ=∅ := Finset.not_nonempty_iff_eq_empty.mp hsc + rw [he] + simp only [Finset.sum_empty,min_eq_right hS,mul_zero,Finset.sum_const_zero] + exact le_rfl + · have he : S=∅ := Finset.not_nonempty_iff_eq_empty.mp hs + rw [he] at hSc ⊢ + simp only [Finset.sum_empty,min_eq_left hSc,mul_zero] + exact le_rfl + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleCorrection.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleCorrection.lean new file mode 100644 index 0000000000000000000000000000000000000000..131b2ed07a28ece1c22f90fcc302465f21370e21 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleCorrection.lean @@ -0,0 +1,231 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleMixing +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBinPopulation +import OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledIdentification + +namespace OAI + +/-! # Exact population correction for the literal companion weight -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit ForestScaledPenalty GridBoundary +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def integerPoint (A : Instance I J) (C : ℝ) (f : FreeIndex A.small A.T A.b) : + Fin (dimension A) → ℝ := fun i => integerCube A (binWidth A C) f (index A i) + +lemma pull_integerPoint (A : Instance I J) (C : ℝ) (f : FreeIndex A.small A.T A.b) : + pull A (integerPoint A C f)=integerCube A (binWidth A C) f := by + funext t + simp only [pull,integerPoint,Equiv.apply_symm_apply] + +/-- The continuous evaluator density at every integer assignment is the +original summand defining the manuscript's h. -/ +lemma density_at_integer (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (z : View A → ℕ) (f : FreeIndex A.small A.T A.b) : + rho A C a z (integerPoint A C f)= + (2:ℝ)^(-(a*C/height A C)*ForestPenaltyBound.penalty A z f) := by + unfold rho DenseWeights.density D + rw [pull_integerPoint] + change (2:ℝ)^(-(a/height A C*penalty A C (binWidth A C) + (fun i j => (ForestCountIdentification.smallX A.small z i j:ℤ)) + (fun i j => ((A.b i j-ForestCountIdentification.smallY A.small z i j:ℕ):ℤ)) + (integerCube A (binWidth A C) f)))=_ + rw [penalty_at_integer A C (binWidth A C) (binWidth_positive A C hC)] + congr 1 + ring + +lemma sum_density_integer (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (z : View A → ℕ) : + (∑ f : FreeIndex A.small A.T A.b,rho A C a z (integerPoint A C f))= + h A (a*C/height A C) z := by + unfold h ForestCountIdentification.sourceMarginal + apply Finset.sum_congr rfl + intro f _ + exact density_at_integer A C a hC z f + +def integerBin (A : Instance I J) (K : ℕ) (hK : 0 < K) + (f : FreeIndex A.small A.T A.b) : Grid (I := Fin (dimension A)) K := fun i => + let t := index A i + ⟨(FairBits.scale K (A.b t.val.1 t.val.2+1) (f t).val:ℤ),by + constructor + · positivity + · have hh := FairBits.scale_lt hK (Nat.succ_pos _) (f t).isLt + have hhZ : (FairBits.scale K (A.b t.val.1 t.val.2+1) (f t).val:ℤ) integerBin A K hK f=v) + +lemma ownFiber_positive (A : Instance I J) (K : ℕ) (hK : 0 < K) + (f : FreeIndex A.small A.T A.b) : + 0 < (integerFiber A K hK (integerBin A K hK f)).card := by + apply Finset.card_pos.mpr + exact ⟨f,by simp [integerFiber]⟩ + +def binSum (A : Instance I J) (C a : ℝ) (z : View A → ℕ) (K : ℕ) : ℝ := + ∑ v : Grid (I := Fin (dimension A)) K,gridWeight A C a z v + +lemma binSum_positive (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) : 0 < binSum A C a z K := by + let : Nonempty (Grid (I := Fin (dimension A)) K) := + ⟨fun _ => ⟨0,by constructor <;> omega⟩⟩ + exact Finset.sum_pos (fun _ _ => DenseWeights.binWeight_pos _ _ _) Finset.univ_nonempty + +def assignmentCount (A : Instance I J) : ℕ := Fintype.card (FreeIndex A.small A.T A.b) + +lemma assignmentCount_positive (A : Instance I J) : 0 < assignmentCount A := by + let : Nonempty (FreeIndex A.small A.T A.b) := ⟨fun _ => 0⟩ + exact Fintype.card_pos + +def correctedMass (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : ℝ := + gridWeight A C a z (integerBin A K hK f)/binSum A C a z K/ + (integerFiber A K hK (integerBin A K hK f)).card + +def correction (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : ℝ := + ((K:ℝ)^dimension A*(integerFiber A K hK (integerBin A K hK f)).card/assignmentCount A)* + rho A C a z (integerPoint A C f)/gridWeight A C a z (integerBin A K hK f) + +/-- Population correction cancels the bin size and bin weight exactly, +before taking any expectation or approximation. -/ +lemma corrected_mass_product (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : + correctedMass A C a z K hK f*correction A C a z K hK f= + ((K:ℝ)^dimension A/(assignmentCount A*binSum A C a z K))* + rho A C a z (integerPoint A C f) := by + have hweight : gridWeight A C a z (integerBin A K hK f)≠0 := + (DenseWeights.binWeight_pos _ _ _).ne' + have hfiber : ((integerFiber A K hK (integerBin A K hK f)).card:ℝ)≠0 := by + exact_mod_cast (ownFiber_positive A K hK f).ne' + have hc : (assignmentCount A:ℝ)≠0 := by exact_mod_cast (assignmentCount_positive A).ne' + have hz := (binSum_positive A C a z K hK).ne' + unfold correctedMass correction + field_simp [hweight,hfiber,hc,hz] + +/-- The exact corrected mean contains the literal original free-assignment +sum, not a continuous integral or a surrogate count. -/ +theorem corrected_expectation (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (z : View A → ℕ) (K : ℕ) (hK : 0 < K) : + (∑ f : FreeIndex A.small A.T A.b, + correctedMass A C a z K hK f*correction A C a z K hK f)= + ((K:ℝ)^dimension A/(assignmentCount A*binSum A C a z K))* + h A (a*C/height A C) z := by + simp_rw [corrected_mass_product] + rw [←Finset.mul_sum,sum_density_integer A C a hC] + +def ratioObservable (A : Instance I J) (C : ℝ) (a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℝ := + gridWeight A C (a+1) z v/gridWeight A C a z v + +def ratioMean (A : Instance I J) (C : ℝ) (a : ℕ) (z : View A → ℕ) (K : ℕ) : ℝ := + ∑ v : Grid (I := Fin (dimension A)) K, + (gridWeight A C a z v/binSum A C a z K)*ratioObservable A C a z v + +private lemma floor_step (x q : ℝ) (hq0 : 0 ≤ q) (hq1 : q ≤ 1) : + ⌊x+q⌋=⌊x⌋ ∨ ⌊x+q⌋=⌊x⌋+1 := by + have hlo := Int.floor_mono (show x ≤ x+q by linarith) + have hhi := Int.floor_mono (show x+q ≤ x+1 by linarith) + rw [Int.floor_add_one] at hhi + omega + +/-- The actual phase observable takes exactly the two source values, +since one annealing step changes its integer exponent by zero or one. -/ +theorem ratioObservable_cases (A : Instance I J) (C : ℝ) (hC : 0 < C) + (a : ℕ) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) (v : Grid (I := Fin (dimension A)) K) : + ratioObservable A C a z v=1 ∨ ratioObservable A C a z v=1/2 := by + have hD := D_bounds A C hC z hz (realCorner v) (by + intro i + constructor + · change (0:ℝ) ≤ ((v i).val:ℝ) + exact_mod_cast (v i).property.1 + · have hh : (realCorner v i:ℝ) ≤ K := by + change ((v i).val:ℝ) ≤ K + exact_mod_cast (show (v i).val ≤ (K:ℤ) by have hh := (v i).property.2; omega) + exact hh.trans hKB) + let q := D A C z (realCorner v)/height A C + have hq0 : 0 ≤ q := div_nonneg hD.1 (height_positive A C hC).le + have hq1 : q ≤ 1 := (div_le_one (height_positive A C hC)).mpr hD.2 + let x := (a:ℝ)/height A C*D A C z (realCorner v) + have he : ((a:ℝ)+1)/height A C*D A C z (realCorner v)=x+q := by + dsimp only [x,q] + ring + have hr : ratioObservable A C a z v=(2:ℝ)^(-((⌊x+q⌋:ℤ):ℝ)+((⌊x⌋:ℤ):ℝ)) := by + unfold ratioObservable gridWeight V DenseWeights.binWeight + rw [he,←Real.rpow_sub (by norm_num : (0:ℝ)<2)] + congr 1 + change -((⌊x+q⌋:ℤ):ℝ)- -((⌊x⌋:ℤ):ℝ)=_ + ring + rcases floor_step x q hq0 hq1 with hf|hf + · left + rw [hr,hf] + simp + · right + rw [hr,hf] + have hh : -(((⌊x⌋:ℤ)+1:ℤ):ℝ)+((⌊x⌋:ℤ):ℝ)=(-1:ℝ) := by + push_cast + ring + rw [hh] + norm_num + +lemma ratioMean_eq (A : Instance I J) (C : ℝ) (a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) : + ratioMean A C a z K=binSum A C (a+1) z K/binSum A C a z K := by + unfold ratioMean binSum + rw [Finset.sum_div] + apply Finset.sum_congr rfl + intro v _ + have hv : gridWeight A C a z v≠0 := (DenseWeights.binWeight_pos _ _ _).ne' + have hZ := (binSum_positive A C a z K hK).ne' + unfold ratioObservable + change (gridWeight A C a z v/binSum A C a z K)* + (gridWeight A C (a+1) z v/gridWeight A C a z v)= + gridWeight A C (a+1) z v/binSum A C a z K + field_simp [hv,hZ] + +lemma binSum_zero (A : Instance I J) (C : ℝ) (z : View A → ℕ) (K : ℕ) : + binSum A C 0 z K=(K:ℝ)^dimension A := by + simp only [binSum,gridWeight,V,DenseWeights.binWeight,zero_div,zero_mul,Int.floor_zero, + Int.cast_zero,neg_zero,Real.rpow_zero,Finset.sum_const,Finset.card_univ,nsmul_eq_mul, + mul_one,oracle_grid_card,Nat.cast_pow] + +lemma ratio_telescope (A : Instance I J) (C : ℝ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (j : ℕ) : + (∏ a∈Finset.range j,ratioMean A C a z K)=binSum A C j z K/(K:ℝ)^dimension A := by + have hp : (K:ℝ)^dimension A≠0 := pow_ne_zero _ (by exact_mod_cast hK.ne') + induction j with + | zero => simp only [Finset.range_zero,Finset.prod_empty,Nat.cast_zero,binSum_zero,div_self hp] + | succ j ih => + rw [Finset.prod_range_succ,ih,ratioMean_eq A C j z K hK] + have hZ := (binSum_positive A C j z K hK).ne' + push_cast + field_simp [hp,hZ] + +/-- The original h-value is exactly the product of the actual stationary +ratio means and the integer-population correction mean. -/ +theorem oracle_telescope (A : Instance I J) (C : ℝ) (hC : 0 < C) + (z : View A → ℕ) (K : ℕ) (hK : 0 < K) (j : ℕ) : + (assignmentCount A:ℝ)*(∏ a∈Finset.range j,ratioMean A C a z K)* + (∑ f : FreeIndex A.small A.T A.b, + correctedMass A C j z K hK f*correction A C j z K hK f)= + h A ((j:ℝ)*C/height A C) z := by + rw [ratio_telescope A C z K hK j,corrected_expectation A C j hC z K hK] + have hp : (K:ℝ)^dimension A≠0 := pow_ne_zero _ (by exact_mod_cast hK.ne') + have hZ := (binSum_positive A C j z K hK).ne' + have hc : (assignmentCount A:ℝ)≠0 := by exact_mod_cast (assignmentCount_positive A).ne' + field_simp [hp,hZ,hc] + + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleCut.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..3366ffc564bd578be74ee3f73bcfa833dbe1a023 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleCut.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleDensity +import OAI.Combinatorics.ContingencyTables.Dense.GridMinCut + +namespace OAI + +/-! # Actual weighted bin-cut bound for the companion evaluator -/ + +namespace ContingencyTables.CompanionOracleDensity + +open scoped BigOperators Classical +open CompanionFactorialApplication GridBoundary + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma closedBin_distances (A : Instance I J) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) + (x : Fin (dimension A) → ℝ) (hx : ClosedBin (corner v) x) : + ∀ i,|x i-realCorner v i| ≤ 1 := by + intro i + change |x i-(corner v i:ℝ)| ≤ 1 + apply abs_le.mpr + constructor <;> linarith [(hx i).1,(hx i).2] + +lemma tube_distances (A : Instance I J) {K : ℕ} {Q : (Fin (dimension A) → ℤ) → Prop} + (edge : CutEdge K Q) (r : ℝ) (x : Fin (dimension A) → ℝ) (hx : x ∈ edgeTube edge r) : + (∀ i,|x i-realCorner edge.val.1 i| ≤ 1+r) ∧ + (∀ i,|x i-realCorner edge.val.2.1 i| ≤ 1+r) := by + have hcoord (i : Fin (dimension A)) := hx i (Set.mem_univ i) + constructor + · intro i + have hi := hcoord i + dsimp [tubeLower,tubeUpper] at hi + change |x i-(corner edge.val.1 i:ℝ)| ≤ 1+r + by_cases he : i=edge.val.2.2 + · subst i + simp only [ite_true] at hi + exact abs_le.mpr ⟨by linarith [hi.1],by linarith [hi.2]⟩ + · simp only [ite_eq_right he] at hi + exact abs_le.mpr ⟨by linarith [hi.1],by linarith [hi.2]⟩ + · intro i + have hi := hcoord i + dsimp [tubeLower,tubeUpper] at hi + change |x i-(corner edge.val.2.1 i:ℝ)| ≤ 1+r + by_cases he : i=edge.val.2.2 + · have hadj : (corner edge.val.2.1 i:ℝ)=(corner edge.val.1 i:ℝ)+1 := by + simpa only [he,Int.cast_add,Int.cast_one] using + congrArg (fun z : ℤ => (z:ℝ)) edge.property.1.1 + simp only [ite_eq_left he] at hi + rw [hadj] + exact abs_le.mpr ⟨by linarith [hi.1],by linarith [hi.2]⟩ + · have heq : corner edge.val.2.1 i=corner edge.val.1 i := + congrArg Subtype.val (edge.property.1.2 i he) + simp only [ite_eq_right he] at hi + rw [heq] + exact abs_le.mpr ⟨by linarith [hi.1],by linarith [hi.2]⟩ + +lemma tube_comparison (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + {K : ℕ} {Q : (Fin (dimension A) → ℤ) → Prop} (edge : CutEdge K Q) + (r : ℝ) (hr : 0 ≤ r) (hr1 : r ≤ 1) (x : Fin (dimension A) → ℝ) + (hx : x ∈ edgeTube edge r) : + rho A C a z x ≤ 4*min (V A C a z (realCorner edge.val.1)) + (V A C a z (realCorner edge.val.2.1)) := by + obtain ⟨hlo,hhi⟩ := tube_distances A edge r x hx + rw [mul_min_of_nonneg _ _ (by norm_num : (0:ℝ) ≤ 4)] + apply le_min + · apply DenseWeights.tube_density_comparison + exact (exponent_change A C a hC ha haH z x _ (1+r) (by positivity) hlo).trans (by linarith) + · apply DenseWeights.tube_density_comparison + exact (exponent_change A C a hC ha haH z x _ (1+r) (by positivity) hhi).trans (by linarith) + +lemma interpolation_bounds (d K q : ℕ) (hd : 1 ≤ d) (hK : 1 ≤ K) (hq : q ≤ d) : + 0 < denseInterpolation d K ∧ denseInterpolation d K < 1 ∧ + denseInterpolation d K*K ≤ 1/4 ∧ + (q-1:ℕ)*(2*(denseInterpolation d K*K)) ≤ (1/2:ℝ) := by + have hdR : (1:ℝ) ≤ d := by exact_mod_cast hd + have hKR : (1:ℝ) ≤ K := by exact_mod_cast hK + have hqR : (q-1:ℕ) ≤ (d:ℝ) := by exact_mod_cast (Nat.sub_le q 1).trans hq + have hden : (0:ℝ) < 4*d*K := by positivity + have hr : denseInterpolation d K*K=1/(4*(d:ℝ)) := by + unfold denseInterpolation + field_simp [ne_of_gt (show (0:ℝ) ¬Q x))) : + (1/(128*(A.d:ℝ)*K))*min + (∑ v : Selected K Q,V A C a z (realCorner v.val)) + (∑ v : Selected K (fun x => ¬Q x),V A C a z (realCorner v.val)) ≤ + ∑ e : CutEdge K Q,min (V A C a z (realCorner e.val.1)) + (V A C a z (realCorner e.val.2.1)) := by + obtain ⟨ht,ht1,hr,hsize⟩ := interpolation_bounds A.d K (dimension A) A.hd hK + (ForestScaledPenalty.free_card_le A) + have hh := GridBoundary.weighted_min_cut hPL Q (denseInterpolation A.d K) ht ht1 hr hsize + (rho A C a z) (fun v => V A C a z (realCorner v)) + (fun v => DenseWeights.binWeight_pos _ _ _) (rho_continuous A C a z).continuousOn + (fun x _ => rho_positive A C a z x) + (fun x _ y _ t ht ht1 => rho_logConcave A C a hC ha z x (Set.mem_univ _) y (Set.mem_univ _) t ht ht1) + (fun v x hx => by + have hclosed : ClosedBin (corner v) x := fun i => ⟨(hx i).1.le,(hx i).2.le⟩ + exact (bin_comparison A C a hC ha haH z (realCorner v) x + (fun i => by simpa only [abs_sub_comm] using closedBin_distances A v x hclosed i)).1) + (fun e x hx => tube_comparison A C a hC ha haH z e (denseInterpolation A.d K*K) + (by positivity) (by linarith) x hx.1) hne hne' + have hg := two_rpow_gain (denseInterpolation A.d K) ht.le + have hm : 0 ≤ min (∑ v : Selected K Q,V A C a z (realCorner v.val)) + (∑ v : Selected K (fun x => ¬Q x),V A C a z (realCorner v.val)) := by + apply le_min <;> exact Finset.sum_nonneg (fun _ _ => (DenseWeights.binWeight_pos _ _ _).le) + have he : 1/(128*(A.d:ℝ)*K)=denseInterpolation A.d K/32 := by + unfold denseInterpolation + ring + rw [he] + exact (mul_le_mul_of_nonneg_right (by linarith : denseInterpolation A.d K/32 ≤ + ((2:ℝ)^denseInterpolation A.d K-1)/16) hm).trans hh + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleDensity.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleDensity.lean new file mode 100644 index 0000000000000000000000000000000000000000..c86ea42a5867cd6fae6fb8aff9971d2bc9ad50c1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleDensity.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledBounds +import OAI.Combinatorics.ContingencyTables.Dense.DenseWeights + +namespace OAI + +/-! # The literal weight-evaluator density on its finite-dimensional bin cube -/ + +namespace ContingencyTables.CompanionOracleDensity + +open scoped BigOperators Classical +open CompanionFactorialApplication ForestAssignmentSplit ForestScaledPenalty + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable abbrev dimension (A : Instance I J) := Fintype.card (FreeCell A.small A.T) + +noncomputable def index (A : Instance I J) : Fin (dimension A) ≃ FreeCell A.small A.T := + (Fintype.equivFin _).symm + +noncomputable def pull (A : Instance I J) (v : Fin (dimension A) → ℝ) : FreeCell A.small A.T → ℝ := + fun f => v ((index A).symm f) + +noncomputable def binWidth (A : Instance I J) (C : ℝ) : ℝ := 16*C*(A.d:ℝ)^2 + +noncomputable def height (A : Instance I J) (C : ℝ) : ℝ := 10*C*(A.d:ℝ)^2*((A.W:ℝ)+1) + +noncomputable def D (A : Instance I J) (C : ℝ) (z : View A → ℕ) + (v : Fin (dimension A) → ℝ) : ℝ := + penalty A C (binWidth A C) (rowCounts A z) (columnCounts A z) (pull A v) + +lemma binWidth_positive (A : Instance I J) (C : ℝ) (hC : 0 < C) : 0 < binWidth A C := by + have hd : (0:ℝ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + unfold binWidth + positivity + +lemma height_positive (A : Instance I J) (C : ℝ) (hC : 0 < C) : 0 < height A C := by + have hd : (0:ℝ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + unfold height + positivity + +theorem D_bounds (A : Instance I J) (C : ℝ) (hC : 0 < C) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (v : Fin (dimension A) → ℝ) (hv : ∀ i,0 ≤ v i ∧ v i ≤ binWidth A C) : + 0 ≤ D A C z v ∧ D A C z v ≤ height A C := by + have hh := penalty_cube_bound A C (binWidth A C) hC.le (binWidth_positive A C hC) + z hz (pull A v) (fun f => hv ((index A).symm f)) + refine ⟨hh.1,hh.2.trans_eq ?_⟩ + unfold height + ring + +theorem D_change (A : Instance I J) (C : ℝ) (hC : 0 < C) (z : View A → ℕ) + (v w : Fin (dimension A) → ℝ) (r : ℝ) (hr : 0 ≤ r) + (hvw : ∀ i,|v i-w i| ≤ r) : |D A C z v-D A C z w| ≤ r/8 := by + have hh := penalty_change A C (binWidth A C) hC.le (binWidth_positive A C hC) + (rowCounts A z) (columnCounts A z) (pull A v) (pull A w) r hr + (fun f => hvw ((index A).symm f)) + have hd : (A.d:ℝ) ≠ 0 := by exact_mod_cast (show A.d≠0 by have hh := A.hd; omega) + have he : (2*C*(A.d:ℝ)^2/binWidth A C)*r=r/8 := by + unfold binWidth + field_simp [hC.ne',hd] + ring + simpa only [D,he] using hh + +theorem D_continuous (A : Instance I J) (C : ℝ) (z : View A → ℕ) : Continuous (D A C z) := by + have hpull : Continuous (pull A) := continuous_pi (fun f => continuous_apply ((index A).symm f)) + exact (penalty_continuous A C (binWidth A C) (rowCounts A z) (columnCounts A z)).comp hpull + +theorem D_convex (A : Instance I J) (C : ℝ) (hC : 0 ≤ C) (z : View A → ℕ) : + ConvexOn ℝ Set.univ (D A C z) := by + refine ⟨convex_univ,?_⟩ + intro v _ w _ a b ha hb hab + have hh := (penalty_convex A C (binWidth A C) hC (rowCounts A z) (columnCounts A z)).2 + (Set.mem_univ (pull A v)) (Set.mem_univ (pull A w)) ha hb hab + exact hh + +noncomputable def rho (A : Instance I J) (C a : ℝ) (z : View A → ℕ) : + (Fin (dimension A) → ℝ) → ℝ := DenseWeights.density (a/height A C) (D A C z) + +noncomputable def V (A : Instance I J) (C a : ℝ) (z : View A → ℕ) : + (Fin (dimension A) → ℝ) → ℝ := DenseWeights.binWeight (a/height A C) (D A C z) + +theorem rho_continuous (A : Instance I J) (C a : ℝ) (z : View A → ℕ) : + Continuous (rho A C a z) := DenseWeights.density_continuous _ _ (D_continuous A C z) + +theorem rho_positive (A : Instance I J) (C a : ℝ) (z : View A → ℕ) (v : Fin (dimension A) → ℝ) : + 0 < rho A C a z v := DenseWeights.density_pos _ _ _ + +theorem rho_logConcave (A : Instance I J) (C a : ℝ) (hC : 0 < C) (ha : 0 ≤ a) + (z : View A → ℕ) : PublishedInputs.LogConcaveOn (rho A C a z) Set.univ := + DenseWeights.density_logConcave _ (div_nonneg ha (height_positive A C hC).le) _ _ (D_convex A C hC.le z) + +/-- Every evaluator phase has base-two logarithmic Lipschitz constant +at most 1/8; the bin and cut-tube comparisons now apply to the actual +forest density. -/ +theorem exponent_change (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + (v w : Fin (dimension A) → ℝ) (r : ℝ) (hr : 0 ≤ r) + (hvw : ∀ i,|v i-w i| ≤ r) : + |(a/height A C)*D A C z v-(a/height A C)*D A C z w| ≤ r/8 := by + have hH := height_positive A C hC + have hf0 : 0 ≤ a/height A C := div_nonneg ha hH.le + have hf1 : a/height A C ≤ 1 := (div_le_one hH).mpr haH + rw [← mul_sub,abs_mul,abs_of_nonneg hf0] + exact (mul_le_mul_of_nonneg_left (D_change A C hC z v w r hr hvw) hf0).trans + (mul_le_of_le_one_left (by positivity) hf1) + +theorem bin_comparison (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + (v w : Fin (dimension A) → ℝ) (hvw : ∀ i,|v i-w i| ≤ 1) : + V A C a z v/4 ≤ rho A C a z w ∧ rho A C a z w ≤ 2*V A C a z v := by + have hh := exponent_change A C a hC ha haH z w v 1 (by norm_num) + (fun i => by simpa only [abs_sub_comm] using hvw i) + exact DenseWeights.bin_density_comparison _ _ w v (hh.trans (by norm_num)) + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleDraw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleDraw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8621394067fcc3f685a1662c73f10bcb9b47142 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleDraw.lean @@ -0,0 +1,212 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBinIntervals +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleFiniteStep +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordPadding +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalkApproximation + +namespace OAI + +/-! # Actual bounded Boolean draws for the companion correction experiment -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess FairBits +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma binSize_le_range (A : Instance I J) (K : ℕ) (hK : 0 < K) + (v : Grid (I := Fin (dimension A)) K) (i : Fin (dimension A)) : + binSize A K v i ≤ freeRange A (index A i) := by + have hN : 0 < freeRange A (index A i) := Nat.succ_pos _ + have he := FairBits.fiber_card hK hN (naturalBin_lt A v (index A i)) + have hc : (FairBits.fiber K (freeRange A (index A i)) (naturalBin A v (index A i))).card ≤ + freeRange A (index A i) := by + exact (Finset.card_le_card (Finset.filter_subset _ _)).trans_eq (Finset.card_range _) + rw [he] at hc + exact hc + +abbrev BinWords (A : Instance I J) (h : ℕ) := + (i : Fin (dimension A)) → Fin (offsetBitLength (freeRange A (index A i)) h A.d) → Bool + +def binWordBits (A : Instance I J) (h : ℕ) : ℕ := + ∑ i : Fin (dimension A),offsetBitLength (freeRange A (index A i)) h A.d + +def binWordEquiv (A : Instance I J) (h : ℕ) : + (Fin (binWordBits A h) → Bool) ≃ BinWords A h := + (Equiv.arrowCongr finSigmaFinEquiv.symm (Equiv.refl Bool)).trans (Equiv.piCurry (fun _ _ => Bool)) + +lemma binBits_le (A : Instance I J) (K : ℕ) (hK : 0 < K) + (v : Grid (I := Fin (dimension A)) K) (h : ℕ) (i : Fin (dimension A)) : + offsetBitLength (binSize A K v i) h A.d ≤ + offsetBitLength (freeRange A (index A i)) h A.d := by + unfold offsetBitLength + exact Nat.add_le_add_right (Nat.clog_mono_right 2 + (Nat.add_le_add_right (binSize_le_range A K hK v i) 1)) _ + +def binWordDraw (A : Instance I J) (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (h : ℕ) (bits : BinWords A h) : + FreeIndex A.small A.T A.b := + binOffsetValue A K hK v (fun i => scaledBitInteger (binSize A K v i) + (offsetBitLength (binSize A K v i) h A.d) (binSize_positive A K hK hW v i) + (prefixWord (binBits_le A K hK v h i) (bits i))) + +/-- The bin-dependent interval length only chooses a prefix of the +fixed per-coordinate word. This preserves the analyzed quotient law. -/ +theorem binWordDraw_law (A : Instance I J) (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (h : ℕ) : + mapLaw (uniformLaw (α := BinWords A h)) (binWordDraw A K hK hW v h)= + approximateBinLaw A K hK hW v h := by + unfold binWordDraw approximateBinLaw + rw [←mapLaw_comp,←pi_uniformLaw] + rw [pi_mapLaw (fun i : Fin (dimension A) => + uniformLaw (α := Fin (offsetBitLength (freeRange A (index A i)) h A.d) → Bool)) + (fun i bits => scaledBitInteger (binSize A K v i) + (offsetBitLength (binSize A K v i) h A.d) (binSize_positive A K hK hW v i) + (prefixWord (binBits_le A K hK v h i) bits))] + congr 1 + congr 1 + funext i + rw [padded_draw_law] + exact scaledBitIntegerLaw_eq _ _ _ + +def flatBinDraw (A : Instance I J) (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (h : ℕ) (bits : Fin (binWordBits A h) → Bool) : + FreeIndex A.small A.T A.b := binWordDraw A K hK hW v h (binWordEquiv A h bits) + +lemma flatBinDraw_law (A : Instance I J) (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (h : ℕ) : + mapLaw (uniformLaw (α := Fin (binWordBits A h) → Bool)) (flatBinDraw A K hK hW v h)= + approximateBinLaw A K hK hW v h := by + unfold flatBinDraw + rw [←map_equiv (binWordEquiv A h),uniform_equiv,binWordDraw_law] + +def stationaryIntegerLaw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) : RationalLaw (FreeIndex A.small A.T A.b) := + bindLaw (oracleStationaryLaw A C a z hK) (exactBinLaw A K (by omega) hW) + +/-- The stationary bin draw followed by the actual uniform integer +interval draw is precisely the corrected mass used in the exact h identity. -/ +theorem stationaryIntegerLaw_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (f : FreeIndex A.small A.T A.b) : + ((stationaryIntegerLaw A C a z K hK hW).mass f:ℝ)=correctedMass A C a z K (by omega) f := by + change ((∑ v,(oracleStationaryLaw A C a z hK).mass v* + (exactBinLaw A K (by omega) hW v).mass f:ℚ):ℝ)=_ + simp only [Rat.cast_sum,Rat.cast_mul,exactBinLaw_mass,oracleStationaryLaw_cast, + oracleChain_pi,apply_ite,Rat.cast_div,Rat.cast_one,Rat.cast_natCast,Rat.cast_zero] + calc + _ = ∑ v : Grid (I := Fin (dimension A)) K, + if integerBin A K (by omega) f=v then + gridWeight A C a z v/binSum A C a z K/(integerFiber A K (by omega) v).card else 0 := by + apply Finset.sum_congr rfl + intro v _ + split_ifs <;> simp only [binSum,div_eq_mul_inv,one_mul,mul_zero] + _ = _ := by simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true,correctedMass] + +def sampledIntegerLaw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) : RationalLaw (FreeIndex A.small A.T A.b) := + bindLaw (oracleBitWalkLaw A C a z v n) (fun w => approximateBinLaw A K (by omega) hW w h) + +/-- Both errors are accounted for once: mixing of the actual bin walk, +then bounded quotient sampling inside its selected bin. -/ +theorem sampledIntegerLaw_variation (A : Instance I J) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q h : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hW : 100*A.d*K ≤ A.W) + (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + (variation (sampledIntegerLaw A C a z K hK hW v (oracleTime A C K Q theta) h) + (stationaryIntegerLaw A C a z K hK hW):ℝ) ≤ + theta/(8*Q)+(A.d:ℝ)/(2:ℝ)^(4*(h+A.d)) := by + have hb := variation_bind_uniform (oracleBitWalkLaw A C a z v (oracleTime A C K Q theta)) + (oracleStationaryLaw A C a z hK) (fun w => approximateBinLaw A K (by omega) hW w h) + (exactBinLaw A K (by omega) hW) ((A.d:ℚ)/(2:ℚ)^(4*(h+A.d))) + (fun w => approximateBinLaw_variation A K (by omega) hW w h) + have hbR := (Rat.cast_le (K := ℝ)).mpr hb + simp only [Rat.cast_add,Rat.cast_div,Rat.cast_natCast,Rat.cast_pow,Rat.cast_ofNat] at hbR + exact hbR.trans (add_le_add + (oracleBitWalkLaw_variation A C a theta hC haH htheta z hz K Q hK hQ hKB hPL hCheeger v) le_rfl) + + +private lemma map_product_bind {X Y Z T : Type*} [Fintype X] [Fintype Y] [Fintype Z] [Fintype T] + [DecidableEq Z] [DecidableEq T] (p : RationalLaw X) (q : RationalLaw Y) + (draw : X → Z) (finish : Z → Y → T) : + mapLaw (productLaw p q) (fun xy => finish (draw xy.1) xy.2)= + bindLaw (mapLaw p draw) (fun z => mapLaw q (finish z)) := by + apply RationalLaw.ext + funext t + simp only [mapLaw,productLaw,bindLaw,Fintype.sum_prod_type] + symm + calc + _ = ∑ x,p.mass x*(∑ y,if finish (draw x) y=t then q.mass y else 0) := by + simp_rw [Finset.sum_mul,ite_mul,zero_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + simp + _ = _ := by + apply Finset.sum_congr rfl + intro x _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + split_ifs <;> simp + +def oracleWalkWordEquiv (n k : ℕ) : (Fin (n*k) → Bool) ≃ (Fin n → Fin k → Bool) := + (Equiv.arrowCongr finProdFinEquiv.symm (Equiv.refl Bool)).trans (Equiv.curry _ _ _) + +def flatOracleWalk (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) + (bits : Fin (n*oracleStepBits A C) → Bool) : Grid (I := Fin (dimension A)) K := + wordWalk (oracleBitStep A C a z) v n (oracleWalkWordEquiv n (oracleStepBits A C) bits) + +lemma flatOracleWalk_law (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (n*oracleStepBits A C) → Bool)) (flatOracleWalk A C a z v n)= + oracleBitWalkLaw A C a z v n := by + unfold flatOracleWalk + rw [←map_equiv (oracleWalkWordEquiv n (oracleStepBits A C)),uniform_equiv] + rfl + +def oracleIntegerBits (A : Instance I J) (C n h : ℕ) : ℕ := + n*oracleStepBits A C+binWordBits A h + +def oracleIntegerDraw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) + (bits : Fin (oracleIntegerBits A C n h) → Bool) : FreeIndex A.small A.T A.b := + let draws := splitWordEquiv (n*oracleStepBits A C) (binWordBits A h) bits + flatBinDraw A K (by omega) hW (flatOracleWalk A C a z v n draws.1) h draws.2 + +/-- One fixed Boolean word drives the bin walk and then the integer draw. +The bin-dependent interval length never changes the reserved word length. -/ +theorem oracleIntegerDraw_law (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) (n h : ℕ) : + mapLaw (uniformLaw (α := Fin (oracleIntegerBits A C n h) → Bool)) + (oracleIntegerDraw A C a z K hK hW v n h)=sampledIntegerLaw A C a z K hK hW v n h := by + unfold oracleIntegerDraw oracleIntegerBits + dsimp only + rw [←map_equiv (splitWordEquiv (n*oracleStepBits A C) (binWordBits A h)) + (uniformLaw (α := Fin (n*oracleStepBits A C+binWordBits A h) → Bool)) + (fun draws => flatBinDraw A K (by omega) hW (flatOracleWalk A C a z v n draws.1) h draws.2), + uniform_equiv,←uniform_product] + rw [map_product_bind + (uniformLaw (α := Fin (n*oracleStepBits A C) → Bool)) + (uniformLaw (α := Fin (binWordBits A h) → Bool)) + (flatOracleWalk A C a z v n) (fun w bits => flatBinDraw A K (by omega) hW w h bits), + flatOracleWalk_law] + unfold sampledIntegerLaw + congr 1 + funext w + exact flatBinDraw_law A K (by omega) hW w h + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleEstimator.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleEstimator.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd2ff941ccbff01dd169f761f9ced1afc0c2e3a8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleEstimator.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleSchedule +import OAI.Combinatorics.ContingencyTables.Transport.FiniteIndependentFailures +import OAI.Combinatorics.ContingencyTables.Transport.FiniteProductAccuracy + +namespace OAI + +/-! # The literal rational product estimator for a companion h-value -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary ResidualMixture FirstSuccess +open CommonBasesFPRAS FiniteLawMoments FiniteIndependentAverages +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def rationalAverage {X : Type*} (g : X → ℚ) (N : ℕ) (draws : Fin N → X) : ℚ := + (∑ i,g (draws i))/N + +lemma rationalAverage_cast {X : Type*} (g : X → ℚ) (N : ℕ) (draws : Fin N → X) : + (rationalAverage g N draws:ℝ)=sampleAverage (fun x => (g x:ℝ)) N draws := by + simp only [rationalAverage,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast,sampleAverage,sampleSum] + +abbrev RatioBlock (A : Instance I J) (C K j : ℕ) (delta failure : ℚ) := + Fin (sampleCount j delta failure) → RatioWords A C (oracleTime A C K 1 delta) + +abbrev CorrectionBlock (A : Instance I J) (C K j : ℕ) (delta failure : ℚ) := + Fin (sampleCount j delta failure) → + (Fin (oracleIntegerBits A C (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) → Bool) + +abbrev EstimatorInput (A : Instance I J) (C K j : ℕ) (delta failure : ℚ) := + (Fin j → RatioBlock A C K j delta failure) × CorrectionBlock A C K j delta failure + +def observedFactor (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (delta failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : + Option (Fin j) → ℚ + | none => rationalAverage + (correctionSample A C j z K hK hW (roundingTolerance delta) v + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) + (sampleCount j delta failure) draws.2 + | some a => rationalAverage + (ratioSample A C a.val z v (oracleTime A C K 1 delta)) + (sampleCount j delta failure) (draws.1 a) + +def targetFactor (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) : Option (Fin j) → ℝ + | none => correctionMean A C j z K hK hW + | some a => ratioMean A C a.val z K + +def estimateValue (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (delta failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : ℚ := + (assignmentCount A:ℚ)*∏ i,observedFactor A C z K hK hW j delta failure v draws i + +/-- The exact means appearing in the implemented product telescope to +h, including the integer-population correction and the free-assignment count. -/ +theorem targetFactor_product (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) : + (assignmentCount A:ℝ)*(∏ i,targetFactor A C z K hK hW j i)= + h A ((j:ℝ)*C/height A C) z := by + have hp : (∏ a : Fin j,ratioMean A C a.val z K)= + ∏ a∈Finset.range j,ratioMean A C a z K := + Fin.prod_univ_eq_prod_range (fun a : ℕ => ratioMean A (C:ℝ) a z K) j + rw [Fintype.prod_option] + simp only [targetFactor] + rw [hp,correctionMean_eq] + have ht := oracle_telescope A C (by exact_mod_cast hC) z K (by omega) j + convert ht using 1; ring + +lemma targetFactor_positive (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) (i : Option (Fin j)) : + 0 < targetFactor A C z K hK hW j i := by + cases i with + | none => + have hh := (correctionMean_bounds A C j hC hj z K hK hW hB).1 + change 0 < correctionMean A C j z K hK hW + linarith + | some a => + have hh := (ratioMean_bounds A C a.val hC z hz hK hB.le).1 + change 0 < ratioMean A C a.val z K + linarith + +def GoodEstimate (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (delta failure : ℚ) + (v : Grid (I := Fin (dimension A)) K) (draws : EstimatorInput A C K j delta failure) : Prop := + ∀ i,|(observedFactor A C z K hK hW j delta failure v draws i:ℝ)-targetFactor A C z K hK hW j i| ≤ + (delta:ℝ)*targetFactor A C z K hK hW j i + +def innerTolerance (epsilon : ℚ) (j : ℕ) : ℚ := epsilon/(200*(j+1)) + +/-- On the event certified by the actual independent block experiments, +the returned rational product estimates the literal original h-value. -/ +theorem goodEstimate_accuracy (A : Instance I J) (C : ℕ) (hC : 0 < C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) + (hB : (K:ℝ)=binWidth A C) (j : ℕ) (hj : j ≤ rationalHeight A C) + (epsilon failure : ℚ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (v : Grid (I := Fin (dimension A)) K) + (draws : EstimatorInput A C K j (innerTolerance epsilon j) failure) + (hgood : GoodEstimate A C z K hK hW j (innerTolerance epsilon j) failure v draws) : + (1-(epsilon:ℝ)/4)*h A ((j:ℝ)*C/height A C) z ≤ + (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) ∧ + (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ) ≤ + (1+(epsilon:ℝ)/4)*h A ((j:ℝ)*C/height A C) z := by + have htol : (innerTolerance epsilon j:ℝ)= + (epsilon:ℝ)/(200*(Fintype.card (Option (Fin j)):ℝ)) := by + simp only [innerTolerance,Rat.cast_div,Rat.cast_mul,Rat.cast_ofNat,Rat.cast_add, + Rat.cast_natCast,Rat.cast_one,Fintype.card_option,Fintype.card_fin,Nat.cast_add,Nat.cast_one] + have hprod := FiniteProductAccuracy.product_relative + (fun i => (observedFactor A C z K hK hW j (innerTolerance epsilon j) failure v draws i:ℝ)) + (targetFactor A C z K hK hW j) (targetFactor_positive A C hC z hz K hK hW hB j hj) + epsilon (by exact_mod_cast he0) (by exact_mod_cast he1) + (by intro i; rw [←htol]; exact hgood i) (by simp) + have hcount : (0:ℝ) ≤ assignmentCount A := Nat.cast_nonneg _ + have hlow := mul_le_mul_of_nonneg_left hprod.1 hcount + have hupp := mul_le_mul_of_nonneg_left hprod.2 hcount + have htarget := targetFactor_product A C hC z K hK hW j + have hvalue : (estimateValue A C z K hK hW j (innerTolerance epsilon j) failure v draws:ℝ)= + (assignmentCount A:ℝ)*∏ i, + (observedFactor A C z K hK hW j (innerTolerance epsilon j) failure v draws i:ℝ) := by + simp only [estimateValue,Rat.cast_mul,Rat.cast_natCast,Rat.cast_prod] + rw [hvalue] + rw [←htarget] + constructor + · simpa only [mul_left_comm] using hlow + · simpa only [mul_left_comm] using hupp + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleFibres.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleFibres.lean new file mode 100644 index 0000000000000000000000000000000000000000..88dbd654dc1c9a291a11ce23982706554cf6afe2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleFibres.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleCorrection + +namespace OAI + +/-! # The actual integer bins have the manuscript's Cartesian populations -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def freeRange (A : Instance I J) (t : FreeCell A.small A.T) : ℕ := A.b t.val.1 t.val.2+1 + +def naturalBin (A : Instance I J) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) + (t : FreeCell A.small A.T) : ℕ := ((v ((index A).symm t)).val).toNat + +lemma naturalBin_cast (A : Instance I J) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) + (t : FreeCell A.small A.T) : (naturalBin A v t:ℤ)=(v ((index A).symm t)).val := + Int.toNat_of_nonneg (v ((index A).symm t)).property.1 + +lemma naturalBin_lt (A : Instance I J) {K : ℕ} (v : Grid (I := Fin (dimension A)) K) + (t : FreeCell A.small A.T) : naturalBin A v t + (w ((index A).symm t)).val) h + change (FairBits.scale K (freeRange A (index A ((index A).symm t))) + (f (index A ((index A).symm t))).val:ℤ)=(v ((index A).symm t)).val at hh + rw [Equiv.apply_symm_apply,←naturalBin_cast A v t] at hh + exact_mod_cast hh + · intro h + funext i + apply Subtype.ext + have hh := congrArg (fun n : ℕ => (n:ℤ)) (h (index A i)) + rw [naturalBin_cast,Equiv.symm_apply_apply] at hh + exact hh + +def integerFiberEquiv (A : Instance I J) (K : ℕ) (hK : 0 < K) + (v : Grid (I := Fin (dimension A)) K) : + {f // f∈integerFiber A K hK v} ≃ + CompanionBinPopulation.Assignments K (freeRange A) (naturalBin A v) where + toFun f t := ⟨(f.val t).val,by + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_range.mpr (f.val t).isLt,?_⟩ + exact (integerBin_eq_iff A K hK v f.val).mp (Finset.mem_filter.mp f.property).2 t⟩ + invFun x := ⟨(fun t => ⟨(x t).val,by + exact Finset.mem_range.mp (Finset.mem_filter.mp (x t).property).1⟩),by + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + apply (integerBin_eq_iff A K hK v _).mpr + intro t + exact (Finset.mem_filter.mp (x t).property).2⟩ + left_inv f := by + apply Subtype.ext + funext t + exact Fin.ext rfl + right_inv x := by + funext t + exact Subtype.ext rfl + +theorem integerFiber_card (A : Instance I J) (K : ℕ) (hK : 0 < K) + (v : Grid (I := Fin (dimension A)) K) : + (integerFiber A K hK v).card= + ∏ t : FreeCell A.small A.T,(FairBits.fiber K (freeRange A t) (naturalBin A v t)).card := by + let : DecidableEq (FreeCell A.small A.T) := Classical.decEq _ + calc + _ = Fintype.card {f // f∈integerFiber A K hK v} := (Fintype.card_coe _).symm + _ = _ := Fintype.card_congr (integerFiberEquiv A K hK v) + _ = _ := CompanionBinPopulation.assignment_card K (freeRange A) (naturalBin A v) + +theorem integerFiber_nonempty (A : Instance I J) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (dimension A)) K) : + (integerFiber A K hK v).Nonempty := by + have hpop (t : FreeCell A.small A.T) : + (FairBits.fiber K (freeRange A t) (naturalBin A v t)).Nonempty := by + apply CompanionBinPopulation.coordinate_nonempty K (freeRange A t) A.d _ hK A.hd + · have hh := (A.hlarge t.val.1 t.val.2 t.property.1).1 + unfold freeRange + omega + · exact naturalBin_lt A v t + let x : CompanionBinPopulation.Assignments K (freeRange A) (naturalBin A v) := + fun t => ⟨(hpop t).choose,(hpop t).choose_spec⟩ + exact ⟨((integerFiberEquiv A K hK v).symm x).val, + ((integerFiberEquiv A K hK v).symm x).property⟩ + +lemma assignmentCount_eq_prod (A : Instance I J) : + assignmentCount A=∏ t : FreeCell A.small A.T,freeRange A t := by + simp only [assignmentCount,FreeIndex,Fintype.card_pi,Fintype.card_fin,freeRange] + +theorem population_eq_integerFiber (A : Instance I J) (K : ℕ) (hK : 0 < K) + (v : Grid (I := Fin (dimension A)) K) : + CompanionBinPopulation.population K (freeRange A) (naturalBin A v)= + (K:ℚ)^dimension A*(integerFiber A K hK v).card/assignmentCount A := by + rw [CompanionBinPopulation.population_eq_card,CompanionBinPopulation.assignment_card, + ←integerFiber_card A K hK, + assignmentCount_eq_prod] + simp only [dimension,Nat.cast_prod] + +theorem actual_population_bounds (A : Instance I J) (K : ℕ) (hK : 0 < K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (dimension A)) K) : + 1/2 ≤ (K:ℚ)^dimension A*(integerFiber A K hK v).card/assignmentCount A ∧ + (K:ℚ)^dimension A*(integerFiber A K hK v).card/assignmentCount A ≤ 2 := by + have hh := CompanionBinPopulation.population_bounds K A.d (freeRange A) (naturalBin A v) + hK A.hd (ForestScaledPenalty.free_card_le A) + (by + intro t + have hb := (A.hlarge t.val.1 t.val.2 t.property.1).1 + unfold freeRange + omega) + (naturalBin_lt A v) + simpa only [population_eq_integerFiber A K hK] using hh + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleFiniteStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleFiniteStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea674d389e70f2fb26b7cd339b7eab6f56a09ae1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleFiniteStep.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleKernel +import OAI.Combinatorics.ContingencyTables.Dense.DenseAxisBits +import OAI.Combinatorics.ContingencyTables.Transport.DyadicAcceptance +import OAI.Combinatorics.ContingencyTables.Transport.FiniteMetropolis +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordWalk + +namespace OAI + +/-! # A fixed finite Boolean experiment for each actual evaluator transition -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS ResidualMixture FirstSuccess FairBits +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma oracle_acceptance_finite_coin (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) (v w : Grid (I := Fin (dimension A)) K) : + ((Finset.univ.filter (acceptDyadic + (gridExponent A C a z w-gridExponent A C a z v) (rationalHeight A C))).card:ℝ)/ + (2:ℝ)^rationalHeight A C= + min 1 (gridWeight A C a z w/gridWeight A C a z v) := by + rw [acceptDyadic_probability] + · rw [gridWeight_eq_dyadic,gridWeight_eq_dyadic,dyadic_ratio_min] + · exact (Nat.sub_le _ _).trans ((gridExponent_upper A C a hC z hz hKB w).trans haH) + +def finiteOracleStepLaw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : RationalLaw (Grid (I := Fin (dimension A)) K) := + finiteAcceptLaw v + (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun w => acceptDyadic (gridExponent A C a z w-gridExponent A C a z v) (rationalHeight A C)) + +/-- Every valid direction has one code; unused directions, boundary +proposals and failed dyadic tests stay at the starting vertex. -/ +theorem finiteOracleStepLaw_eq (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1 ≤ K) (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) : + finiteOracleStepLaw A C a z v=oracleTransitionLaw A C a z hK v := by + apply RationalLaw.eq_of_off_diagonal _ _ v + intro w hwv + apply Rat.cast_injective (α := ℝ) + change ((finiteAcceptLaw v + (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun w => acceptDyadic (gridExponent A C a z w-gridExponent A C a z v) + (rationalHeight A C))).mass w:ℝ)=(oracleTransition A C a z v w:ℝ) + rw [finiteAcceptLaw_off_diagonal v w _ _ hwv.symm, + axisCodeStep_count (dense_proposal_code_bound A.d (dimension A) (ForestScaledPenalty.free_card_le A))] + simp only [Rat.cast_mul,Rat.cast_div,Rat.cast_natCast,Fintype.card_fin,Nat.cast_pow,Nat.cast_ofNat] + push_cast + rw [Finset.filter_congr_decidable (Finset.univ : Finset (Fin (2^rationalHeight A C))) + (acceptDyadic (gridExponent A C a z w-gridExponent A C a z v) (rationalHeight A C)) + (fun bits => Classical.propDecidable _)] + rw [oracle_acceptance_finite_coin A C a hC haH z hz hKB v w] + unfold oracleTransition + rw [ite_eq_right hwv.symm,add_zero,oracleMove_cast] + unfold MetropolisChain.move binProposal + by_cases hvw : Neighbor v w <;> simp [hvw] + +def oracleStepBits (A : Instance I J) (C : ℕ) : ℕ := + Nat.clog 2 (8*A.d)+rationalHeight A C + +def oracleBitStep (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) + (bits : Fin (oracleStepBits A C) → Bool) : Grid (I := Fin (dimension A)) K := + let draw := pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C) bits + match axisCodeStep v draw.1 with + | none => v + | some w => if draw.2.val < 2^(rationalHeight A C-(gridExponent A C a z w-gridExponent A C a z v)) + then w else v + +def oracleBitStepLaw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : RationalLaw (Grid (I := Fin (dimension A)) K) := + mapLaw (uniformLaw (α := Fin (oracleStepBits A C) → Bool)) (oracleBitStep A C a z v) + +lemma oracleBitStepLaw_eq_finite (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + oracleBitStepLaw A C a z v=finiteOracleStepLaw A C a z v := by + let E := pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C) + let f := finiteAcceptStep v + (fun code : Fin (2^Nat.clog 2 (8*A.d)) => axisCodeStep v code) + (fun w => acceptDyadic (gridExponent A C a z w-gridExponent A C a z v) (rationalHeight A C)) + have hf : oracleBitStep A C a z v=fun bits => f (E bits) := by + funext bits + dsimp [oracleBitStep,f,E,finiteAcceptStep] + simp only [acceptDyadic] + cases axisCodeStep v ((pairWordEquiv (Nat.clog 2 (8*A.d)) (rationalHeight A C)) bits).1 with + | none => rfl + | some w => dsimp only; split_ifs <;> rfl + unfold oracleBitStepLaw + rw [hf] + change mapLaw (uniformLaw (α := Fin (Nat.clog 2 (8*A.d)+rationalHeight A C) → Bool)) + (fun bits => f (E bits))=_ + rw [←map_equiv E,uniform_equiv,←uniform_product] + rfl + +theorem oracleBitStepLaw_eq (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1 ≤ K) (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) : + oracleBitStepLaw A C a z v=oracleTransitionLaw A C a z hK v := by + rw [oracleBitStepLaw_eq_finite] + exact finiteOracleStepLaw_eq A C a hC haH z hz hK hKB v + +def oracleBitWalkLaw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : RationalLaw (Grid (I := Fin (dimension A)) K) := + wordWalkLaw (oracleBitStep A C a z) v n + +/-- A fixed rectangular Boolean array realizes the complete independent +finite walk whose mixing estimate was proved for the real chain. -/ +theorem oracleBitWalkLaw_eq (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (haH : a ≤ rationalHeight A C) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1 ≤ K) (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : + oracleBitWalkLaw A C a z v n=oracleWalkLaw A C a z hK v n := by + unfold oracleBitWalkLaw oracleWalkLaw + rw [wordWalkLaw_eq] + have he : (fun w : Grid (I := Fin (dimension A)) K => + mapLaw (uniformLaw (α := Fin (oracleStepBits A C) → Bool)) (oracleBitStep A C a z w))= + oracleTransitionLaw A C a z hK := by + funext w + exact oracleBitStepLaw_eq A C a hC haH z hz hK hKB w + rw [he] + +theorem oracleBitWalkLaw_variation (A : Instance I J) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + (variation (oracleBitWalkLaw A C a z v (oracleTime A C K Q theta)) + (oracleStationaryLaw A C a z hK):ℝ) ≤ theta/(8*Q) := by + rw [oracleBitWalkLaw_eq A C a hC haH z hz hK hKB] + apply oracleWalkLaw_variation A C a theta hC _ htheta z hz K Q hK hQ hKB hPL hCheeger v + rw [←rationalHeight_cast] + exact_mod_cast haH + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleJointLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleJointLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d33b8ed33a44146941a46962caa85bbfb7bd98df --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleJointLaw.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleFibres + +namespace OAI + +/-! # Normalization of the actual bin-then-integer sampling law -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +private lemma sum_by_bins {X Y : Type*} [Fintype X] [Fintype Y] [DecidableEq Y] + (bin : X → Y) (g : X → ℝ) : + (∑ y : Y,∑ x : X,if bin x=y then g x else 0)=∑ x,g x := by + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro x _ + simp + +private lemma total_of_bin_sums {X Y : Type*} [Fintype X] [Fintype Y] [DecidableEq Y] + (bin : X → Y) (g : X → ℝ) (p : Y → ℝ) + (h : ∀ y,(∑ x : X,if bin x=y then g x else 0)=p y) + (hp : ∑ y,p y=1) : ∑ x,g x=1 := by + calc + _ = ∑ y : Y,∑ x : X,if bin x=y then g x else 0 := (sum_by_bins bin g).symm + _ = ∑ y,p y := Finset.sum_congr rfl (fun y _ => h y) + _ = 1 := hp + +theorem correctedMass_nonnegative (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (f : FreeIndex A.small A.T A.b) : + 0 ≤ correctedMass A C a z K hK f := by + unfold correctedMass + exact div_nonneg + (div_nonneg (DenseWeights.binWeight_pos _ _ _).le (binSum_positive A C a z K hK).le) + (Nat.cast_nonneg _) + +private lemma correctedMass_fiber_sum (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) + (v : Grid (I := Fin (dimension A)) K) : + (∑ f : FreeIndex A.small A.T A.b, + if integerBin A K hK f=v then correctedMass A C a z K hK f else 0)= + gridWeight A C a z v/binSum A C a z K := by + have hc : ((integerFiber A K hK v).card:ℝ)≠0 := by + exact_mod_cast (Finset.card_pos.mpr (integerFiber_nonempty A K hK hW v)).ne' + have hZ := (binSum_positive A C a z K hK).ne' + calc + _ = ∑ f : FreeIndex A.small A.T A.b, if integerBin A K hK f=v then + gridWeight A C a z v/binSum A C a z K/(integerFiber A K hK v).card else 0 := by + apply Finset.sum_congr rfl + intro f _ + by_cases hf : integerBin A K hK f=v + · simp only [correctedMass,hf,ite_true] + · simp only [hf,ite_false] + _ = ∑ f∈integerFiber A K hK v, + gridWeight A C a z v/binSum A C a z K/(integerFiber A K hK v).card := by + simp only [integerFiber,Finset.sum_filter] + _ = _ := by + rw [Finset.sum_const,nsmul_eq_mul] + field_simp [hc,hZ] + +/-- Choosing a stationary bin and then an exactly uniform integer point +in that bin defines a probability law on the actual free assignments. -/ +theorem correctedMass_total (A : Instance I J) (C a : ℝ) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) : + (∑ f : FreeIndex A.small A.T A.b,correctedMass A C a z K hK f)=1 := by + apply total_of_bin_sums (integerBin A K hK) (correctedMass A C a z K hK) + (fun v => gridWeight A C a z v/binSum A C a z K) + (correctedMass_fiber_sum A C a z K hK hW) + rw [←Finset.sum_div] + exact div_self (binSum_positive A C a z K hK).ne' + +lemma integerPoint_distance (A : Instance I J) (C : ℝ) (K : ℕ) (hK : 0 < K) + (hB : (K:ℝ)=binWidth A C) (f : FreeIndex A.small A.T A.b) : + ∀ i,|integerPoint A C f i-realCorner (integerBin A K hK f) i| ≤ 1 := by + intro i + let t := index A i + let N := freeRange A t + let x := (f t).val + have hq : (0:ℚ) ≤ (K:ℚ)*x/N := by positivity + have hlo : (FairBits.scale K N x:ℚ) ≤ (K:ℚ)*x/N := Nat.floor_le hq + have hhi : (K:ℚ)*x/N < (FairBits.scale K N x:ℚ)+1 := Nat.lt_floor_add_one _ + have hloR : (FairBits.scale K N x:ℝ) ≤ (K:ℝ)*x/N := by + simpa only [Rat.cast_natCast,Rat.cast_mul,Rat.cast_div] using (Rat.cast_le (K := ℝ)).mpr hlo + have hhiR : (K:ℝ)*x/N < (FairBits.scale K N x:ℝ)+1 := by + simpa only [Rat.cast_natCast,Rat.cast_mul,Rat.cast_div,Rat.cast_add,Rat.cast_one] using + (Rat.cast_lt (K := ℝ)).mpr hhi + have hN : (N:ℝ)=(A.b t.val.1 t.val.2:ℝ)+1 := by simp [N,freeRange] + change |binWidth A C*(f t).val/((A.b t.val.1 t.val.2:ℝ)+1)- + (FairBits.scale K N (f t).val:ℝ)| ≤ 1 + rw [←hB,←hN] + change |(K:ℝ)*x/N-(FairBits.scale K N x:ℝ)| ≤ 1 + exact abs_le.mpr ⟨by linarith,by linarith⟩ + +/-- The correction variable is uniformly bounded, independently of the +success event and of the number of integers in a bin. -/ +theorem correction_bounds (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + (K : ℕ) (hK : 0 < K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (f : FreeIndex A.small A.T A.b) : + 1/8 ≤ correction A C a z K hK f ∧ correction A C a z K hK f ≤ 4 := by + let v := integerBin A K hK f + have hpQ := actual_population_bounds A K hK hW v + have hp : (1/2:ℝ) ≤ (K:ℝ)^dimension A*(integerFiber A K hK v).card/assignmentCount A ∧ + (K:ℝ)^dimension A*(integerFiber A K hK v).card/assignmentCount A ≤ 2 := by + constructor + · simpa only [Rat.cast_div,Rat.cast_one,Rat.cast_ofNat,Rat.cast_mul,Rat.cast_pow,Rat.cast_natCast] + using (Rat.cast_le (K := ℝ)).mpr hpQ.1 + · simpa only [Rat.cast_div,Rat.cast_ofNat,Rat.cast_mul,Rat.cast_pow,Rat.cast_natCast] + using (Rat.cast_le (K := ℝ)).mpr hpQ.2 + have hdist : ∀ i,|realCorner v i-integerPoint A C f i| ≤ 1 := by + intro i + simpa only [abs_sub_comm] using integerPoint_distance A C K hK hB f i + have hb := bin_comparison A C a hC ha haH z (realCorner v) (integerPoint A C f) hdist + have hw : 0 < gridWeight A C a z v := DenseWeights.binWeight_pos _ _ _ + have hr : (1/4:ℝ) ≤ rho A C a z (integerPoint A C f)/gridWeight A C a z v ∧ + rho A C a z (integerPoint A C f)/gridWeight A C a z v ≤ 2 := by + constructor + · apply (le_div_iff₀ hw).mpr + simpa only [gridWeight,div_eq_mul_inv,mul_comm,one_mul] using hb.1 + · exact (div_le_iff₀ hw).mpr (by simpa only [gridWeight] using hb.2) + have he : correction A C a z K hK f= + ((K:ℝ)^dimension A*(integerFiber A K hK v).card/assignmentCount A)* + (rho A C a z (integerPoint A C f)/gridWeight A C a z v) := by + unfold correction + ring + rw [he] + constructor + · have hh := mul_le_mul hp.1 hr.1 (by norm_num : (0:ℝ) ≤ 1/4) (by linarith : + 0 ≤ (K:ℝ)^dimension A*(integerFiber A K hK v).card/assignmentCount A) + norm_num at hh ⊢ + exact hh + · have hh := mul_le_mul hp.2 hr.2 (by linarith [hr.1] : + 0 ≤ rho A C a z (integerPoint A C f)/gridWeight A C a z v) + (by norm_num : (0:ℝ) ≤ 2) + norm_num at hh ⊢ + exact hh + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleKernel.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6dd185ae827f270d5dd75767a3dd0262f4067e5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleKernel.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleRational +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleBudget +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalks + +namespace OAI + +/-! # The actual rational transition and finite walk of the companion evaluator -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS ResidualMixture FirstSuccess +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def oracleProposalRat (d : ℕ) : ℚ := 1/(2:ℚ)^Nat.clog 2 (8*d) + +def oracleMove (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v w : Grid (I := Fin (dimension A)) K) : ℚ := + if Neighbor v w then oracleProposalRat A.d*min 1 + (rationalGridWeight A C a z w/rationalGridWeight A C a z v) else 0 + +def oracleTransition (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v w : Grid (I := Fin (dimension A)) K) : ℚ := + oracleMove A C a z v w+if v=w then 1-∑ b,oracleMove A C a z v b else 0 + +lemma oracleMove_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v w : Grid (I := Fin (dimension A)) K) : + (oracleMove A C a z v w:ℝ)= + MetropolisChain.move (gridWeight A C a z) Neighbor (binProposal A.d) v w := by + unfold oracleMove MetropolisChain.move + split_ifs + · simp only [Rat.cast_mul,Rat.cast_min,Rat.cast_one,Rat.cast_div, + rationalGridWeight_cast,oracleProposalRat,binProposal,Rat.cast_pow,Rat.cast_ofNat] + · exact Rat.cast_zero + +theorem oracleTransition_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v w : Grid (I := Fin (dimension A)) K) : + (oracleTransition A C a z v w:ℝ)=(oracleChain A C a z hK).P v w := by + unfold oracleTransition + dsimp only [oracleChain,MetropolisChain.chain,FiniteChain.ofMoves] + by_cases hvw : v=w <;> + simp only [hvw,ite_true,ite_false,Rat.cast_add,Rat.cast_sub,Rat.cast_sum, + Rat.cast_one,Rat.cast_zero,oracleMove_cast] + +def oracleTransitionLaw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v : Grid (I := Fin (dimension A)) K) : + RationalLaw (Grid (I := Fin (dimension A)) K) where + mass := oracleTransition A C a z v + nonnegative := fun w => by + have hh := (oracleChain A C a z hK).nonnegative v w + rw [←oracleTransition_cast A C a z hK] at hh + exact_mod_cast hh + total := by + apply Rat.cast_injective (α := ℝ) + simp only [Rat.cast_sum,oracleTransition_cast A C a z hK,Rat.cast_one] + exact (oracleChain A C a z hK).stochastic v + +def oracleWalkLaw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : + RationalLaw (Grid (I := Fin (dimension A)) K) := + walkLaw (oracleTransitionLaw A C a z hK) v n + +theorem oracleWalkLaw_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (n : ℕ) (v w : Grid (I := Fin (dimension A)) K) : + ((oracleWalkLaw A C a z hK v n).mass w:ℝ)= + ((oracleChain A C a z hK).kernel.power n).P v w := by + induction n generalizing w with + | zero => + simp only [oracleWalkLaw,walkLaw,pointLaw,FiniteKernel.power,FiniteKernel.identity] + by_cases hvw : v=w + · subst w; simp + · simp [hvw,Ne.symm hvw] + | succ n ih => + change ((∑ b,(oracleWalkLaw A C a z hK v n).mass b*oracleTransition A C a z b w:ℚ):ℝ)=_ + simp only [Rat.cast_sum,Rat.cast_mul,ih,oracleTransition_cast A C a z hK, + FiniteKernel.power,FiniteKernel.comp,FiniteChain.kernel] + +def oracleStationaryLaw (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) : RationalLaw (Grid (I := Fin (dimension A)) K) := by + let : Nonempty (Grid (I := Fin (dimension A)) K) := + ⟨fun _ => ⟨0,by constructor <;> omega⟩⟩ + let w := fun v : Grid (I := Fin (dimension A)) K => rationalGridWeight A C a z v + have hw : ∀ v,0 < w v := rationalGridWeight_positive A C a z + have hZ : 0 < ∑ v,w v := Finset.sum_pos (fun v _ => hw v) Finset.univ_nonempty + exact ⟨fun v => w v/∑ b,w b,fun v => (div_pos (hw v) hZ).le, + by rw [←Finset.sum_div]; exact div_self hZ.ne'⟩ + +theorem oracleStationaryLaw_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) (v : Grid (I := Fin (dimension A)) K) : + ((oracleStationaryLaw A C a z hK).mass v:ℝ)=(oracleChain A C a z hK).π v := by + change ((rationalGridWeight A C a z v/ + ∑ w : Grid (I := Fin (dimension A)) K,rationalGridWeight A C a z w:ℚ):ℝ)=_ + simp only [Rat.cast_div,Rat.cast_sum,rationalGridWeight_cast] + rfl + +/-- The rational finite-walk law inherits the proved source schedule. +No exact real-valued primitive is used to define its transitions. -/ +theorem oracleWalkLaw_variation (A : Instance I J) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : (a:ℝ) ≤ height A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + (variation (oracleWalkLaw A C a z hK v (oracleTime A C K Q theta)) + (oracleStationaryLaw A C a z hK):ℝ) ≤ theta/(8*Q) := by + let P := oracleChain A C a z hK + let n := oracleTime A C K Q theta + let delta : ℝ := theta/(8*Q) + have hpoint (w : Grid (I := Fin (dimension A)) K) : + |(P.kernel.power n).P v w-P.π w| ≤ P.π w*delta := by + have hm := oracleChain_scheduled_point_mixing A C a theta + (by exact_mod_cast hC) (Nat.cast_nonneg _) haH htheta z hz K Q hK hQ hKB hPL hCheeger v w + change |P.iterate n (P.pointDensity w) v-1| ≤ delta at hm + rw [←P.kernel_power_density] at hm + calc + _ = P.π w*|(P.kernel.power n).P v w/P.π w-1| := by + calc + _ = |P.π w*((P.kernel.power n).P v w/P.π w-1)| := by + congr 1 + field_simp [(P.positive w).ne'] + _ = _ := by rw [abs_mul,abs_of_pos (P.positive w)] + _ ≤ _ := mul_le_mul_of_nonneg_left hm (P.positive w).le + have hsum := Finset.sum_le_sum (fun w (_ : w∈Finset.univ) => hpoint w) + rw [←Finset.sum_mul,P.normalized,one_mul] at hsum + unfold variation + simp only [Rat.cast_div,Rat.cast_sum,Rat.cast_abs,Rat.cast_sub,Rat.cast_ofNat, + oracleWalkLaw_cast,oracleStationaryLaw_cast] + change (∑ w,|(P.kernel.power n).P v w-P.π w|)/2 ≤ delta + have hd : 0 ≤ delta := by dsimp only [delta]; positivity + linarith + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleMixing.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleMixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b539f6b15acc3ca115baa0dc8c7315a2d04ef34 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleMixing.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleChain + +namespace OAI + +/-! # Quantitative mixing for the companion's actual evaluator grid -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CommonBasesFPRAS GridBoundary CompanionFactorialApplication +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma oracle_grid_card (q K : ℕ) : Fintype.card (Grid (I := Fin q) K)=K^q := by + have hc : Fintype.card (Set.Icc (0:ℤ) ((K:ℤ)-1))=K := by + have hh := Int.card_fintype_Icc_of_le 0 ((K:ℤ)-1) + (show (0:ℤ) ≤ (K:ℤ)-1+1 by omega) + omega + simp only [Grid,Fintype.card_fun,Fintype.card_fin,hc] + +lemma gridWeight_bounds (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (_haH : a ≤ height A C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) + (v : Grid (I := Fin (dimension A)) K) : + (2:ℝ)^(-a) ≤ gridWeight A C a z v ∧ gridWeight A C a z v ≤ 1 := by + have hD := D_bounds A C hC z hz (realCorner v) (by + intro i + constructor + · change (0:ℝ) ≤ ((v i).val:ℝ) + exact_mod_cast (v i).property.1 + · have hh : (realCorner v i:ℝ) ≤ K := by + change ((v i).val:ℝ) ≤ K + exact_mod_cast (show (v i).val ≤ (K:ℤ) by have hh := (v i).property.2; omega) + exact hh.trans hKB) + have hH := height_positive A C hC + have he0 : 0 ≤ a/height A C*D A C z (realCorner v) := + mul_nonneg (div_nonneg ha hH.le) hD.1 + have he1 : a/height A C*D A C z (realCorner v) ≤ a := by + calc + _ ≤ a/height A C*height A C := + mul_le_mul_of_nonneg_left hD.2 (div_nonneg ha hH.le) + _ = a := div_mul_cancel₀ a hH.ne' + have hf0 : (0:ℤ) ≤ ⌊a/height A C*D A C z (realCorner v)⌋ := + Int.floor_nonneg.mpr he0 + have hf1 := (Int.floor_le (a/height A C*D A C z (realCorner v))).trans he1 + unfold gridWeight V DenseWeights.binWeight + constructor + · exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + · calc + _ ≤ (2:ℝ)^(0:ℝ) := + Real.rpow_le_rpow_of_exponent_le (by norm_num) (by exact_mod_cast neg_nonpos.mpr hf0) + _ = 1 := Real.rpow_zero _ + +lemma oracleChain_pi_lower (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) {K : ℕ} (hK : 1 ≤ K) + (hKB : (K:ℝ) ≤ binWidth A C) (v : Grid (I := Fin (dimension A)) K) : + (2:ℝ)^(-a)/(K:ℝ)^dimension A ≤ (oracleChain A C a z hK).π v := by + let : Nonempty (Grid (I := Fin (dimension A)) K) := ⟨v⟩ + have hsumpos : 0 < ∑ w : Grid (I := Fin (dimension A)) K,gridWeight A C a z w := + Finset.sum_pos (fun _ _ => DenseWeights.binWeight_pos _ _ _) Finset.univ_nonempty + have hsum : (∑ w : Grid (I := Fin (dimension A)) K,gridWeight A C a z w) ≤ + (K:ℝ)^dimension A := by + calc + _ ≤ ∑ _w : Grid (I := Fin (dimension A)) K,(1:ℝ) := + Finset.sum_le_sum (fun w _ => (gridWeight_bounds A C a hC ha haH z hz hKB w).2) + _ = _ := by simp only [Finset.sum_const,Finset.card_univ,nsmul_eq_mul,mul_one, + oracle_grid_card,Nat.cast_pow] + rw [oracleChain_pi] + exact div_le_div₀ (DenseWeights.binWeight_pos _ _ _).le + (gridWeight_bounds A C a hC ha haH z hz hKB v).1 hsumpos hsum + +def mixingConstant (A : Instance I J) (K : ℕ) : ℝ := 2*(10000*(A.d:ℝ)^2*K)^2 + +lemma mixingConstant_ge_one (A : Instance I J) {K : ℕ} (hK : 1 ≤ K) : + 1 ≤ mixingConstant A K := by + have hd : (1:ℝ) ≤ A.d := by exact_mod_cast A.hd + have hk : (1:ℝ) ≤ K := by exact_mod_cast hK + have hd2 : (1:ℝ) ≤ (A.d:ℝ)^2 := one_le_pow₀ hd + have hm : (1:ℝ) ≤ 10000*(A.d:ℝ)^2*K := by + have hh := mul_le_mul hd2 hk (by norm_num : (0:ℝ) ≤ 1) (sq_nonneg (A.d:ℝ)) + nlinarith + unfold mixingConstant + nlinarith [sq_nonneg (10000*(A.d:ℝ)^2*K-1)] + +lemma cutConstant_lower (A : Instance I J) {K : ℕ} (hK : 1 ≤ K) : + 1/(10000*(A.d:ℝ)^2*K) ≤ cutConstant A K := by + have hd : (0:ℝ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + have hk : (0:ℝ) < K := by exact_mod_cast (show 0 < K by omega) + calc + _ ≤ 1/(2048*(A.d:ℝ)^2*K) := + one_div_le_one_div_of_le (by positivity) (by gcongr; norm_num) + _ = (1/(16*(A.d:ℝ)))/(128*(A.d:ℝ)*K) := by field_simp [hd.ne',hk.ne']; ring + _ ≤ cutConstant A K := + div_le_div_of_nonneg_right (proposal_bounds A.d A.hd).2.1 (by positivity) + +theorem oracleChain_polynomial_poincare (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) : + ∀ f,(oracleChain A C a z hK).variance f ≤ + mixingConstant A K*(oracleChain A C a z hK).energy f := by + intro f + have hd : (0:ℝ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + have hk : (0:ℝ) < K := by exact_mod_cast (show 0 < K by omega) + have hlo := cutConstant_lower A hK + have hb : 2/(cutConstant A K)^2 ≤ mixingConstant A K := by + calc + _ ≤ 2/(1/(10000*(A.d:ℝ)^2*K))^2 := by + apply div_le_div_of_nonneg_left (by norm_num) (by positivity) + exact pow_le_pow_left₀ (by positivity) hlo 2 + _ = _ := by unfold mixingConstant; field_simp [hd.ne',hk.ne'] + exact (oracleChain_poincare A C a hC ha haH z hK hPL hCheeger f).trans + (mul_le_mul_of_nonneg_right hb (FiniteChain.energy_nonneg _ f)) + +/-- Pointwise relative mixing for the implemented dyadic-proposal +Metropolis chain; this also bounds total variation. -/ +theorem oracleChain_point_mixing (A : Instance I J) (C a : ℝ) (hC : 0 < C) + (ha : 0 ≤ a) (haH : a ≤ height A C) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) {K : ℕ} (hK : 1 ≤ K) + (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (n : ℕ) (v w : Grid (I := Fin (dimension A)) K) : + |(oracleChain A C a z hK).iterate n ((oracleChain A C a z hK).pointDensity w) v-1| ≤ + Real.exp (-(n:ℝ)/mixingConstant A K)/((2:ℝ)^(-a)/(K:ℝ)^dimension A) := by + have hKR : (0:ℝ) < K := by exact_mod_cast (show 0 < K by omega) + apply FiniteChain.point_mixing_exp + · exact mixingConstant_ge_one A hK + · positivity + · exact oracleChain_pi_lower A C a hC ha haH z hz hK hKB + · exact oracleChain_polynomial_poincare A C a hC ha haH z hK hPL hCheeger + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleRational.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleRational.lean new file mode 100644 index 0000000000000000000000000000000000000000..77a80c06b9dddd550f266f63cee58df5af34c87e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleRational.lean @@ -0,0 +1,199 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleMixing +import Mathlib.Data.Rat.Floor + +namespace OAI + +/-! # Exact rational arithmetic for the companion evaluator's bin weights -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication ForestAssignmentSplit ForestScaledPenalty +open ForestAffineCoefficients ForestRootPenalty GraphCompletionCounts GridBoundary +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def rationalIndicator (b : Bool) : ℚ := if b then 1 else 0 + +lemma rationalIndicator_cast (b : Bool) : (rationalIndicator b:ℝ)=ForestCut.indicator b := by + cases b <;> norm_num [rationalIndicator,ForestCut.indicator] + +def rationalSign (A : Instance I J) (t : TreeCell A.T) (a : I×J) : ℚ := + rationalIndicator (cutSide A t (.inl a.1))-rationalIndicator (cutSide A t (.inr a.2)) + +lemma rationalSign_cast (A : Instance I J) (t : TreeCell A.T) (a : I×J) : + (rationalSign A t a:ℝ)=sign A t a := by + simp only [rationalSign,Rat.cast_sub,rationalIndicator_cast,sign] + +def rationalCoefficient (A : Instance I J) (t : TreeCell A.T) (a : I×J) : ℚ := + if A.small a.1 a.2=false ∧ ¬A.T.Adj (.inl a.1) (.inr a.2) + then -rationalSign A t a/rationalSign A t t.val else 0 + +lemma rationalCoefficient_cast (A : Instance I J) (t : TreeCell A.T) (a : I×J) : + (rationalCoefficient A t a:ℝ)=coefficient A t a := by + unfold rationalCoefficient coefficient + split_ifs <;> simp only [Rat.cast_div,Rat.cast_neg,rationalSign_cast,Rat.cast_zero] + +def rationalSmallContribution (A : Instance I J) (t : TreeCell A.T) + (x q : I → J → ℤ) : ℚ := + ∑ a : I×J,if A.small a.1 a.2 then + rationalIndicator (cutSide A t (.inl a.1))*((x a.1 a.2:ℚ)-A.X a.1 a.2)- + rationalIndicator (cutSide A t (.inr a.2))*((q a.1 a.2:ℚ)-A.X a.1 a.2) else 0 + +lemma rationalSmallContribution_cast (A : Instance I J) (t : TreeCell A.T) + (x q : I → J → ℤ) : + (rationalSmallContribution A t x q:ℝ)= + smallContribution A t (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ)) := by + unfold rationalSmallContribution smallContribution + rw [Rat.cast_sum] + apply Finset.sum_congr rfl + intro a _ + split_ifs <;> simp only [Rat.cast_sub,Rat.cast_mul,rationalIndicator_cast, + Rat.cast_intCast,Rat.cast_zero] + +def rationalOffset (A : Instance I J) (t : TreeCell A.T) (x q : I → J → ℤ) : ℚ := + A.X t.val.1 t.val.2-rationalSmallContribution A t x q/rationalSign A t t.val- + ∑ a : I×J,rationalCoefficient A t a*(A.X a.1 a.2:ℚ) + +lemma rationalOffset_cast (A : Instance I J) (t : TreeCell A.T) (x q : I → J → ℤ) : + (rationalOffset A t x q:ℝ)= + offset A t (fun i j => (x i j:ℝ)) (fun i j => (q i j:ℝ)) := by + simp only [rationalOffset,offset,Rat.cast_sub,Rat.cast_div,Rat.cast_intCast, + Rat.cast_sum,Rat.cast_mul,rationalCoefficient_cast,rationalSign_cast, + rationalSmallContribution_cast] + +def rationalBinWidth (A : Instance I J) (C : ℕ) : ℕ := 16*C*A.d^2 + +def rationalHeight (A : Instance I J) (C : ℕ) : ℕ := 10*C*A.d^2*(A.W+1) + +lemma rationalBinWidth_cast (A : Instance I J) (C : ℕ) : + (rationalBinWidth A C:ℝ)=binWidth A C := by + simp only [rationalBinWidth,binWidth,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_pow] + +lemma rationalHeight_cast (A : Instance I J) (C : ℕ) : + (rationalHeight A C:ℝ)=height A C := by + simp only [rationalHeight,height,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_pow,Nat.cast_add,Nat.cast_one] + +def rationalScaledTree (A : Instance I J) (C : ℕ) (x q : I → J → ℤ) + (v : FreeCell A.small A.T → ℚ) (t : TreeCell A.T) : ℚ := + rationalOffset A t x q/(A.b t.val.1 t.val.2:ℚ)+ + ∑ f : FreeCell A.small A.T, + (rationalCoefficient A t f.val*((A.b f.val.1 f.val.2:ℚ)+1)/rationalBinWidth A C/ + (A.b t.val.1 t.val.2:ℚ))*v f + +lemma rationalScaledTree_cast (A : Instance I J) (C : ℕ) (x q : I → J → ℤ) + (v : FreeCell A.small A.T → ℚ) (t : TreeCell A.T) : + (rationalScaledTree A C x q v t:ℝ)= + scaledTree A (binWidth A C) x q (fun f => (v f:ℝ)) t := by + simp only [rationalScaledTree,scaledTree,AffinePenalty.affineValue,normalizedOffset, + normalizedCoefficient,Rat.cast_add,Rat.cast_div,Rat.cast_mul,Rat.cast_sum, + Rat.cast_natCast,Rat.cast_one,rationalOffset_cast,rationalCoefficient_cast,rationalBinWidth_cast] + +def rationalRootConstant (A : Instance I J) (x q : I → J → ℤ) : ℚ := + ∑ a,if ForestPenaltyApplication.rootFlag A.T a then + |(signedResidual A.small A.T A.r A.c x q 0 a:ℚ)| else 0 + +lemma rationalRootConstant_cast (A : Instance I J) (x q : I → J → ℤ) : + (rationalRootConstant A x q:ℝ)=rootConstant A x q := by + unfold rationalRootConstant rootConstant + rw [Rat.cast_sum] + apply Finset.sum_congr rfl + intro a _ + split_ifs <;> simp only [Rat.cast_abs,Rat.cast_intCast,Rat.cast_zero] + +def rationalD (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (v : Fin (dimension A) → ℚ) : ℚ := + C*(rationalRootConstant A (rowCounts A z) (columnCounts A z)+ + ∑ t : TreeCell A.T,max 0 (max + (-rationalScaledTree A C (rowCounts A z) (columnCounts A z) (fun f => v ((index A).symm f)) t) + (rationalScaledTree A C (rowCounts A z) (columnCounts A z) (fun f => v ((index A).symm f)) t-1))) + +/-- The rational calculation is termwise equal to the geometric density +penalty; it does not use an approximation or enumerate free assignments. -/ +theorem rationalD_cast (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (v : Fin (dimension A) → ℚ) : + (rationalD A C z v:ℝ)=D A C z (fun i => (v i:ℝ)) := by + simp only [rationalD,D,penalty,intervalCost,Rat.cast_mul,Rat.cast_natCast, + Rat.cast_add,Rat.cast_sum,rationalRootConstant_cast,Rat.cast_max,Rat.cast_zero, + Rat.cast_neg,Rat.cast_sub,Rat.cast_one,rationalScaledTree_cast] + rfl + +lemma rationalD_nonnegative (A : Instance I J) (C : ℕ) (z : View A → ℕ) + (v : Fin (dimension A) → ℚ) : 0 ≤ rationalD A C z v := by + have hh := penalty_nonnegative A (C:ℝ) (binWidth A C) (Nat.cast_nonneg _) + (rowCounts A z) (columnCounts A z) (pull A (fun i => (v i:ℝ))) + change 0 ≤ D A C z (fun i => (v i:ℝ)) at hh + rw [←rationalD_cast] at hh + exact_mod_cast hh + +def gridExponent (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℕ := + ⌊(a:ℚ)/rationalHeight A C*rationalD A C z (fun i => (corner v i:ℚ))⌋₊ + +theorem gridExponent_eq_floor (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + (gridExponent A C a z v:ℤ)=⌊(a:ℝ)/height A C*D A C z (realCorner v)⌋ := by + have hn := mul_nonneg (div_nonneg (Nat.cast_nonneg a) (Nat.cast_nonneg (rationalHeight A C))) + (rationalD_nonnegative A C z (fun i => (corner v i:ℚ))) + rw [gridExponent,Int.natCast_floor_eq_floor hn] + have he : (((a:ℚ)/rationalHeight A C*rationalD A C z (fun i => (corner v i:ℚ)):ℚ):ℝ)= + (a:ℝ)/height A C*D A C z (realCorner v) := by + simp only [Rat.cast_mul,Rat.cast_div,Rat.cast_natCast,rationalHeight_cast,rationalD_cast, + Rat.cast_intCast] + rfl + rw [←he,Rat.floor_cast] + +theorem gridWeight_eq_dyadic (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + gridWeight A C a z v=1/(2:ℝ)^gridExponent A C a z v := by + unfold gridWeight V DenseWeights.binWeight + rw [←gridExponent_eq_floor] + simp only [Int.cast_natCast,Real.rpow_neg (by norm_num : (0:ℝ)≤2),Real.rpow_natCast,one_div] + +theorem gridExponent_upper (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) (v : Grid (I := Fin (dimension A)) K) : + gridExponent A C a z v ≤ a := by + have hCR : (0:ℝ) < C := by exact_mod_cast hC + have hD := D_bounds A C hCR z hz (realCorner v) (by + intro i + constructor + · change (0:ℝ) ≤ ((v i).val:ℝ) + exact_mod_cast (v i).property.1 + · have hh : (realCorner v i:ℝ) ≤ K := by + change ((v i).val:ℝ) ≤ K + exact_mod_cast (show (v i).val ≤ (K:ℤ) by have hh := (v i).property.2; omega) + exact hh.trans hKB) + have hH := height_positive A C hCR + have hbound : (a:ℝ)/height A C*D A C z (realCorner v) ≤ a := by + calc + _ ≤ (a:ℝ)/height A C*height A C := + mul_le_mul_of_nonneg_left hD.2 (div_nonneg (Nat.cast_nonneg _) hH.le) + _ = _ := div_mul_cancel₀ _ hH.ne' + have he := gridExponent_eq_floor A C a z v + have hh := (Int.floor_le ((a:ℝ)/height A C*D A C z (realCorner v))).trans hbound + rw [←he] at hh + exact_mod_cast hh + +def rationalGridWeight (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℚ := + 1/(2:ℚ)^gridExponent A C a z v + +theorem rationalGridWeight_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + (rationalGridWeight A C a z v:ℝ)=gridWeight A C a z v := by + rw [gridWeight_eq_dyadic] + simp only [rationalGridWeight,Rat.cast_div,Rat.cast_one,Rat.cast_pow,Rat.cast_ofNat] + +lemma rationalGridWeight_positive (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : 0 < rationalGridWeight A C a z v := by + unfold rationalGridWeight + positivity + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleSchedule.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a46fa01da53993d413978ea7f70854d444a5aa1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOracleSchedule.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCorrectionSamples +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRatioSamples + +namespace OAI + +/-! # Explicit accuracy and sample-count parameters for the weight oracle -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS ResidualMixture FirstSuccess +open FiniteLawMoments FiniteIndependentAverages +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def offsetAccuracy (A : Instance I J) (delta : ℚ) : ℕ := ⌈4096*(A.d:ℚ)/delta⌉₊ + +def correctionTheta (delta : ℚ) : ℝ := (delta:ℝ)/256 + +def roundingTolerance (delta : ℚ) : ℚ := delta/4 + +def sampleCount (j : ℕ) (delta failure : ℚ) : ℕ := ⌈65536*(j+1)/(failure*delta^2)⌉₊ + +private lemma le_two_pow (n : ℕ) : n ≤ 2^n := by + induction n with + | zero => norm_num + | succ n ih => + have hp : 0 < 2^n := pow_pos (by decide) _ + rw [pow_succ] + omega + +lemma offsetAccuracy_positive (A : Instance I J) (delta : ℚ) (hdelta : 0 < delta) : + 0 < offsetAccuracy A delta := by + have hd : (0:ℚ) < A.d := by exact_mod_cast (show 0 < A.d by have hh := A.hd; omega) + have hh := Nat.le_ceil (4096*(A.d:ℚ)/delta) + have hp : (0:ℚ) < offsetAccuracy A delta := lt_of_lt_of_le (by positivity) hh + exact_mod_cast hp + +lemma offsetAccuracy_error (A : Instance I J) (delta : ℚ) (hdelta : 0 < delta) : + (A.d:ℝ)/(2:ℝ)^(4*(offsetAccuracy A delta+A.d)) ≤ (delta:ℝ)/4096 := by + have hd : (0:ℝ) < delta := by exact_mod_cast hdelta + have hh : (4096:ℝ)*A.d/(delta:ℝ) ≤ offsetAccuracy A delta := by + have hb := Nat.le_ceil (4096*(A.d:ℚ)/delta) + unfold offsetAccuracy + exact_mod_cast hb + have he : offsetAccuracy A delta ≤ 2^(4*(offsetAccuracy A delta+A.d)) := by + exact (le_two_pow _).trans (Nat.pow_le_pow_right (by decide) (by omega)) + have hp : (offsetAccuracy A delta:ℝ) ≤ (2:ℝ)^(4*(offsetAccuracy A delta+A.d)) := by exact_mod_cast he + rw [div_le_div_iff₀ (by positivity : (0:ℝ) < 2^(4*(offsetAccuracy A delta+A.d))) (by norm_num : (0:ℝ)<4096)] + have hb := (div_le_iff₀ hd).mp hh + nlinarith [mul_le_mul_of_nonneg_left hp hd.le] + +lemma correction_noise_budget (A : Instance I J) (delta : ℚ) (hdelta : 0 < delta) : + correctionTheta delta/(8*1)+(A.d:ℝ)/(2:ℝ)^(4*(offsetAccuracy A delta+A.d)) ≤ + (delta:ℝ)/1024 := by + have hh := offsetAccuracy_error A delta hdelta + have hd : (0:ℝ) < delta := by exact_mod_cast hdelta + unfold correctionTheta + linarith + +lemma sampleCount_positive (j : ℕ) (delta failure : ℚ) (hdelta : 0 < delta) + (hfailure : 0 < failure) : 0 < sampleCount j delta failure := by + have hh := Nat.le_ceil (65536*(j+1:ℚ)/(failure*delta^2)) + have hp : (0:ℚ) < sampleCount j delta failure := lt_of_lt_of_le (by positivity) hh + exact_mod_cast hp + +/-- Every one of the j ratio averages and the final correction average +has failure at most this common share. -/ +lemma sampleCount_budget (j : ℕ) (delta failure : ℚ) (hdelta : 0 < delta) + (hfailure : 0 < failure) : + 16384/((sampleCount j delta failure:ℝ)*(delta:ℝ)^2) ≤ (failure:ℝ)/(4*((j:ℝ)+1)) := by + have hd : (0:ℝ) < delta := by exact_mod_cast hdelta + have hf : (0:ℝ) < failure := by exact_mod_cast hfailure + have hN : (0:ℝ) < sampleCount j delta failure := by + exact_mod_cast sampleCount_positive j delta failure hdelta hfailure + have hh : (65536:ℝ)*((j:ℝ)+1)/((failure:ℝ)*(delta:ℝ)^2) ≤ sampleCount j delta failure := by + have hb := Nat.le_ceil (65536*(j+1:ℚ)/(failure*delta^2)) + unfold sampleCount + exact_mod_cast hb + rw [div_le_div_iff₀ (by positivity : (0:ℝ) < (sampleCount j delta failure:ℝ)*(delta:ℝ)^2) + (by positivity : (0:ℝ) < 4*((j:ℝ)+1))] + have hb := (div_le_iff₀ (show (0:ℝ) < (failure:ℝ)*(delta:ℝ)^2 by positivity)).mp hh + nlinarith + +/-- The concrete correction schedule discharges both arithmetic error +allowances; only the named published PL/Cheeger inputs remain. -/ +theorem scheduled_correction_failure (A : Instance I J) (C a j : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (delta failure : ℚ) + (hdelta : 0 < delta) (hdelta1 : delta < 1) (hfailure : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K : ℕ) (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : Fin (sampleCount j delta failure) → + (Fin (oracleIntegerBits A C (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta)) → Bool) => + if (delta:ℝ)*correctionMean A C a z K hK hW < + |sampleAverage (fun bits => + (correctionSample A C a z K hK hW (roundingTolerance delta) v + (oracleTime A C K 1 (correctionTheta delta)) (offsetAccuracy A delta) bits:ℝ)) + (sampleCount j delta failure) draws-correctionMean A C a z K hK hW| then (1:ℝ) else 0) ≤ + (failure:ℝ)/(4*((j:ℝ)+1)) := by + have hd : (0:ℝ) < delta := by exact_mod_cast hdelta + have hs : (0:ℚ) < roundingTolerance delta := by unfold roundingTolerance; positivity + have hsHalf : roundingTolerance delta ≤ 1/2 := by unfold roundingTolerance; linarith + have hsDelta : (roundingTolerance delta:ℝ) ≤ (delta:ℝ)/4 := by + simp only [roundingTolerance,Rat.cast_div,Rat.cast_ofNat,le_refl] + exact (correctionSamples_failure A C a (correctionTheta delta) delta hC haH + (by unfold correctionTheta; positivity) hd z hz K 1 (offsetAccuracy A delta) + (sampleCount j delta failure) hK (by decide) hW (sampleCount_positive j delta failure hdelta hfailure) + hB (roundingTolerance delta) hs hsHalf hsDelta (by simpa only [Nat.cast_one] using correction_noise_budget A delta hdelta) + hPL hCheeger v).trans (sampleCount_budget j delta failure hdelta hfailure) + + +theorem scheduled_ratio_failure (A : Instance I J) (C a j : ℕ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (delta failure : ℚ) + (hdelta : 0 < delta) (hfailure : 0 < failure) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K : ℕ) (hK : 1 ≤ K) (hB : (K:ℝ)=binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : Fin (sampleCount j delta failure) → + RatioWords A C (oracleTime A C K 1 delta) => + if (delta:ℝ)*ratioMean A C a z K < + |sampleAverage (fun bits => (ratioSample A C a z v (oracleTime A C K 1 delta) bits:ℝ)) + (sampleCount j delta failure) draws-ratioMean A C a z K| then (1:ℝ) else 0) ≤ + (failure:ℝ)/(4*((j:ℝ)+1)) := by + have hd : (0:ℝ) < delta := by exact_mod_cast hdelta + have hn := sampleCount_positive j delta failure hdelta hfailure + have hh := ratioSamples_failure A C a delta hC haH hd z hz K 1 (sampleCount j delta failure) + hK (by decide) hn hB.le hPL hCheeger v + apply hh.trans + calc + 16/((sampleCount j delta failure:ℝ)*(delta:ℝ)^2) ≤ + 16384/((sampleCount j delta failure:ℝ)*(delta:ℝ)^2) := + div_le_div_of_nonneg_right (by norm_num) (by positivity) + _ ≤ _ := sampleCount_budget j delta failure hdelta hfailure + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOrderedProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOrderedProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..807cea4948df6a9768c7a497ef4f65d9f3d58038 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOrderedProposal.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionNeighborProgram + +namespace OAI + +/-! # The companion proposal with a specified coordinate order + +The coordinate scan and its paired-state validator work with the same +explicit order used by the initializer. Its dyadic proposal law is +independent of this order, including unused proposal words. +-/ + +namespace ContingencyTables.CompanionOrderedProposal + +open CommonBasesFPRAS TwoLiftStates CompanionFactorialApplication +open CompanionArithmeticProposal CompanionChainValidator CompanionNeighborProgram +open CompanionBooleanPhase FirstSuccess ResidualMixture ProfilePrograms +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] +variable (A : Instance I J) {m p : ℕ} + +def orderedNeighbors (e : (Labels A×Bool) ≃ Fin m) (S : State A) : List (State A) := + neighborStates e pairs S + +lemma mem_orderedNeighbors (e : (Labels A×Bool) ≃ Fin m) (S T : State A) : + T∈orderedNeighbors A e S ↔ ExchangeAdjacent S.val T.val := + mem_neighborStates e pairs S T + +lemma orderedNeighbors_nodup (e : (Labels A×Bool) ≃ Fin m) (S : State A) : + (orderedNeighbors A e S).Nodup := neighborStates_nodup e pairs S + +lemma orderedNeighbors_length (e : (Labels A×Bool) ≃ Fin m) (S : State A) : + (orderedNeighbors A e S).length≤2^proposalBits A := by + have he : (orderedNeighbors A e S).toFinset= + Finset.univ.filter (fun T : State A => ExchangeAdjacent S.val T.val) := by + ext T + simp only [List.mem_toFinset,Finset.mem_filter,Finset.mem_univ,true_and, + mem_orderedNeighbors] + rw [←List.toFinset_card_of_nodup (orderedNeighbors_nodup A e S),he] + simpa only [Fintype.card_subtype] using proposal_codes A S + +def orderedProposal (e : (Labels A×Bool) ≃ Fin m) (S : State A) + (bits : Fin (proposalBits A) → Bool) : Option (State A) := + listWordChoice (orderedNeighbors A e S,List.ofFn bits) + +lemma orderedProposal_mass (e : (Labels A×Bool) ≃ Fin m) (S T : State A) : + (mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) + (orderedProposal A e S)).mass (some T)= + if ExchangeAdjacent S.val T.val then 1/(2:ℚ)^proposalBits A else 0 := by + exact (listWordChoice_mass (orderedNeighbors A e S) (orderedNeighbors_nodup A e S) + (proposalBits A) (orderedNeighbors_length A e S) T).trans + (by simp only [mem_orderedNeighbors]) + +/-- Every complete coordinate order has the analysed proposal law. -/ +theorem orderedProposal_law (e : (Labels A×Bool) ≃ Fin m) (S : State A) : + mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) (orderedProposal A e S)= + mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) + (CompanionBooleanPhase.proposal A S) := by + let u := mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) (orderedProposal A e S) + let v := mapLaw (uniformLaw (α := Fin (proposalBits A) → Bool)) + (CompanionBooleanPhase.proposal A S) + have hs (T : State A) : u.mass (some T)=v.mass (some T) := + (orderedProposal_mass A e S T).trans (CompanionBooleanPhase.proposal_mass A S T).symm + change u=v + apply RationalLaw.ext + funext T + cases T with + | some T => exact hs T + | none => + have hu := u.total + have hv := v.total + simp only [Fintype.sum_option] at hu hv + simp_rw [hs] at hu + linarith + +def orderedCatalog (g : Fin p ≃ Labels A) (e : (Labels A×Bool) ≃ Fin m) : List (ℕ×ℕ) := + List.ofFn (fun i => ((e (g i,false)).val,(e (g i,true)).val)) + +lemma pairedStateTest_ordered (g : Fin p ≃ Labels A) (e : (Labels A×Bool) ≃ Fin m) + (S : Set (Labels A×Bool)) : + pairedStateTest (orderedCatalog A g e,encodeSet e S)=true ↔ ChainState pairs S := by + unfold pairedStateTest orderedCatalog + simp only [List.map_ofFn] + change patternTest ((List.ofFn (fun i : Fin p => + (encodeSet e S).getD (e (g i,false)).val 0), + List.ofFn (fun i : Fin p => (encodeSet e S).getD (e (g i,true)).val 0)),1)=true ↔ _ + simp only [encodeSet,getD_setProfile,setProfile,coordinateSet,Set.mem_preimage, + Equiv.symm_apply_apply] + exact paired_pattern_iff g S + +lemma validExchanges_ordered (g : Fin p ≃ Labels A) (e : (Labels A×Bool) ≃ Fin m) + (S : State A) : + validExchanges (orderedCatalog A g e,encodeSet e S.val)= + (orderedNeighbors A e S).map (fun T => encodeSet e T.val) := by + unfold validExchanges orderedNeighbors neighborStates neighborSets + rw [List.map_filterMap,List.filterMap_map,←List.filterMap_eq_filter] + apply List.filterMap_congr + intro xs hxs + obtain ⟨T,hT,rfl⟩ := (mem_raw_codes e S.val xs).mp hxs + simp only [Function.comp_apply,decode_encode] + by_cases h : ChainState pairs T + · have hp : pairedStateTest (orderedCatalog A g e,encodeSet e T)=true := + (pairedStateTest_ordered A g e T).mpr h + simp only [dite_eq_left h,Option.map_some,Option.guard,hp,ite_true] + · have hp : pairedStateTest (orderedCatalog A g e,encodeSet e T)=false := by + apply Bool.eq_false_iff.mpr + intro ht + exact h ((pairedStateTest_ordered A g e T).mp ht) + simp only [dite_eq_right h,Option.map_none,Option.guard,hp,Bool.false_eq_true,ite_false] + +/-- The polynomial list program returns exactly the encoded state drawn +by the ordered proposal; no enumeration of all chain states is needed. -/ +theorem codeProposal_ordered (g : Fin p ≃ Labels A) (e : (Labels A×Bool) ≃ Fin m) + (S : State A) (bits : Fin (proposalBits A) → Bool) : + codeProposal ((orderedCatalog A g e,encodeSet e S.val),List.ofFn bits)= + (orderedProposal A e S bits).map (fun T => encodeSet e T.val) := by + rw [codeProposal,validExchanges_ordered] + simp only [listWordChoice,orderedProposal,List.getElem?_map] + +end +end ContingencyTables.CompanionOrderedProposal + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOrderedReturn.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOrderedReturn.lean new file mode 100644 index 0000000000000000000000000000000000000000..61a5d94f2b48018c455db16331e2cf52f26fa6d4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOrderedReturn.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBoundedWalkProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCappedReturnProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionComputedProposal + +namespace OAI + +/-! # The return scan in the computed paired-coordinate order -/ + +namespace ContingencyTables.CompanionOrderedReturn + +open MatchingFPRAS.TreeTyped CompanionBoundedWalkProgram CompanionTraceProgram +open CompanionCappedReturnProgram CompanionComputedProposal + +abbrev Input := CompanionBoundedWalkProgram.State × List (List Bool) + +def scanInput (z : Input) : TotalReturnInput := + ((PairedCatalogProgram.catalog z.1.2,history z),z.1.2) +def scanInputRealizer : Realizer scanInput := + pair (pair (composition (f := fun z : Input => z.1.2) (g := PairedCatalogProgram.catalog) + (composition first second) PairedCatalogProgram.catalogRealizer) + historyRealizer) (composition first second) +lemma polynomial_scanInput : PolynomialTime scanInputRealizer := + polynomial_pair (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) PairedCatalogProgram.polynomial_catalog) + polynomial_history) (polynomial_composition polynomial_first polynomial_second) + +def output (z : Input) : List ℕ := totalReturnCode (scanInput z) +def outputRealizer : Realizer output := + composition (f := scanInput) (g := totalReturnCode) scanInputRealizer totalReturnCodeRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_scanInput polynomial_totalReturnCode + +noncomputable section +open CommonBasesFPRAS CompanionFactorialApplication CompanionArithmeticProposal +open CompanionOrderedProposal CompanionBooleanPhase CompanionTraceWords TwoLiftStates +open scoped Classical +variable {I J : Type} [Fintype I] [Fintype J] + +lemma plainTest_ordered (A : Instance I J) {p q : ℕ} (g : Fin p ≃ Labels A) + (e : (Labels A × Bool) ≃ Fin q) (S : Set (Labels A × Bool)) : + pairedPlainTest (orderedCatalog A g e,encodeSet e S)=true ↔ PlainState pairs S := + CompanionPhaseCounts.plainTest_ordered A g e S + +lemma firstPlainCode_ordered (A : Instance I J) {p q : ℕ} (g : Fin p ≃ Labels A) + (e : (Labels A × Bool) ≃ Fin q) (xs : List (CompanionBooleanPhase.State A)) : + firstPlainCode (orderedCatalog A g e,xs.map (fun S => encodeSet e S.val))= + (firstHit (plainPredicate pairs) xs).map (fun T => encodeSet e T.val.val) := by + induction xs with + | nil => simp only [firstPlainCode,List.map_nil,List.filter_nil,List.getElem?_nil,firstHit,Option.map_none] + | cons S xs ih => + unfold firstPlainCode at ih ⊢ + simp only [List.map_cons,List.filter_cons,firstHit] + by_cases h : PlainState pairs S.val + · have ht := (plainTest_ordered A g e S.val).mpr h + simp only [ht,ite_true,plainPredicate,dite_eq_left h,Option.map_some,List.getElem?_cons_zero] + · have ht : pairedPlainTest (orderedCatalog A g e,encodeSet e S.val)=false := by + apply Bool.eq_false_iff.mpr + intro ht + exact h ((plainTest_ordered A g e S.val).mp ht) + simpa only [ht,Bool.false_eq_true,ite_false,plainPredicate,dite_eq_right h] using ih + +theorem totalReturnCode_ordered (A : Instance I J) {p q : ℕ} (g : Fin p ≃ Labels A) + (e : (Labels A × Bool) ≃ Fin q) + (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) + (xs : List (CompanionBooleanPhase.State A)) : + totalReturnCode ((orderedCatalog A g e,xs.map (fun T => encodeSet e T.val)),encodeSet e S.val.val)= + encodeSet e (CompanionCappedReturn.returnDefault (plainPredicate pairs) S xs).val.val := by + unfold totalReturnCode returnCode + rw [←List.map_tail,firstPlainCode_ordered] + unfold CompanionCappedReturn.returnDefault + cases firstHit (plainPredicate pairs) xs.tail <;> rfl + +end +end ContingencyTables.CompanionOrderedReturn + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterHistoryProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterHistoryProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b54bf5c5505fd8533cf6b2543de810b8d05a968 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterHistoryProgram.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseProgram + +namespace OAI + +/-! # Chronological execution of all counting phases -/ +namespace ContingencyTables.CompanionOuterHistoryProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped +abbrev Prepared := CompanionPhaseContextProgram.Prepared +abbrev Stored := CompanionPhaseFinishProgram.Stored +abbrev Fixed := Prepared×Stored +abbrev State := Fixed×List Stored +abbrev Input := Fixed×List (List Bool) +local instance : Codec Fixed := inferInstance +local instance : Codec State := inferInstance +local instance : Codec Input := inferInstance + +def phaseInput (z : List Bool×State) : CompanionOuterPhaseProgram.Input := (z.2,z.1) +def phaseInputRealizer : Realizer phaseInput := pair second first +lemma polynomial_phaseInput : PolynomialTime phaseInputRealizer := + polynomial_pair polynomial_second polynomial_first + +def next (z : List Bool×State) : Stored := CompanionOuterPhaseProgram.output (phaseInput z) +def nextRealizer : Realizer next := + composition (f := phaseInput) (g := CompanionOuterPhaseProgram.output) + phaseInputRealizer CompanionOuterPhaseProgram.outputRealizer +lemma polynomial_next : PolynomialTime nextRealizer := + polynomial_composition polynomial_phaseInput CompanionOuterPhaseProgram.polynomial_output + +def advance (z : List Bool×State) : State := (z.2.1,z.2.2++[next z]) +def advanceRealizer : Realizer advance := + pair (composition second first) + (composition (pair (composition second second) + (composition (pair nextRealizer (constant [])) listCons)) append) +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition (polynomial_pair polynomial_next (polynomial_constant [])) polynomial_listCons)) + polynomial_append) + +def run (z : Input) : State := z.2.foldl (fun state bits => advance (bits,state)) (z.1,[]) +def runRealizer : Realizer run := + composition (pair second (pair first (constant []))) (fold advanceRealizer) + +def storedHistory (z : Input) : List Stored := (run z).2 +def storedHistoryRealizer : Realizer storedHistory := + composition (f := run) (g := Prod.snd) runRealizer second + +def output (z : Input) : Stored := + CompanionOuterPhaseProgram.old ((z.1,storedHistory z),[]) +def outputRealizer : Realizer output := + composition (f := fun z : Input => ((z.1,storedHistory z),[])) + (g := CompanionOuterPhaseProgram.old) + (pair (pair first storedHistoryRealizer) (constant [])) CompanionOuterPhaseProgram.oldRealizer + +lemma advance_fixed (bits : List Bool) (state : State) : (advance (bits,state)).1=state.1 := rfl +lemma run_fixed (z : Input) : (run z).1=z.1 := by + have h (words : List (List Bool)) (state : State) : + (words.foldl (fun state bits => advance (bits,state)) state).1=state.1 := by + induction words generalizing state with + | nil => rfl + | cons word words ih => exact ih _ + exact h z.2 (z.1,[]) + +end ContingencyTables.CompanionOuterHistoryProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..dea9ad762b511c8a969512e3f3f95f93157f74d8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseLaw.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartContinuation + +namespace OAI + +/-! # Law of an executed outer phase, including its initialized restart -/ +namespace ContingencyTables.CompanionOuterPhaseProgram +open MatchingFPRAS CommonBasesFPRAS FirstSuccess FairBits CompanionFactorialApplication +open CompanionComputedInitial CompanionComputedProposal CompanionArithmeticProposal +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram CompanionOracleDensity +open GridBoundary FiniteObservableTransport TwoLiftStates +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def tailWidth (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) (padding : ℕ) : ℕ := + let p := CompanionInitializedRestartProgram.parameters A H T N R L epsilon + let xi := TreeFraction.val (CountingPhaseParametersProgram.noise p) + let k := CountingPhaseParametersProgram.precision p + let obs := CountingPhaseParametersProgram.observations p + obs*CompanionBooleanPhase.stepBits A C K j k xi+ + ((obs+1)*CompanionObservationQueriesProgram.blockWidth + (configs A C K H T N R L j epsilon z v reserve)+padding) + +def phaseWordWidth (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) (padding : ℕ) : ℕ := + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon)+ + tailWidth A C K H T N R L j epsilon z v reserve padding) + +attribute [local irreducible] CompanionInitializedRestartProgram.output + CompanionInitializedRestartProgram.model CompanionInitializedRestartProgram.jointModel + CompanionPhaseContinuation.run CompanionOuterPhaseProgram.output + +theorem output_sameLaw (A : Instance (Fin m) (Fin n)) (C K H T N R L j padding : ℕ) + (hC : 0 + CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + (output (data A C K H T N R L j epsilon z v w E (List.ofFn bits)))) + (fun bits : (Fin (CompanionInitialDraw.initialBits A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + CompanionRestartProgram.sumBits A C K j p)→Bool)×RootedPhaseTrial.TrialWords A C K j k obs xi => + CompanionPhaseFinishProgram.storedView A (pairLabels A) + ((RootedPhaseTrial.trial A (RootedCompletion.rowColumn A.T) C K j k obs hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old + (CompanionInitializedRestartProgram.model A C K H T N R L j epsilon hK hW v w bits.1).val + bits.2).getD old)) := by + dsimp only + let p := CompanionInitializedRestartProgram.parameters A H T N R L epsilon + let xi := TreeFraction.val (CountingPhaseParametersProgram.noise p) + let k := CountingPhaseParametersProgram.precision p + let obs := CountingPhaseParametersProgram.observations p + let a := wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H)) + let b := CompanionRestartProgram.sumBits A C K j p + let tail := tailWidth A C K H T N R L j epsilon z v reserve padding + let cs := configs A C K H T N R L j epsilon z v reserve + let project := CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + have hd (i : ℕ) (hi : i ≤ j+1) : + (CompanionRestartStageProgram.degree A C K i p z v reserve).length= + PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) i)) := by + unfold CompanionRestartStageProgram.degree CompanionRestartStageProgram.oracleData + rw [List.length_take,List.length_replicate,RootedOracleConfigProgram.rootDegree_data, + min_eq_left (hdegree i hi)] + have ht (i : ℕ) (hi : i ≤ j+1) : + (CompanionRestartStageProgram.depth A C K i p z v reserve).length= + PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) i)) := by + unfold CompanionRestartStageProgram.depth CompanionRestartStageProgram.oracleData + rw [List.length_take,List.length_replicate,RootedOracleConfigProgram.depth_data, + min_eq_left (hdepth i hi)] + have hi := CompanionInitializedRestartProgram.output_joint_sameLaw A C K H T N R L j tail + hC (by omega) hK hW hB epsilon hxi z v w (fun i => E (i.val+1)) + (fun i => by + unfold CompanionRestartStageProgram.oracleData + rw [RootedOracleConfigProgram.rootDegree_data] + exact (hdegree (i.val+1) (by omega)).trans_eq hlen) + (fun i => by + unfold CompanionRestartStageProgram.oracleData + rw [RootedOracleConfigProgram.depth_data] + exact (hdepth (i.val+1) (by omega)).trans_eq hlen) + have hi' := fun phi => (hi phi).trans + ((CompanionInitializedRestartProgram.jointModel_sameLaw A C K H T N R L j tail + epsilon hK hW v w) phi) + let F := fun code (bits : Fin tail→Bool) => + project (CompanionPhaseContinuation.run cs (matrixCode (w j),E j) k obs code (List.ofFn bits)) + let G := fun (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) + (bits : RootedPhaseTrial.TrialWords A C K j k obs xi) => + CompanionPhaseFinishProgram.storedView A (pairLabels A) + ((RootedPhaseTrial.trial A (RootedCompletion.rowColumn A.T) C K j k obs hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old S.val bits).getD old) + have hs (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) : + SameLaw (F (encodeSet (coordinateOrder A) S.val.val)) (G S) := + CompanionPhaseContinuation.run_sameLaw padding A C K j k obs hC hj hK hW hB xi hxi z v + (CompanionRestartStageProgram.degree A C K j p z v reserve) + (CompanionRestartStageProgram.depth A C K j p z v reserve) + (CompanionRestartStageProgram.degree A C K (j+1) p z v reserve) + (CompanionRestartStageProgram.depth A C K (j+1) p z v reserve) + (hd j (by omega)) (ht j (by omega)) (hd (j+1) le_rfl) (ht (j+1) le_rfl) + old (w j) (E j) hw hE S.val + have hh := joint_encoded_bind _ + (CompanionInitializedRestartProgram.model A C K H T N R L j epsilon hK hW v w) + (fun S => encodeSet (coordinateOrder A) S.val.val) F G hi' hs + intro phi + have he (bits : Fin (a+(b+tail))→Bool) : + project (output (data A C K H T N R L j epsilon z v w E (List.ofFn bits)))= + F (CompanionInitializedRestartProgram.output + (CompanionInitializedRestartProgram.data A C K H T N R L j epsilon z v w + (fun i => E (i.val+1)) (List.ofFn bits))) + (splitWordEquiv b tail (splitWordEquiv a (b+tail) bits).2).2 := by + dsimp only [F] + rw [output_data_run A C K H T N R L j epsilon z v w E reserve (List.ofFn bits) + (by rw [List.length_ofFn]; exact hlen.symm)] + congr 2 + rw [←List.drop_drop,DensePrograms.ofFn_split_drop,DensePrograms.ofFn_split_drop] + change uniformAverage (fun bits : Fin (a+(b+tail))→Bool => + phi (project (output (data A C K H T N R L j epsilon z v w E (List.ofFn bits)))))=_ + simp_rw [he] + exact hh phi + +end +end ContingencyTables.CompanionOuterPhaseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fd7ff9362619f8ef9ed1b6a4466d58d835bc5f7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseProgram.lean @@ -0,0 +1,202 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSchedule +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrialProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartProgram + +namespace OAI + +/-! # One complete adaptive phase from the stored chronological history -/ +namespace ContingencyTables.CompanionOuterPhaseProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped +abbrev Prepared := CompanionPhaseContextProgram.Prepared +abbrev Stored := CompanionPhaseFinishProgram.Stored +abbrev Request := (Prepared×Stored)×List Stored +abbrev Input := Request×List Bool +local instance : Codec CompanionObservedUpdateProgram.Configs := inferInstance +local instance : Codec CompanionObservedUpdateProgram.Base := inferInstance +local instance : Codec (CompanionObservedUpdateProgram.Configs×CompanionObservedUpdateProgram.Base) := inferInstance +local instance : Codec CompanionObservedUpdateProgram.Input := inferInstance +local instance : Codec (Prepared×Stored) := inferInstance +local instance : Codec Request := inferInstance +local instance : Codec Input := inferInstance + +def history (z : Input) : List Stored := z.1.2 +def historyRealizer : Realizer history := composition first second +lemma polynomial_history : PolynomialTime historyRealizer := + polynomial_composition polynomial_first polynomial_second + +def phase (z : Input) : ℕ := (history z).length +def phaseRealizer : Realizer phase := + composition (f := history) (g := List.length) historyRealizer listLength +lemma polynomial_phase : PolynomialTime phaseRealizer := + polynomial_composition polynomial_history polynomial_listLength + +def old (z : Input) : Stored := + if phase z=0 then z.1.1.2 else (history z).getD (phase z-1) default +def oldRealizer : Realizer old := + (choose (composition (pair phaseRealizer (constant 0)) natEqual) + (composition (composition first first) second) + (composition (pair historyRealizer (composition (pair phaseRealizer (constant 1)) subtract)) + (getDFast default))).congr (by intro z; simp only [old,Function.comp_apply,decide_eq_true_eq]) +lemma polynomial_old : PolynomialTime oldRealizer := by + unfold oldRealizer + apply polynomial_congr + exact polynomial_choose + (polynomial_composition (polynomial_pair polynomial_phase (polynomial_constant 0)) polynomial_natEqual) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition (polynomial_pair polynomial_history + (polynomial_composition (polynomial_pair polynomial_phase (polynomial_constant 1)) polynomial_subtract)) + (polynomial_getDFast default)) + +def reserve (z : Input) : List Bool := z.2.map (fun _ => false) +def reserveRealizer : Realizer reserve := composition second (map (constant false)) +lemma polynomial_reserve : PolynomialTime reserveRealizer := + polynomial_composition polynomial_second (polynomial_map (polynomial_constant false)) + +def contextInput (z : Input×ℕ) : CompanionPhaseContextProgram.Input := + (((z.1.1.1.1,phase z.1+z.2),reserve z.1)) +def contextInputRealizer : Realizer contextInput := + pair (pair (composition (composition (composition first first) first) first) + (composition (pair (composition (f := Prod.fst) (g := phase) first phaseRealizer) second) add)) + (composition (f := Prod.fst) (g := reserve) first reserveRealizer) +lemma polynomial_contextInput : PolynomialTime contextInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_first) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_phase) + polynomial_second) polynomial_add)) (polynomial_composition polynomial_first polynomial_reserve) + +def configAt (i : ℕ) (z : Input) : RootedLabelWeightProgram.Config := + CompanionPhaseContextProgram.config (contextInput (z,i)) +def configAtRealizer (i : ℕ) : Realizer (configAt i) := + composition (f := fun z : Input => contextInput (z,i)) (g := CompanionPhaseContextProgram.config) + (composition (f := fun z : Input => (z,i)) (g := contextInput) + (pair identity (constant i)) contextInputRealizer) CompanionPhaseContextProgram.configRealizer +lemma polynomial_configAt (i : ℕ) : PolynomialTime (configAtRealizer i) := + polynomial_composition (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant i)) + polynomial_contextInput) CompanionPhaseContextProgram.polynomial_config + +def restartRequest (z : Input) : Prepared×List Stored := (z.1.1.1,history z) +def restartRequestRealizer : Realizer restartRequest := + pair (composition (composition first first) first) historyRealizer +lemma polynomial_restartRequest : PolynomialTime restartRequestRealizer := + polynomial_pair (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_history + +def restartWidth (z : Input) : ℕ := CompanionRestartSchedule.width (restartRequest z) +def restartWidthRealizer : Realizer restartWidth := + composition (f := restartRequest) (g := CompanionRestartSchedule.width) + restartRequestRealizer CompanionRestartSchedule.widthRealizer +lemma polynomial_restartWidth : PolynomialTime restartWidthRealizer := + polynomial_composition polynomial_restartRequest CompanionRestartSchedule.polynomial_width + +def restartInput (z : Input) : CompanionInitializedRestartProgram.Input := + (restartRequest z,z.2) +def restartInputRealizer : Realizer restartInput := + pair restartRequestRealizer second +lemma polynomial_restartInput : PolynomialTime restartInputRealizer := + polynomial_pair polynomial_restartRequest polynomial_second + +def startCode (z : Input) : List ℕ := CompanionInitializedRestartProgram.output (restartInput z) +def startCodeRealizer : Realizer startCode := + composition (f := restartInput) (g := CompanionInitializedRestartProgram.output) + restartInputRealizer CompanionInitializedRestartProgram.outputRealizer +lemma polynomial_startCode : PolynomialTime startCodeRealizer := + polynomial_composition polynomial_restartInput CompanionInitializedRestartProgram.polynomial_output + +def parameters (z : Input) : CountingPhaseParametersProgram.Input := z.1.1.1.2 +def parametersRealizer : Realizer parameters := composition (composition (composition first first) first) second +lemma polynomial_parameters : PolynomialTime parametersRealizer := + polynomial_composition (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second + +def precision (z : Input) : ℕ := CountingPhaseParametersProgram.precision (parameters z) +def precisionRealizer : Realizer precision := + composition (f := parameters) (g := CountingPhaseParametersProgram.precision) + parametersRealizer CountingPhaseParametersProgram.precisionRealizer +lemma polynomial_precision : PolynomialTime precisionRealizer := + polynomial_composition polynomial_parameters CountingPhaseParametersProgram.polynomial_precision + +def observations (z : Input) : ℕ := CountingPhaseParametersProgram.observations (parameters z) +def observationsRealizer : Realizer observations := + composition (f := parameters) (g := CountingPhaseParametersProgram.observations) + parametersRealizer CountingPhaseParametersProgram.observationsRealizer +lemma polynomial_observations : PolynomialTime observationsRealizer := + polynomial_composition polynomial_parameters CountingPhaseParametersProgram.polynomial_observations + +attribute [local irreducible] old startCode configAt + +def walkState (z : Input) : CompanionBoundedWalkProgram.State := + ((((configAt 0 z,(old z).1),precision z),startCode z),startCode z) +def walkStateRealizer : Realizer walkState := + pair (pair (pair (pair (configAtRealizer 0) (composition (f := old) (g := Prod.fst) oldRealizer first)) + precisionRealizer) startCodeRealizer) startCodeRealizer +lemma polynomial_walkState : PolynomialTime walkStateRealizer := + polynomial_pair (polynomial_pair (polynomial_pair (polynomial_pair (polynomial_configAt 0) + (polynomial_composition polynomial_old polynomial_first)) polynomial_precision) polynomial_startCode) + polynomial_startCode + +def widthInput (z : Input) : CompanionMetropolisWordProgram.Input := + (((walkState z).1.1,(walkState z).2),[]) +def widthInputRealizer : Realizer widthInput := + pair (pair (composition (composition (f := walkState) (g := Prod.fst) walkStateRealizer first) first) + (composition (f := walkState) (g := Prod.snd) walkStateRealizer second)) (constant []) +lemma polynomial_widthInput : PolynomialTime widthInputRealizer := + polynomial_pair (polynomial_pair (polynomial_composition (polynomial_composition polynomial_walkState + polynomial_first) polynomial_first) (polynomial_composition polynomial_walkState polynomial_second)) + (polynomial_constant []) + +def trajectoryWidth (z : Input) : ℕ := observations z*CompanionTransitionWidth.width (widthInput z) +def trajectoryWidthRealizer : Realizer trajectoryWidth := + composition (pair observationsRealizer (composition (f := widthInput) (g := CompanionTransitionWidth.width) + widthInputRealizer CompanionTransitionWidth.widthRealizer)) multiply +lemma polynomial_trajectoryWidth : PolynomialTime trajectoryWidthRealizer := + polynomial_composition (polynomial_pair polynomial_observations + (polynomial_composition polynomial_widthInput CompanionTransitionWidth.polynomial_width)) polynomial_multiply + +def afterRestart (z : Input) : List Bool := z.2.drop (restartWidth z) +def afterRestartRealizer : Realizer afterRestart := composition (pair second restartWidthRealizer) dropFast +lemma polynomial_afterRestart : PolynomialTime afterRestartRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_restartWidth) polynomial_dropFast + +def trajectoryInput (z : Input) : CompanionTrajectoryProgram.Input := + ((walkState z,observations z),(afterRestart z).take (trajectoryWidth z)) +def trajectoryInputRealizer : Realizer trajectoryInput := + pair (pair walkStateRealizer observationsRealizer) + (composition (pair afterRestartRealizer trajectoryWidthRealizer) takeFast) +lemma polynomial_trajectoryInput : PolynomialTime trajectoryInputRealizer := + polynomial_pair (polynomial_pair polynomial_walkState polynomial_observations) + (polynomial_composition (polynomial_pair polynomial_afterRestart polynomial_trajectoryWidth) polynomial_takeFast) + +def trialInput (z : Input) : CompanionPhaseTrialProgram.Input := + ((((configAt 0 z,configAt 1 z),old z),trajectoryInput z),(afterRestart z).drop (trajectoryWidth z)) +def trialInputRealizer : Realizer trialInput := + pair (pair (pair (pair (configAtRealizer 0) (configAtRealizer 1)) oldRealizer) trajectoryInputRealizer) + (composition (pair afterRestartRealizer trajectoryWidthRealizer) dropFast) +lemma polynomial_trialInput : PolynomialTime trialInputRealizer := + polynomial_pair (polynomial_pair (polynomial_pair (polynomial_pair (polynomial_configAt 0) + (polynomial_configAt 1)) polynomial_old) polynomial_trajectoryInput) + (polynomial_composition (polynomial_pair polynomial_afterRestart polynomial_trajectoryWidth) polynomial_dropFast) + +attribute [local irreducible] trialInput + +def fallback (p : Stored×Option Stored) : Stored := p.2.getD p.1 +def fallbackRealizer : Realizer fallback := + (optionCases identity second).congr (by intro p; unfold fallback; cases p.2 <;> rfl) +lemma polynomial_fallback : PolynomialTime fallbackRealizer := by + unfold fallbackRealizer + apply polynomial_congr + exact polynomial_optionCases polynomial_identity polynomial_second + +def output (z : Input) : Stored := (CompanionPhaseTrialProgram.output (trialInput z)).getD (old z) +def outputRealizer : Realizer output := + composition (f := fun z : Input => (old z,CompanionPhaseTrialProgram.output (trialInput z))) + (g := fallback) + (pair oldRealizer (composition (f := trialInput) (g := CompanionPhaseTrialProgram.output) + trialInputRealizer CompanionPhaseTrialProgram.outputRealizer)) fallbackRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair polynomial_old (polynomial_composition polynomial_trialInput + CompanionPhaseTrialProgram.polynomial_output)) polynomial_fallback + +end ContingencyTables.CompanionOuterPhaseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..43779a5191c08a15871c08c09d4e118d768011d6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterPhaseSemantics.lean @@ -0,0 +1,171 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrialLaw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartJoint + +namespace OAI + +/-! # Literal data and slices of a complete adaptive phase -/ +namespace ContingencyTables.CompanionOuterPhaseProgram +open MatchingFPRAS CommonBasesFPRAS CompanionFactorialApplication CompanionComputedInitial +open CompanionComputedProposal CompanionArithmeticProposal CompanionEvaluatedWeightProgram +open CompanionMultiplierMatrixProgram CompanionOracleDensity GridBoundary +open scoped BigOperators Classical +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) : Input := + (((CompanionRestartInitializer.data A C K H T N R L epsilon z v,(matrixCode (w 0),E 0)), + List.ofFn (fun i : Fin j => (matrixCode (w (i.val+1)),E (i.val+1)))),bits) + +lemma phase_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) : + phase (data A C K H T N R L j epsilon z v w E bits)=j := by + simp only [phase,history,data,List.length_ofFn] + +lemma old_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) : + old (data A C K H T N R L j epsilon z v w E bits)=(matrixCode (w j),E j) := by + rw [old,phase_data] + cases j with + | zero => rfl + | succ j => + simp only [Nat.add_one_ne_zero,ite_false,history,data,Nat.add_sub_cancel, + List.getD_eq_getElem?_getD,List.getElem?_ofFn,Nat.lt_succ_self,dite_true,Option.getD_some] + +lemma restartInput_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) : + restartInput (data A C K H T N R L j epsilon z v w E bits)= + CompanionInitializedRestartProgram.data A C K H T N R L j epsilon z v w + (fun i => E (i.val+1)) bits := rfl + +lemma configAt_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j i : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) : + configAt i (data A C K H T N R L j epsilon z v w E bits)= + RootedLabelWeightProgram.config A C K (j+i) + (TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon))) + (TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon))) z v + (CompanionRestartStageProgram.degree A C K (j+i) + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon) z v bits) + (CompanionRestartStageProgram.depth A C K (j+i) + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon) z v bits) := by + unfold configAt contextInput + rw [phase_data] + change CompanionPhaseContextProgram.config (CompanionPhaseContextProgram.data A C K (j+i) + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon) z v (reserve _))=_ + rw [CompanionPhaseContextProgram.config_data,RootedOracleConfigProgram.output_data] + simp only [reserve,data,List.map_const',List.length_replicate, + CompanionRestartStageProgram.degree,CompanionRestartStageProgram.depth, + CompanionRestartStageProgram.oracleData] + + + +lemma restartWidth_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) : + restartWidth (data A C K H T N R L j epsilon z v w E bits)= + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + CompanionRestartProgram.sumBits A C K j + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon) := by + unfold restartWidth restartRequest + change CompanionRestartSchedule.width (CompanionRestartInitializer.data A C K H T N R L epsilon z v,_)=_ + rw [CompanionRestartSchedule.width,CompanionRestartInitializer.width_data, + CompanionRestartSchedule.restartWidth_data] + rw [show (history (data A C K H T N R L j epsilon z v w E bits)).length=j from + phase_data A C K H T N R L j epsilon z v w E bits] + rfl + +lemma walkState_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) (S : CompanionBooleanPhase.State A) + (hs : startCode (data A C K H T N R L j epsilon z v w E bits)=encodeSet (coordinateOrder A) S.val) : + walkState (data A C K H T N R L j epsilon z v w E bits)= + CompanionFlatReturnProgram.stateData A C K j + (CountingPhaseParametersProgram.precision (CompanionInitializedRestartProgram.parameters A H T N R L epsilon)) + (TreeFraction.val (CountingPhaseParametersProgram.noise (CompanionInitializedRestartProgram.parameters A H T N R L epsilon))) + z v + (CompanionRestartStageProgram.degree A C K j (CompanionInitializedRestartProgram.parameters A H T N R L epsilon) z v bits) + (CompanionRestartStageProgram.depth A C K j (CompanionInitializedRestartProgram.parameters A H T N R L epsilon) z v bits) + (w j) S := by + unfold walkState + rw [configAt_data,old_data,hs] + simp only [Nat.add_zero] + rfl + +lemma trajectoryWidth_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) (S : CompanionBooleanPhase.State A) + (hs : startCode (data A C K H T N R L j epsilon z v w E bits)=encodeSet (coordinateOrder A) S.val) : + trajectoryWidth (data A C K H T N R L j epsilon z v w E bits)= + CountingPhaseParametersProgram.observations (CompanionInitializedRestartProgram.parameters A H T N R L epsilon)* + CompanionBooleanPhase.stepBits A C K j + (CountingPhaseParametersProgram.precision (CompanionInitializedRestartProgram.parameters A H T N R L epsilon)) + (TreeFraction.val (CountingPhaseParametersProgram.noise (CompanionInitializedRestartProgram.parameters A H T N R L epsilon))) := by + unfold trajectoryWidth widthInput + rw [walkState_data A C K H T N R L j epsilon z v w E bits S hs] + change CountingPhaseParametersProgram.observations _* + CompanionTransitionWidth.width (CompanionMetropolisWordProgram.packed + (RootedLabelWeightProgram.config A C K j _ _ z v _ _,matrixCode (w j)) _ + (encodeSet (coordinateOrder A) S.val) [])=_ + rw [CompanionTransitionWidth.width_config] + rfl + + + +lemma trialInput_data (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (bits : List Bool) (S : CompanionBooleanPhase.State A) + (hs : startCode (data A C K H T N R L j epsilon z v w E bits)=encodeSet (coordinateOrder A) S.val) : + let p := CompanionInitializedRestartProgram.parameters A H T N R L epsilon + let xi := TreeFraction.val (CountingPhaseParametersProgram.noise p) + let k := CountingPhaseParametersProgram.precision p + let obs := CountingPhaseParametersProgram.observations p + let a := wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + CompanionRestartProgram.sumBits A C K j p + let t := obs*CompanionBooleanPhase.stepBits A C K j k xi + trialInput (data A C K H T N R L j epsilon z v w E bits)= + CompanionPhaseTrialProgram.data A C K j k obs xi z v + (CompanionRestartStageProgram.degree A C K j p z v bits) + (CompanionRestartStageProgram.depth A C K j p z v bits) + (CompanionRestartStageProgram.degree A C K (j+1) p z v bits) + (CompanionRestartStageProgram.depth A C K (j+1) p z v bits) + (w j) (E j) S ((bits.drop a).take t) ((bits.drop a).drop t) := by + dsimp only + unfold trialInput trajectoryInput + rw [configAt_data,configAt_data,old_data, + walkState_data A C K H T N R L j epsilon z v w E bits S hs, + trajectoryWidth_data A C K H T N R L j epsilon z v w E bits S hs] + unfold afterRestart + rw [restartWidth_data] + simp only [Nat.add_zero] + rfl + +end +end ContingencyTables.CompanionOuterPhaseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterWidths.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterWidths.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec1612ef064a9b8462c7fb679cc14896affbd001 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionOuterWidths.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartContinuation +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseHistory + +namespace OAI + +/-! # Executed phase widths and the source history word + +The supplied precision markers do not contribute to the number of oracle +bits. After identifying the computed scalar controls, the complete phase +width is the source width plus its unused padding. +-/ +namespace ContingencyTables.CompanionOuterWidths +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial +open CompanionOracleDensity GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma configs_blockWidth (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + CompanionObservationQueriesProgram.blockWidth + (CompanionOuterPhaseProgram.configs A C K H T N R L j epsilon z v reserve)= + CompanionPhaseWords.observationBits A C K j + (TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon))) := by + unfold CompanionOuterPhaseProgram.configs + exact CompanionObservationQueriesProgram.blockWidth_phaseConfigs A C K j _ z v _ _ _ _ + +lemma configs_blockWidth_reserve (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (a b : List Bool) : + CompanionObservationQueriesProgram.blockWidth + (CompanionOuterPhaseProgram.configs A C K H T N R L j epsilon z v a)= + CompanionObservationQueriesProgram.blockWidth + (CompanionOuterPhaseProgram.configs A C K H T N R L j epsilon z v b) := by + rw [configs_blockWidth,configs_blockWidth] + +def tailWidth (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) (padding : ℕ) : ℕ := + let p := CompanionInitializedRestartProgram.parameters A H T N R L epsilon + let xi := TreeFraction.val (CountingPhaseParametersProgram.noise p) + let k := CountingPhaseParametersProgram.precision p + let obs := CountingPhaseParametersProgram.observations p + obs*CompanionBooleanPhase.stepBits A C K j k xi+ + ((obs+1)*CompanionObservationQueriesProgram.blockWidth + (CompanionOuterPhaseProgram.configs A C K H T N R L j epsilon z v reserve)+padding) + +def phaseWidth (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) (padding : ℕ) : ℕ := + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon)+ + tailWidth A C K H T N R L j epsilon z v reserve padding) + +lemma phaseWidth_reserve (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (a b : List Bool) (padding : ℕ) : + phaseWidth A C K H T N R L j epsilon z v a padding= + phaseWidth A C K H T N R L j epsilon z v b padding := by + unfold phaseWidth tailWidth + rw [configs_blockWidth_reserve A C K H T N R L j epsilon z v a b] + +lemma initialWidth_eq (A : Instance (Fin m) (Fin n)) (C K H N R L j : ℕ) + (epsilon : TreeFraction.Fraction) : + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + CompanionRestartProgram.sumBits A C K j + (CompanionInitializedRestartProgram.parameters A H + (CompanionTargetMixing.restartTime A H L) N R L epsilon)= + RootedRestartWords.initialStageBits A C K H L + (CountingPhaseParametersProgram.precision + (CompanionInitializedRestartProgram.parameters A H + (CompanionTargetMixing.restartTime A H L) N R L epsilon)) + R (CountingPhaseSchedule.initialPrecision H) j + (TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A H + (CompanionTargetMixing.restartTime A H L) N R L epsilon))) := by + rw [CompanionRestartSchedule.initialWidths_eq] + rfl + +theorem phaseWidth_source (A : Instance (Fin m) (Fin n)) + (s : RootedPhaseHistory.Settings A) (N j : ℕ) (epsilon : TreeFraction.Fraction) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) s.K) + (reserve : List Bool) (padding : ℕ) + (hk : CountingPhaseParametersProgram.precision + (CompanionInitializedRestartProgram.parameters A s.H + (CompanionTargetMixing.restartTime A s.H s.L) N s.n s.L epsilon)=s.k) + (hN : CountingPhaseParametersProgram.observations + (CompanionInitializedRestartProgram.parameters A s.H + (CompanionTargetMixing.restartTime A s.H s.L) N s.n s.L epsilon)=s.N) + (hh : CountingPhaseSchedule.initialPrecision s.H=s.h) + (hxi : TreeFraction.val (CountingPhaseParametersProgram.noise + (CompanionInitializedRestartProgram.parameters A s.H + (CompanionTargetMixing.restartTime A s.H s.L) N s.n s.L epsilon))=s.xi) : + phaseWidth A s.C s.K s.H (CompanionTargetMixing.restartTime A s.H s.L) + N s.n s.L j epsilon z v reserve padding=RootedPhaseHistory.width A s j+padding := by + unfold phaseWidth tailWidth + rw [configs_blockWidth] + rw [←Nat.add_assoc,initialWidth_eq] + simp only [hk,hN,hh,hxi,RootedPhaseHistory.width,CompanionPhaseWords.phaseBits,Nat.add_assoc] + +end +end ContingencyTables.CompanionOuterWidths + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseComposition.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseComposition.lean new file mode 100644 index 0000000000000000000000000000000000000000..90ce0568be169a866fbfabb15246aab93070312a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseComposition.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Counting.InitialMultiplierValues +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierUpdate + +namespace OAI + +/-! +# Actual companion phase history and counting-error composition + +Each stored multiplier is the explicit initial rational value followed by +the actual empirical plain/defect update. Successful finite observations +propagate goodness and add at most 4 eta to the logarithmic counting error. +-/ + +namespace ContingencyTables.CompanionPhaseComposition + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication CompanionAnnealing CompanionInitialization +open CompanionMultiplierUpdate TwoLiftStates + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def weights (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) : + ℕ → ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ + | 0 => CompanionInitialMultipliers.multiplier A + | j+1 => learnedMultipliers pairs (weights A samples j) (samples j) + +def Accurate (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) (eta : ℝ) (j : ℕ) : Prop := + AccuratePhase pairs (weights A samples j) (weight A j) (ratio A j) eta (samples j) + +/-- Goodness is obtained for the actual stored phase multipliers from +exact initialization and every preceding successful observation. -/ +theorem weights_good (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) + (eta : ℝ) (he0 : 0≤ eta) (he : eta≤1/4) (L : ℕ) + (hall : ∀ j< L,Accurate A samples eta j) : + GoodMultipliers pairs (weight A L) (weights A samples L) := by + induction L with + | zero => + simpa only [weights,weight,Nat.cast_zero,zero_div] using CompanionInitialMultipliers.initial_good A + | succ L ih => + have hg := ih (by intro j hj; exact hall j (by omega)) + exact successful_phase_learns A L (weights A samples L) hg.positive eta he0 he + (samples L) (hall L (by omega)) + +noncomputable def observedRatio (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) (j : ℕ) : ℝ := + empiricalRatio pairs (ratio A j) (samples j) + +noncomputable def total (A : Instance I J) (j : ℕ) : ℝ := slotTotal pairs (weight A j) ∅ + +lemma total_positive (A : Instance I J) (j : ℕ) : 0< total A j := + slotTotal_pos pairs _ (weight_positive A j) ∅ PairedLabels.fresh + +lemma observedRatio_positive (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) + (eta : ℝ) (he : eta≤1/4) (j : ℕ) + (hw : ∀ p r,0< weights A samples j p r) (hacc : Accurate A samples eta j) : + 0< observedRatio A samples j := by + have hZ := chainTotal_pos pairs PairedLabels.fresh PairedLabels.cover (weights A samples j) + (weight A j) (weight_positive A j) hw + have hp : 0< chainMean pairs (weights A samples j) (weight A j) (plainObservable pairs (ratio A j)) := by + rw [ratio_mean] + exact div_pos (total_positive A (j+1)) hZ + have hq : 0< chainMean pairs (weights A samples j) (weight A j) (plainObservable pairs (fun _ => 1)) := by + rw [plain_probability_mean pairs PairedLabels.fresh PairedLabels.cover] + exact div_pos (total_positive A j) hZ + have hph := relative_error_bounds _ _ _ (hacc (.inr ())) + simp only [phaseObservable] at hph + have hqh := accurate_plain pairs (weights A samples j) (weight A j) (ratio A j) eta (samples j) hacc + exact div_pos (AnnealingMultipliers.empirical_positive hp he hph.1) + (AnnealingMultipliers.empirical_positive hq he hqh.1) + +noncomputable def estimate (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) : ℕ → ℝ + | 0 => total A 0 + | j+1 => estimate A samples j*observedRatio A samples j + +/-- The actual product estimator has total logarithmic error at most +4 L eta on the event that every preceding phase observation is accurate. -/ +theorem estimate_log_error (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) + (eta : ℝ) (he0 : 0≤ eta) (he : eta≤1/4) (L : ℕ) + (hall : ∀ j< L,Accurate A samples eta j) : + 0< estimate A samples L ∧ + |Real.log (estimate A samples L/total A L)|≤4*(L:ℝ)*eta := by + induction L with + | zero => + have hT := total_positive A 0 + exact ⟨hT,by simp [estimate,div_self hT.ne']⟩ + | succ L ih => + have hprev : ∀ j< L,Accurate A samples eta j := by intro j hj; exact hall j (by omega) + have hE := ih hprev + have hg := weights_good A samples eta he0 he L hprev + have hR := observedRatio_positive A samples eta he L hg.positive (hall L (by omega)) + have hstep := successful_phase_ratio_log A L (weights A samples L) hg.positive eta he0 he + (samples L) (hall L (by omega)) + change |Real.log (observedRatio A samples L/(total A (L+1)/total A L))|≤4*eta at hstep + have hT := total_positive A L + have hT' := total_positive A (L+1) + have hid : estimate A samples (L+1)/total A (L+1)= + (estimate A samples L/total A L)*(observedRatio A samples L/(total A (L+1)/total A L)) := by + change (estimate A samples L*observedRatio A samples L)/total A (L+1)=_ + field_simp [hT.ne',hT'.ne'] + refine ⟨mul_pos hE.1 hR,?_⟩ + rw [hid,Real.log_mul (div_ne_zero hE.1.ne' hT.ne') + (div_ne_zero hR.ne' (div_ne_zero hT'.ne' hT.ne'))] + have hsum := abs_add_le (Real.log (estimate A samples L/total A L)) + (Real.log (observedRatio A samples L/(total A (L+1)/total A L))) + push_cast + linarith [hE.2,hstep] + +end ContingencyTables.CompanionPhaseComposition + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseContextProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseContextProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..983fa04d9b168ab0c2cda0fa31f3d19c03500338 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseContextProgram.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleConfigSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseParametersProgram + +namespace OAI + +/-! # Computing a phase configuration from immutable prepared data + +The reserve is used only through its length. All precision-marker bits +are false, so the physical configuration is independent of the random +contents of the word that provides its bounded allocation. +-/ + +namespace ContingencyTables.CompanionPhaseContextProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev Prepared := RootedOracleWalkProgram.State × CountingPhaseParametersProgram.Input +abbrev Input := (Prepared × ℕ) × List Bool + +def noise (z : Input) : TreeFraction.Fraction := CountingPhaseParametersProgram.noise z.1.1.2 +def noiseRealizer : Realizer noise := + composition (f := fun z : Input => z.1.1.2) (g := CountingPhaseParametersProgram.noise) + (composition (composition first first) second) CountingPhaseParametersProgram.noiseRealizer +lemma polynomial_noise : PolynomialTime noiseRealizer := + polynomial_composition (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) CountingPhaseParametersProgram.polynomial_noise + +def precision (z : Input) : ℕ := CountingPhaseParametersProgram.precision z.1.1.2 +def precisionRealizer : Realizer precision := + composition (f := fun z : Input => z.1.1.2) (g := CountingPhaseParametersProgram.precision) + (composition (composition first first) second) CountingPhaseParametersProgram.precisionRealizer +lemma polynomial_precision : PolynomialTime precisionRealizer := + polynomial_composition (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) CountingPhaseParametersProgram.polynomial_precision + +def scalar (e : ScalarScheduleProgram.Expr) (z : Input) : ℕ := + CountingPhaseParametersProgram.scalar e z.1.1.2 +def scalarRealizer (e : ScalarScheduleProgram.Expr) : Realizer (scalar e) := + composition (f := fun z : Input => z.1.1.2) (g := CountingPhaseParametersProgram.scalar e) + (composition (composition first first) second) (CountingPhaseParametersProgram.scalarRealizer e) +lemma polynomial_scalar (e : ScalarScheduleProgram.Expr) : PolynomialTime (scalarRealizer e) := + polynomial_composition (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) (CountingPhaseParametersProgram.polynomial_scalar e) + +def falseReserve (z : Input) : List Bool := z.2.map (fun _ => false) +def falseReserveRealizer : Realizer falseReserve := composition second (map (constant false)) +lemma polynomial_falseReserve : PolynomialTime falseReserveRealizer := + polynomial_composition polynomial_second (polynomial_map (polynomial_constant false)) + +def configInput (z : Input) : RootedOracleConfigProgram.Input := + (((z.1.1.1,noise z),z.1.2),falseReserve z) +def configInputRealizer : Realizer configInput := + pair (pair (pair (composition (composition first first) first) noiseRealizer) + (composition first second)) falseReserveRealizer +lemma polynomial_configInput : PolynomialTime configInputRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_noise) (polynomial_composition polynomial_first polynomial_second)) polynomial_falseReserve + +def config (z : Input) : RootedLabelWeightProgram.Config := + RootedOracleConfigProgram.output (configInput z) +def configRealizer : Realizer config := + composition (f := configInput) (g := RootedOracleConfigProgram.output) + configInputRealizer RootedOracleConfigProgram.outputRealizer +theorem polynomial_config : PolynomialTime configRealizer := + polynomial_composition polynomial_configInput RootedOracleConfigProgram.polynomial_output + +lemma falseReserve_length (z : Input) : (falseReserve z).length=z.2.length := List.length_map _ + +lemma falseReserve_eq (z : Input) : falseReserve z=List.replicate z.2.length false := by + unfold falseReserve + induction z.2 with + | nil => rfl + | cons b bs ih => simpa only [List.map_cons,List.length_cons,List.replicate_succ] using congrArg (List.cons false) ih + +noncomputable section +open CompanionFactorialApplication CompanionOracleDensity GridBoundary +open scoped Classical +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (reserve : List Bool) : Input := + (((RootedOracleWalkProgram.data A C 0 K z v,parameters),j),reserve) + +lemma config_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (reserve : List Bool) : + config (data A C K j parameters z v reserve)= + RootedOracleConfigProgram.output (RootedOracleConfigProgram.data A C K j + (CountingPhaseParametersProgram.noise parameters) z v (List.replicate reserve.length false)) := by + unfold config configInput noise data + rw [falseReserve_eq] + rfl + +end +end ContingencyTables.CompanionPhaseContextProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseContinuation.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseContinuation.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec2063adffe9f625e0b5c2ddaf80bc5ad8709e47 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseContinuation.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTrialPadding + +namespace OAI + +/-! # Continuing an adaptive phase from its initialized profile -/ +namespace ContingencyTables.CompanionPhaseContinuation +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram +open CompanionOracleDensity CompanionWeightOracle GridBoundary FiniteObservableTransport CommonBasesFPRAS TwoLiftStates +open scoped Classical +noncomputable section + +abbrev Configs := CompanionObservedUpdateProgram.Configs +abbrev Stored := CompanionPhaseFinishProgram.Stored + +def state (cs : Configs) (old : Stored) (k : ℕ) (code : List ℕ) : CompanionBoundedWalkProgram.State := + ((((cs.1,old.1),k),code),code) + +def width (cs : Configs) (old : Stored) (k : ℕ) (code : List ℕ) : ℕ := + CompanionTransitionWidth.width ((((cs.1,old.1),k),code),[]) + +def input (cs : Configs) (old : Stored) (k N : ℕ) (code : List ℕ) (tail : List Bool) : + CompanionPhaseTrialProgram.Input := + (((cs,old),((state cs old k code,N),tail.take (N*width cs old k code))), + tail.drop (N*width cs old k code)) + +def run (cs : Configs) (old : Stored) (k N : ℕ) (code : List ℕ) (tail : List Bool) : Stored := + (CompanionPhaseTrialProgram.output (input cs old k N code tail)).getD old + +lemma outer_eq (z : CompanionOuterPhaseProgram.Input) : + CompanionOuterPhaseProgram.output z= + run (CompanionOuterPhaseProgram.configAt 0 z,CompanionOuterPhaseProgram.configAt 1 z) + (CompanionOuterPhaseProgram.old z) (CompanionOuterPhaseProgram.precision z) + (CompanionOuterPhaseProgram.observations z) (CompanionOuterPhaseProgram.startCode z) + (CompanionOuterPhaseProgram.afterRestart z) := rfl + +lemma view_getD {p : ℕ} (o : Option Stored) (s : Stored) : + CompanionPhaseFinishProgram.view (p := p) (o.getD s)= + (o.map CompanionPhaseFinishProgram.view).getD (CompanionPhaseFinishProgram.view s) := by + cases o <;> rfl + +variable {m n : ℕ} + +lemma input_encoded (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) (xi : ℚ) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth nextDegree nextDepth : List Bool) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (E : TreeFraction.Fraction) + (S : CompanionBooleanPhase.State A) (tail : List Bool) : + let cs := CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth + input cs (matrixCode w,E) k N (encodeSet (coordinateOrder A) S.val) tail= + CompanionPhaseTrialProgram.data A C K j k N xi z v degree depth nextDegree nextDepth w E S + (tail.take (N*CompanionBooleanPhase.stepBits A C K j k xi)) + (tail.drop (N*CompanionBooleanPhase.stepBits A C K j k xi)) := by + dsimp only + unfold input width + change (((_,_),((_,N),tail.take (N*CompanionTransitionWidth.width + (CompanionMetropolisWordProgram.packed + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w) + k (encodeSet (coordinateOrder A) S.val) [])))), + tail.drop (N*CompanionTransitionWidth.width + (CompanionMetropolisWordProgram.packed + (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w) + k (encodeSet (coordinateOrder A) S.val) [])))=_ + rw [CompanionTransitionWidth.width_config] + rfl + + +theorem run_sameLaw (padding : ℕ) (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) + (hC : 0 + CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + (run cs (matrixCode w,E) k N (encodeSet (coordinateOrder A) S.val) (List.ofFn bits))) + (fun bits : RootedPhaseTrial.TrialWords A C K j k N xi => + CompanionPhaseFinishProgram.storedView A (pairLabels A) + ((RootedPhaseTrial.trial A (RootedCompletion.rowColumn A.T) C K j k N hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old S bits).getD old)) := by + dsimp only + let cs := CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth + let t := N*CompanionBooleanPhase.stepBits A C K j k xi + let q := (N+1)*CompanionObservationQueriesProgram.blockWidth cs + let project := CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + let oldView := CompanionPhaseFinishProgram.storedView A (pairLabels A) old + have hold : project (matrixCode w,E)=oldView := by + apply Prod.ext + · funext i j + exact (congrArg TreeFraction.val (readEntry_code w i j)).trans (hw i j) + · exact hE + have h := CompanionPhaseTrialProgram.trial_padded_sameLaw padding A C K j k N hC hj hK hW hB + xi hxi z v degree depth nextDegree nextDepth hdegree hdepth hnextDegree hnextDepth old w E hw hE S + dsimp only at h + have hm := h.map (fun o => o.getD oldView) + intro phi + have he := uniformAverage_equiv (FairBits.splitWordEquiv t (q+padding)) + (fun p => phi (((CompanionPhaseTrialProgram.output (CompanionPhaseTrialProgram.data A C K j k N + xi z v degree depth nextDegree nextDepth w E S (List.ofFn p.1) (List.ofFn p.2))).map project).getD oldView)) + have hleft (bits : Fin (t+(q+padding))→Bool) : + project (run cs (matrixCode w,E) k N (encodeSet (coordinateOrder A) S.val) (List.ofFn bits))= + (((CompanionPhaseTrialProgram.output (CompanionPhaseTrialProgram.data A C K j k N xi z v + degree depth nextDegree nextDepth w E S + (List.ofFn (FairBits.splitWordEquiv t (q+padding) bits).1) + (List.ofFn (FairBits.splitWordEquiv t (q+padding) bits).2))).map project).getD oldView) := by + unfold run + rw [input_encoded] + dsimp only [project] at hold ⊢ + rw [view_getD,hold,DensePrograms.ofFn_split_take,DensePrograms.ofFn_split_drop] + have hright (bits : RootedPhaseTrial.TrialWords A C K j k N xi) : + ((RootedPhaseTrial.trial A (RootedCompletion.rowColumn A.T) C K j k N hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old S bits).map + (CompanionPhaseFinishProgram.storedView A (pairLabels A))).getD oldView= + CompanionPhaseFinishProgram.storedView A (pairLabels A) + ((RootedPhaseTrial.trial A (RootedCompletion.rowColumn A.T) C K j k N hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old S bits).getD old) := by + cases RootedPhaseTrial.trial A (RootedCompletion.rowColumn A.T) C K j k N hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old S bits <;> rfl + have hl : uniformAverage (fun bits : Fin (t+(q+padding))→Bool => + phi (project (run cs (matrixCode w,E) k N (encodeSet (coordinateOrder A) S.val) (List.ofFn bits))))= + uniformAverage (fun p : (Fin t→Bool)×(Fin (q+padding)→Bool) => phi (((CompanionPhaseTrialProgram.output (CompanionPhaseTrialProgram.data A C K j k N + xi z v degree depth nextDegree nextDepth w E S (List.ofFn p.1) (List.ofFn p.2))).map project).getD oldView)) := by + simp_rw [hleft] + exact he + exact hl.trans ((hm phi).trans (by simp_rw [hright])) + +end +end ContingencyTables.CompanionPhaseContinuation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseCounts.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..031edddb99144cf59d554a977aedacf3c55c6235 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseCounts.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionComputedProposal +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTraceProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRationalUpdates + +namespace OAI + +/-! # Executable counts in an outer counting phase + +The stored trajectory is scanned directly. Both the transversal count +and each labelled defect count use the actual polynomial occupancy +tests. No set-state enumeration is performed. +-/ + +namespace ContingencyTables.CompanionPhaseCounts + +open MatchingFPRAS.TreeTyped ProfilePrograms CompanionChainValidator +open CompanionTraceProgram CompanionOrderedProposal CompanionArithmeticProposal +open CompanionFactorialApplication CompanionBooleanPhase +open CommonBasesFPRAS TwoLiftStates +open scoped Classical + +def plainCountCode (z : ReturnInput) : ℕ := + (z.2.filter (fun xs => pairedPlainTest (z.1,xs))).length + +def plainCountRealizer : Realizer plainCountCode := + composition (filterWith pairedPlainTestRealizer) listLength + +theorem polynomial_plainCount : PolynomialTime plainCountRealizer := + polynomial_composition (polynomial_filterWith polynomial_pairedPlainTest) polynomial_listLength + +def pairedDefectTest (z : ValidatorInput×(ℕ×ℕ)) : Bool := + defectTest (((z.1.1.map (fun ij => z.1.2.getD ij.1 0), + z.1.1.map (fun ij => z.1.2.getD ij.2 0)),1),z.2) + +def pairedDefectTestRealizer : Realizer pairedDefectTest := + composition (pair (pair (pair + (composition (pair (composition first second) (composition first first)) + (mapWith pairFirstLookup)) + (composition (pair (composition first second) (composition first first)) + (mapWith pairSecondLookup))) (constant 1)) second) defectTestRealizer + +theorem polynomial_pairedDefectTest : PolynomialTime pairedDefectTestRealizer := + polynomial_composition (polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_first polynomial_first)) + (polynomial_mapWith polynomial_pairFirstLookup)) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_first polynomial_first)) + (polynomial_mapWith polynomial_pairSecondLookup))) (polynomial_constant 1)) + polynomial_second) polynomial_defectTest + +abbrev DefectCountInput := ReturnInput×(ℕ×ℕ) + +def defectItem (z : (List (ℕ×ℕ)×(ℕ×ℕ))×List ℕ) : Bool := + pairedDefectTest ((z.1.1,z.2),z.1.2) + +def defectItemRealizer : Realizer defectItem := + composition (pair (pair (composition first first) second) (composition first second)) + pairedDefectTestRealizer + +lemma polynomial_defectItem : PolynomialTime defectItemRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_second)) polynomial_pairedDefectTest + +def defectCountCode (z : DefectCountInput) : ℕ := + (z.1.2.filter (fun xs => pairedDefectTest ((z.1.1,xs),z.2))).length + +def defectCountRealizer : Realizer defectCountCode := + composition (composition (pair (pair (composition first first) second) + (composition first second)) (filterWith defectItemRealizer)) listLength + +theorem polynomial_defectCount : PolynomialTime defectCountRealizer := + polynomial_composition (polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_second)) + (polynomial_filterWith polynomial_defectItem)) polynomial_listLength + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] +variable (A : Instance I J) {p m : ℕ} (g : Fin p ≃ Labels A) + (e : (Labels A×Bool) ≃ Fin m) + +lemma plainTest_ordered (S : Set (Labels A×Bool)) : + pairedPlainTest (orderedCatalog A g e,encodeSet e S)=true ↔ PlainState pairs S := by + unfold pairedPlainTest orderedCatalog + simp only [List.map_ofFn] + change balancedTest ((List.ofFn (fun i : Fin p => (encodeSet e S).getD (e (g i,false)).val 0), + List.ofFn (fun i : Fin p => (encodeSet e S).getD (e (g i,true)).val 0)),1)=true ↔ _ + simp only [encodeSet,getD_setProfile,setProfile,coordinateSet,Set.mem_preimage, + Equiv.symm_apply_apply] + rw [balancedTest_ofFn,plain_iff_occupancy] + change (∀ i,occupancy S (g i)=1) ↔ ∀ a,occupancy S a=1 + constructor + · intro h a + simpa only [Equiv.apply_symm_apply] using h (g.symm a) + · intro h i + exact h (g i) + +lemma defectTest_ordered (S : Set (Labels A×Bool)) (i j : Fin p) : + pairedDefectTest ((orderedCatalog A g e,encodeSet e S),(i.val,j.val))=true ↔ + DefectState pairs (pair (g i)) (pair (g j)) S := by + classical + unfold pairedDefectTest orderedCatalog + simp only [List.map_ofFn] + change defectTest (((List.ofFn (fun k : Fin p => (encodeSet e S).getD (e (g k,false)).val 0), + List.ofFn (fun k : Fin p => (encodeSet e S).getD (e (g k,true)).val 0)),1), + (i.val,j.val))=true ↔ _ + simp only [encodeSet,getD_setProfile,setProfile,coordinateSet,Set.mem_preimage, + Equiv.symm_apply_apply] + rw [defectTest_ofFn,defect_iff_occupancy] + constructor + · rintro ⟨hij,h⟩ + refine ⟨fun he => hij (g.injective he),fun a => ?_⟩ + have hh := h (g.symm a) + by_cases hai : a=g i <;> by_cases haj : a=g j + all_goals simpa only [occupancy,Equiv.apply_symm_apply,Equiv.symm_apply_eq, + hai,haj,ite_true,ite_false] using hh + · rintro ⟨hij,h⟩ + refine ⟨fun he => hij (congrArg g he),fun k => ?_⟩ + simpa only [occupancy,Equiv.apply_eq_iff_eq] using h (g k) + +theorem plainCount_code (states : List (Set (Labels A×Bool))) : + plainCountCode (orderedCatalog A g e,states.map (encodeSet e))= + CompanionRationalUpdates.plainCount A states := by + unfold plainCountCode CompanionRationalUpdates.plainCount + rw [List.filter_map,List.length_map,List.countP_eq_length_filter] + congr 1 + apply List.filter_congr + intro S _ + exact Bool.eq_iff_iff.mpr (by simp only [Function.comp_apply,plainTest_ordered,decide_eq_true_eq]) + +theorem defectCount_code (states : List (Set (Labels A×Bool))) (i j : Fin p) : + defectCountCode ((orderedCatalog A g e,states.map (encodeSet e)),(i.val,j.val))= + CompanionRationalUpdates.defectCount A states (pair (g i)) (pair (g j)) := by + unfold defectCountCode CompanionRationalUpdates.defectCount + rw [List.filter_map,List.length_map,List.countP_eq_length_filter] + congr 1 + apply List.filter_congr + intro S _ + exact Bool.eq_iff_iff.mpr (by simp only [Function.comp_apply,defectTest_ordered,decide_eq_true_eq]) + +end +end ContingencyTables.CompanionPhaseCounts + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseFinishProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseFinishProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa3a7df8551481d43137b48f9b70308b3dd2e0cb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseFinishProgram.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierMatrixProgram +import OAI.Combinatorics.ContingencyTables.Machines.FractionAggregateProgram + +namespace OAI + +/-! # Executing the observed ratio and learned phase update + +The supplied pairs contain the current and next weight queries for every +observed state. Only plain states contribute to the ratio. The same actual +trajectory supplies the plain/defect counts and the abort test. +-/ +namespace ContingencyTables.CompanionPhaseFinishProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial +open CompanionTraceProgram CompanionMultiplierMatrixProgram CompanionPhaseCounts + +abbrev Fraction := TreeFraction.Fraction +abbrev Stored := FractionMatrix×Fraction +abbrev Input := ((ReturnInput×FractionMatrix)×Fraction)×List (Fraction×Fraction) +abbrev TermInput := CompanionChainValidator.ValidatorInput×(Fraction×Fraction) + +def term (z : TermInput) : Fraction := + if CompanionTraceProgram.pairedPlainTest z.1 then TreeFraction.div (z.2.2,z.2.1) else (0,1) +def termRealizer : Realizer term := + choose (composition (f := fun z : TermInput => z.1) (g := CompanionTraceProgram.pairedPlainTest) + first CompanionTraceProgram.pairedPlainTestRealizer) + (composition (f := fun z : TermInput => (z.2.2,z.2.1)) (g := TreeFraction.div) + (pair (composition second second) (composition second first)) TreeFraction.divRealizer) + (constant (0,1)) +lemma polynomial_term : PolynomialTime termRealizer := + polynomial_choose (polynomial_composition polynomial_first CompanionTraceProgram.polynomial_pairedPlainTest) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition polynomial_second polynomial_first)) TreeFraction.polynomial_div) + (polynomial_constant (0,1)) + +lemma term_den_pos (z : TermInput) : 0 < (term z).2 := by + unfold term + split_ifs + · exact TreeFraction.normalize_den_pos _ + · decide + +def trajectory (z : Input) : ReturnInput := z.1.1.1 +def trajectoryRealizer : Realizer trajectory := composition (composition first first) first +lemma polynomial_trajectory : PolynomialTime trajectoryRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first + +def indices (z : Input) : List ℕ := List.range (trajectory z).2.length +def indicesRealizer : Realizer indices := + composition (composition (composition trajectoryRealizer second) listLength) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_trajectory polynomial_second) polynomial_listLength) X + intro z + simpa only [eval_X,Function.comp_apply] using + (list_length_le_weight (trajectory z).2).trans + ((weight_snd (trajectory z)).trans + ((weight_fst z.1.1).trans ((weight_fst z.1).trans (weight_fst z)))) + +def termInput (z : Input×ℕ) : TermInput := + (((trajectory z.1).1,(trajectory z.1).2.getD z.2 []),z.1.2.getD z.2 ((0,1),(0,1))) +def termInputRealizer : Realizer termInput := + pair (pair (composition (composition (f := fun z : Input×ℕ => z.1) (g := trajectory) first trajectoryRealizer) first) + (composition (pair (composition (composition (f := fun z : Input×ℕ => z.1) (g := trajectory) first trajectoryRealizer) second) second) (getDFast []))) + (composition (pair (composition first second) second) (getDFast ((0,1),(0,1)))) +lemma polynomial_termInput : PolynomialTime termInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_trajectory) polynomial_first) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_trajectory) polynomial_second) + polynomial_second) (polynomial_getDFast []))) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second) (polynomial_getDFast ((0,1),(0,1)))) + +def indexedTerm (z : Input×ℕ) : Fraction := term (termInput z) +def indexedTermRealizer : Realizer indexedTerm := + composition (f := termInput) (g := term) termInputRealizer termRealizer +lemma polynomial_indexedTerm : PolynomialTime indexedTermRealizer := + polynomial_composition polynomial_termInput polynomial_term + +def terms (z : Input) : List Fraction := (indices z).map (fun i => indexedTerm (z,i)) +def termsRealizer : Realizer terms := composition (pair identity indicesRealizer) (mapWith indexedTermRealizer) +lemma polynomial_terms : PolynomialTime termsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_indexedTerm) + +attribute [local irreducible] trajectory terms + +def total (z : Input) : Fraction := TreeFraction.sum (terms z) +def totalRealizer : Realizer total := + composition (f := terms) (g := TreeFraction.sum) termsRealizer TreeFraction.sumRealizer +lemma polynomial_total : PolynomialTime totalRealizer := + polynomial_composition polynomial_terms TreeFraction.polynomial_sum + +def count (z : Input) : Fraction := (plainCountCode (trajectory z),1) +def countRealizer : Realizer count := + pair (composition (f := trajectory) (g := plainCountCode) trajectoryRealizer plainCountRealizer) (constant 1) +lemma polynomial_count : PolynomialTime countRealizer := + polynomial_pair (polynomial_composition polynomial_trajectory polynomial_plainCount) (polynomial_constant 1) + +def ratio (z : Input) : Fraction := TreeFraction.div (total z,count z) +def ratioRealizer : Realizer ratio := + composition (f := fun z : Input => (total z,count z)) (g := TreeFraction.div) + (pair totalRealizer countRealizer) TreeFraction.divRealizer +lemma polynomial_ratio : PolynomialTime ratioRealizer := + polynomial_composition (polynomial_pair polynomial_total polynomial_count) TreeFraction.polynomial_div + +attribute [local irreducible] ratio + +def estimate (z : Input) : Fraction := TreeFraction.mul (z.1.2,ratio z) +def estimateRealizer : Realizer estimate := + composition (f := fun z : Input => (z.1.2,ratio z)) (g := TreeFraction.mul) + (pair (composition first second) ratioRealizer) TreeFraction.mulRealizer +lemma polynomial_estimate : PolynomialTime estimateRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_ratio) TreeFraction.polynomial_mul + +def next (z : Input) : Stored := (updateMatrix z.1.1,estimate z) +def nextRealizer : Realizer next := + pair (composition (f := fun z : Input => z.1.1) (g := updateMatrix) + (composition first first) updateMatrixRealizer) estimateRealizer +lemma polynomial_next : PolynomialTime nextRealizer := + polynomial_pair (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_updateMatrix) polynomial_estimate + +attribute [local irreducible] next + +def output (z : Input) : Option Stored := + if positiveCounts (trajectory z) then some (next z) else none +def outputRealizer : Realizer output := + choose (composition (f := trajectory) (g := positiveCounts) trajectoryRealizer positiveCountsRealizer) + (composition (f := next) (g := Option.some) nextRealizer TreeTyped.some) (constant none) +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_choose (polynomial_composition polynomial_trajectory polynomial_positiveCounts) + (polynomial_composition polynomial_next polynomial_some) (polynomial_constant none) + +end ContingencyTables.CompanionPhaseFinishProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseFinishSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseFinishSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..892503f97b6549ee1a6501565e5868abb7a12249 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseFinishSemantics.lean @@ -0,0 +1,219 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseFinishProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseWords + +namespace OAI + +/-! # Exact semantics of the stored phase update -/ +namespace ContingencyTables.CompanionPhaseFinishProgram +open MatchingFPRAS CompanionFactorialApplication CompanionTraceProgram CompanionPhaseCounts +open CompanionMultiplierMatrixProgram CompanionMultiplierProgram CompanionOrderedProposal +open CompanionArithmeticProposal CompanionRationalUpdates CommonBasesFPRAS TwoLiftStates +open scoped BigOperators Classical +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] +variable (A : Instance I J) {p q N : ℕ} (g : Fin p ≃ Labels A) (e : (Labels A×Bool) ≃ Fin q) + +def data (states : Fin N→Set (Labels A×Bool)) + (w : Fin p→Fin p→Fraction) (estimate : Fraction) (values : Fin N→Fraction×Fraction) : Input := + ((((orderedCatalog A g e,(List.ofFn states).map (encodeSet e)),matrixCode w),estimate),List.ofFn values) + +lemma termInput_data (states : Fin N→Set (Labels A×Bool)) + (w : Fin p→Fin p→Fraction) (E : Fraction) (values : Fin N→Fraction×Fraction) (i : Fin N) : + termInput (data A g e states w E values,i.val)= + ((orderedCatalog A g e,encodeSet e (states i)),values i) := by + simp only [termInput,data,trajectory,List.map_ofFn,List.getD_eq_getElem?_getD, + List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some,Fin.eta,Function.comp_apply] + +lemma term_value (states : Fin N→Set (Labels A×Bool)) + (w : Fin p→Fin p→Fraction) (E : Fraction) (values : Fin N→Fraction×Fraction) (i : Fin N) : + TreeFraction.val (indexedTerm (data A g e states w E values,i.val))= + if PlainState pairs (states i) then TreeFraction.val (values i).2/TreeFraction.val (values i).1 else 0 := by + rw [indexedTerm,termInput_data] + have hp : pairedPlainTest (orderedCatalog A g e,encodeSet e (states i))= + decide (PlainState pairs (states i)) := + Bool.eq_iff_iff.mpr (by simp only [plainTest_ordered,decide_eq_true_eq]) + unfold term + rw [hp] + by_cases h : PlainState pairs (states i) + · simp only [h,decide_true,ite_true,TreeFraction.div_val] + · simp only [h,decide_false,Bool.false_eq_true,ite_false,TreeFraction.val, + Nat.cast_zero,Nat.cast_one,zero_div] + +lemma terms_data (states : Fin N→Set (Labels A×Bool)) + (w : Fin p→Fin p→Fraction) (E : Fraction) (values : Fin N→Fraction×Fraction) : + terms (data A g e states w E values)= + List.ofFn (fun i : Fin N => indexedTerm (data A g e states w E values,i.val)) := by + unfold terms indices trajectory data + simp only [List.length_map,List.length_ofFn] + apply List.ext_getElem + · simp + · intro i hi _ + simp only [List.length_map,List.length_range] at hi + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + +lemma terms_den_pos (z : Input) (x : Fraction) (hx : x∈terms z) : 0 < x.2 := by + obtain ⟨i,_,rfl⟩ := List.mem_map.mp hx + exact term_den_pos _ + +lemma ratio_data (states : Fin N→Set (Labels A×Bool)) + (w : Fin p→Fin p→Fraction) (E : Fraction) (values : Fin N→Fraction×Fraction) : + TreeFraction.val (ratio (data A g e states w E values))= + (∑ i,if PlainState pairs (states i) then TreeFraction.val (values i).2/TreeFraction.val (values i).1 else 0)/ + (plainCount A (List.ofFn states):ℚ) := by + rw [ratio,TreeFraction.div_val,total,TreeFraction.sum_val _ (terms_den_pos _)] + rw [terms_data] + simp only [List.map_ofFn,List.sum_ofFn,Function.comp_apply,term_value] + have hc : TreeFraction.val (count (data A g e states w E values))= + (plainCount A (List.ofFn states):ℚ) := by + unfold count trajectory data + rw [plainCount_code] + simp only [TreeFraction.val,Nat.cast_one,div_one] + rw [hc] + +lemma updated_entry (states : Fin N→Set (Labels A×Bool)) (hl : 0 < N) + (w : Fin p→Fin p→Fraction) (old : CompanionPhaseWords.Stored A) + (hw : ∀ i j,TreeFraction.val (w i j)=old.multiplier (pair (g i)) (pair (g j))) (i j : Fin p) : + TreeFraction.val (readEntry + (updateMatrix ((orderedCatalog A g e,(List.ofFn states).map (encodeSet e)),matrixCode w),(i.val,j.val)))= + rationalLearn pairs old.multiplier (List.ofFn states) (pair (g i)) (pair (g j)) := by + rw [updateMatrix_code,readEntry_code,updateCode_value, + plainCount_code,defectCount_code,hw] + rw [rationalLearn_counts A old.multiplier (List.ofFn states) (by simpa only [List.length_ofFn] using hl)] + have hp : pair (g i)∈(pairs : List (Pair A)) := pair_mem _ + have hq : pair (g j)∈(pairs : List (Pair A)) := pair_mem _ + have he : pair (g i)=pair (g j) ↔ i=j := + ⟨fun h => g.injective (pair_injective h),fun h => congrArg (fun k => pair (g k)) h⟩ + by_cases hij : i=j + · subst j + simp only [hp,ne_eq,not_true_eq_false,and_false,ite_false,ite_true] + · have hv : i.val≠j.val := fun h => hij (Fin.ext h) + have hpq : pair (g i)≠pair (g j) := fun h => hij (he.mp h) + simp only [hv,hp,hq,true_and,ite_false] + exact (ite_eq_left hpq).symm + +/-- The relevant view of a physical stored value consists of its actual +label-pair entries and its rational estimate. -/ +def view (z : Stored) : (Fin p→Fin p→ℚ)×ℚ := + ((fun i j => TreeFraction.val (readEntry (z.1,(i.val,j.val)))),TreeFraction.val z.2) + +def storedView (s : CompanionPhaseWords.Stored A) : (Fin p→Fin p→ℚ)×ℚ := + ((fun i j => s.multiplier (pair (g i)) (pair (g j))),s.estimate) + +/-- The phase result as a function of just the rational query values. -/ +def rationalResult (states : Fin N→Set (Labels A×Bool)) (old : CompanionPhaseWords.Stored A) + (values : List (ℚ×ℚ)) : Option ((Fin p→Fin p→ℚ)×ℚ) := + if CountsPositive A (List.ofFn states) then + some ((fun i j => rationalLearn pairs old.multiplier (List.ofFn states) (pair (g i)) (pair (g j))), + old.estimate*((∑ i : Fin N,if PlainState pairs (states i) then + (values.getD i.val (0,0)).2/(values.getD i.val (0,0)).1 else 0)/ + (plainCount A (List.ofFn states):ℚ))) + else none + +lemma output_values (states : Fin N→Set (Labels A×Bool)) + (old : CompanionPhaseWords.Stored A) (w : Fin p→Fin p→Fraction) (E : Fraction) + (values : Fin N→Fraction×Fraction) + (hw : ∀ i j,TreeFraction.val (w i j)=old.multiplier (pair (g i)) (pair (g j))) + (hE : TreeFraction.val E=old.estimate) : + (output (data A g e states w E values)).map (view (p := p))= + rationalResult A g states old (List.ofFn (fun i => + (TreeFraction.val (values i).1,TreeFraction.val (values i).2))) := by + have ht : positiveCounts (trajectory (data A g e states w E values))=true ↔ + CountsPositive A (List.ofFn states) := positiveCounts_code A g e (List.ofFn states) + by_cases hp : CountsPositive A (List.ofFn states) + · have hN : 0 < N := by + simpa only [List.length_ofFn] using hp.1.trans_le (plainCount_le A (List.ofFn states)) + simp only [output,ht.mpr hp,ite_true,Option.map_some,rationalResult,hp] + apply congrArg Option.some + apply Prod.ext + · funext i k + exact updated_entry A g e states hN w old hw i k + · change TreeFraction.val (estimate (data A g e states w E values))=_ + rw [estimate,TreeFraction.mul_val,ratio_data] + dsimp only [data] + rw [hE] + congr 2 + apply Finset.sum_congr rfl + intro i _ + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some,Fin.eta] + · have htest : positiveCounts (trajectory (data A g e states w E values))=false := + Bool.eq_false_iff.mpr (fun h => hp (ht.mp h)) + simp only [output,htest,Bool.false_eq_true,ite_false,Option.map_none,rationalResult,hp] + +/-- Applying the physical arithmetic and then reading its canonical entries +is exactly the source update, including the abort outcome. -/ +theorem output_update (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : GridBoundary.Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (old : CompanionPhaseWords.Stored A) (states : Fin N→Set (Labels A×Bool)) + (w : Fin p→Fin p→Fraction) (E : Fraction) (values : Fin N→Fraction×Fraction) + (bits : Fin (CompanionPhaseWords.phaseBits A C K j N xi)→Bool) + (hw : ∀ i j,TreeFraction.val (w i j)=old.multiplier (pair (g i)) (pair (g j))) + (hE : TreeFraction.val E=old.estimate) + (hv : ∀ i, + TreeFraction.val (values i).1=RootedWeightOracle.evaluate A R C K hK hW j xi v (states i) + (CompanionPhaseWords.phaseWordEquiv A C K j N xi bits i).1 ∧ + TreeFraction.val (values i).2=RootedWeightOracle.evaluate A R C K hK hW (j+1) xi v (states i) + (CompanionPhaseWords.phaseWordEquiv A C K j N xi bits i).2) : + (output (data A g e states w E values)).map (view (p := p))= + (RootedPhaseWords.update A R C K j N hK hW xi v old states bits).map (storedView A g) := by + have ht : positiveCounts (trajectory (data A g e states w E values))=true ↔ + CountsPositive A (List.ofFn states) := + positiveCounts_code A g e (List.ofFn states) + have hr : TreeFraction.val (ratio (data A g e states w E values))= + RootedPhaseWords.observedRatio A R C K j N hK hW xi v states bits := by + rw [ratio_data] + unfold RootedPhaseWords.observedRatio + congr 1 + apply Finset.sum_congr rfl + intro i _ + rw [(hv i).1,(hv i).2] + rfl + by_cases hp : CountsPositive A (List.ofFn states) + · have htest := ht.mpr hp + have hN : 0 < N := by + simpa only [List.length_ofFn] using hp.1.trans_le (plainCount_le A (List.ofFn states)) + simp only [output,htest,ite_true,Option.map_some,RootedPhaseWords.update,hp] + apply congrArg Option.some + apply Prod.ext + · funext i k + change TreeFraction.val (readEntry + (updateMatrix ((orderedCatalog A g e,(List.ofFn states).map (encodeSet e)),matrixCode w), + (i.val,k.val)))=rationalLearn pairs old.multiplier (List.ofFn states) (pair (g i)) (pair (g k)) + exact updated_entry A g e states hN w old hw i k + · change TreeFraction.val (estimate (data A g e states w E values))= + old.estimate*RootedPhaseWords.observedRatio A R C K j N hK hW xi v states bits + rw [estimate,TreeFraction.mul_val,hr] + exact congrArg (fun q => q*RootedPhaseWords.observedRatio A R C K j N hK hW xi v states bits) hE + · have htest : positiveCounts (trajectory (data A g e states w E values))=false := + Bool.eq_false_iff.mpr (fun h => hp (ht.mp h)) + simp only [output,htest,Bool.false_eq_true,ite_false,Option.map_none,RootedPhaseWords.update,hp] + +lemma rationalResult_phase (R : RootedCompletion.Selection A.T) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : GridBoundary.Grid (I := Fin (CompanionOracleDensity.dimension A)) K) + (old : CompanionPhaseWords.Stored A) (states : Fin N→Set (Labels A×Bool)) + (bits : Fin (CompanionPhaseWords.phaseBits A C K j N xi)→Bool) : + rationalResult A g states old (List.ofFn (fun i => + (RootedWeightOracle.evaluate A R C K hK hW j xi v (states i) + (CompanionPhaseWords.phaseWordEquiv A C K j N xi bits i).1, + RootedWeightOracle.evaluate A R C K hK hW (j+1) xi v (states i) + (CompanionPhaseWords.phaseWordEquiv A C K j N xi bits i).2)))= + (RootedPhaseWords.update A R C K j N hK hW xi v old states bits).map (storedView A g) := by + by_cases hp : CountsPositive A (List.ofFn states) + · simp only [rationalResult,RootedPhaseWords.update,hp,ite_true,Option.map_some,storedView] + apply congrArg Option.some + apply Prod.ext + · rfl + · change old.estimate * _ = old.estimate * _ + unfold RootedPhaseWords.observedRatio + apply congrArg (fun t : ℚ => old.estimate*(t/(plainCount A (List.ofFn states):ℚ))) + apply Finset.sum_congr rfl + intro i _ + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some,Fin.eta] + rfl + · simp only [rationalResult,RootedPhaseWords.update,hp,ite_false,Option.map_none] + +end +end ContingencyTables.CompanionPhaseFinishProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseOracleError.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseOracleError.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ea63077422cc4c452f4b66aaffa790984cdbbe8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseOracleError.lean @@ -0,0 +1,302 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseWords +import OAI.Combinatorics.ContingencyTables.Transport.FiniteIndependentFailures + +namespace OAI + +/-! # Error contributed by the actual fresh weight calls in a phase -/ + +namespace ContingencyTables.CompanionPhaseWords + +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle CompanionRationalUpdates +open CommonBasesFPRAS FiniteIndependentAverages GridBoundary TwoLiftStates +open scoped BigOperators Classical + +noncomputable section + +lemma average_ext_instances {X : Type*} (s t : Fintype X) (f g : X → ℝ) + (h : ∀ x,f x=g x) : @uniformAverage X s f=@uniformAverage X t g := by + cases Subsingleton.elim s t + exact congrArg (@uniformAverage X s) (funext h) + +lemma failure_of_success {X : Type*} [Fintype X] [Nonempty X] + (P : X → Prop) (delta : ℝ) + (h : 1-delta ≤ uniformAverage (fun x => if P x then (1:ℝ) else 0)) : + uniformAverage (fun x => if ¬P x then (1:ℝ) else 0) ≤ delta := by + have hp (x : X) : (if P x then (1:ℝ) else 0)+(if ¬P x then 1 else 0)=1 := by + by_cases hx : P x <;> simp [hx] + have he := uniformAverage_add (fun x => if P x then (1:ℝ) else 0) + (fun x => if ¬P x then (1:ℝ) else 0) + simp_rw [hp] at he + rw [uniformAverage_const] at he + linarith + +lemma independent_pair_failure {X Y : Type*} [Fintype X] [Fintype Y] + [Nonempty X] [Nonempty Y] (P : X → Prop) (Q : Y → Prop) + (a b : ℝ) (hP : uniformAverage (fun x => if ¬P x then (1:ℝ) else 0) ≤ a) + (hQ : uniformAverage (fun y => if ¬Q y then (1:ℝ) else 0) ≤ b) : + uniformAverage (fun xy : X×Y => if ¬(P xy.1 ∧ Q xy.2) then (1:ℝ) else 0) ≤ a+b := by + have hfst : uniformAverage (fun xy : X×Y => if ¬P xy.1 then (1:ℝ) else 0)= + uniformAverage (fun x => if ¬P x then (1:ℝ) else 0) := by + calc + _ = uniformAverage (fun x : X => uniformAverage (fun _y : Y => if ¬P x then (1:ℝ) else 0)) := + @uniformAverage_prod X Y _ _ (fun xy : X×Y => if ¬P xy.1 then (1:ℝ) else 0) + _ = _ := by simp_rw [uniformAverage_const] + have hsnd : uniformAverage (fun xy : X×Y => if ¬Q xy.2 then (1:ℝ) else 0)= + uniformAverage (fun y => if ¬Q y then (1:ℝ) else 0) := by + calc + _ = uniformAverage (fun _x : X => uniformAverage (fun y : Y => if ¬Q y then (1:ℝ) else 0)) := + @uniformAverage_prod X Y _ _ (fun xy : X×Y => if ¬Q xy.2 then (1:ℝ) else 0) + _ = _ := uniformAverage_const _ + calc + _ ≤ uniformAverage (fun xy : X×Y => + (if ¬P xy.1 then (1:ℝ) else 0)+(if ¬Q xy.2 then (1:ℝ) else 0)) := by + apply uniformAverage_mono + intro xy + by_cases hp : P xy.1 <;> by_cases hq : Q xy.2 <;> simp [hp,hq] + _ = uniformAverage (fun x => if ¬P x then (1:ℝ) else 0)+ + uniformAverage (fun y => if ¬Q y then (1:ℝ) else 0) := by + rw [uniformAverage_add,hfst,hsnd] + _ ≤ a+b := add_le_add hP hQ + +lemma independent_reindex_failure {X Y : Type*} [Fintype X] [Fintype Y] [Nonempty X] + (N : ℕ) (e : Y ≃ (Fin N → X)) (P : Fin N → X → Prop) : + uniformAverage (fun y : Y => if ¬(∀ i,P i (e y i)) then (1:ℝ) else 0) ≤ + ∑ i : Fin N,uniformAverage (fun x : X => if ¬P i x then (1:ℝ) else 0) := by + let bad (i : Fin N) (x : X) := ¬P i x + have he := uniformAverage_equiv e + (fun xs : Fin N → X => if ∃ i,bad i (xs i) then (1:ℝ) else 0) + have hb : uniformAverage (fun xs : Fin N → X => if ∃ i,bad i (xs i) then (1:ℝ) else 0) ≤ + ∑ i : Fin N,uniformAverage (fun x : X => if bad i x then (1:ℝ) else 0) := by + convert independent_union_failure bad using 1 + all_goals + congr 1 <;> try exact Subsingleton.elim _ _ + · funext xs + by_cases h : ∃ i,bad i (xs i) <;> simp [h] + · funext i + congr 1 + funext x + by_cases h : bad i x <;> simp [h] + simpa only [bad,not_forall] using he.trans_le hb + +variable {I J : Type*} [Fintype I] [Fintype J] + +def accurateCalls (A : Instance I J) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) : Prop := + ∀ i,accurateCall A C K j hK hW xi v (states i) (phaseWordEquiv A C K j N xi bits i).1 ∧ + accurateCall A C K (j+1) hK hW xi v (states i) (phaseWordEquiv A C K j N xi bits i).2 + +lemma accurateCall_failure (A : Instance I J) (C : ℕ) (hC : 0 < C) (K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) : + uniformAverage (fun bits : WeightWord A C K j xi => + if ¬accurateCall A C K j hK hW xi v S bits then (1:ℝ) else 0) ≤ (xi:ℝ) := by + have hs := evaluate_success A C hC K hK hW hB j hj xi hx0 hx1 hPL hCheeger v S + exact @failure_of_success (WeightWord A C K j xi) inferInstance inferInstance + (accurateCall A C K j hK hW xi v S) (xi:ℝ) hs + +lemma pairedCalls_failure (A : Instance I J) (C : ℕ) (hC : 0 < C) (K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) : + uniformAverage (fun bits : WeightWord A C K j xi × WeightWord A C K (j+1) xi => + if ¬(accurateCall A C K j hK hW xi v S bits.1 ∧ + accurateCall A C K (j+1) hK hW xi v S bits.2) then (1:ℝ) else 0) ≤ (xi:ℝ)+(xi:ℝ) := by + have hS := accurateCall_failure A C hC K j hK hW hB (by omega) xi hx0 hx1 hPL hCheeger v S + have hT := accurateCall_failure A C hC K (j+1) hK hW hB hj xi hx0 hx1 hPL hCheeger v S + exact @independent_pair_failure (WeightWord A C K j xi) (WeightWord A C K (j+1) xi) + inferInstance inferInstance inferInstance inferInstance + (accurateCall A C K j hK hW xi v S) (accurateCall A C K (j+1) hK hW xi v S) + (xi:ℝ) (xi:ℝ) hS hT + +/-- The calls use independent actual finite words even for a fixed, +arbitrary sequence of observed states. No sampling assumption on that +sequence is required for this oracle-error estimate. -/ +theorem accurateCalls_failure (A : Instance I J) (C : ℕ) (hC : 0 < C) (K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) : + uniformAverage (fun bits : Fin (phaseBits A C K j N xi) → Bool => + if ¬accurateCalls A C K j N hK hW xi v states bits then (1:ℝ) else 0) ≤ + 2*(N:ℝ)*(xi:ℝ) := by + let X := WeightWord A C K j xi × WeightWord A C K (j+1) xi + let Y := Fin (phaseBits A C K j N xi) → Bool + let good (i : Fin N) (b : X) := + accurateCall A C K j hK hW xi v (states i) b.1 ∧ + accurateCall A C K (j+1) hK hW xi v (states i) b.2 + have hbad (i : Fin N) : uniformAverage (fun b : X => if ¬good i b then (1:ℝ) else 0) ≤ + (xi:ℝ)+(xi:ℝ) := by + exact pairedCalls_failure A C hC K j hK hW hB hj xi hx0 hx1 hPL hCheeger v (states i) + have he := @independent_reindex_failure X Y inferInstance inferInstance inferInstance N + (phaseWordEquiv A C K j N xi) good + have hfun : (fun bits : Y => + if ¬accurateCalls A C K j N hK hW xi v states bits then (1:ℝ) else 0)= + (fun bits : Y => if ¬(∀ i,good i (phaseWordEquiv A C K j N xi bits i)) then (1:ℝ) else 0) := by + funext bits + have hi : accurateCalls A C K j N hK hW xi v states bits ↔ + ∀ i,good i (phaseWordEquiv A C K j N xi bits i) := Iff.rfl + by_cases h : ∀ i,good i (phaseWordEquiv A C K j N xi bits i) + · simp [hi,h] + · simp [hi,h] + rw [hfun] + calc + _ ≤ ∑ i : Fin N,uniformAverage (fun b : X => if ¬good i b then (1:ℝ) else 0) := + by + convert he using 1 + · apply average_ext_instances + intro bits + by_cases hh : ∀ i,good i (phaseWordEquiv A C K j N xi bits i) <;> simp [hh] + · apply Finset.sum_congr rfl + intro i _ + apply average_ext_instances + intro b + by_cases hh : good i b <;> simp [hh] + _ ≤ ∑ _ : Fin N,((xi:ℝ)+(xi:ℝ)) := Finset.sum_le_sum (fun i _ => hbad i) + _ = 2*(N:ℝ)*(xi:ℝ) := by simp; ring + +/-- The exact empirical ratio written as the plain-state sum divided +by its integer plain-state population. -/ +def exactObservedRatio (A : Instance I J) (j N : ℕ) + (states : Fin N → Set (Labels A×Bool)) : ℝ := + (∑ i,plainObservable pairs (CompanionMultiplierUpdate.ratio A j) (states i))/ + plainCount A (List.ofFn states) + +private lemma indicator_list_sum_real {X : Type*} (P : X → Prop) (l : List X) : + (l.map (fun x => if P x then (1:ℝ) else 0)).sum=(l.countP (fun x => decide (P x)):ℝ) := by + induction l with + | nil => simp + | cons x l ih => by_cases hx : P x <;> simp [hx,ih,add_comm] + +lemma exactObservedRatio_eq (A : Instance I J) (j N : ℕ) + (states : Fin N → Set (Labels A×Bool)) : + exactObservedRatio A j N states= + empiricalRatio pairs (CompanionMultiplierUpdate.ratio A j) (List.ofFn states) := by + by_cases hN : N=0 + · subst N + simp [exactObservedRatio,empiricalRatio,empirical,plainCount] + · have hNR : (N:ℝ)≠0 := Nat.cast_ne_zero.mpr hN + unfold exactObservedRatio empiricalRatio empirical + unfold plainObservable + rw [indicator_list_sum_real] + simp only [List.map_ofFn,List.sum_ofFn,List.length_ofFn,plainCount] + exact (div_div_div_cancel_right₀ hNR _ _).symm + +private lemma ratio_exponential_bounds {u v uh vh e : ℝ} + (hu : 0 < u) (hv : 0 < v) (he0 : 0 ≤ e) (he1 : e ≤ 1/4) + (huh : (1-e)*u ≤ uh ∧ uh ≤ (1+e)*u) + (hvh : (1-e)*v ≤ vh ∧ vh ≤ (1+e)*v) : + Real.exp (-4*e)*(v/u) ≤ vh/uh ∧ vh/uh ≤ Real.exp (4*e)*(v/u) := by + have huh0 := AnnealingMultipliers.empirical_positive hu he1 huh.1 + have hr := AnnealingMultipliers.relative_ratio hv hu he0 he1 hvh huh + have hid : vh*u/(uh*v)=(vh/uh)/(v/u) := by + field_simp [hu.ne',hv.ne',huh0.ne'] + rw [hid] at hr + have hlo : Real.exp (-4*e) ≤ (vh/uh)/(v/u) := by + calc + _ ≤ Real.exp (Real.log ((vh/uh)/(v/u))) := + Real.exp_le_exp.mpr (by linarith [(abs_le.mp hr.2.2.2).1]) + _ = _ := Real.exp_log hr.1 + have hhi : (vh/uh)/(v/u) ≤ Real.exp (4*e) := by + calc + _ = Real.exp (Real.log ((vh/uh)/(v/u))) := (Real.exp_log hr.1).symm + _ ≤ _ := Real.exp_le_exp.mpr (abs_le.mp hr.2.2.2).2 + exact ⟨(le_div_iff₀ (div_pos hv hu)).mp hlo,(div_le_iff₀ (div_pos hv hu)).mp hhi⟩ + +lemma observedTerm_bounds (A : Instance I J) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K (j+1) xi) + (hcall : accurateCall A C K j hK hW xi v S bits.1 ∧ + accurateCall A C K (j+1) hK hW xi v S bits.2) : + Real.exp (-4*(xi:ℝ))*plainObservable pairs (CompanionMultiplierUpdate.ratio A j) S ≤ + (observedTerm A C K j hK hW xi v S bits:ℝ) ∧ + (observedTerm A C K j hK hW xi v S bits:ℝ) ≤ + Real.exp (4*(xi:ℝ))*plainObservable pairs (CompanionMultiplierUpdate.ratio A j) S := by + by_cases hp : PlainState pairs S + · simp only [observedTerm,plainObservable,hp,ite_true,Rat.cast_div, + CompanionMultiplierUpdate.ratio] + exact ratio_exponential_bounds (CompanionAnnealing.weight_positive A j S) + (CompanionAnnealing.weight_positive A (j+1) S) (by exact_mod_cast hx0) + (by + have h4 : (4:ℝ)*(xi:ℝ) ≤ 1 := by + exact_mod_cast (show (4:ℚ)*xi ≤ 1 by linarith) + linarith) hcall.1 hcall.2 + · simp only [observedTerm,plainObservable,hp,ite_false,Rat.cast_zero,mul_zero,le_refl,and_self] + +lemma exactObservedRatio_positive (A : Instance I J) (j N : ℕ) + (states : Fin N → Set (Labels A×Bool)) (hc : 0 < plainCount A (List.ofFn states)) : + 0 < exactObservedRatio A j N states := by + obtain ⟨S,hS,hplain⟩ := List.countP_pos_iff.mp hc + obtain ⟨i,hi⟩ := List.mem_ofFn.mp hS + have hpi : PlainState pairs (states i) := by + rw [hi] + exact of_decide_eq_true hplain + have hterm : 0 < plainObservable pairs (CompanionMultiplierUpdate.ratio A j) (states i) := by + rw [plainObservable,ite_eq_left hpi] + exact lt_of_lt_of_le (by norm_num) (CompanionMultiplierUpdate.ratio_bounds A j (states i)).1 + unfold exactObservedRatio + apply div_pos _ (by exact_mod_cast hc) + apply hterm.trans_le + apply Finset.single_le_sum _ (Finset.mem_univ i) + intro k _ + by_cases hk : PlainState pairs (states k) + · rw [plainObservable,ite_eq_left hk] + exact le_trans (by norm_num) (CompanionMultiplierUpdate.ratio_bounds A j (states k)).1 + · simp only [plainObservable,hk,ite_false,le_refl] + +/-- Relative errors of all fresh calls remain bounded after averaging +the state ratios. The number of observations does not enlarge this +deterministic multiplicative error. -/ +theorem observedRatio_bounds (A : Instance I J) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hg : accurateCalls A C K j N hK hW xi v states bits) : + Real.exp (-4*(xi:ℝ))*exactObservedRatio A j N states ≤ + (observedRatio A C K j N hK hW xi v states bits:ℝ) ∧ + (observedRatio A C K j N hK hW xi v states bits:ℝ) ≤ + Real.exp (4*(xi:ℝ))*exactObservedRatio A j N states := by + have hb (i : Fin N) := observedTerm_bounds A C K j hK hW xi hx0 hx1 v (states i) + (phaseWordEquiv A C K j N xi bits i) (hg i) + simp only [observedRatio,exactObservedRatio,Rat.cast_div,Rat.cast_sum,Rat.cast_natCast] + constructor + · rw [←mul_div_assoc] + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + rw [Finset.mul_sum] + exact Finset.sum_le_sum (fun i _ => (hb i).1) + · rw [←mul_div_assoc] + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg _) + rw [Finset.mul_sum] + exact Finset.sum_le_sum (fun i _ => (hb i).2) + +theorem observedRatio_log_error (A : Instance I J) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) (hx0 : 0 ≤ xi) (hx1 : xi ≤ 1/4) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (hc : 0 < plainCount A (List.ofFn states)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hg : accurateCalls A C K j N hK hW xi v states bits) : + |Real.log ((observedRatio A C K j N hK hW xi v states bits:ℝ)/ + exactObservedRatio A j N states)| ≤ 4*(xi:ℝ) := by + have he := exactObservedRatio_positive A j N states hc + have hb := observedRatio_bounds A C K j N hK hW xi hx0 hx1 v states bits hg + have ho := lt_of_lt_of_le (mul_pos (Real.exp_pos _) he) hb.1 + have hl := (le_div_iff₀ he).mpr hb.1 + have hu := (div_le_iff₀ he).mpr hb.2 + have hlogl := Real.log_le_log (Real.exp_pos _) hl + have hlogu := Real.log_le_log (div_pos ho he) hu + rw [Real.log_exp] at hlogl hlogu + exact abs_le.mpr ⟨by linarith, hlogu⟩ + +end + +end ContingencyTables.CompanionPhaseWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseSize.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseSize.lean new file mode 100644 index 0000000000000000000000000000000000000000..8adfeec9b03e104e341171fa0b76040c0491cc76 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseSize.lean @@ -0,0 +1,180 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCodeBounds +import OAI.Combinatorics.ContingencyTables.Counting.CompanionStoredShape + +namespace OAI + +/-! # Phase query sizes do not depend on the heights of old multipliers -/ +namespace ContingencyTables.CompanionPhaseSize +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial +open CompanionOuterPhaseProgram + +lemma list_weight_bound {X : Type} [Codec X] (xs : List X) (B : ℕ) + (hx : ∀ x∈xs,weight x ≤ B) : weight xs ≤ xs.length*(B+1)+1 := by + have h := weight_map_bound (f := id) (as := xs) hx + simpa only [List.map_id] using h + +lemma initialInput_bound (z : Input) : + weight (CompanionInitializedRestartProgram.initialInput (restartInput z)) ≤ + weight (z.1.1.1,z.2) := by + have ht := weight_sublist (List.take_sublist + (CompanionInitializedRestartProgram.initialWidth (restartInput z)) z.2) + change weight (z.1.1.1,z.2.take _) ≤ weight (z.1.1.1,z.2) + simp only [weight_prod] + omega + +lemma start_bound : ∃ p : Polynomial ℕ,∀ z : Input, + weight (startCode z) ≤ p.eval (weight (z.1.1.1,z.2)) := by + obtain ⟨p,hp⟩ := CompanionRestartInitializer.polynomial_output + refine ⟨7*p+1,?_⟩ + intro z + have hi := hp (CompanionInitializedRestartProgram.initialInput (restartInput z)) + have hm := polynomial_eval_monotone p (initialInput_bound z) + dsimp only at hm + have hs := CompanionCodeBounds.initialized_output (restartInput z) + change weight (startCode z) ≤ _ at hs + change _+weight (CompanionInitializedRestartProgram.initialCode (restartInput z)) ≤ _ at hi + simp only [eval_add,eval_mul,eval_ofNat,eval_one] + omega + +lemma config_bound : ∃ p : Polynomial ℕ,∀ (z : Input) (S : ℕ), + weight z.1.1.1 ≤ S → z.2.length ≤ S → (history z).length ≤ S → + weight (configAt 0 z) ≤ p.eval S ∧ weight (configAt 1 z) ≤ p.eval S := by + obtain ⟨p,hp⟩ := CompanionPhaseContextProgram.polynomial_config + refine ⟨p.comp (9*X+12),?_⟩ + intro z S hprep hbits hhist + have hreserve : weight (reserve z) ≤ 4*S+1 := by + have h := weight_map_bound (f := fun _ : Bool => false) (as := z.2) + (fun _ _ => weight_bool false) + change weight (reserve z) ≤ _ at h + omega + have hb (i : ℕ) (hi : i ≤ 1) : weight (contextInput (z,i)) ≤ 9*S+12 := by + have hj := weight_nat_numeric (phase z+i) + have hlen : phase z ≤ S := hhist + change weight ((z.1.1.1,phase z+i),reserve z) ≤ _ + simp only [weight_prod] + omega + constructor + · have h := hp (contextInput (z,0)) + have hm := polynomial_eval_monotone p (hb 0 (by omega)) + dsimp only at hm + simp only [eval_comp,eval_add,eval_mul,eval_ofNat,eval_X] + change _+weight (configAt 0 z) ≤ _ at h + omega + · have h := hp (contextInput (z,1)) + have hm := polynomial_eval_monotone p (hb 1 (by omega)) + dsimp only at hm + simp only [eval_comp,eval_add,eval_mul,eval_ofNat,eval_X] + change _+weight (configAt 1 z) ≤ _ at h + omega + +lemma trajectory_bounds : ∃ p : Polynomial ℕ,∀ (z : Input) (S : ℕ), + weight z.1.1.1 ≤ S → weight z.2 ≤ S → + (CompanionPhaseTrialProgram.trajectory (trialInput z)).length ≤ S+1 ∧ + (∀ code∈CompanionPhaseTrialProgram.trajectory (trialInput z),weight code ≤ p.eval S) ∧ + (CompanionPhaseTrialProgram.catalogue (trialInput z)).length ≤ p.eval S := by + obtain ⟨p,hp⟩ := start_bound + refine ⟨6*(p.comp (1+2*X))+1,?_⟩ + intro z S hprep hbits + have harg : weight (z.1.1.1,z.2) ≤ 1+2*S := by simp only [weight_prod]; omega + have hstart : weight (startCode z) ≤ p.eval (1+2*S) := + (hp z).trans (polynomial_eval_monotone p harg) + have hsize : (startCode z).length ≤ p.eval (1+2*S) := + (list_length_le_weight _).trans hstart + have hc := CompanionCodeBounds.trajectory_codes (trajectoryInput z) (6*p.eval (1+2*S)+1) + (by change weight (startCode z) ≤ _; omega) + (by change 6*(startCode z).length+1 ≤ _; omega) + have hl := CompanionCodeBounds.trajectory_length (trajectoryInput z) + have hlen : (trajectoryInput z).2.length ≤ S := by + have h := list_length_le_weight z.2 + change ((z.2.drop _).take _).length ≤ S + simp only [List.length_take,List.length_drop] + omega + refine ⟨by change (CompanionTrajectoryProgram.output (trajectoryInput z)).length ≤ _; omega,?_,?_⟩ + · change ∀ code∈CompanionTrajectoryProgram.output (trajectoryInput z),weight code ≤ _ + simpa only [eval_add,eval_mul,eval_ofNat,eval_one,eval_comp,eval_X] using hc + · change (PairedCatalogProgram.catalog (startCode z)).length ≤ _ + simp only [PairedCatalogProgram.catalog,List.length_map,List.length_range, + eval_add,eval_mul,eval_ofNat,eval_one,eval_comp,eval_X] + have hd := Nat.div_le_self (startCode z).length 2 + omega + + +lemma query_bound : ∃ q : Polynomial ℕ,∀ (z : Input) (S : ℕ), + weight z.1.1.1 ≤ S → weight z.2 ≤ S → (history z).length ≤ S → + weight (CompanionObservationQueriesProgram.output + (CompanionObservedUpdateProgram.queryInput + (CompanionPhaseTrialProgram.updateInput (trialInput z)))) ≤ q.eval S := by + obtain ⟨p,hp⟩ := config_bound + obtain ⟨r,hr⟩ := trajectory_bounds + obtain ⟨q,hq⟩ := CompanionObservationQueriesProgram.polynomial_output + refine ⟨q.comp (2*p+(X+1)*(r+1)+X+5),?_⟩ + intro z S hprep hbits hhist + have hb : z.2.length ≤ S := (list_length_le_weight _).trans hbits + have hc := hp z S hprep hb hhist + have ht := hr z S hprep hbits + have hcodes := list_weight_bound _ (r.eval S) ht.2.1 + have hcodeweight : weight (CompanionPhaseTrialProgram.trajectory (trialInput z)) ≤ + (S+1)*(r.eval S+1)+1 := hcodes.trans (by gcongr; exact ht.1) + have htail : weight ((afterRestart z).drop (trajectoryWidth z)) ≤ S := + ((weight_sublist (List.drop_sublist _ _)).trans + (weight_sublist (List.drop_sublist _ _))).trans hbits + have hin : weight (CompanionObservedUpdateProgram.queryInput + (CompanionPhaseTrialProgram.updateInput (trialInput z))) ≤ + 2*p.eval S+(S+1)*(r.eval S+1)+S+5 := by + change weight ((configAt 0 z,configAt 1 z), + (CompanionPhaseTrialProgram.trajectory (trialInput z), + (afterRestart z).drop (trajectoryWidth z))) ≤ _ + simp only [weight_prod] + omega + have hout := hq (CompanionObservedUpdateProgram.queryInput + (CompanionPhaseTrialProgram.updateInput (trialInput z))) + have hm := polynomial_eval_monotone q hin + simp only [eval_comp,eval_add,eval_mul,eval_ofNat,eval_X,eval_one] + exact (Nat.le_add_left _ _).trans (hout.trans hm) + + + +open CompanionStoredSize + +/-- A uniform additive increment and dimension bound for an entire phase. +The polynomial depends only on immutable data, word length and phase number. -/ +lemma phase_bounds : ∃ p : Polynomial ℕ,∀ (z : Input) (S M R : ℕ), + weight z.1.1.1 ≤ S → weight z.2 ≤ S → (history z).length ≤ S → 1 ≤ M → + StoredHeight M (old z) → StoredShape R (old z) → p.eval S ≤ R → + StoredHeight (M+p.eval S) (output z) ∧ StoredShape R (output z) := by + obtain ⟨q,hq⟩ := query_bound + obtain ⟨r,hr⟩ := trajectory_bounds + let p := r+(X+1)*(2*(q+1)+3)+(X+1)+5 + refine ⟨p,?_⟩ + intro z S M R hprep hbits hhist hM hm hshape hR + let d := CompanionObservedUpdateProgram.finishInput + (CompanionPhaseTrialProgram.updateInput (trialInput z)) + have ht := hr z S hprep hbits + have hq' := hq z S hprep hbits hhist + have hv : ∀ x∈d.2,TreeFraction.height x.1 ≤ q.eval S+1 ∧ + TreeFraction.height x.2 ≤ q.eval S+1 := by + intro x hx + have hxw : weight x ≤ q.eval S := (weight_mem hx).trans hq' + exact ⟨(TreeFraction.height_le_weight _).trans ((weight_fst x).trans (by omega)), + (TreeFraction.height_le_weight _).trans ((weight_snd x).trans (by omega))⟩ + have hn := next_height d M (q.eval S+1) hM (by omega) hm.1 hm.2 hv + have hlen : (CompanionPhaseFinishProgram.trajectory d).2.length ≤ S+1 := ht.1 + have hp : r.eval S+(S+1)*(2*(q.eval S+1)+3)+(S+1)+5=p.eval S := by + simp only [p,eval_add,eval_mul,eval_ofNat,eval_X,eval_one] + have hmul := Nat.mul_le_mul_right (2*(q.eval S+1)+3) hlen + have hn' : StoredHeight (M+p.eval S) (CompanionPhaseFinishProgram.next d) := + height_mono (by omega) hn + have hns := next_shape d + have hcat : (CompanionPhaseFinishProgram.trajectory d).1.length ≤ r.eval S := ht.2.2 + have hns' : StoredShape R (CompanionPhaseFinishProgram.next d) := + shape_mono (hcat.trans (by omega)) hns + change StoredHeight (M+p.eval S) ((CompanionPhaseFinishProgram.output d).getD (old z)) ∧ + StoredShape R ((CompanionPhaseFinishProgram.output d).getD (old z)) + unfold CompanionPhaseFinishProgram.output + split_ifs + · exact ⟨hn',hns'⟩ + · exact ⟨height_mono (Nat.le_add_right M _) hm,hshape⟩ + +end ContingencyTables.CompanionPhaseSize + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrajectory.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrajectory.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c48fd07a3eddafb5fd8651d7d14dd80c47b470e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrajectory.lean @@ -0,0 +1,193 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBooleanKernel +import Mathlib.Data.List.OfFn + +namespace OAI + +/-! # The observed Boolean trajectory has the source path law + +The finite history stores the visited prefix. Its exact real reference +expectation is the manuscript's list-path expectation, so the row error +controls events involving all empirical observations simultaneously. +-/ + +namespace ContingencyTables.CompanionPhaseTrajectory + +open CommonBasesFPRAS RealKernelApproximation CompanionBooleanPhase +open FirstSuccess ResidualMixture FiniteLawMoments +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle +open CompanionRationalUpdates TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +variable {X : Type*} + +def historyPrefix {N : ℕ} (a : PathState X N) : List X := + List.ofFn (fun i : Fin (a.1.val+1) => + a.2 ⟨i.val,lt_of_lt_of_le i.isLt (Nat.succ_le_succ (Nat.le_of_lt_succ a.1.isLt))⟩) + +lemma prefix_nonempty {N : ℕ} (a : PathState X N) : historyPrefix a≠[] := by + simp [historyPrefix] + +lemma prefix_last {N : ℕ} (a : PathState X N) : + (historyPrefix a).getLast (prefix_nonempty a)=pathRead a := by + unfold historyPrefix + rw [List.getLast_ofFn_succ] + apply congrArg a.2 + apply Fin.ext + rfl + +lemma prefix_end {N : ℕ} (a : PathState X N) : + (historyPrefix a).dropLast++[pathRead a]=historyPrefix a := by + rw [←prefix_last a] + exact List.dropLast_append_getLast (prefix_nonempty a) + +lemma read_put {N : ℕ} (a : PathState X N) (x : X) : pathRead (pathPut a x)=x := by + simp [pathRead,pathPut] + +lemma position_put {N : ℕ} (a : PathState X N) (x : X) (h : a.1.val simp [FiniteKernel.power,FiniteKernel.comp,FiniteKernel.identity] + | succ n ih => + change (∑ y,(K.power (n+1)).P x y*K.P y z)= + ∑ y,K.P x y*(∑ v,(K.power n).P y v*K.P v z) + simp_rw [ih,Finset.sum_mul,Finset.mul_sum,mul_assoc] + exact Finset.sum_comm + +private lemma power_expectation_succ (K : FiniteKernel X X) (n : ℕ) (x : X) (F : X → ℝ) : + (∑ z,(K.power (n+1)).P x z*F z)= + ∑ y,K.P x y*(∑ z,(K.power n).P y z*F z) := by + simp_rw [power_succ_left,Finset.sum_mul,Finset.mul_sum,mul_assoc] + exact Finset.sum_comm + +omit [Fintype X] in +private lemma lift_expectation {Y Z : Type*} [Fintype Y] [Fintype Z] + (K : FiniteKernel X Y) (read : Z → X) (put : Z → Y → Z) (a : Z) (F : Z → ℝ) : + (∑ b,(liftKernel K read put).P a b*F b)=∑ y,K.P (read a) y*F (put a y) := by + simp only [liftKernel,FiniteKernel.push,mapKernel,Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro y _ + simp only [mul_ite,mul_one,mul_zero,ite_mul,zero_mul] + simp + +/-- Before saturation, the finite lifted chain has exactly the usual +list-path expectation, with the observed prefix retained. -/ +theorem prefix_expectation (C : FiniteChain X) (N n : ℕ) + (a : PathState X N) (hn : a.1.val+n≤N) (F : List X → ℝ) : + (∑ b,((liftKernel C.kernel pathRead pathPut).power n).P a b*F (historyPrefix b))= + C.pathExpectation n (pathRead a) (fun l => F ((historyPrefix a).dropLast++l)) := by + induction n generalizing a F with + | zero => + simp only [FiniteKernel.power,FiniteKernel.identity,FiniteChain.pathExpectation, + ite_mul,one_mul,zero_mul] + simp only [Finset.sum_ite_eq,Finset.mem_univ,ite_true,prefix_end] + | succ n ih => + have ha : a.1.val F ((historyPrefix (pathPut a y)).dropLast++l)) := by + apply Finset.sum_congr rfl + intro y _ + congr 1 + apply ih + rw [position_put a y ha] + omega + _ = C.pathExpectation (n+1) (pathRead a) (fun l => F ((historyPrefix a).dropLast++l)) := by + simp only [read_put,prefix_put a _ ha,List.dropLast_concat,FiniteChain.pathExpectation] + apply Finset.sum_congr rfl + intro y _ + congr 1 + apply congrArg (C.pathExpectation n y) + funext l + simpa only [List.append_assoc,List.singleton_append] using + congrArg (fun xs => F (xs++l)) (prefix_end a).symm + +theorem initial_prefix_expectation (C : FiniteChain X) (N : ℕ) (x : X) (F : List X → ℝ) : + (∑ b,((liftKernel C.kernel pathRead pathPut).power N).P (pathInitial N x) b*F (historyPrefix b))= + C.pathExpectation N x F := by + have h := prefix_expectation C N N (pathInitial N x) (by simp [pathInitial]) F + rw [prefix_initial] at h + simpa only [List.dropLast_singleton,List.nil_append,pathRead,pathInitial] using h + +private lemma event_le_distance {Y : Type*} [Fintype Y] (p q : Y → ℝ) + (hmass : ∑ y,p y=∑ y,q y) (E : Y → Prop) : + (∑ y,p y*(if E y then 1 else 0))≤ + (∑ y,q y*(if E y then 1 else 0))+distance p q := by + have h := distance_event p q hmass (Finset.univ.filter E) + rw [Finset.sum_filter,Finset.sum_filter] at h + simp only [mul_ite,mul_one,mul_zero] + linarith [le_abs_self ((∑ y,if E y then p y else 0)-(∑ y,if E y then q y else 0))] + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Every event of the actual observed Boolean trajectory is bounded by +the source list-path event plus one proved row error per transition. -/ +theorem recorded_event_bound (A : Instance I J) (C : ℕ) (hC : 0 + if E (historyPrefix (recordedWalk A C K j k N N hK hW xi v w S bits)) then (1:ℝ) else 0)≤ + (targetChain A j hp w hw).pathExpectation N S (fun l => if E l then 1 else 0)+ + N*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + let p := pathLaw A C K j k N N hK hW xi v w S + let q := targetPathMass A j hp w hw N N S + have hq : ∑ b,q b=1 := by + have hh := initial_prefix_expectation (targetChain A j hp w hw) N S (fun _ => (1:ℝ)) + simpa only [targetPathMass,q,mul_one,FiniteChain.pathExpectation_const] using hh + have hpq : (∑ b,(p.mass b:ℝ))=∑ b,q b := by rw [hq]; exact_mod_cast p.total + have he := event_le_distance (fun b => (p.mass b:ℝ)) q hpq (fun b => E (historyPrefix b)) + have hd := path_distance_bound A C hC K j k hK hW hB hj xi hx0 hx1 hPL hCheeger v hp w hw N N S + have hword := word_expectation (recordedWalk A C K j k N N hK hW xi v w S) + (fun b => if E (historyPrefix b) then (1:ℝ) else 0) + rw [recordedWalk_law] at hword + change _=∑ b,(p.mass b:ℝ)*(if E (historyPrefix b) then 1 else 0) at hword + have htarget := initial_prefix_expectation (targetChain A j hp w hw) N S + (fun l => if E l then (1:ℝ) else 0) + change (∑ b,q b*(if E (historyPrefix b) then 1 else 0))=_ at htarget + rw [hword] + exact he.trans (by rw [htarget]; exact add_le_add_right hd _) + +end + +end ContingencyTables.CompanionPhaseTrajectory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrialLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrialLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..690736d93512ee341cefa25ee8cecd7b333c03a4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrialLaw.lean @@ -0,0 +1,145 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrialProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTrajectoryLaw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionObservedUpdateLaw +import OAI.Combinatorics.ContingencyTables.Machines.FiniteEncodedBind +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseTrial +import OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartAgreement + +namespace OAI + +/-! # The executed trajectory and fresh queries form the source phase trial -/ +namespace ContingencyTables.CompanionPhaseTrialProgram +open MatchingFPRAS CommonBasesFPRAS CompanionFactorialApplication CompanionComputedInitial +open CompanionComputedProposal CompanionOrderedProposal CompanionArithmeticProposal +open CompanionOracleDensity CompanionWeightOracle CompanionMultiplierMatrixProgram +open CompanionEvaluatedWeightProgram FiniteObservableTransport GridBoundary TwoLiftStates +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) (xi : ℚ) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth nextDegree nextDepth : List Bool) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (E : TreeFraction.Fraction) + (S : CompanionBooleanPhase.State A) (walkBits queryBits : List Bool) : Input := + (((CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth, + (matrixCode w,E)), + CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S walkBits),queryBits) + +lemma output_data (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) (xi : ℚ) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth nextDegree nextDepth : List Bool) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (E : TreeFraction.Fraction) + (S : CompanionBooleanPhase.State A) (walkBits queryBits : List Bool) : + output (data A C K j k N xi z v degree depth nextDegree nextDepth w E S walkBits queryBits)= + CompanionObservedUpdateProgram.output + ((CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth, + (((orderedCatalog A (pairLabels A) (coordinateOrder A), + CompanionTrajectoryProgram.output + (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S walkBits)), + matrixCode w),E)),queryBits) := by + simp only [output,updateInput,storedInput,returnInput,catalogue,trajectory,data, + CompanionFlatReturnProgram.data,CompanionFlatReturnProgram.stateData] + rw [generated_catalog] + +/-- Before changing multiplier representation, this law uses the canonical +matrix's source weights for the trajectory and the given stored value for the update. -/ +theorem sameLaw (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) + (hC : 0 + (output (data A C K j k N xi z v degree depth nextDegree nextDepth w E S + (List.ofFn bits.1) (List.ofFn bits.2))).map (CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))) + (fun bits : RootedPhaseTrial.TrialWords A C K j k N xi => + (RootedPhaseWords.update A (RootedCompletion.rowColumn A.T) C K j (N+1) hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old + (RootedPhaseExperiment.observedStates A (RootedCompletion.rowColumn A.T) + C K j k N hK hW xi (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S bits.1) + bits.2).map (CompanionPhaseFinishProgram.storedView A (pairLabels A))) := by + dsimp only + let cs := CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth + let f := fun bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool => + CompanionTrajectoryProgram.output + (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits)) + let g := RootedPhaseExperiment.observedStates A (RootedCompletion.rowColumn A.T) + C K j k N hK hW xi (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S + let e := fun states : Fin (N+1)→Set (Labels A×Bool) => + (List.ofFn states).map (encodeSet (coordinateOrder A)) + let F := fun codes : List (List ℕ) => fun bits : Fin ((N+1)*CompanionObservationQueriesProgram.blockWidth cs)→Bool => + (CompanionObservedUpdateProgram.output + ((cs,(((orderedCatalog A (pairLabels A) (coordinateOrder A),codes),matrixCode w),E)), + List.ofFn bits)).map (CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length)) + let G := fun states : Fin (N+1)→Set (Labels A×Bool) => + fun bits : Fin (CompanionPhaseWords.phaseBits A C K j (N+1) xi)→Bool => + (RootedPhaseWords.update A (RootedCompletion.rowColumn A.T) C K j (N+1) hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old states bits).map + (CompanionPhaseFinishProgram.storedView A (pairLabels A)) + have hi : SameLaw f (fun bits => e (g bits)) := + CompanionTrajectoryProgram.observations_sameLaw A C K j k N hC (by omega) hK hW hB + xi hxi z v degree depth hdegree hdepth w S + have hs : ∀ states,SameLaw (F (e states)) (G states) := by + intro states + exact CompanionObservedUpdateProgram.sameLaw_phase A C K j hC hj hK hW hB xi hxi z v + degree depth nextDegree nextDepth hdegree hdepth hnextDegree hnextDepth states old w E hw hE + have h := encoded_bind f g e F G hi hs + intro phi + have hl : (fun bits : (Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool) × + (Fin ((N+1)*CompanionObservationQueriesProgram.blockWidth cs)→Bool) => phi ((output (data A C K j k N xi z v degree depth nextDegree nextDepth + w E S (List.ofFn bits.1) (List.ofFn bits.2))).map (CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))))= + (fun bits => phi (F (f bits.1) bits.2)) := by + funext bits + rw [output_data] + rw [hl] + exact h phi + +theorem trial_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) + (hC : 0 + (output (data A C K j k N xi z v degree depth nextDegree nextDepth w E S + (List.ofFn bits.1) (List.ofFn bits.2))).map (CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))) + (fun bits : RootedPhaseTrial.TrialWords A C K j k N xi => + (RootedPhaseTrial.trial A (RootedCompletion.rowColumn A.T) C K j k N hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old S bits).map + (CompanionPhaseFinishProgram.storedView A (pairLabels A))) := by + have hag : CompanionMultiplierAgreement.Agree A (sourceWeights A w) old.multiplier := by + intro a b + simpa only [sourceWeights,pair,Equiv.apply_symm_apply] using + hw ((pairLabels A).symm a) ((pairLabels A).symm b) + have h := sameLaw A C K j k N hC hj hK hW hB xi hxi z v degree depth nextDegree nextDepth + hdegree hdepth hnextDegree hnextDepth old w E hw hE S + dsimp only at h ⊢ + rw [CompanionMultiplierAgreement.observedStates_eq A (RootedCompletion.rowColumn A.T) + C K j k N hK hW xi (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) old.multiplier hag] at h + exact h + +end +end ContingencyTables.CompanionPhaseTrialProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrialProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrialProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..08a79caf822b1d193f1a7dcb4784e1f6f679c625 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseTrialProgram.lean @@ -0,0 +1,78 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTrajectoryProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionObservedUpdateProgram + +namespace OAI + +/-! # A complete executed trajectory and fresh-observation phase trial -/ +namespace ContingencyTables.CompanionPhaseTrialProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped +abbrev Stored := CompanionPhaseFinishProgram.Stored +abbrev Frame := CompanionObservedUpdateProgram.Configs×Stored +abbrev Input := (Frame×CompanionTrajectoryProgram.Input)×List Bool +local instance : Codec CompanionObservedUpdateProgram.Configs := inferInstance +local instance : Codec CompanionObservedUpdateProgram.Base := inferInstance +local instance : Codec (CompanionObservedUpdateProgram.Configs×CompanionObservedUpdateProgram.Base) := inferInstance +local instance : Codec CompanionObservedUpdateProgram.Input := inferInstance +local instance : Codec Frame := inferInstance +local instance : Codec (Frame×CompanionTrajectoryProgram.Input) := inferInstance +local instance : Codec Input := inferInstance + +def trajectory (z : Input) : List (List ℕ) := CompanionTrajectoryProgram.output z.1.2 +def trajectoryRealizer : Realizer trajectory := + composition (f := fun z : Input => z.1.2) (g := CompanionTrajectoryProgram.output) + (composition first second) CompanionTrajectoryProgram.outputRealizer +lemma polynomial_trajectory : PolynomialTime trajectoryRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) + CompanionTrajectoryProgram.polynomial_output + +def catalogue (z : Input) : List (ℕ×ℕ) := PairedCatalogProgram.catalog z.1.2.1.1.2 +def catalogueRealizer : Realizer catalogue := + composition (f := fun z : Input => z.1.2.1.1.2) (g := PairedCatalogProgram.catalog) + (composition (composition (composition (composition first second) first) first) second) + PairedCatalogProgram.catalogRealizer +lemma polynomial_catalogue : PolynomialTime catalogueRealizer := + polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + polynomial_first) polynomial_second) PairedCatalogProgram.polynomial_catalog + +attribute [local irreducible] trajectory catalogue + +def returnInput (z : Input) : CompanionTraceProgram.ReturnInput := (catalogue z,trajectory z) +def returnInputRealizer : Realizer returnInput := pair catalogueRealizer trajectoryRealizer +lemma polynomial_returnInput : PolynomialTime returnInputRealizer := + polynomial_pair polynomial_catalogue polynomial_trajectory + +def storedInput (z : Input) : CompanionObservedUpdateProgram.Base := + ((returnInput z,z.1.1.2.1),z.1.1.2.2) +def storedInputRealizer : Realizer storedInput := + pair (pair returnInputRealizer + (composition (composition (composition first first) second) first)) + (composition (composition (composition first first) second) second) +lemma polynomial_storedInput : PolynomialTime storedInputRealizer := + polynomial_pair (polynomial_pair polynomial_returnInput + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_second) polynomial_first)) + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_second) polynomial_second) + +def updateInput (z : Input) : CompanionObservedUpdateProgram.Input := + ((z.1.1.1,storedInput z),z.2) +def updateInputRealizer : Realizer updateInput := + pair (pair (composition (composition first first) first) storedInputRealizer) second +lemma polynomial_updateInput : PolynomialTime updateInputRealizer := + polynomial_pair (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_storedInput) + polynomial_second + +attribute [local irreducible] updateInput + +def output (z : Input) : Option Stored := CompanionObservedUpdateProgram.output (updateInput z) +def outputRealizer : Realizer output := + composition (f := updateInput) (g := CompanionObservedUpdateProgram.output) + updateInputRealizer CompanionObservedUpdateProgram.outputRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_updateInput CompanionObservedUpdateProgram.polynomial_output + +end ContingencyTables.CompanionPhaseTrialProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..acf809c33131240f7fe2e1e7c25c5ec5964d81ec --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhaseWords.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRationalUpdates + +namespace OAI + +/-! # Explicit fresh words and rational arithmetic for one outer phase -/ + +namespace ContingencyTables.CompanionPhaseWords + +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle CompanionRationalUpdates +open CommonBasesFPRAS GridBoundary FirstSuccess FairBits TwoLiftStates +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +/-- Separate current-parameter and next-parameter oracle words are +reserved at every observed state, including states at which they are unused. -/ +def observationBits (A : Instance I J) (C K j : ℕ) (xi : ℚ) : ℕ := + medianEstimatorBits A C K j xi xi+medianEstimatorBits A C K (j+1) xi xi + +def phaseBits (A : Instance I J) (C K j N : ℕ) (xi : ℚ) : ℕ := + N*observationBits A C K j xi + +def phaseWordEquiv (A : Instance I J) (C K j N : ℕ) (xi : ℚ) : + (Fin (phaseBits A C K j N xi) → Bool) ≃ + (Fin N → WeightWord A C K j xi × WeightWord A C K (j+1) xi) := + (oracleWalkWordEquiv N (observationBits A C K j xi)).trans + (Equiv.piCongrRight (fun _ => splitWordEquiv _ _)) + +def observedTerm (A : Instance I J) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K (j+1) xi) : ℚ := + if PlainState pairs S then + evaluate A C K hK hW (j+1) xi v S bits.2/evaluate A C K hK hW j xi v S bits.1 + else 0 + +def observedRatio (A : Instance I J) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) : ℚ := + (∑ i,observedTerm A C K j hK hW xi v (states i) (phaseWordEquiv A C K j N xi bits i))/ + plainCount A (List.ofFn states) + +lemma observedTerm_nonneg (A : Instance I J) (C : ℕ) (hC : 0 < C) (K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi × WeightWord A C K (j+1) xi) : + 0 ≤ observedTerm A C K j hK hW xi v S bits := by + unfold observedTerm + split_ifs + · exact (div_pos (evaluate_positive A C hC K hK hW hB (j+1) hj xi hx0 hx1 v S bits.2) + (evaluate_positive A C hC K hK hW hB j (by omega) xi hx0 hx1 v S bits.1)).le + · rfl + +lemma observedRatio_positive (A : Instance I J) (C : ℕ) (hC : 0 < C) (K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (states : Fin N → Set (Labels A×Bool)) + (hc : 0 < plainCount A (List.ofFn states)) + (bits : Fin (phaseBits A C K j N xi) → Bool) : + 0 < observedRatio A C K j N hK hW xi v states bits := by + obtain ⟨S,hS,hplain⟩ := List.countP_pos_iff.mp hc + obtain ⟨i,hi⟩ := List.mem_ofFn.mp hS + have hpi : PlainState pairs (states i) := by + rw [hi] + exact of_decide_eq_true hplain + have hterm : 0 < observedTerm A C K j hK hW xi v (states i) + (phaseWordEquiv A C K j N xi bits i) := by + rw [observedTerm,ite_eq_left hpi] + exact div_pos (evaluate_positive A C hC K hK hW hB (j+1) hj xi hx0 hx1 v _ _) + (evaluate_positive A C hC K hK hW hB j (by omega) xi hx0 hx1 v _ _) + unfold observedRatio + apply div_pos _ (by exact_mod_cast hc) + exact hterm.trans_le (Finset.single_le_sum + (fun k _ => observedTerm_nonneg A C hC K j hK hW hB hj xi hx0 hx1 v _ _) + (Finset.mem_univ i)) + +structure Stored (A : Instance I J) where + multiplier : Pair A → Pair A → ℚ + estimate : ℚ + +def update (A : Instance I J) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (old : Stored A) + (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) : Option (Stored A) := + if CountsPositive A (List.ofFn states) then + some ⟨rationalLearn pairs old.multiplier (List.ofFn states), + old.estimate*observedRatio A C K j N hK hW xi v states bits⟩ + else none + +/-- A nonaborting update keeps every stored rational positive, even if +all its weight calls were statistically inaccurate. -/ +theorem update_positive (A : Instance I J) (C : ℕ) (hC : 0 < C) (K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (hj : j+1 ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (old next : Stored A) + (hw : ∀ p q,0 < old.multiplier p q) (hE : 0 < old.estimate) + (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hu : update A C K j N hK hW xi v old states bits=some next) : + (∀ p q,0 < next.multiplier p q) ∧ 0 < next.estimate := by + unfold update at hu + split_ifs at hu with hc + · cases Option.some.inj hu + constructor + · apply checkedUpdate_positive A old.multiplier hw (List.ofFn states) + simp only [checkedUpdate,hc,ite_true] + · exact mul_pos hE (observedRatio_positive A C hC K j N hK hW hB hj xi hx0 hx1 v states hc.1 bits) + +lemma update_multiplier_cast (A : Instance I J) (C K j N : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (old next : Stored A) + (states : Fin N → Set (Labels A×Bool)) + (bits : Fin (phaseBits A C K j N xi) → Bool) + (hu : update A C K j N hK hW xi v old states bits=some next) (p q : Pair A) : + (next.multiplier p q:ℝ)= + learnedMultipliers pairs (fun p q => (old.multiplier p q:ℝ)) (List.ofFn states) p q := by + unfold update at hu + split_ifs at hu + · cases Option.some.inj hu + exact rationalLearn_cast _ _ _ _ _ + +end + +end ContingencyTables.CompanionPhaseWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhysicalNormalizer.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhysicalNormalizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..72027d7c0a175d9da80eaa01749730e49a85a35e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhysicalNormalizer.lean @@ -0,0 +1,126 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BalancedPhysicalPartition +import OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalEnumeration +import OAI.Combinatorics.ContingencyTables.Transport.TransversalCount + +namespace OAI + +/-! # The actual companion normalizer equals the full physical balanced mass -/ + +namespace ContingencyTables.CompanionPhysicalNormalizer + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication TwoLiftStates +open BalancedCellFibres PhysicalLargeProfiles LargePairEnumeration TreeMarginalSignature +open ForestPenaltyApplication ForestCountIdentification + +private lemma finite_sum_congr {C : Type*} (F G : Fintype C) (f g : C → ℝ) + (h : ∀ c,f c=g c) : + @Finset.sum C ℝ _ (@Finset.univ C F) f=@Finset.sum C ℝ _ (@Finset.univ C G) g := by + have he : F=G := Subsingleton.elim _ _ + cases he + exact Finset.sum_congr rfl (fun c _ => h c) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def physicalMass (A : Instance I J) (alpha : ℝ) : ℝ := + ∑ a : Profiles (cellWidth A),physicalWeight A.T A.b + (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha + (BalancedCellFibres.profile (cellWidth A) a) + +lemma small_width (A : Instance I J) (s : SmallCell A) : + cellWidth A s.val=A.b s.val.1 s.val.2 := by + have ht : ¬A.T.Adj (.inl s.val.1) (.inr s.val.2) := by + intro ht + have hs : A.small s.val.1 s.val.2=false := A.hTG ht + exact Bool.false_ne_true (hs.symm.trans s.property) + simp only [cellWidth,ForestLiteralCount.width,ht,ite_false] + +noncomputable def smallInterval (A : Instance I J) (s : SmallCell A) : + Fin (cellWidth A s.val+1) ≃ Fin (A.b s.val.1 s.val.2+1) where + toFun k := ⟨k.val,by rw [← small_width A s]; exact k.isLt⟩ + invFun k := ⟨k.val,by rw [small_width A s]; exact k.isLt⟩ + left_inv _ := rfl + right_inv _ := rfl + +noncomputable def smallProfilesEquiv (A : Instance I J) : + SmallProfiles (fun a : I×J => A.small a.1 a.2) (cellWidth A) ≃ + TransversalCount.Profile (fun s : SmallCell A => A.b s.val.1 s.val.2) := + Equiv.piCongrRight (smallInterval A) + +lemma small_display_eq (A : Instance I J) + (s : SmallProfiles (fun a : I×J => A.small a.1 a.2) (cellWidth A)) : + smallDisplay (fun a : I×J => A.small a.1 a.2) (cellWidth A) s= + TransversalCount.display (fun s : SmallCell A => A.b s.val.1 s.val.2) (smallProfilesEquiv A s) := by + funext u + rcases u with ⟨a,b⟩ + cases b + · rfl + · change cellWidth A a.val-(s a).val=A.b a.val.1 a.val.2-(s a).val + exact congrArg (fun n : ℕ => n-(s a).val) (small_width A a) + +lemma h_eq_physical_sum (A : Instance I J) (alpha : ℝ) (z : View A → ℕ) + (hz : BalancedBox.InBox (bounds A) z) : + h A alpha z= + ∑ a : PhysicalAssignments (fun a : I×J => A.small a.1 a.2) (cellWidth A), + physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha + (physicalProfile (fun a : I×J => A.small a.1 a.2) (cellWidth A) z a) := by + let e := (Fintype.equivFin (LargeCell (fun a : I×J => A.small a.1 a.2))).symm + have hh := sourceMarginal_eq_largeMarginal A.small A.b A.T A.hTG A.hT A.hmax A.r A.c A.X + A.d A.W alpha A.hd A.hcard A.hlarge A.hsmall A.hX A.hXr A.hXc e z hz + change h A alpha z=_ at hh + rw [hh] + unfold ForestLargeMarginal.largeMarginal + convert sum_joined_eq_physical (fun a : I×J => A.small a.1 a.2) (cellWidth A) e z + (physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha) using 1 + all_goals + apply finite_sum_congr + intro a + rfl + +lemma physicalMass_eq_split (A : Instance I J) (alpha : ℝ) : + physicalMass A alpha= + ∑ s : SmallProfiles (fun a : I×J => A.small a.1 a.2) (cellWidth A), + ∑ a : PhysicalAssignments (fun a : I×J => A.small a.1 a.2) (cellWidth A), + physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha + (physicalProfile (fun a : I×J => A.small a.1 a.2) (cellWidth A) + (smallDisplay (fun a : I×J => A.small a.1 a.2) (cellWidth A) s) a) := by + let F := physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha + let small : I×J → Bool := fun a => A.small a.1 a.2 + change (∑ a : Profiles (cellWidth A),F (BalancedCellFibres.profile (cellWidth A) a))= + ∑ s : SmallProfiles small (cellWidth A),∑ a : PhysicalAssignments small (cellWidth A), + F (physicalProfile small (cellWidth A) (smallDisplay small (cellWidth A) s) a) + have he := Fintype.sum_equiv (partition small (cellWidth A)) + (fun a => F (BalancedCellFibres.profile (cellWidth A) a)) + (fun a => F (physicalProfile small (cellWidth A) (smallDisplay small (cellWidth A) a.1) a.2)) + (by + intro a + have hh := partition_profile small (cellWidth A) ((partition small (cellWidth A)) a) + simpa only [Equiv.symm_apply_apply] using congrArg F hh) + rw [he,Fintype.sum_prod_type] + +/-- Exact cancellation and actual small/large product partition identify +the manuscript's normalizer with the physical mass used in the terminal +root and tree contamination estimates. -/ +theorem normalizer_eq_physical_mass (A : Instance I J) (alpha : ℝ) : + slotTotal pairs (f A alpha) ∅=physicalMass A alpha := by + rw [CompanionTransversalCount.total_eq_raw_profiles] + rw [physicalMass_eq_split] + symm + apply Fintype.sum_equiv (smallProfilesEquiv A) + intro s + rw [small_display_eq] + symm + apply h_eq_physical_sum + intro u + rcases u with ⟨a,b⟩ + cases b + · exact Nat.le_of_lt_succ ((smallProfilesEquiv A s) a).isLt + · exact Nat.sub_le _ _ + +end ContingencyTables.CompanionPhysicalNormalizer + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhysicalTables.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhysicalTables.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e9e3cc5d86a6aace5944bccf235c36423aacf6b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionPhysicalTables.lean @@ -0,0 +1,163 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.TreeFeasibleMass +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhysicalNormalizer +import OAI.Combinatorics.ContingencyTables.Model + +namespace OAI + +/-! # Feasible physical balanced profiles are exactly bounded contingency tables -/ + +namespace ContingencyTables.CompanionPhysicalTables + +open scoped BigOperators Classical +open CompanionFactorialApplication TreeMarginalSignature BalancedCellFibres + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def physicalTable (A : Instance I J) (a : Profiles (cellWidth A)) : I → J → ℤ := + fun i j => ForestLiteralCount.lower A.T A.d A.b i j+(a (i,j)).val + +def Feasible (A : Instance I J) (a : Profiles (cellWidth A)) : Prop := + (∀ i j,0 ≤ physicalTable A a i j ∧ physicalTable A a i j ≤ A.b i j) ∧ + (∀ i,(∑ j,physicalTable A a i j)=A.r i) ∧ + (∀ j,(∑ i,physicalTable A a i j)=A.c j) + +abbrev PhysicalTables (A : Instance I J) := {a : Profiles (cellWidth A) // Feasible A a} + +lemma row_nonnegative (A : Instance I J) (i : I) : 0 ≤ A.r i := by + rw [← A.hXr i] + exact Finset.sum_nonneg (fun j _ => (A.hX i j).1) + +lemma column_nonnegative (A : Instance I J) (j : J) : 0 ≤ A.c j := by + rw [← A.hXc j] + exact Finset.sum_nonneg (fun i _ => (A.hX i j).1) + +lemma physicalTable_assignment (A : Instance I J) (Y : I → J → ℤ) + (hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j) : + physicalTable A (tableAssignment A Y hY)=Y := by + funext i j + have hz : 0 ≤ Y i j-ForestLiteralCount.lower A.T A.d A.b i j := by + linarith [(hY i j).1,lower_nonpositive A i j] + simp only [physicalTable,tableAssignment,Int.toNat_of_nonneg hz] + ring + +lemma assignment_physicalTable (A : Instance I J) (a : Profiles (cellWidth A)) + (ha : ∀ i j,0 ≤ physicalTable A a i j ∧ physicalTable A a i j ≤ A.b i j) : + tableAssignment A (physicalTable A a) ha=a := by + funext c + apply Fin.ext + simp only [tableAssignment,physicalTable,add_sub_cancel_left,Int.toNat_natCast] + +noncomputable def toBounded (A : Instance I J) (a : PhysicalTables A) : + BoundedTable (fun i => (A.r i).toNat) (fun j => (A.c j).toNat) A.b := by + let Y : I → J → ℕ := fun i j => (physicalTable A a.val i j).toNat + have hy (i : I) (j : J) : (Y i j:ℤ)=physicalTable A a.val i j := + Int.toNat_of_nonneg (a.property.1 i j).1 + refine ⟨⟨Y,⟨?_,?_⟩⟩,?_⟩ + · intro i + have hh : (∑ j,(Y i j:ℤ))=((A.r i).toNat:ℤ) := by + simp_rw [hy] + rw [a.property.2.1 i,Int.toNat_of_nonneg (row_nonnegative A i)] + exact_mod_cast hh + · intro j + have hh : (∑ i,(Y i j:ℤ))=((A.c j).toNat:ℤ) := by + simp_rw [hy] + rw [a.property.2.2 j,Int.toNat_of_nonneg (column_nonnegative A j)] + exact_mod_cast hh + · intro i j + have hh : (Y i j:ℤ) ≤ A.b i j := by rw [hy]; exact (a.property.1 i j).2 + exact_mod_cast hh + +noncomputable def fromBounded (A : Instance I J) + (X : BoundedTable (fun i => (A.r i).toNat) (fun j => (A.c j).toNat) A.b) : PhysicalTables A := by + let Y : I → J → ℤ := fun i j => X.val.val i j + have hY : ∀ i j,0 ≤ Y i j ∧ Y i j ≤ A.b i j := by + intro i j + dsimp only [Y] + exact ⟨Nat.cast_nonneg _,by exact_mod_cast X.property i j⟩ + refine ⟨tableAssignment A Y hY,?_⟩ + unfold Feasible + rw [physicalTable_assignment] + refine ⟨hY,?_,?_⟩ + · intro i + have hh : (∑ j,Y i j)=((A.r i).toNat:ℤ) := by + dsimp only [Y] + exact_mod_cast X.val.property.1 i + rwa [Int.toNat_of_nonneg (row_nonnegative A i)] at hh + · intro j + have hh : (∑ i,Y i j)=((A.c j).toNat:ℤ) := by + dsimp only [Y] + exact_mod_cast X.val.property.2 j + rwa [Int.toNat_of_nonneg (column_nonnegative A j)] at hh + +lemma toBounded_integer (A : Instance I J) (a : PhysicalTables A) (i : I) (j : J) : + ((toBounded A a).val.val i j:ℤ)=physicalTable A a.val i j := by + change ((physicalTable A a.val i j).toNat:ℤ)=physicalTable A a.val i j + exact Int.toNat_of_nonneg (a.property.1 i j).1 + +lemma fromBounded_table (A : Instance I J) + (X : BoundedTable (fun i => (A.r i).toNat) (fun j => (A.c j).toNat) A.b) : + physicalTable A (fromBounded A X).val=fun i j => (X.val.val i j:ℤ) := by + unfold fromBounded + exact physicalTable_assignment _ _ _ + +lemma physicalTable_injective (A : Instance I J) : Function.Injective (physicalTable A) := by + intro a a' hh + funext t + apply Fin.ext + have he := congrFun (congrFun hh t.1) t.2 + simp only [physicalTable] at he + exact_mod_cast (add_left_cancel he) + +/-- The terminal feasible-profile count is the original bounded-table +count, with the instance's necessarily nonnegative margins. -/ +noncomputable def tablesEquiv (A : Instance I J) : + PhysicalTables A ≃ BoundedTable (fun i => (A.r i).toNat) (fun j => (A.c j).toNat) A.b where + toFun := toBounded A + invFun := fromBounded A + left_inv a := by + apply Subtype.ext + apply physicalTable_injective A + funext i j + rw [fromBounded_table] + exact toBounded_integer A a i j + right_inv X := by + apply Subtype.ext + apply Subtype.ext + funext i j + have hh := toBounded_integer A (fromBounded A X) i j + rw [fromBounded_table] at hh + dsimp only at hh + exact_mod_cast hh + +theorem cardinality_eq (A : Instance I J) : + Fintype.card (PhysicalTables A)= + Fintype.card (BoundedTable (fun i => (A.r i).toNat) (fun j => (A.c j).toNat) A.b) := + Fintype.card_congr (tablesEquiv A) + +theorem feasible_weight_one (A : Instance I J) (alpha : ℝ) (a : Profiles (cellWidth A)) + (ha : Feasible A a) : + ForestPenaltyApplication.physicalWeight A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c alpha (BalancedCellFibres.profile (cellWidth A) a)=1 := by + have hh := tableAssignment_unit A alpha (physicalTable A a) ha.1 ha.2.1 ha.2.2 + rwa [assignment_physicalTable A a ha.1] at hh + +/-- Every original bounded table contributes exactly one unit, so the +actual normalizer always dominates the table count. -/ +theorem table_count_le_mass (A : Instance I J) (alpha : ℝ) : + (Fintype.card (BoundedTable (fun i => (A.r i).toNat) (fun j => (A.c j).toNat) A.b):ℝ) ≤ + CompanionPhysicalNormalizer.physicalMass A alpha := by + have hcount : (∑ a : Profiles (cellWidth A),if Feasible A a then (1:ℝ) else 0)= + (Fintype.card (PhysicalTables A):ℝ) := by + simp only [Finset.sum_ite,Finset.sum_const_zero,add_zero,Finset.sum_const,nsmul_eq_mul,mul_one] + rw [Fintype.card_subtype] + rw [← cardinality_eq,← hcount] + unfold CompanionPhysicalNormalizer.physicalMass + apply Finset.sum_le_sum + intro a _ + split_ifs with ha + · rw [feasible_weight_one A alpha a ha] + · exact ForestPenaltyApplication.physicalWeight_nonnegative _ _ _ _ _ _ _ _ + +end ContingencyTables.CompanionPhysicalTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionProjectedHistory.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionProjectedHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa5d65734eb796d77de4d8c97060315e9eb3b21c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionProjectedHistory.lean @@ -0,0 +1,132 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionHistoryReadback +import OAI.Combinatorics.ContingencyTables.Transport.FiniteBoundedProjectedHistory + +namespace OAI + +/-! # Lifting executed phase laws through the complete adaptive history -/ +namespace ContingencyTables.CompanionProjectedHistory +open MatchingFPRAS CommonBasesFPRAS FiniteObservableTransport +open CompanionFactorialApplication CompanionStoredRepresentation +open CompanionCanonicalHistory +open scoped Classical +noncomputable section + +abbrev Stored := CompanionPhaseFinishProgram.Stored + +def advance (fixed : CompanionOuterHistoryProgram.Fixed) {W : ℕ} + (history : List Stored) (bits : Fin W→Bool) : List Stored := + history++[CompanionOuterPhaseProgram.output ((fixed,history),List.ofFn bits)] + +lemma fold_eq (fixed : CompanionOuterHistoryProgram.Fixed) {W : ℕ} + (words : List (Fin W→Bool)) (history : List Stored) : + ((words.map List.ofFn).foldl + (fun state bits => CompanionOuterHistoryProgram.advance (bits,state)) (fixed,history))= + (fixed,words.foldl (advance fixed) history) := by + induction words generalizing history with + | nil => rfl + | cons word words ih => + simpa only [List.map_cons,List.foldl_cons,advance,CompanionOuterHistoryProgram.advance, + CompanionOuterHistoryProgram.next,CompanionOuterHistoryProgram.phaseInput] using + ih (advance fixed history word) + +lemma storedHistory_eq (fixed : CompanionOuterHistoryProgram.Fixed) {W : ℕ} + (words : List (Fin W→Bool)) : + CompanionOuterHistoryProgram.storedHistory (fixed,words.map List.ofFn)= + words.foldl (advance fixed) [] := by + exact congrArg Prod.snd (fold_eq fixed words []) + +lemma fold_length (fixed : CompanionOuterHistoryProgram.Fixed) {W : ℕ} + (words : List (Fin W→Bool)) (history : List Stored) : + (words.foldl (advance fixed) history).length=history.length+words.length := by + induction words generalizing history with + | nil => simp only [List.foldl_nil,List.length_nil,Nat.add_zero] + | cons word words ih => + rw [List.foldl_cons,ih] + simp only [advance,List.length_append,List.length_cons,List.length_nil,List.length_cons] + omega + +variable {I J : Type} [Fintype I] [Fintype J] + +theorem history_sameLaw (A : Instance I J) {p W : ℕ} (g : Fin p ≃ Labels A) + (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (fixed : CompanionOuterHistoryProgram.Fixed) + (hrep : ∀ history : List Stored,(∀ x∈history,StoredRep p x)→history.length CompanionPhaseFinishProgram.view (p := p) + (CompanionOuterPhaseProgram.output ((fixed,history),List.ofFn bits))) + (canonicalStep A g R s (history.map (CompanionPhaseFinishProgram.view (p := p))))) : + SameLaw (fun words : Fin s.H→(Fin W→Bool) => + (CompanionOuterHistoryProgram.storedHistory + (fixed,(List.ofFn words).map List.ofFn)).map (CompanionPhaseFinishProgram.view (p := p))) + (fun words : Fin s.H→RootedPhaseHistory.Word A s => + canonicalDecoded A g R s (List.ofFn words)) := by + let F : List Stored→(Fin W→Bool)→List Stored := advance fixed + let G := canonicalAdvance A g R s + let e := List.map (CompanionPhaseFinishProgram.view (p := p)) + let Valid := fun history : List Stored => ∀ x∈history,StoredRep p x + have hv : ∀ history,Valid history→history.length e (F history bits)) (G (e history)) := by + intro history hh hlt + have h := (hstep history hh hlt).map (fun x => e history++[x]) + intro phi + simpa only [e,F,G,advance,canonicalAdvance,List.map_append,List.map_singleton] using h phi + have h := bounded_projected_foldl_sameLaw F G e Valid List.length s.H + (fun history bits => by simp only [F,advance,List.length_append,List.length_cons,List.length_nil]) + hv hs [] (by simp [Valid]) s.H (by simp) + intro phi + simpa only [storedHistory_eq,e,F,G,canonicalDecoded,List.map_nil] using h phi + +theorem output_sameLaw (A : Instance I J) {p W : ℕ} (g : Fin p ≃ Labels A) + (R : RootedCompletion.Selection A.T) (s : RootedPhaseHistory.Settings A) + (fixed : CompanionOuterHistoryProgram.Fixed) + (hinit : CompanionPhaseFinishProgram.view (p := p) fixed.2= + project A g (RootedStoredEstimate.initialStored A)) + (hrep : ∀ history : List Stored,(∀ x∈history,StoredRep p x)→history.length CompanionPhaseFinishProgram.view (p := p) + (CompanionOuterPhaseProgram.output ((fixed,history),List.ofFn bits))) + (canonicalStep A g R s (history.map (CompanionPhaseFinishProgram.view (p := p))))) : + SameLaw (fun words : Fin s.H→(Fin W→Bool) => + TreeFraction.val (CompanionOuterHistoryProgram.output + (fixed,(List.ofFn words).map List.ofFn)).2) + (RootedCountingWords.estimate A R s) := by + have h := (history_sameLaw A g R s fixed hrep hstep).map + (fun history => (canonicalLookup A g history s.H).2) + have he (words : Fin s.H→(Fin W→Bool)) : + TreeFraction.val (CompanionOuterHistoryProgram.output + (fixed,(List.ofFn words).map List.ofFn)).2= + (canonicalLookup A g + ((CompanionOuterHistoryProgram.storedHistory + (fixed,(List.ofFn words).map List.ofFn)).map (CompanionPhaseFinishProgram.view (p := p))) s.H).2 := by + change (CompanionPhaseFinishProgram.view (p := p) + (CompanionOuterPhaseProgram.old ((fixed, + CompanionOuterHistoryProgram.storedHistory (fixed,(List.ofFn words).map List.ofFn)),[]))).2=_ + have hh := CompanionHistoryReadback.view_old_canonical A g fixed + (CompanionOuterHistoryProgram.storedHistory (fixed,(List.ofFn words).map List.ofFn)) [] hinit + have hl : (CompanionOuterHistoryProgram.storedHistory + (fixed,(List.ofFn words).map List.ofFn)).length=s.H := by + rw [storedHistory_eq,fold_length] + simp only [List.length_nil,List.length_ofFn,Nat.zero_add] + rw [hh,hl] + intro phi + simp_rw [he] + exact (h phi).trans (by + apply congrArg uniformAverage + funext words + rw [estimate_project] + rfl) + +end +end ContingencyTables.CompanionProjectedHistory + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRatioSamples.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRatioSamples.lean new file mode 100644 index 0000000000000000000000000000000000000000..027c8d18c32ca9676a1d85128a947f772d73b9b0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRatioSamples.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleFiniteStep +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleCorrection +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments +import OAI.Combinatorics.ContingencyTables.Transport.FiniteBiasedAverages + +namespace OAI + +/-! # Concrete rational observations of the companion annealing ratios -/ + +namespace ContingencyTables.CompanionOracleDensity + +open CompanionFactorialApplication GridBoundary CommonBasesFPRAS ResidualMixture FirstSuccess +open FiniteLawMoments FiniteIndependentAverages +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def rationalRatioObservable (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : ℚ := + rationalGridWeight A C (a+1) z v/rationalGridWeight A C a z v + +lemma rationalRatioObservable_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) : + (rationalRatioObservable A C a z v:ℝ)=ratioObservable A C a z v := by + simp only [rationalRatioObservable,Rat.cast_div,rationalGridWeight_cast,Nat.cast_add, + Nat.cast_one,ratioObservable] + +lemma ratioObservable_bounds (A : Instance I J) (C : ℝ) (hC : 0 < C) + (a : ℕ) (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hKB : (K:ℝ) ≤ binWidth A C) (v : Grid (I := Fin (dimension A)) K) : + 1/2 ≤ ratioObservable A C a z v ∧ ratioObservable A C a z v ≤ 1 := by + rcases ratioObservable_cases A C hC a z hz hKB v with h|h <;> rw [h] <;> norm_num + +lemma ratioMean_stationary (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (hK : 1 ≤ K) : + expectation (oracleStationaryLaw A C a z hK) (ratioObservable A C a z)=ratioMean A C a z K := by + unfold expectation ratioMean + apply Finset.sum_congr rfl + intro v _ + rw [oracleStationaryLaw_cast,oracleChain_pi] + rfl + +lemma ratioMean_bounds (A : Instance I J) (C a : ℕ) (hC : 0 < C) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + {K : ℕ} (hK : 1 ≤ K) (hKB : (K:ℝ) ≤ binWidth A C) : + 1/2 ≤ ratioMean A C a z K ∧ ratioMean A C a z K ≤ 1 := by + rw [←ratioMean_stationary A C a z hK] + exact expectation_bounds _ _ _ _ (ratioObservable_bounds A C (by exact_mod_cast hC) a z hz hKB) + +abbrev RatioWords (A : Instance I J) (C n : ℕ) := Fin n → Fin (oracleStepBits A C) → Bool + +def ratioSample (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) (bits : RatioWords A C n) : ℚ := + rationalRatioObservable A C a z (wordWalk (oracleBitStep A C a z) v n bits) + +lemma ratioSample_cast (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) (bits : RatioWords A C n) : + (ratioSample A C a z v n bits:ℝ)= + ratioObservable A C a z (wordWalk (oracleBitStep A C a z) v n bits) := + rationalRatioObservable_cast _ _ _ _ _ + +lemma ratioSample_mean (A : Instance I J) (C a : ℕ) (z : View A → ℕ) + {K : ℕ} (v : Grid (I := Fin (dimension A)) K) (n : ℕ) : + uniformAverage (fun bits : RatioWords A C n => (ratioSample A C a z v n bits:ℝ))= + expectation (oracleBitWalkLaw A C a z v n) (ratioObservable A C a z) := by + simp_rw [ratioSample_cast] + exact word_expectation (wordWalk (oracleBitStep A C a z) v n) _ + +/-- The actual finite walk has small expectation bias for the literal +ratio of consecutive normalizers. -/ +theorem ratioSample_mean_bias (A : Instance I J) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + |uniformAverage (fun bits : RatioWords A C (oracleTime A C K Q theta) => + (ratioSample A C a z v (oracleTime A C K Q theta) bits:ℝ))-ratioMean A C a z K| ≤ + theta/(4*Q) := by + rw [ratioSample_mean,←ratioMean_stationary A C a z hK] + have hb := expectation_difference + (oracleBitWalkLaw A C a z v (oracleTime A C K Q theta)) + (oracleStationaryLaw A C a z hK) (ratioObservable A C a z) 1 (fun w => by + have hw := ratioObservable_bounds A C (by exact_mod_cast hC) a z hz hKB w + rw [abs_of_nonneg (by linarith : 0 ≤ ratioObservable A C a z w)] + exact hw.2) + have hm := oracleBitWalkLaw_variation A C a theta hC haH htheta z hz K Q hK hQ + hKB hPL hCheeger v + apply hb.trans + calc + _ ≤ 2*1*(theta/(8*Q)) := mul_le_mul_of_nonneg_left hm (by norm_num) + _ = _ := by + have hQR : (Q:ℝ)≠0 := by exact_mod_cast hQ.ne' + field_simp [hQR] + ring + +/-- Independent Boolean arrays give an explicit confidence bound around +its exact annealing ratio, including the finite-walk mean bias. -/ +theorem ratioSamples_failure (A : Instance I J) (C a : ℕ) (theta : ℝ) + (hC : 0 < C) (haH : a ≤ rationalHeight A C) (htheta : 0 < theta) + (z : View A → ℕ) (hz : BalancedBox.InBox (bounds A) z) + (K Q N : ℕ) (hK : 1 ≤ K) (hQ : 0 < Q) (hN : 0 < N) + (hKB : (K:ℝ) ≤ binWidth A C) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) : + uniformAverage (fun draws : Fin N → RatioWords A C (oracleTime A C K Q theta) => + if theta*ratioMean A C a z K < + |sampleAverage (fun bits => (ratioSample A C a z v (oracleTime A C K Q theta) bits:ℝ)) + N draws-ratioMean A C a z K| then (1:ℝ) else 0) ≤ 16/(N*theta^2) := by + let g := fun bits : RatioWords A C (oracleTime A C K Q theta) => + (ratioSample A C a z v (oracleTime A C K Q theta) bits:ℝ) + have hg (bits : RatioWords A C (oracleTime A C K Q theta)) : 0 ≤ g bits ∧ g bits ≤ 1 := by + dsimp only [g] + rw [ratioSample_cast] + have hh := ratioObservable_bounds A C (by exact_mod_cast hC) a z hz hKB + (wordWalk (oracleBitStep A C a z) v (oracleTime A C K Q theta) bits) + exact ⟨by linarith,hh.2⟩ + have hr := ratioMean_bounds A C a hC z hz hK hKB + have hQR : (1:ℝ) ≤ Q := by exact_mod_cast (show 1 ≤ Q by omega) + have hb : |uniformAverage g-ratioMean A C a z K| ≤ theta*ratioMean A C a z K/2 := by + have hb := ratioSample_mean_bias A C a theta hC haH htheta z hz K Q hK hQ hKB hPL hCheeger v + have h1 : theta/(4*(Q:ℝ)) ≤ theta/4 := by + apply div_le_div_of_nonneg_left htheta.le (by norm_num) + nlinarith + exact hb.trans (h1.trans (by nlinarith [hr.1])) + have hh := biased_target_failure g 1 (ratioMean A C a z K) theta hg + (by linarith [hr.1]) htheta hb N hN + apply hh.trans + have hNR : (0:ℝ) < N := by exact_mod_cast hN + have hs : (theta/2)^2 ≤ (theta*ratioMean A C a z K)^2 := by + apply (sq_le_sq₀ (by positivity) (mul_nonneg htheta.le (by linarith [hr.1]))).mpr + nlinarith [hr.1] + calc + 4*1^2/((N:ℝ)*(theta*ratioMean A C a z K)^2) ≤ 4/(N*(theta/2)^2) := + div_le_div₀ (by norm_num) (by norm_num) (by positivity) (mul_le_mul_of_nonneg_left hs hNR.le) + _ = _ := by field_simp [hNR.ne',htheta.ne']; ring + +end + +end ContingencyTables.CompanionOracleDensity + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRationalUpdates.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRationalUpdates.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a91bdfb6ee6b36a4629892702f180cd4062e848 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRationalUpdates.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseComposition +import OAI.Combinatorics.ContingencyTables.Counting.CompanionWeightOracle + +namespace OAI + +/-! # Exact rational multiplier updates of the outer annealing run -/ + +namespace ContingencyTables.CompanionRationalUpdates + +open CompanionFactorialApplication CompanionPhaseComposition CompanionMultiplierUpdate +open CommonBasesFPRAS TwoLiftStates +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +abbrev Pair (A : Instance I J) := (Labels A×Bool)×(Labels A×Bool) + +def initial (A : Instance I J) (p q : Pair A) : ℚ := + if (p.1.1).1=(q.1.1).1 then 6 + else 6*((A.b (p.1.1).1.val.1 (p.1.1).1.val.2:ℚ)+1)/ + ((A.b (q.1.1).1.val.1 (q.1.1).1.val.2:ℚ)+2) + +lemma initial_positive (A : Instance I J) (p q : Pair A) : 0 < initial A p q := by + unfold initial + split_ifs <;> positivity + +lemma initial_cast (A : Instance I J) (p q : Pair A) : + (initial A p q:ℝ)=CompanionInitialMultipliers.multiplier A p q := by + simp only [initial,CompanionInitialMultipliers.multiplier,InitialMultiplierValues.value] + split_ifs <;> simp only [Rat.cast_ofNat,Rat.cast_div,Rat.cast_mul,Rat.cast_add,Rat.cast_natCast,Rat.cast_one] + +/-- The initializer has a uniform binary bound using only the polynomial +small-cell scale, including values at pair arguments outside defect types. -/ +lemma initial_binary_bound (A : Instance I J) (p q : Pair A) : + RatBound (initial A p q) (2^(A.W+4)) := by + have hp := A.hsmall (p.1.1).1.val.1 (p.1.1).1.val.2 (p.1.1).1.property + have hq := A.hsmall (q.1.1).1.val.1 (q.1.1).1.val.2 (q.1.1).1.property + have hW : A.W ≤ 2^A.W := A.W.lt_two_pow_self.le + have hpow : 0 < 2^A.W := by positivity + have hnum : 6*(A.b (p.1.1).1.val.1 (p.1.1).1.val.2+1) ≤ 2^(A.W+4) := by + rw [pow_add] + norm_num + omega + have hden : A.b (q.1.1).1.val.1 (q.1.1).1.val.2+2 ≤ 2^(A.W+4) := by + rw [pow_add] + norm_num + omega + unfold initial + split_ifs + · apply RatBound.nat 6 _ _ (by positivity) + rw [pow_add] + norm_num + omega + · have hh := RatBound.nat_div _ _ _ hnum hden (by positivity) + simpa only [Nat.cast_mul,Nat.cast_add,Nat.cast_one,Nat.cast_ofNat] using hh + +def plainCount (A : Instance I J) (l : List (Set (Labels A×Bool))) : ℕ := + l.countP (fun S => decide (PlainState pairs S)) + +def defectCount (A : Instance I J) (l : List (Set (Labels A×Bool))) (p q : Pair A) : ℕ := + l.countP (fun S => decide (DefectState pairs p q S)) + +lemma plainCount_le (A : Instance I J) (l : List (Set (Labels A×Bool))) : + plainCount A l ≤ l.length := List.countP_le_length + +lemma defectCount_le (A : Instance I J) (l : List (Set (Labels A×Bool))) (p q : Pair A) : + defectCount A l p q ≤ l.length := List.countP_le_length + +lemma rationalLearn_counts (A : Instance I J) (w : Pair A → Pair A → ℚ) + (l : List (Set (Labels A×Bool))) (hl : 0 < l.length) (p q : Pair A) : + rationalLearn pairs w l p q= + if p∈pairs ∧ q∈pairs ∧ p≠q then w p q*(plainCount A l:ℚ)/(defectCount A l p q:ℚ) + else w p q := by + have hN : (l.length:ℚ)≠0 := by exact_mod_cast hl.ne' + unfold rationalLearn rationalEmpirical rationalPlain rationalDefect plainCount defectCount + simp only [indicator_list_sum] + split_ifs <;> simp only [div_div_div_cancel_right₀ hN,mul_div_assoc] + +/-- Every decision to divide is preceded by the literal positive-count +check used in the source algorithm. -/ +def CountsPositive (A : Instance I J) (l : List (Set (Labels A×Bool))) : Prop := + 0 < plainCount A l ∧ ∀ p∈pairs,∀ q∈pairs,p≠q → 0 < defectCount A l p q + +def checkedUpdate (A : Instance I J) (w : Pair A → Pair A → ℚ) + (l : List (Set (Labels A×Bool))) : Option (Pair A → Pair A → ℚ) := + if CountsPositive A l then some (rationalLearn pairs w l) else none + +lemma checkedUpdate_positive (A : Instance I J) (w : Pair A → Pair A → ℚ) + (hw : ∀ p q,0 < w p q) (l : List (Set (Labels A×Bool))) + (w' : Pair A → Pair A → ℚ) (hu : checkedUpdate A w l=some w') : + ∀ p q,0 < w' p q := by + unfold checkedUpdate at hu + split_ifs at hu with hc + · cases Option.some.inj hu + have hl : 0 < l.length := lt_of_lt_of_le hc.1 (plainCount_le A l) + intro p q + rw [rationalLearn_counts A w l hl] + split_ifs with hpq + · exact div_pos (mul_pos (hw p q) (by exact_mod_cast hc.1)) + (by exact_mod_cast hc.2 p hpq.1 q hpq.2.1 hpq.2.2) + · exact hw p q + +/-- The literal rational history is exactly the real +history, including all unsuccessful histories. -/ +def history (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) : + ℕ → Pair A → Pair A → ℚ + | 0 => initial A + | j+1 => rationalLearn pairs (history A samples j) (samples j) + +lemma history_cast (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) + (j : ℕ) (p q : Pair A) : + (history A samples j p q:ℝ)=weights A samples j p q := by + induction j generalizing p q with + | zero => exact initial_cast A p q + | succ j ih => + change (rationalLearn pairs (history A samples j) (samples j) p q:ℝ)=_ + rw [rationalLearn_cast] + have he : (fun p q => (history A samples j p q:ℝ))=weights A samples j := by + funext p q + exact ih p q + rw [he] + rfl + +theorem history_good (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) + (eta : ℝ) (he0 : 0 ≤ eta) (he1 : eta ≤ 1/4) (j : ℕ) + (hall : ∀ a (history A samples j p q:ℝ)) := by + have he : (fun p q => (history A samples j p q:ℝ))=weights A samples j := by + funext p q + exact history_cast A samples j p q + rw [he] + exact weights_good A samples eta he0 he1 j hall + +lemma history_positive (A : Instance I J) (samples : ℕ → List (Set (Labels A×Bool))) + (eta : ℝ) (he0 : 0 ≤ eta) (he1 : eta ≤ 1/4) (j : ℕ) + (hall : ∀ a simpa only [history,Nat.zero_mul,Nat.add_zero] using initial_binary_bound A p q + | succ j ih => + have hh := rationalLearn_bound pairs (history A samples j) (samples j) + (2^(A.W+4+j*N)) (2^N) (by positivity) + ((hlen j (by omega)).trans N.lt_two_pow_self.le) + (fun p q => ih (by intro a ha; exact hlen a (by omega)) p q) p q + simpa only [history,←pow_add,Nat.add_mul,Nat.one_mul,Nat.add_assoc] using hh + +end + +end ContingencyTables.CompanionRationalUpdates + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReferenceAccuracy.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReferenceAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..01e966a714e926964975c784cd5935ffe61ceb26 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReferenceAccuracy.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseComposition + +namespace OAI + +/-! # Relative accuracy of the literal companion ratio estimator + +The source's tolerance epsilon/(200(H+1)) turns the proved accumulated +logarithmic error into the required multiplicative error. The terminal +contamination bound supplies the remaining error term. +-/ + +namespace ContingencyTables.CompanionReferenceAccuracy + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication CompanionPhaseComposition + +theorem relative_of_log_error (epsilon R : ℝ) (he0 : 0 < epsilon) (he1 : epsilon < 1) + (hR : 0 < R) (herr : |Real.log R| ≤ epsilon/50) : + 1-epsilon/4 ≤ R ∧ R ≤ 1+epsilon/4 := by + have hl := Real.log_le_sub_one_of_pos hR + have hu := Real.one_sub_inv_le_log_of_pos hR + have he := abs_le.mp herr + have hinv : 1-epsilon/50 ≤ R⁻¹ := by linarith + have hm := mul_le_mul_of_nonneg_right hinv hR.le + rw [inv_mul_cancel₀ hR.ne'] at hm + have hc : (1-epsilon/50)*(1+epsilon/4) ≥ 1 := by + nlinarith [mul_nonneg he0.le (sub_nonneg.mpr he1.le)] + constructor + · linarith + · exact le_of_mul_le_mul_left (hm.trans hc) (show 0 < 1-epsilon/50 by linarith) + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def tolerance (epsilon : ℝ) (H : ℕ) : ℝ := + epsilon/(200*((H:ℝ)+1)) + +theorem accurate_phases_relative (A : Instance I J) + (samples : ℕ → List (Set (Labels A×Bool))) (epsilon : ℝ) + (he0 : 0 < epsilon) (he1 : epsilon < 1) (H : ℕ) + (hall : ∀ j < H, Accurate A samples (tolerance epsilon H) j) : + (1-epsilon/4)*total A H ≤ estimate A samples H ∧ + estimate A samples H ≤ (1+epsilon/4)*total A H := by + have hden : (0:ℝ) < 200*((H:ℝ)+1) := by positivity + have heta : 0 ≤ tolerance epsilon H := by unfold tolerance; positivity + have heta1 : tolerance epsilon H ≤ 1/4 := by + unfold tolerance + rw [div_le_iff₀ hden] + nlinarith [show (0:ℝ) ≤ H by positivity] + have hh := estimate_log_error A samples (tolerance epsilon H) heta heta1 H hall + have hC := total_positive A H + have herror : 4*(H:ℝ)*tolerance epsilon H ≤ epsilon/50 := by + unfold tolerance + rw [← mul_div_assoc,div_le_div_iff₀ hden (by norm_num : (0:ℝ) < 50)] + nlinarith [show (0:ℝ) ≤ H by positivity] + have hr := relative_of_log_error epsilon (estimate A samples H/total A H) he0 he1 + (div_pos hh.1 hC) (hh.2.trans herror) + constructor + · exact (le_div_iff₀ hC).mp hr.1 + · exact (div_le_iff₀ hC).mp hr.2 + +/-- The terminal contamination bound and a successful phase history +give a relative-error estimate of the table count. -/ +theorem reference_accuracy (A : Instance I J) + (samples : ℕ → List (Set (Labels A×Bool))) (epsilon Z : ℝ) + (he0 : 0 < epsilon) (he1 : epsilon < 1) (hZ : 0 ≤ Z) (H : ℕ) + (hall : ∀ j < H, Accurate A samples (tolerance epsilon H) j) + (hterminal : Z ≤ total A H ∧ total A H ≤ (1+epsilon/32)*Z) : + (1-epsilon)*Z ≤ estimate A samples H ∧ estimate A samples H ≤ (1+epsilon)*Z := by + apply final_estimate_accuracy epsilon Z (total A H) (estimate A samples H) he0 he1 hZ + · refine ⟨hterminal.1, hterminal.2.trans ?_⟩ + nlinarith [mul_nonneg he0.le hZ] + · exact accurate_phases_relative A samples epsilon he0 he1 H hall + +end ContingencyTables.CompanionReferenceAccuracy + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRepeatedReturnLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRepeatedReturnLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef25218d11cdc58f8f82d30a2251f43e12350f18 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRepeatedReturnLaw.lean @@ -0,0 +1,166 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRepeatedReturnProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnHistoryLaw +import OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnWords + +namespace OAI + +/-! # The physical return loop has the actual repeated-return law -/ + +namespace ContingencyTables.CompanionRepeatedReturnProgram + +open MatchingFPRAS CommonBasesFPRAS FirstSuccess ResidualMixture +open CompanionFactorialApplication CompanionOracleDensity CompanionWeightOracle +open CompanionComputedInitial CompanionComputedProposal CompanionArithmeticProposal +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram +open FiniteObservableTransport TwoLiftStates GridBoundary +open scoped Classical + +noncomputable section +variable {m n : ℕ} + +def fixedData (A : Instance (Fin m) (Fin n)) (C K j k cap : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S₀ : Set (Labels A × Bool)) : Fixed := + ((((RootedLabelWeightProgram.config A C K j xi xi z v degree depth,matrixCode w),k), + encodeSet (coordinateOrder A) S₀),cap) + +def data (A : Instance (Fin m) (Fin n)) (C K j k cap t : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : Set (Labels A × Bool)) (bits : List Bool) : Input := + (((fixedData A C K j k cap xi z v degree depth w S, + encodeSet (coordinateOrder A) S),t),bits) + +def codeStep (fixed : Fixed) (code : List ℕ) (bits : List Bool) : List ℕ := + next (bits,(fixed,code)) + +lemma walk_eq (fixed : Fixed) (words : List (List Bool)) (code : List ℕ) : + walk ((fixed,code),words)=(fixed,words.foldl (codeStep fixed) code) := by + induction words generalizing code with + | nil => rfl + | cons word words ih => + simpa only [walk,List.foldl_cons,advance,codeStep] using ih (next (word,(fixed,code))) + +lemma blockWidth_data (A : Instance (Fin m) (Fin n)) (C K j k cap : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : Set (Labels A × Bool)) : + blockWidth (fixedData A C K j k cap xi z v degree depth w S)= + (cap+1)*CompanionBooleanPhase.stepBits A C K j k xi := by + unfold blockWidth widthInput fixedData + dsimp only + exact congrArg (fun width : ℕ => (cap+1)*width) + (CompanionTransitionWidth.width_config A C K j k xi z v degree depth (matrixCode w) S []) + +lemma words_data (A : Instance (Fin m) (Fin n)) (C K j k cap t : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : Set (Labels A × Bool)) + (bits : Fin (t*((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi)) → Bool) : + words (data A C K j k cap t xi z v degree depth w S (List.ofFn bits))= + List.ofFn (fun i : Fin t => List.ofFn (gridWordEquiv t + ((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi) bits i)) := by + unfold words data + dsimp only + rw [blockWidth_data] + rw [DensePrograms.wordChunks_ofFn (by unfold CompanionBooleanPhase.stepBits; positivity)] + exact List.take_of_length_le (by simp only [List.length_ofFn]; exact le_rfl) + +theorem codeStep_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k cap : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S₀ : Set (Labels A × Bool)) (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) : + SameLaw (fun bits : Fin ((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi) → Bool => + codeStep (fixedData A C K j k cap xi z v degree depth w S₀) + (encodeSet (coordinateOrder A) S.val.val) (List.ofFn bits)) + (fun bits => encodeSet (coordinateOrder A) + (RootedCappedReturn.returnWordDefault A (RootedCompletion.rowColumn A.T) C K j k cap hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S bits).val.val) := by + have h := RootedReturnHistoryLaw.flatReturn_sameLaw A C K j k cap hC hj hK hW hB xi hxi + z v degree depth hdegree hdepth w S + have hm := h.map (fun code => ProfilePrograms.capView + (((encodeSet (coordinateOrder A) S₀).length,1),code)) + intro phi + simpa only [codeStep,next,bound,candidate,returnInput,fixedData, + CompanionFlatReturnProgram.data,CompanionFlatReturnProgram.stateData, + CompanionBoundedWalkProgram.cap_encode] using hm phi + +private lemma wordWalk_fold {X : Type*} {k : ℕ} + (F : X → (Fin k → Bool) → X) (x : X) (t : ℕ) (bits : Fin t → Fin k → Bool) : + wordWalk F x t bits=(List.ofFn bits).foldl F x := by + induction t with + | zero => rfl + | succ t ih => + rw [wordWalk,ih,List.ofFn_succ',List.concat_eq_append,List.foldl_append] + rfl + +/-- Independent physical return blocks preserve the entire repeated +return distribution, including fallback events in every block. -/ +theorem output_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k cap t : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) : + SameLaw (fun bits : Fin (t*((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi)) → Bool => + output (data A C K j k cap t xi z v degree depth w S.val.val (List.ofFn bits))) + (fun bits => encodeSet (coordinateOrder A) + (RootedReturnWords.booleanReturns A (RootedCompletion.rowColumn A.T) C K j k cap t hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S bits).val.val) := by + let fixed := fixedData A C K j k cap xi z v degree depth w S.val.val + let F := fun (code : List ℕ) + (bits : Fin ((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi) → Bool) => + codeStep fixed code (List.ofFn bits) + let G := RootedCappedReturn.returnWordDefault A (RootedCompletion.rowColumn A.T) C K j k cap hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) + let encode := fun T : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) => + encodeSet (coordinateOrder A) T.val.val + have hh := foldl_sameLaw F G encode + (codeStep_sameLaw A C K j k cap hC hj hK hW hB xi hxi z v degree depth hdegree hdepth w S.val.val) S t + let E := gridWordEquiv t ((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi) + have hout (bits : Fin (t*((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi)) → Bool) : + output (data A C K j k cap t xi z v degree depth w S.val.val (List.ofFn bits))= + (List.ofFn (E bits)).foldl F (encode S) := by + unfold output + rw [words_data] + change (walk ((fixed,encode S),List.ofFn (fun i => List.ofFn (E bits i)))).2=_ + rw [walk_eq] + have he : List.ofFn (fun i => List.ofFn (E bits i))=(List.ofFn (E bits)).map List.ofFn := by + rw [List.map_ofFn] + rfl + rw [he,List.foldl_map] + intro phi + have hleft := uniformAverage_equiv E + (fun bs => phi ((List.ofFn bs).foldl F (encode S))) + have hright := uniformAverage_equiv E + (fun bs => phi (encode ((List.ofFn bs).foldl G S))) + calc + _ = uniformAverage (fun bits => phi ((List.ofFn (E bits)).foldl F (encode S))) := by + apply congrArg uniformAverage + funext bits + dsimp only + rw [hout] + _ = uniformAverage (fun bs => phi ((List.ofFn bs).foldl F (encode S))) := hleft + _ = uniformAverage (fun bs => phi (encode ((List.ofFn bs).foldl G S))) := hh phi + _ = uniformAverage (fun bits => phi (encode ((List.ofFn (E bits)).foldl G S))) := hright.symm + _ = _ := by + apply congrArg uniformAverage + funext bits + dsimp only + change phi (encode ((List.ofFn (E bits)).foldl G S))= + phi (encode (wordWalk G S t (E bits))) + rw [wordWalk_fold] + +end +end ContingencyTables.CompanionRepeatedReturnProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRepeatedReturnProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRepeatedReturnProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..2715a8729a201cd6b95b25159c5a539858aa242b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRepeatedReturnProgram.lean @@ -0,0 +1,159 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFlatReturnProgram + +namespace OAI + +/-! # Bounded iteration of the executed capped-return routine + +The numeric repetition count only truncates chunks of the supplied +word. The stored profile is clipped to the fixed initial dimension, +which is redundant on every actual encoded state. +-/ + +namespace ContingencyTables.CompanionRepeatedReturnProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial DensePrograms + +abbrev Fixed := CompanionBoundedWalkProgram.Fixed × ℕ +abbrev State := Fixed × List ℕ +abbrev Input := (State × ℕ) × List Bool + +def returnInput (z : List Bool × State) : CompanionFlatReturnProgram.Input := + ((((z.2.1.1.1,z.2.2),z.2.2),z.2.1.2+1),z.1) +def returnInputRealizer : Realizer returnInput := by + let frame : Realizer (fun z : List Bool × State => z.2.1.1.1) := + composition (composition (composition second first) first) first + let current : Realizer (fun z : List Bool × State => z.2.2) := composition second second + let cap : Realizer (fun z : List Bool × State => z.2.1.2+1) := + composition (f := fun z : List Bool × State => z.2.1.2) (g := Nat.succ) + (composition (composition second first) second) successor + exact pair (pair (pair (pair frame current) current) cap) first +lemma polynomial_returnInput : PolynomialTime returnInputRealizer := by + unfold returnInputRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_second polynomial_first) polynomial_first) polynomial_first) + (polynomial_composition polynomial_second polynomial_second)) + (polynomial_composition polynomial_second polynomial_second)) + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_second polynomial_first) polynomial_second) polynomial_successor)) polynomial_first + +def candidate (z : List Bool × State) : List ℕ := CompanionFlatReturnProgram.output (returnInput z) +def candidateRealizer : Realizer candidate := + composition (f := returnInput) (g := CompanionFlatReturnProgram.output) + returnInputRealizer CompanionFlatReturnProgram.outputRealizer +lemma polynomial_candidate : PolynomialTime candidateRealizer := + polynomial_composition polynomial_returnInput CompanionFlatReturnProgram.polynomial_output + +def bound (z : List Bool × State) : ℕ := z.2.1.1.2.length +def boundRealizer : Realizer bound := + composition (composition (composition (composition second first) first) second) listLength +lemma polynomial_bound : PolynomialTime boundRealizer := by + unfold boundRealizer + exact polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_second polynomial_first) polynomial_first) + polynomial_second) polynomial_listLength + +attribute [local irreducible] candidate + +def next (z : List Bool × State) : List ℕ := ProfilePrograms.capView ((bound z,1),candidate z) +def nextRealizer : Realizer next := + composition (f := fun z : List Bool × State => ((bound z,1),candidate z)) + (g := ProfilePrograms.capView) (pair (pair boundRealizer (constant 1)) candidateRealizer) + ProfilePrograms.capViewRealizer +lemma polynomial_next : PolynomialTime nextRealizer := + polynomial_composition (polynomial_pair (polynomial_pair polynomial_bound (polynomial_constant 1)) + polynomial_candidate) ProfilePrograms.polynomial_capView + +def advance (z : List Bool × State) : State := (z.2.1,next z) +def advanceRealizer : Realizer advance := pair (composition second first) nextRealizer +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) polynomial_next + +lemma advance_weight (word : List Bool) (state : State) (S : ℕ) (hs : weight state.1 ≤ S) : + weight (advance (word,state)) ≤ 10*(S+1) := by + have hb : state.1.1.2.length ≤ S := (list_length_le_weight _).trans + ((weight_snd state.1.1).trans ((weight_fst state.1).trans hs)) + have hn := ProfilePrograms.capView_weight state.1.1.2.length 1 (candidate (word,state)) + change weight (next (word,state)) ≤ _ at hn + norm_num only [Nat.size_one] at hn + change weight (state.1,next (word,state)) ≤ _ + rw [weight_prod] + omega + +def walk (z : State × List (List Bool)) : State := + z.2.foldl (fun state bits => advance (bits,state)) z.1 +def walkRealizer : Realizer walk := composition (pair second first) (fold advanceRealizer) + +lemma fold_fixed (words : List (List Bool)) (state : State) : + (words.foldl (fun state bits => advance (bits,state)) state).1=state.1 := by + induction words generalizing state with + | nil => rfl + | cons word words ih => exact ih _ + +lemma fold_weight (words : List (List Bool)) (state : State) (S : ℕ) (hs : weight state ≤ S) : + weight (words.foldl (fun state bits => advance (bits,state)) state) ≤ 10*(S+1) := by + induction words using List.reverseRecOn with + | nil => simpa using hs.trans (by omega : S ≤ 10*(S+1)) + | append_singleton words word _ => + rw [List.foldl_append] + simp only [List.foldl_cons,List.foldl_nil] + apply advance_weight + rw [fold_fixed] + exact (weight_fst state).trans hs + +theorem polynomial_walk : PolynomialTime walkRealizer := by + apply polynomial_composition (polynomial_pair polynomial_second polynomial_first) + apply polynomial_fold polynomial_advance (10*(X+1)) + intro words state pre post _ + simp only [eval_mul,eval_ofNat,eval_add,eval_X,eval_one] + exact fold_weight pre state (weight (words,state)) (weight_snd (words,state)) + +def widthInput (fixed : Fixed) : CompanionMetropolisWordProgram.Input := + ((fixed.1.1,fixed.1.2),[]) +def widthInputRealizer : Realizer widthInput := + pair (pair (composition first first) (composition first second)) (constant []) +lemma polynomial_widthInput : PolynomialTime widthInputRealizer := by + unfold widthInputRealizer + exact polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_first polynomial_second)) (polynomial_constant []) + +def blockWidth (fixed : Fixed) : ℕ := + (fixed.2+1)*CompanionTransitionWidth.width (widthInput fixed) +def blockWidthRealizer : Realizer blockWidth := + composition (f := fun fixed : Fixed => (fixed.2+1,CompanionTransitionWidth.width (widthInput fixed))) + (g := fun z : ℕ × ℕ => z.1*z.2) + (pair (composition second successor) + (composition (f := widthInput) (g := CompanionTransitionWidth.width) + widthInputRealizer CompanionTransitionWidth.widthRealizer)) multiply +lemma polynomial_blockWidth : PolynomialTime blockWidthRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_successor) + (polynomial_composition polynomial_widthInput CompanionTransitionWidth.polynomial_width)) polynomial_multiply + +def words (z : Input) : List (List Bool) := + (wordChunks (blockWidth z.1.1.1,z.2)).take z.1.2 +def wordsRealizer : Realizer words := + composition (f := fun z : Input => (wordChunks (blockWidth z.1.1.1,z.2),z.1.2)) + (g := fun z : List (List Bool) × ℕ => z.1.take z.2) + (pair (composition (f := fun z : Input => (blockWidth z.1.1.1,z.2)) (g := wordChunks) + (pair (composition (f := fun z : Input => z.1.1.1) (g := blockWidth) + (composition (composition first first) first) blockWidthRealizer) second) wordChunksRealizer) + (composition first second)) takeFast +lemma polynomial_words : PolynomialTime wordsRealizer := by + apply polynomial_composition _ polynomial_takeFast + apply polynomial_pair _ (polynomial_composition polynomial_first polynomial_second) + apply polynomial_composition _ polynomial_wordChunks + apply polynomial_pair _ polynomial_second + exact polynomial_composition (by tree_poly) polynomial_blockWidth + +def output (z : Input) : List ℕ := (walk (z.1.1,words z)).2 +def outputRealizer : Realizer output := + composition (f := fun z : Input => (z.1.1,words z)) (g := fun z => (walk z).2) + (pair (composition first first) wordsRealizer) + (composition (f := walk) (g := Prod.snd) walkRealizer second) +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_words) (polynomial_composition polynomial_walk polynomial_second) + +end ContingencyTables.CompanionRepeatedReturnProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartContinuation.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartContinuation.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f7bf90fb8808880105b15fb6f7fcbbc6f1c49d5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartContinuation.lean @@ -0,0 +1,80 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseContinuation + +namespace OAI + +/-! # Binding a restart law to its independent phase continuation -/ +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS +noncomputable section + +theorem joint_encoded_bind {A B U V C Z W : Type*} + [Fintype A] [Fintype B] [Fintype U] [Fintype V] + (f : A → C×U) (g : B → Z) (e : Z → C) + (F : C → U → W) (G : Z → V → W) + (hinit : SameLaw f (fun p : B×U => (e (g p.1),p.2))) + (hstep : ∀ z,SameLaw (F (e z)) (G z)) : + SameLaw (fun a => F (f a).1 (f a).2) (fun p : B×V => G (g p.1) p.2) := by + intro phi + have hi := hinit (fun p => phi (F p.1 p.2)) + refine hi.trans ?_ + rw [uniformAverage_prod,uniformAverage_prod] + apply congrArg uniformAverage + funext b + exact hstep (g b) phi + +end +end ContingencyTables.FiniteObservableTransport + +namespace ContingencyTables.CompanionOuterPhaseProgram +open MatchingFPRAS CommonBasesFPRAS CompanionFactorialApplication CompanionComputedInitial +open CompanionComputedProposal CompanionArithmeticProposal CompanionEvaluatedWeightProgram +open CompanionMultiplierMatrixProgram CompanionOracleDensity GridBoundary FiniteObservableTransport +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def configs (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + CompanionPhaseContinuation.Configs := + let p := CompanionInitializedRestartProgram.parameters A H T N R L epsilon + CompanionObservationQueriesProgram.phaseConfigs A C K j + (TreeFraction.val (CountingPhaseParametersProgram.noise p)) z v + (CompanionRestartStageProgram.degree A C K j p z v reserve) + (CompanionRestartStageProgram.depth A C K j p z v reserve) + (CompanionRestartStageProgram.degree A C K (j+1) p z v reserve) + (CompanionRestartStageProgram.depth A C K (j+1) p z v reserve) + +lemma output_data_run (A : Instance (Fin m) (Fin n)) (C K H T N R L j : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ→LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (E : ℕ→TreeFraction.Fraction) (reserve bits : List Bool) + (hlen : bits.length=reserve.length) : + output (data A C K H T N R L j epsilon z v w E bits)= + CompanionPhaseContinuation.run (configs A C K H T N R L j epsilon z v reserve) + (matrixCode (w j),E j) + (CountingPhaseParametersProgram.precision + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon)) + (CountingPhaseParametersProgram.observations + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon)) + (CompanionInitializedRestartProgram.output + (CompanionInitializedRestartProgram.data A C K H T N R L j epsilon z v w + (fun i => E (i.val+1)) bits)) + (bits.drop (wordLength A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + CompanionRestartProgram.sumBits A C K j + (CompanionInitializedRestartProgram.parameters A H T N R L epsilon))) := by + rw [CompanionPhaseContinuation.outer_eq,configAt_data,configAt_data,old_data] + unfold startCode afterRestart + rw [restartInput_data,restartWidth_data] + simp only [Nat.add_zero] + unfold configs CompanionObservationQueriesProgram.phaseConfigs + simp only [CompanionRestartStageProgram.degree,CompanionRestartStageProgram.depth, + CompanionRestartStageProgram.oracleData,hlen] + rfl + +end +end ContingencyTables.CompanionOuterPhaseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartDataLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartDataLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..874999de67bff589c8d8f42838e9e1864c0e48d7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartDataLaw.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartStageLaw + +namespace OAI + +/-! # The concrete stored-matrix restart experiment -/ +namespace ContingencyTables.CompanionRestartProgram +open MatchingFPRAS CommonBasesFPRAS FirstSuccess FiniteObservableTransport +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram +open CompanionOracleDensity CompanionWeightOracle TwoLiftStates GridBoundary +open scoped BigOperators Classical +noncomputable section +variable {m n : ℕ} + +def stagesData (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) : List Stage := + List.ofFn (fun i : Fin j => + (CompanionPhaseContextProgram.data A C K (i.val+1) parameters z v reserve,matrixCode (w (i.val+1)))) + +def baseData (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) : + List Stage×List ℕ := + (stagesData A C K j parameters z v reserve w,encodeSet (coordinateOrder A) S) + +def sourceWidth (A : Instance (Fin m) (Fin n)) (C K : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (i : ℕ) : ℕ := + CountingPhaseParametersProgram.scalar (.input 3) parameters* + ((CountingPhaseParametersProgram.scalar (.input 5) parameters+1)* + CompanionBooleanPhase.stepBits A C K (i+1) (CountingPhaseParametersProgram.precision parameters) + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters))) + +lemma request_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) + (i : Fin j) : + request ((baseData A C K j parameters z v reserve w S,[]),i.val)= + CompanionRestartStageProgram.data A C K (i.val+1) parameters z v reserve (w (i.val+1)) S := by + unfold request baseData stagesData + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some] + rfl + +theorem widthAt_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) + (i : Fin j) : + widthAt (baseData A C K j parameters z v reserve w S) i.val= + sourceWidth A C K parameters i.val := by + unfold widthAt indexedWidth + rw [request_data,CompanionRestartStageProgram.width_data] + rfl + +def sourceStep (A : Instance (Fin m) (Fin n)) (C K : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) (i : ℕ) + (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) + (bits : Fin (sourceWidth A C K parameters i) → Bool) : + PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) := + RootedReturnWords.booleanReturns A (RootedCompletion.rowColumn A.T) C K (i+1) + (CountingPhaseParametersProgram.precision parameters) + (CountingPhaseParametersProgram.scalar (.input 5) parameters) + (CountingPhaseParametersProgram.scalar (.input 3) parameters) hK hW + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A (w (i+1))) S bits + +theorem detached_data_sameLaw (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hH : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (parameters : CountingPhaseParametersProgram.Input) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (reserve : List Bool) + (hdegree : ∀ i : Fin j,RootedOracleConfigProgram.rootDegree + (CompanionRestartStageProgram.oracleData A C K (i.val+1) parameters z v reserve) ≤ reserve.length) + (hdepth : ∀ i : Fin j,RootedOracleConfigProgram.depth + (CompanionRestartStageProgram.oracleData A C K (i.val+1) parameters z v reserve) ≤ reserve.length) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S₀ : Set (Labels A×Bool)) (i : Fin j) + (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) : + SameLaw (fun bits : Fin (widthAt (baseData A C K j parameters z v reserve w S₀) i.val) → Bool => + detachedStep (baseData A C K j parameters z v reserve w S₀) i.val + (encodeSet (coordinateOrder A) S.val.val) (List.ofFn bits)) + (fun bits => encodeSet (coordinateOrder A) + (sourceStep A C K parameters hK hW v w i.val S bits).val.val) := by + have hstage := CompanionRestartStageProgram.output_sameLaw A C K (i.val+1) + hC (by omega) hK hW hB parameters hxi z v reserve (hdegree i) (hdepth i) (w (i.val+1)) S + dsimp only at hstage + have hm := hstage.map (fun code => ProfilePrograms.capView + (((encodeSet (coordinateOrder A) S₀).length,1),code)) + have hu := widthAt_data A C K j parameters z v reserve w S₀ i + have ht := SameLaw.word_length hu.symm + (fun bits => ProfilePrograms.capView (((encodeSet (coordinateOrder A) S₀).length,1), + CompanionRestartStageProgram.output + (CompanionRestartStageProgram.data A C K (i.val+1) parameters z v reserve + (w (i.val+1)) S.val.val,bits))) + (fun bits => ProfilePrograms.capView (((encodeSet (coordinateOrder A) S₀).length,1), + encodeSet (coordinateOrder A) (sourceStep A C K parameters hK hW v w i.val S bits).val.val)) hm + intro phi + have he : (stagesData A C K j parameters z v reserve w).getD i.val default= + (CompanionPhaseContextProgram.data A C K (i.val+1) parameters z v reserve,matrixCode (w (i.val+1))) := by + simp only [stagesData,List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some] + simpa only [detachedStep,baseData,he,CompanionRestartStageProgram.data, + CompanionBoundedWalkProgram.cap_encode] using ht phi + +theorem output_data_sameLaw (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hH : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (parameters : CountingPhaseParametersProgram.Input) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (reserve : List Bool) + (hdegree : ∀ i : Fin j,RootedOracleConfigProgram.rootDegree + (CompanionRestartStageProgram.oracleData A C K (i.val+1) parameters z v reserve) ≤ reserve.length) + (hdepth : ∀ i : Fin j,RootedOracleConfigProgram.depth + (CompanionRestartStageProgram.oracleData A C K (i.val+1) parameters z v reserve) ≤ reserve.length) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) : + SameLaw (fun bits : Fin (∑ i : Fin (baseData A C K j parameters z v reserve w S.val.val).1.length, + widthAt (baseData A C K j parameters z v reserve w S.val.val) i.val) → Bool => + output (baseData A C K j parameters z v reserve w S.val.val,List.ofFn bits)) + (fun bits : Fin (∑ i : Fin (baseData A C K j parameters z v reserve w S.val.val).1.length, + sourceWidth A C K parameters i.val) → Bool => + encodeSet (coordinateOrder A) + (varyingWalk (sourceWidth A C K parameters) (sourceStep A C K parameters hK hW v w) S + (baseData A C K j parameters z v reserve w S.val.val).1.length + (varyingWordEquiv (sourceWidth A C K parameters) + (baseData A C K j parameters z v reserve w S.val.val).1.length bits)).val.val) := by + apply output_sameLaw _ _ _ (fun T => encodeSet (coordinateOrder A) T.val.val) S rfl + intro i hi T + have hij : i < j := by simpa only [baseData,stagesData,List.length_ofFn] using hi + exact detached_data_sameLaw A C K j hC hH hK hW hB parameters hxi z v reserve hdegree hdepth + w S.val.val ⟨i,hij⟩ T + +end +end ContingencyTables.CompanionRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartInitializer.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartInitializer.lean new file mode 100644 index 0000000000000000000000000000000000000000..56d0b41722f973a97150d7295e55f42521c72d85 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartInitializer.lean @@ -0,0 +1,162 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseContextProgram +import OAI.Combinatorics.ContingencyTables.Machines.InitialDrawReindex + +namespace OAI + +/-! # The computed finite initializer used before every restart experiment -/ +namespace ContingencyTables.CompanionRestartInitializer +open MatchingFPRAS MatchingFPRAS.TreeTyped ScalarScheduleProgram DensePrograms + +abbrev Prepared := CompanionPhaseContextProgram.Prepared +abbrev Input := Prepared×List Bool + +def forest (z : Prepared) : RootedForestCatalog.Data := z.1.1.2.2.1 +def forestRealizer : Realizer forest := + composition (composition (composition (composition first first) second) second) first +lemma polynomial_forest : PolynomialTime forestRealizer := by + unfold forestRealizer + exact polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_second) + polynomial_first + +def cellInput (z : Prepared) : CompanionCellCatalog.Input := + (((forest z).1.2,(forest z).2),(forest z).1.1.2) +def cellInputRealizer : Realizer cellInput := + pair (pair (composition (f := forest) (g := fun d : RootedForestCatalog.Data => d.1.2) + forestRealizer (composition first second)) + (composition (f := forest) (g := Prod.snd) forestRealizer second)) + (composition (f := forest) (g := fun d : RootedForestCatalog.Data => d.1.1.2) + forestRealizer (composition (composition first first) second)) +lemma polynomial_cellInput : PolynomialTime cellInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition polynomial_forest (polynomial_composition polynomial_first polynomial_second)) + (polynomial_composition polynomial_forest polynomial_second)) + (polynomial_composition polynomial_forest + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second)) + +def fields (z : Prepared) : List ℕ := z.1.1.2.1.1.1::z.2.1 +def fieldsRealizer : Realizer fields := + composition (f := fun z : Prepared => (z.1.1.2.1.1.1,z.2.1)) + (g := fun p : ℕ×List ℕ => p.1::p.2) + (pair (composition (composition (composition (composition (composition first first) second) first) first) first) + (composition second first)) listCons +lemma polynomial_fields : PolynomialTime fieldsRealizer := by + unfold fieldsRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_first) polynomial_first) polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) polynomial_listCons + +def initialBound : Expr := (.input 0)*(3*(.input 2)+1)+1 +def initialExponent : Expr := 2048*((.input 3)+1) +def scalar (e : Expr) (z : Prepared) : ℕ := e.eval (fields z) +def scalarRealizer (e : Expr) : Realizer (scalar e) := + composition (f := fields) (g := e.eval) fieldsRealizer e.realizer +lemma polynomial_scalar (e : Expr) : PolynomialTime (scalarRealizer e) := + polynomial_composition polynomial_fields e.polynomial + +def precision (z : Prepared) : ℕ := Nat.clog 2 (scalar initialBound z)+scalar initialExponent z +def precisionRealizer : Realizer precision := + composition (f := fun z : Prepared => + (Nat.clog 2 (scalar initialBound z),scalar initialExponent z)) + (g := fun p : ℕ×ℕ => p.1+p.2) + (pair (composition (f := scalar initialBound) (g := Nat.clog 2) + (scalarRealizer initialBound) ceilLogTwoRealizer) (scalarRealizer initialExponent)) add +lemma polynomial_precision : PolynomialTime precisionRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_scalar initialBound) polynomial_ceilLogTwo) + (polynomial_scalar initialExponent)) polynomial_add + +def capacities (z : Prepared) : List ℕ := CompanionCellCatalog.capacities (cellInput z) +def capacitiesRealizer : Realizer capacities := + composition (f := cellInput) (g := CompanionCellCatalog.capacities) + cellInputRealizer CompanionCellCatalog.capacitiesRealizer +lemma polynomial_capacities : PolynomialTime capacitiesRealizer := + polynomial_composition polynomial_cellInput CompanionCellCatalog.polynomial_capacities + +def width (z : Prepared) : ℕ := (InitialChoiceProgram.widths (capacities z,precision z)).sum +def widthRealizer : Realizer width := + composition (f := fun z : Prepared => InitialChoiceProgram.widths (capacities z,precision z)) + (g := List.sum) + (composition (f := fun z : Prepared => (capacities z,precision z)) (g := InitialChoiceProgram.widths) + (pair capacitiesRealizer precisionRealizer) InitialChoiceProgram.widthsRealizer) listSum +theorem polynomial_width : PolynomialTime widthRealizer := + polynomial_composition (polynomial_composition (polynomial_pair polynomial_capacities polynomial_precision) + InitialChoiceProgram.polynomial_widths) polynomial_listSum + +def prepare (z : Input) : CompanionComputedInitial.ProgramInput := ((cellInput z.1,precision z.1),z.2) +def prepareRealizer : Realizer prepare := + pair (pair (composition (f := fun z : Input => z.1) (g := cellInput) first cellInputRealizer) + (composition (f := fun z : Input => z.1) (g := precision) first precisionRealizer)) second +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_cellInput) + (polynomial_composition polynomial_first polynomial_precision)) polynomial_second + +def output (z : Input) : List ℕ := CompanionComputedInitial.initialProgram (prepare z) +def outputRealizer : Realizer output := + composition (f := prepare) (g := CompanionComputedInitial.initialProgram) + prepareRealizer CompanionComputedInitial.initialProgramRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare CompanionComputedInitial.polynomial_initialProgram + +noncomputable section +open CompanionFactorialApplication CompanionOracleDensity GridBoundary +open CompanionComputedInitial CompanionArithmeticProposal FiniteObservableTransport +open scoped BigOperators Classical +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (C K H T N R L : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : Prepared := + (RootedOracleWalkProgram.data A C 0 K z v, + ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon)) + +lemma cellInput_data (A : Instance (Fin m) (Fin n)) (C K H T N R L : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + cellInput (data A C K H T N R L epsilon z v)=CompanionCellCatalog.input A := rfl + +lemma precision_data (A : Instance (Fin m) (Fin n)) (C K H T N R L : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + precision (data A C K H T N R L epsilon z v)= + CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H) := by + simp [precision,scalar,fields,data,RootedOracleWalkProgram.data, + initialBound,initialExponent,Expr.eval,CompanionInitialDraw.precision,CountingPhaseSchedule.initialPrecision] + +lemma width_data (A : Instance (Fin m) (Fin n)) (C K H T N R L : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + width (data A C K H T N R L epsilon z v)= + CompanionComputedInitial.wordLength A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H)) := by + unfold width capacities + rw [cellInput_data,CompanionCellCatalog.capacities_eq,precision_data] + rw [InitialChoiceProgram.widths_ofFn,List.sum_ofFn] + rfl + +theorem output_sameLaw (A : Instance (Fin m) (Fin n)) (C K H T N R L : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + let B := CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H) + SameLaw (fun bits : Fin (CompanionComputedInitial.wordLength A B) → Bool => + output (data A C K H T N R L epsilon z v,List.ofFn bits)) + (fun bits => encodeSet (coordinateOrder A) (CompanionInitialDraw.draw A B bits).val.val) := by + dsimp only + have hB : 0 < CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H) := by + unfold CompanionInitialDraw.precision CountingPhaseSchedule.initialPrecision + omega + have h := initialProgram_sameLaw A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H)) hB + intro phi + convert h phi using 1 + apply congrArg CommonBasesFPRAS.uniformAverage + funext bits + dsimp only + rw [output,prepare,cellInput_data,precision_data] + +end +end ContingencyTables.CompanionRestartInitializer + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartNativeLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartNativeLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b50f0ebed66c6fee84ca80213da232038c2aafb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartNativeLaw.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartDataLaw + +namespace OAI + +/-! # A common native bit width for all initial plain states -/ +namespace ContingencyTables.CompanionRestartProgram +open MatchingFPRAS CommonBasesFPRAS FirstSuccess FiniteObservableTransport +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionEvaluatedWeightProgram +open CompanionOracleDensity TwoLiftStates GridBoundary +open scoped BigOperators Classical +noncomputable section +variable {m n : ℕ} + +private lemma normalize_varying_law {X Y : Type*} [Fintype X] [DecidableEq X] + (a l j : ℕ) (hl : l=j) (width : ℕ → ℕ) + (step : (i : ℕ) → X → (Fin (width i) → Bool) → X) + (f : List Bool → Y) (e : X → Y) (x : X) + (ha : a=∑ i : Fin j,width i.val) + (h : SameLaw (fun bits : Fin a → Bool => f (List.ofFn bits)) + (fun bits : Fin (∑ i : Fin l,width i.val) → Bool => + e (varyingWalk width step x l (varyingWordEquiv width l bits)))) : + SameLaw (fun bits : Fin (∑ i : Fin j,width i.val) → Bool => f (List.ofFn bits)) + (fun bits : Fin (∑ i : Fin j,width i.val) → Bool => + e (varyingWalk width step x j (varyingWordEquiv width j bits))) := by + cases hl + exact SameLaw.word_length ha f _ h + +def sumBits (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) : ℕ := + ∑ i : Fin j,sourceWidth A C K parameters i.val + +lemma widthSum_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) : + (∑ i : Fin (baseData A C K j parameters z v reserve w S).1.length, + widthAt (baseData A C K j parameters z v reserve w S) i.val)=sumBits A C K j parameters := by + have hn : (baseData A C K j parameters z v reserve w S).1.length=j := by + simp only [baseData,stagesData,List.length_ofFn] + rw [hn] + exact Finset.sum_congr rfl (fun i _ => widthAt_data A C K j parameters z v reserve w S i) + +theorem output_native_sameLaw (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hH : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (parameters : CountingPhaseParametersProgram.Input) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (reserve : List Bool) + (hdegree : ∀ i : Fin j,RootedOracleConfigProgram.rootDegree + (CompanionRestartStageProgram.oracleData A C K (i.val+1) parameters z v reserve) ≤ reserve.length) + (hdepth : ∀ i : Fin j,RootedOracleConfigProgram.depth + (CompanionRestartStageProgram.oracleData A C K (i.val+1) parameters z v reserve) ≤ reserve.length) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) : + SameLaw (fun bits : Fin (sumBits A C K j parameters) → Bool => + output (baseData A C K j parameters z v reserve w S.val.val,List.ofFn bits)) + (fun bits : Fin (sumBits A C K j parameters) → Bool => + encodeSet (coordinateOrder A) + (varyingWalk (sourceWidth A C K parameters) (sourceStep A C K parameters hK hW v w) S j + (varyingWordEquiv (sourceWidth A C K parameters) j bits)).val.val) := by + have h := output_data_sameLaw A C K j hC hH hK hW hB parameters hxi z v reserve hdegree hdepth w S + have hn := widthSum_data A C K j parameters z v reserve w S.val.val + have hl : (baseData A C K j parameters z v reserve w S.val.val).1.length=j := by + simp only [baseData,stagesData,List.length_ofFn] + exact normalize_varying_law _ _ j hl (sourceWidth A C K parameters) + (sourceStep A C K parameters hK hW v w) + (fun bits => output (baseData A C K j parameters z v reserve w S.val.val,bits)) + (fun T => encodeSet (coordinateOrder A) T.val.val) S hn h + +end +end ContingencyTables.CompanionRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartPadding.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartPadding.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a1750539fb6b395b1d7158172f4c17798feabc2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartPadding.lean @@ -0,0 +1,105 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSemantics + +namespace OAI + +/-! # Unused tail bits do not alter the executed restart stages -/ +namespace ContingencyTables.DensePrograms +open scoped BigOperators + +lemma prefix_sum_add_width_le {q : ℕ} (width : Fin q → ℕ) (i : Fin q) : + ((List.ofFn width).take i.val).sum+width i ≤ ∑ j,width j := by + by_cases hi : width i=0 + · rw [hi,Nat.add_zero,←List.sum_ofFn] + exact (List.take_sublist i.val (List.ofFn width)).sum_le_sum (fun _ _ => Nat.zero_le _) + · have h := (finSigmaFinEquiv (⟨i,⟨width i-1,by omega⟩⟩ : Sigma (fun i => Fin (width i)))).isLt + rw [finSigmaFinEquiv_apply,←take_ofFn_sum] at h + dsimp only at h + omega + +theorem dependentChunk_take_sum {q : ℕ} (width : Fin q → ℕ) + (bits : List Bool) (i : Fin q) : + dependentChunk ((List.ofFn width,bits.take (∑ j,width j)),i.val)= + dependentChunk ((List.ofFn width,bits),i.val) := by + have hw : (List.ofFn width).getD i.val 0=width i := by + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some,Fin.eta] + have hb := prefix_sum_add_width_le width i + dsimp only [dependentChunk,chunkStart] + rw [hw,List.drop_take,List.take_take,min_eq_left (by omega)] + +end ContingencyTables.DensePrograms + +namespace ContingencyTables.CompanionRestartProgram +open CommonBasesFPRAS FirstSuccess DensePrograms FiniteObservableTransport +open scoped BigOperators Classical + +lemma stageWord_take_sum (base : List Stage×List ℕ) (bits : List Bool) + (i : Fin base.1.length) : + stageWord ((base,bits.take (∑ j : Fin base.1.length,widthAt base j.val)),i.val)= + stageWord ((base,bits),i.val) := by + unfold stageWord + rw [widths_ofFn,widths_ofFn] + exact dependentChunk_take_sum (fun i : Fin base.1.length => widthAt base i.val) bits i + +private lemma foldl_eq_on {A B : Type*} (f g : B → A → B) (xs : List A) + (h : ∀ a,a ∈ xs → ∀ b,f b a=g b a) (b : B) : xs.foldl f b=xs.foldl g b := by + induction xs generalizing b with + | nil => rfl + | cons a xs ih => + simp only [List.foldl_cons] + rw [h a (by simp) b] + exact ih (fun a ha b => h a (by simp [ha]) b) _ + +theorem output_take_sum (base : List Stage×List ℕ) (bits : List Bool) : + output (base,bits.take (∑ i : Fin base.1.length,widthAt base i.val))= + output (base,bits) := by + unfold output + rw [walk_eq,walk_eq] + change (List.range base.1.length).foldl + (fun code i => next (i,((base,bits.take (∑ j : Fin base.1.length,widthAt base j.val)),code))) base.2= + (List.range base.1.length).foldl (fun code i => next (i,((base,bits),code))) base.2 + apply foldl_eq_on + intro i hi code + have hlt : i < base.1.length := List.mem_range.mp hi + rw [next_detached,next_detached,stageWord_take_sum base bits ⟨i,hlt⟩] + +end ContingencyTables.CompanionRestartProgram + +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS FairBits +open scoped Classical +noncomputable section + +theorem SameLaw.append_unused {Y Z : Type*} [Fintype Y] {n : ℕ} + {f : (Fin n → Bool) → Z} {g : Y → Z} (h : SameLaw f g) (t : ℕ) : + SameLaw (fun bits : Fin (n+t) → Bool => f (splitWordEquiv n t bits).1) g := by + intro phi + have he := uniformAverage_equiv (splitWordEquiv n t) + (fun p : (Fin n → Bool)×(Fin t → Bool) => phi (f p.1)) + refine he.trans ?_ + rw [uniformAverage_prod] + simp only [uniformAverage_const] + exact h phi + +theorem restart_append_sameLaw {Y : Type*} [Fintype Y] + (base : List CompanionRestartProgram.Stage×List ℕ) (n : ℕ) + (hn : (∑ i : Fin base.1.length,CompanionRestartProgram.widthAt base i.val)=n) + (g : Y → List ℕ) + (h : SameLaw (fun bits : Fin n → Bool => + CompanionRestartProgram.output (base,List.ofFn bits)) g) (t : ℕ) : + SameLaw (fun bits : Fin (n+t) → Bool => + CompanionRestartProgram.output (base,List.ofFn bits)) g := by + have hp := h.append_unused t + have he (bits : Fin (n+t) → Bool) : + CompanionRestartProgram.output (base,List.ofFn bits)= + CompanionRestartProgram.output (base,List.ofFn (splitWordEquiv n t bits).1) := by + have hs := (CompanionRestartProgram.output_take_sum base (List.ofFn bits)).symm + rw [hn,DensePrograms.ofFn_split_take] at hs + exact hs + intro phi + simp_rw [he] + exact hp phi + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f39059ce4d2c87bd093ad0687c4e3904896d8d3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartProgram.lean @@ -0,0 +1,172 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartStageProgram +import OAI.Combinatorics.ContingencyTables.Machines.DependentWordProgram + +namespace OAI + +/-! # Executed restart stages with disjoint variable-width words + +The supplied stage list determines the number of iterations. The current +encoded profile is bounded by the original profile length after every stage. +-/ +namespace ContingencyTables.CompanionRestartProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial DensePrograms +open CompanionMultiplierMatrixProgram + +abbrev Stage := CompanionPhaseContextProgram.Input × FractionMatrix +abbrev Input := (List Stage × List ℕ) × List Bool +abbrev State := Input × List ℕ + +def request (z : Input × ℕ) : CompanionRestartStageProgram.Request := + (z.1.1.1.getD z.2 default,z.1.1.2) +def requestRealizer : Realizer request := + pair (composition (f := fun z : Input×ℕ => (z.1.1.1,z.2)) + (g := fun p : List Stage×ℕ => p.1.getD p.2 default) + (pair (composition (composition first first) first) second) (getDFast default)) + (composition (composition first first) second) +lemma polynomial_request : PolynomialTime requestRealizer := + polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) (polynomial_getDFast default)) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + +def indices (z : Input) : List ℕ := List.range z.1.1.length +def indicesRealizer : Realizer indices := + composition (composition (composition first first) listLength) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +def indexedWidth (z : Input×ℕ) : ℕ := CompanionRestartStageProgram.width (request z) +def indexedWidthRealizer : Realizer indexedWidth := + composition (f := request) (g := CompanionRestartStageProgram.width) + requestRealizer CompanionRestartStageProgram.widthRealizer +lemma polynomial_indexedWidth : PolynomialTime indexedWidthRealizer := + polynomial_composition polynomial_request CompanionRestartStageProgram.polynomial_width + +def widths (z : Input) : List ℕ := (indices z).map (fun i => indexedWidth (z,i)) +def widthsRealizer : Realizer widths := + composition (pair identity indicesRealizer) (mapWith indexedWidthRealizer) +lemma polynomial_widths : PolynomialTime widthsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_indexedWidth) + +def stageWord (z : Input×ℕ) : List Bool := dependentChunk ((widths z.1,z.1.2),z.2) +def stageWordRealizer : Realizer stageWord := + composition (f := fun z : Input×ℕ => ((widths z.1,z.1.2),z.2)) + (g := dependentChunk) + (pair (pair (composition (f := fun z : Input×ℕ => z.1) (g := widths) first widthsRealizer) + (composition first second)) second) dependentChunkRealizer +lemma polynomial_stageWord : PolynomialTime stageWordRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_widths) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second) + polynomial_dependentChunk + +def stageInput (z : ℕ×State) : CompanionRestartStageProgram.Input := + ((z.2.1.1.1.getD z.1 default,z.2.2),stageWord (z.2.1,z.1)) +def stageInputRealizer : Realizer stageInput := by + let selected : Realizer (fun z : ℕ×State => z.2.1.1.1.getD z.1 (default : Stage)) := + composition (f := fun z : ℕ×State => (z.2.1.1.1,z.1)) + (g := fun p : List Stage×ℕ => p.1.getD p.2 default) + (pair (composition (composition (composition second first) first) first) first) (getDFast default) + exact pair (pair selected (composition second second)) + (composition (f := fun z : ℕ×State => (z.2.1,z.1)) (g := stageWord) + (pair (composition second first) first) stageWordRealizer) +lemma polynomial_stageInput : PolynomialTime stageInputRealizer := by + unfold stageInputRealizer + apply polynomial_pair + · apply polynomial_pair + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_second polynomial_first) polynomial_first) polynomial_first) + polynomial_first) (polynomial_getDFast default) + · exact polynomial_composition polynomial_second polynomial_second + · exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) polynomial_first) polynomial_stageWord + +def candidate (z : ℕ×State) : List ℕ := CompanionRestartStageProgram.output (stageInput z) +def candidateRealizer : Realizer candidate := + composition (f := stageInput) (g := CompanionRestartStageProgram.output) + stageInputRealizer CompanionRestartStageProgram.outputRealizer +lemma polynomial_candidate : PolynomialTime candidateRealizer := + polynomial_composition polynomial_stageInput CompanionRestartStageProgram.polynomial_output + +def bound (z : ℕ×State) : ℕ := z.2.1.1.2.length +def boundRealizer : Realizer bound := + composition (composition (composition (composition second first) first) second) listLength +lemma polynomial_bound : PolynomialTime boundRealizer := + polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_second polynomial_first) polynomial_first) polynomial_second) + polynomial_listLength + +attribute [local irreducible] candidate + +def next (z : ℕ×State) : List ℕ := ProfilePrograms.capView ((bound z,1),candidate z) +def nextRealizer : Realizer next := + composition (f := fun z : ℕ×State => ((bound z,1),candidate z)) (g := ProfilePrograms.capView) + (pair (pair boundRealizer (constant 1)) candidateRealizer) ProfilePrograms.capViewRealizer +lemma polynomial_next : PolynomialTime nextRealizer := + polynomial_composition (polynomial_pair (polynomial_pair polynomial_bound (polynomial_constant 1)) + polynomial_candidate) ProfilePrograms.polynomial_capView + +def advance (z : ℕ×State) : State := (z.2.1,next z) +def advanceRealizer : Realizer advance := pair (composition second first) nextRealizer +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) polynomial_next + +lemma advance_weight (i : ℕ) (state : State) (S : ℕ) (hs : weight state.1 ≤ S) : + weight (advance (i,state)) ≤ 10*(S+1) := by + have hb : state.1.1.2.length ≤ S := (list_length_le_weight _).trans + ((weight_snd state.1.1).trans ((weight_fst state.1).trans hs)) + have hn := ProfilePrograms.capView_weight state.1.1.2.length 1 (candidate (i,state)) + change weight (next (i,state)) ≤ _ at hn + norm_num only [Nat.size_one] at hn + change weight (state.1,next (i,state)) ≤ _ + rw [weight_prod] + omega + +def walk (z : State×List ℕ) : State := z.2.foldl (fun state i => advance (i,state)) z.1 +def walkRealizer : Realizer walk := composition (pair second first) (fold advanceRealizer) + +lemma fold_fixed (is : List ℕ) (state : State) : + (is.foldl (fun state i => advance (i,state)) state).1=state.1 := by + induction is generalizing state with + | nil => rfl + | cons i is ih => exact ih _ + +lemma fold_weight (is : List ℕ) (state : State) (S : ℕ) (hs : weight state ≤ S) : + weight (is.foldl (fun state i => advance (i,state)) state) ≤ 10*(S+1) := by + induction is using List.reverseRecOn with + | nil => simpa using hs.trans (by omega : S ≤ 10*(S+1)) + | append_singleton is i _ => + rw [List.foldl_append] + simp only [List.foldl_cons,List.foldl_nil] + apply advance_weight + rw [fold_fixed] + exact (weight_fst state).trans hs + +theorem polynomial_walk : PolynomialTime walkRealizer := by + apply polynomial_composition (polynomial_pair polynomial_second polynomial_first) + apply polynomial_fold polynomial_advance (10*(X+1)) + intro is state pre post _ + simp only [eval_mul,eval_ofNat,eval_add,eval_X,eval_one] + exact fold_weight pre state (weight (is,state)) (weight_snd (is,state)) + +def output (z : Input) : List ℕ := (walk ((z,z.1.2),indices z)).2 +def outputRealizer : Realizer output := + composition (f := fun z : Input => ((z,z.1.2),indices z)) + (g := fun z : State×List ℕ => (walk z).2) + (pair (pair identity (composition first second)) indicesRealizer) + (composition (f := walk) (g := Prod.snd) walkRealizer second) +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_second)) polynomial_indices) + (polynomial_composition polynomial_walk polynomial_second) + +end ContingencyTables.CompanionRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSchedule.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ce3a00902edcfe8f86949037974808a64ecb6c0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSchedule.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartProgram + +namespace OAI + +/-! # A deterministic bit allocation for initialized restart experiments -/ +namespace ContingencyTables.CompanionRestartSchedule +open MatchingFPRAS MatchingFPRAS.TreeTyped ScalarScheduleProgram DensePrograms Polynomial + +abbrev Prepared := CompanionPhaseContextProgram.Prepared +abbrev StageInput := Prepared×ℕ +abbrev Input := Prepared×List CompanionPhaseFinishProgram.Stored + +def configInput (z : StageInput) : RootedOracleConfigProgram.Input := + CompanionPhaseContextProgram.configInput ((z.1,z.2+1),[]) +def configInputRealizer : Realizer configInput := + composition (f := fun z : StageInput => ((z.1,z.2+1),([] : List Bool))) + (g := CompanionPhaseContextProgram.configInput) + (pair (pair first (composition second successor)) (constant [])) + CompanionPhaseContextProgram.configInputRealizer +lemma polynomial_configInput : PolynomialTime configInputRealizer := + polynomial_composition (polynomial_pair (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_successor)) (polynomial_constant [])) + CompanionPhaseContextProgram.polynomial_configInput + +def queryWidth (z : StageInput) : ℕ := RootedOracleConfigProgram.wordWidth (configInput z) +def queryWidthRealizer : Realizer queryWidth := + composition (f := configInput) (g := RootedOracleConfigProgram.wordWidth) + configInputRealizer RootedOracleConfigProgram.wordWidthRealizer +lemma polynomial_queryWidth : PolynomialTime queryWidthRealizer := + polynomial_composition polynomial_configInput RootedOracleConfigProgram.polynomial_wordWidth + +def scalar (e : Expr) (z : StageInput) : ℕ := CountingPhaseParametersProgram.scalar e z.1.2 +def scalarRealizer (e : Expr) : Realizer (scalar e) := + composition (f := fun z : StageInput => z.1.2) (g := CountingPhaseParametersProgram.scalar e) + (composition first second) (CountingPhaseParametersProgram.scalarRealizer e) +lemma polynomial_scalar (e : Expr) : PolynomialTime (scalarRealizer e) := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) + (CountingPhaseParametersProgram.polynomial_scalar e) + +def proposalWidth (z : StageInput) : ℕ := Nat.clog 2 (scalar (.input 0) z*scalar (.input 0) z) +def proposalWidthRealizer : Realizer proposalWidth := + composition (f := fun z : StageInput => scalar (.input 0) z*scalar (.input 0) z) + (g := Nat.clog 2) + (composition (f := fun z : StageInput => (scalar (.input 0) z,scalar (.input 0) z)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair (scalarRealizer (.input 0)) (scalarRealizer (.input 0))) multiply) + ceilLogTwoRealizer +lemma polynomial_proposalWidth : PolynomialTime proposalWidthRealizer := + polynomial_composition (polynomial_composition (polynomial_pair (polynomial_scalar _) (polynomial_scalar _)) + polynomial_multiply) polynomial_ceilLogTwo + +def precision (z : StageInput) : ℕ := CountingPhaseParametersProgram.precision z.1.2 +def precisionRealizer : Realizer precision := + composition (f := fun z : StageInput => z.1.2) (g := CountingPhaseParametersProgram.precision) + (composition first second) CountingPhaseParametersProgram.precisionRealizer +lemma polynomial_precision : PolynomialTime precisionRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) + CountingPhaseParametersProgram.polynomial_precision + + private def consR {f : StageInput→ℕ} {g : StageInput→List ℕ} + (F : Realizer f) (G : Realizer g) : Realizer (fun z => f z::g z) := + composition (f := fun z : StageInput => (f z,g z)) + (g := fun p : ℕ×List ℕ => p.1::p.2) (pair F G) listCons + private lemma polynomial_consR {f : StageInput→ℕ} {g : StageInput→List ℕ} + (F : Realizer f) (G : Realizer g) (hF : PolynomialTime F) (hG : PolynomialTime G) : + PolynomialTime (consR F G) := polynomial_composition (polynomial_pair hF hG) polynomial_listCons + +def fields (z : StageInput) : List ℕ := + [proposalWidth z,queryWidth z,precision z,scalar (.input 3) z,scalar (.input 5) z] +def fieldsRealizer : Realizer fields := + consR proposalWidthRealizer (consR queryWidthRealizer (consR precisionRealizer + (consR (scalarRealizer (.input 3)) (consR (scalarRealizer (.input 5)) (constant []))))) +lemma polynomial_fields : PolynomialTime fieldsRealizer := by + unfold fieldsRealizer + exact polynomial_consR _ _ polynomial_proposalWidth (polynomial_consR _ _ polynomial_queryWidth + (polynomial_consR _ _ polynomial_precision (polynomial_consR _ _ (polynomial_scalar _) + (polynomial_consR _ _ (polynomial_scalar _) (polynomial_constant []))))) + +def expression : Expr := (.input 3)*((.input 4+1)*(1+(.input 0+((.input 1+.input 1)+.input 2)))) +def stageWidth (z : StageInput) : ℕ := expression.eval (fields z) +def stageWidthRealizer : Realizer stageWidth := + composition (f := fields) (g := expression.eval) fieldsRealizer expression.realizer +theorem polynomial_stageWidth : PolynomialTime stageWidthRealizer := + polynomial_composition polynomial_fields expression.polynomial + +def indices (z : Input) : List ℕ := List.range z.2.length +def indicesRealizer : Realizer indices := composition (composition second listLength) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_second polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using (list_length_le_weight z.2).trans (weight_snd z) + +def indexedWidth (z : Input×ℕ) : ℕ := stageWidth (z.1.1,z.2) +def indexedWidthRealizer : Realizer indexedWidth := + composition (f := fun z : Input×ℕ => (z.1.1,z.2)) (g := stageWidth) + (pair (composition first first) second) stageWidthRealizer +lemma polynomial_indexedWidth : PolynomialTime indexedWidthRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_stageWidth + +def restartWidth (z : Input) : ℕ := ((indices z).map (fun i => indexedWidth (z,i))).sum +def restartWidthRealizer : Realizer restartWidth := + composition (f := fun z : Input => (indices z).map (fun i => indexedWidth (z,i))) + (g := List.sum) (composition (pair identity indicesRealizer) (mapWith indexedWidthRealizer)) listSum +theorem polynomial_restartWidth : PolynomialTime restartWidthRealizer := + polynomial_composition (polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_indexedWidth)) polynomial_listSum + +def width (z : Input) : ℕ := CompanionRestartInitializer.width z.1+restartWidth z +def widthRealizer : Realizer width := + composition (f := fun z : Input => (CompanionRestartInitializer.width z.1,restartWidth z)) + (g := fun p : ℕ×ℕ => p.1+p.2) + (pair (composition (f := fun z : Input => z.1) (g := CompanionRestartInitializer.width) + first CompanionRestartInitializer.widthRealizer) restartWidthRealizer) add +theorem polynomial_width : PolynomialTime widthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first CompanionRestartInitializer.polynomial_width) + polynomial_restartWidth) polynomial_add + +end ContingencyTables.CompanionRestartSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartScheduleSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartScheduleSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..0530a61bf83659957f578f508f2ccaf9ad5ee1ff --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartScheduleSemantics.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSchedule +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartDataLaw + +namespace OAI + +/-! # Exact deterministic restart budgets for the source experiment -/ +namespace ContingencyTables.CompanionRestartSchedule +open MatchingFPRAS CompanionFactorialApplication CompanionOracleDensity +open CompanionComputedInitial GridBoundary FirstSuccess +open scoped BigOperators Classical +noncomputable section +variable {m n : ℕ} + +lemma configInput_data (A : Instance (Fin m) (Fin n)) (C K H T N R L i : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + configInput (CompanionRestartInitializer.data A C K H T N R L epsilon z v,i)= + RootedOracleConfigProgram.data A C K (i+1) + (CountingPhaseParametersProgram.noise ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon)) z v [] := rfl + +lemma queryWidth_data (A : Instance (Fin m) (Fin n)) (C K H T N R L i : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + queryWidth (CompanionRestartInitializer.data A C K H T N R L epsilon z v,i)= + CompanionOracleDensity.medianEstimatorBits A C K (i+1) + (TreeFraction.val (CountingPhaseParametersProgram.noise ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon))) + (TreeFraction.val (CountingPhaseParametersProgram.noise ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon))) := by + rw [queryWidth,configInput_data,RootedOracleConfigProgram.wordWidth_data] + +lemma proposalWidth_data (A : Instance (Fin m) (Fin n)) (C K H T N R L i : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + proposalWidth (CompanionRestartInitializer.data A C K H T N R L epsilon z v,i)= + CompanionBooleanPhase.proposalBits A := by + simp only [proposalWidth,scalar,CompanionRestartInitializer.data, + CountingPhaseParametersProgram.scalar,ScalarScheduleProgram.Expr.eval, + List.getD_cons_zero,CompanionBooleanPhase.proposalBits,pow_two] + +theorem stageWidth_data (A : Instance (Fin m) (Fin n)) (C K H T N R L i : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) : + stageWidth (CompanionRestartInitializer.data A C K H T N R L epsilon z v,i)= + CompanionRestartProgram.sourceWidth A C K + ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon) i := by + unfold stageWidth + change T*((R+1)*(1+(proposalWidth (CompanionRestartInitializer.data A C K H T N R L epsilon z v,i)+ + ((queryWidth (CompanionRestartInitializer.data A C K H T N R L epsilon z v,i)+ + queryWidth (CompanionRestartInitializer.data A C K H T N R L epsilon z v,i))+ + CountingPhaseParametersProgram.precision ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon)))))=_ + rw [proposalWidth_data,queryWidth_data] + rfl + +theorem restartWidth_data (A : Instance (Fin m) (Fin n)) (C K H T N R L : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (history : List CompanionPhaseFinishProgram.Stored) : + restartWidth (CompanionRestartInitializer.data A C K H T N R L epsilon z v,history)= + ∑ i : Fin history.length,CompanionRestartProgram.sourceWidth A C K + ([Fintype.card (Labels A),A.W,H,T,N,R,L],epsilon) i.val := by + unfold restartWidth indices + rw [DirectedBFSCode.range_eq_map] + simp only [List.map_map,Function.comp_def] + rw [←List.ofFn_eq_map,List.sum_ofFn] + apply Finset.sum_congr rfl + intro i _ + exact stageWidth_data A C K H T N R L i.val epsilon z v + +lemma initialWidths_eq (A : Instance (Fin m) (Fin n)) (B : ℕ) : + CompanionComputedInitial.wordLength A B=CompanionInitialDraw.initialBits A B := by + unfold CompanionComputedInitial.wordLength CompanionInitialDraw.initialBits InitialFactorialBits.bitCount + calc + _ = ∑ s : SmallCell A,FixedCardinalityMixture.drawBits B (A.b s.val.1 s.val.2) := + Fintype.sum_equiv (CompanionComputedInitial.cellOrder A).symm _ _ (fun _ => rfl) + _ = _ := (Fintype.sum_equiv (CompanionInitialDraw.cellEnum A).symm _ _ (fun _ => rfl)).symm + + /-- The physical width is exactly the initialized source-stage width, + and depends on a history only through its length. -/ +theorem width_data (A : Instance (Fin m) (Fin n)) (C K H N R L : ℕ) + (epsilon : TreeFraction.Fraction) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (history : List CompanionPhaseFinishProgram.Stored) : + width (CompanionRestartInitializer.data A C K H (CompanionTargetMixing.restartTime A H L) N R L + epsilon z v,history)= + RootedRestartWords.initialStageBits A C K H L + (CountingPhaseParametersProgram.precision + ([Fintype.card (Labels A),A.W,H,CompanionTargetMixing.restartTime A H L,N,R,L],epsilon)) + R (CountingPhaseSchedule.initialPrecision H) history.length + (TreeFraction.val (CountingPhaseParametersProgram.noise + ([Fintype.card (Labels A),A.W,H,CompanionTargetMixing.restartTime A H L,N,R,L],epsilon))) := by + rw [width,CompanionRestartInitializer.width_data,restartWidth_data,initialWidths_eq] + rfl + +end +end ContingencyTables.CompanionRestartSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4582f394a11a543496bda240c8eb068efb3918e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSemantics.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartProgram +import OAI.Combinatorics.ContingencyTables.Machines.FiniteVaryingObservable + +namespace OAI + +/-! # Exact disjoint-word semantics of the physical restart loop -/ +namespace ContingencyTables.CompanionRestartProgram +open FirstSuccess FiniteObservableTransport MatchingFPRAS DensePrograms CommonBasesFPRAS +open scoped BigOperators Classical + +def widthAt (base : List Stage×List ℕ) (i : ℕ) : ℕ := indexedWidth ((base,[]),i) + +lemma widths_ofFn (base : List Stage×List ℕ) (bits : List Bool) : + widths (base,bits)=List.ofFn (fun i : Fin base.1.length => widthAt base i.val) := by + unfold widths indices + rw [DirectedBFSCode.range_eq_map] + simp only [List.map_map,Function.comp_def] + change (List.finRange base.1.length).map (fun i => widthAt base i.val)=_ + exact List.ofFn_eq_map.symm + +lemma stageWord_ofFn (base : List Stage×List ℕ) + (bits : Fin (∑ i : Fin base.1.length,widthAt base i.val) → Bool) + (i : Fin base.1.length) : + stageWord ((base,List.ofFn bits),i.val)= + List.ofFn (varyingWordEquiv (widthAt base) base.1.length bits i) := by + unfold stageWord + rw [widths_ofFn] + exact dependentChunk_ofFn (fun i : Fin base.1.length => widthAt base i.val) bits i + +def detachedStep (base : List Stage×List ℕ) (i : ℕ) (code : List ℕ) + (bits : List Bool) : List ℕ := + ProfilePrograms.capView ((base.2.length,1), + CompanionRestartStageProgram.output ((base.1.getD i default,code),bits)) + +lemma next_detached (base : List Stage×List ℕ) (allBits : List Bool) (i : ℕ) (code : List ℕ) : + next (i,((base,allBits),code))= + detachedStep base i code (stageWord ((base,allBits),i)) := rfl + +lemma walk_eq (input : Input) (is : List ℕ) (code : List ℕ) : + walk ((input,code),is)= + (input,is.foldl (fun code i => next (i,(input,code))) code) := by + induction is generalizing code with + | nil => rfl + | cons i is ih => + simpa only [walk,List.foldl_cons,advance] using ih (next (i,(input,code))) + + private lemma fold_range_varying {C : Type*} (width : ℕ → ℕ) + (F : ℕ → C → C) (G : (i : ℕ) → C → (Fin (width i) → Bool) → C) + (c : C) (N : ℕ) (words : VaryingWords width N) + (h : ∀ i : Fin N,∀ c,F i.val c=G i.val c (words i)) : + (List.range N).foldl (fun c i => F i c) c=varyingWalk width G c N words := by + induction N with + | zero => rfl + | succ N ih => + rw [List.range_succ,List.foldl_append] + simp only [List.foldl_cons,List.foldl_nil,varyingWalk] + have hp := ih (Fin.init words) (fun i c => h i.castSucc c) + rw [hp] + exact h (Fin.last N) _ + +/-- The bounded list program consumes exactly its independent stage +blocks. No assumption about the encoded states is needed here. -/ +theorem output_varyingWalk (base : List Stage×List ℕ) + (bits : Fin (∑ i : Fin base.1.length,widthAt base i.val) → Bool) : + output (base,List.ofFn bits)= + varyingWalk (widthAt base) + (fun i code word => detachedStep base i code (List.ofFn word)) + base.2 base.1.length (varyingWordEquiv (widthAt base) base.1.length bits) := by + unfold output + rw [walk_eq] + change (List.range base.1.length).foldl + (fun code i => next (i,((base,List.ofFn bits),code))) base.2=_ + apply fold_range_varying + intro i code + rw [next_detached,stageWord_ofFn] + +noncomputable section + +/-- Conditional laws compose across the actual disjoint variable-width +blocks, even when the source and encoded state spaces have different sizes. -/ +theorem output_sameLaw {Z : Type*} (base : List Stage×List ℕ) (v : ℕ → ℕ) + (G : (i : ℕ) → Z → (Fin (v i) → Bool) → Z) (e : Z → List ℕ) + (z : Z) (hz : base.2=e z) + (h : ∀ i,i < base.1.length → ∀ s,SameLaw + (fun bits : Fin (widthAt base i) → Bool => detachedStep base i (e s) (List.ofFn bits)) + (fun bits => e (G i s bits))) : + SameLaw (fun bits : Fin (∑ i : Fin base.1.length,widthAt base i.val) → Bool => + output (base,List.ofFn bits)) + (fun bits : Fin (∑ i : Fin base.1.length,v i.val) → Bool => + e (varyingWalk v G z base.1.length (varyingWordEquiv v base.1.length bits))) := by + let F := fun (i : ℕ) (code : List ℕ) (bits : Fin (widthAt base i) → Bool) => + detachedStep base i code (List.ofFn bits) + have hh := varyingWalk_sameLaw_prefix (widthAt base) v F G e z base.1.length h + intro phi + have hu := uniformAverage_equiv (varyingWordEquiv (widthAt base) base.1.length) + (fun words => phi (varyingWalk (widthAt base) F (e z) base.1.length words)) + have hv := uniformAverage_equiv (varyingWordEquiv v base.1.length) + (fun words => phi (e (varyingWalk v G z base.1.length words))) + calc + _ = uniformAverage (fun bits => phi (varyingWalk (widthAt base) F (e z) base.1.length + (varyingWordEquiv (widthAt base) base.1.length bits))) := by + apply congrArg uniformAverage + funext bits + dsimp only + rw [output_varyingWalk,hz] + _ = uniformAverage (fun words => phi (varyingWalk (widthAt base) F (e z) base.1.length words)) := hu + _ = uniformAverage (fun words => phi (e (varyingWalk v G z base.1.length words))) := hh phi + _ = _ := hv.symm + +end +end ContingencyTables.CompanionRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartStageLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartStageLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..a53ab58c1cf803bc82415a9e83e3bcad34b6cfbc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartStageLaw.lean @@ -0,0 +1,157 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartStageProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRepeatedReturnLaw + +namespace OAI + +/-! # The computed restart stage is the literal finite-word return law -/ +namespace ContingencyTables.CompanionRestartStageProgram +open MatchingFPRAS CommonBasesFPRAS CompanionFactorialApplication +open CompanionOracleDensity CompanionWeightOracle CompanionComputedInitial +open CompanionComputedProposal CompanionArithmeticProposal CompanionMultiplierMatrixProgram +open CompanionEvaluatedWeightProgram +open FiniteObservableTransport TwoLiftStates GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def oracleData (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : + RootedOracleConfigProgram.Input := + RootedOracleConfigProgram.data A C K j (CountingPhaseParametersProgram.noise parameters) + z v (List.replicate reserve.length false) + +def degree (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : List Bool := + (List.replicate reserve.length false).take + (RootedOracleConfigProgram.rootDegree (oracleData A C K j parameters z v reserve)) + +def depth (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) : List Bool := + (List.replicate reserve.length false).take + (RootedOracleConfigProgram.depth (oracleData A C K j parameters z v reserve)) + +def data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) : Request := + ((CompanionPhaseContextProgram.data A C K j parameters z v reserve,matrixCode w), + encodeSet (coordinateOrder A) S) + +lemma config_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) : + CompanionPhaseContextProgram.config (context (data A C K j parameters z v reserve w S))= + RootedLabelWeightProgram.config A C K j + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) z v + (degree A C K j parameters z v reserve) (depth A C K j parameters z v reserve) := by + unfold context data + rw [CompanionPhaseContextProgram.config_data,RootedOracleConfigProgram.output_data] + rfl + +lemma fixed_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) : + fixed (data A C K j parameters z v reserve w S)= + CompanionRepeatedReturnProgram.fixedData A C K j + (CountingPhaseParametersProgram.precision parameters) + (CountingPhaseParametersProgram.scalar (.input 5) parameters) + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) z v + (degree A C K j parameters z v reserve) (depth A C K j parameters z v reserve) w S := by + unfold fixed frame + rw [config_data] + rfl + +lemma prepare_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) + (bits : List Bool) : + prepare (data A C K j parameters z v reserve w S,bits)= + CompanionRepeatedReturnProgram.data A C K j + (CountingPhaseParametersProgram.precision parameters) + (CountingPhaseParametersProgram.scalar (.input 5) parameters) + (CountingPhaseParametersProgram.scalar (.input 3) parameters) + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) z v + (degree A C K j parameters z v reserve) (depth A C K j parameters z v reserve) w S bits := by + unfold prepare + rw [fixed_data] + rfl + +theorem width_data (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (parameters : CountingPhaseParametersProgram.Input) (z : View A → ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (reserve : List Bool) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) (S : Set (Labels A×Bool)) : + width (data A C K j parameters z v reserve w S)= + CountingPhaseParametersProgram.scalar (.input 3) parameters* + ((CountingPhaseParametersProgram.scalar (.input 5) parameters+1)* + CompanionBooleanPhase.stepBits A C K j (CountingPhaseParametersProgram.precision parameters) + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters))) := by + unfold width + rw [fixed_data,CompanionRepeatedReturnProgram.blockWidth_data] + rfl + +theorem output_sameLaw (A : Instance (Fin m) (Fin n)) (C K j : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (parameters : CountingPhaseParametersProgram.Input) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (reserve : List Bool) + (hdegree : RootedOracleConfigProgram.rootDegree (oracleData A C K j parameters z v reserve) ≤ reserve.length) + (hdepth : RootedOracleConfigProgram.depth (oracleData A C K j parameters z v reserve) ≤ reserve.length) + (w : LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A))) : + let k := CountingPhaseParametersProgram.precision parameters + let cap := CountingPhaseParametersProgram.scalar (.input 5) parameters + let t := CountingPhaseParametersProgram.scalar (.input 3) parameters + let xi := TreeFraction.val (CountingPhaseParametersProgram.noise parameters) + SameLaw (fun bits : Fin (t*((cap+1)*CompanionBooleanPhase.stepBits A C K j k xi)) → Bool => + output (data A C K j parameters z v reserve w S.val.val,List.ofFn bits)) + (fun bits => encodeSet (coordinateOrder A) + (RootedReturnWords.booleanReturns A (RootedCompletion.rowColumn A.T) C K j k cap t hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (CompanionEvaluatedWeightProgram.sourceWeights A w) S bits).val.val) := by + dsimp only + have hd : (degree A C K j parameters z v reserve).length= + PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)/2) j)) := by + rw [degree,List.length_take,List.length_replicate,min_eq_left hdegree] + exact RootedOracleConfigProgram.rootDegree_data A C K j _ z v _ + have ht : (depth A C K j parameters z v reserve).length= + PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)/2) j)) := by + rw [depth,List.length_take,List.length_replicate,min_eq_left hdepth] + exact RootedOracleConfigProgram.depth_data A C K j _ z v _ + have h := CompanionRepeatedReturnProgram.output_sameLaw A C K j + (CountingPhaseParametersProgram.precision parameters) + (CountingPhaseParametersProgram.scalar (.input 5) parameters) + (CountingPhaseParametersProgram.scalar (.input 3) parameters) + hC hj hK hW hB (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) hxi + z v (degree A C K j parameters z v reserve) (depth A C K j parameters z v reserve) hd ht w S + intro phi + have he : (fun bits : Fin ((CountingPhaseParametersProgram.scalar (.input 3) parameters)* + ((CountingPhaseParametersProgram.scalar (.input 5) parameters+1)* + CompanionBooleanPhase.stepBits A C K j (CountingPhaseParametersProgram.precision parameters) + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)))) → Bool => output (data A C K j parameters z v reserve w S.val.val,List.ofFn bits))= + (fun bits => CompanionRepeatedReturnProgram.output (CompanionRepeatedReturnProgram.data A C K j + (CountingPhaseParametersProgram.precision parameters) + (CountingPhaseParametersProgram.scalar (.input 5) parameters) + (CountingPhaseParametersProgram.scalar (.input 3) parameters) + (TreeFraction.val (CountingPhaseParametersProgram.noise parameters)) z v + (degree A C K j parameters z v reserve) (depth A C K j parameters z v reserve) w S.val.val + (List.ofFn bits))) := by + funext bits + unfold output + rw [prepare_data] + rw [he] + exact h phi + +end +end ContingencyTables.CompanionRestartStageProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartStageProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartStageProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c44b1a1cba35d05ff94e3d40f87e5533b4c7f76d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartStageProgram.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRepeatedReturnProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseContextProgram + +namespace OAI + +/-! # One executed warm-restart stage + +The context supplies the phase, immutable oracle metadata and deterministic +precision markers. The matrix is the stored multiplier for that phase. +-/ +namespace ContingencyTables.CompanionRestartStageProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped +open CompanionMultiplierMatrixProgram + +abbrev Request := (CompanionPhaseContextProgram.Input × FractionMatrix) × List ℕ +abbrev Input := Request × List Bool + +def context (z : Request) : CompanionPhaseContextProgram.Input := z.1.1 +def contextRealizer : Realizer context := composition first first +lemma polynomial_context : PolynomialTime contextRealizer := + polynomial_composition polynomial_first polynomial_first + +def frame (z : Request) : CompanionMetropolisProgram.Frame × ℕ := + ((CompanionPhaseContextProgram.config (context z),z.1.2), + CompanionPhaseContextProgram.precision (context z)) +def frameRealizer : Realizer frame := + pair (pair + (composition (f := context) (g := CompanionPhaseContextProgram.config) + contextRealizer CompanionPhaseContextProgram.configRealizer) + (composition first second)) + (composition (f := context) (g := CompanionPhaseContextProgram.precision) + contextRealizer CompanionPhaseContextProgram.precisionRealizer) +lemma polynomial_frame : PolynomialTime frameRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition polynomial_context CompanionPhaseContextProgram.polynomial_config) + (polynomial_composition polynomial_first polynomial_second)) + (polynomial_composition polynomial_context CompanionPhaseContextProgram.polynomial_precision) + +def cap (z : Request) : ℕ := CompanionPhaseContextProgram.scalar (.input 5) (context z) +def capRealizer : Realizer cap := + composition (f := context) (g := CompanionPhaseContextProgram.scalar (.input 5)) + contextRealizer (CompanionPhaseContextProgram.scalarRealizer (.input 5)) +lemma polynomial_cap : PolynomialTime capRealizer := + polynomial_composition polynomial_context (CompanionPhaseContextProgram.polynomial_scalar _) + +def repetitions (z : Request) : ℕ := CompanionPhaseContextProgram.scalar (.input 3) (context z) +def repetitionsRealizer : Realizer repetitions := + composition (f := context) (g := CompanionPhaseContextProgram.scalar (.input 3)) + contextRealizer (CompanionPhaseContextProgram.scalarRealizer (.input 3)) +lemma polynomial_repetitions : PolynomialTime repetitionsRealizer := + polynomial_composition polynomial_context (CompanionPhaseContextProgram.polynomial_scalar _) + +attribute [local irreducible] frame cap repetitions + +def fixed (z : Request) : CompanionRepeatedReturnProgram.Fixed := ((frame z,z.2),cap z) +def fixedRealizer : Realizer fixed := pair (pair frameRealizer second) capRealizer +lemma polynomial_fixed : PolynomialTime fixedRealizer := + polynomial_pair (polynomial_pair polynomial_frame polynomial_second) polynomial_cap + +def prepare (z : Input) : CompanionRepeatedReturnProgram.Input := + (((fixed z.1,z.1.2),repetitions z.1),z.2) +def prepareRealizer : Realizer prepare := + pair (pair (pair (composition (f := fun z : Input => z.1) (g := fixed) + first fixedRealizer) (composition first second)) + (composition (f := fun z : Input => z.1) (g := repetitions) first repetitionsRealizer)) second +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_fixed) + (polynomial_composition polynomial_first polynomial_second)) + (polynomial_composition polynomial_first polynomial_repetitions)) polynomial_second + +def output (z : Input) : List ℕ := CompanionRepeatedReturnProgram.output (prepare z) +def outputRealizer : Realizer output := + composition (f := prepare) (g := CompanionRepeatedReturnProgram.output) + prepareRealizer CompanionRepeatedReturnProgram.outputRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_prepare CompanionRepeatedReturnProgram.polynomial_output + +def width (z : Request) : ℕ := + repetitions z*CompanionRepeatedReturnProgram.blockWidth (fixed z) +def widthRealizer : Realizer width := + composition (f := fun z : Request => + (repetitions z,CompanionRepeatedReturnProgram.blockWidth (fixed z))) + (g := fun z : ℕ×ℕ => z.1*z.2) + (pair repetitionsRealizer (composition (f := fixed) + (g := CompanionRepeatedReturnProgram.blockWidth) fixedRealizer + CompanionRepeatedReturnProgram.blockWidthRealizer)) multiply +theorem polynomial_width : PolynomialTime widthRealizer := + polynomial_composition (polynomial_pair polynomial_repetitions + (polynomial_composition polynomial_fixed CompanionRepeatedReturnProgram.polynomial_blockWidth)) + polynomial_multiply + +end ContingencyTables.CompanionRestartStageProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSupport.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSupport.lean new file mode 100644 index 0000000000000000000000000000000000000000..85da87d2368a675f4075150aee99e198df2eec30 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionRestartSupport.lean @@ -0,0 +1,89 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartLaw +import OAI.Combinatorics.ContingencyTables.Transport.FiniteSameLawSupport +import OAI.Combinatorics.ContingencyTables.Counting.CompanionStoredRepresentation + +namespace OAI + +/-! # Every executed restart has the canonical paired catalog + +Finite uniform words have positive mass individually. The proved padded +restart law therefore gives a valid encoded source state on every word, +including words on which one of the return attempts uses its fallback. +-/ +namespace ContingencyTables.CompanionInitializedRestartProgram +open MatchingFPRAS CommonBasesFPRAS FiniteObservableTransport +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionEvaluatedWeightProgram +open CompanionOracleDensity TwoLiftStates GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma catalog_length_encode (A : Instance (Fin m) (Fin n)) (S : Set (Labels A×Bool)) : + (PairedCatalogProgram.catalog (encodeSet (coordinateOrder A) S)).length= + (CanonicalInitialEncoding.copyOrder (capacities A)).length := by + rw [encodeSet_reindex,PairedCatalogProgram.catalog_encode] + exact List.length_ofFn + +lemma catalog_length_of_supported (A : Instance (Fin m) (Fin n)) (code : List ℕ) + (h : ∃ S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)), + code=encodeSet (coordinateOrder A) S.val.val) : + (PairedCatalogProgram.catalog code).length= + (CanonicalInitialEncoding.copyOrder (capacities A)).length := by + obtain ⟨S,rfl⟩ := h + exact catalog_length_encode A S.val.val + +lemma outer_trial_catalog (z : CompanionOuterPhaseProgram.Input) : + CompanionPhaseTrialProgram.catalogue (CompanionOuterPhaseProgram.trialInput z)= + PairedCatalogProgram.catalog (CompanionOuterPhaseProgram.startCode z) := rfl + +theorem outer_output_rep_of_supported (A : Instance (Fin m) (Fin n)) + (z : CompanionOuterPhaseProgram.Input) + (hinit : CompanionStoredRepresentation.StoredRep + (CanonicalInitialEncoding.copyOrder (capacities A)).length z.1.1.2) + (hh : ∀ s∈z.1.2,CompanionStoredRepresentation.StoredRep + (CanonicalInitialEncoding.copyOrder (capacities A)).length s) + (hs : ∃ S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)), + CompanionOuterPhaseProgram.startCode z=encodeSet (coordinateOrder A) S.val.val) : + CompanionStoredRepresentation.StoredRep + (CanonicalInitialEncoding.copyOrder (capacities A)).length + (CompanionOuterPhaseProgram.output z) := by + apply CompanionStoredRepresentation.outer_output_rep z hinit hh + rw [outer_trial_catalog] + exact catalog_length_of_supported A _ hs + +theorem output_padded_supported (A : Instance (Fin m) (Fin n)) (C K H T N R L j padding : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=CompanionOracleDensity.binWidth A C) + (epsilon : TreeFraction.Fraction) + (hxi : 0 < TreeFraction.val (CountingPhaseParametersProgram.noise (parameters A H T N R L epsilon))) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (w : ℕ → LabelIndex A → LabelIndex A → TreeFraction.Fraction) + (estimates : Fin j → TreeFraction.Fraction) + (hdegree : ∀ i : Fin j,RootedOracleConfigProgram.rootDegree + (CompanionRestartStageProgram.oracleData A C K (i.val+1) (parameters A H T N R L epsilon) z v + (List.replicate (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) false)) ≤ + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) + (hdepth : ∀ i : Fin j,RootedOracleConfigProgram.depth + (CompanionRestartStageProgram.oracleData A C K (i.val+1) (parameters A H T N R L epsilon) z v + (List.replicate (wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) false)) ≤ + wordLength A (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) + (bits : Fin (wordLength A + (CompanionInitialDraw.precision A (CountingPhaseSchedule.initialPrecision H))+ + (CompanionRestartProgram.sumBits A C K j (parameters A H T N R L epsilon)+padding)) → Bool) : + ∃ S : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)), + output (data A C K H T N R L j epsilon z v w estimates (List.ofFn bits))= + encodeSet (coordinateOrder A) S.val.val := by + have hl := output_padded_sameLaw A C K H T N R L j padding + hC hj hK hW hB epsilon hxi z v w estimates hdegree hdepth + obtain ⟨sourceBits,he⟩ := hl.exists_preimage bits + exact ⟨model A C K H T N R L j epsilon hK hW v w sourceBits,he.symm⟩ + +end +end ContingencyTables.CompanionInitializedRestartProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReturnIteration.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReturnIteration.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca1e1ef11ef7d07c09502577dc707446b833b24c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReturnIteration.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionWarmReturn +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTargetMixing +import OAI.Combinatorics.ContingencyTables.Transport.WarmKernelIteration + +namespace OAI + +/-! # Repeated bounded returns to the literal companion law + +Only the exact reference trajectory is required to remain warm. The +actual finite-word return kernel can accumulate its error without any +additional warmness hypothesis on its output. +-/ + +namespace ContingencyTables.CompanionReturnIteration + +open CommonBasesFPRAS RealKernelApproximation CompanionFactorialApplication +open CompanionBooleanPhase CompanionOracleDensity CompanionRationalUpdates +open CompanionWarmReturn CompanionTargetTrace CompanionTargetMixing +open CompanionAnnealing CompanionWarmStart TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +theorem reference_mixing_distance (A : Instance I J) (H L j : ℕ) (hj : j≤H) + (hbox : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1))≤(2:ℝ)^L) + (hp : 0 (w p q:ℝ))) + (nu : PlainIndex (pairs : List (Pair A)) → ℝ) (hnu : ∀ S,0≤nu S) + (hmass : ∑ S,nu S=1) (t : ℕ) : + distance (((CompanionTargetTrace.actualTrace A j hp w hw).kernel.power t).push nu) + (fun S => law A j S.val.val)≤ + (Real.exp (-(t:ℝ)/(2*ObservableBounds.observableConstant + (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/CompanionTrace.minimumMass A H L)/2 := by + let D := CompanionTargetTrace.actualTrace A j hp w hw + have hmix (x y : PlainIndex (pairs : List (Pair A))) : + |(D.kernel.power t).P x y/D.π y-1|≤ + Real.exp (-(t:ℝ)/(2*ObservableBounds.observableConstant + (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/CompanionTrace.minimumMass A H L := by + rw [actualTrace_pi] + exact target_point_mixing A H L j hj hbox hp w hw hgood t x y + have hm := WarmKernelIteration.mixing_distance D nu hnu hmass t _ hmix + have hpi : D.π=(fun S => law A j S.val.val) := by + funext S + exact actualTrace_pi A j hp w hw S + rw [hpi] at hm + exact hm + +theorem repeated_return_distance (A : Instance I J) (C : ℕ) (hC : 0 (w p q:ℝ))) + (hn : 0 by simpa only [actualTrace_pi] using hrwarm S) + exact WarmKernelIteration.power_distance + (CompanionTargetTrace.actualTrace A j hp w hw) + (returnKernel A C K j k n hK hW xi v w) nu hnu hmass U _ hwar hstep t + +/-- The terminal law after repeated actual Boolean returns. The first +term is the accumulated implementation error; the second is mixing of +the exact literal trace. -/ +theorem repeated_return_stationary (A : Instance I J) (C : ℕ) (hC : 0 (w p q:ℝ))) + (hn : 0 law A j S.val.val)≤ + (t:ℝ)*((5*(Fintype.card (Labels A):ℝ)^2*U)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))+ + (Real.exp (-(t:ℝ)/(2*ObservableBounds.observableConstant + (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/CompanionTrace.minimumMass A H L)/2 := by + have hr := repeated_return_distance A C hC K j k n hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw hgood hn nu hnu hmass.le U hU hwarm t + have hm := reference_mixing_distance A H L j hjH hbox hp w hw hgood nu hnu hmass t + have ht := distance_triangle + (((returnKernel A C K j k n hK hW xi v w).power t).push nu) + (((CompanionTargetTrace.actualTrace A j hp w hw).kernel.power t).push nu) + (fun S => law A j S.val.val) + exact ht.trans (_root_.add_le_add hr hm) + +end +end ContingencyTables.CompanionReturnIteration + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReturnWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReturnWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..c139f121eac4f800c6a88f2aa278ba281cb50e57 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionReturnWords.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionReturnIteration +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalk + +namespace OAI + +/-! # A fixed Boolean word for repeated capped returns + +The restart routine iterates the actual defaulted return experiment. +Every iteration receives a disjoint block, and an optional initial +finite-word draw receives its own disjoint block as well. +-/ + +namespace ContingencyTables.CompanionReturnWords + +open CommonBasesFPRAS ResidualMixture FirstSuccess FairBits RealKernelApproximation +open CompanionFactorialApplication CompanionBooleanPhase CompanionOracleDensity +open CompanionCappedReturn CompanionWarmReturn CompanionReturnIteration +open CompanionRationalUpdates CompanionAnnealing TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +private theorem walkLaw_cast_power {X : Type*} [Fintype X] [DecidableEq X] + (Q : X → RationalLaw X) (x : X) (n : ℕ) (y : X) : + ((walkLaw Q x n).mass y:ℝ)=((rationalKernel Q).power n).P x y := by + induction n generalizing y with + | zero => + simp only [walkLaw,pointLaw,FiniteKernel.power,FiniteKernel.identity] + by_cases h : x=y + · subst y; simp + · simp [h,Ne.symm h] + | succ n ih => + change ((∑ z,(walkLaw Q x n).mass z*(Q z).mass y:ℚ):ℝ)=_ + simp only [Rat.cast_sum,Rat.cast_mul,ih, + FiniteKernel.power,FiniteKernel.comp,rationalKernel] + +variable {I J : Type} [Fintype I] [Fintype J] + +def returnBits (A : Instance I J) (C K j k n t : ℕ) (xi : ℚ) : ℕ := + t*((n+1)*stepBits A C K j k xi) + +def booleanReturns (A : Instance I J) (C K j k n t : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) + (bits : Fin (returnBits A C K j k n t xi) → Bool) : + PlainIndex (pairs : List (Pair A)) := + wordWalk (returnWordDefault A C K j k n hK hW xi v w) S t + (gridWordEquiv t ((n+1)*stepBits A C K j k xi) bits) + +def booleanReturnsLaw (A : Instance I J) (C K j k n t : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) : + RationalLaw (PlainIndex (pairs : List (Pair A))) := + mapLaw (uniformLaw (α := Fin (returnBits A C K j k n t xi) → Bool)) + (booleanReturns A C K j k n t hK hW xi v w S) + +theorem booleanReturnsLaw_eq (A : Instance I J) (C K j k n t : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) : + booleanReturnsLaw A C K j k n t hK hW xi v w S= + walkLaw (returnLaw A C K j k n hK hW xi v w) S t := by + let step := returnWordDefault A C K j k n hK hW xi v w + change mapLaw (uniformLaw (α := Fin (t*((n+1)*stepBits A C K j k xi)) → Bool)) + (fun bits => wordWalk step S t + (gridWordEquiv t ((n+1)*stepBits A C K j k xi) bits))=_ + have he := map_equiv (gridWordEquiv t ((n+1)*stepBits A C K j k xi)) + (uniformLaw (α := Fin (t*((n+1)*stepBits A C K j k xi)) → Bool)) + (wordWalk step S t) + rw [uniform_equiv] at he + exact he.symm.trans (wordWalkLaw_eq step S t) + +theorem booleanReturnsLaw_cast (A : Instance I J) (C K j k n t : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S T : PlainIndex (pairs : List (Pair A))) : + ((booleanReturnsLaw A C K j k n t hK hW xi v w S).mass T:ℝ)= + ((returnKernel A C K j k n hK hW xi v w).power t).P S T := by + rw [booleanReturnsLaw_eq] + exact walkLaw_cast_power (returnLaw A C K j k n hK hW xi v w) S t T + +def initializedReturns (A : Instance I J) (C K j k n t r : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (initial : (Fin r → Bool) → PlainIndex (pairs : List (Pair A))) + (bits : Fin (r+returnBits A C K j k n t xi) → Bool) : + PlainIndex (pairs : List (Pair A)) := + let b := splitWordEquiv r (returnBits A C K j k n t xi) bits + booleanReturns A C K j k n t hK hW xi v w (initial b.1) b.2 + +def initializedReturnsLaw (A : Instance I J) (C K j k n t r : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (initial : (Fin r → Bool) → PlainIndex (pairs : List (Pair A))) : + RationalLaw (PlainIndex (pairs : List (Pair A))) := + mapLaw (uniformLaw (α := Fin (r+returnBits A C K j k n t xi) → Bool)) + (initializedReturns A C K j k n t r hK hW xi v w initial) + +theorem initializedReturnsLaw_eq (A : Instance I J) (C K j k n t r : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (initial : (Fin r → Bool) → PlainIndex (pairs : List (Pair A))) : + initializedReturnsLaw A C K j k n t r hK hW xi v w initial= + bindLaw (mapLaw (uniformLaw (α := Fin r → Bool)) initial) + (booleanReturnsLaw A C K j k n t hK hW xi v w) := by + unfold initializedReturnsLaw initializedReturns + dsimp only + have he := map_equiv (splitWordEquiv r (returnBits A C K j k n t xi)) + (uniformLaw (α := Fin (r+returnBits A C K j k n t xi) → Bool)) + (fun b => booleanReturns A C K j k n t hK hW xi v w (initial b.1) b.2) + rw [uniform_equiv,←uniform_product] at he + exact he.symm.trans (mapLaw_product_finish _ _ initial + (booleanReturns A C K j k n t hK hW xi v w)) + +theorem initializedReturnsLaw_cast (A : Instance I J) (C K j k n t r : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (initial : (Fin r → Bool) → PlainIndex (pairs : List (Pair A))) + (T : PlainIndex (pairs : List (Pair A))) : + ((initializedReturnsLaw A C K j k n t r hK hW xi v w initial).mass T:ℝ)= + ((returnKernel A C K j k n hK hW xi v w).power t).push + (fun S => ((mapLaw (uniformLaw (α := Fin r → Bool)) initial).mass S:ℝ)) T := by + rw [initializedReturnsLaw_eq] + simp only [bindLaw,Rat.cast_sum,Rat.cast_mul,booleanReturnsLaw_cast,FiniteKernel.push] + +/-- The initial word need only be close in total variation to a warm +reference law. No pointwise warmness of the actual initial word law is +assumed. -/ +theorem initializedReturns_distance (A : Instance I J) (C : ℕ) (hC : 0 (w p q:ℝ))) + (hn : 0 ((initializedReturnsLaw A C K j k n t r hK hW xi v w initial).mass T:ℝ)) + (fun S => CompanionWarmStart.law A j S.val.val)≤ + distance (fun S => ((mapLaw (uniformLaw (α := Fin r → Bool)) initial).mass S:ℝ)) nu+ + ((t:ℝ)*((5*(Fintype.card (Labels A):ℝ)^2*U)/(n:ℝ)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2))+ + (Real.exp (-(t:ℝ)/(2*ObservableBounds.observableConstant + (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/CompanionTrace.minimumMass A H L)/2) := by + let p : PlainIndex (pairs : List (Pair A)) → ℝ := fun S => + ((mapLaw (uniformLaw (α := Fin r → Bool)) initial).mass S:ℝ) + let Q := (returnKernel A C K j k n hK hW xi v w).power t + have he : + (fun T => ((initializedReturnsLaw A C K j k n t r hK hW xi v w initial).mass T:ℝ))= + Q.push p := by + funext T + exact initializedReturnsLaw_cast A C K j k n t r hK hW xi v w initial T + rw [he] + have hc := distance_push Q p nu + have hr := repeated_return_stationary A C hC K H L j k n hK hW hB hj hjH hbox + xi hx0 hx1 hPL hCheeger v hp w hw hgood hn nu hnu hmass U hU hwarm t + have ht := distance_triangle (Q.push p) (Q.push nu) + (fun S => CompanionWarmStart.law A j S.val.val) + exact ht.trans (_root_.add_le_add hc hr) + +end +end ContingencyTables.CompanionReturnWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionScaleSizes.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionScaleSizes.lean new file mode 100644 index 0000000000000000000000000000000000000000..47a10a4d0929ddf8d3277a7ff67d58eb3671bda3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionScaleSizes.lean @@ -0,0 +1,100 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialDraw +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMinMass + +namespace OAI + +/-! # Explicit sizes at the companion's bounded-capacity scale + +The unary copy labels are used only below the chosen cutoff, not below +the original binary-encoded capacities. These estimates retain the +cutoff dependency and then substitute the paper's actual polynomial +scale. The initial precision is bounded without executing a real log. +-/ + +namespace ContingencyTables.CompanionScaleSizes + +open CompanionFactorialApplication CompanionInitialDraw +open scoped BigOperators Classical + +def strength (d K : ℕ) (epsilon : ℚ) : ℕ := + ⌈(2048:ℚ)*d*K^2/epsilon⌉₊ + +def bins (d C : ℕ) : ℕ := 16*C*d^2 + +def cutoff (d C : ℕ) : ℕ := 100*d*bins d C + +def finalPhase (d C : ℕ) : ℕ := 10*C*d^2*(cutoff d C+1) + +lemma strength_source (d K : ℕ) (hd : 0 (A.hsmall _ _ s.property).le) + _ = Fintype.card (SmallCell A)*A.W := by simp + _ ≤ A.d*A.W := Nat.mul_le_mul_right _ (cellCount_bound A) + +lemma scheduled_label_count (A : Instance I J) (C : ℕ) (hW : A.W=cutoff A.d C) : + Fintype.card (Labels A)≤1600*C*A.d^4 := by + calc + _ ≤ A.d*A.W := label_count_le A + _ = _ := by rw [hW,cutoff_eq]; ring + +lemma precision_le (A : Instance I J) (h : ℕ) : + precision A h≤A.d*(3*A.W+1)+1+h := by + unfold precision + apply Nat.add_le_add_right + exact Nat.clog_le_of_le_pow (Nat.le_of_lt Nat.lt_two_pow_self) + +theorem initialBits_polynomial_bound (A : Instance I J) (h : ℕ) : + initialBits A (precision A h)≤ + A.d*(A.W+1)*(A.d*(3*A.W+1)+1+h) := by + exact (initialBits_bound A (precision A h)).trans + (Nat.mul_le_mul_left _ (precision_le A h)) + +/-- After substituting W=100dB, B=16Cd², the complete initializer word +length is an explicit polynomial in d, C, and its accuracy exponent. -/ +theorem scheduled_initialBits (A : Instance I J) (C h : ℕ) (hW : A.W=cutoff A.d C) : + initialBits A (precision A h)≤ + A.d*(1600*C*A.d^3+1)*(A.d*(4800*C*A.d^3+1)+1+h) := by + have hh := initialBits_polynomial_bound A h + rw [hW,cutoff_eq] at hh + convert hh using 1 + ring + +end ContingencyTables.CompanionScaleSizes + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStateMultiplierProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStateMultiplierProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..5306dd744bb33562f70fa10d1f3bdc7b7b8a3124 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStateMultiplierProgram.lean @@ -0,0 +1,141 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierMatrixProgram + +namespace OAI + +/-! # Reading the multiplier of an actual encoded chain state + +The at most quadratic list of labelled defect types is searched using +the proved occupancy test. Uniqueness of defect labels identifies the +selected matrix entry with the mathematical chain multiplier. +-/ + +namespace ContingencyTables.CompanionStateMultiplierProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms +open CompanionChainValidator CompanionPhaseCounts CompanionMultiplierMatrixProgram + +def coordinates (z : ValidatorInput) : List ℕ := z.1.map Prod.fst +def coordinatesRealizer : Realizer coordinates := composition first (map first) +lemma polynomial_coordinates : PolynomialTime coordinatesRealizer := + polynomial_composition polynomial_first (polynomial_map polynomial_first) + +def candidates (z : ValidatorInput) : List (ℕ × ℕ) := cellPairs (coordinates z,coordinates z) +def candidatesRealizer : Realizer candidates := + composition (pair coordinatesRealizer coordinatesRealizer) cellPairsRealizer +lemma polynomial_candidates : PolynomialTime candidatesRealizer := + polynomial_composition (polynomial_pair polynomial_coordinates polynomial_coordinates) polynomial_cellPairs + +def found (z : ValidatorInput) : List (ℕ × ℕ) := + (candidates z).filter (fun st => pairedDefectTest (z,st)) +def foundRealizer : Realizer found := + composition (pair identity candidatesRealizer) (filterWith pairedDefectTestRealizer) +lemma polynomial_found : PolynomialTime foundRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_candidates) + (polynomial_filterWith polynomial_pairedDefectTest) + +abbrev Input := FractionMatrix × ValidatorInput + +def noDefect (z : Input) : Bool := (found z.2).isEmpty +def noDefectRealizer : Realizer noDefect := composition (composition second foundRealizer) isEmpty +lemma polynomial_noDefect : PolynomialTime noDefectRealizer := + polynomial_composition (polynomial_composition polynomial_second polynomial_found) polynomial_isEmpty + +def readDefect (z : Input) : TreeFraction.Fraction := readEntry (z.1,(found z.2).getD 0 (0,0)) +def readDefectRealizer : Realizer readDefect := + composition (f := fun z : Input => (z.1,(found z.2).getD 0 (0,0))) (g := readEntry) + (pair first (composition (pair (composition second foundRealizer) (constant 0)) + (getDFast (0,0)))) readEntryRealizer +lemma polynomial_readDefect : PolynomialTime readDefectRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_found) (polynomial_constant 0)) + (polynomial_getDFast (0,0)))) polynomial_readEntry + +def output (z : Input) : TreeFraction.Fraction := if noDefect z then (1,1) else readDefect z +def outputRealizer : Realizer output := choose noDefectRealizer (constant (1,1)) readDefectRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_choose polynomial_noDefect (polynomial_constant (1,1)) polynomial_readDefect + +noncomputable section +open CompanionFactorialApplication CompanionArithmeticProposal CompanionOrderedProposal +open CommonBasesFPRAS TwoLiftStates +open scoped Classical +variable {I J : Type} [Fintype I] [Fintype J] +variable (A : Instance I J) {p m : ℕ} (g : Fin p ≃ Labels A) (e : (Labels A × Bool) ≃ Fin m) + +lemma candidates_mem (S : Set (Labels A × Bool)) (ij : ℕ × ℕ) : + ij ∈ candidates (orderedCatalog A g e,encodeSet e S) ↔ ij.1 < p ∧ ij.2 < p := by + rcases ij with ⟨i,j⟩ + unfold candidates + rw [mem_cellPairs] + simp only [coordinates,orderedCatalog,List.length_map,List.length_ofFn] + +lemma found_mem (S : Set (Labels A × Bool)) (ij : ℕ × ℕ) : + ij ∈ found (orderedCatalog A g e,encodeSet e S) ↔ + ∃ (i j : Fin p), (i.val,j.val)=ij ∧ DefectState pairs (pair (g i)) (pair (g j)) S := by + rw [found,List.mem_filter,candidates_mem] + constructor + · rintro ⟨⟨hi,hj⟩,ht⟩ + refine ⟨⟨ij.1,hi⟩,⟨ij.2,hj⟩,rfl,?_⟩ + exact (defectTest_ordered A g e S _ _).mp ht + · rintro ⟨i,j,hij,ht⟩ + cases hij + exact ⟨⟨i.isLt,j.isLt⟩,(defectTest_ordered A g e S i j).mpr ht⟩ + +lemma found_exists (S : Set (Labels A × Bool)) : + found (orderedCatalog A g e,encodeSet e S) ≠ [] ↔ + ∃ a b,DefectState pairs a b S := by + constructor + · intro hn + obtain ⟨ij,hij⟩ := List.exists_mem_of_ne_nil _ hn + obtain ⟨i,j,_,hd⟩ := (found_mem A g e S ij).mp hij + exact ⟨pair (g i),pair (g j),hd⟩ + · rintro ⟨a,b,hd⟩ hn + obtain ⟨u,_,hu⟩ := List.mem_map.mp hd.1 + obtain ⟨v,_,hv⟩ := List.mem_map.mp hd.2.1 + have hm : ((g.symm u).val,(g.symm v).val) ∈ found (orderedCatalog A g e,encodeSet e S) := by + apply (found_mem A g e S _).mpr + refine ⟨g.symm u,g.symm v,rfl,?_⟩ + simpa only [Equiv.apply_symm_apply,hu,hv] using hd + simp only [hn,List.not_mem_nil] at hm + +theorem output_code (S : Set (Labels A × Bool)) (w : Fin p → Fin p → TreeFraction.Fraction) : + TreeFraction.val (output (CompanionMultiplierMatrixProgram.matrixCode w, + (orderedCatalog A g e,encodeSet e S)))= + rationalMultiplier pairs + (fun a b => TreeFraction.val (w (g.symm a.1.1) (g.symm b.1.1))) S := by + by_cases h : ∃ a b,DefectState pairs a b S + · have hn := (found_exists A g e S).mpr h + have hm : (found (orderedCatalog A g e,encodeSet e S)).getD 0 (0,0) ∈ + found (orderedCatalog A g e,encodeSet e S) := by + cases hl : found (orderedCatalog A g e,encodeSet e S) with + | nil => exact (hn hl).elim + | cons a as => simp only [List.getD_cons_zero,List.mem_cons,true_or] + obtain ⟨i,j,hij,hd⟩ := (found_mem A g e S _).mp hm + have he := hd.unique h.choose_spec.choose_spec + unfold output noDefect readDefect + have heNonempty : (found (orderedCatalog A g e,encodeSet e S)).isEmpty=false := by + cases hl : found (orderedCatalog A g e,encodeSet e S) with + | nil => exact (hn hl).elim + | cons a as => rfl + rw [heNonempty] + simp only [Bool.false_eq_true,ite_false] + rw [←hij,readEntry_code] + have hi : g i=h.choose.1.1 := congrArg (fun a => a.1.1) he.1 + have hj : g j=h.choose_spec.choose.1.1 := congrArg (fun a => a.1.1) he.2 + have hi' : i=g.symm h.choose.1.1 := by + simpa only [Equiv.symm_apply_apply] using congrArg g.symm hi + have hj' : j=g.symm h.choose_spec.choose.1.1 := by + simpa only [Equiv.symm_apply_apply] using congrArg g.symm hj + rw [rationalMultiplier,dite_eq_left h] + rw [←hi',←hj'] + · have hn : found (orderedCatalog A g e,encodeSet e S)=[] := by + by_contra hn + exact h ((found_exists A g e S).mp hn) + simp only [output,noDefect,hn,List.isEmpty_nil,ite_true,TreeFraction.val, + Nat.cast_one,div_one,rationalMultiplier,dite_eq_right h] + +end +end ContingencyTables.CompanionStateMultiplierProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredRepresentation.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredRepresentation.lean new file mode 100644 index 0000000000000000000000000000000000000000..515f25866021946c3437e52dcd544d94ae7973b9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredRepresentation.lean @@ -0,0 +1,199 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialStoredProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterHistoryProgram + +namespace OAI + +/-! # Exact square-matrix representations along the physical phase loop + +Successful updates construct every entry in catalog order. Aborted updates +retain the previous stored value, so the same representation supports the +readback used in the projected history law. +-/ +namespace ContingencyTables.CompanionStoredRepresentation +open MatchingFPRAS CompanionMultiplierMatrixProgram + +def MatrixRep (p : ℕ) (M : FractionMatrix) : Prop := + ∃ w : Fin p→Fin p→TreeFraction.Fraction, M=matrixCode w + +def StoredRep (p : ℕ) (s : CompanionPhaseFinishProgram.Stored) : Prop := + MatrixRep p s.1 + +def entries (p : ℕ) (M : FractionMatrix) (i j : Fin p) : TreeFraction.Fraction := + readEntry (M,(i.val,j.val)) + +theorem matrixCode_rep {p : ℕ} (w : Fin p→Fin p→TreeFraction.Fraction) : + MatrixRep p (matrixCode w) := ⟨w,rfl⟩ + +theorem readback {p : ℕ} {M : FractionMatrix} (h : MatrixRep p M) : + matrixCode (entries p M)=M := by + obtain ⟨w,rfl⟩ := h + have he : entries p (matrixCode w)=w := by + funext i j + exact readEntry_code w i j + rw [he] + +theorem stored_readback {p : ℕ} {s : CompanionPhaseFinishProgram.Stored} + (h : StoredRep p s) : (matrixCode (entries p s.1),s.2)=s := by + exact Prod.ext (readback h) rfl + +theorem matrixCode_injective {p : ℕ} : + Function.Injective (matrixCode (p := p)) := by + intro w w' h + funext i j + have he := congrArg (fun M => readEntry (M,(i.val,j.val))) h + simpa only [readEntry_code] using he + +private theorem map_range_ofFn {α : Type} (f : ℕ→α) (p : ℕ) : + (List.range p).map f=List.ofFn (fun i : Fin p => f i.val) := by + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + +theorem updateMatrix_rep (z : CompanionMultiplierMatrixProgram.Input) : + MatrixRep z.1.1.length (updateMatrix z) := by + refine ⟨fun i j => updateEntry (z,(i.val,j.val)),?_⟩ + simp only [updateMatrix,updateRow,rowEntry,indices,map_range_ofFn,matrixCode] + +theorem finish_output_rep (z : CompanionPhaseFinishProgram.Input) + (s : CompanionPhaseFinishProgram.Stored) + (h : CompanionPhaseFinishProgram.output z=some s) : + StoredRep z.1.1.1.1.length s := by + unfold CompanionPhaseFinishProgram.output at h + split_ifs at h + · cases Option.some.inj h + exact updateMatrix_rep z.1.1 + +theorem observed_output_rep (z : CompanionObservedUpdateProgram.Input) + (s : CompanionPhaseFinishProgram.Stored) + (h : CompanionObservedUpdateProgram.output z=some s) : + StoredRep z.1.2.1.1.1.length s := + finish_output_rep (CompanionObservedUpdateProgram.finishInput z) s h + +theorem trial_output_rep (z : CompanionPhaseTrialProgram.Input) + (s : CompanionPhaseFinishProgram.Stored) + (h : CompanionPhaseTrialProgram.output z=some s) : + StoredRep (CompanionPhaseTrialProgram.catalogue z).length s := + observed_output_rep (CompanionPhaseTrialProgram.updateInput z) s h + +theorem trial_getD_rep {p : ℕ} (z : CompanionPhaseTrialProgram.Input) + (old : CompanionPhaseFinishProgram.Stored) (hold : StoredRep p old) + (hlen : (CompanionPhaseTrialProgram.catalogue z).length=p) : + StoredRep p ((CompanionPhaseTrialProgram.output z).getD old) := by + cases h : CompanionPhaseTrialProgram.output z with + | none => simpa only [Option.getD_none] using hold + | some s => + simpa only [Option.getD_some,hlen] using trial_output_rep z s h + +theorem old_rep {p : ℕ} (z : CompanionOuterPhaseProgram.Input) + (hinit : StoredRep p z.1.1.2) + (hh : ∀ s∈z.1.2,StoredRep p s) : + StoredRep p (CompanionOuterPhaseProgram.old z) := by + unfold CompanionOuterPhaseProgram.old CompanionOuterPhaseProgram.phase + CompanionOuterPhaseProgram.history + split_ifs with he + · exact hinit + · have hi : z.1.2.length-1 < z.1.2.length := by omega + rw [List.getD_eq_getElem _ _ hi] + exact hh _ (List.getElem_mem hi) + +theorem outer_output_rep {p : ℕ} (z : CompanionOuterPhaseProgram.Input) + (hinit : StoredRep p z.1.1.2) + (hh : ∀ s∈z.1.2,StoredRep p s) + (hlen : (CompanionPhaseTrialProgram.catalogue + (CompanionOuterPhaseProgram.trialInput z)).length=p) : + StoredRep p (CompanionOuterPhaseProgram.output z) := + trial_getD_rep (CompanionOuterPhaseProgram.trialInput z) + (CompanionOuterPhaseProgram.old z) (old_rep z hinit hh) hlen + +theorem history_rep {p : ℕ} (fixed : CompanionOuterHistoryProgram.Fixed) + (hinit : StoredRep p fixed.2) + (hcat : ∀ (history : List CompanionPhaseFinishProgram.Stored) (bits : List Bool), + (∀ s∈history,StoredRep p s) → + (CompanionPhaseTrialProgram.catalogue + (CompanionOuterPhaseProgram.trialInput ((fixed,history),bits))).length=p) + (words : List (List Bool)) : + ∀ s∈CompanionOuterHistoryProgram.storedHistory (fixed,words),StoredRep p s := by + have hf (ws : List (List Bool)) (history : List CompanionPhaseFinishProgram.Stored) + (hh : ∀ s∈history,StoredRep p s) : + ∀ s∈(ws.foldl (fun state bits => CompanionOuterHistoryProgram.advance (bits,state)) + (fixed,history)).2,StoredRep p s := by + induction ws generalizing history with + | nil => exact hh + | cons bits ws ih => + apply ih + intro s hs + obtain hs|hs := List.mem_append.mp hs + · exact hh s hs + · have he : s=CompanionOuterHistoryProgram.next (bits,(fixed,history)) := by + simpa only [List.mem_singleton] using hs + subst s + exact outer_output_rep ((fixed,history),bits) hinit hh (hcat history bits hh) + exact hf words [] (by simp) + +theorem history_output_rep {p : ℕ} (fixed : CompanionOuterHistoryProgram.Fixed) + (hinit : StoredRep p fixed.2) + (hcat : ∀ (history : List CompanionPhaseFinishProgram.Stored) (bits : List Bool), + (∀ s∈history,StoredRep p s) → + (CompanionPhaseTrialProgram.catalogue + (CompanionOuterPhaseProgram.trialInput ((fixed,history),bits))).length=p) + (words : List (List Bool)) : + StoredRep p (CompanionOuterHistoryProgram.output (fixed,words)) := + old_rep ((fixed,CompanionOuterHistoryProgram.storedHistory (fixed,words)),[]) + hinit (history_rep fixed hinit hcat words) + +theorem history_rep_bounded {p H : ℕ} (fixed : CompanionOuterHistoryProgram.Fixed) + (hinit : StoredRep p fixed.2) + (hcat : ∀ (history : List CompanionPhaseFinishProgram.Stored) (bits : List Bool), + history.length < H → (∀ s∈history,StoredRep p s) → + (CompanionPhaseTrialProgram.catalogue + (CompanionOuterPhaseProgram.trialInput ((fixed,history),bits))).length=p) + (words : List (List Bool)) (hwords : words.length ≤ H) : + ∀ s∈CompanionOuterHistoryProgram.storedHistory (fixed,words),StoredRep p s := by + have hf (ws : List (List Bool)) (history : List CompanionPhaseFinishProgram.Stored) + (hh : ∀ s∈history,StoredRep p s) (hlen : history.length+ws.length ≤ H) : + ∀ s∈(ws.foldl (fun state bits => CompanionOuterHistoryProgram.advance (bits,state)) + (fixed,history)).2,StoredRep p s := by + induction ws generalizing history with + | nil => exact hh + | cons bits ws ih => + have hj : history.length < H := by + simp only [List.length_cons] at hlen + omega + apply ih + · intro s hs + obtain hs|hs := List.mem_append.mp hs + · exact hh s hs + · have he : s=CompanionOuterHistoryProgram.next (bits,(fixed,history)) := by + simpa only [List.mem_singleton] using hs + subst s + exact outer_output_rep ((fixed,history),bits) hinit hh (hcat history bits hj hh) + · simp only [List.length_append,List.length_cons,List.length_nil] at * + omega + exact hf words [] (by simp) (by simpa only [List.length_nil,Nat.zero_add] using hwords) + +theorem history_output_rep_bounded {p H : ℕ} (fixed : CompanionOuterHistoryProgram.Fixed) + (hinit : StoredRep p fixed.2) + (hcat : ∀ (history : List CompanionPhaseFinishProgram.Stored) (bits : List Bool), + history.length < H → (∀ s∈history,StoredRep p s) → + (CompanionPhaseTrialProgram.catalogue + (CompanionOuterPhaseProgram.trialInput ((fixed,history),bits))).length=p) + (words : List (List Bool)) (hwords : words.length ≤ H) : + StoredRep p (CompanionOuterHistoryProgram.output (fixed,words)) := + old_rep ((fixed,CompanionOuterHistoryProgram.storedHistory (fixed,words)),[]) + hinit (history_rep_bounded fixed hinit hcat words hwords) + +noncomputable section +open CompanionFactorialApplication +open scoped Classical +variable {m n : ℕ} (A : Instance (Fin m) (Fin n)) + +theorem initial_output_rep (S : Set (Labels A×Bool)) : + StoredRep (CanonicalInitialEncoding.copyOrder (CompanionComputedInitial.capacities A)).length + (CompanionInitialStoredProgram.output (CompanionInitialStoredProgram.data A S)) := + ⟨CompanionInitialMatrixProgram.initialEntries A,CompanionInitialStoredProgram.output_matrix A S⟩ + +end +end ContingencyTables.CompanionStoredRepresentation + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredShape.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredShape.lean new file mode 100644 index 0000000000000000000000000000000000000000..07c0ca5d2e8fd9937f1295ee1b59a54fd09670d5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredShape.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionStoredSize + +namespace OAI + +/-! # Height and shape invariants for chronological stored values -/ +namespace ContingencyTables.CompanionStoredSize +open MatchingFPRAS MatchingFPRAS.TreeTyped CompanionMultiplierMatrixProgram +open CompanionPhaseFinishProgram + +def StoredShape (R : ℕ) (s : Stored) : Prop := + s.1.length ≤ R ∧ ∀ row∈s.1,row.length ≤ R + +lemma height_mono {M N : ℕ} (h : M ≤ N) {s : Stored} (hs : StoredHeight M s) : StoredHeight N s := + ⟨fun row hr x hx => (hs.1 row hr x hx).trans h,hs.2.trans h⟩ + +lemma shape_mono {M N : ℕ} (h : M ≤ N) {s : Stored} (hs : StoredShape M s) : StoredShape N s := + ⟨hs.1.trans h,fun row hr => (hs.2 row hr).trans h⟩ + +lemma shape_of_weight (s : Stored) : StoredShape (weight s) s := by + refine ⟨(list_length_le_weight _).trans (weight_fst s),?_⟩ + intro row hr + exact (list_length_le_weight _).trans ((weight_mem hr).trans (weight_fst s)) + +lemma height_of_weight (s : Stored) : StoredHeight (weight s) s := by + refine ⟨?_,(TreeFraction.height_le_weight _).trans (weight_snd s)⟩ + intro row hr x hx + exact (TreeFraction.height_le_weight _).trans + ((weight_mem hx).trans ((weight_mem hr).trans (weight_fst s))) + +lemma weight_of_bounds (s : Stored) (R M : ℕ) (hR : StoredShape R s) (hM : StoredHeight M s) : + weight s ≤ R*(R*(8*M+4)+2)+8*M+5 := by + have rows (row : List TreeFraction.Fraction) (hr : row∈s.1) : + weight row ≤ R*(8*M+4)+1 := by + have h := weight_map_bound (f := id) (as := row) (N := 8*M+3) (by + intro x hx + exact (TreeFraction.weight_le_height x).trans (by have := hM.1 row hr x hx; omega)) + simp only [List.map_id] at h + exact h.trans (by gcongr; exact hR.2 row hr) + have h := weight_map_bound (f := id) (as := s.1) (N := R*(8*M+4)+1) rows + simp only [List.map_id] at h + have hm := TreeFraction.weight_le_height s.2 + have hn : weight s.1 ≤ R*(R*(8*M+4)+2)+1 := h.trans (by gcongr; exact hR.1) + conv_lhs => rw [show s=(s.1,s.2) from rfl,weight_prod] + nlinarith [hM.2] + +lemma next_shape (z : CompanionPhaseFinishProgram.Input) : + StoredShape (trajectory z).1.length (next z) := by + constructor + · simp only [next,updateMatrix,CompanionMultiplierMatrixProgram.indices,List.length_map, + List.length_range] + exact le_rfl + · intro row hr + obtain ⟨i,_,rfl⟩ := List.mem_map.mp hr + simp only [updateRow,CompanionMultiplierMatrixProgram.indices,List.length_map,List.length_range] + exact le_rfl + +end ContingencyTables.CompanionStoredSize + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredSize.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredSize.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3f6c2794e3d064e0a690bc5e4fb62d5d179584f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionStoredSize.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFractionSize + +namespace OAI + +/-! # A phase adds a bounded amount to each stored fraction's binary height -/ +namespace ContingencyTables.CompanionStoredSize +open MatchingFPRAS CompanionFractionSize CompanionMultiplierMatrixProgram +open CompanionPhaseFinishProgram CompanionMultiplierProgram CompanionPhaseCounts + +private lemma getD_property {X : Type} (P : X→Prop) (xs : List X) (i : ℕ) (d : X) + (hx : ∀ x∈xs,P x) (hd : P d) : P (xs.getD i d) := by + rw [List.getD_eq_getElem?_getD] + cases he : xs[i]? with + | none => exact hd + | some x => exact hx x (List.mem_of_getElem? he) + +def MatrixHeight (M : ℕ) (w : FractionMatrix) : Prop := + ∀ row∈w,∀ x∈row,TreeFraction.height x ≤ M + +def StoredHeight (M : ℕ) (s : Stored) : Prop := MatrixHeight M s.1 ∧ TreeFraction.height s.2 ≤ M + +lemma readEntry_height (M : ℕ) (hM : 1 ≤ M) (w : FractionMatrix) (hw : MatrixHeight M w) + (ij : ℕ×ℕ) : TreeFraction.height (readEntry (w,ij)) ≤ M := by + have hr : ∀ x∈w.getD ij.1 [],TreeFraction.height x ≤ M := + getD_property (fun row => ∀ x∈row,TreeFraction.height x ≤ M) w ij.1 [] hw + (by simp only [List.not_mem_nil,IsEmpty.forall_iff,implies_true]) + exact getD_property (fun x => TreeFraction.height x ≤ M) _ ij.2 (0,1) hr + (by simpa only [TreeFraction.height,Nat.size_zero,Nat.size_one,Nat.zero_max] using hM) + +lemma updateMatrix_height (M : ℕ) (hM : 1 ≤ M) (z : CompanionMultiplierMatrixProgram.Input) + (hw : MatrixHeight M z.2) : MatrixHeight (M+z.1.2.length+1) (updateMatrix z) := by + intro row hr x hx + obtain ⟨i,_,rfl⟩ := List.mem_map.mp hr + obtain ⟨j,_,rfl⟩ := List.mem_map.mp hx + change TreeFraction.height (updateCode ((z.1,(i,j)),readEntry (z.2,(i,j)))) ≤ _ + exact (updateCode_height _).trans (by + have h := readEntry_height M hM z.2 hw (i,j) + dsimp only + omega) + +lemma terms_length (z : CompanionPhaseFinishProgram.Input) : + (terms z).length=(trajectory z).2.length := by + simp only [terms,CompanionPhaseFinishProgram.indices,List.length_map,List.length_range] + +lemma terms_height (z : CompanionPhaseFinishProgram.Input) (V : ℕ) (hV : 1 ≤ V) + (hv : ∀ x∈z.2,TreeFraction.height x.1 ≤ V ∧ TreeFraction.height x.2 ≤ V) : + ∀ x∈terms z,TreeFraction.height x ≤ 2*V+1 := by + intro x hx + obtain ⟨i,_,rfl⟩ := List.mem_map.mp hx + have hb := getD_property + (fun x : TreeFraction.Fraction×TreeFraction.Fraction => + TreeFraction.height x.1 ≤ V ∧ TreeFraction.height x.2 ≤ V) + z.2 i ((0,1),(0,1)) hv (by + simpa only [TreeFraction.height,Nat.size_zero,Nat.size_one,Nat.zero_max,and_self] using hV) + exact term_height (termInput (z,i)) V hb.1 hb.2 + +lemma ratio_height (z : CompanionPhaseFinishProgram.Input) (V : ℕ) (hV : 1 ≤ V) + (hv : ∀ x∈z.2,TreeFraction.height x.1 ≤ V ∧ TreeFraction.height x.2 ≤ V) : + TreeFraction.height (ratio z) ≤ (trajectory z).2.length*(2*V+3)+(trajectory z).2.length+3 := by + have ht := sum_height (terms z) (2*V+1) (terms_height z V hV hv) + rw [terms_length] at ht + have hconst : 2*V+1+2=2*V+3 := by omega + rw [hconst] at ht + have hc : TreeFraction.height (count z) ≤ (trajectory z).2.length+1 := by + have hp : plainCountCode (trajectory z) ≤ (trajectory z).2.length := List.length_filter_le _ _ + have hs : (plainCountCode (trajectory z)).size ≤ plainCountCode (trajectory z) := + Nat.size_le.mpr Nat.lt_two_pow_self + change max (plainCountCode (trajectory z)).size (1:ℕ).size ≤ _ + norm_num only [Nat.size_one] + omega + have hr := height_div (total z) (count z) + change TreeFraction.height (ratio z) ≤ _ at hr + change TreeFraction.height (total z) ≤ _ at ht + omega + +/-- This bound is additive in the old stored height; iterating phases +therefore preserves a polynomial representation size. -/ +lemma next_height (z : CompanionPhaseFinishProgram.Input) (M V : ℕ) (hM : 1 ≤ M) (hV : 1 ≤ V) + (hw : MatrixHeight M z.1.1.2) (he : TreeFraction.height z.1.2 ≤ M) + (hv : ∀ x∈z.2,TreeFraction.height x.1 ≤ V ∧ TreeFraction.height x.2 ≤ V) : + StoredHeight (M+(trajectory z).2.length*(2*V+3)+(trajectory z).2.length+5) (next z) := by + constructor + · have hm := updateMatrix_height M hM z.1.1 hw + intro row hr x hx + have h := hm row hr x hx + change TreeFraction.height x ≤ M+(trajectory z).2.length+1 at h + omega + · have hr := ratio_height z V hV hv + have hm := height_mul z.1.2 (ratio z) + change TreeFraction.height (estimate z) ≤ _ at hm + change TreeFraction.height (estimate z) ≤ _ + omega + +end ContingencyTables.CompanionStoredSize + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTargetMixing.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTargetMixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..97a121c0a36f838eb1b4cbb4065c06a1272d22b7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTargetMixing.lean @@ -0,0 +1,164 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTargetTrace +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTrace + +namespace OAI + +/-! # Mixing of the literal dyadic trace + +The original and degree-completed state chains agree. Their traces +therefore agree as well, and the dyadic holding factor costs at most +two in the trace Poincare estimate. +-/ + +namespace ContingencyTables.CompanionTargetMixing + +open CommonBasesFPRAS CompanionFactorialApplication CompanionBooleanPhase +open CompanionTraceWords CompanionTargetTrace CompanionConcentration +open CompanionAnnealing CompanionWarmStart CompanionRationalUpdates TwoLiftStates +open DegreeCompletion ObservableBounds +open scoped BigOperators Classical + +noncomputable section + +private theorem trace_exit_congr {X : Type*} [Fintype X] + (C D : FiniteChain X) (B : X → Prop) [Nonempty (FiniteChain.Inside B)] + (h : C=D) + (hC : ∀ x : FiniteChain.Outside B,∃ y : FiniteChain.Inside B,0 (w p q:ℝ)) (weight A j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A j) + +theorem literalTrace_eq_completed (A : Instance I J) (j : ℕ) + (hp : 0 (w p q:ℝ)) + (fun p q => by exact_mod_cast hw p q) := by + let := plainIndex_nonempty (pairs : List (Pair A)) PairedLabels.fresh PairedLabels.cover + let F := completeDegree (weight A j) (pairs : List (Pair A)).length + have hF := completeDegree_positive (weight A j) (pairs : List (Pair A)).length + (actual_degree A j).1 + have h := trace_exit_congr (referenceChain A j hp w hw) + (metropolisChain pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + (fun p q => (w p q:ℝ)) F (fun p q => by exact_mod_cast hw p q) hF) + (plainPredicate pairs) (referenceChain_eq_completed A j hp w hw) + (metropolis_plain_exit pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + (fun p q => (w p q:ℝ)) (weight A j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A j)) + (metropolis_plain_exit pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover + (fun p q => (w p q:ℝ)) F (fun p q => by exact_mod_cast hw p q) hF) + exact h + +private lemma literalTrace_poincare (A : Instance I J) (j : ℕ) + (hp : 0 (w p q:ℝ))) + (H : PlainIndex (pairs : List (Pair A)) → ℝ) : + (literalTrace A j hp w hw).variance H≤ + observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)* + (literalTrace A j hp w hw).energy H := by + rw [literalTrace_eq_completed] + exact CompanionTrace.trace_poincare A j hp (fun p q => (w p q:ℝ)) hgood H + +theorem targetTrace_poincare (A : Instance I J) (j : ℕ) + (hp : 0 (w p q:ℝ))) + (H : PlainIndex (pairs : List (Pair A)) → ℝ) : + (CompanionTargetTrace.actualTrace A j hp w hw).variance H≤ + (2*observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2))* + (CompanionTargetTrace.actualTrace A j hp w hw).energy H := by + let := plainIndex_nonempty (pairs : List (Pair A)) PairedLabels.fresh PairedLabels.cover + have hnonneg : 0≤observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := by + unfold observableConstant + positivity + have hh := FiniteChainSlowdown.trace_variance_bound (referenceChain A j hp w hw) + (plainPredicate pairs) (sourceKilled A j hp w hw) (by intro x y; rfl) + (slowdown A) (by linarith [(slowdown_bounds A hp).1]) (slowdown_bounds A hp).2 + (slowdown_bounds A hp).1 + (observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)) hnonneg H + (literalTrace_poincare A j hp w hw hgood H) + exact hh + +theorem target_point_mixing (A : Instance I J) (H K j : ℕ) (hj : j≤H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1))≤(2:ℝ)^K) + (hp : 0 (w p q:ℝ))) (t : ℕ) + (x y : PlainIndex (pairs : List (Pair A))) : + |((CompanionTargetTrace.actualTrace A j hp w hw).kernel.power t).P x y/ + law A j y.val.val-1|≤ + Real.exp (-(t:ℝ)/(2*observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)))/ + CompanionTrace.minimumMass A H K := by + have hpR : (1:ℝ)≤Fintype.card (Labels A) := by exact_mod_cast hp + have hK : 1≤2*observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := by + have hh := observableConstant_lower (Fintype.card (Labels A)) ((A.W:ℝ)^2) + hpR (square_width_one_le A) + have hp5 : (1:ℝ)≤(Fintype.card (Labels A):ℝ)^5 := one_le_pow₀ hpR + linarith + have hmin (S : PlainIndex (pairs : List (Pair A))) : + CompanionTrace.minimumMass A H K≤(CompanionTargetTrace.actualTrace A j hp w hw).π S := by + rw [actualTrace_pi] + have hh := CompanionTrace.trace_minimum A H K j hj hB hp + (fun p q => (w p q:ℝ)) (fun p q => by exact_mod_cast hw p q) S + rw [CompanionTrace.trace_pi] at hh + exact hh + have hh := (CompanionTargetTrace.actualTrace A j hp w hw).kernel_point_mixing + (2*observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)) + (CompanionTrace.minimumMass A H K) hK (CompanionTrace.minimumMass_positive A H K) + hmin (targetTrace_poincare A j hp w hw hgood) t x y + rwa [actualTrace_pi] at hh + +def restartTime (A : Instance I J) (H K : ℕ) : ℕ := 2*CompanionTrace.time A H K + +theorem restart_schedule (A : Instance I J) (H K : ℕ) (hp : 0 (w p q:ℝ))) + (nu : PlainIndex (pairs : List (Pair A)) → ℝ) (hnu : ∀ S,0≤nu S) + (hmass : ∑ S,nu S≤1) (y : PlainIndex (pairs : List (Pair A))) : + ((CompanionTargetTrace.actualTrace A j hp w hw).kernel.power (restartTime A H K)).push nu y≤ + 2*law A j y.val.val := by + have hy : 0 mul_le_mul_of_nonneg_left (hrow x) (hnu x)) + _ = (∑ x,nu x)*(2*law A j y.val.val) := by rw [Finset.sum_mul] + _ ≤ _ := by nlinarith + +end +end ContingencyTables.CompanionTargetMixing + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTargetTrace.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTargetTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..a84a999dcf00b16601cb03c387d0be0d8657ddec --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTargetTrace.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCappedReturn +import OAI.Combinatorics.ContingencyTables.Counting.CompanionWarmStart + +namespace OAI + +/-! # Warm cap bounds for the actual dyadic companion trace + +Holding slowdown leaves the stationary law unchanged. The good +multiplier bound therefore gives the same polynomial mean-return and +capped-return bounds as the original Metropolis chain. +-/ + +namespace ContingencyTables.CompanionTargetTrace + +open CommonBasesFPRAS CompanionFactorialApplication CompanionBooleanPhase +open CompanionTraceWords CompanionCappedReturn CompanionConcentration +open CompanionAnnealing CompanionWarmStart TwoLiftStates +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def actualTrace (A : Instance I J) (j : ℕ) (hp : 0 (w p q:ℝ)) (weight A j) := by + exact metropolis_insideMass pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover (fun p q => (w p q:ℝ)) (weight A j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A j) + +theorem actualTrace_pi (A : Instance I J) (j : ℕ) (hp : 0 (w p q:ℝ)) (weight A j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A j) S + exact h + +theorem insideMass_lower (A : Instance I J) (j : ℕ) (hp : 0 (w p q:ℝ))) : + 1/(5*(Fintype.card (Labels A):ℝ)^2)≤ + (targetChain A j hp w hw).insideMass (plainPredicate pairs) := by + rw [insideMass_eq] + have h := plain_mass_lower pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover (fun p q => (w p q:ℝ)) (weight A j) + (fun p q => by exact_mod_cast hw p q) (weight_positive A j) hgood.upper + simpa only [PairedLabels.length,CompanionWarmStart.total] using h + +private theorem warm_div_mass (A : Instance I J) (j : ℕ) (hp : 0 (w p q:ℝ))) + (U : ℝ) (hU : 0≤U) : + U/(targetChain A j hp w hw).insideMass (plainPredicate pairs)≤ + 5*(Fintype.card (Labels A):ℝ)^2*U := by + have hpR : (0:ℝ) (w p q:ℝ))) + (phi : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) → ℝ) + (hphi : ∀ S,0≤phi S ∧ phi S≤1) (n : ℕ) (hn : 0 phi (returnDefault (plainPredicate pairs) S xs))- + (∑ T,(targetChain A j hp w hw).traceMatrix (plainPredicate pairs) + (targetKilled A j hp w hw) S T*phi T)|)≤ + (5*(Fintype.card (Labels A):ℝ)^2*U)/(n:ℝ) := by + let := plainIndex_nonempty (pairs : List (CompanionRationalUpdates.Pair A)) + PairedLabels.fresh PairedLabels.cover + have hh := warm_returnDefault_error (targetChain A j hp w hw) (plainPredicate pairs) + (targetKilled A j hp w hw) (targetKilled_matches A j hp w hw) phi hphi n hn nu hnu U + (by + intro S + have hs := hwarm S + rw [←actualTrace_pi A j hp w hw S] at hs + simpa only [actualTrace] using hs) + exact hh.trans (div_le_div_of_nonneg_right (warm_div_mass A j hp w hw hgood U hU) + (Nat.cast_nonneg n)) + +def capSteps (A : Instance I J) (budget : ℕ) : ℕ := + 20*(Fintype.card (Labels A))^2*budget + +theorem four_warm_cap_error (A : Instance I J) (j : ℕ) (hp : 0 (w p q:ℝ))) + (phi : PlainIndex (pairs : List (CompanionRationalUpdates.Pair A)) → ℝ) + (hphi : ∀ S,0≤phi S ∧ phi S≤1) (budget : ℕ) (hb : 0 phi (returnDefault (plainPredicate pairs) S xs))- + (∑ T,(targetChain A j hp w hw).traceMatrix (plainPredicate pairs) + (targetKilled A j hp w hw) S T*phi T)|)≤1/(budget:ℝ) := by + have hn : 0 (A.r i).toNat) (fun j => (A.c j).toNat) A.b) + +lemma tableCount_ge_one (A : Instance I J) : 1 ≤ tableCount A := by + have ha : Feasible A (tableAssignment A A.X A.hX) := by + unfold Feasible + rw [physicalTable_assignment] + exact ⟨A.hX,A.hXr,A.hXc⟩ + have hpos : 0 < Fintype.card (PhysicalTables A) := + Fintype.card_pos_iff.mpr ⟨⟨tableAssignment A A.X A.hX,ha⟩⟩ + have hh : 1 ≤ Fintype.card (PhysicalTables A) := hpos + rw [cardinality_eq] at hh + unfold tableCount + exact_mod_cast hh + +lemma treeCell_card_le (A : Instance I J) : Fintype.card (TreeCell A) ≤ A.d := by + exact (Fintype.card_le_of_injective (fun t : TreeCell A => t.val) Subtype.val_injective).trans + (by simpa only [Fintype.card_prod] using A.hcard) + +/-- Actual endpoint tables and the proved scalar signature estimates +control the entire union of narrow tree violations. -/ +lemma total_near_mass_le (A : Instance I J) (E : Endpoints A) (alpha gamma : ℝ) + (ha : 0 ≤ alpha) (hg : 0 < gamma) (hW : 20*A.d ≤ A.W) (B K : ℕ) + (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) (hBK : 2*B ≤ K) (hK : 0 < K) : + (∑ t : TreeCell A,nearMass A alpha t.val gamma) ≤ + (4*A.d*gamma*K:ℝ)*physicalMass A alpha := by + have hM : 0 < physicalMass A alpha := by + exact lt_of_lt_of_le (by norm_num : (0:ℝ)<1) + ((tableCount_ge_one A).trans (table_count_le_mass A alpha)) + have hh (t : TreeCell A) : nearMass A alpha t.val gamma ≤ + (4*gamma*K:ℝ)*physicalMass A alpha := by + apply (div_le_iff₀ hM).mp + exact near_mass_bound A alpha gamma t.val t.property ha hg hW B K hB hBK hK + (E.lowerTable t) (E.upperTable t) (E.lowerBounds t) (E.upperBounds t) + (E.lowerRows t) (E.lowerColumns t) (E.upperRows t) (E.upperColumns t) + (E.lowerAttains t) (E.upperAttains t) + calc + _ ≤ ∑ _t : TreeCell A,(4*gamma*K:ℝ)*physicalMass A alpha := + Finset.sum_le_sum (fun t _ => hh t) + _ = (Fintype.card (TreeCell A):ℝ)*((4*gamma*K:ℝ)*physicalMass A alpha) := by simp + _ ≤ (A.d:ℝ)*((4*gamma*K:ℝ)*physicalMass A alpha) := + mul_le_mul_of_nonneg_right (by exact_mod_cast treeCell_card_le A) (by positivity) + _ = _ := by ring + +lemma feasible_sum_eq_tableCount (A : Instance I J) : + (∑ a : Profiles (cellWidth A),if Feasible A a then (1:ℝ) else 0)=tableCount A := by + have hh : (∑ a : Profiles (cellWidth A),if Feasible A a then (1:ℝ) else 0)= + (Fintype.card (PhysicalTables A):ℝ) := by simp [PhysicalTables,Fintype.card_subtype] + rw [hh,cardinality_eq] + rfl + +lemma mass_le_table_far_near (A : Instance I J) (alpha gamma : ℝ) (K : ℕ) + (ha : 0 < alpha) (hg1 : gamma ≤ 1) (hscale : 4*(K:ℝ) ≤ alpha*gamma) : + physicalMass A alpha ≤ tableCount A+ + (∑ a : Profiles (cellWidth A),if 4*(K:ℝ) ≤ alpha*actualPenalty A a + then actualWeight A alpha a else 0)+ + ∑ t : TreeCell A,nearMass A alpha t.val gamma := by + have hh := TerminalMassCover.mass_le_cover (actualWeight A alpha) (Feasible A) + (fun a => 4*(K:ℝ) ≤ alpha*actualPenalty A a) + (fun t : TreeCell A => fun a => a t.val ∈ cellPositions A t.val gamma) + (fun a => ForestPenaltyApplication.physicalWeight_nonnegative _ _ _ _ _ _ _ _) + (fun a ha => feasible_weight_one A alpha a ha) + (by + intro a hw hbad + rcases infeasible_in_far_or_near A alpha gamma K ha hg1 hscale a hw hbad with hf|⟨t,ht,hn⟩ + · exact Or.inl hf + · exact Or.inr ⟨⟨t,ht⟩,hn⟩) + change physicalMass A alpha ≤ _ at hh + rw [feasible_sum_eq_tableCount] at hh + apply hh.trans_eq + congr 1 + apply Finset.sum_congr rfl + intro t _ + unfold nearMass + apply Finset.sum_congr rfl + intro a _ + by_cases ha : a t.val∈cellPositions A t.val gamma <;> simp only [ha,ite_true,ite_false] + +/-- This is the literal terminal normalizer estimate. The finite table +bijection, root integrality, far bound and actual tree-marginal estimates +are all proved. Arithmetic conditions below are discharged by the +manuscript's explicit choices of K, gamma and the final coefficient. -/ +theorem terminal_count_estimate (A : Instance I J) (E : Endpoints A) + (alpha gamma epsilon : ℝ) (B K : ℕ) + (ha : 0 < alpha) (hg : 0 < gamma) (hg1 : gamma ≤ 1) + (he : 0 < epsilon) (he1 : epsilon < 1) + (hscale : 4*(K:ℝ) ≤ alpha*gamma) (hnear : 4*(A.d:ℝ)*gamma*K ≤ epsilon/128) + (hfar : (2:ℝ)^(-(3*K:ℕ):ℝ) ≤ epsilon/128) + (hW : 20*A.d ≤ A.W) (hB : (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^B) + (hBK : 2*B ≤ K) (hK : 0 < K) : + tableCount A ≤ CommonBasesFPRAS.slotTotal TwoLiftStates.pairs (f A alpha) ∅ ∧ + CommonBasesFPRAS.slotTotal TwoLiftStates.pairs (f A alpha) ∅ ≤ (1+epsilon/32)*tableCount A := by + rw [normalizer_eq_physical_mass] + have hZM : tableCount A ≤ physicalMass A alpha := table_count_le_mass A alpha + have hM1 := (tableCount_ge_one A).trans hZM + have hM : 0 ≤ physicalMass A alpha := by linarith + have hcover := mass_le_table_far_near A alpha gamma K ha hg1 hscale + have hfarMass := (far_mass_le A alpha B K hW hB hBK).trans hfar + have hfarScaled : (∑ a : Profiles (cellWidth A),if 4*(K:ℝ) ≤ alpha*actualPenalty A a + then actualWeight A alpha a else 0) ≤ (epsilon/128)*physicalMass A alpha := by + exact hfarMass.trans (by + simpa only [mul_one] using mul_le_mul_of_nonneg_left hM1 + (show 0 ≤ epsilon/128 by positivity)) + have hnearMass := total_near_mass_le A E alpha gamma ha.le hg hW B K hB hBK hK + have hnearScaled : (∑ t : TreeCell A,nearMass A alpha t.val gamma) ≤ + (epsilon/128)*physicalMass A alpha := + hnearMass.trans (mul_le_mul_of_nonneg_right hnear hM) + have hbad : physicalMass A alpha ≤ tableCount A+(epsilon/64)*physicalMass A alpha := by + linarith + exact TerminalMassCover.relative_count_bound (tableCount A) (physicalMass A alpha) epsilon + (by linarith [tableCount_ge_one A]) he he1 hZM hbad + +end ContingencyTables.CompanionTerminalMass + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTerminalParameters.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTerminalParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..72ca93cd85a9a41a7cac1815fcd23beb974ea18a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTerminalParameters.lean @@ -0,0 +1,101 @@ +import Mathlib.Analysis.SpecialFunctions.Log.Base +import Mathlib.Algebra.Order.Floor.Semiring +import Mathlib.Algebra.Order.Archimedean.Real.Basic +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.FieldSimp +import Lean.Elab.Tactic.Omega + +namespace OAI + +/-! # The companion's literal terminal parameter choices -/ + +namespace ContingencyTables.CompanionTerminalParameters + +noncomputable def precision (epsilon : ℝ) : ℕ := Nat.ceil (Real.logb 2 (1/epsilon)) + +noncomputable def allowance (L d : ℕ) (epsilon : ℝ) : ℕ := + 20*(L+d+precision epsilon+1) + +noncomputable def gamma (L d : ℕ) (epsilon : ℝ) : ℝ := + epsilon/(512*(d:ℝ)*allowance L d epsilon) + +noncomputable def coefficient (L d : ℕ) (epsilon : ℝ) : ℕ := + Nat.ceil (4*(allowance L d epsilon:ℝ)/gamma L d epsilon) + +lemma allowance_positive (L d : ℕ) (epsilon : ℝ) : 0 < allowance L d epsilon := by + unfold allowance + omega + +lemma allowance_bits (L d : ℕ) (epsilon : ℝ) : 2*L ≤ allowance L d epsilon := by + unfold allowance + omega + +lemma gamma_positive (L d : ℕ) (epsilon : ℝ) (hd : 1 ≤ d) (he : 0 < epsilon) : + 0 < gamma L d epsilon := by + have hdR : (0:ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hK : (0:ℝ) < allowance L d epsilon := by exact_mod_cast allowance_positive L d epsilon + unfold gamma + positivity + +lemma gamma_le_one (L d : ℕ) (epsilon : ℝ) (hd : 1 ≤ d) + (he1 : epsilon < 1) : gamma L d epsilon ≤ 1 := by + have hdR : (1:ℝ) ≤ d := by exact_mod_cast hd + have hKR : (1:ℝ) ≤ allowance L d epsilon := by + exact_mod_cast (show 1 ≤ allowance L d epsilon from allowance_positive L d epsilon) + unfold gamma + apply (div_le_one (by positivity)).mpr + nlinarith [mul_le_mul hdR hKR (by norm_num : (0:ℝ) ≤ 1) (by positivity : (0:ℝ) ≤ d)] + +lemma near_fraction (L d : ℕ) (epsilon : ℝ) (hd : 1 ≤ d) : + 4*(d:ℝ)*gamma L d epsilon*allowance L d epsilon=epsilon/128 := by + have hd0 : (d:ℝ) ≠ 0 := Nat.cast_ne_zero.mpr (by omega) + have hK0 : (allowance L d epsilon:ℝ) ≠ 0 := + Nat.cast_ne_zero.mpr (Nat.ne_of_gt (allowance_positive L d epsilon)) + unfold gamma + field_simp [hd0,hK0] + ring + +lemma coefficient_positive (L d : ℕ) (epsilon : ℝ) (hd : 1 ≤ d) (he : 0 < epsilon) : + 0 < coefficient L d epsilon := by + apply Nat.one_le_ceil_iff.mpr + have hK : (0:ℝ) < allowance L d epsilon := by exact_mod_cast allowance_positive L d epsilon + exact div_pos (by positivity) (gamma_positive L d epsilon hd he) + +lemma terminal_scale (L d : ℕ) (epsilon : ℝ) (hd : 1 ≤ d) (he : 0 < epsilon) : + 4*(allowance L d epsilon:ℝ) ≤ (coefficient L d epsilon:ℝ)*gamma L d epsilon := by + have hg := gamma_positive L d epsilon hd he + have hh := mul_le_mul_of_nonneg_right + (Nat.le_ceil (4*(allowance L d epsilon:ℝ)/gamma L d epsilon)) hg.le + rw [div_mul_cancel₀ _ hg.ne'] at hh + exact hh + +lemma reciprocal_precision (epsilon : ℝ) (he : 0 < epsilon) : + (2:ℝ)^(-(precision epsilon:ℝ)) ≤ epsilon := by + have hq : 1/epsilon ≤ (2:ℝ)^(precision epsilon:ℝ) := by + calc + _ = (2:ℝ)^Real.logb 2 (1/epsilon) := + (Real.rpow_logb (by norm_num) (by norm_num) (by positivity)).symm + _ ≤ _ := Real.rpow_le_rpow_of_exponent_le (by norm_num) (Nat.le_ceil _) + rw [Real.rpow_neg (by norm_num : (0:ℝ) ≤ 2),← one_div] + have hh := one_div_le_one_div_of_le (by positivity : (0:ℝ) < 1/epsilon) hq + simpa using hh + +lemma far_fraction (L d : ℕ) (epsilon : ℝ) (he : 0 < epsilon) : + (2:ℝ)^(-(3*allowance L d epsilon:ℕ):ℝ) ≤ epsilon/128 := by + have hindex : precision epsilon+7 ≤ 3*allowance L d epsilon := by + unfold allowance + omega + calc + _ ≤ (2:ℝ)^(-((precision epsilon:ℝ)+7)) := + Real.rpow_le_rpow_of_exponent_le (by norm_num) (by exact_mod_cast (show + -((3*allowance L d epsilon:ℕ):ℤ) ≤ -((precision epsilon+7:ℕ):ℤ) by omega)) + _ = (2:ℝ)^(-(precision epsilon:ℝ))/128 := by + rw [neg_add,Real.rpow_add (by norm_num : (0:ℝ) < 2)] + norm_num; ring + _ ≤ _ := div_le_div_of_nonneg_right (reciprocal_precision epsilon he) (by norm_num) + +end ContingencyTables.CompanionTerminalParameters + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTerminalRegions.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTerminalRegions.lean new file mode 100644 index 0000000000000000000000000000000000000000..041eeab3391847c9c00ad4493cf3e52cd1e3345c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTerminalRegions.lean @@ -0,0 +1,193 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhysicalTables +import OAI.Combinatorics.ContingencyTables.Counting.CompanionNearMass + +namespace OAI + +/-! # Literal infeasible physical profiles lie in the terminal far or near regions -/ + +namespace ContingencyTables.CompanionTerminalRegions + +open scoped BigOperators Classical +open CompanionFactorialApplication CompanionPhysicalTables CompanionFarMass +open CompanionNearMass ForestPenaltyApplication TreeMarginalSignature BalancedCellFibres +open EqualitySoftening + +variable {I J : Type*} [Fintype I] [Fintype J] + +lemma physicalRow_eq_table (A : Instance I J) (a : Profiles (cellWidth A)) (i : I) (j : J) : + physicalRow (ForestLiteralCount.lower A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) a) i j=(physicalTable A a i j:ℝ) := by + simp only [physicalRow,BalancedCellFibres.profile,Bool.false_eq_true,ite_false,physicalTable, + Int.cast_add,Int.cast_natCast] + +lemma physicalColumn_eq_table (A : Instance I J) (a : Profiles (cellWidth A)) (i : I) (j : J) : + physicalColumn (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) a) i j=(physicalTable A a i j:ℝ) := by + have hk : (a (i,j)).val ≤ cellWidth A (i,j) := Nat.le_of_lt_succ (a (i,j)).isLt + simp only [physicalColumn,BalancedCellFibres.profile,ite_true,Nat.cast_sub hk] + change (ForestLiteralCount.lower A.T A.d A.b i j:ℝ)+(cellWidth A (i,j):ℝ)- + ((cellWidth A (i,j):ℝ)-((a (i,j)).val:ℝ))=(physicalTable A a i j:ℝ) + simp only [physicalTable,Int.cast_add,Int.cast_natCast] + ring + +noncomputable def integerDeviation (A : Instance I J) (a : Profiles (cellWidth A)) : I⊕J → ℤ := + Sum.elim (fun i => (∑ j,physicalTable A a i j)-A.r i) + (fun j => (∑ i,physicalTable A a i j)-A.c j) + +lemma deviation_eq_integer (A : Instance I J) (a : Profiles (cellWidth A)) (v : I⊕J) : + deviation (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) + A.r A.c (BalancedCellFibres.profile (cellWidth A) a) v=(integerDeviation A a v:ℝ) := by + cases v with + | inl i => + simp only [deviation,integerDeviation,Sum.elim_inl] + simp_rw [physicalRow_eq_table] + push_cast + rfl + | inr j => + simp only [deviation,integerDeviation,Sum.elim_inr] + simp_rw [physicalColumn_eq_table] + push_cast + rfl + +lemma nonTree_bounded (A : Instance I J) (a : Profiles (cellWidth A)) (i : I) (j : J) + (ht : ¬A.T.Adj (.inl i) (.inr j)) : + 0 ≤ physicalTable A a i j ∧ physicalTable A a i j ≤ A.b i j := by + have hk : (a (i,j)).val ≤ cellWidth A (i,j) := Nat.le_of_lt_succ (a (i,j)).isLt + simp only [cellWidth,ForestLiteralCount.width,ht,ite_false] at hk + simp only [physicalTable,ForestLiteralCount.lower,ht,ite_false,zero_add] + exact ⟨Nat.cast_nonneg _,by exact_mod_cast hk⟩ + +lemma treePenalty_nonnegative (A : Instance I J) (a : Profiles (cellWidth A)) : + 0 ≤ treePenalty A.T A.b (ForestLiteralCount.lower A.T A.d A.b) + (BalancedCellFibres.profile (cellWidth A) a) := by + unfold treePenalty + apply Finset.sum_nonneg + intro i _ + apply Finset.sum_nonneg + intro j _ + split_ifs + · exact div_nonneg (le_max_left _ _) (Nat.cast_nonneg _) + · exact le_rfl + +lemma rootPenalty_nonnegative (A : Instance I J) (a : Profiles (cellWidth A)) : + 0 ≤ rootPenalty A.T (ForestLiteralCount.lower A.T A.d A.b) + (ForestLiteralCount.width A.T A.d A.b) A.r A.c (BalancedCellFibres.profile (cellWidth A) a) := by + unfold rootPenalty + apply Finset.sum_nonneg + intro v _ + split_ifs <;> first | exact abs_nonneg _ | exact le_rfl + +lemma root_deviation_le_penalty (A : Instance I J) (a : Profiles (cellWidth A)) (v : I⊕J) + (hv : rootFlag A.T v=true) : |(integerDeviation A a v:ℝ)| ≤ actualPenalty A a := by + have hh := Finset.single_le_sum + (f := fun g => if rootFlag A.T g then + |deviation (ForestLiteralCount.lower A.T A.d A.b) (ForestLiteralCount.width A.T A.d A.b) + A.r A.c (BalancedCellFibres.profile (cellWidth A) a) g| else 0) + (fun g _ => by split_ifs <;> first | exact abs_nonneg _ | exact le_rfl) + (Finset.mem_univ v) + simp only [hv,ite_true,deviation_eq_integer] at hh + exact hh.trans (by + unfold actualPenalty penalty rootPenalty + simp_rw [deviation_eq_integer] + linarith [treePenalty_nonnegative A a]) + +lemma tree_distance_le_penalty (A : Instance I J) (a : Profiles (cellWidth A)) (t : I×J) + (ht : A.T.Adj (.inl t.1) (.inr t.2)) : + max 0 (max (-(physicalTable A a t.1 t.2:ℝ)) + ((physicalTable A a t.1 t.2:ℝ)-A.b t.1 t.2))/(A.b t.1 t.2:ℝ) ≤ actualPenalty A a := by + let z := BalancedCellFibres.profile (cellWidth A) a + let D : I → J → ℝ := fun i j => if A.T.Adj (.inl i) (.inr j) then + affineDistance (ForestLiteralCount.lower A.T A.d A.b i j) 1 (A.b i j) (z ((i,j),false)) / + (A.b i j:ℝ) else 0 + have hD (i : I) (j : J) : 0 ≤ D i j := by + dsimp only [D] + split_ifs + · exact div_nonneg (le_max_left _ _) (Nat.cast_nonneg _) + · exact le_rfl + have hinner := Finset.single_le_sum (fun j _ => hD t.1 j) (Finset.mem_univ t.2) + have houter := Finset.single_le_sum + (f := fun i => ∑ j,D i j) + (fun i _ => Finset.sum_nonneg (fun j _ => hD i j)) (Finset.mem_univ t.1) + have hh : D t.1 t.2 ≤ treePenalty A.T A.b (ForestLiteralCount.lower A.T A.d A.b) z := + hinner.trans houter + dsimp only [D] at hh + rw [ite_eq_left ht] at hh + simp only [affineDistance,mul_one] at hh + have hrow := physicalRow_eq_table A a t.1 t.2 + change (ForestLiteralCount.lower A.T A.d A.b t.1 t.2:ℝ)+(z ((t.1,t.2),false):ℝ)=_ at hrow + rw [hrow] at hh + exact hh.trans (by + unfold actualPenalty penalty + linarith [rootPenalty_nonnegative A a]) + +/-- Positive mass and penalty below one force every literal margin to +hold: nonroots are exact indicators and root discrepancies are integral. -/ +lemma margins_of_small_penalty (A : Instance I J) (alpha : ℝ) + (a : Profiles (cellWidth A)) (hw : 0 < actualWeight A alpha a) + (hp : actualPenalty A a < 1) : + (∀ i,(∑ j,physicalTable A a i j)=A.r i) ∧ + (∀ j,(∑ i,physicalTable A a i j)=A.c j) := by + have hnonroot : ∀ v,rootFlag A.T v=false → integerDeviation A a v=0 := by + have hh := hw + unfold actualWeight at hh + rw [exact_eq] at hh + split_ifs at hh with h + · intro v hv + have hz := h v hv + rw [deviation_eq_integer] at hz + exact_mod_cast hz + · exact False.elim (lt_irrefl 0 hh) + have hall (v : I⊕J) : integerDeviation A a v=0 := by + cases hv : rootFlag A.T v + · exact hnonroot v hv + · have hh := (root_deviation_le_penalty A a v hv).trans_lt hp + have hz : |integerDeviation A a v| < (1:ℤ) := by exact_mod_cast hh + have hz' := abs_lt.mp hz + omega + constructor + · intro i + have hh := hall (.inl i) + simpa only [integerDeviation,Sum.elim_inl,sub_eq_zero] using hh + · intro j + have hh := hall (.inr j) + simpa only [integerDeviation,Sum.elim_inr,sub_eq_zero] using hh + +theorem infeasible_in_far_or_near (A : Instance I J) (alpha gamma : ℝ) (K : ℕ) + (ha : 0 < alpha) (hg1 : gamma ≤ 1) (hscale : 4*(K:ℝ) ≤ alpha*gamma) + (a : Profiles (cellWidth A)) (hw : 0 < actualWeight A alpha a) (hbad : ¬Feasible A a) : + 4*(K:ℝ) ≤ alpha*actualPenalty A a ∨ + ∃ t : I×J,A.T.Adj (.inl t.1) (.inr t.2) ∧ a t ∈ cellPositions A t gamma := by + by_cases hfar : 4*(K:ℝ) ≤ alpha*actualPenalty A a + · exact Or.inl hfar + right + have hp : actualPenalty A a < gamma := by + have hh : alpha*actualPenalty A a < alpha*gamma := (lt_of_not_ge hfar).trans_le hscale + exact lt_of_mul_lt_mul_left hh ha.le + have hm := margins_of_small_penalty A alpha a hw (hp.trans_le hg1) + have hcell : ¬∀ i j,0 ≤ physicalTable A a i j ∧ physicalTable A a i j ≤ A.b i j := by + intro hc + exact hbad ⟨hc,hm⟩ + obtain ⟨i,hi⟩ := not_forall.mp hcell + obtain ⟨j,hviol⟩ := not_forall.mp hi + have ht : A.T.Adj (.inl i) (.inr j) := by + by_contra ht + exact hviol (nonTree_bounded A a i j ht) + refine ⟨(i,j),ht,?_⟩ + have hb : (0:ℝ) < A.b i j := by exact_mod_cast (A.hlarge i j (A.hTG ht)).2 + have hd := (tree_distance_le_penalty A a (i,j) ht).trans_lt hp + have hdist : max 0 (max (-(physicalTable A a i j:ℝ)) + ((physicalTable A a i j:ℝ)-A.b i j)) < gamma*A.b i j := (div_lt_iff₀ hb).mp hd + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + change ((physicalTable A a i j<0) ∧ -(physicalTable A a i j:ℝ) hviol ⟨hlo,hhi⟩),?_⟩ + exact (le_max_right _ _).trans (le_max_right _ _) |>.trans_lt hdist + · left + exact ⟨lt_of_not_ge hlo,(le_max_left _ _).trans (le_max_right _ _) |>.trans_lt hdist⟩ + +end ContingencyTables.CompanionTerminalRegions + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrace.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrace.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c240ff59c57e4f4f55e360e0995c5551110bc92 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrace.lean @@ -0,0 +1,234 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMinMass +import OAI.Combinatorics.ContingencyTables.Counting.CompanionConcentration +import OAI.Combinatorics.ContingencyTables.Transport.TraceBounds + +namespace OAI + +/-! # Trace restart bounds for the literal companion weights + +The actual factorial lifts supply the trace inverse gap, and exact +binomial cancellation supplies its minimum mass. The restart stage +therefore has a two-warm endpoint from every initial subprobability law. +-/ + +namespace ContingencyTables.CompanionTrace + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication CompanionAnnealing TwoLiftStates +open CompanionConcentration BinaryContraction DegreeCompletion TraceBounds ObservableBounds + +variable {I J : Type*} [Fintype I] [Fintype J] + +private lemma restart_exponential (M : ℕ) : + Real.exp (-2*((M:ℝ)+5))/(1/2:ℝ)^M ≤ 1 := by + have h2 : (2:ℝ) ≤ Real.exp 2 := by + linarith [Real.add_one_le_exp (2:ℝ)] + have he : Real.exp (-2:ℝ) ≤ 1/2 := by + rw [Real.exp_neg] + simpa only [one_div] using one_div_le_one_div_of_le (by norm_num) h2 + have hp := pow_le_pow_left₀ (Real.exp_nonneg (-2)) he M + have h10 : Real.exp (-10:ℝ) ≤ 1 := Real.exp_le_one_iff.mpr (by norm_num) + have hid : Real.exp (-2*((M:ℝ)+5))=Real.exp (-2:ℝ)^M*Real.exp (-10:ℝ) := by + rw [← Real.exp_nat_mul,← Real.exp_add] + congr 1 + ring + rw [hid,div_le_one (by positivity : (0:ℝ) < (1/2:ℝ)^M)] + exact (mul_le_of_le_one_right (pow_nonneg (Real.exp_nonneg _) _) h10).trans hp + +def integerConstant (A : Instance I J) : ℕ := + let p := Fintype.card (Labels A) + 10*p^4*(9*(p*(1+8*p*A.W^4))+2*(8+32*p*A.W^6)) + +lemma integerConstant_cast (A : Instance I J) : + (integerConstant A:ℝ)=observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := by + unfold integerConstant observableConstant + push_cast + ring + +def time (A : Instance I J) (H K : ℕ) : ℕ := + 2*integerConstant A*(H+Fintype.card (Labels A)+K+5) + +noncomputable def trace (A : Instance I J) (j : ℕ) (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0 < w p r) : FiniteChain (PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) := + metropolisTrace pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w + (completeDegree (weight A j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length) + hw (completeDegree_positive _ _ (actual_degree A j).1) + +lemma trace_pi (A : Instance I J) (j : ℕ) (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0 < w p r) (S : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + (trace A j hp w hw).π S=CompanionWarmStart.law A j S.val.val := by + exact completed_trace_pi pairs PairedLabels.fresh (pairs_ne_nil A hp) PairedLabels.cover w + (weight A j) hw (actual_degree A j).1 S + +private lemma actual_dual_degree (A : Instance I J) (j : ℕ) : + DegreePositive (g A ((j:ℝ)/scale A)) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length ∧ + AdditionProperty (g A ((j:ℝ)/scale A)) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length := by + have hg := second_properties A ((j:ℝ)/scale A) + (div_nonneg (Nat.cast_nonneg j) (scale_positive A).le) + simpa only [PairedLabels.length] using hg + +private lemma actual_plain_agreement (A : Instance I J) (j : ℕ) + (S : Set (Labels A×Bool)) (hS : PlainState pairs S) : + weight A j S=g A ((j:ℝ)/scale A) S := by + exact (plain_lifts_agree (labelCell A) (h A ((j:ℝ)/scale A)) S hS).symm + +private lemma actual_lift_comparison (A : Instance I J) (j : ℕ) + (S : Set (Labels A×Bool)) (hS : ChainState pairs S) : + weight A j S≤(A.W:ℝ)^2*g A ((j:ℝ)/scale A) S := by + apply firstLift_le_square_secondLift (labelCell A) (h A ((j:ℝ)/scale A)) S hS A.W + (by have hW := A.hW; omega) + · intro s + rw [label_width] + exact A.hsmall _ _ s.property + · exact (h_positive A _ _).le + +private lemma omission_instance {X : Type*} [Fintype X] + (d e : DecidableEq X) (f : Set X → ℝ) (k : ℕ) + (h : @OmissionProperty X _ d f k) : @OmissionProperty X _ e f k := by + cases Subsingleton.elim d e + exact h + +private lemma addition_instance {X : Type*} [Fintype X] + (d e : DecidableEq X) (f : Set X → ℝ) (k : ℕ) + (h : @AdditionProperty X _ d f k) : @AdditionProperty X _ e f k := by + cases Subsingleton.elim d e + exact h + +private lemma trace_poincare_raw (A : Instance I J) (j : ℕ) (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A j) w) + (H : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) : + (trace A j hp w hw.positive).variance H ≤ + (2*(Fintype.card (Labels A):ℝ)^2*((Fintype.card (Labels A):ℝ)* + (1+8*(Fintype.card (Labels A):ℝ)*((A.W:ℝ)^2)^2)))* + (trace A j hp w hw.positive).energy H := by + let d : DecidableEq (Labels A×Bool) := inferInstance + have hsigf := omission_instance (inferInstance : DecidableEq (Labels A×Bool)) d + (weight A j) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length (actual_degree A j).2 + have hsigg := addition_instance (inferInstance : DecidableEq (Labels A×Bool)) d + (g A ((j:ℝ)/scale A)) (pairs : List ((Labels A×Bool)×(Labels A×Bool))).length + (actual_dual_degree A j).2 + have hh := @omission_trace_poincare (Labels A×Bool) inferInstance d + pairs PairedLabels.fresh (pairs_ne_nil A hp) + PairedLabels.cover w (weight A j) (g A ((j:ℝ)/scale A)) hw.positive + (actual_degree A j).1 (actual_dual_degree A j).1 + hsigf hsigg + ((A.W:ℝ)^2) (sq_nonneg _) hw.lower + (actual_plain_agreement A j) (actual_lift_comparison A j) H + change (trace A j hp w hw.positive).variance H ≤ + (2*((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)^2)* + (((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)* + (1+8*((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)*((A.W:ℝ)^2)^2))* + (trace A j hp w hw.positive).energy H at hh + have hcoef : (2*((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)^2)* + (((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)* + (1+8*((pairs : List ((Labels A×Bool)×(Labels A×Bool))).length:ℝ)*((A.W:ℝ)^2)^2))= + 2*(Fintype.card (Labels A):ℝ)^2*((Fintype.card (Labels A):ℝ)* + (1+8*(Fintype.card (Labels A):ℝ)*((A.W:ℝ)^2)^2)) := by + rw [PairedLabels.length] + exact hh.trans_eq (congrArg (fun k : ℝ => k*(trace A j hp w hw.positive).energy H) hcoef) + +theorem trace_poincare (A : Instance I J) (j : ℕ) (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A j) w) + (H : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) : + (trace A j hp w hw.positive).variance H ≤ + observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)* + (trace A j hp w hw.positive).energy H := by + have hpR : (1:ℝ) ≤ Fintype.card (Labels A) := by exact_mod_cast hp + have hcoef := trace_constant_le_observable (Fintype.card (Labels A)) ((A.W:ℝ)^2) + hpR (square_width_one_le A) + exact (trace_poincare_raw A j hp w hw H).trans + (mul_le_mul_of_nonneg_right hcoef ((trace A j hp w hw.positive).energy_nonneg H)) + +noncomputable def minimumMass (A : Instance I J) (H K : ℕ) : ℝ := + (1/2:ℝ)^(H+Fintype.card (Labels A)+K) + +lemma minimumMass_positive (A : Instance I J) (H K : ℕ) : 0 < minimumMass A H K := by + unfold minimumMass + positivity + +/-- The manuscript's literal integer restart schedule gives pointwise +relative error at most one with the proved minimum mass. -/ +theorem schedule_error (A : Instance I J) (H K : ℕ) + (hp : 0 < Fintype.card (Labels A)) : + Real.exp (-(time A H K:ℝ)/observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2))/ + minimumMass A H K ≤ 1 := by + have hpR : (0:ℝ) < Fintype.card (Labels A) := by exact_mod_cast hp + have hp1 : (1:ℝ) ≤ Fintype.card (Labels A) := by exact_mod_cast hp + have hbound := observableConstant_lower (Fintype.card (Labels A)) ((A.W:ℝ)^2) + hp1 (square_width_one_le A) + have hconst : 0 < observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := + lt_of_lt_of_le (by positivity) hbound + have hexp : -(time A H K:ℝ)/observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2)= + -2*((H+Fintype.card (Labels A)+K:ℕ)+5:ℝ) := by + unfold time + push_cast + rw [integerConstant_cast] + field_simp [hconst.ne'] + rw [hexp] + exact restart_exponential (H+Fintype.card (Labels A)+K) + +lemma trace_minimum (A : Instance I J) (H K j : ℕ) (hj : j ≤ H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^K) + (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : ∀ p r,0 < w p r) (S : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + minimumMass A H K ≤ (trace A j hp w hw).π S := by + rw [trace_pi] + apply le_trans _ (CompanionMinMass.law_lower A K j hB S.val.val S.property) + exact pow_le_pow_of_le_one (by norm_num : (0:ℝ) ≤ 1/2) (by norm_num) (by omega) + +/-- The pointwise error estimate has no new signature or minimum-mass +assumption: both are supplied by the actual count/lift application. -/ +theorem trace_point_mixing (A : Instance I J) (H K j : ℕ) (hj : j ≤ H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^K) + (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A j) w) (t : ℕ) + (x y : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + |((trace A j hp w hw.positive).kernel.power t).P x y/ + CompanionWarmStart.law A j y.val.val-1| ≤ + Real.exp (-(t:ℝ)/observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2))/minimumMass A H K := by + let T := trace A j hp w hw.positive + have hpR : (1:ℝ) ≤ Fintype.card (Labels A) := by exact_mod_cast hp + have hK : 1 ≤ observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2) := by + have hh := observableConstant_lower (Fintype.card (Labels A)) ((A.W:ℝ)^2) + hpR (square_width_one_le A) + have hp5 : (1:ℝ) ≤ (Fintype.card (Labels A):ℝ)^5 := one_le_pow₀ hpR + nlinarith + have hh := T.kernel_point_mixing _ _ hK (minimumMass_positive A H K) + (trace_minimum A H K j hj hB hp w hw.positive) (trace_poincare A j hp w hw) t x y + rwa [trace_pi] at hh + +/-- A stage with pointwise relative error at most one ends two-warm, +even when its incoming law is merely a subprobability law. -/ +theorem stage_warm (A : Instance I J) (H K j : ℕ) (hj : j ≤ H) + (hB : (∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) ≤ (2:ℝ)^K) + (hp : 0 < Fintype.card (Labels A)) + (w : ((Labels A×Bool)×(Labels A×Bool)) → ((Labels A×Bool)×(Labels A×Bool)) → ℝ) + (hw : GoodMultipliers pairs (weight A j) w) (t : ℕ) + (ht : Real.exp (-(t:ℝ)/observableConstant (Fintype.card (Labels A)) ((A.W:ℝ)^2))/minimumMass A H K ≤ 1) + (nu : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool))) → ℝ) + (hnu : ∀ S,0 ≤ nu S) (hmass : ∑ S,nu S ≤ 1) + (y : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + ((trace A j hp w hw.positive).kernel.power t).push nu y ≤ 2*CompanionWarmStart.law A j y.val.val := by + have hy : 0 < CompanionWarmStart.law A j y.val.val := + div_pos (weight_positive A j _) (CompanionWarmStart.total_positive A j) + have hrow (x : PlainIndex (pairs : List ((Labels A×Bool)×(Labels A×Bool)))) : + ((trace A j hp w hw.positive).kernel.power t).P x y ≤ + 2*CompanionWarmStart.law A j y.val.val := by + have hh := (le_abs_self _).trans ((trace_point_mixing A H K j hj hB hp w hw t x y).trans ht) + apply (div_le_iff₀ hy).mp + linarith + calc + _ ≤ ∑ x,nu x*(2*CompanionWarmStart.law A j y.val.val) := + Finset.sum_le_sum (fun x _ => mul_le_mul_of_nonneg_left (hrow x) (hnu x)) + _ = (∑ x,nu x)*(2*CompanionWarmStart.law A j y.val.val) := by rw [Finset.sum_mul] + _ ≤ _ := by nlinarith + +end ContingencyTables.CompanionTrace + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTraceProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTraceProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..565cfdb33835f952b35f14bc23bd91534dae7193 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTraceProgram.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTraceWords +import OAI.Combinatorics.ContingencyTables.Counting.CompanionNeighborProgram + +namespace OAI + +/-! # Polynomial code for recognizing and locating a trace return + +The paired plain-state test sums the two bits of each label. The return +program scans the supplied path after its initial state; no enumeration +of the exponential paired-state space occurs. +-/ + +namespace ContingencyTables.CompanionTraceProgram + +open CommonBasesFPRAS CompanionChainValidator CompanionArithmeticProposal +open CompanionFactorialApplication CompanionBooleanPhase CompanionTraceWords +open ProfilePrograms MatchingFPRAS.TreeTyped +open scoped Classical + +def pairedPlainTest (z : ValidatorInput) : Bool := + balancedTest ((z.1.map (fun ij => z.2.getD ij.1 0), + z.1.map (fun ij => z.2.getD ij.2 0)),1) + +def pairedPlainTestRealizer : Realizer pairedPlainTest := + composition (pair (pair + (composition (pair second first) (mapWith pairFirstLookup)) + (composition (pair second first) (mapWith pairSecondLookup))) (constant 1)) + balancedTestRealizer + +theorem polynomial_pairedPlainTest : PolynomialTime pairedPlainTestRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_pairFirstLookup)) + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_pairSecondLookup))) (polynomial_constant 1)) + polynomial_balancedTest + +abbrev ReturnInput := List (ℕ×ℕ)×List (List ℕ) + +def firstPlainCode (z : ReturnInput) : Option (List ℕ) := + (z.2.filter (fun xs => pairedPlainTest (z.1,xs)))[0]? + +def firstPlainCodeRealizer : Realizer firstPlainCode := + composition (composition (filterWith pairedPlainTestRealizer) + (pair identity (constant 0))) getOptionFast + +theorem polynomial_firstPlainCode : PolynomialTime firstPlainCodeRealizer := + polynomial_composition (polynomial_composition + (polynomial_filterWith polynomial_pairedPlainTest) + (polynomial_pair polynomial_identity (polynomial_constant 0))) polynomial_getOptionFast + +/-- Strict first return: the initial path entry is omitted. -/ +def returnCode (z : ReturnInput) : Option (List ℕ) := + firstPlainCode (z.1,z.2.tail) + +def returnCodeRealizer : Realizer returnCode := + composition (pair first (composition second tail)) firstPlainCodeRealizer + +theorem polynomial_returnCode : PolynomialTime returnCodeRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_tail)) polynomial_firstPlainCode + +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +theorem pairedPlainTest_encode (A : Instance I J) (S : Set (Labels A×Bool)) : + pairedPlainTest (pairCatalog A,encodeSet (coordinateEquiv A) S)=true ↔ + PlainState TwoLiftStates.pairs S := by + unfold pairedPlainTest pairCatalog + simp only [List.map_ofFn] + change balancedTest ((List.ofFn (fun i : Fin (Fintype.card (Labels A)) => + (encodeSet (coordinateEquiv A) S).getD + (coordinateEquiv A (labelEquiv A i,false)).val 0), + List.ofFn (fun i : Fin (Fintype.card (Labels A)) => + (encodeSet (coordinateEquiv A) S).getD + (coordinateEquiv A (labelEquiv A i,true)).val 0)),1)=true ↔ _ + simp only [encodeSet,getD_setProfile,setProfile,coordinateSet,Set.mem_preimage, + Equiv.symm_apply_apply] + rw [balancedTest_ofFn,plain_iff_occupancy] + change (∀ i,TwoLiftStates.occupancy S (labelEquiv A i)=1) ↔ + ∀ p,TwoLiftStates.occupancy S p=1 + constructor + · intro h p + simpa only [Equiv.apply_symm_apply] using h ((labelEquiv A).symm p) + · intro h i + exact h (labelEquiv A i) + +/-- The list program returns the encoding of the same first plain +state as the semantic scan, including the no-return outcome. -/ +theorem firstPlainCode_encode (A : Instance I J) (xs : List (State A)) : + firstPlainCode (pairCatalog A,xs.map (fun S => encodeSet (coordinateEquiv A) S.val))= + (firstHit (plainPredicate TwoLiftStates.pairs) xs).map + (fun T => encodeSet (coordinateEquiv A) T.val.val) := by + induction xs with + | nil => simp [firstPlainCode,firstHit] + | cons S xs ih => + unfold firstPlainCode at ih ⊢ + simp only [List.map_cons,List.filter_cons,firstHit] + by_cases h : PlainState TwoLiftStates.pairs S.val + · have ht : pairedPlainTest (pairCatalog A,encodeSet (coordinateEquiv A) S.val)=true := + (pairedPlainTest_encode A S.val).mpr h + simp only [ht,ite_true,plainPredicate,dite_eq_left h,Option.map_some,List.getElem?_cons_zero] + · have ht : pairedPlainTest (pairCatalog A,encodeSet (coordinateEquiv A) S.val)=false := by + apply Bool.eq_false_iff.mpr + intro ht + exact h ((pairedPlainTest_encode A S.val).mp ht) + simpa only [ht,Bool.false_eq_true,ite_false,plainPredicate,dite_eq_right h] using ih + +theorem returnCode_encode (A : Instance I J) (xs : List (State A)) : + returnCode (pairCatalog A,xs.map (fun S => encodeSet (coordinateEquiv A) S.val))= + (firstHit (plainPredicate TwoLiftStates.pairs) xs.tail).map + (fun T => encodeSet (coordinateEquiv A) T.val.val) := by + unfold returnCode + rw [← List.map_tail] + exact firstPlainCode_encode A xs.tail + +end +end ContingencyTables.CompanionTraceProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTraceWords.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTraceWords.lean new file mode 100644 index 0000000000000000000000000000000000000000..4da8df7d66100901b50bfb6a1a9cc6d9afe785d3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTraceWords.lean @@ -0,0 +1,304 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionArithmeticStep +import OAI.Combinatorics.ContingencyTables.Machines.FiniteTraceSlowdown + +namespace OAI + +/-! # Capped trace returns from the actual companion Boolean walk + +The return search scans the recorded path after its initial state. Its +reference expectation is the finite Green sum defining the capped trace; +the Boolean walk contributes its path error. +-/ + +namespace ContingencyTables.CompanionTraceWords + +open CommonBasesFPRAS CompanionFactorialApplication CompanionBooleanPhase +open CompanionPhaseTrajectory CompanionOracleDensity CompanionWeightOracle +open CompanionRationalUpdates TwoLiftStates GridBoundary FirstSuccess ResidualMixture +open scoped BigOperators Classical + +noncomputable section + +variable {X : Type*} + +/-- A fixed indicator convention keeps equivalent event descriptions +independent of the decision procedures inferred for their propositions. -/ +def eventIndicator (P : Prop) : ℝ := @ite ℝ P (Classical.propDecidable P) 1 0 + +lemma eventIndicator_eq (P : Prop) [Decidable P] : + eventIndicator P=(if P then (1:ℝ) else 0) := by + by_cases h : P <;> simp only [eventIndicator,h,ite_true,ite_false] + +def firstHit (B : X → Prop) : List X → Option (FiniteChain.Inside B) + | [] => none + | x::xs => if hx : B x then some ⟨x,hx⟩ else firstHit B xs + +def returnValue (B : X → Prop) (phi : FiniteChain.Inside B → ℝ) (xs : List X) : ℝ := + DrawTree.optionValue phi (firstHit B xs.tail) + +variable [Fintype X] + +private lemma expectation_congr_start (C : FiniteChain X) (n : ℕ) (x : X) + (F G : List X → ℝ) (h : ∀ xs,F (x::xs)=G (x::xs)) : + C.pathExpectation n x F=C.pathExpectation n x G := by + cases n with + | zero => exact h [] + | succ n => + apply Finset.sum_congr rfl + intro y _ + congr 1 + exact C.pathExpectation_congr n y _ _ h + +private lemma firstHit_expectation (C : FiniteChain X) (B : X → Prop) + (phi : FiniteChain.Inside B → ℝ) (n : ℕ) (x : X) : + C.pathExpectation n x (fun xs => DrawTree.optionValue phi (firstHit B xs))= + if hx : B x then phi ⟨x,hx⟩ else C.pathExpectation n x (returnValue B phi) := by + by_cases hx : B x + · rw [dite_eq_left hx] + calc + _ = C.pathExpectation n x (fun _ => phi ⟨x,hx⟩) := by + apply expectation_congr_start + intro xs + simp only [firstHit,dite_eq_left hx,DrawTree.optionValue] + _ = _ := C.pathExpectation_const n x _ + · rw [dite_eq_right hx] + apply expectation_congr_start + intro xs + simp only [firstHit,dite_eq_right hx,returnValue,List.tail_cons] + +private lemma returnValue_succ (C : FiniteChain X) (B : X → Prop) + (phi : FiniteChain.Inside B → ℝ) (n : ℕ) (x : X) : + C.pathExpectation (n+1) x (returnValue B phi)= + ∑ y,C.P x y*(if hy : B y then phi ⟨y,hy⟩ + else C.pathExpectation n y (returnValue B phi)) := by + simp only [FiniteChain.pathExpectation,returnValue,List.tail_cons] + apply Finset.sum_congr rfl + intro y _ + rw [firstHit_expectation] + +private lemma returnValue_split (C : FiniteChain X) (B : X → Prop) + (phi : FiniteChain.Inside B → ℝ) (n : ℕ) (x : X) : + C.pathExpectation (n+1) x (returnValue B phi)= + (∑ y : FiniteChain.Inside B,C.P x y.val*phi y)+ + ∑ y : FiniteChain.Outside B,C.P x y.val*C.pathExpectation n y.val (returnValue B phi) := by + rw [returnValue_succ,←Fintype.sum_subtype_add_sum_subtype B] + congr 1 + · apply Finset.sum_congr rfl + intro y _ + rw [dite_eq_left y.property] + · apply Finset.sum_congr rfl + intro y _ + rw [dite_eq_right y.property] + +private lemma partialGreen_succ (Q : KilledKernel X) (n : ℕ) (f : X → ℝ) (x : X) : + Q.partialGreen (n+1) f x=f x+Q.apply (Q.partialGreen n f) x := by + unfold KilledKernel.partialGreen + rw [Finset.sum_range_succ'] + simp only [KilledKernel.iterate_succ,KilledKernel.iterate_zero] + rw [KilledKernel.apply_sum] + exact add_comm _ _ + +/-- An outside starting state has exactly the truncated Green expectation. -/ +theorem outside_return_expectation (C : FiniteChain X) (B : X → Prop) + (Q : KilledKernel (FiniteChain.Outside B)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) + (phi : FiniteChain.Inside B → ℝ) (n : ℕ) (x : FiniteChain.Outside B) : + C.pathExpectation n x.val (returnValue B phi)= + Q.partialGreen n (fun z => ∑ y : FiniteChain.Inside B,C.P z.val y.val*phi y) x := by + induction n generalizing x with + | zero => simp [FiniteChain.pathExpectation,returnValue,firstHit,DrawTree.optionValue, + KilledKernel.partialGreen] + | succ n ih => + rw [returnValue_split,partialGreen_succ] + congr 1 + unfold KilledKernel.apply + apply Finset.sum_congr rfl + intro y _ + rw [ih,hQ] + +/-- Starting inside and allowing n+1 transitions gives the manuscript's +capped trace, with n possible further outside transitions. -/ +theorem inside_return_expectation (C : FiniteChain X) (B : X → Prop) + (Q : KilledKernel (FiniteChain.Outside B)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) + (phi : FiniteChain.Inside B → ℝ) (n : ℕ) (x : FiniteChain.Inside B) : + C.pathExpectation (n+1) x.val (returnValue B phi)= + ∑ y : FiniteChain.Inside B,C.cappedTrace B Q n x y*phi y := by + rw [returnValue_split] + simp_rw [outside_return_expectation C B Q hQ] + simp only [FiniteChain.cappedTrace,add_mul,Finset.sum_add_distrib] + congr 1 + simp only [Finset.sum_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro z _ + simp only [mul_assoc] + rw [←Finset.mul_sum,KilledKernel.partialGreen_sum] + congr 1 + apply Finset.sum_congr rfl + intro y _ + unfold KilledKernel.partialGreen + simp_rw [show (fun t : FiniteChain.Outside B => C.P t.val y.val*phi y)= + (fun t => phi y*C.P t.val y.val) by funext t; ring] + simp only [KilledKernel.iterate_mul,←Finset.mul_sum] + ring + +omit [Fintype X] in +private lemma option_event (B : X → Prop) (E : FiniteChain.Inside B → Prop) + (o : Option (FiniteChain.Inside B)) : + eventIndicator (∃ y,o=some y ∧ E y)= + DrawTree.optionValue (fun y => if E y then 1 else 0) o := by + cases o <;> simp [eventIndicator,DrawTree.optionValue] + +theorem return_event_expectation (C : FiniteChain X) (B : X → Prop) + (Q : KilledKernel (FiniteChain.Outside B)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) (E : FiniteChain.Inside B → Prop) + (n : ℕ) (x : FiniteChain.Inside B) : + C.pathExpectation (n+1) x.val + (fun xs => eventIndicator (∃ y,firstHit B xs.tail=some y ∧ E y))= + ∑ y : FiniteChain.Inside B,C.cappedTrace B Q n x y*(if E y then 1 else 0) := by + calc + _ = C.pathExpectation (n+1) x.val (returnValue B (fun y => if E y then 1 else 0)) := by + apply C.pathExpectation_congr + intro xs + exact option_event B E (firstHit B xs.tail) + _ = _ := inside_return_expectation C B Q hQ _ n x + +theorem return_failure_expectation (C : FiniteChain X) (B : X → Prop) + (Q : KilledKernel (FiniteChain.Outside B)) + (hQ : ∀ x y,Q.Q x y=C.P x.val y.val) (n : ℕ) (x : FiniteChain.Inside B) : + C.pathExpectation (n+1) x.val + (fun xs => eventIndicator (firstHit B xs.tail=none))= + 1-∑ y : FiniteChain.Inside B,C.cappedTrace B Q n x y := by + have hfun : (fun xs : List X => + eventIndicator (firstHit B xs.tail=none)+returnValue B (fun _ => 1) xs)= + fun _ => (1:ℝ) := by + funext xs + unfold returnValue + cases firstHit B xs.tail <;> simp [eventIndicator,DrawTree.optionValue] + have he := C.pathExpectation_add (n+1) x.val + (fun xs => eventIndicator (firstHit B xs.tail=none)) + (returnValue B (fun _ => 1)) + rw [hfun,C.pathExpectation_const,inside_return_expectation C B Q hQ] at he + simp only [mul_one] at he + linarith + +variable {I J : Type} [Fintype I] [Fintype J] + +def sourceKilled (A : Instance I J) (j : ℕ) (hp : 0 (w p q:ℝ)) (CompanionAnnealing.weight A j) + (fun p q => by exact_mod_cast hw p q) (CompanionAnnealing.weight_positive A j) + +def targetKilled (A : Instance I J) (j : ℕ) (hp : 0 + if E (historyPrefix (CompanionArithmeticStep.recordedWalk A C K j k N N hK hW xi v w S bits)) + then (1:ℝ) else 0)= + uniformAverage (fun bits : Fin (N*stepBits A C K j k xi) → Bool => + if E (historyPrefix (CompanionBooleanPhase.recordedWalk A C K j k N N hK hW xi v w S bits)) + then (1:ℝ) else 0) := by + have hnew := FiniteLawMoments.word_expectation + (CompanionArithmeticStep.recordedWalk A C K j k N N hK hW xi v w S) + (fun a => if E (historyPrefix a) then (1:ℝ) else 0) + have hold := FiniteLawMoments.word_expectation + (CompanionBooleanPhase.recordedWalk A C K j k N N hK hW xi v w S) + (fun a => if E (historyPrefix a) then (1:ℝ) else 0) + rw [CompanionArithmeticStep.recordedWalk_law] at hnew + rw [CompanionBooleanPhase.recordedWalk_law] at hold + exact hnew.trans hold.symm + +theorem arithmetic_recorded_event_bound (A : Instance I J) (C : ℕ) (hC : 0 + eventIndicator (E (historyPrefix + (CompanionArithmeticStep.recordedWalk A C K j k N N hK hW xi v w S bits))))≤ + (targetChain A j hp w hw).pathExpectation N S (fun xs => eventIndicator (E xs))+ + N*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + exact (arithmetic_event_eq A C K j k N hK hW xi v w S E).trans_le + (recorded_event_bound A C hC K j k hK hW hB hj xi hx0 hx1 hPL hCheeger v hp w hw N S E) + +/-- The concrete bounded return experiment has the capped trace event +bound plus one implementation error per used step. -/ +theorem returnWord_event (A : Instance I J) (C : ℕ) (hC : 0 + eventIndicator (∃ T,returnWord A C K j k (n+1) hK hW xi v w S.val bits=some T ∧ E T))≤ + (∑ T,(targetChain A j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A j hp w hw) n S T*eventIndicator (E T))+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + have he := arithmetic_recorded_event_bound A C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw (n+1) S.val + (fun xs => ∃ T,firstHit (plainPredicate pairs) xs.tail=some T ∧ E T) + have ht := return_event_expectation (targetChain A j hp w hw) (plainPredicate pairs) + (targetKilled A j hp w hw) (targetKilled_matches A j hp w hw) E n S + have hfinal := he.trans_eq (congrArg (fun t : ℝ => t+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2)) ht) + exact hfinal + +/-- Capping the concrete word experiment adds the exact reference +nonreturn probability and the accumulated step-implementation error. -/ +theorem returnWord_failure (A : Instance I J) (C : ℕ) (hC : 0 + eventIndicator (returnWord A C K j k (n+1) hK hW xi v w S.val bits=none))≤ + 1-(∑ T,(targetChain A j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A j hp w hw) n S T)+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) := by + have he := arithmetic_recorded_event_bound A C hC K j k hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw (n+1) S.val (fun xs => firstHit (plainPredicate pairs) xs.tail=none) + have ht := return_failure_expectation (targetChain A j hp w hw) (plainPredicate pairs) + (targetKilled A j hp w hw) (targetKilled_matches A j hp w hw) n S + have hfinal := he.trans_eq (congrArg (fun t : ℝ => t+ + ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2)) ht) + exact hfinal + +end +end ContingencyTables.CompanionTraceWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrajectoryLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrajectoryLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..db654933d72008b9d5ea76e49bafa3d7e69e5cf5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrajectoryLaw.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTrajectoryProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnHistoryLaw +import OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseExperiment + +namespace OAI + +/-! # The executed observation trajectory has the selected-root source law -/ +namespace ContingencyTables.CompanionTrajectoryProgram +open MatchingFPRAS CommonBasesFPRAS FirstSuccess ResidualMixture FiniteObservableTransport +open CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionOracleDensity CompanionWeightOracle +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram CompanionPhaseTrajectory +open CompanionBooleanPhase (State) +open RealKernelApproximation GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +theorem observations_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (S : State A) : + SameLaw (fun bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool => + output (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits))) + (fun bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool => + (List.ofFn (RootedPhaseExperiment.observedStates A (RootedCompletion.rowColumn A.T) + C K j k N hK hW xi (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w) S bits)).map + (encodeSet (coordinateOrder A))) := by + let R := RootedCompletion.rowColumn A.T + let v' := RootedCatalogGrid.gridEquiv A K v + let sw := sourceWeights A w + let F := RootedBooleanPhase.step A R C K j k hK hW xi v' sw + let ret := fun a : PathState (State A) N => + (historyPrefix a).map (fun T => encodeSet (coordinateOrder A) T.val) + have hb := RootedBooleanPhase.recordedWalk_law A R C K j k N N hK hW xi v' sw S + have ha := RootedArithmeticStep.recordedWalk_law A R C K j k N N hK hW xi v' sw S + have hm := (SameLaw.of_mapLaw_eq + (RootedBooleanPhase.recordedWalk A R C K j k N N hK hW xi v' sw S) + (RootedArithmeticStep.recordedWalk A R C K j k N N hK hW xi v' sw S) + (hb.trans ha.symm)).map ret + have hleft (bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool) : + ret (RootedBooleanPhase.recordedWalk A R C K j k N N hK hW xi v' sw S bits)= + (traceStates F S (List.ofFn (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi) bits))).map + (fun T => encodeSet (coordinateOrder A) T.val) := by + unfold ret + rw [show historyPrefix (RootedBooleanPhase.recordedWalk A R C K j k N N hK hW xi v' sw S bits)= + traceStates F S (List.ofFn (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi) bits)) from + recorded_prefix F N S N le_rfl _] + have hright (bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool) : + ret (RootedArithmeticStep.recordedWalk A R C K j k N N hK hW xi v' sw S bits)= + (List.ofFn (RootedPhaseExperiment.observedStates A R C K j k N hK hW xi v' sw S bits)).map + (encodeSet (coordinateOrder A)) := by + rw [RootedPhaseExperiment.observedStates_list] + simp only [ret,List.map_map,Function.comp_def] + intro phi + have h := output_sameLaw A C K j k N hC hj hK hW hB xi hxi z v degree depth hdegree hdepth w S phi + have hl : uniformAverage (fun bits => phi (ret + (RootedBooleanPhase.recordedWalk A R C K j k N N hK hW xi v' sw S bits)))= + uniformAverage (fun bits => phi ((traceStates F S + (List.ofFn (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi) bits))).map + (fun T => encodeSet (coordinateOrder A) T.val))) := by + apply congrArg uniformAverage + funext bits + exact congrArg phi (hleft bits) + have hr : uniformAverage (fun bits => phi (ret + (RootedArithmeticStep.recordedWalk A R C K j k N N hK hW xi v' sw S bits)))= + uniformAverage (fun bits => phi ((List.ofFn (RootedPhaseExperiment.observedStates A R + C K j k N hK hW xi v' sw S bits)).map (encodeSet (coordinateOrder A)))) := by + apply congrArg uniformAverage + funext bits + exact congrArg phi (hright bits) + exact h.trans (hl.symm.trans ((hm phi).trans hr)) + +end +end ContingencyTables.CompanionTrajectoryProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrajectoryProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrajectoryProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..18dba597b8b775b8b05d223f8bac57d910c0102e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrajectoryProgram.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionFlatReturnProgram + +namespace OAI + +/-! # The flat executed observation trajectory, including its initial state -/ +namespace ContingencyTables.CompanionTrajectoryProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped +abbrev Input := CompanionFlatReturnProgram.Input + +def output (z : Input) : List (List ℕ) := + CompanionBoundedWalkProgram.history (CompanionFlatReturnProgram.returnInput z) +def outputRealizer : Realizer output := + composition (f := CompanionFlatReturnProgram.returnInput) (g := CompanionBoundedWalkProgram.history) + CompanionFlatReturnProgram.returnInputRealizer CompanionBoundedWalkProgram.historyRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition CompanionFlatReturnProgram.polynomial_returnInput + CompanionBoundedWalkProgram.polynomial_history + +open CommonBasesFPRAS CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionOracleDensity CompanionWeightOracle +open CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram FiniteObservableTransport +open TwoLiftStates GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +theorem output_sameLaw (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) + (hC : 0 < C) (hj : j ≤ rationalHeight A C) (hK : 1 ≤ K) + (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (xi : ℚ) (hxi : 0 < xi) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) (degree depth : List Bool) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))) + (hdepth : depth.length=PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j))) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (S : CompanionBooleanPhase.State A) : + SameLaw (fun bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool => + output (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits))) + (fun bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool => + (traceStates (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) C K j k hK hW xi + (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w)) S + (List.ofFn (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi) bits))).map + (fun T => encodeSet (coordinateOrder A) T.val)) := by + let state := CompanionFlatReturnProgram.stateData A C K j k xi z v degree depth w S + have hs := CompanionBoundedWalkProgram.history_sameLaw A C K j k hC hj hK hW hB xi hxi + z v degree depth hdegree hdepth w S N + dsimp only at hs + intro phi + have hl := uniformAverage_equiv (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi)) + (fun ws => phi (CompanionBoundedWalkProgram.history + (state,List.ofFn (fun i => List.ofFn (ws i))))) + have hr := uniformAverage_equiv (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi)) + (fun ws => phi ((traceStates (RootedBooleanPhase.step A (RootedCompletion.rowColumn A.T) + C K j k hK hW xi (RootedCatalogGrid.gridEquiv A K v) (sourceWeights A w)) S + (List.ofFn ws)).map (fun T => encodeSet (coordinateOrder A) T.val))) + have ho (bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool) : + output (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits))= + CompanionBoundedWalkProgram.history (state,List.ofFn (fun i => List.ofFn + (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi) bits i))) := by + change CompanionBoundedWalkProgram.history + (state,CompanionFlatReturnProgram.words + (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits)))=_ + rw [CompanionFlatReturnProgram.words_data] + have he : uniformAverage (fun bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool => + phi (output (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits))))= + uniformAverage (fun bits => phi (CompanionBoundedWalkProgram.history + (state,List.ofFn (fun i => List.ofFn (gridWordEquiv N (CompanionBooleanPhase.stepBits A C K j k xi) bits i))))) := by + apply congrArg uniformAverage + funext bits + exact congrArg phi (ho bits) + exact he.trans (hl.trans ((hs phi).trans hr.symm)) + +end +end ContingencyTables.CompanionTrajectoryProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTransitionWidth.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTransitionWidth.lean new file mode 100644 index 0000000000000000000000000000000000000000..f87f79ebcd1a12a647d7f0dd83ce15223a9b6617 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTransitionWidth.lean @@ -0,0 +1,62 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisWordSemantics +import OAI.Combinatorics.ContingencyTables.Machines.ScalarScheduleProgram + +namespace OAI + +/-! # Executing the exact companion transition word length -/ + +namespace ContingencyTables.CompanionTransitionWidth + +open MatchingFPRAS MatchingFPRAS.TreeTyped ScalarScheduleProgram +open CompanionMetropolisWordProgram + +def values (z : Input) : List ℕ := [proposalWidth z,queryWidth z,z.1.1.2] +attribute [local irreducible] proposalWidth queryWidth +def valuesRealizer : Realizer values := by + let k : Realizer (fun z : Input => z.1.1.2) := composition (composition first first) second + let ks : Realizer (fun z : Input => [z.1.1.2]) := + composition (f := fun z : Input => (z.1.1.2,([] : List ℕ))) (g := fun p => p.1::p.2) + (pair k (constant [])) listCons + let qs : Realizer (fun z : Input => [queryWidth z,z.1.1.2]) := + composition (f := fun z : Input => (queryWidth z,[z.1.1.2])) (g := fun p => p.1::p.2) + (pair queryWidthRealizer ks) listCons + exact composition (f := fun z : Input => (proposalWidth z,[queryWidth z,z.1.1.2])) + (g := fun p => p.1::p.2) (pair proposalWidthRealizer qs) listCons +lemma polynomial_values : PolynomialTime valuesRealizer := by + unfold valuesRealizer + exact polynomial_composition (polynomial_pair polynomial_proposalWidth + (polynomial_composition (polynomial_pair polynomial_queryWidth + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_constant [])) polynomial_listCons)) polynomial_listCons)) polynomial_listCons + +def expression : Expr := 1+(Expr.input 0+((Expr.input 1+Expr.input 1)+Expr.input 2)) +def width (z : Input) : ℕ := expression.eval (values z) +def widthRealizer : Realizer width := + composition (f := values) (g := expression.eval) valuesRealizer expression.realizer +theorem polynomial_width : PolynomialTime widthRealizer := + polynomial_composition polynomial_values expression.polynomial + +lemma width_eq (z : Input) : width z=1+(proposalWidth z+((queryWidth z+queryWidth z)+z.1.1.2)) := by + rfl + +lemma width_pos (z : Input) : 0 < width z := by rw [width_eq]; omega + +noncomputable section +open CompanionFactorialApplication CompanionComputedInitial CompanionArithmeticProposal +open CompanionOracleDensity CompanionWeightOracle GridBoundary +variable {m n : ℕ} + +theorem width_config (A : Instance (Fin m) (Fin n)) (C K j k : ℕ) (xi : ℚ) + (z : View A → ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : CompanionMultiplierMatrixProgram.FractionMatrix) + (S : Set (Labels A × Bool)) (bits : List Bool) : + width (packed (RootedLabelWeightProgram.config A C K j xi xi z v degree depth,w) + k (encodeSet (coordinateOrder A) S) bits)=CompanionBooleanPhase.stepBits A C K j k xi := by + rw [width_eq,proposalWidth_code,queryWidth_config] + rfl + +end +end ContingencyTables.CompanionTransitionWidth + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrialPadding.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrialPadding.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9f104bccd24b3ff7966c9707906819a7efd7941 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionTrialPadding.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionObservationPadding +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCodeBounds + +namespace OAI + +/-! # The phase trial with an unused query suffix -/ +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS FairBits +open scoped Classical +noncomputable section + +theorem SameLaw.right_padding {U V Z : Type*} [Fintype U] [Fintype V] {n : ℕ} + {f : U×(Fin n→Bool)→Z} {g : V→Z} (h : SameLaw f g) (padding : ℕ) : + SameLaw (fun p : U×(Fin (n+padding)→Bool) => f (p.1,(splitWordEquiv n padding p.2).1)) g := by + intro phi + have hh := h phi + rw [uniformAverage_prod] at hh ⊢ + refine Eq.trans ?_ hh + apply congrArg uniformAverage + funext u + have he := uniformAverage_equiv (splitWordEquiv n padding) + (fun p : (Fin n→Bool)×(Fin padding→Bool) => phi (f (u,p.1))) + rw [uniformAverage_prod] at he + simpa only [uniformAverage_const] using he + +end +end ContingencyTables.FiniteObservableTransport + +namespace ContingencyTables.CompanionPhaseTrialProgram +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionEvaluatedWeightProgram CompanionMultiplierMatrixProgram +open CompanionOracleDensity CompanionWeightOracle GridBoundary FiniteObservableTransport CommonBasesFPRAS TwoLiftStates +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma trajectory_length_data (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) (xi : ℚ) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth : List Bool) (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) + (S : CompanionBooleanPhase.State A) (bits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool) : + (CompanionTrajectoryProgram.output + (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits))).length=N+1 := by + let state := CompanionFlatReturnProgram.stateData A C K j k xi z v degree depth w S + let words := CompanionFlatReturnProgram.words + (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits)) + have h := (CompanionCodeBounds.history_bound state words + (TreeTyped.weight state.2+6*state.1.2.length+1) (by omega) (by omega)).2 + change (CompanionTrajectoryProgram.output + (CompanionFlatReturnProgram.data A C K j k N xi z v degree depth w S (List.ofFn bits))).length= + words.length+1 at h + dsimp only [words] at h + rw [CompanionFlatReturnProgram.words_data,List.length_ofFn] at h + exact h + +lemma output_data_take (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) (xi : ℚ) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (degree depth nextDegree nextDepth : List Bool) + (w : LabelIndex A→LabelIndex A→TreeFraction.Fraction) (E : TreeFraction.Fraction) + (S : CompanionBooleanPhase.State A) (walkBits : Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool) + (queryBits : List Bool) : + let cs := CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth + output (data A C K j k N xi z v degree depth nextDegree nextDepth w E S + (List.ofFn walkBits) (queryBits.take ((N+1)*CompanionObservationQueriesProgram.blockWidth cs)))= + output (data A C K j k N xi z v degree depth nextDegree nextDepth w E S + (List.ofFn walkBits) queryBits) := by + dsimp only + have h := output_take + ((data A C K j k N xi z v degree depth nextDegree nextDepth w E S (List.ofFn walkBits) queryBits).1) + queryBits + dsimp only [data] at h + rw [trajectory_length_data] at h + exact h + + +theorem trial_padded_sameLaw (padding : ℕ) (A : Instance (Fin m) (Fin n)) (C K j k N : ℕ) + (hC : 0 + (output (data A C K j k N xi z v degree depth nextDegree nextDepth w E S + (List.ofFn bits.1) (List.ofFn bits.2))).map (CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))) + (fun bits : RootedPhaseTrial.TrialWords A C K j k N xi => + (RootedPhaseTrial.trial A (RootedCompletion.rowColumn A.T) C K j k N hK hW xi + (RootedCatalogGrid.gridEquiv A K v) old S bits).map + (CompanionPhaseFinishProgram.storedView A (pairLabels A))) := by + dsimp only + have h := trial_sameLaw A C K j k N hC hj hK hW hB xi hxi z v degree depth nextDegree nextDepth + hdegree hdepth hnextDegree hnextDepth old w E hw hE S + dsimp only at h + have hp := h.right_padding padding + intro phi + have he (bits : (Fin (N*CompanionBooleanPhase.stepBits A C K j k xi)→Bool) × + (Fin ((N+1)*CompanionObservationQueriesProgram.blockWidth + (CompanionObservationQueriesProgram.phaseConfigs A C K j xi z v degree depth nextDegree nextDepth)+padding)→Bool)) : + output (data A C K j k N xi z v degree depth nextDegree nextDepth w E S + (List.ofFn bits.1) (List.ofFn bits.2))= + output (data A C K j k N xi z v degree depth nextDegree nextDepth w E S + (List.ofFn bits.1) (List.ofFn (FairBits.splitWordEquiv _ padding bits.2).1)) := by + rw [←output_data_take A C K j k N xi z v degree depth nextDegree nextDepth w E S bits.1 + (List.ofFn bits.2),DensePrograms.ofFn_split_take] + simp_rw [he] + exact hp phi + +end +end ContingencyTables.CompanionPhaseTrialProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionUniformPhaseBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionUniformPhaseBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..b258281a396c1c5a8721c14d8747cc0a03a4b56e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionUniformPhaseBounds.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionUniformPhaseWidth +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartScheduleSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CountingPublicWordBound + +namespace OAI + +/-! # The computed common width covers every actual phase and marker -/ +namespace ContingencyTables.CompanionUniformPhaseWidth +open MatchingFPRAS CompanionFactorialApplication CompanionOracleDensity +open RootedPhaseHistory GridBoundary +open scoped BigOperators Classical +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (s : Settings A) (epsilon : TreeFraction.Fraction) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) s.K) : Input := + CompanionRestartInitializer.data A s.C s.K s.H (CompanionTargetMixing.restartTime A s.H s.L) + s.N s.n s.L epsilon z v + +lemma fields_data (A : Instance (Fin m) (Fin n)) (s : Settings A) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) s.K) + (hk : CountingPhaseParametersProgram.precision + ([Fintype.card (Labels A),A.W,s.H,CompanionTargetMixing.restartTime A s.H s.L,s.N,s.n,s.L],epsilon)=s.k) + (hh : s.h=CountingPhaseSchedule.initialPrecision s.H) : + fields (data A s epsilon z v)= + [A.d,s.K,rationalHeight A s.C,0,Fintype.card (Labels A),A.W,s.H, + CompanionTargetMixing.restartTime A s.H s.L,s.N,s.n,s.L,s.k,s.h] := by + have ho : oracleInput (data A s epsilon z v)=RootedOracleConfigProgram.data A s.C s.K 0 + (CountingPhaseParametersProgram.noise + ([Fintype.card (Labels A),A.W,s.H,CompanionTargetMixing.restartTime A s.H s.L,s.N,s.n,s.L],epsilon)) + z v [] := rfl + unfold fields rawFields + rw [ho,RootedOracleConfigProgram.fields_data] + change [A.d,s.K,rationalHeight A s.C,0]++ + [Fintype.card (Labels A),A.W,s.H,CompanionTargetMixing.restartTime A s.H s.L,s.N,s.n,s.L]++ + [CountingPhaseParametersProgram.precision + ([Fintype.card (Labels A),A.W,s.H,CompanionTargetMixing.restartTime A s.H s.L,s.N,s.n,s.L],epsilon), + CountingPhaseScalarProgram.initialPrecision.eval + [Fintype.card (Labels A),A.W,s.H,CompanionTargetMixing.restartTime A s.H s.L,s.N,s.n,s.L]]=_ + rw [hk,CountingPhaseScalarProgram.initialPrecision_value,←hh] + rfl + +theorem width_covers (A : Instance (Fin m) (Fin n)) (s : Settings A) + (epsilon : TreeFraction.Fraction) (z : View A→ℕ) + (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) s.K) + (hk : CountingPhaseParametersProgram.precision + ([Fintype.card (Labels A),A.W,s.H,CompanionTargetMixing.restartTime A s.H s.L,s.N,s.n,s.L],epsilon)=s.k) + (hh : s.h=CountingPhaseSchedule.initialPrecision s.H) + (hxi : s.xi=1/(s.k:ℚ)) (hkpos : 0 < s.k) (hHpos : 0 < s.H) + (hcap : CountingTerminalSchedule.capacityBits A ≤ s.L) : + totalWidth A s ≤ width (data A s epsilon z v) ∧ + (∀ j,j ≤ s.H → + PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (s.xi/2) j))+ + PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (s.xi/2) j)) ≤ + width (data A s epsilon z v)) ∧ + 2*Fintype.card (Labels A) ≤ width (data A s epsilon z v) := by + let M := measure (data A s epsilon z v) + have hs : ∀ x,x ∈ [A.d,s.K,rationalHeight A s.C,0,Fintype.card (Labels A),A.W,s.H, + CompanionTargetMixing.restartTime A s.H s.L,s.N,s.n,s.L,s.k,s.h] → x ≤ M := by + intro x hx + have hmem : x ∈ fields (data A s epsilon z v) := by + rw [fields_data A s epsilon z v hk hh] + exact hx + exact (List.le_sum_of_mem hmem).trans (Nat.le_succ _) + have hd : A.d ≤ M := hs _ (by simp) + have hK : s.K ≤ M := hs _ (by simp) + have hheight : rationalHeight A s.C ≤ M := hs _ (by simp) + have hp : Fintype.card (Labels A) ≤ M := hs _ (by simp) + have hW : A.W ≤ M := hs _ (by simp) + have hH : s.H ≤ M := hs _ (by simp) + have ht : CompanionTargetMixing.restartTime A s.H s.L ≤ M := hs _ (by simp) + have hN : s.N ≤ M := hs _ (by simp) + have hn : s.n ≤ M := hs _ (by simp) + have hL : s.L ≤ M := hs _ (by simp) + have hkM : s.k ≤ M := hs _ (by simp) + have hhM : s.h ≤ M := hs _ (by simp) + have hr := CountingPublicWordBound.reciprocal_controls s.k M hkpos hkM + have hx0 : 0 < s.xi := by rw [hxi]; exact hr.1 + have hxiM : 1/s.xi ≤ (M:ℚ) := by rw [hxi]; exact hr.2.1 + have hrepeats : CommonBasesFPRAS.repetitionCount s.xi ≤ 64*(M+1) := by + rw [hxi] + exact hr.2.2 + have hb := CountingWordsBound.bitCount_bound A s M hd hW hK hH hkM hn hN hhM hheight + (hcap.trans hL) hp ht hx0 hxiM hrepeats + have htotal : totalWidth A s ≤ RootedCountingWords.bitCount A s := by + change totalWidth A s ≤ s.H*totalWidth A s + simpa only [Nat.one_mul] using Nat.mul_le_mul_right (totalWidth A s) hHpos + have hb' := htotal.trans hb + dsimp only [M] at hb' hp + simp only [width_value] + refine ⟨hb'.trans (by omega),?_,?_⟩ + · intro j hj + have hm := CountingMarkerBounds.padding_bound j M s.xi (hj.trans hH) hx0 hxiM + dsimp only [M] at hm + exact hm.trans (by omega) + · omega + +end +end ContingencyTables.CompanionUniformPhaseWidth + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionUniformPhaseWidth.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionUniformPhaseWidth.lean new file mode 100644 index 0000000000000000000000000000000000000000..70be2d766808556a71b08acdd453ad32e2e94385 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionUniformPhaseWidth.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSchedule +import OAI.Combinatorics.ContingencyTables.Counting.CountingWordsBound +import OAI.Combinatorics.ContingencyTables.Counting.CountingMarkerBounds + +namespace OAI + +/-! # A computed common padded width for every adaptive phase + +All bounds are fixed arithmetic circuits. No numeric phase count controls +an unbounded preprocessing loop. +-/ +namespace ContingencyTables.CompanionUniformPhaseWidth +open MatchingFPRAS MatchingFPRAS.TreeTyped ScalarScheduleProgram + +abbrev Input := CompanionPhaseContextProgram.Prepared + +def oracleInput (z : Input) : RootedOracleConfigProgram.Input := + (((z.1,CountingPhaseParametersProgram.noise z.2),0),[]) +def oracleInputRealizer : Realizer oracleInput := + pair (pair (pair first (composition (f := Prod.snd) (g := CountingPhaseParametersProgram.noise) + second CountingPhaseParametersProgram.noiseRealizer)) (constant 0)) (constant []) +lemma polynomial_oracleInput : PolynomialTime oracleInputRealizer := + polynomial_pair (polynomial_pair (polynomial_pair polynomial_first + (polynomial_composition polynomial_second CountingPhaseParametersProgram.polynomial_noise)) + (polynomial_constant 0)) (polynomial_constant []) + +def rawFields (z : Input) : List ℕ := RootedOracleConfigProgram.fields (oracleInput z)++z.2.1 +def rawFieldsRealizer : Realizer rawFields := + composition (f := fun z : Input => (RootedOracleConfigProgram.fields (oracleInput z),z.2.1)) + (g := fun p : List ℕ×List ℕ => p.1++p.2) + (pair (composition (f := oracleInput) (g := RootedOracleConfigProgram.fields) + oracleInputRealizer RootedOracleConfigProgram.fieldsRealizer) (composition second first)) append +lemma polynomial_rawFields : PolynomialTime rawFieldsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_oracleInput RootedOracleConfigProgram.polynomial_fields) + (polynomial_composition polynomial_second polynomial_first)) polynomial_append + +def precision (z : Input) : ℕ := CountingPhaseParametersProgram.precision z.2 +def precisionRealizer : Realizer precision := + composition (f := Prod.snd) (g := CountingPhaseParametersProgram.precision) + second CountingPhaseParametersProgram.precisionRealizer +lemma polynomial_precision : PolynomialTime precisionRealizer := + polynomial_composition polynomial_second CountingPhaseParametersProgram.polynomial_precision + +def initialPrecision (z : Input) : ℕ := + CountingPhaseParametersProgram.scalar CountingPhaseScalarProgram.initialPrecision z.2 +def initialPrecisionRealizer : Realizer initialPrecision := + composition (f := Prod.snd) + (g := CountingPhaseParametersProgram.scalar CountingPhaseScalarProgram.initialPrecision) + second (CountingPhaseParametersProgram.scalarRealizer CountingPhaseScalarProgram.initialPrecision) +lemma polynomial_initialPrecision : PolynomialTime initialPrecisionRealizer := + polynomial_composition polynomial_second + (CountingPhaseParametersProgram.polynomial_scalar CountingPhaseScalarProgram.initialPrecision) + +def fields (z : Input) : List ℕ := rawFields z++[precision z,initialPrecision z] +def fieldsRealizer : Realizer fields := + composition (f := fun z : Input => (rawFields z,[precision z,initialPrecision z])) + (g := fun p : List ℕ×List ℕ => p.1++p.2) + (pair rawFieldsRealizer (composition + (pair precisionRealizer (composition (pair initialPrecisionRealizer (constant [])) listCons)) listCons)) append +lemma polynomial_fields : PolynomialTime fieldsRealizer := + polynomial_composition (polynomial_pair polynomial_rawFields + (polynomial_composition (polynomial_pair polynomial_precision + (polynomial_composition (polynomial_pair polynomial_initialPrecision (polynomial_constant [])) + polynomial_listCons)) polynomial_listCons)) polynomial_append + +def measure (z : Input) : ℕ := (fields z).sum+1 +def measureRealizer : Realizer measure := composition (composition fieldsRealizer listSum) successor +lemma polynomial_measure : PolynomialTime measureRealizer := + polynomial_composition (polynomial_composition polynomial_fields polynomial_listSum) polynomial_successor + +def x : Expr := .input 0 +def innerExpression : Expr := 400*(x+1)*x +def timeExpression : Expr := 2*(10000*x^2*x)^2*(x+x*x+2+4096*innerExpression) +def sampleExpression : Expr := 65536*(x+1)*innerExpression^2 +def binExpression : Expr := x*(x+1+4*(4096*x*innerExpression+x)) +def estimatorExpression : Expr := x*(sampleExpression*(timeExpression*(9*x)))+ + sampleExpression*(timeExpression*(9*x)+binExpression) +def medianExpression : Expr := 64*(x+1)*estimatorExpression +def initialExpression : Expr := x*(x+1)*(x*(3*x+1)+1+x) +def stepExpression : Expr := 1+(x^2+((medianExpression+medianExpression)+x)) +def stageExpression : Expr := x*((x+1)*stepExpression) +def phaseExpression : Expr := initialExpression+x*stageExpression+ + (x*stepExpression+(x+1)*(medianExpression+medianExpression)) +def widthExpression : Expr := x*(x*phaseExpression)+409600*(x+1)*x+2*x+1 + +def width (z : Input) : ℕ := widthExpression.eval [measure z] +def widthRealizer : Realizer width := + composition (f := fun z : Input => [measure z]) (g := widthExpression.eval) + (composition (pair measureRealizer (constant [])) listCons) widthExpression.realizer +theorem polynomial_width : PolynomialTime widthRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_measure (polynomial_constant [])) polynomial_listCons) + widthExpression.polynomial + +theorem width_value (z : Input) : + width z=CountingWordsBound.wordPolynomial.eval (measure z)+ + CountingMarkerBounds.paddingPolynomial.eval (measure z)+2*measure z+1 := by + simp only [width,widthExpression,phaseExpression,initialExpression,stageExpression,stepExpression, + medianExpression,estimatorExpression,sampleExpression,timeExpression,binExpression,innerExpression,x, + Expr.eval_power,Expr.eval,CountingWordsBound.wordPolynomial,CountingWordsBound.phasePolynomial, + CountingWordsBound.initialPolynomial,CountingWordsBound.stagePolynomial,CountingWordsBound.stepPolynomial, + CountingOracleWordBounds.medianPolynomial,CountingOracleWordBounds.estimatorPolynomial, + CountingOracleWordBounds.samplePolynomial,CountingOracleWordBounds.timePolynomial, + CountingOracleWordBounds.binPolynomial,CountingOracleWordBounds.innerPolynomial, + CountingMarkerBounds.paddingPolynomial,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_pow, + Polynomial.eval_X,Polynomial.eval_ofNat,Polynomial.eval_one,List.getD_cons_zero] + +theorem width_pos (z : Input) : 0 < width z := by rw [width_value]; omega + +end ContingencyTables.CompanionUniformPhaseWidth + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionWarmReturn.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionWarmReturn.lean new file mode 100644 index 0000000000000000000000000000000000000000..262a9dfeb543063e13a77e1e33723717a6f015ca --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionWarmReturn.lean @@ -0,0 +1,192 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionTargetTrace +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments + +namespace OAI + +/-! # The implemented capped return on a warm input law + +The output kernel comes from the actual bounded Boolean word. Its error +against the literal trace is bounded using the cap loss and the proved +joint-path approximation, averaged under the incoming warm law. +-/ + +namespace ContingencyTables.CompanionWarmReturn + +open CommonBasesFPRAS ResidualMixture FirstSuccess FiniteLawMoments RealKernelApproximation +open CompanionFactorialApplication CompanionBooleanPhase CompanionOracleDensity +open CompanionWeightOracle CompanionRationalUpdates CompanionTraceWords +open CompanionCappedReturn CompanionTargetTrace CompanionAnnealing CompanionWarmStart +open CompanionConcentration TwoLiftStates GridBoundary +open scoped BigOperators Classical + +noncomputable section + +private lemma weighted_error {Y : Type*} [Fintype Y] + (nu f g loss : Y → ℝ) (delta e : ℝ) (hnu : ∀ y,0≤nu y) + (hmass : ∑ y,nu y≤1) (he : 0≤e) + (hpoint : ∀ y,f y≤g y+loss y+e) (hloss : ∑ y,nu y*loss y≤delta) : + (∑ y,nu y*f y)≤(∑ y,nu y*g y)+delta+e := by + have h := Finset.sum_le_sum (fun y (_ : y∈Finset.univ) => + mul_le_mul_of_nonneg_left (hpoint y) (hnu y)) + have hm := mul_le_mul_of_nonneg_right hmass he + simp only [mul_add,Finset.sum_add_distrib,←Finset.sum_mul,one_mul] at h hm + linarith + +private lemma push_observation {X Y : Type*} [Fintype X] [Fintype Y] + (K : FiniteKernel X Y) (nu : X → ℝ) (g : Y → ℝ) : + (∑ y,K.push nu y*g y)=∑ x,nu x*(∑ y,K.P x y*g y) := by + simp only [FiniteKernel.push,Finset.sum_mul,Finset.mul_sum,mul_assoc] + exact Finset.sum_comm + +private theorem distance_of_events {Y : Type*} [Fintype Y] + (p q : Y → ℝ) (delta : ℝ) (hmass : ∑ y,p y=∑ y,q y) + (hevent : ∀ E : Y → Prop,(∑ y,p y*eventIndicator (E y))≤ + (∑ y,q y*eventIndicator (E y))+delta) : distance p q≤delta := by + let E : Y → Prop := fun y => 0≤p y-q y + have hzero : (∑ y,(p y-q y))=0 := by + rw [Finset.sum_sub_distrib,hmass,sub_self] + have hpoint (y : Y) : |p y-q y|= + 2*((p y-q y)*eventIndicator (E y))-(p y-q y) := by + by_cases h : 0≤p y-q y + · simp only [E,eventIndicator,h,ite_true,abs_of_nonneg h,mul_one] + ring + · simp only [E,eventIndicator,h,ite_false,abs_of_neg (lt_of_not_ge h),mul_zero] + ring + have hsum : (∑ y,|p y-q y|)=2*(∑ y,(p y-q y)*eventIndicator (E y)) := by + simp only [hpoint,Finset.sum_sub_distrib,←Finset.mul_sum,hzero,sub_zero] + have hh := hevent E + simp only [sub_mul,Finset.sum_sub_distrib] at hsum + unfold distance + rw [hsum] + linarith + +variable {I J : Type} [Fintype I] [Fintype J] + +def returnLaw (A : Instance I J) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) : RationalLaw (PlainIndex (pairs : List (Pair A))) := + mapLaw (uniformLaw (α := Fin ((n+1)*stepBits A C K j k xi) → Bool)) + (returnWordDefault A C K j k n hK hW xi v w S) + +def returnKernel (A : Instance I J) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) : + FiniteKernel (PlainIndex (pairs : List (Pair A))) (PlainIndex (pairs : List (Pair A))) := + rationalKernel (returnLaw A C K j k n hK hW xi v w) + +private lemma return_observation (A : Instance I J) (C K j k n : ℕ) + (hK : 1≤K) (hW : 100*A.d*K≤A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (w : Pair A → Pair A → ℚ) + (S : PlainIndex (pairs : List (Pair A))) (E : PlainIndex (pairs : List (Pair A)) → Prop) : + (∑ T,(returnKernel A C K j k n hK hW xi v w).P S T*eventIndicator (E T))= + uniformAverage (fun bits : Fin ((n+1)*stepBits A C K j k xi) → Bool => + eventIndicator (E (returnWordDefault A C K j k n hK hW xi v w S bits))) := by + exact (word_expectation (returnWordDefault A C K j k n hK hW xi v w S) + (fun T => eventIndicator (E T))).symm + +theorem warm_cap_loss (A : Instance I J) (j : ℕ) (hp : 0 (w p q:ℝ))) + (n : ℕ) (hn : 0 (w p q:ℝ))) + (hn : 0 + ∑ T,(returnKernel A C K j k n hK hW xi v w).P S T*eventIndicator (E T) + let g : PlainIndex (pairs : List (Pair A)) → ℝ := fun S => + ∑ T,(CompanionTargetTrace.actualTrace A j hp w hw).kernel.P S T*eventIndicator (E T) + let loss : PlainIndex (pairs : List (Pair A)) → ℝ := fun S => + 1-∑ T,(targetChain A j hp w hw).cappedTrace (plainPredicate pairs) + (targetKilled A j hp w hw) n S T + let err : ℝ := ((n+1:ℕ):ℝ)*((6*(xi:ℝ)+1/(2:ℝ)^k)/2) + have herr : 0≤err := by dsimp only [err]; positivity + have hpoint (S) : f S≤g S+loss S+err := by + dsimp only [f,g,loss,err] + rw [return_observation] + exact returnWordDefault_event A C hC K j k n hK hW hB hj xi hx0 hx1 + hPL hCheeger v hp w hw S E + have hcap := warm_cap_loss A j hp w hw hgood n hn nu hnu U hU hwarm + have hsum := @weighted_error (PlainIndex (pairs : List (Pair A))) inferInstance + nu f g loss ((5*(Fintype.card (Labels A):ℝ)^2*U)/(n:ℝ)) err + hnu hmass herr hpoint hcap + exact hsum + +/-- This is the law of the implemented Boolean return, compared to the +literal trace on the same incoming warm distribution. -/ +theorem warm_return_distance (A : Instance I J) (C : ℕ) (hC : 0 (w p q:ℝ))) + (hn : 0 simp + | succ j ih => + have h := weight_adjacent A j S + constructor + · rw [pow_succ] + nlinarith [mul_le_mul_of_nonneg_left ih.1 (show (0:ℝ)≤1/2 by norm_num)] + · exact h.2.trans ih.2 + +theorem total_bounds_zero (A : Instance I J) (j : ℕ) : + (1/2:ℝ)^j*total A 0≤ total A j ∧ total A j≤ total A 0 := by + unfold total + constructor + · rw [← slotTotal_scale] + exact slotTotal_mono _ _ _ (fun S => (weight_bounds_zero A j S).1) _ + · exact slotTotal_mono _ _ _ (fun S => (weight_bounds_zero A j S).2) _ + +lemma zero_weight_lower (A : Instance I J) (S : Set (Labels A×Bool)) : + freeTotal A/CompanionFactorialApplication.denominator A≤ weight A 0 S := by + unfold weight + simp only [Nat.cast_zero,zero_div] + unfold f firstLift + rw [h_zero] + have hf : (1:ℝ)≤ FactorialSignatures.factorialProduct + (groupCount (group (labelCell A)) S) := by + unfold FactorialSignatures.factorialProduct + apply Finset.one_le_prod₀ + intro u _ + exact_mod_cast Nat.succ_le_of_lt (Nat.factorial_pos _) + exact div_le_div_of_nonneg_right (by nlinarith [free_positive A]) + (CompanionFactorialApplication.denominator_positive A).le + +/-- An explicit positive minimum mass for the actual transversal law. +Its binary size depends on j and the bounded small-cell capacities. -/ +theorem law_lower (A : Instance I J) (j : ℕ) (S : Set (Labels A×Bool)) : + (1/2:ℝ)^j/(CompanionFactorialApplication.denominator A* + ∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1))≤ law A j S := by + have hM := free_positive A + have hD := CompanionFactorialApplication.denominator_positive A + have hB : 0<(∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1)) := + Finset.prod_pos (fun _ _ => by positivity) + have hweight := weight_bounds_zero A j S + have hz := zero_weight_lower A S + have hT := (total_bounds_zero A j).2 + have hT0 : total A 0=freeTotal A*∏ s : SmallCell A,((A.b s.val.1 s.val.2:ℝ)+1) := by + unfold total weight + simpa only [Nat.cast_zero,zero_div] using total_zero A + rw [hT0] at hT + have hpositive := total_positive A j + have hpow : 0≤(1/2:ℝ)^j := by positivity + unfold law + rw [div_le_div_iff₀ (mul_pos hD hB) hpositive] + have hlo : (1/2:ℝ)^j*freeTotal A≤ weight A j S*CompanionFactorialApplication.denominator A := by + have hz' := (div_le_iff₀ hD).mp hz + have hmul := mul_le_mul_of_nonneg_right hweight.1 hD.le + have hmul' := mul_le_mul_of_nonneg_left hz' hpow + nlinarith + have hupper := mul_le_mul_of_nonneg_left hT hpow + have hfinal := mul_le_mul_of_nonneg_right hlo hB.le + nlinarith + +end ContingencyTables.CompanionWarmStart + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionWeightOracle.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionWeightOracle.lean new file mode 100644 index 0000000000000000000000000000000000000000..d7d560e74d6f4a155e9f8385199109be85a7513d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CompanionWeightOracle.lean @@ -0,0 +1,123 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorAmplification +import OAI.Combinatorics.ContingencyTables.Counting.CompanionAnnealing + +namespace OAI + +/-! # The actual labelled-weight oracle used by the outer chain -/ + +namespace ContingencyTables.CompanionWeightOracle + +open CompanionFactorialApplication CompanionOracleDensity GridBoundary LabelledFactorial TwoLiftStates +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] + +def profile (A : Instance I J) (S : Set (Labels A×Bool)) : View A → ℕ := + groupCount (group (labelCell A)) S + +lemma profile_inBox (A : Instance I J) (S : Set (Labels A×Bool)) : + BalancedBox.InBox (bounds A) (profile A S) := by + rw [←label_capacity] + exact SliceFactorial.groupCount_inBox _ _ + +def factorialNumerator (A : Instance I J) (S : Set (Labels A×Bool)) : ℕ := + ∏ u : View A, (profile A S u).factorial + +def factorialDenominator (A : Instance I J) : ℕ := + ∏ s : SmallCell A, (A.b s.val.1 s.val.2).factorial + +def factorialRatio (A : Instance I J) (S : Set (Labels A×Bool)) : ℚ := + (factorialNumerator A S:ℚ)/factorialDenominator A + +lemma factorialRatio_positive (A : Instance I J) (S : Set (Labels A×Bool)) : + 0 < factorialRatio A S := by + unfold factorialRatio factorialNumerator factorialDenominator + positivity + +lemma factorialRatio_cast (A : Instance I J) (S : Set (Labels A×Bool)) : + (factorialRatio A S:ℝ)= + FactorialSignatures.factorialProduct (profile A S)/CompanionFactorialApplication.denominator A := by + simp only [factorialRatio,factorialNumerator,factorialDenominator,Rat.cast_div,Rat.cast_prod, + Rat.cast_natCast,Nat.cast_prod,FactorialSignatures.factorialProduct,CompanionFactorialApplication.denominator, + TwoLiftStates.denominator,label_width] + +theorem weight_source (A : Instance I J) (C : ℕ) (hC : 0 < C) (j : ℕ) + (S : Set (Labels A×Bool)) : + CompanionAnnealing.weight A j S= + h A ((j:ℝ)*C/height A C) (profile A S)*(factorialRatio A S:ℝ) := by + rw [factorialRatio_cast] + have he : (j:ℝ)*(C:ℝ)/height A C=(j:ℝ)/CompanionAnnealing.scale A := by + simpa only [height,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_pow,Nat.cast_add,Nat.cast_one] using + CompanionAnnealing.source_parameter A C j hC + rw [he] + simp only [CompanionAnnealing.weight,CompanionFactorialApplication.f,firstLift,profile,mul_div_assoc] + +abbrev WeightWord (A : Instance I J) (C K j : ℕ) (xi : ℚ) := + Fin (medianEstimatorBits A C K j xi xi) → Bool + +def evaluate (A : Instance I J) (C : ℕ) (K : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (j : ℕ) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi) : ℚ := + medianEstimate A C (profile A S) K hK hW j xi xi v bits*factorialRatio A S + +/-- The relative-accuracy event describes the weight evaluator at +each labelled state. -/ +def accurateCall (A : Instance I J) (C K j : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (xi : ℚ) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi) : Prop := + (1-(xi:ℝ))*CompanionAnnealing.weight A j S ≤ (evaluate A C K hK hW j xi v S bits:ℝ) ∧ + (evaluate A C K hK hW j xi v S bits:ℝ) ≤ (1+(xi:ℝ))*CompanionAnnealing.weight A j S + +lemma evaluate_positive (A : Instance I J) (C : ℕ) (hC : 0 < C) (K : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (j : ℕ) (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) + (bits : WeightWord A C K j xi) : 0 < evaluate A C K hK hW j xi v S bits := by + have hr := (medianEstimate_range A C hC (profile A S) (profile_inBox A S) + K hK hW hB j hj xi xi hx0 hx1 v bits).1 + have hc : (0:ℝ) < assignmentCount A := by exact_mod_cast assignmentCount_positive A + have hm : (0:ℚ) < medianEstimate A C (profile A S) K hK hW j xi xi v bits := by + exact_mod_cast lt_of_lt_of_le (by positivity : (0:ℝ) < (assignmentCount A:ℝ)*(1/2:ℝ)^j/16) hr + exact mul_pos hm (factorialRatio_positive A S) + +/-- Every query at the actual labelled state uses a fresh bounded word. +Only PL and finite Cheeger remain in the evaluation guarantee. -/ +theorem evaluate_success (A : Instance I J) (C : ℕ) (hC : 0 < C) (K : ℕ) + (hK : 1 ≤ K) (hW : 100*A.d*K ≤ A.W) (hB : (K:ℝ)=binWidth A C) + (j : ℕ) (hj : j ≤ rationalHeight A C) (xi : ℚ) (hx0 : 0 < xi) (hx1 : xi < 1) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (dimension A)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (dimension A)) K)) + (v : Grid (I := Fin (dimension A)) K) (S : Set (Labels A×Bool)) : + 1-(xi:ℝ) ≤ uniformAverage (fun bits : WeightWord A C K j xi => + if accurateCall A C K j hK hW xi v S bits then (1:ℝ) else 0) := by + unfold accurateCall + have hs := medianEstimate_success A C hC (profile A S) (profile_inBox A S) + K hK hW hB j hj xi xi hx0 hx1 hx0 hPL hCheeger v + apply hs.trans + apply uniformAverage_mono + intro bits + by_cases hg : (1-(xi:ℝ))*h A ((j:ℝ)*C/height A C) (profile A S) ≤ + (medianEstimate A C (profile A S) K hK hW j xi xi v bits:ℝ) ∧ + (medianEstimate A C (profile A S) K hK hW j xi xi v bits:ℝ) ≤ + (1+(xi:ℝ))*h A ((j:ℝ)*C/height A C) (profile A S) + · have hf : (0:ℝ) ≤ factorialRatio A S := by exact_mod_cast (factorialRatio_positive A S).le + have hlo := mul_le_mul_of_nonneg_right hg.1 hf + have hhi := mul_le_mul_of_nonneg_right hg.2 hf + have ho : (1-(xi:ℝ))*CompanionAnnealing.weight A j S ≤ (evaluate A C K hK hW j xi v S bits:ℝ) ∧ + (evaluate A C K hK hW j xi v S bits:ℝ) ≤ (1+(xi:ℝ))*CompanionAnnealing.weight A j S := by + rw [weight_source A C hC j S] + simpa only [evaluate,Rat.cast_mul,mul_assoc] using And.intro hlo hhi + simp only [hg,ho,le_refl] + · simp only [hg,ite_false] + split_ifs <;> norm_num + +end + +end ContingencyTables.CompanionWeightOracle + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/ComputedCountingParameters.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/ComputedCountingParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..c88b89e34cac74ae229b275d643fe099bacba8df --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/ComputedCountingParameters.lean @@ -0,0 +1,128 @@ +import OAI.Combinatorics.ContingencyTables.Transport.ComputedCompanionInstance +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingAmplification +import OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalSchedule + +namespace OAI + +/-! # Counting schedules computed from the original bounded margins + +The capacity-bit sum is formed after the executed endpoint translation. +All remaining dimensions, precisions, cutoffs and phase counts use the +proved rational/natural formulas. No numeric schedule hypothesis is +left to an external caller. +-/ + +namespace ContingencyTables.ComputedCountingParameters + +open CompanionFactorialApplication CompanionOracleDensity RootedPhaseHistory GridBoundary +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +def dimensionAllowance : ℕ := 1+m*n + +def capacityBits (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : ℕ := + ∑ a : Fin m×Fin n,(ComputedTableTightening.newBounds r c b a.1 a.2+1).size + +def coefficient (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) : ℕ := + CountingTerminalSchedule.coefficient (capacityBits r c b) (dimensionAllowance (m:=m) (n:=n)) + (epsilon/2) + +def binCount (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) : ℕ := + 16*coefficient r c b epsilon*(dimensionAllowance (m:=m) (n:=n))^2 + +def cutoff (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) : ℕ := + 100*dimensionAllowance (m:=m) (n:=n)*binCount r c b epsilon + +def phases (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) : ℕ := + 10*coefficient r c b epsilon*(dimensionAllowance (m:=m) (n:=n))^2*(cutoff r c b epsilon+1) + +lemma coefficient_pos (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) (he : 0⟨0,le_refl _,by have h:=binCount_pos r c b epsilon he; omega⟩ + +def settings (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 + if (1-(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ)≤ + (estimate hEK r c b hne epsilon he delta bits:ℝ) ∧ + (estimate hEK r c b hne epsilon he delta bits:ℝ)≤ + (1+(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ) + then (1:ℝ) else 0) := by + let A:=data hEK r c b hne epsilon he + let K:=binCount r c b epsilon + have hK : 1≤K:=binCount_pos r c b epsilon he + have hW : 100*A.d*K≤A.W:=(cutoff_eq hEK r c b hne epsilon he).ge + have hW' : 20*A.d≤A.W := by + have hh:=Nat.mul_le_mul_left (100*A.d) hK + simp only [Nat.mul_one] at hh + exact (show 20*A.d≤100*A.d by omega).trans (hh.trans hW) + have hL : (∏ a : Fin m×Fin n,(A.b a.1 a.2+1))≤2^capacityBits r c b := by + simpa only [A,data_capacityBits] using CountingTerminalSchedule.capacity_product_bound A + have hbox : (∏ a : SmallCell A,((A.b a.val.1 a.val.2:ℝ)+1))≤ + (2:ℝ)^capacityBits r c b := by + simpa only [A,data_capacityBits] using CountingTerminalSchedule.small_product_bound A + have hcount : CompanionTerminalMass.tableCount A=(Fintype.card (BoundedTable r c b):ℝ) := + ComputedCompanionInstance.original_count hEK r c b hne (cutoff r c b epsilon) + (cutoff_two r c b epsilon he) + have hs:=RootedCountingAmplification.success A (root hEK r c b hne epsilon he) + (coefficient r c b epsilon) K (phases r c b epsilon) (capacityBits r c b) + hK hW epsilon delta he he1 hd (start hEK r c b hne epsilon he) + (ComputedCompanionInstance.endpoints hEK r c b hne (cutoff r c b epsilon) + (cutoff_two r c b epsilon he)) hW' hL + (phases_final hEK r c b hne epsilon he) (coefficient_pos r c b epsilon he) + (binCount_cast hEK r c b hne epsilon he) (phases_height hEK r c b hne epsilon he).le + hbox (hPL _) (hCheeger _ _) hp + rw [hcount] at hs + exact hs + +end +end ContingencyTables.ComputedCountingWords + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/ComputedCountingZero.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/ComputedCountingZero.lean new file mode 100644 index 0000000000000000000000000000000000000000..818468ca5fc8b8cf4e0879b8c1a6ab7b8e2e877e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/ComputedCountingZero.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingWords +import OAI.Combinatorics.ContingencyTables.Rooted.RootedZeroLabels + +namespace OAI + +/-! # The computed zero-label counting branch + +When all retained capacities vanish, the actual direct weight estimator +replaces the phase walk. Its target is still the original bounded-table +count, transported through the executed endpoint translation. +-/ + +namespace ContingencyTables.ComputedCountingZero + +open CommonBasesFPRAS CompanionFactorialApplication GridBoundary +open CompanionOracleDensity CompanionTerminalApplication +open ComputedCountingParameters +open scoped BigOperators Classical + +noncomputable section +variable {m n : ℕ} + +def zeroBits (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 00) (binCount r c b epsilon) (binCount_pos r c b epsilon he) + (cutoff_eq hEK r c b hne epsilon he).ge + (finalPhase (data hEK r c b hne epsilon he) (capacityBits r c b) ((epsilon/2:ℚ):ℝ)) + ((epsilon/2)/2) delta (start hEK r c b hne epsilon he) bits + +theorem zero_success (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger (Grid (I:=Fin q) k)) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) + (he : 0 + if (1-(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ)≤ + (zeroEstimate hEK r c b hne epsilon he delta bits:ℝ) ∧ + (zeroEstimate hEK r c b hne epsilon he delta bits:ℝ)≤ + (1+(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ) + then (1:ℝ) else 0) := by + let A:=data hEK r c b hne epsilon he + let K:=binCount r c b epsilon + have hK: 1≤K:=binCount_pos r c b epsilon he + have hW: 100*A.d*K≤A.W:=(cutoff_eq hEK r c b hne epsilon he).ge + have hW': 20*A.d≤A.W := by + have hh:=Nat.mul_le_mul_left (100*A.d) hK + simp only [Nat.mul_one] at hh + exact (show 20*A.d≤100*A.d by omega).trans (hh.trans hW) + have hL: (∏ a : Fin m×Fin n,(A.b a.1 a.2+1))≤2^capacityBits r c b := by + simpa only [A,data_capacityBits] using CountingTerminalSchedule.capacity_product_bound A + have hH: finalPhase A (capacityBits r c b) ((epsilon/2:ℚ):ℝ)≤ + rationalHeight A (coefficient r c b epsilon) := + (phases_final hEK r c b hne epsilon he).symm.trans_le + (phases_height hEK r c b hne epsilon he).le + have hcount: CompanionTerminalMass.tableCount A=(Fintype.card (BoundedTable r c b):ℝ) := + ComputedCompanionInstance.original_count hEK r c b hne (cutoff r c b epsilon) + (cutoff_two r c b epsilon he) + have hs:=RootedZeroLabels.success A (ComputedCountingWords.root hEK r c b hne epsilon he) + hzero (ComputedCompanionInstance.endpoints hEK r c b hne (cutoff r c b epsilon) + (cutoff_two r c b epsilon he)) (coefficient r c b epsilon) K (capacityBits r c b) + (coefficient_pos r c b epsilon he) hK hW (binCount_cast hEK r c b hne epsilon he) hW' + (epsilon/2) delta (by positivity) (by linarith) hd hL hH + (hPL _) (hCheeger _ _) (start hEK r c b hne epsilon he) + rw [hcount] at hs + dsimp only [A,K] at hs + have hs': 1-(delta:ℝ)≤uniformAverage (fun bits : Fin (zeroBits hEK r c b hne epsilon he delta)→Bool => + if (1-((epsilon/2:ℚ):ℝ))*(Fintype.card (BoundedTable r c b):ℝ)≤ + (zeroEstimate hEK r c b hne epsilon he delta bits:ℝ) ∧ + (zeroEstimate hEK r c b hne epsilon he delta bits:ℝ)≤ + (1+((epsilon/2:ℚ):ℝ))*(Fintype.card (BoundedTable r c b):ℝ) + then (1:ℝ) else 0) := hs + apply hs'.trans + apply uniformAverage_mono + intro bits + have hZ: (0:ℝ)≤Fintype.card (BoundedTable r c b):=Nat.cast_nonneg _ + have heR: (0:ℝ) nlinarith [mul_nonneg heR.le hZ] + simp only [hh,hout,le_refl] + · simp only [hh,ite_false] + split_ifs <;> norm_num + +end +end ContingencyTables.ComputedCountingZero + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingActualInitialization.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingActualInitialization.lean new file mode 100644 index 0000000000000000000000000000000000000000..8fb4b1d4fc49fcde45fdc0ca0f0fca6f0df6b2eb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingActualInitialization.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CompanionStoredRepresentation + +namespace OAI + +/-! # Canonical physical initialization on the original bounded-table input -/ +namespace ContingencyTables.CountingPositiveProgram +open MatchingFPRAS CompanionFactorialApplication CompanionComputedProposal GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +theorem start_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 0) + (CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he)), + CompanionInitialStoredProgram.output (CompanionInitialStoredProgram.data A ∅)) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let x : CountingAdaptiveInputProgram.Input := + ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),bits) + have hp := CountingAdaptiveInputProgram.prepared_data hEK r c b hne epsilon he bits + have hc : CountingPreparedState.catalog x.1=RootedForestCatalog.data A := + CountingComputedSettings.catalog_data hEK r c b hne epsilon he + have hw : CountingAdaptiveInputProgram.labelWidth x=2*Fintype.card (Labels A) := by + unfold CountingAdaptiveInputProgram.labelWidth + rw [CountingComputedSettings.labelCount_data hEK r c b hne epsilon he] + apply Prod.ext hp + change CountingAdaptiveInputProgram.initial x=_ + unfold CountingAdaptiveInputProgram.initial + rw [CountingAdaptiveInputProgram.initialInput_data x A s.C s.K s.H + (CompanionTargetMixing.restartTime A s.H s.L) s.N s.n s.L + (CountingBaseProgram.half (TreeFraction.repr epsilon)) (fun _ => 0) + (CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he)) + hp hc hw hlen] + +theorem start_rep (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 0) + (CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he)),initial) + +lemma phase_bounds (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : TreeFraction.Fraction) (j : ℕ) + (hj : j < (ComputedCountingParameters.settings hEK r c b hne epsilon he).H) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let W := CountingPositiveProgram.phaseWidth ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta) + RootedPhaseHistory.totalWidth A s ≤ W ∧ j+1 ≤ rationalHeight A s.C ∧ + (∀ i,i ≤ j+1 → PowerOfTwoApproximation.rootDegree + (roundingTolerance (innerTolerance (s.xi/2) i)) ≤ W) ∧ + (∀ i,i ≤ j+1 → PowerOfTwoApproximation.depth + (roundingTolerance (innerTolerance (s.xi/2) i)) ≤ W) := by + dsimp only + have hc := CountingPositiveProgram.phaseWidth_covers hEK r c b hne epsilon he delta + have hj' : j+1 ≤ (ComputedCountingParameters.settings hEK r c b hne epsilon he).H := + Nat.succ_le_of_lt hj + refine ⟨hc.1,hj'.trans (CountingActualSettings.height hEK r c b hne epsilon he),?_,?_⟩ + · intro i hi + have hm := hc.2.1 i (hi.trans hj') + omega + · intro i hi + have hm := hc.2.1 i (hi.trans hj') + omega + +theorem output_rep (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : TreeFraction.Fraction) (initial : CompanionPhaseFinishProgram.Stored) + (hinit : StoredRep (CanonicalInitialEncoding.copyOrder + (capacities (ComputedCountingParameters.data hEK r c b hne epsilon he))).length initial) + (history : List CompanionPhaseFinishProgram.Stored) + (hh : ∀ q∈history,StoredRep (CanonicalInitialEncoding.copyOrder + (capacities (ComputedCountingParameters.data hEK r c b hne epsilon he))).length q) + (hj : history.length < (ComputedCountingParameters.settings hEK r c b hne epsilon he).H) + (bits : Fin (CountingPositiveProgram.phaseWidth + ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta))→Bool) : + StoredRep (CanonicalInitialEncoding.copyOrder + (capacities (ComputedCountingParameters.data hEK r c b hne epsilon he))).length + (CompanionOuterPhaseProgram.output + ((fixed hEK r c b hne epsilon he initial,history),List.ofFn bits)) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let e := CountingBaseProgram.half (TreeFraction.repr epsilon) + let v := CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he) + let W := CountingPositiveProgram.phaseWidth ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta) + have hr : CompanionCanonicalPhaseLaw.rawSettings A s.C s.K s.H s.N s.n s.L e s.hK s.hW v=s := + CountingActualSettings.raw_settings hEK r c b hne epsilon he + have hb := phase_bounds hEK r c b hne epsilon he delta history.length hj + have hwidth : RootedPhaseHistory.totalWidth A + (CompanionCanonicalPhaseLaw.rawSettings A s.C s.K s.H s.N s.n s.L e s.hK s.hW v) ≤ W := by + rw [hr] + exact hb.1 + have hd : ∀ i,i ≤ history.length+1 → PowerOfTwoApproximation.rootDegree + (roundingTolerance (innerTolerance + ((CompanionCanonicalPhaseLaw.rawSettings A s.C s.K s.H s.N s.n s.L e s.hK s.hW v).xi/2) i)) ≤ W := by + rw [hr] + exact hb.2.2.1 + have ht : ∀ i,i ≤ history.length+1 → PowerOfTwoApproximation.depth + (roundingTolerance (innerTolerance + ((CompanionCanonicalPhaseLaw.rawSettings A s.C s.K s.H s.N s.n s.L e s.hK s.hW v).xi/2) i)) ≤ W := by + rw [hr] + exact hb.2.2.2 + exact CompanionCanonicalPhaseSupport.output_rep A s.C s.K s.H s.N s.n s.L W e + (CountingActualSettings.coefficient_pos hEK r c b hne epsilon he) s.hK s.hW + (CountingActualSettings.bin_width hEK r c b hne epsilon he) + (CountingActualSettings.noise_pos hEK r c b hne epsilon he) + (fun _ => 0) v initial history hj hb.2.1 hwidth hd ht hinit hh bits + +theorem output_sameLaw (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : TreeFraction.Fraction) (initial : CompanionPhaseFinishProgram.Stored) + (hinit : StoredRep (CanonicalInitialEncoding.copyOrder + (capacities (ComputedCountingParameters.data hEK r c b hne epsilon he))).length initial) + (hi : CompanionPhaseFinishProgram.view + (p := (CanonicalInitialEncoding.copyOrder + (capacities (ComputedCountingParameters.data hEK r c b hne epsilon he))).length) initial= + project (ComputedCountingParameters.data hEK r c b hne epsilon he) + (pairLabels (ComputedCountingParameters.data hEK r c b hne epsilon he)) + (RootedStoredEstimate.initialStored (ComputedCountingParameters.data hEK r c b hne epsilon he))) + (history : List CompanionPhaseFinishProgram.Stored) + (hh : ∀ q∈history,StoredRep (CanonicalInitialEncoding.copyOrder + (capacities (ComputedCountingParameters.data hEK r c b hne epsilon he))).length q) + (hj : history.length < (ComputedCountingParameters.settings hEK r c b hne epsilon he).H) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + SameLaw (fun bits : Fin (CountingPositiveProgram.phaseWidth + ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta))→Bool => + CompanionPhaseFinishProgram.view (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length) + (CompanionOuterPhaseProgram.output + ((fixed hEK r c b hne epsilon he initial,history),List.ofFn bits))) + (fun bits : RootedPhaseHistory.Word A s => canonicalStep A (pairLabels A) + (RootedCompletion.rowColumn A.T) s + (history.map (CompanionPhaseFinishProgram.view + (p := (CanonicalInitialEncoding.copyOrder (capacities A)).length))) bits) := by + dsimp only + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let e := CountingBaseProgram.half (TreeFraction.repr epsilon) + let v := CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he) + let W := CountingPositiveProgram.phaseWidth ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta) + have hr : CompanionCanonicalPhaseLaw.rawSettings A s.C s.K s.H s.N s.n s.L e s.hK s.hW v=s := + CountingActualSettings.raw_settings hEK r c b hne epsilon he + have hb := phase_bounds hEK r c b hne epsilon he delta history.length hj + have hwidth : RootedPhaseHistory.totalWidth A + (CompanionCanonicalPhaseLaw.rawSettings A s.C s.K s.H s.N s.n s.L e s.hK s.hW v) ≤ W := by + rw [hr] + exact hb.1 + have hd : ∀ i,i ≤ history.length+1 → PowerOfTwoApproximation.rootDegree + (roundingTolerance (innerTolerance + ((CompanionCanonicalPhaseLaw.rawSettings A s.C s.K s.H s.N s.n s.L e s.hK s.hW v).xi/2) i)) ≤ W := by + rw [hr] + exact hb.2.2.1 + have ht : ∀ i,i ≤ history.length+1 → PowerOfTwoApproximation.depth + (roundingTolerance (innerTolerance + ((CompanionCanonicalPhaseLaw.rawSettings A s.C s.K s.H s.N s.n s.L e s.hK s.hW v).xi/2) i)) ≤ W := by + rw [hr] + exact hb.2.2.2 + have h := CompanionCanonicalPhaseLaw.output_sameLaw A s.C s.K s.H s.N s.n s.L W e + (CountingActualSettings.coefficient_pos hEK r c b hne epsilon he) s.hK s.hW + (CountingActualSettings.bin_width hEK r c b hne epsilon he) + (CountingActualSettings.noise_pos hEK r c b hne epsilon he) + (fun _ => 0) v initial history hj hb.2.1 hwidth hd ht hinit hh hi + dsimp only at h + rw [hr] at h + exact h + +end +end ContingencyTables.CountingActualPhase + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingActualSettings.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingActualSettings.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc8ceb5881f8eddc37ca66d5d3ec4a3b3080d802 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingActualSettings.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalPhaseLaw +import OAI.Combinatorics.ContingencyTables.Counting.CountingActualInitialization + +namespace OAI + +/-! # The executed original-input controls are exactly the source settings -/ +namespace ContingencyTables.CountingActualSettings +open MatchingFPRAS CompanionFactorialApplication CompanionOracleDensity GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} +variable (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) +variable (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) +variable (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 ComputedCountingParameters.data hEK r c b hne epsilon he +local notation "s" => ComputedCountingParameters.settings hEK r c b hne epsilon he +local notation "e" => CountingBaseProgram.half (TreeFraction.repr epsilon) +local notation "v" => CountingPreparedState.start A (RootedPhaseHistory.Settings.K s) + (ComputedCountingParameters.binCount_pos r c b epsilon he) +local notation "p" => CompanionInitializedRestartProgram.parameters A (RootedPhaseHistory.Settings.H s) + (CompanionTargetMixing.restartTime A (RootedPhaseHistory.Settings.H s) (RootedPhaseHistory.Settings.L s)) + (RootedPhaseHistory.Settings.N s) (RootedPhaseHistory.Settings.n s) (RootedPhaseHistory.Settings.L s) e + +lemma precision : CountingPhaseParametersProgram.precision p=(s).k := by + have h := CountingComputedSettings.precision_data hEK r c b hne epsilon he + rw [CountingComputedSettings.parameters_data hEK r c b hne epsilon he] at h + exact h + +lemma observations : CountingPhaseParametersProgram.observations p=(s).N := by + unfold CompanionInitializedRestartProgram.parameters + rw [CountingPhaseParametersProgram.observations_val,CountingBaseProgram.half_val, + TreeFraction.val_repr he.le] + rfl + +lemma noise : TreeFraction.val (CountingPhaseParametersProgram.noise p)=(s).xi := by + have h := CountingComputedSettings.noise_data hEK r c b hne epsilon he + rw [CountingComputedSettings.parameters_data hEK r c b hne epsilon he] at h + exact h + +lemma noise_pos : 0 (2,CountingComputedSettings.labelCount z.1)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 2) (composition (f := Prod.fst) (g := CountingComputedSettings.labelCount) + first CountingComputedSettings.labelCountRealizer)) multiply +lemma polynomial_labelWidth : PolynomialTime labelWidthRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 2) + (polynomial_composition polynomial_first CountingComputedSettings.polynomial_labelCount)) polynomial_multiply + +def zeroCode (z : Input) : List ℕ := (z.2.take (labelWidth z)).map (fun _ => 0) +def zeroCodeRealizer : Realizer zeroCode := + composition (f := fun z : Input => z.2.take (labelWidth z)) + (g := fun bs : List Bool => bs.map (fun _ => (0:ℕ))) + (composition (f := fun z : Input => (z.2,labelWidth z)) (g := fun p : List Bool×ℕ => p.1.take p.2) + (pair second labelWidthRealizer) takeFast) (map (constant 0)) +lemma polynomial_zeroCode : PolynomialTime zeroCodeRealizer := + polynomial_composition (polynomial_composition (polynomial_pair polynomial_second polynomial_labelWidth) + polynomial_takeFast) (polynomial_map (polynomial_constant 0)) + +def initialInput (z : Input) : CompanionInitialStoredProgram.Input := + (CountingPreparedState.catalog z.1,(capacities z,zeroCode z)) +def initialInputRealizer : Realizer initialInput := + pair (composition (f := Prod.fst) (g := CountingPreparedState.catalog) + first CountingPreparedState.catalogRealizer) (pair capacitiesRealizer zeroCodeRealizer) +lemma polynomial_initialInput : PolynomialTime initialInputRealizer := + polynomial_pair (polynomial_composition polynomial_first CountingPreparedState.polynomial_catalog) + (polynomial_pair polynomial_capacities polynomial_zeroCode) + +def initial (z : Input) : Stored := CompanionInitialStoredProgram.output (initialInput z) +def initialRealizer : Realizer initial := + composition (f := initialInput) (g := CompanionInitialStoredProgram.output) + initialInputRealizer CompanionInitialStoredProgram.outputRealizer +lemma polynomial_initial : PolynomialTime initialRealizer := + polynomial_composition polynomial_initialInput CompanionInitialStoredProgram.polynomial_output + +def output (z : Input) : Output := (prepared z,initial z) +def outputRealizer : Realizer output := pair preparedRealizer initialRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_pair polynomial_prepared polynomial_initial + +/-- The outer confidence parameter is handled by independent repetition. -/ +def runInput (z : CountingDirectProgram.Input) : Output×List Bool := (output (z.1.1,z.2),z.2) +def runInputRealizer : Realizer runInput := + pair (composition (f := fun z : CountingDirectProgram.Input => (z.1.1,z.2)) (g := output) + (pair (composition first first) second) outputRealizer) second +theorem polynomial_runInput : PolynomialTime runInputRealizer := + polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_output) polynomial_second + +end ContingencyTables.CountingAdaptiveInputProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAdaptiveInputSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAdaptiveInputSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..c73098b79aba587d430ad6a425ce60566891cfe7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAdaptiveInputSemantics.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingAdaptiveInputProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseFinishSemantics + +namespace OAI + +/-! # The computed initial record is the literal adaptive counting record -/ +namespace ContingencyTables.CountingAdaptiveInputProgram +open MatchingFPRAS CompanionFactorialApplication CompanionComputedInitial CompanionComputedProposal +open CompanionArithmeticProposal CompanionMultiplierMatrixProgram TwoLiftStates GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +theorem prepared_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (reserve : List Bool) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + prepared ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),reserve)= + CompanionRestartInitializer.data A s.C s.K s.H + (CompanionTargetMixing.restartTime A s.H s.L) s.N s.n s.L + (CountingBaseProgram.half (TreeFraction.repr epsilon)) (fun _ => 0) + (CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he)) := by + dsimp only + unfold prepared CountingPreparedState.output + rw [CountingPreparedState.state_data hEK r c b hne epsilon he, + CountingComputedSettings.parameters_data hEK r c b hne epsilon he] + rfl + +lemma zeroCode_data (x : Input) (A : Instance (Fin m) (Fin n)) + (hw : labelWidth x=2*Fintype.card (Labels A)) + (hr : 2*Fintype.card (Labels A) ≤ x.2.length) : + zeroCode x=encodeSet (coordinateOrder A) ∅ := by + have hcard : (CanonicalInitialEncoding.pairOrder (CompanionComputedInitial.capacities A)).length= + 2*Fintype.card (Labels A) := by + have h := (Fintype.card_congr (coordinateOrder A)).symm + simpa only [Fintype.card_fin,Fintype.card_prod,Fintype.card_bool,Nat.mul_comm] using h + have he : ProfilePrograms.setProfile (coordinateSet (coordinateOrder A) ∅)= + (fun _ => (0:ℕ)) := by + funext i + simp only [ProfilePrograms.setProfile,coordinateSet,Set.mem_preimage,Set.mem_empty_iff_false,ite_false] + rw [zeroCode,List.map_const',List.length_take,hw,min_eq_left hr,encodeSet,he,List.ofFn_const,hcard] + +lemma initialInput_data (x : Input) (A : Instance (Fin m) (Fin n)) + (C K H T N R L : ℕ) (epsilon : TreeFraction.Fraction) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (hp : prepared x=CompanionRestartInitializer.data A C K H T N R L epsilon z v) + (hc : CountingPreparedState.catalog x.1=RootedForestCatalog.data A) + (hw : labelWidth x=2*Fintype.card (Labels A)) + (hr : 2*Fintype.card (Labels A) ≤ x.2.length) : + initialInput x=CompanionInitialStoredProgram.data A ∅ := by + have hb : capacities x=List.ofFn (CompanionComputedInitial.capacities A) := by + unfold capacities CompanionRestartInitializer.capacities + rw [hp,CompanionRestartInitializer.cellInput_data,CompanionCellCatalog.capacities_eq] + rfl + unfold initialInput CompanionInitialStoredProgram.data + rw [hc,hb,zeroCode_data x A hw hr] + +theorem initial_view (x : Input) (A : Instance (Fin m) (Fin n)) + (C K H T N R L : ℕ) (epsilon : TreeFraction.Fraction) + (z : View A→ℕ) (v : Grid (I := Fin (RootedCatalogGrid.freeCount A)) K) + (hp : prepared x=CompanionRestartInitializer.data A C K H T N R L epsilon z v) + (hc : CountingPreparedState.catalog x.1=RootedForestCatalog.data A) + (hw : labelWidth x=2*Fintype.card (Labels A)) + (hr : 2*Fintype.card (Labels A) ≤ x.2.length) : + CompanionPhaseFinishProgram.view (initial x)= + CompanionPhaseFinishProgram.storedView A (pairLabels A) (RootedStoredEstimate.initialStored A) := by + rw [initial,initialInput_data x A C K H T N R L epsilon z v hp hc hw hr] + apply Prod.ext + · funext i j + change TreeFraction.val (readEntry ((CompanionInitialStoredProgram.output + (CompanionInitialStoredProgram.data A ∅)).1,(i.val,j.val)))=_ + rw [CompanionInitialStoredProgram.output_matrix,readEntry_code] + exact CompanionInitialMatrixProgram.initialEntries_val A i j + · exact CompanionInitialStoredProgram.total_data A ∅ + +end +end ContingencyTables.CountingAdaptiveInputProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAdaptiveReserve.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAdaptiveReserve.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d6c75dd612c73b20d5b1b0ce3f721230acb7438 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAdaptiveReserve.lean @@ -0,0 +1,33 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingAdaptiveInputProgram + +namespace OAI + +/-! # The initializer uses only the length of its reserved word -/ +namespace ContingencyTables.CountingAdaptiveInputProgram +open MatchingFPRAS + +lemma zeroCode_eq_of_length_eq (x : CountingBaseProgram.Input) (a b : List Bool) + (h : a.length=b.length) : zeroCode (x,a)=zeroCode (x,b) := by + simp only [zeroCode,List.map_const',List.length_take,labelWidth,h] + +lemma initialInput_eq_of_length_eq (x : CountingBaseProgram.Input) (a b : List Bool) + (h : a.length=b.length) : initialInput (x,a)=initialInput (x,b) := by + change (CountingPreparedState.catalog x,(capacities (x,a),zeroCode (x,a)))= + (CountingPreparedState.catalog x,(capacities (x,b),zeroCode (x,b))) + rw [zeroCode_eq_of_length_eq x a b h] + rfl + +theorem output_eq_of_length_eq (x : CountingBaseProgram.Input) (a b : List Bool) + (h : a.length=b.length) : output (x,a)=output (x,b) := by + have hi := initialInput_eq_of_length_eq x a b h + apply Prod.ext + · rfl + · exact congrArg CompanionInitialStoredProgram.output hi + +theorem output_ofFn (x : CountingBaseProgram.Input) (N : ℕ) (bits : Fin N→Bool) : + output (x,List.ofFn bits)=output (x,List.replicate N false) := + output_eq_of_length_eq x _ _ (by simp only [List.length_ofFn,List.length_replicate]) + +end ContingencyTables.CountingAdaptiveInputProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca1b48617c058358e2e41935a4e49f016568dfe1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedLaw.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingAmplifiedProgram +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CountingPublicInputBounds + +namespace OAI + +/-! # Exact law and public word budget of outer confidence repetition -/ +namespace ContingencyTables.CountingAmplifiedProgram +open MatchingFPRAS GridBoundary CommonBasesFPRAS FiniteObservableTransport Polynomial CountingPublicInputBounds +open scoped Classical +noncomputable section + +variable (single : Input→TreeFraction.Fraction) (width : Request→ℕ) + +theorem sameLaw (req : Request) (hw : 0 < width req) (K : ℕ) (g : (Fin K→Bool)→ℚ) + (hs : SameLaw (fun bits : Fin (width req)→Bool => TreeFraction.val (single (req,List.ofFn bits))) g) : + SameLaw (fun bits : Fin (budget width req)→Bool => + TreeFraction.val (output single width (req,List.ofFn bits))) + (fun bits : Fin (repeats req*K)→Bool => + rationalMedian (List.ofFn (fun i => g (gridWordEquiv (repeats req) K bits i)))) := by + let R := repeats req + let f := fun bits : Fin (width req)→Bool => TreeFraction.val (single (req,List.ofFn bits)) + have hp := (hs.independent R).map (fun xs : Fin R→ℚ => rationalMedian (List.ofFn xs)) + intro phi + have hleft := uniformAverage_equiv (gridWordEquiv R (width req)) + (fun xs => phi (rationalMedian (List.ofFn (fun i => f (xs i))))) + have hright := uniformAverage_equiv (gridWordEquiv R K) + (fun xs => phi (rationalMedian (List.ofFn (fun i => g (xs i))))) + have hout : uniformAverage (fun bits : Fin (budget width req)→Bool => + phi (TreeFraction.val (output single width (req,List.ofFn bits)) ))= + uniformAverage (fun bits : Fin (R*width req)→Bool => + phi (rationalMedian (List.ofFn (fun i => f (gridWordEquiv R (width req) bits i))))) := by + apply congrArg uniformAverage + funext bits + exact congrArg phi (output_ofFn single width req hw bits) + exact hout.trans (hleft.trans ((hp phi).trans hright.symm)) + +variable {m n : ℕ} + +lemma repeats_request (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (hd : 0 < delta) : + repeats (CountingDirectProgram.request r c b epsilon delta)=repetitionCount delta := by + change FractionRepetitionProgram.count (TreeFraction.repr delta)=_ + rw [FractionRepetitionProgram.count_val,TreeFraction.val_repr hd.le] + +def budgetPolynomial (p : Polynomial ℕ) : Polynomial ℕ := 64*X*p + +lemma budget_bound (p : Polynomial ℕ) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (hd : 0 < delta) + (hw : width (CountingDirectProgram.request r c b epsilon delta) ≤ p.eval (size r c b epsilon delta)) : + budget width (CountingDirectProgram.request r c b epsilon delta) ≤ + (budgetPolynomial p).eval (size r c b epsilon delta) := by + unfold budget + rw [repeats_request r c b epsilon delta hd] + simpa only [budgetPolynomial,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X, + CommonBasesFPRAS.repetitionCount] + using Nat.mul_le_mul (repeats_le r c b epsilon delta) hw + +end +end ContingencyTables.CountingAmplifiedProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..206199f192f68ea47b9a1f5108bae799243b7aaf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedProgram.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectProgram +import OAI.Combinatorics.ContingencyTables.Machines.RepeatedFractionProgram + +namespace OAI + +/-! # Outer confidence repetition of the executed counting program -/ +namespace ContingencyTables.CountingAmplifiedProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped CommonBasesFPRAS GridBoundary +abbrev Request := CountingDirectProgram.Request +abbrev Input := CountingDirectProgram.Input + +variable (single : Input→TreeFraction.Fraction) (F : Realizer single) +variable (width : Request→ℕ) (N : Realizer width) + +def repeats (req : Request) : ℕ := FractionRepetitionProgram.count req.2 +def repeatsRealizer : Realizer repeats := + composition (f := fun req : Request => req.2) (g := FractionRepetitionProgram.count) + second FractionRepetitionProgram.countRealizer +lemma polynomial_repeats : PolynomialTime repeatsRealizer := + polynomial_composition polynomial_second FractionRepetitionProgram.polynomial_count + +def prepared (z : Input) : RepeatedFractionProgram.Input Request := + ((z.1,(repeats z.1,width z.1)),z.2) +def preparedRealizer : Realizer (prepared width) := + pair (pair first (pair (composition (f := fun z : Input => z.1) (g := repeats) + first repeatsRealizer) (composition (f := fun z : Input => z.1) (g := width) first N))) second +lemma polynomial_prepared (hN : PolynomialTime N) : PolynomialTime (preparedRealizer width N) := + polynomial_pair (polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition polynomial_first polynomial_repeats) + (polynomial_composition polynomial_first hN))) polynomial_second + +attribute [local irreducible] prepared + +def output (z : Input) : TreeFraction.Fraction := RepeatedFractionProgram.output single (prepared width z) +def outputRealizer : Realizer (output single width) := + composition (f := prepared width) (g := RepeatedFractionProgram.output single) + (preparedRealizer width N) (RepeatedFractionProgram.outputRealizer F) +lemma polynomial_output (hF : PolynomialTime F) (hN : PolynomialTime N) : + PolynomialTime (outputRealizer single F width N) := + polynomial_composition (polynomial_prepared width N hN) (RepeatedFractionProgram.polynomial_output F hF) + +def budget (req : Request) : ℕ := repeats req*width req +def budgetRealizer : Realizer (budget width) := + composition (f := fun req : Request => (repeats req,width req)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair repeatsRealizer N) multiply +lemma polynomial_budget (hN : PolynomialTime N) : PolynomialTime (budgetRealizer width N) := + polynomial_composition (polynomial_pair polynomial_repeats hN) polynomial_multiply + +lemma output_ofFn (req : Request) (hw : 0 < width req) + (bits : Fin (budget width req)→Bool) : + TreeFraction.val (output single width (req,List.ofFn bits))= + rationalMedian (List.ofFn (fun i : Fin (repeats req) => + TreeFraction.val (single (req,List.ofFn (gridWordEquiv (repeats req) (width req) bits i))))) := by + unfold output prepared + exact RepeatedFractionProgram.output_ofFn (f := single) req (repeats req) (width req) hw bits + +end ContingencyTables.CountingAmplifiedProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedSourceLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedSourceLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..80baa52ff9f50e33fe9d62c82977ccd626fdba30 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingAmplifiedSourceLaw.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchSuccess +import OAI.Combinatorics.ContingencyTables.Counting.CountingExecutedMachine +import OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveWordLaw +import OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingWords + +namespace OAI + +/-! # Confidence amplification preserves the executed source law -/ +namespace ContingencyTables.CountingExecutedMachine +open MatchingFPRAS CommonBasesFPRAS CompanionFactorialApplication GridBoundary FiniteObservableTransport +open scoped Classical +noncomputable section +variable {m n : ℕ} + +theorem positive_sameLaw (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 + TreeFraction.val (CountingPositiveProgram.output + (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) + (RootedCountingWords.flatEstimate (ComputedCountingParameters.data hEK r c b hne epsilon he) + (ComputedCountingWords.root hEK r c b hne epsilon he) + (ComputedCountingParameters.settings hEK r c b hne epsilon he))) : + SameLaw (fun bits : Fin (positiveWidth (CountingDirectProgram.request r c b epsilon delta))→Bool => + TreeFraction.val (positive (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) + (ComputedCountingWords.estimate hEK r c b hne epsilon he delta) := by + have hpos : 0 + TreeFraction.val (CountingPositiveProgram.output + (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) + (RootedCountingWords.flatEstimate (ComputedCountingParameters.data hEK r c b hne epsilon he) + (ComputedCountingWords.root hEK r c b hne epsilon he) + (ComputedCountingParameters.settings hEK r c b hne epsilon he))) : + 1-(delta:ℝ) ≤ uniformAverage + (fun bits : Fin (positiveWidth (CountingDirectProgram.request r c b epsilon delta))→Bool => + if CountingBranchProgram.Accurate r c b epsilon (TreeFraction.val (positive + (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) then (1:ℝ) else 0) := by + have hl := positive_sameLaw hEK r c b hne epsilon delta he hd hs + have ha := ComputedCountingWords.positive_success hEK hPL hCheeger r c b hne epsilon delta he he1 hd hp + exact ha.trans_eq (hl (fun q => if CountingBranchProgram.Accurate r c b epsilon q then (1:ℝ) else 0)).symm + +end +end ContingencyTables.CountingExecutedMachine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBaseProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBaseProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..893971bde351c9fb400364c7621556a6f7f4abc1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBaseProgram.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingCoefficientProgram +import OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingParameters + +namespace OAI + +/-! # Executing the capacity-bit and dimension inputs to the counting schedule -/ + +namespace ContingencyTables.CountingBaseProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped +open NetworkVertexCode + +abbrev Input := NetworkVertexCode.Input × TreeFraction.Fraction + +def cellBits (x : ℕ) : ℕ := (x+1).size +def cellBitsRealizer : Realizer cellBits := + (composition (composition successor toBits) listLength).congr + (fun x => Nat.size_eq_bits_len (x+1)) +lemma polynomial_cellBits : PolynomialTime cellBitsRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_composition polynomial_successor polynomial_toBits) polynomial_listLength) + +def capacityBits (z : NetworkVertexCode.Input) : ℕ := + (((TightenedInputProgram.compute z).2.flatten).map cellBits).sum +def capacityBitsRealizer : Realizer capacityBits := + composition (f := fun z : NetworkVertexCode.Input => (TightenedInputProgram.compute z).2.flatten) + (g := fun xs : List ℕ => (xs.map cellBits).sum) + (composition (composition TightenedInputProgram.computeRealizer second) flatten) + (composition (map cellBitsRealizer) listSum) +lemma polynomial_capacityBits : PolynomialTime capacityBitsRealizer := + polynomial_composition (polynomial_composition + (polynomial_composition TightenedInputProgram.polynomial_compute polynomial_second) + polynomial_flatten) + (polynomial_composition (polynomial_map polynomial_cellBits) polynomial_listSum) + +def dimension (z : NetworkVertexCode.Input) : ℕ := 1+z.1.1.length*z.1.2.length +def dimensionRealizer : Realizer dimension := + composition (f := fun z : NetworkVertexCode.Input => (1,z.1.1.length*z.1.2.length)) + (g := fun p : ℕ×ℕ => p.1+p.2) (pair (constant 1) + (composition (pair (composition (composition first first) listLength) + (composition (composition first second) listLength)) multiply)) add +lemma polynomial_dimension : PolynomialTime dimensionRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 1) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_listLength) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_listLength)) + polynomial_multiply)) polynomial_add + +def half (e : TreeFraction.Fraction) : TreeFraction.Fraction := (e.1,2*e.2) +def halfRealizer : Realizer half := + pair first (composition (f := fun e : TreeFraction.Fraction => (2,e.2)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair (constant 2) second) multiply) +lemma polynomial_half : PolynomialTime halfRealizer := + polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_second) polynomial_multiply) + +lemma half_val (e : TreeFraction.Fraction) : TreeFraction.val (half e)=TreeFraction.val e/2 := by + simp only [half,TreeFraction.val,Nat.cast_mul,Nat.cast_ofNat] + ring + +def frame (z : Input) : CountingCoefficientProgram.Input := + ((capacityBits z.1,dimension z.1),half z.2) +def frameRealizer : Realizer frame := + pair (pair + (composition (f := fun z : Input => z.1) (g := capacityBits) first capacityBitsRealizer) + (composition (f := fun z : Input => z.1) (g := dimension) first dimensionRealizer)) + (composition (f := fun z : Input => z.2) (g := half) second halfRealizer) +lemma polynomial_frame : PolynomialTime frameRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_capacityBits) + (polynomial_composition polynomial_first polynomial_dimension)) + (polynomial_composition polynomial_second polynomial_half) + +def coefficient (z : Input) : ℕ := CountingCoefficientProgram.coefficient (frame z) +def coefficientRealizer : Realizer coefficient := + composition (f := frame) (g := CountingCoefficientProgram.coefficient) + frameRealizer CountingCoefficientProgram.coefficientRealizer +lemma polynomial_coefficient : PolynomialTime coefficientRealizer := + polynomial_composition polynomial_frame CountingCoefficientProgram.polynomial_coefficient + +lemma capacityBits_data {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + capacityBits (data r c b)=ComputedCountingParameters.capacityBits r c b := by + unfold capacityBits + rw [TightenedInputProgram.compute_code] + simp only [data,ResidualGraphProgram.natCode,List.map_flatten,List.map_ofFn,Function.comp_def, + List.sum_flatten,List.sum_ofFn,cellBits,ComputedCountingParameters.capacityBits, + Fintype.sum_prod_type] + +lemma dimension_data {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + dimension (data r c b)=ComputedCountingParameters.dimensionAllowance (m:=m) (n:=n) := by + simp only [dimension,data,List.length_ofFn,ComputedCountingParameters.dimensionAllowance] + +lemma coefficient_data {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) (he : 0 < epsilon) : + coefficient (data r c b,TreeFraction.repr epsilon)= + ComputedCountingParameters.coefficient r c b epsilon := by + unfold coefficient frame + rw [capacityBits_data,dimension_data] + have hn : 0 < (half (TreeFraction.repr epsilon)).1 := by + change 0 < epsilon.num.natAbs + exact Int.natAbs_pos.mpr (ne_of_gt (Rat.num_pos.mpr he)) + have hd : 0 < (half (TreeFraction.repr epsilon)).2 := by + change 0 < 2*epsilon.den + exact Nat.mul_pos (by decide) epsilon.pos + rw [CountingCoefficientProgram.coefficient_val _ _ _ hn hd,half_val, + TreeFraction.val_repr he.le] + rfl + +end ContingencyTables.CountingBaseProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchBudgetBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchBudgetBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..bded9137f001e470497f6e6acdc7bf554447d3d4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchBudgetBound.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectBudgetBound + +namespace OAI + +/-! # Combining the computed counting branches' public word budgets -/ +namespace ContingencyTables.CountingBranchProgram +open MatchingFPRAS CountingPublicInputBounds Polynomial +open scoped Classical +noncomputable section + +def budgetPolynomial (positivePolynomial : Polynomial ℕ) : Polynomial ℕ := + CountingDirectBudgetBound.budgetPolynomial+positivePolynomial + +lemma publicBudget_bound (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (positive : Request→ℕ) (p : Polynomial ℕ) + (hp : ∀ (m n : ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ), + (∃ X,TableTightening.Feasible r c b X) → ∀ epsilon delta : ℚ, + 0 < epsilon → 0 < delta → + positive (CountingDirectProgram.request r c b epsilon delta) ≤ p.eval (size r c b epsilon delta)) + (m n : ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (he : 0 < epsilon) (hd : 0 < delta) : + publicBudget positive (Algorithms.encodeCountingInput r c b epsilon delta) ≤ + (budgetPolynomial p).eval (size r c b epsilon delta) := by + have hrequest : request (CountingInputParser.parseInput + (Algorithms.encodeCountingInput r c b epsilon delta))= + CountingDirectProgram.request r c b epsilon delta := by + rw [CountingInputParser.public_spec] + rfl + unfold publicBudget + rw [hrequest] + by_cases hf : feasible (CountingDirectProgram.request r c b epsilon delta)=true + · have hne := (feasible_data hEK r c b epsilon delta).mp hf + by_cases hz : direct (CountingDirectProgram.request r c b epsilon delta)=true + · rw [budget_direct positive _ hf hz] + exact (CountingDirectBudgetBound.budget_public hEK r c b hne epsilon delta he hd).trans + (by simp only [budgetPolynomial,Polynomial.eval_add]; omega) + · have hz' : direct (CountingDirectProgram.request r c b epsilon delta)=false := + Bool.eq_false_iff.mpr hz + rw [budget_positive positive _ hf hz'] + exact (hp m n r c b hne epsilon delta he hd).trans + (by simp only [budgetPolynomial,Polynomial.eval_add]; omega) + · have hf' : feasible (CountingDirectProgram.request r c b epsilon delta)=false := + Bool.eq_false_iff.mpr hf + rw [budget_rejected positive _ hf'] + exact Nat.zero_le _ + +end +end ContingencyTables.CountingBranchProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..79bef4c0ec9b3678080883e6e67a7b5705059c59 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchMachine.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CountingMachineEvents + +namespace OAI + +/-! # Public-machine output guarantees for the counting dispatcher -/ +namespace ContingencyTables.CountingBranchProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream +open scoped Classical +noncomputable section + +variable (positive : Input→TreeFraction.Fraction) (F : Realizer positive) +variable (width : Request→ℕ) (N : Realizer width) + +noncomputable def machine : RandomMachine := + FiniteWordExecution.machine (publicBudgetRealizer width N) (publicOutputRealizer positive F) +noncomputable def machineTime (as : List Symbol) : ℕ := + FiniteWordExecution.machineTime (publicBudgetRealizer width N) (publicOutputRealizer positive F) as + +def sourceValue (as : List Symbol) (bits : Bits (publicBudget width as)) : ℚ := + TreeFraction.val (output positive (parsedInput (as,List.ofFn bits))) + +lemma sourceValue_nonnegative (as : List Symbol) (bits : Bits (publicBudget width as)) : + 0 ≤ sourceValue positive width as bits := TreeFraction.val_nonneg _ + +lemma sourceValue_output (as : List Symbol) (bits : Bits (publicBudget width as)) : + publicOutput positive (as,List.ofFn bits)=encodeRat (sourceValue positive width as bits) := + publicOutput_eq positive _ + +variable {m n : ℕ} + +/-- Every random tape halts with a nonnegative rational, including on +statistically unsuccessful histories of the positive-label branch. -/ +theorem outputs_nonnegative (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (t : ℕ) + (ht : machineTime positive F width N (Algorithms.encodeCountingInput r c b epsilon delta) ≤ t) : + ∀ bits : Bits t, ∃ q : ℚ, 0 ≤ q ∧ + Outputs (machine positive F width N) (Algorithms.encodeCountingInput r c b epsilon delta) bits q := by + have hh := FiniteWordExecution.machine_rational_all + (publicBudgetRealizer width N) (publicOutputRealizer positive F) + (Algorithms.encodeCountingInput r c b epsilon delta) + (CountingInputSymbols.counting_nonzero r c b epsilon delta) + (fun bs a ha => (publicOutput_symbols positive _ a ha).2) + (sourceValue positive width _) (sourceValue_output positive width _) + (fun q => 0 ≤ q) (sourceValue_nonnegative positive width _) t ht + intro bits + obtain ⟨q,hq,hp⟩ := hh bits + exact ⟨q,hp,hq⟩ + +lemma sourceValue_zero (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) + (hz : Algorithms.count r c b=0) + (bits : Bits (publicBudget width (Algorithms.encodeCountingInput r c b epsilon delta))) : + sourceValue positive width (Algorithms.encodeCountingInput r c b epsilon delta) bits=0 := by + have hf := (count_zero_iff_rejected hEK r c b epsilon delta).mp hz + unfold sourceValue + rw [parsedInput_public,output_rejected positive _ hf] + norm_num [TreeFraction.val] + +/-- Exact zero output follows from the executed feasibility test. -/ +theorem outputs_zero (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) + (hz : Algorithms.count r c b=0) (t : ℕ) + (ht : machineTime positive F width N (Algorithms.encodeCountingInput r c b epsilon delta) ≤ t) : + ∀ bits : Bits t, + Outputs (machine positive F width N) (Algorithms.encodeCountingInput r c b epsilon delta) bits 0 := by + have hh := FiniteWordExecution.machine_rational_all + (publicBudgetRealizer width N) (publicOutputRealizer positive F) + (Algorithms.encodeCountingInput r c b epsilon delta) + (CountingInputSymbols.counting_nonzero r c b epsilon delta) + (fun bs a ha => (publicOutput_symbols positive _ a ha).2) + (sourceValue positive width _) (sourceValue_output positive width _) + (fun q => q=0) (sourceValue_zero positive width hEK r c b epsilon delta hz) t ht + intro bits + obtain ⟨q,hq,rfl⟩ := hh bits + exact hq + +end +end ContingencyTables.CountingBranchProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7de4f51bb9b5b2ada3c0c8621fbc8c6bceebe58e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchProgram.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingInputParser +import OAI.Combinatorics.ContingencyTables.Machines.NetworkFeasibilityProgram +import OAI.Combinatorics.ContingencyTables.Machines.FractionOutputProgram + +namespace OAI + +/-! # Public dispatch for the two counting branches + +The positive-label evaluator is a program parameter, instantiated by the +adaptive estimator. Feasibility and the zero-label branch are computed from +the same parsed input used by the complete public machine. +-/ +namespace ContingencyTables.CountingBranchProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped +abbrev Request := CountingDirectProgram.Request +abbrev Input := CountingDirectProgram.Input + +/-- Reassociate the two rational parameters without re-encoding them. -/ +def request (z : CountingInputParser.Input) : Request := ((z.1,z.2.1),z.2.2) +def requestRealizer : Realizer request := + pair (pair first (composition second first)) (composition second second) +lemma polynomial_request : PolynomialTime requestRealizer := + polynomial_pair (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_composition polynomial_second polynomial_second) + +def feasible (z : Request) : Bool := NetworkFeasibilityProgram.test z.1.1 +def feasibleRealizer : Realizer feasible := + composition (f := fun z : Request => z.1.1) (g := NetworkFeasibilityProgram.test) + (composition first first) NetworkFeasibilityProgram.testRealizer +lemma polynomial_feasible : PolynomialTime feasibleRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) + NetworkFeasibilityProgram.polynomial_test + +def direct (z : Request) : Bool := decide (CountingComputedSettings.labelCount z.1=0) +def directRealizer : Realizer direct := + composition (f := fun z : Request => (CountingComputedSettings.labelCount z.1,0)) + (g := fun p : ℕ×ℕ => decide (p.1=p.2)) + (pair (composition (f := fun z : Request => z.1) (g := CountingComputedSettings.labelCount) + first CountingComputedSettings.labelCountRealizer) (constant 0)) natEqual +lemma polynomial_direct : PolynomialTime directRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first CountingComputedSettings.polynomial_labelCount) + (polynomial_constant 0)) polynomial_natEqual + +attribute [local irreducible] feasible direct + +section Evaluator +variable (positive : Input → TreeFraction.Fraction) (F : Realizer positive) + +def feasibleOutput (z : Input) : TreeFraction.Fraction := + if direct z.1 then CountingDirectProgram.output z else positive z +def feasibleOutputRealizer : Realizer (feasibleOutput positive) := + choose (composition (f := fun z : Input => z.1) (g := direct) first directRealizer) CountingDirectProgram.outputRealizer F +lemma polynomial_feasibleOutput (hF : PolynomialTime F) : + PolynomialTime (feasibleOutputRealizer positive F) := + polynomial_choose (polynomial_composition polynomial_first polynomial_direct) + CountingDirectProgram.polynomial_output hF + +attribute [local irreducible] feasibleOutput + +def output (z : Input) : TreeFraction.Fraction := + if feasible z.1 then feasibleOutput positive z else (0,1) +def outputRealizer : Realizer (output positive) := + choose (composition (f := fun z : Input => z.1) (g := feasible) first feasibleRealizer) (feasibleOutputRealizer positive F) (constant (0,1)) +lemma polynomial_output (hF : PolynomialTime F) : PolynomialTime (outputRealizer positive F) := + polynomial_choose (polynomial_composition polynomial_first polynomial_feasible) + (polynomial_feasibleOutput positive F hF) (polynomial_constant (0,1)) + +attribute [local irreducible] output + +def parsedInput (z : List Symbol×List Bool) : Input := + (request (CountingInputParser.parseInput z.1),z.2) +def parsedInputRealizer : Realizer parsedInput := + pair (composition (composition first CountingInputParser.publicRealizer) requestRealizer) second +lemma polynomial_parsedInput : PolynomialTime parsedInputRealizer := + polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first CountingInputParser.polynomial_public) polynomial_request) + polynomial_second + +def publicOutput (z : List Symbol×List Bool) : List Symbol := + FractionOutputProgram.output (output positive (parsedInput z)) +def publicOutputRealizer : Realizer (publicOutput positive) := + composition (f := fun z => output positive (parsedInput z)) (g := FractionOutputProgram.output) + (composition (f := parsedInput) (g := output positive) parsedInputRealizer (outputRealizer positive F)) + FractionOutputProgram.outputRealizer +lemma polynomial_publicOutput (hF : PolynomialTime F) : + PolynomialTime (publicOutputRealizer positive F) := + polynomial_composition (polynomial_composition polynomial_parsedInput + (polynomial_output positive F hF)) FractionOutputProgram.polynomial_output + +lemma publicOutput_eq (z : List Symbol×List Bool) : + publicOutput positive z=encodeRat (TreeFraction.val (output positive (parsedInput z))) := + FractionOutputProgram.output_eq _ + +lemma publicOutput_symbols (z : List Symbol×List Bool) (a : Symbol) + (ha : a∈publicOutput positive z) : a≠0 ∧ a≠6 ∧ a≠7 := + FractionOutputProgram.output_symbols _ a ha + +lemma output_nonnegative (z : Input) : 0 ≤ TreeFraction.val (output positive z) := + TreeFraction.val_nonneg _ + +end Evaluator + +section Budget +variable (positive : Request → ℕ) (N : Realizer positive) + +def feasibleBudget (z : Request) : ℕ := if direct z then CountingDirectProgram.budget z else positive z +def feasibleBudgetRealizer : Realizer (feasibleBudget positive) := + choose directRealizer CountingDirectProgram.budgetRealizer N +lemma polynomial_feasibleBudget (hN : PolynomialTime N) : + PolynomialTime (feasibleBudgetRealizer positive N) := + polynomial_choose polynomial_direct CountingDirectProgram.polynomial_budget hN + +attribute [local irreducible] feasibleBudget + +def budget (z : Request) : ℕ := if feasible z then feasibleBudget positive z else 0 +def budgetRealizer : Realizer (budget positive) := + choose feasibleRealizer (feasibleBudgetRealizer positive N) (constant 0) +lemma polynomial_budget (hN : PolynomialTime N) : PolynomialTime (budgetRealizer positive N) := + polynomial_choose polynomial_feasible (polynomial_feasibleBudget positive N hN) (polynomial_constant 0) + +attribute [local irreducible] budget + +def publicBudget (as : List Symbol) : ℕ := budget positive (request (CountingInputParser.parseInput as)) +def publicBudgetRealizer : Realizer (publicBudget positive) := + composition (f := fun as => request (CountingInputParser.parseInput as)) (g := budget positive) + (composition CountingInputParser.publicRealizer requestRealizer) (budgetRealizer positive N) +lemma polynomial_publicBudget (hN : PolynomialTime N) : PolynomialTime (publicBudgetRealizer positive N) := + polynomial_composition (polynomial_composition CountingInputParser.polynomial_public polynomial_request) + (polynomial_budget positive N hN) +end Budget + +end ContingencyTables.CountingBranchProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..76bf93094fb5ec0ce9ab481b921ed32e473c06f0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchSemantics.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectSemantics + +namespace OAI + +/-! # The public counting dispatch preserves the original bounded input -/ +namespace ContingencyTables.CountingBranchProgram +open MatchingFPRAS CompanionFactorialApplication +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma parsedInput_public (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (bits : List Bool) : + parsedInput (Algorithms.encodeCountingInput r c b epsilon delta,bits)= + (CountingDirectProgram.request r c b epsilon delta,bits) := by + unfold parsedInput + rw [CountingInputParser.public_spec] + rfl + +lemma feasible_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + feasible (CountingDirectProgram.request r c b epsilon delta)=true ↔ + ∃ X,TableTightening.Feasible r c b X := by + exact NetworkFeasibilityProgram.test_correct hEK r c b + +lemma count_zero_iff_rejected (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + Algorithms.count r c b=0 ↔ feasible (CountingDirectProgram.request r c b epsilon delta)=false := by + constructor + · intro hz + apply Bool.eq_false_iff.mpr + intro hf + obtain ⟨X,hX⟩ := (feasible_data hEK r c b epsilon delta).mp hf + have hp : 0 < Fintype.card (BoundedTable r c b) := + Fintype.card_pos_iff.mpr ⟨⟨⟨X,hX.1⟩,hX.2⟩⟩ + exact (Nat.ne_of_gt hp) hz + · intro hf + have hn : ¬∃ X,TableTightening.Feasible r c b X := by + intro hx + have ht := (feasible_data hEK r c b epsilon delta).mpr hx + rw [hf] at ht + exact Bool.false_ne_true ht + have hEmpty : IsEmpty (BoundedTable r c b) := ⟨fun X => hn ⟨X.val.val,X.val.property,X.property⟩⟩ + let := hEmpty + exact Fintype.card_eq_zero + +lemma direct_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + direct (CountingDirectProgram.request r c b epsilon delta)=true ↔ + Fintype.card (Labels (ComputedCountingParameters.data hEK r c b hne epsilon he))=0 := by + unfold direct CountingDirectProgram.request + rw [CountingComputedSettings.labelCount_data hEK r c b hne epsilon he] + simp only [decide_eq_true_eq] + +lemma output_rejected (positive : Input→TreeFraction.Fraction) (req : Request) + (h : feasible req=false) (bits : List Bool) : output positive (req,bits)=(0,1) := by + simp only [output,h,Bool.false_eq_true,ite_false] + +lemma output_direct (positive : Input→TreeFraction.Fraction) (req : Request) + (hf : feasible req=true) (hd : direct req=true) (bits : List Bool) : + output positive (req,bits)=CountingDirectProgram.output (req,bits) := by + simp only [output,feasibleOutput,hf,hd,ite_true] + +lemma output_positive (positive : Input→TreeFraction.Fraction) (req : Request) + (hf : feasible req=true) (hd : direct req=false) (bits : List Bool) : + output positive (req,bits)=positive (req,bits) := by + simp only [output,feasibleOutput,hf,hd,ite_true,Bool.false_eq_true,ite_false] + +lemma budget_rejected (positive : Request→ℕ) (req : Request) + (h : feasible req=false) : budget positive req=0 := by + simp only [budget,h,Bool.false_eq_true,ite_false] + +lemma budget_direct (positive : Request→ℕ) (req : Request) + (hf : feasible req=true) (hd : direct req=true) : + budget positive req=CountingDirectProgram.budget req := by + simp only [budget,feasibleBudget,hf,hd,ite_true] + +lemma budget_positive (positive : Request→ℕ) (req : Request) + (hf : feasible req=true) (hd : direct req=false) : budget positive req=positive req := by + simp only [budget,feasibleBudget,hf,hd,ite_true,Bool.false_eq_true,ite_false] + +end +end ContingencyTables.CountingBranchProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchSuccess.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchSuccess.lean new file mode 100644 index 0000000000000000000000000000000000000000..14e037473c508991def0ccd951c8f26d6307b206 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingBranchSuccess.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectSuccess +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchMachine + +namespace OAI + +/-! # Accuracy of the public dispatcher from its positive counting branch -/ +namespace ContingencyTables.CountingBranchProgram +open MatchingFPRAS CommonBasesFPRAS CompanionFactorialApplication GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +abbrev Accurate (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) (q : ℚ) : Prop := + (1-(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ) ≤ (q:ℝ) ∧ + (q:ℝ) ≤ (1+(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ) + +theorem success (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger (Grid (I := Fin q) k)) + (positive : Input→TreeFraction.Fraction) (width : Request→ℕ) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (he : 0 + if Accurate r c b epsilon (TreeFraction.val (positive + (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) then (1:ℝ) else 0)) : + 1-(delta:ℝ) ≤ uniformAverage + (fun bits : Fin (budget width (CountingDirectProgram.request r c b epsilon delta))→Bool => + if Accurate r c b epsilon (TreeFraction.val (output positive + (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) then (1:ℝ) else 0) := by + let req := CountingDirectProgram.request r c b epsilon delta + change 1-(delta:ℝ) ≤ uniformAverage + (fun bits : Fin (budget width req)→Bool => + if Accurate r c b epsilon (TreeFraction.val (output positive (req,List.ofFn bits))) + then (1:ℝ) else 0) + by_cases hf : feasible req=true + · have hne := (feasible_data hEK r c b epsilon delta).mp hf + by_cases hz : direct req=true + · rw [budget_direct width req hf hz] + simp_rw [output_direct positive req hf hz] + exact CountingDirectProgram.success hEK hPL hCheeger r c b hne epsilon delta he he1 hd + ((direct_data hEK r c b hne epsilon delta he).mp hz) + · have hz' := Bool.eq_false_iff.mpr hz + rw [budget_positive width req hf hz'] + simp_rw [output_positive positive req hf hz'] + exact hpositive hne (Nat.pos_of_ne_zero (fun h => hz + ((direct_data hEK r c b hne epsilon delta he).mpr h))) + · have hf' := Bool.eq_false_iff.mpr hf + have hzero := (count_zero_iff_rejected hEK r c b epsilon delta).mpr hf' + have hz : Fintype.card (BoundedTable r c b)=0 := hzero + simp_rw [output_rejected positive req hf',Accurate,hz,Nat.cast_zero,mul_zero] + norm_num [TreeFraction.val,uniformAverage_const] + exact_mod_cast hd.le + +end +end ContingencyTables.CountingBranchProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingCoefficientBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingCoefficientBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..109211375ff2c18a3ade374f4b4f0284852f48e5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingCoefficientBounds.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalSchedule +import OAI.Combinatorics.ContingencyTables.Counting.CountingScheduleSizes + +namespace OAI + +/-! # Numeric polynomial bounds for the computed terminal coefficient -/ + +namespace ContingencyTables.CountingCoefficientBounds +open CountingTerminalSchedule +noncomputable section + +lemma precision_le (epsilon : ℚ) (E : ℕ) (hE : 1/epsilon ≤ (E:ℚ)) : + precision epsilon ≤ E := by + unfold precision + have hc : ⌈1/epsilon⌉₊ ≤ E := Nat.ceil_le.mpr hE + exact Nat.clog_le_of_le_pow (hc.trans (Nat.lt_two_pow_self.le)) + +lemma allowance_le (L d E : ℕ) (epsilon : ℚ) (hE : 1/epsilon ≤ (E:ℚ)) : + allowance L d epsilon ≤ 20*(L+d+E+1) := by + have hp := precision_le epsilon E hE + unfold allowance + omega + +lemma coefficient_le (L d E : ℕ) (epsilon : ℚ) (he : 0 < epsilon) + (hE : 1/epsilon ≤ (E:ℚ)) : + coefficient L d epsilon ≤ 2048*d*(20*(L+d+E+1))^2*E := by + apply Nat.ceil_le.mpr + have ha := allowance_le L d E epsilon hE + have haQ : (allowance L d epsilon:ℚ) ≤ (20*(L+d+E+1):ℕ) := by exact_mod_cast ha + have hs : (allowance L d epsilon:ℚ)^2 ≤ ((20*(L+d+E+1):ℕ):ℚ)^2 := by + have ha0 : (0:ℚ) ≤ allowance L d epsilon := Nat.cast_nonneg _ + nlinarith + have hm := mul_le_mul hs hE (one_div_pos.mpr he).le (sq_nonneg _) + have hmul := mul_le_mul_of_nonneg_left hm (show (0:ℚ) ≤ 2048*d by positivity) + convert hmul using 1 <;> push_cast <;> ring + +open Polynomial + +def coefficientPolynomial : Polynomial ℕ := 2048*X*(20*(3*X+1))^2*X + +lemma coefficient_polynomial (L d E M : ℕ) (epsilon : ℚ) (he : 0 < epsilon) + (hE : 1/epsilon ≤ (E:ℚ)) (hL : L ≤ M) (hd : d ≤ M) (hEM : E ≤ M) : + coefficient L d epsilon ≤ coefficientPolynomial.eval M := by + have hb := coefficient_le L d E epsilon he hE + have ha : 20*(L+d+E+1) ≤ 20*(3*M+1) := by omega + have ht : 2048*d*(20*(L+d+E+1))^2*E ≤ 2048*M*(20*(3*M+1))^2*M := + Nat.mul_le_mul (Nat.mul_le_mul (Nat.mul_le_mul_left 2048 hd) + (Nat.pow_le_pow_left ha 2)) hEM + exact hb.trans (by simpa only [coefficientPolynomial,eval_mul,eval_ofNat,eval_X, + eval_pow,eval_add,eval_one] using ht) + +end +end ContingencyTables.CountingCoefficientBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingCoefficientProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingCoefficientProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..48573df756b5416065f12a947c95253ebd112b27 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingCoefficientProgram.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalSchedule +import OAI.Combinatorics.ContingencyTables.Machines.OffsetCountProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram +import OAI.Combinatorics.MatchingCount.Complexity.TreeFractionCosts + +namespace OAI + +/-! # The terminal coefficient computed with binary natural arithmetic -/ + +namespace ContingencyTables.CountingCoefficientProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.TreeFraction Polynomial +open OffsetCountPrograms DensePrograms + +abbrev Input := (ℕ×ℕ)×Fraction + +def precision (e : Fraction) : ℕ := Nat.clog 2 (ceilQuotient (e.2,e.1)) +def precisionRealizer : Realizer precision := + composition (f := fun e : Fraction => ceilQuotient (e.2,e.1)) (g := Nat.clog 2) + (composition (pair second first) ceilQuotientRealizer) ceilLogTwoRealizer +lemma polynomial_precision : PolynomialTime precisionRealizer := + polynomial_composition + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + polynomial_ceilQuotient) polynomial_ceilLogTwo + +def allowance (z : Input) : ℕ := 20*(z.1.1+z.1.2+precision z.2+1) +def allowanceRealizer : Realizer allowance := by + let ld : Realizer (fun z : Input => z.1.1+z.1.2) := composition first add + let pr : Realizer (fun z : Input => precision z.2) := + composition (f := fun z : Input => z.2) (g := precision) second precisionRealizer + let s : Realizer (fun z : Input => z.1.1+z.1.2+precision z.2+1) := + composition (composition (pair ld pr) add) successor + exact composition (f := fun z : Input => (20,z.1.1+z.1.2+precision z.2+1)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair (constant 20) s) multiply +lemma polynomial_allowance : PolynomialTime allowanceRealizer := by + unfold allowanceRealizer + exact polynomial_composition (polynomial_pair (polynomial_constant 20) + (polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first TreeTyped.polynomial_add) + (polynomial_composition polynomial_second polynomial_precision)) TreeTyped.polynomial_add) + polynomial_successor)) polynomial_multiply + +def numerator (z : Input) : ℕ := 2048*z.1.2*(allowance z)^2*z.2.2 +def numeratorRealizer : Realizer numerator := by + let d : Realizer (fun z : Input => 2048*z.1.2) := + composition (f := fun z : Input => (2048,z.1.2)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 2048) (composition first second)) multiply + let sq : Realizer (fun z : Input => (allowance z)^2) := + (composition (pair allowanceRealizer allowanceRealizer) multiply).congr + (fun z => (pow_two _).symm) + exact composition (pair (composition (pair d sq) multiply) (composition second second)) multiply +lemma polynomial_numerator : PolynomialTime numeratorRealizer := by + unfold numeratorRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 2048) + (polynomial_composition polynomial_first polynomial_second)) polynomial_multiply) + (polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_allowance polynomial_allowance) polynomial_multiply))) + polynomial_multiply) + (polynomial_composition polynomial_second polynomial_second)) polynomial_multiply + +def coefficient (z : Input) : ℕ := ceilQuotient (numerator z,z.2.1) +def coefficientRealizer : Realizer coefficient := + composition (f := fun z : Input => (numerator z,z.2.1)) (g := ceilQuotient) + (pair numeratorRealizer (composition second first)) ceilQuotientRealizer +lemma polynomial_coefficient : PolynomialTime coefficientRealizer := + polynomial_composition (polynomial_pair polynomial_numerator + (polynomial_composition polynomial_second polynomial_first)) polynomial_ceilQuotient + +lemma precision_val (e : Fraction) (hn : 0 < e.1) : + precision e=CountingTerminalSchedule.precision (val e) := by + unfold precision CountingTerminalSchedule.precision + rw [ceilQuotient_eq e.2 e.1 hn] + congr 2 + simp only [val,one_div,inv_div] + +lemma allowance_val (L d : ℕ) (e : Fraction) (hn : 0 < e.1) : + allowance ((L,d),e)=CountingTerminalSchedule.allowance L d (val e) := by + simp only [allowance,CountingTerminalSchedule.allowance,precision_val e hn] + +lemma coefficient_val (L d : ℕ) (e : Fraction) (hn : 0 < e.1) (hd : 0 < e.2) : + coefficient ((L,d),e)=CountingTerminalSchedule.coefficient L d (val e) := by + unfold coefficient + rw [ceilQuotient_eq _ _ hn] + unfold CountingTerminalSchedule.coefficient + rw [←allowance_val L d e hn] + congr 1 + simp only [numerator,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_pow,val] + field_simp + +lemma coefficient_repr (L d : ℕ) (epsilon : ℚ) (he : 0 < epsilon) : + coefficient ((L,d),TreeFraction.repr epsilon)= + CountingTerminalSchedule.coefficient L d epsilon := by + have hn : 0 < (TreeFraction.repr epsilon).1 := by + change 0 < epsilon.num.natAbs + exact Int.natAbs_pos.mpr (ne_of_gt (Rat.num_pos.mpr he)) + rw [coefficient_val L d _ hn epsilon.pos,TreeFraction.val_repr he.le] + +end ContingencyTables.CountingCoefficientProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingComputedSettings.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingComputedSettings.lean new file mode 100644 index 0000000000000000000000000000000000000000..e549b6a688e6fa68b4d10bfecf2838ad5525fcf9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingComputedSettings.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseParametersProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingLabelCountProgram +import OAI.Combinatorics.ContingencyTables.Rooted.ComputedRootedInput + +namespace OAI + +/-! # Computing every scalar control from the original bounded table -/ + +namespace ContingencyTables.CountingComputedSettings +open MatchingFPRAS MatchingFPRAS.TreeTyped ScalarScheduleProgram +open CountingPhaseScalarProgram + +abbrev Input := CountingBaseProgram.Input +abbrev Parameters := CountingPhaseParametersProgram.Input + +def catalog (z : Input) : RootedForestCatalog.Data := + ComputedRootedInput.catalogData (z.1,CountingTerminalProgram.cutoff z) +def catalogRealizer : Realizer catalog := + composition (f := fun z : Input => (z.1,CountingTerminalProgram.cutoff z)) + (g := ComputedRootedInput.catalogData) (pair first CountingTerminalProgram.cutoffRealizer) + ComputedRootedInput.catalogDataRealizer +lemma polynomial_catalog : PolynomialTime catalogRealizer := + polynomial_composition (polynomial_pair polynomial_first CountingTerminalProgram.polynomial_cutoff) + ComputedRootedInput.polynomial_catalogData + +def labelCount (z : Input) : ℕ := CountingLabelCountProgram.count (catalog z) +def labelCountRealizer : Realizer labelCount := + composition (f := catalog) (g := CountingLabelCountProgram.count) + catalogRealizer CountingLabelCountProgram.countRealizer +lemma polynomial_labelCount : PolynomialTime labelCountRealizer := + polynomial_composition polynomial_catalog CountingLabelCountProgram.polynomial_count + +def preliminary (z : Input) : List ℕ := + [labelCount z,CountingTerminalProgram.cutoff z,CountingTerminalProgram.phases z,0,0,0, + CountingBaseProgram.capacityBits z.1] +private def consR {f : Input → ℕ} {g : Input → List ℕ} + (F : Realizer f) (G : Realizer g) : Realizer (fun z => f z::g z) := + composition (f := fun z : Input => (f z,g z)) (g := fun p : ℕ×List ℕ => p.1::p.2) + (pair F G) listCons +private lemma poly_consR {f : Input → ℕ} {g : Input → List ℕ} + (F : Realizer f) (G : Realizer g) (hF : PolynomialTime F) (hG : PolynomialTime G) : + PolynomialTime (consR F G) := polynomial_composition (polynomial_pair hF hG) polynomial_listCons + +def preliminaryRealizer : Realizer preliminary := + consR labelCountRealizer (consR CountingTerminalProgram.cutoffRealizer + (consR CountingTerminalProgram.phasesRealizer (consR (constant 0) (consR (constant 0) + (consR (constant 0) (consR (composition (f := fun z : Input => z.1) + (g := CountingBaseProgram.capacityBits) first CountingBaseProgram.capacityBitsRealizer) + (constant []))))))) +lemma polynomial_preliminary : PolynomialTime preliminaryRealizer := by + unfold preliminaryRealizer + apply poly_consR _ _ polynomial_labelCount + apply poly_consR _ _ CountingTerminalProgram.polynomial_cutoff + apply poly_consR _ _ CountingTerminalProgram.polynomial_phases + apply poly_consR _ _ (polynomial_constant 0) + apply poly_consR _ _ (polynomial_constant 0) + apply poly_consR _ _ (polynomial_constant 0) + exact poly_consR _ _ (polynomial_composition polynomial_first CountingBaseProgram.polynomial_capacityBits) + (polynomial_constant []) + +def fullReturnCap : Expr := 65536*(h+1)^2*(restartTime+1)*(p^2+1) +def controlExpressions : List Expr := [p,w,h,restartTime,0,fullReturnCap,capacityBits] + +def basic (z : Input) : Parameters := + (vector controlExpressions (preliminary z),CountingBaseProgram.half z.2) +def basicRealizer : Realizer basic := + pair (composition (f := preliminary) (g := vector controlExpressions) + preliminaryRealizer (vectorRealizer controlExpressions)) + (composition second CountingBaseProgram.halfRealizer) +lemma polynomial_basic : PolynomialTime basicRealizer := + polynomial_pair (polynomial_composition polynomial_preliminary (polynomial_vector controlExpressions)) + (polynomial_composition polynomial_second CountingBaseProgram.polynomial_half) + +def fillObservations (z : Parameters) : Parameters := + (z.1.take 4++(CountingPhaseParametersProgram.observations z::z.1.drop 5),z.2) +def fillObservationsRealizer : Realizer fillObservations := by + let frontR : Realizer (fun z : Parameters => z.1.take 4) := + composition (f := fun z : Parameters => (z.1,4)) + (g := fun p : List ℕ×ℕ => p.1.take p.2) (pair first (constant 4)) takeFast + let suffix : Realizer (fun z : Parameters => z.1.drop 5) := + composition (f := fun z : Parameters => (z.1,5)) + (g := fun p : List ℕ×ℕ => p.1.drop p.2) (pair first (constant 5)) dropFast + let tailR : Realizer (fun z : Parameters => CountingPhaseParametersProgram.observations z::z.1.drop 5) := + composition (pair CountingPhaseParametersProgram.observationsRealizer suffix) listCons + exact pair (composition (pair frontR tailR) append) second +lemma polynomial_fillObservations : PolynomialTime fillObservationsRealizer := by + unfold fillObservationsRealizer + exact polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first (polynomial_constant 4)) polynomial_takeFast) + (polynomial_composition (polynomial_pair CountingPhaseParametersProgram.polynomial_observations + (polynomial_composition (polynomial_pair polynomial_first (polynomial_constant 5)) polynomial_dropFast)) + polynomial_listCons)) polynomial_append) polynomial_second + +def parameters (z : Input) : Parameters := fillObservations (basic z) +def parametersRealizer : Realizer parameters := + composition (f := basic) (g := fillObservations) basicRealizer fillObservationsRealizer +lemma polynomial_parameters : PolynomialTime parametersRealizer := + polynomial_composition polynomial_basic polynomial_fillObservations + +open CompanionFactorialApplication +open scoped Classical +variable {m n : ℕ} + +lemma catalog_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + catalog (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + RootedForestCatalog.data (ComputedCountingParameters.data hEK r c b hne epsilon he) := by + unfold catalog + rw [CountingTerminalProgram.cutoff_data r c b epsilon he] + exact ComputedRootedInput.catalogData_instance hEK r c b hne _ _ + +lemma labelCount_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + labelCount (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + Fintype.card (Labels (ComputedCountingParameters.data hEK r c b hne epsilon he)) := by + rw [labelCount,catalog_data hEK r c b hne epsilon he,CountingLabelCountProgram.count_data] + +lemma basic_values (P W H L : ℕ) : + vector controlExpressions [P,W,H,0,0,0,L]= + [P,W,H,4*CountingPhaseSchedule.observable P W*(H+P+L+5),0, + CountingPhaseSchedule.returnCap P H (4*CountingPhaseSchedule.observable P W*(H+P+L+5)),L] := by + simp [vector,controlExpressions,CountingPhaseScalarProgram.p,CountingPhaseScalarProgram.w, + CountingPhaseScalarProgram.h,capacityBits,restartTime,observable,fullReturnCap,Expr.eval, + CountingPhaseSchedule.observable,CountingPhaseSchedule.returnCap] + +lemma fillObservations_values (P W H T N R L : ℕ) (e : CountingOracleScheduleProgram.Fraction) : + fillObservations ([P,W,H,T,N,R,L],e)= + ([P,W,H,T,CountingPhaseSchedule.observations P W H + (CountingPhaseSchedule.tolerance H (TreeFraction.val e)),R,L],e) := by + simp [fillObservations,CountingPhaseParametersProgram.observations_val] + +end ContingencyTables.CountingComputedSettings + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingConditionalAssembly.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingConditionalAssembly.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1fbd4cc10236c2e52934ff8009d67f5101a2aad --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingConditionalAssembly.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingAmplifiedSourceLaw +import OAI.Combinatorics.ContingencyTables.Counting.CountingPublicAccuracy + +namespace OAI + +/-! # Assembly of the public counting specification from its executed history law -/ +namespace ContingencyTables.CountingExecutedMachine +open MatchingFPRAS CommonBasesFPRAS CompanionFactorialApplication GridBoundary FiniteObservableTransport +open scoped Classical +noncomputable section + +theorem statement_of_single_law + (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger (Grid (I := Fin q) k)) + (hlaw : ∀ (m n : ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 + TreeFraction.val (CountingPositiveProgram.output + (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) + (RootedCountingWords.flatEstimate (ComputedCountingParameters.data hEK r c b hne epsilon he) + (ComputedCountingWords.root hEK r c b hne epsilon he) + (ComputedCountingParameters.settings hEK r c b hne epsilon he))) : + Algorithms.CountingStatement := by + obtain ⟨C,d,hC,ht⟩ := public_time hEK + refine ⟨machine,C,d,hC,?_⟩ + intro m n _ _ r c b _ epsilon delta he he1 hd _ + have htime := ht m n r c b epsilon delta he hd + refine ⟨outputs_nonnegative r c b epsilon delta _ htime, + (fun hz => outputs_zero hEK r c b epsilon delta hz _ htime),?_⟩ + apply public_success hEK hPL hCheeger r c b epsilon delta he he1 hd + · intro hne hp + exact positive_success hEK hPL hCheeger r c b hne epsilon delta he he1 hd hp + (hlaw m n r c b hne epsilon delta he) + · exact htime + +end +end ContingencyTables.CountingExecutedMachine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingControlBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingControlBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..9457c56a9f3af6e33647a567b61cde3e6f532dd9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingControlBounds.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ScalarScheduleBounds +import OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseScalarProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingScheduleSizes + +namespace OAI + +/-! # Polynomial bounds for the observation and precision controls -/ + +namespace ContingencyTables.CountingControlBounds +open ScalarScheduleProgram CountingPhaseSchedule Polynomial +noncomputable section + +def observationPolynomial : Polynomial ℕ := + CountingPhaseScalarProgram.observationNumerator.bound*(1600*(X+1)*X)^2+2 +def returnPolynomial : Polynomial ℕ := CountingPhaseScalarProgram.returnCap.bound +def largePolynomial : Polynomial ℕ := X+observationPolynomial+returnPolynomial+1 +def precisionPolynomial : Polynomial ℕ := + CountingPhaseScalarProgram.precisionBase.bound.comp largePolynomial+1600*(X+1)*X + +lemma half_inverse_le (epsilon : ℚ) (M : ℕ) (h : 1/epsilon ≤ (M:ℚ)) : + 1/(epsilon/2) ≤ ((2*M:ℕ):ℚ) := by + have hh := mul_le_mul_of_nonneg_left h (show (0:ℚ) ≤ 2 by norm_num) + convert hh using 1 <;> push_cast <;> ring + +lemma observations_bound (p W H M : ℕ) (epsilon : ℚ) (he : 0 < epsilon) + (hp : p ≤ M) (hW : W ≤ M) (hH : H ≤ M) (hi : 1/epsilon ≤ (M:ℚ)) : + observations p W H (tolerance H (epsilon/2)) ≤ observationPolynomial.eval M := by + have hn := observations_le p W H (2*M) (epsilon/2) (by positivity) + (half_inverse_le epsilon M hi) + have hnumer := CountingPhaseScalarProgram.observationNumerator.eval_le_of_mem + [p,W,H,0,0,0,0] M (by + intro x hx + simp only [List.mem_cons,List.not_mem_nil,or_false] at hx + rcases hx with rfl | rfl | rfl | rfl | rfl | rfl | rfl <;> omega) + rw [CountingPhaseScalarProgram.observationNumerator_value] at hnumer + have ht : 800*(H+1)*(2*M) ≤ 1600*(M+1)*M := by + calc + _ = 1600*(H+1)*M := by ring + _ ≤ _ := Nat.mul_le_mul_right M (Nat.mul_le_mul_left 1600 (Nat.add_le_add_right hH 1)) + refine hn.trans ?_ + simp only [observationBound,observationPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_pow,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + exact Nat.add_le_add_right (Nat.mul_le_mul hnumer (Nat.pow_le_pow_left ht 2)) 2 + +lemma return_bound (p H T M : ℕ) (hp : p ≤ M) (hH : H ≤ M) (hT : T ≤ M) : + returnCap p H T ≤ returnPolynomial.eval M := by + have hb := CountingPhaseScalarProgram.returnCap.eval_le_of_mem [p,0,H,T,0,0,0] M (by + intro x hx + simp only [List.mem_cons,List.not_mem_nil,or_false] at hx + rcases hx with rfl | rfl | rfl | rfl | rfl | rfl | rfl <;> omega) + rwa [CountingPhaseScalarProgram.returnCap_value] at hb + +lemma precision_bound (p W H T M : ℕ) (epsilon : ℚ) (he : 0 < epsilon) + (hp : p ≤ M) (hW : W ≤ M) (hH : H ≤ M) (hT : T ≤ M) + (hi : 1/epsilon ≤ (M:ℚ)) : + precision H T (observations p W H (tolerance H (epsilon/2))) (returnCap p H T) + (tolerance H (epsilon/2)) ≤ precisionPolynomial.eval M := by + let N := observations p W H (tolerance H (epsilon/2)) + let R := returnCap p H T + have hN : N ≤ observationPolynomial.eval M := observations_bound p W H M epsilon he hp hW hH hi + have hR : R ≤ returnPolynomial.eval M := return_bound p H T M hp hH hT + have hB : M ≤ largePolynomial.eval M := by + simp only [largePolynomial,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + omega + have hb := CountingPhaseScalarProgram.precisionBase.eval_le_of_mem [p,W,H,T,N,R,0] + (largePolynomial.eval M) (by + intro x hx + simp only [List.mem_cons,List.not_mem_nil,or_false] at hx + have hN' : N ≤ largePolynomial.eval M := by + simp only [largePolynomial,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + omega + have hR' : R ≤ largePolynomial.eval M := by + simp only [largePolynomial,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + omega + rcases hx with rfl | rfl | rfl | rfl | rfl | rfl | rfl <;> omega) + rw [CountingPhaseScalarProgram.precisionBase_value] at hb + have hc : ⌈1/tolerance H (epsilon/2)⌉₊ ≤ 1600*(M+1)*M := by + apply (Nat.ceil_le.mpr (inverse_tolerance_le H (2*M) (epsilon/2) (by positivity) + (half_inverse_le epsilon M hi))).trans + calc + 800*(H+1)*(2*M)=1600*(H+1)*M := by ring + _ ≤ _ := Nat.mul_le_mul_right M (Nat.mul_le_mul_left 1600 (Nat.add_le_add_right hH 1)) + simp only [precisionPolynomial,Polynomial.eval_add,Polynomial.eval_comp,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + change 1024*(H+1)*noiseCoefficient H T N R+⌈1/tolerance H (epsilon/2)⌉₊+1 ≤ _ + omega + +end +end ContingencyTables.CountingControlBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectBudgetBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectBudgetBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..817a6f8ac37d8b7cda5fcb9e2c257fec865951e0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectBudgetBound.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectWordBound +import OAI.Combinatorics.ContingencyTables.Counting.CountingMarkerBounds + +namespace OAI + +/-! # Public runtime allowance for the direct branch's padded random word -/ +namespace ContingencyTables.CountingDirectBudgetBound +open Polynomial CountingPublicInputBounds +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def budgetPolynomial : Polynomial ℕ := CountingDirectWordBound.wordPolynomial+ + CountingMarkerBounds.paddingPolynomial.comp CountingDirectWordBound.controlPolynomial + +lemma budget_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) + (he : 0 < epsilon) (hd : 0 < delta) : + CountingDirectProgram.budget (CountingDirectProgram.request r c b epsilon delta) ≤ + budgetPolynomial.eval (size r c b epsilon delta) := by + let S := size r c b epsilon delta + let M := CountingDirectWordBound.controlPolynomial.eval S + have hH : ComputedCountingParameters.phases r c b epsilon ≤ M := by + have hb : CountingTerminalBounds.phasePolynomial.eval S ≤ M := by + simp only [M,CountingDirectWordBound.controlPolynomial,CountingPublicWordBound.controlPolynomial, + Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + exact (CountingPublicTerminalBounds.terminal_public hEK r c b hne epsilon delta he).2.2.trans hb + have h4S : 4*S ≤ M := by + simp only [M,CountingDirectWordBound.controlPolynomial, + Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + omega + have hi : 1/((epsilon/2)/2) ≤ (M:ℚ) := by + have hh := mul_le_mul_of_nonneg_left (inverse_le r c b epsilon delta) + (show (0:ℚ) ≤ 4 by norm_num) + have hh' : 1/((epsilon/2)/2) ≤ ((4*S:ℕ):ℚ) := by + convert hh using 1 <;> push_cast <;> ring + exact hh'.trans (by exact_mod_cast h4S) + have hp := CountingMarkerBounds.padding_bound + (ComputedCountingParameters.phases r c b epsilon) M ((epsilon/2)/2) hH (by positivity) hi + rw [CountingDirectProgram.budget_data hEK r c b hne epsilon delta he hd] + have hw := CountingDirectWordBound.zeroBits_public hEK r c b hne epsilon delta he + rw [Nat.add_assoc] + simpa only [budgetPolynomial,Polynomial.eval_add,Polynomial.eval_comp, + CountingDirectProgram.degree,CountingDirectProgram.depth,S,M] using Nat.add_le_add hw hp + +end +end ContingencyTables.CountingDirectBudgetBound + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..677ef4423072df384c362cfaaff83528399b8103 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectLaw.lean @@ -0,0 +1,167 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectSemantics +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableReindex +import OAI.Combinatorics.ContingencyTables.Transport.FinitePaddedAverage + +namespace OAI + +/-! # Exact law of the executed direct counting estimator -/ +namespace ContingencyTables.CountingDirectProgram +open MatchingFPRAS CompanionFactorialApplication CompanionOracleDensity GridBoundary +open CommonBasesFPRAS FiniteObservableTransport +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def modelContext (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + RootedEstimatorLayoutProgram.Context := + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let C := ComputedCountingParameters.coefficient r c b epsilon + let K := ComputedCountingParameters.binCount r c b epsilon + RootedEstimatorMedianProgram.context A C K (ComputedCountingParameters.phases r c b epsilon) + ((epsilon/2)/2) (fun _ => 0) + (CountingPreparedState.start A K (ComputedCountingParameters.binCount_pos r c b epsilon he)) + +def modelWidth (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) (delta : ℚ) : ℕ := + repetitionCount delta*RootedEstimatorLayoutProgram.wordWidth (modelContext hEK r c b hne epsilon he) + +def modelValue (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : ℚ) (bits : List Bool) : ℚ := + TreeFraction.val (RootedEstimatorMedianProgram.output + ((modelContext hEK r c b hne epsilon he,repetitionCount delta), + ((List.replicate (degree r c b epsilon) false,List.replicate (depth r c b epsilon) false),bits))) + +attribute [local irreducible] modelContext modelWidth modelValue +attribute [local irreducible] ComputedCountingParameters.data ComputedCountingParameters.coefficient +attribute [local irreducible] ComputedCountingParameters.phases ComputedCountingParameters.binCount +attribute [local irreducible] ComputedCountingZero.zeroEstimate ComputedCountingZero.zeroBits + +lemma modelWidth_eq (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) (delta : ℚ) : + modelWidth hEK r c b hne epsilon he delta=ComputedCountingZero.zeroBits hEK r c b hne epsilon he delta := by + unfold modelWidth modelContext RootedEstimatorMedianProgram.context + rw [RootedEstimatorWordProgram.scheduledWordWidth] + unfold ComputedCountingZero.zeroBits medianEstimatorBits + rw [←ComputedCountingParameters.phases_final hEK r c b hne epsilon he] + +def referenceBits (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) (delta : ℚ) : ℕ := + medianEstimatorBits (ComputedCountingParameters.data hEK r c b hne epsilon he) + (ComputedCountingParameters.coefficient r c b epsilon) (ComputedCountingParameters.binCount r c b epsilon) + (ComputedCountingParameters.phases r c b epsilon) ((epsilon/2)/2) delta + +def reference (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) (delta : ℚ) + (bits : Fin (referenceBits hEK r c b hne epsilon he delta)→Bool) : ℚ := + RootedOracleDensity.medianEstimate (ComputedCountingParameters.data hEK r c b hne epsilon he) + (ComputedCountingWords.root hEK r c b hne epsilon he) (ComputedCountingParameters.coefficient r c b epsilon) + (fun _ => 0) (ComputedCountingParameters.binCount r c b epsilon) + (ComputedCountingParameters.binCount_pos r c b epsilon he) + (ComputedCountingParameters.cutoff_eq hEK r c b hne epsilon he).ge + (ComputedCountingParameters.phases r c b epsilon) ((epsilon/2)/2) delta + (ComputedCountingParameters.start hEK r c b hne epsilon he) bits + +attribute [local irreducible] referenceBits reference + +lemma native_sameLaw (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + SameLaw (fun bits : Fin (modelWidth hEK r c b hne epsilon he delta)→Bool => + modelValue hEK r c b hne epsilon he delta (List.ofFn bits)) + (reference hEK r c b hne epsilon he delta) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let C := ComputedCountingParameters.coefficient r c b epsilon + let K := ComputedCountingParameters.binCount r c b epsilon + let H := ComputedCountingParameters.phases r c b epsilon + have hs := RootedEstimatorMedianProgram.sameLaw A C K H + (ComputedCountingParameters.coefficient_pos r c b epsilon he) + (ComputedCountingParameters.phases_height hEK r c b hne epsilon he).le + (ComputedCountingParameters.binCount_pos r c b epsilon he) + (ComputedCountingParameters.cutoff_eq hEK r c b hne epsilon he).ge + (ComputedCountingParameters.binCount_cast hEK r c b hne epsilon he) + ((epsilon/2)/2) delta (by positivity) (fun _ => 0) (fun _ => Nat.zero_le _) + (CountingPreparedState.start A K (ComputedCountingParameters.binCount_pos r c b epsilon he)) + (List.replicate (degree r c b epsilon) false) (List.replicate (depth r c b epsilon) false) + (by rw [List.length_replicate]; rfl) (by rw [List.length_replicate]; rfl) + dsimp only [A,C,K,H] at hs + rw [CountingPreparedState.start_transport hEK r c b hne epsilon he] at hs + unfold RootedEstimatorMedianProgram.value at hs + unfold modelWidth modelValue modelContext reference referenceBits ComputedCountingWords.root + exact hs + +lemma reference_sameLaw (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + SameLaw (reference hEK r c b hne epsilon he delta) + (ComputedCountingZero.zeroEstimate hEK r c b hne epsilon he delta) := by + unfold reference referenceBits ComputedCountingZero.zeroEstimate ComputedCountingZero.zeroBits + rw [←ComputedCountingParameters.phases_final hEK r c b hne epsilon he] + intro phi + rfl + +lemma model_sameLaw (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + SameLaw (fun bits : Fin (modelWidth hEK r c b hne epsilon he delta)→Bool => + modelValue hEK r c b hne epsilon he delta (List.ofFn bits)) + (ComputedCountingZero.zeroEstimate hEK r c b hne epsilon he delta) := by + intro phi + exact (native_sameLaw hEK r c b hne epsilon delta he phi).trans + (reference_sameLaw hEK r c b hne epsilon delta he phi) + +lemma output_model (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) + (he : 0 < epsilon) (hd : 0 < delta) (N : ℕ) + (hwidth : modelWidth hEK r c b hne epsilon he delta ≤ N) + (hdegree : degree r c b epsilon ≤ N) (hdepth : depth r c b epsilon ≤ N) + (bits : Fin N→Bool) : + TreeFraction.val (output (request r c b epsilon delta,List.ofFn bits))= + modelValue hEK r c b hne epsilon he delta + (List.ofFn (FirstSuccess.prefixWord hwidth bits)) := by + have hw : wordWidth (request r c b epsilon delta,List.ofFn bits)=modelWidth hEK r c b hne epsilon he delta := + (wordWidth_data hEK r c b hne epsilon delta he hd _).trans (modelWidth_eq hEK r c b hne epsilon he delta).symm + have hc : context (request r c b epsilon delta,List.ofFn bits)=modelContext hEK r c b hne epsilon he := + by + unfold modelContext + exact context_data hEK r c b hne epsilon delta he _ + have hr : repeats (request r c b epsilon delta,List.ofFn bits)=repetitionCount delta := by + change FractionRepetitionProgram.count (TreeFraction.repr delta)=_ + rw [FractionRepetitionProgram.count_val,TreeFraction.val_repr hd.le] + have hm := markers_data hEK r c b hne epsilon delta he N hdegree hdepth bits + unfold output medianInput config sampleBits + rw [hc,hr,hm,hw,BinVectorProgram.take_ofFn_prefix hwidth] + unfold modelValue + rfl + +lemma sameLaw (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) + (he : 0 < epsilon) (hd : 0 < delta) : + SameLaw (fun bits : Fin (budget (request r c b epsilon delta))→Bool => + TreeFraction.val (output (request r c b epsilon delta,List.ofFn bits))) + (ComputedCountingZero.zeroEstimate hEK r c b hne epsilon he delta) := by + have hbudget := budget_data hEK r c b hne epsilon delta he hd + have hwidth : modelWidth hEK r c b hne epsilon he delta ≤ budget (request r c b epsilon delta) := by + rw [modelWidth_eq,hbudget] + omega + have hdegree : degree r c b epsilon ≤ budget (request r c b epsilon delta) := by omega + have hdepth : depth r c b epsilon ≤ budget (request r c b epsilon delta) := by omega + intro phi + simp_rw [output_model hEK r c b hne epsilon delta he hd _ hwidth hdegree hdepth] + exact (FairBits.padded_equiv_average hwidth (Equiv.refl _) (fun bits => + phi (modelValue hEK r c b hne epsilon he delta (List.ofFn bits)))).trans + (model_sameLaw hEK r c b hne epsilon delta he phi) + +end +end ContingencyTables.CountingDirectProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..98b2ce902dc4a0548fa9e7a7ceb85a4b3d232b77 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectProgram.lean @@ -0,0 +1,147 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPreparedState +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleConfigProgram +import OAI.Combinatorics.ContingencyTables.Machines.FractionRepetitionProgram + +namespace OAI + +/-! # The direct estimator for the zero-label branch + +The same finite-word median evaluator handles this branch. The confidence +parameter controls the outer repetition count independently of its relative +accuracy, which is one quarter of the public accuracy. +-/ +namespace ContingencyTables.CountingDirectProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +abbrev Input := (CountingBaseProgram.Input×TreeFraction.Fraction)×List Bool + +def accuracy (z : Input) : TreeFraction.Fraction := CountingBaseProgram.half (CountingBaseProgram.half z.1.1.2) +def accuracyRealizer : Realizer accuracy := + composition (composition (composition (composition first first) second) + CountingBaseProgram.halfRealizer) CountingBaseProgram.halfRealizer +lemma polynomial_accuracy : PolynomialTime accuracyRealizer := + polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + CountingBaseProgram.polynomial_half) CountingBaseProgram.polynomial_half + +def reserve (z : Input) : List Bool := z.2.map (fun _ => false) +def reserveRealizer : Realizer reserve := composition second (map (constant false)) +lemma polynomial_reserve : PolynomialTime reserveRealizer := + polynomial_composition polynomial_second (polynomial_map (polynomial_constant false)) + +def oracleInput (z : Input) : RootedOracleConfigProgram.Input := + (((CountingPreparedState.state z.1.1,accuracy z),CountingTerminalProgram.phases z.1.1),reserve z) +def oracleInputRealizer : Realizer oracleInput := + pair (pair (pair (composition (f := fun z : Input => z.1.1) (g := CountingPreparedState.state) + (composition first first) CountingPreparedState.stateRealizer) accuracyRealizer) + (composition (f := fun z : Input => z.1.1) (g := CountingTerminalProgram.phases) + (composition first first) CountingTerminalProgram.phasesRealizer)) reserveRealizer +lemma polynomial_oracleInput : PolynomialTime oracleInputRealizer := + polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + CountingPreparedState.polynomial_state) polynomial_accuracy) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + CountingTerminalProgram.polynomial_phases)) polynomial_reserve + +def rawConfig (z : Input) : RootedLabelWeightProgram.Config := RootedOracleConfigProgram.output (oracleInput z) +def rawConfigRealizer : Realizer rawConfig := + composition (f := oracleInput) (g := RootedOracleConfigProgram.output) + oracleInputRealizer RootedOracleConfigProgram.outputRealizer +lemma polynomial_rawConfig : PolynomialTime rawConfigRealizer := + polynomial_composition polynomial_oracleInput RootedOracleConfigProgram.polynomial_output +attribute [local irreducible] rawConfig + +def context (z : Input) : RootedEstimatorLayoutProgram.Context := (rawConfig z).1.1 +def contextRealizer : Realizer context := composition (composition rawConfigRealizer first) first +lemma polynomial_context : PolynomialTime contextRealizer := + polynomial_composition (polynomial_composition polynomial_rawConfig polynomial_first) polynomial_first + +def repeats (z : Input) : ℕ := FractionRepetitionProgram.count z.1.2 +def repeatsRealizer : Realizer repeats := + composition (f := fun z : Input => z.1.2) (g := FractionRepetitionProgram.count) + (composition first second) FractionRepetitionProgram.countRealizer +lemma polynomial_repeats : PolynomialTime repeatsRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) + FractionRepetitionProgram.polynomial_count + +def markers (z : Input) : List Bool×List Bool := (rawConfig z).2 +def markersRealizer : Realizer markers := composition rawConfigRealizer second +lemma polynomial_markers : PolynomialTime markersRealizer := + polynomial_composition polynomial_rawConfig polynomial_second +attribute [local irreducible] context repeats markers + +def config (z : Input) : RootedLabelWeightProgram.Config := ((context z,repeats z),markers z) +def configRealizer : Realizer config := pair (pair contextRealizer repeatsRealizer) markersRealizer +lemma polynomial_config : PolynomialTime configRealizer := + polynomial_pair (polynomial_pair polynomial_context polynomial_repeats) polynomial_markers +attribute [local irreducible] config + +def contextWidth (z : Input) : ℕ := RootedOracleConfigProgram.contextWidth (oracleInput z) +def contextWidthRealizer : Realizer contextWidth := + composition (f := oracleInput) (g := RootedOracleConfigProgram.contextWidth) + oracleInputRealizer RootedOracleConfigProgram.contextWidthRealizer +lemma polynomial_contextWidth : PolynomialTime contextWidthRealizer := + polynomial_composition polynomial_oracleInput RootedOracleConfigProgram.polynomial_contextWidth +attribute [local irreducible] contextWidth + +def wordWidth (z : Input) : ℕ := repeats z*contextWidth z +def wordWidthRealizer : Realizer wordWidth := + composition (f := fun z : Input => (repeats z,contextWidth z)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair repeatsRealizer contextWidthRealizer) multiply +lemma polynomial_wordWidth : PolynomialTime wordWidthRealizer := + polynomial_composition (polynomial_pair polynomial_repeats polynomial_contextWidth) polynomial_multiply + +def sampleBits (z : Input) : List Bool := z.2.take (wordWidth z) +def sampleBitsRealizer : Realizer sampleBits := + composition (f := fun z : Input => (z.2,wordWidth z)) + (g := fun p : List Bool×ℕ => p.1.take p.2) (pair second wordWidthRealizer) takeFast +lemma polynomial_sampleBits : PolynomialTime sampleBitsRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_wordWidth) polynomial_takeFast + +def medianInput (z : Input) : RootedEstimatorMedianProgram.Input := ((config z).1,((config z).2,sampleBits z)) +def medianInputRealizer : Realizer medianInput := + pair (composition configRealizer first) (pair (composition configRealizer second) sampleBitsRealizer) +lemma polynomial_medianInput : PolynomialTime medianInputRealizer := + polynomial_pair (polynomial_composition polynomial_config polynomial_first) + (polynomial_pair (polynomial_composition polynomial_config polynomial_second) polynomial_sampleBits) + +def output (z : Input) : TreeFraction.Fraction := RootedEstimatorMedianProgram.output (medianInput z) +def outputRealizer : Realizer output := + composition (f := medianInput) (g := RootedEstimatorMedianProgram.output) + medianInputRealizer RootedEstimatorMedianProgram.outputRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_medianInput RootedEstimatorMedianProgram.polynomial_output + + +abbrev Request := CountingBaseProgram.Input×TreeFraction.Fraction + +def empty (z : Request) : Input := (z,[]) +def emptyRealizer : Realizer empty := pair identity (constant []) +lemma polynomial_empty : PolynomialTime emptyRealizer := polynomial_pair polynomial_identity (polynomial_constant []) + +def padding (z : Request) : ℕ := + RootedOracleConfigProgram.rootDegree (oracleInput (empty z))+ + RootedOracleConfigProgram.depth (oracleInput (empty z)) +def paddingRealizer : Realizer padding := + composition (pair (composition (composition emptyRealizer oracleInputRealizer) + RootedOracleConfigProgram.rootDegreeRealizer) + (composition (composition emptyRealizer oracleInputRealizer) + RootedOracleConfigProgram.depthRealizer)) add +lemma polynomial_padding : PolynomialTime paddingRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_empty polynomial_oracleInput) + RootedOracleConfigProgram.polynomial_rootDegree) + (polynomial_composition (polynomial_composition polynomial_empty polynomial_oracleInput) + RootedOracleConfigProgram.polynomial_depth)) polynomial_add + +def budget (z : Request) : ℕ := wordWidth (empty z)+padding z +def budgetRealizer : Realizer budget := + composition (pair (composition emptyRealizer wordWidthRealizer) paddingRealizer) add +lemma polynomial_budget : PolynomialTime budgetRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_empty polynomial_wordWidth) + polynomial_padding) polynomial_add + +end ContingencyTables.CountingDirectProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..3723b23c19a4693e2962209ff7c2e6de231063b8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectSemantics.lean @@ -0,0 +1,140 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleConfigSemantics +import OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingZero + +namespace OAI + +/-! # The direct binary evaluator uses the original counting parameters -/ +namespace ContingencyTables.CountingDirectProgram +open MatchingFPRAS CompanionFactorialApplication GridBoundary CompanionOracleDensity +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def request (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : Request := + ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),TreeFraction.repr delta) + +lemma accuracy_value (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (he : 0 < epsilon) (bits : List Bool) : + TreeFraction.val (accuracy (request r c b epsilon delta,bits))=(epsilon/2)/2 := by + change TreeFraction.val (CountingBaseProgram.half (CountingBaseProgram.half (TreeFraction.repr epsilon)))=_ + rw [CountingBaseProgram.half_val,CountingBaseProgram.half_val,TreeFraction.val_repr he.le] + +lemma oracleInput_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) + (bits : List Bool) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let C := ComputedCountingParameters.coefficient r c b epsilon + let K := ComputedCountingParameters.binCount r c b epsilon + let H := ComputedCountingParameters.phases r c b epsilon + oracleInput (request r c b epsilon delta,bits)= + RootedOracleConfigProgram.data A C K H + (accuracy (request r c b epsilon delta,bits)) (fun _ => 0) + (CountingPreparedState.start A K (ComputedCountingParameters.binCount_pos r c b epsilon he)) + (bits.map (fun _ => false)) := by + dsimp only + unfold oracleInput request + rw [CountingPreparedState.state_data hEK r c b hne epsilon he, + CountingTerminalProgram.phases_data r c b epsilon he] + rfl + +lemma context_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) + (bits : List Bool) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let C := ComputedCountingParameters.coefficient r c b epsilon + let K := ComputedCountingParameters.binCount r c b epsilon + let H := ComputedCountingParameters.phases r c b epsilon + context (request r c b epsilon delta,bits)= + RootedEstimatorMedianProgram.context A C K H ((epsilon/2)/2) (fun _ => 0) + (CountingPreparedState.start A K (ComputedCountingParameters.binCount_pos r c b epsilon he)) := by + dsimp only + change RootedOracleConfigProgram.context (oracleInput (request r c b epsilon delta,bits))=_ + rw [oracleInput_data hEK r c b hne epsilon delta he bits, + RootedOracleConfigProgram.context_data,accuracy_value r c b epsilon delta he bits] + +lemma wordWidth_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) (hd : 0 < delta) + (bits : List Bool) : + wordWidth (request r c b epsilon delta,bits)= + ComputedCountingZero.zeroBits hEK r c b hne epsilon he delta := by + have hr : repeats (request r c b epsilon delta,bits)=CommonBasesFPRAS.repetitionCount delta := by + change FractionRepetitionProgram.count (TreeFraction.repr delta)=_ + rw [FractionRepetitionProgram.count_val,TreeFraction.val_repr hd.le] + rw [wordWidth,hr,contextWidth] + rw [oracleInput_data hEK r c b hne epsilon delta he bits, + RootedOracleConfigProgram.contextWidth,RootedOracleConfigProgram.context_data, + accuracy_value r c b epsilon delta he bits] + rw [RootedEstimatorMedianProgram.context,RootedEstimatorWordProgram.scheduledWordWidth] + unfold ComputedCountingZero.zeroBits medianEstimatorBits + rw [←ComputedCountingParameters.phases_final hEK r c b hne epsilon he] + +def degree (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon : ℚ) : ℕ := + PowerOfTwoApproximation.rootDegree (roundingTolerance + (innerTolerance (((epsilon/2)/2)/2) (ComputedCountingParameters.phases r c b epsilon))) +def depth (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon : ℚ) : ℕ := + PowerOfTwoApproximation.depth (roundingTolerance + (innerTolerance (((epsilon/2)/2)/2) (ComputedCountingParameters.phases r c b epsilon))) + +lemma degree_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) + (bits : List Bool) : + RootedOracleConfigProgram.rootDegree (oracleInput (request r c b epsilon delta,bits))= + degree r c b epsilon := by + rw [oracleInput_data hEK r c b hne epsilon delta he bits, + RootedOracleConfigProgram.rootDegree_data,accuracy_value r c b epsilon delta he bits] + rfl + +lemma depth_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) + (bits : List Bool) : + RootedOracleConfigProgram.depth (oracleInput (request r c b epsilon delta,bits))= + depth r c b epsilon := by + rw [oracleInput_data hEK r c b hne epsilon delta he bits, + RootedOracleConfigProgram.depth_data,accuracy_value r c b epsilon delta he bits] + rfl + +lemma budget_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) + (he : 0 < epsilon) (hd : 0 < delta) : + budget (request r c b epsilon delta)= + ComputedCountingZero.zeroBits hEK r c b hne epsilon he delta+degree r c b epsilon+depth r c b epsilon := by + unfold budget padding empty + rw [wordWidth_data hEK r c b hne epsilon delta he hd [], + degree_data hEK r c b hne epsilon delta he [],depth_data hEK r c b hne epsilon delta he []] + omega + +lemma markers_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) + (N : ℕ) (hdegree : degree r c b epsilon ≤ N) (hdepth : depth r c b epsilon ≤ N) + (bits : Fin N→Bool) : + markers (request r c b epsilon delta,List.ofFn bits)= + (List.replicate (degree r c b epsilon) false,List.replicate (depth r c b epsilon) false) := by + change RootedOracleConfigProgram.markers + (oracleInput (request r c b epsilon delta,List.ofFn bits))=_ + rw [RootedOracleConfigProgram.markers, + degree_data hEK r c b hne epsilon delta he (List.ofFn bits), + depth_data hEK r c b hne epsilon delta he (List.ofFn bits)] + simp only [oracleInput,reserve,List.map_ofFn,Function.comp_def,List.ofFn_const, + List.take_replicate,min_eq_left hdegree,min_eq_left hdepth] + +lemma sampleBits_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) + (he : 0 < epsilon) (hd : 0 < delta) (N : ℕ) + (hwidth : ComputedCountingZero.zeroBits hEK r c b hne epsilon he delta ≤ N) (bits : Fin N→Bool) : + sampleBits (request r c b epsilon delta,List.ofFn bits)=List.ofFn (FirstSuccess.prefixWord hwidth bits) := by + rw [sampleBits,wordWidth_data hEK r c b hne epsilon delta he hd] + exact BinVectorProgram.take_ofFn_prefix hwidth bits + +end +end ContingencyTables.CountingDirectProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectSuccess.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectSuccess.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c21b56d95060902b9ac84749837f1f9cd389cb4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectSuccess.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingDirectLaw + +namespace OAI + +/-! # Accuracy of the executed direct counting branch -/ +namespace ContingencyTables.CountingDirectProgram +open MatchingFPRAS CompanionFactorialApplication GridBoundary CommonBasesFPRAS +open scoped Classical +noncomputable section +variable {m n : ℕ} + +theorem success (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger (Grid (I := Fin q) k)) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) + (he : 0 < epsilon) (he1 : epsilon < 1) (hd : 0 < delta) + (hzero : Fintype.card (Labels (ComputedCountingParameters.data hEK r c b hne epsilon he))=0) : + 1-(delta:ℝ) ≤ uniformAverage + (fun bits : Fin (budget (request r c b epsilon delta))→Bool => + if (1-(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ) ≤ + (TreeFraction.val (output (request r c b epsilon delta,List.ofFn bits)):ℝ) ∧ + (TreeFraction.val (output (request r c b epsilon delta,List.ofFn bits)):ℝ) ≤ + (1+(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ) + then (1:ℝ) else 0) := by + let event := fun q : ℚ => if + (1-(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ) ≤ (q:ℝ) ∧ + (q:ℝ) ≤ (1+(epsilon:ℝ))*(Fintype.card (BoundedTable r c b):ℝ) + then (1:ℝ) else 0 + have hs := ComputedCountingZero.zero_success hEK hPL hCheeger r c b hne + epsilon delta he he1 hd hzero + exact hs.trans_eq (sameLaw hEK r c b hne epsilon delta he hd event).symm + +end +end ContingencyTables.CountingDirectProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectWordBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectWordBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..081ce22e1be26d220083a2d49cc4a3b95450436d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingDirectWordBound.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPublicWordBound +import OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingZero + +namespace OAI + +/-! # Public word budget for the direct zero-label estimator -/ +namespace ContingencyTables.CountingDirectWordBound +open CompanionFactorialApplication CountingPublicInputBounds Polynomial +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def controlPolynomial : Polynomial ℕ := CountingPublicWordBound.controlPolynomial+4*X +def wordPolynomial : Polynomial ℕ := CountingOracleWordBounds.medianPolynomial.comp controlPolynomial + +lemma zeroBits_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + ComputedCountingZero.zeroBits hEK r c b hne epsilon he delta ≤ + wordPolynomial.eval (size r c b epsilon delta) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let C := ComputedCountingParameters.coefficient r c b epsilon + let K := ComputedCountingParameters.binCount r c b epsilon + let H := ComputedCountingParameters.phases r c b epsilon + let S := size r c b epsilon delta + let M := controlPolynomial.eval S + have hSM : S ≤ M := by + simp only [M,controlPolynomial,CountingPublicWordBound.controlPolynomial, + Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hKM : CountingTerminalBounds.gridPolynomial.eval S ≤ M := by + simp only [M,controlPolynomial,CountingPublicWordBound.controlPolynomial, + Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hHM : CountingTerminalBounds.phasePolynomial.eval S ≤ M := by + simp only [M,controlPolynomial,CountingPublicWordBound.controlPolynomial, + Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have h4SM : 4*S ≤ M := by + simp only [M,controlPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X] + omega + have ht := CountingPublicTerminalBounds.terminal_public hEK r c b hne epsilon delta he + have hd : A.d ≤ M := (dimension_le r c b epsilon delta).trans hSM + have hK : K ≤ M := ht.1.trans hKM + have hH : H ≤ M := ht.2.2.trans hHM + have hL : CountingTerminalSchedule.capacityBits A ≤ M := + (capacityBits_le hEK r c b hne epsilon delta).trans hSM + have hi : 1/((epsilon/2)/2) ≤ (M:ℚ) := by + have hh := mul_le_mul_of_nonneg_left (inverse_le r c b epsilon delta) + (show (0:ℚ) ≤ 4 by norm_num) + have hh' : 1/((epsilon/2)/2) ≤ ((4*S:ℕ):ℚ) := by + convert hh using 1 <;> push_cast <;> ring + exact hh'.trans (by exact_mod_cast h4SM) + have hr : CommonBasesFPRAS.repetitionCount delta ≤ 64*(M+1) := + (repeats_le r c b epsilon delta).trans (Nat.mul_le_mul_left 64 (by omega)) + have hb := CountingOracleWordBounds.median_bound_separate A C K H M ((epsilon/2)/2) delta + hd hK hH hH hL (by positivity) hi hr + unfold ComputedCountingZero.zeroBits + rw [←ComputedCountingParameters.phases_final hEK r c b hne epsilon he] + simpa only [wordPolynomial,Polynomial.eval_comp] using hb + +end +end ContingencyTables.CountingDirectWordBound + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingExecutedMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingExecutedMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..5abfe799a68fe08dc72b76765285d827ca4e57df --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingExecutedMachine.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveWordBound +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchMachine +import OAI.Combinatorics.ContingencyTables.Counting.CountingMachineTime + +namespace OAI + +/-! # One fixed counting machine with the computed adaptive program -/ +namespace ContingencyTables.CountingExecutedMachine +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.PhysicalStream +open scoped Classical +noncomputable section + +abbrev positive := CountingAmplifiedProgram.output CountingPositiveProgram.output CountingPositiveProgram.bitCount +abbrev positiveWidth := CountingAmplifiedProgram.budget CountingPositiveProgram.bitCount + +def positiveRealizer : Realizer positive := CountingAmplifiedProgram.outputRealizer + CountingPositiveProgram.output CountingPositiveProgram.outputRealizer + CountingPositiveProgram.bitCount CountingPositiveProgram.bitCountRealizer + +def positiveWidthRealizer : Realizer positiveWidth := CountingAmplifiedProgram.budgetRealizer + CountingPositiveProgram.bitCount CountingPositiveProgram.bitCountRealizer + +lemma polynomial_positive : PolynomialTime positiveRealizer := + CountingAmplifiedProgram.polynomial_output CountingPositiveProgram.output + CountingPositiveProgram.outputRealizer CountingPositiveProgram.bitCount + CountingPositiveProgram.bitCountRealizer CountingPositiveProgram.polynomial_output + CountingPositiveProgram.polynomial_bitCount + +lemma polynomial_positiveWidth : PolynomialTime positiveWidthRealizer := + CountingAmplifiedProgram.polynomial_budget CountingPositiveProgram.bitCount + CountingPositiveProgram.bitCountRealizer CountingPositiveProgram.polynomial_bitCount + +def machine : RandomMachine := + CountingBranchProgram.machine positive positiveRealizer positiveWidth positiveWidthRealizer + +def machineTime (as : List Symbol) : ℕ := + CountingBranchProgram.machineTime positive positiveRealizer positiveWidth positiveWidthRealizer as + +abbrev wordCount := CountingBranchProgram.publicBudget positiveWidth +abbrev publicOutput := CountingBranchProgram.publicOutput positive +abbrev sourceValue := CountingBranchProgram.sourceValue positive positiveWidth + +theorem public_time (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) : + ∃ C d : ℕ,0 + TreeFraction.val (output (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) + (RootedCountingWords.flatEstimate (ComputedCountingParameters.data hEK r c b hne epsilon he) + (ComputedCountingWords.root hEK r c b hne epsilon he) + (ComputedCountingParameters.settings hEK r c b hne epsilon he)) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let req := CountingDirectProgram.request r c b epsilon delta + let initial := CompanionInitialStoredProgram.output (CompanionInitialStoredProgram.data A ∅) + let fixed := CountingActualPhase.fixed hEK r c b hne epsilon he initial + let reserve := List.replicate (bitCount req) false + have hlen : 2*Fintype.card (Labels A) ≤ reserve.length := by + rw [List.length_replicate] + exact initialReserve_le hEK r c b hne epsilon he (TreeFraction.repr delta) + have hstart : start (req,reserve)=fixed := + start_data hEK r c b hne epsilon he (TreeFraction.repr delta) reserve hlen + have hi := start_view hEK r c b hne epsilon he (TreeFraction.repr delta) reserve hlen + change CompanionPhaseFinishProgram.view (start (req,reserve)).2 = _ at hi + rw [hstart] at hi + have hrep : CompanionStoredRepresentation.StoredRep + (CanonicalInitialEncoding.copyOrder (CompanionComputedInitial.capacities A)).length initial := + CompanionStoredRepresentation.initial_output_rep A ∅ + have h := CompanionProjectedHistory.output_sameLaw A (CompanionComputedProposal.pairLabels A) + (ComputedCountingWords.root hEK r c b hne epsilon he) s fixed hi + (fun history hh hj => CountingActualPhase.output_rep hEK r c b hne epsilon he + (TreeFraction.repr delta) initial hrep history hh hj) + (fun history hh hj => CountingActualPhase.output_sameLaw hEK r c b hne epsilon he + (TreeFraction.repr delta) initial hrep hi history hh hj) + have hc : phaseCount req=s.H := phaseCount_data hEK r c b hne epsilon he (TreeFraction.repr delta) + have hw := value_sameLaw req + unfold independentOutput at hw + rw [hstart,hc] at hw + simp only [List.map_ofFn,Function.comp_def] at h + intro phi + have hf := uniformAverage_equiv (gridWordEquiv s.H (RootedPhaseHistory.totalWidth A s)) + (fun words => phi (RootedCountingWords.estimate A + (ComputedCountingWords.root hEK r c b hne epsilon he) s words)) + exact (hw phi).trans ((h phi).trans hf.symm) + +end +end ContingencyTables.CountingPositiveProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingInputParser.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingInputParser.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd49fbe15a70bba298901bdf98edba9f86a14f50 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingInputParser.lean @@ -0,0 +1,175 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixLayoutProgram +import OAI.Combinatorics.ContingencyTables.Transport.NetworkVertexCode + +namespace OAI + +/-! # Parsing the public cell-bounded counting input + +Dimensions only delimit bounded list slices. The matrix layout uses the +lengths of the parsed margin lists, so malformed headers do not create +unbounded numeric loops. Positive rational parameters use their natural +numerator and denominator, exactly as in the public tape encoding. +-/ + +namespace ContingencyTables.CountingInputParser +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.LiteralParse +open MatchingFPRAS.TreeFraction DensePrograms + +abbrev Input := NetworkVertexCode.Input × (Fraction × Fraction) + +def offset (ns : List ℕ) : ℕ := 2+ns.headD 0+ns.tail.headD 0 + +def offsetRealizer : Realizer offset := + composition (pair (composition (pair (constant 2) (head 0)) add) + (composition tail (head 0))) add +lemma polynomial_offset : PolynomialTime offsetRealizer := by + unfold offsetRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 2) (polynomial_head 0)) + polynomial_add) + (polynomial_composition polynomial_tail (polynomial_head 0))) polynomial_add + +def rest (ns : List ℕ) : List ℕ := ns.drop (offset ns) +def restRealizer : Realizer rest := composition (pair identity offsetRealizer) dropFast +lemma polynomial_rest : PolynomialTime restRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_offset) polynomial_dropFast + +def cells (ns : List ℕ) : ℕ := + (GreedyFeasibleTable.marginLists ns).1.length*(GreedyFeasibleTable.marginLists ns).2.length +def cellsRealizer : Realizer cells := + composition (pair (composition (composition GreedyFeasibleTable.marginListsRealizer first) listLength) + (composition (composition GreedyFeasibleTable.marginListsRealizer second) listLength)) multiply +lemma polynomial_cells : PolynomialTime cellsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition GreedyFeasibleTable.polynomial_marginLists + polynomial_first) polynomial_listLength) + (polynomial_composition (polynomial_composition GreedyFeasibleTable.polynomial_marginLists + polynomial_second) polynomial_listLength)) polynomial_multiply + +def capacityFrame (ns : List ℕ) : GridFlatData := + ((0::(GreedyFeasibleTable.marginLists ns).1,0::(GreedyFeasibleTable.marginLists ns).2), + (rest ns).take (cells ns)) +def capacityFrameRealizer : Realizer capacityFrame := + pair (pair + (composition (f := fun ns : List ℕ => (0,(GreedyFeasibleTable.marginLists ns).1)) + (g := fun z : ℕ×List ℕ => z.1::z.2) + (pair (constant 0) (composition GreedyFeasibleTable.marginListsRealizer first)) listCons) + (composition (f := fun ns : List ℕ => (0,(GreedyFeasibleTable.marginLists ns).2)) + (g := fun z : ℕ×List ℕ => z.1::z.2) + (pair (constant 0) (composition GreedyFeasibleTable.marginListsRealizer second)) listCons)) + (composition (pair restRealizer cellsRealizer) takeFast) +lemma polynomial_capacityFrame : PolynomialTime capacityFrameRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant (0:ℕ)) + (polynomial_composition GreedyFeasibleTable.polynomial_marginLists polynomial_first)) polynomial_listCons) + (polynomial_composition (polynomial_pair (polynomial_constant (0:ℕ)) + (polynomial_composition GreedyFeasibleTable.polynomial_marginLists polynomial_second)) polynomial_listCons)) + (polynomial_composition (polynomial_pair polynomial_rest polynomial_cells) polynomial_takeFast) + +def parameters (ns : List ℕ) : List ℕ := (rest ns).drop (cells ns) +def parametersRealizer : Realizer parameters := + composition (pair restRealizer cellsRealizer) dropFast +lemma polynomial_parameters : PolynomialTime parametersRealizer := + polynomial_composition (polynomial_pair polynomial_rest polynomial_cells) polynomial_dropFast + +def fractionPair (ns : List ℕ) : Fraction × Fraction := + ((ns.headD 0,ns.tail.headD 1),(ns.tail.tail.headD 0,ns.tail.tail.tail.headD 1)) +def fractionPairRealizer : Realizer fractionPair := + pair (pair (head 0) (composition tail (head 1))) + (pair (composition (composition tail tail) (head 0)) + (composition (composition (composition tail tail) tail) (head 1))) +lemma polynomial_fractionPair : PolynomialTime fractionPairRealizer := by + unfold fractionPairRealizer + exact polynomial_pair (polynomial_pair (polynomial_head 0) + (polynomial_composition polynomial_tail (polynomial_head 1))) + (polynomial_pair (polynomial_composition (polynomial_composition polynomial_tail polynomial_tail) + (polynomial_head 0)) + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_tail polynomial_tail) + polynomial_tail) (polynomial_head 1))) + +def decode (ns : List ℕ) : Input := + ((GreedyFeasibleTable.marginLists ns,unflattenGrid (capacityFrame ns)),fractionPair (parameters ns)) +def decodeRealizer : Realizer decode := + pair (pair GreedyFeasibleTable.marginListsRealizer + (composition (f := capacityFrame) (g := unflattenGrid) capacityFrameRealizer unflattenGridRealizer)) + (composition (f := parameters) (g := fractionPair) parametersRealizer fractionPairRealizer) +lemma polynomial_decode : PolynomialTime decodeRealizer := + polynomial_pair (polynomial_pair GreedyFeasibleTable.polynomial_marginLists + (polynomial_composition polynomial_capacityFrame polynomial_unflattenGrid)) + (polynomial_composition polynomial_parameters polynomial_fractionPair) + +def parseInput (as : List Symbol) : Input := decode (parse as) +def publicRealizer : Realizer parseInput := + composition (f := parse) (g := decode) parseRealizer decodeRealizer +lemma polynomial_public : PolynomialTime publicRealizer := + polynomial_composition polynomial_parse polynomial_decode + +lemma decode_blocks (rs cs flat tail : List ℕ) (hf : flat.length=rs.length*cs.length) : + decode (rs.length::cs.length::(rs++cs++flat++tail))= + (( (rs,cs),unflattenGrid ((0::rs,0::cs),flat)),fractionPair tail) := by + have hm := GreedyFeasibleTable.marginLists_spec rs.length cs.length rs cs (flat++tail) rfl rfl + have hr : rest (rs.length::cs.length::(rs++cs++flat++tail))=flat++tail := by + simp only [rest,offset,List.headD_cons,List.tail_cons] + rw [show 2+rs.length+cs.length=(rs.length+cs.length)+1+1 by omega] + simp only [List.drop_succ_cons,List.append_assoc] + rw [←List.drop_drop,List.drop_left,List.drop_left] + have hc : cells (rs.length::cs.length::(rs++cs++flat++tail))=flat.length := by + unfold cells + rw [show rs++cs++flat++tail=rs++cs++(flat++tail) by simp only [List.append_assoc],hm] + exact hf.symm + simp only [decode,capacityFrame,parameters] + rw [show rs++cs++flat++tail=rs++cs++(flat++tail) by simp only [List.append_assoc],hm] + rw [←show rs++cs++flat++tail=rs++cs++(flat++tail) by simp only [List.append_assoc]] + rw [hr,hc,List.take_left,List.drop_left] + +lemma encodeMatrix_words {m n : ℕ} (b : Fin m→Fin n→ℕ) : + Algorithms.encodeMatrix b= + (List.ofFn (fun i => List.ofFn (b i))).flatten.flatMap encodeNat := by + rw [←GreedyFeasibleTable.printMatrix_ofFn] + unfold GreedyFeasibleTable.printMatrix + generalize List.ofFn (fun i => List.ofFn (b i))=rows + induction rows with + | nil => rfl + | cons row rows ih => simp only [List.flatMap_cons,List.flatten_cons,List.flatMap_append,ih] + +lemma parse_public {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) + (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + parse (Algorithms.encodeCountingInput r c b epsilon delta)= + m::n::(List.ofFn r++List.ofFn c++ + (List.ofFn (fun i => List.ofFn (b i))).flatten++ + [epsilon.num.natAbs,epsilon.den,delta.num.natAbs,delta.den]) := by + unfold Algorithms.encodeCountingInput parse + rw [GreedyFeasibleTable.encodeMargins_natWords,encodeMatrix_words] + simp only [List.foldr_append,encodeRat_fold] + rw [GreedyFeasibleTable.natWords_fold,GreedyFeasibleTable.natWords_fold] + simp only [List.cons_append,List.append_assoc] + +lemma public_spec {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) + (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + parseInput (Algorithms.encodeCountingInput r c b epsilon delta)= + (NetworkVertexCode.data r c b,(TreeFraction.repr epsilon,TreeFraction.repr delta)) := by + unfold parseInput + rw [parse_public] + have hf : (List.ofFn (fun i => List.ofFn (b i))).flatten.length= + (List.ofFn r).length*(List.ofFn c).length := by + simp only [List.length_flatten,List.map_ofFn,Function.comp_def,List.length_ofFn, + List.sum_ofFn,Finset.sum_const,Finset.card_univ,Fintype.card_fin,smul_eq_mul] + have hh := decode_blocks (List.ofFn r) (List.ofFn c) + (List.ofFn (fun i => List.ofFn (b i))).flatten + [epsilon.num.natAbs,epsilon.den,delta.num.natAbs,delta.den] hf + simp only [List.length_ofFn] at hh + rw [hh] + change (( (List.ofFn r,List.ofFn c),_),_)=( ( (List.ofFn r,List.ofFn c),_),_) + congr 2 + let f : Fin (m*n)→ℕ := fun k => b (finProdFinEquiv.symm k).1 (finProdFinEquiv.symm k).2 + have he : (List.ofFn (fun i => List.ofFn (b i))).flatten=List.ofFn f := by + simpa only [f,Equiv.symm_apply_apply,matrixCode] using flatten_matrixCode f + rw [he] + simpa only [marginCode,f,Equiv.symm_apply_apply,matrixCode,ResidualGraphProgram.natCode,Option.elim_none,Option.elim_some] + using unflattenGrid_code (fun i : Option (Fin m) => i.elim 0 r) + (fun j : Option (Fin n) => j.elim 0 c) f + +end ContingencyTables.CountingInputParser + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingInputSymbols.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingInputSymbols.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac51570ee34e4410de4969e1a8b119f5d55d7760 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingInputSymbols.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FractionOutputProgram +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicMachine +import OAI.Combinatorics.ContingencyTables.Machines.MatrixEncoding + +namespace OAI + +/-! # The public counting input contains no tape blanks -/ + +namespace ContingencyTables.CountingInputSymbols +open MatchingFPRAS Algorithms + +lemma nat_nonzero (n : ℕ) (a : MatchingFPRAS.Symbol) (ha : a∈encodeNat n) : a≠0 := + (FractionOutputProgram.natWord_symbols n a ha).1 + +lemma int_nonzero (n : ℤ) (a : MatchingFPRAS.Symbol) (ha : a∈encodeInt n) : a≠0 := by + simp only [encodeInt,List.mem_append] at ha + rcases ha with ha | ha + · split_ifs at ha <;> simp only [List.mem_singleton] at ha <;> subst a <;> decide + · exact nat_nonzero _ a ha + +lemma rat_nonzero (q : ℚ) (a : MatchingFPRAS.Symbol) (ha : a∈encodeRat q) : a≠0 := by + simp only [encodeRat,List.mem_append] at ha + rcases ha with ha | ha + · exact int_nonzero _ a ha + · exact nat_nonzero _ a ha + +lemma matrix_nonzero {m n : ℕ} (X : Fin m→Fin n→ℕ) + (a : MatchingFPRAS.Symbol) (ha : a∈encodeMatrix X) : a≠0 := by + rw [encodeMatrix_flat] at ha + obtain ⟨k,_,hk⟩ := List.mem_flatMap.mp ha + exact nat_nonzero k a hk + +lemma counting_nonzero {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) + (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + ∀ a∈encodeCountingInput r c b epsilon delta,a≠0 := by + intro a ha + simp only [encodeCountingInput,List.mem_append] at ha + rcases ha with ((ha | ha) | ha) | ha + · exact GreedyFeasibleTable.encodeMargins_nonzero r c a ha + · exact matrix_nonzero b a ha + · exact rat_nonzero epsilon a ha + · exact rat_nonzero delta a ha + +end ContingencyTables.CountingInputSymbols + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingLabelCountProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingLabelCountProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae7203ca2c559045820713a5123deb7167c1d448 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingLabelCountProgram.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedForestCatalog + +namespace OAI + +/-! # Executing the actual number of factorial labels + +Only retained capacities are summed; the program does not expand any +capacity into a list of labels to obtain the phase controls. +-/ + +namespace ContingencyTables.CountingLabelCountProgram +open MatchingFPRAS.TreeTyped + +abbrev Input := RootedForestCatalog.Data + +def catalogInput (z : Input) : CompanionCellCatalog.Input := ((z.1.2,z.2),z.1.1.2) +def catalogInputRealizer : Realizer catalogInput := + pair (pair (composition first second) second) (composition (composition first first) second) +lemma polynomial_catalogInput : PolynomialTime catalogInputRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second) (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) + +def capacities (z : Input) : List ℕ := CompanionCellCatalog.capacities (catalogInput z) +def capacitiesRealizer : Realizer capacities := + composition (f := catalogInput) (g := CompanionCellCatalog.capacities) + catalogInputRealizer CompanionCellCatalog.capacitiesRealizer +lemma polynomial_capacities : PolynomialTime capacitiesRealizer := + polynomial_composition polynomial_catalogInput CompanionCellCatalog.polynomial_capacities + +def count (z : Input) : ℕ := (capacities z).sum +def countRealizer : Realizer count := + composition (f := capacities) (g := List.sum) capacitiesRealizer listSum +lemma polynomial_count : PolynomialTime countRealizer := + polynomial_composition polynomial_capacities polynomial_listSum + +open CompanionFactorialApplication +open scoped BigOperators Classical +variable {m n : ℕ} + +lemma catalogInput_data (A : Instance (Fin m) (Fin n)) : + catalogInput (RootedForestCatalog.data A)=CompanionCellCatalog.input A := rfl + +lemma count_data (A : Instance (Fin m) (Fin n)) : + count (RootedForestCatalog.data A)=Fintype.card (Labels A) := by + rw [count,capacities,catalogInput_data,CompanionCellCatalog.capacities_eq,List.sum_ofFn] + rw [Fintype.card_sigma] + simp only [Fintype.card_fin] + exact Fintype.sum_equiv (CompanionCellCatalog.cellEquiv A) _ _ (fun _ => rfl) + +lemma count_bound (A : Instance (Fin m) (Fin n)) : + Fintype.card (Labels A) ≤ A.d*A.W := by + rw [Fintype.card_sigma] + simp only [Fintype.card_fin] + calc + (∑ s : SmallCell A,A.b s.val.1 s.val.2) ≤ ∑ _s : SmallCell A,A.W := + Finset.sum_le_sum (fun s _ => (A.hsmall _ _ s.property).le) + _ = Fintype.card (SmallCell A)*A.W := by simp + _ ≤ A.d*A.W := Nat.mul_le_mul_right A.W + ((Fintype.card_subtype_le (fun a : Fin m×Fin n => A.small a.1 a.2=true)).trans + (by simpa only [Fintype.card_prod] using A.hcard)) + +end ContingencyTables.CountingLabelCountProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineEvents.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineEvents.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ae9ee497aedfacb8338e83ec2e3f01f33d32d68 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineEvents.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordRationalLaw +import OAI.Combinatorics.ContingencyTables.Counting.CountingInputSymbols +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchProgram + +namespace OAI + +/-! # From the counting experiment's real probability bound to public tapes -/ +namespace ContingencyTables.CountingMachineEvents +open MatchingFPRAS MatchingFPRAS.PhysicalStream CommonBasesFPRAS +open scoped BigOperators Classical +noncomputable section + +lemma average_cast (n : ℕ) (f : Bits n→ℚ) : + (average f:ℝ)=uniformAverage (fun bits => (f bits:ℝ)) := by + simp only [average,uniformAverage,Rat.cast_div,Rat.cast_sum,Rat.cast_pow,Rat.cast_ofNat, + Fintype.card_fun,Fintype.card_bool,Fintype.card_fin,Nat.cast_pow,Nat.cast_ofNat] + +variable {wordCount : List Symbol→ℕ} {output : List Symbol×List Bool→List Symbol} + +theorem success (N : TreeTyped.Realizer wordCount) (F : TreeTyped.Realizer output) + (as : List Symbol) (ha : ∀ a∈as,a≠0) + (hout : ∀ bs,∀ a∈output (as,bs),a≠6 ∧ a≠7) + (draw : Bits (wordCount as)→ℚ) (hf : ∀ bits,output (as,List.ofFn bits)=encodeRat (draw bits)) + (P : ℚ→Prop) (delta : ℚ) + (hs : 1-(delta:ℝ) ≤ uniformAverage (fun bits : Bits (wordCount as) => if P (draw bits) then 1 else 0)) + (t : ℕ) (ht : FiniteWordExecution.machineTime N F as ≤ t) : + 1-delta ≤ ((Finset.univ.filter (fun bits : Bits t => + ∃ q : ℚ,Outputs (FiniteWordExecution.machine N F) as bits q ∧ P q)).card:ℚ)/(2:ℚ)^t := by + have hm := FiniteWordExecution.machine_rational_event N F as ha hout draw hf P t ht + apply le_trans ?_ hm + have hc : ((1-delta:ℚ):ℝ) ≤ + ((average (fun bits : Bits (wordCount as) => if P (draw bits) then (1:ℚ) else 0)):ℝ) := by + rw [average_cast] + simpa only [Rat.cast_sub,Rat.cast_one,apply_ite,Rat.cast_zero] using hs + exact_mod_cast hc + +end +end ContingencyTables.CountingMachineEvents + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineMainEvent.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineMainEvent.lean new file mode 100644 index 0000000000000000000000000000000000000000..21eddfa424fbdd8facdc7fe02ffb724735b65e31 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineMainEvent.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingMachineEvents + +namespace OAI + +/-! # The finite rational event in the main counting statement -/ +namespace ContingencyTables.CountingMachineEvents +open MatchingFPRAS MatchingFPRAS.PhysicalStream CommonBasesFPRAS +open scoped Classical +noncomputable section +variable {wordCount : List Symbol→ℕ} {output : List Symbol×List Bool→List Symbol} +variable {m n : ℕ} + +theorem goodTapes_success (N : TreeTyped.Realizer wordCount) (F : TreeTyped.Realizer output) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) + (hout : ∀ bs,∀ a∈output (Algorithms.encodeCountingInput r c b epsilon delta,bs),a≠6 ∧ a≠7) + (draw : Bits (wordCount (Algorithms.encodeCountingInput r c b epsilon delta))→ℚ) + (hf : ∀ bits,output (Algorithms.encodeCountingInput r c b epsilon delta,List.ofFn bits)=encodeRat (draw bits)) + (hs : 1-(delta:ℝ) ≤ uniformAverage (fun bits => + if (1-epsilon)*(Algorithms.count r c b:ℚ)≤draw bits ∧ + draw bits≤(1+epsilon)*(Algorithms.count r c b:ℚ) then (1:ℝ) else 0)) + (t : ℕ) (ht : FiniteWordExecution.machineTime N F + (Algorithms.encodeCountingInput r c b epsilon delta)≤t) : + 1-delta ≤ ((Algorithms.goodCountingTapes (FiniteWordExecution.machine N F) + r c b epsilon delta t).card:ℚ)/(2:ℚ)^t := by + apply success N F (Algorithms.encodeCountingInput r c b epsilon delta) + (CountingInputSymbols.counting_nonzero r c b epsilon delta) hout draw hf + (fun q => (1-epsilon)*(Algorithms.count r c b:ℚ)≤q ∧ + q≤(1+epsilon)*(Algorithms.count r c b:ℚ)) delta ?_ t ht + convert hs using 1 + congr 1 + funext bits + split_ifs <;> rfl + +end +end ContingencyTables.CountingMachineEvents + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineTime.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineTime.lean new file mode 100644 index 0000000000000000000000000000000000000000..04f1ac943934427c4e4669f53285c3767ea4a8ae --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMachineTime.lean @@ -0,0 +1,55 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordRationalLaw +import OAI.Combinatorics.ContingencyTables.Counting.CountingPublicInputBounds +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileRuntimeBound + +namespace OAI + +/-! # Uniform public time from the counting word budget -/ +namespace ContingencyTables.CountingMachineTime +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.LiteralCodec +open CountingPublicInputBounds Polynomial +open scoped Classical +noncomputable section + +variable {wordCount : List Symbol→ℕ} {output : List Symbol×List Bool→List Symbol} + +theorem public_bound (N : Realizer wordCount) (F : Realizer output) + (hN : PolynomialTime N) (hF : PolynomialTime F) (p : Polynomial ℕ) + (hb : ∀ (m n : ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ), 0 < epsilon → 0 < delta → + wordCount (Algorithms.encodeCountingInput r c b epsilon delta) ≤ + p.eval (size r c b epsilon delta)) : + ∃ C d : ℕ, 0 < C ∧ + ∀ (m n : ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ), 0 < epsilon → 0 < delta → + FiniteWordExecution.machineTime N F (Algorithms.encodeCountingInput r c b epsilon delta) ≤ + Algorithms.countingTime C d r c b epsilon delta := by + obtain ⟨q,hq⟩ := FiniteWordExecution.machineTime_polynomial hN hF + let P : Polynomial ℕ := q.comp (18*X+1+p) + refine ⟨P.eval 1+1,P.natDegree,by omega,?_⟩ + intro m n r c b epsilon delta he hd + let S := size r c b epsilon delta + have hS : 1 ≤ S := by unfold S size; omega + have hlen : (Algorithms.encodeCountingInput r c b epsilon delta).length ≤ S := by + unfold S size + omega + have hm : FiniteWordExecution.wordMeasure wordCount + (Algorithms.encodeCountingInput r c b epsilon delta) ≤ (18*X+1+p).eval S := by + unfold FiniteWordExecution.wordMeasure + rw [weight_word] + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_one] + exact Nat.add_le_add (Nat.add_le_add_right (Nat.mul_le_mul_left 18 hlen) 1) + (hb m n r c b epsilon delta he hd) + calc + _ ≤ q.eval (FiniteWordExecution.wordMeasure wordCount + (Algorithms.encodeCountingInput r c b epsilon delta)) := hq _ + _ ≤ q.eval ((18*X+1+p).eval S) := polynomial_eval_monotone q hm + _ = P.eval S := by simp only [P,Polynomial.eval_comp] + _ ≤ P.eval 1*S^P.natDegree := by + simpa only [one_mul,pow_one] using ProfilePrograms.polynomial_scaled_power P 1 S 1 hS + _ ≤ _ := Nat.mul_le_mul_right _ (Nat.le_succ _) + +end +end ContingencyTables.CountingMachineTime + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMainMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMainMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..fdee08cf606e335ea3d68698d171c041c59f2af0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMainMachine.lean @@ -0,0 +1,26 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingHistoryApplication +import OAI.Combinatorics.ContingencyTables.Counting.CountingConditionalAssembly + +namespace OAI + +/-! # The cell-bounded contingency-table FPRAS on one public fair-bit machine + +The hypotheses are finite-box Prekopa-Leindler, finite-chain Cheeger +and Edmonds-Karp. They imply the guarantees for preprocessing, adaptive +phases, error amplification and fair-bit machine execution. +-/ +namespace ContingencyTables.CountingExecutedMachine +open CompanionFactorialApplication GridBoundary + +theorem counting_conditional + (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger (Grid (I := Fin q) k)) : + Algorithms.CountingStatement := + statement_of_single_law hEK hPL hCheeger + (fun _ _ r c b hne epsilon delta he => + CountingPositiveProgram.value_source_sameLaw hEK r c b hne epsilon delta he) + +end ContingencyTables.CountingExecutedMachine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMarkerBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMarkerBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..84feb8f4b883b02819574792d04d759ec9f107df --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingMarkerBounds.lean @@ -0,0 +1,58 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingOracleWordBounds +import OAI.Combinatorics.ContingencyTables.Transport.PowerOfTwoApproximation + +namespace OAI + +/-! # Polynomial space for the executed power-approximation markers -/ +namespace ContingencyTables.CountingMarkerBounds +open CompanionOracleDensity Polynomial +noncomputable section + +def paddingPolynomial : Polynomial ℕ := 409600*(X+1)*X + +lemma inner_inverse_bound (j M : ℕ) (xi : ℚ) (hj : j ≤ M) + (hxi : 0 < xi) (hi : 1/xi ≤ (M:ℚ)) : + 1/innerTolerance (xi/2) j ≤ ((400*(M+1)*M:ℕ):ℚ) := by + have heq : 1/innerTolerance (xi/2) j=(400:ℚ)*(j+1)*(1/xi) := by + unfold innerTolerance + field_simp + ring + rw [heq] + have hh := mul_le_mul + (show (400:ℚ)*(j+1) ≤ 400*(M+1) by exact_mod_cast Nat.mul_le_mul_left 400 (Nat.add_le_add_right hj 1)) + hi (one_div_pos.mpr hxi).le (by positivity) + simpa only [Nat.cast_mul,Nat.cast_add,Nat.cast_ofNat,Nat.cast_one] using hh + +lemma degree_bound (j M : ℕ) (xi : ℚ) (hj : j ≤ M) + (hxi : 0 < xi) (hi : 1/xi ≤ (M:ℚ)) : + PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j)) ≤ + 512*(400*(M+1)*M) := by + unfold PowerOfTwoApproximation.rootDegree roundingTolerance + apply Nat.ceil_le.mpr + have hh := mul_le_mul_of_nonneg_left (inner_inverse_bound j M xi hj hxi hi) + (show (0:ℚ) ≤ 512 by norm_num) + convert hh using 1 + · field_simp + ring + · push_cast + rfl + +lemma padding_bound (j M : ℕ) (xi : ℚ) (hj : j ≤ M) + (hxi : 0 < xi) (hi : 1/xi ≤ (M:ℚ)) : + PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j))+ + PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j)) ≤ + paddingPolynomial.eval M := by + have hd := degree_bound j M xi hj hxi hi + have hdepth : PowerOfTwoApproximation.depth (roundingTolerance (innerTolerance (xi/2) j)) ≤ + PowerOfTwoApproximation.rootDegree (roundingTolerance (innerTolerance (xi/2) j)) := + Nat.clog_le_of_le_pow (Nat.le_of_lt Nat.lt_two_pow_self) + simp only [paddingPolynomial,Polynomial.eval_mul,Polynomial.eval_add, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + have heq : 409600*(M+1)*M=2*(512*(400*(M+1)*M)) := by ring + rw [heq] + omega + +end +end ContingencyTables.CountingMarkerBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleScheduleBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleScheduleBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..5826f686c7ea2c2f776d0e600a91b179d6be552d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleScheduleBounds.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingOracleScheduleProgram + +namespace OAI + +/-! # Numeric bounds for the executed oracle schedule -/ + +namespace ContingencyTables.CountingOracleScheduleProgram +open MatchingFPRAS + +lemma sampleCount_bound (j E F : ℕ) (delta failure : Fraction) + (hd : 0 < TreeFraction.val delta) (_hf : 0 < TreeFraction.val failure) + (hE : 1/TreeFraction.val delta ≤ (E:ℚ)) + (hF : 1/TreeFraction.val failure ≤ (F:ℚ)) : + sampleCount (j,(delta,failure)) ≤ 65536*(j+1)*F*E^2 := by + rw [sampleCount_val] + apply Nat.ceil_le.mpr + have hs : (1/TreeFraction.val delta)^2 ≤ (E:ℚ)^2 := by + have h0 := (one_div_pos.mpr hd).le + nlinarith + have hh := mul_le_mul hF hs (sq_nonneg _) (Nat.cast_nonneg F) + have hm := mul_le_mul_of_nonneg_left hh (show (0:ℚ) ≤ 65536*(j+1) by positivity) + convert hm using 1 <;> push_cast <;> ring + +lemma offsetAccuracy_bound (d E : ℕ) (delta : Fraction) + (hE : 1/TreeFraction.val delta ≤ (E:ℚ)) : + offsetAccuracy (d,delta) ≤ 4096*d*E := by + rw [offsetAccuracy_val] + apply Nat.ceil_le.mpr + have hh := mul_le_mul_of_nonneg_left hE (show (0:ℚ) ≤ 4096*d by positivity) + convert hh using 1 <;> push_cast <;> ring + +lemma oracleTime_bound (M B E : ℕ) (theta : Fraction) + (hE : 1/TreeFraction.val theta ≤ (E:ℚ)) : + oracleTime ((M,B),theta) ≤ M*(B+16*E) := by + rw [oracleTime_val] + apply Nat.ceil_le.mpr + have ht : 16/TreeFraction.val theta ≤ 16*(E:ℚ) := by + have hh := mul_le_mul_of_nonneg_left hE (show (0:ℚ) ≤ 16 by norm_num) + simpa only [mul_one_div] using hh + have hh := mul_le_mul_of_nonneg_left (add_le_add_left ht (B:ℚ)) (Nat.cast_nonneg M) + simpa only [Nat.cast_mul,Nat.cast_add,Nat.cast_ofNat,add_comm] using hh + +end ContingencyTables.CountingOracleScheduleProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleScheduleProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleScheduleProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..257721b970254956c35d1421609069a00d3b584d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleScheduleProgram.lean @@ -0,0 +1,178 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalSchedule +import OAI.Combinatorics.ContingencyTables.Machines.OffsetCountProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleSchedule +import OAI.Combinatorics.MatchingCount.Complexity.TreeFractionCosts + +namespace OAI + +/-! # Binary arithmetic for the counting oracle sample schedule -/ + +namespace ContingencyTables.CountingOracleScheduleProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev Fraction := TreeFraction.Fraction + +def ceiling (e : Fraction) : ℕ := OffsetCountPrograms.ceilQuotient e +def ceilingRealizer : Realizer ceiling := OffsetCountPrograms.ceilQuotientRealizer +lemma polynomial_ceiling : PolynomialTime ceilingRealizer := OffsetCountPrograms.polynomial_ceilQuotient + +lemma ceiling_val (e : Fraction) : ceiling e=⌈TreeFraction.val e⌉₊ := by + by_cases h : e.2=0 + · simp only [ceiling,OffsetCountPrograms.ceilQuotient,TreeFraction.val,h,Nat.div_zero, + Nat.cast_zero,div_zero,Nat.ceil_zero] + · exact OffsetCountPrograms.ceilQuotient_eq e.1 e.2 (Nat.pos_of_ne_zero h) + +def natural (n : ℕ) : Fraction := (n,1) +def naturalRealizer : Realizer natural := pair identity (constant 1) +lemma polynomial_natural : PolynomialTime naturalRealizer := + polynomial_pair polynomial_identity (polynomial_constant 1) +lemma natural_val (n : ℕ) : TreeFraction.val (natural n)=(n:ℚ) := by + simp only [natural,TreeFraction.val,Nat.cast_one,div_one] + +/-- Phase index, relative tolerance, and failure allowance. -/ +abbrev SampleInput := ℕ×(Fraction×Fraction) +def sampleBase (z : SampleInput) : Fraction := natural (65536*(z.1+1)) +def sampleBaseRealizer : Realizer sampleBase := + composition (f := fun z : SampleInput => 65536*(z.1+1)) (g := natural) + (composition (f := fun z : SampleInput => (65536,z.1+1)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 65536) (composition first successor)) multiply) naturalRealizer +lemma polynomial_sampleBase : PolynomialTime sampleBaseRealizer := + polynomial_composition (polynomial_composition (polynomial_pair (polynomial_constant 65536) + (polynomial_composition polynomial_first polynomial_successor)) polynomial_multiply) polynomial_natural + +def sampleDenominator (z : SampleInput) : Fraction := + TreeFraction.mul (z.2.2,TreeFraction.mul (z.2.1,z.2.1)) +def sampleDenominatorRealizer : Realizer sampleDenominator := + composition (f := fun z : SampleInput => (z.2.2,TreeFraction.mul (z.2.1,z.2.1))) + (g := TreeFraction.mul) + (pair (composition second second) + (composition (f := fun z : SampleInput => (z.2.1,z.2.1)) (g := TreeFraction.mul) + (pair (composition second first) (composition second first)) TreeFraction.mulRealizer)) + TreeFraction.mulRealizer +lemma polynomial_sampleDenominator : PolynomialTime sampleDenominatorRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) TreeFraction.polynomial_mul)) + TreeFraction.polynomial_mul + +def sampleRatio (z : SampleInput) : Fraction := TreeFraction.div (sampleBase z,sampleDenominator z) +def sampleRatioRealizer : Realizer sampleRatio := + composition (f := fun z : SampleInput => (sampleBase z,sampleDenominator z)) + (g := TreeFraction.div) (pair sampleBaseRealizer sampleDenominatorRealizer) TreeFraction.divRealizer +lemma polynomial_sampleRatio : PolynomialTime sampleRatioRealizer := + polynomial_composition (polynomial_pair polynomial_sampleBase polynomial_sampleDenominator) + TreeFraction.polynomial_div + +def sampleCount (z : SampleInput) : ℕ := ceiling (sampleRatio z) +def sampleCountRealizer : Realizer sampleCount := + composition (f := sampleRatio) (g := ceiling) sampleRatioRealizer ceilingRealizer +lemma polynomial_sampleCount : PolynomialTime sampleCountRealizer := + polynomial_composition polynomial_sampleRatio polynomial_ceiling + +lemma sampleCount_val (j : ℕ) (delta failure : Fraction) : + sampleCount (j,(delta,failure))= + CompanionOracleDensity.sampleCount j (TreeFraction.val delta) (TreeFraction.val failure) := by + rw [sampleCount,ceiling_val,sampleRatio,TreeFraction.div_val,sampleBase,natural_val, + sampleDenominator,TreeFraction.mul_val,TreeFraction.mul_val] + unfold CompanionOracleDensity.sampleCount + congr 1 + push_cast + ring + +/-- Ambient dimension and requested relative accuracy. -/ +abbrev OffsetInput := ℕ×Fraction +def offsetBase (z : OffsetInput) : Fraction := natural (4096*z.1) +def offsetBaseRealizer : Realizer offsetBase := + composition (f := fun z : OffsetInput => 4096*z.1) (g := natural) + (composition (f := fun z : OffsetInput => (4096,z.1)) (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 4096) first) multiply) naturalRealizer +lemma polynomial_offsetBase : PolynomialTime offsetBaseRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_constant 4096) polynomial_first) polynomial_multiply) polynomial_natural + +def offsetRatio (z : OffsetInput) : Fraction := TreeFraction.div (offsetBase z,z.2) +def offsetRatioRealizer : Realizer offsetRatio := + composition (f := fun z : OffsetInput => (offsetBase z,z.2)) (g := TreeFraction.div) + (pair offsetBaseRealizer second) TreeFraction.divRealizer +lemma polynomial_offsetRatio : PolynomialTime offsetRatioRealizer := + polynomial_composition (polynomial_pair polynomial_offsetBase polynomial_second) TreeFraction.polynomial_div + +def offsetAccuracy (z : OffsetInput) : ℕ := ceiling (offsetRatio z) +def offsetAccuracyRealizer : Realizer offsetAccuracy := + composition (f := offsetRatio) (g := ceiling) offsetRatioRealizer ceilingRealizer +lemma polynomial_offsetAccuracy : PolynomialTime offsetAccuracyRealizer := + polynomial_composition polynomial_offsetRatio polynomial_ceiling + +lemma offsetAccuracy_val (d : ℕ) (delta : Fraction) : + offsetAccuracy (d,delta)=⌈4096*(d:ℚ)/TreeFraction.val delta⌉₊ := by + rw [offsetAccuracy,ceiling_val,offsetRatio,TreeFraction.div_val,offsetBase,natural_val] + simp only [Nat.cast_mul,Nat.cast_ofNat] + + +/-- The natural mixing factor and the natural height-plus-grid allowance, +followed by the rational per-call accuracy. -/ +abbrev TimeInput := (ℕ×ℕ)×Fraction + +def timeBase (z : TimeInput) : Fraction := natural (z.1.1*z.1.2) +def timeBaseRealizer : Realizer timeBase := + composition (f := fun z : TimeInput => z.1.1*z.1.2) (g := natural) + (composition first multiply) naturalRealizer +lemma polynomial_timeBase : PolynomialTime timeBaseRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_multiply) polynomial_natural + +def timeNumerator (z : TimeInput) : Fraction := natural (16*z.1.1) +def timeNumeratorRealizer : Realizer timeNumerator := + composition (f := fun z : TimeInput => 16*z.1.1) (g := natural) + (composition (f := fun z : TimeInput => (16,z.1.1)) (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 16) (composition first first)) multiply) naturalRealizer +lemma polynomial_timeNumerator : PolynomialTime timeNumeratorRealizer := + polynomial_composition (polynomial_composition (polynomial_pair (polynomial_constant 16) + (polynomial_composition polynomial_first polynomial_first)) polynomial_multiply) polynomial_natural + +def timeExtra (z : TimeInput) : Fraction := TreeFraction.div (timeNumerator z,z.2) +def timeExtraRealizer : Realizer timeExtra := + composition (f := fun z : TimeInput => (timeNumerator z,z.2)) (g := TreeFraction.div) + (pair timeNumeratorRealizer second) TreeFraction.divRealizer +lemma polynomial_timeExtra : PolynomialTime timeExtraRealizer := + polynomial_composition (polynomial_pair polynomial_timeNumerator polynomial_second) TreeFraction.polynomial_div + +def timeTotal (z : TimeInput) : Fraction := TreeFraction.add (timeBase z,timeExtra z) +def timeTotalRealizer : Realizer timeTotal := + composition (f := fun z : TimeInput => (timeBase z,timeExtra z)) (g := TreeFraction.add) + (pair timeBaseRealizer timeExtraRealizer) TreeFraction.addRealizer +lemma polynomial_timeTotal : PolynomialTime timeTotalRealizer := + polynomial_composition (polynomial_pair polynomial_timeBase polynomial_timeExtra) TreeFraction.polynomial_add + +def oracleTime (z : TimeInput) : ℕ := ceiling (timeTotal z) +def oracleTimeRealizer : Realizer oracleTime := + composition (f := timeTotal) (g := ceiling) timeTotalRealizer ceilingRealizer +lemma polynomial_oracleTime : PolynomialTime oracleTimeRealizer := + polynomial_composition polynomial_timeTotal polynomial_ceiling + +lemma oracleTime_val (M B : ℕ) (theta : Fraction) : + oracleTime ((M,B),theta)=⌈(M:ℚ)*((B:ℚ)+16/TreeFraction.val theta)⌉₊ := by + have he : (timeExtra ((M,B),theta)).2 ≠ 0 := by + exact (TreeFraction.normalize_den_pos _).ne' + rw [oracleTime,ceiling_val,timeTotal,TreeFraction.add_val _ _ (by change (1:ℕ) ≠ 0; decide) he, + timeBase,natural_val,timeExtra,TreeFraction.div_val,timeNumerator,natural_val] + congr 1 + push_cast + ring + +lemma oracleTime_instance {I J : Type} [Fintype I] [Fintype J] + (A : CompanionFactorialApplication.Instance I J) (C K : ℕ) (theta : Fraction) : + oracleTime ((2*(10000*A.d^2*K)^2, + CompanionOracleDensity.rationalHeight A C+A.d*K+2),theta)= + CompanionOracleDensity.oracleTime A C K 1 (TreeFraction.val theta) := by + rw [oracleTime_val,CompanionOracleDensity.oracleTime] + rw [←CountingTerminalSchedule.natCeil_ratCast] + congr 1 + simp only [CompanionOracleDensity.mixingConstant,CompanionOracleDensity.rationalHeight, + CompanionOracleDensity.height,Nat.cast_mul,Nat.cast_add,Nat.cast_pow,Nat.cast_ofNat, + Rat.cast_mul,Rat.cast_add,Rat.cast_div,Rat.cast_natCast,Rat.cast_ofNat,Rat.cast_pow] + ring + +end ContingencyTables.CountingOracleScheduleProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleWordBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleWordBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..3dfcbdf917857a8f1c672e0d4b7666e34f934b26 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingOracleWordBounds.lean @@ -0,0 +1,175 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingOracleScheduleBounds +import OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorAmplification +import OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalSchedule + +namespace OAI + +/-! # Polynomial word sizes for the executed density oracle -/ + +namespace ContingencyTables.CountingOracleWordBounds +open CompanionFactorialApplication CompanionOracleDensity GridBoundary +open Polynomial +open scoped BigOperators Classical +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +lemma binWordBits_bound (A : Instance I J) (h : ℕ) : + binWordBits A h ≤ A.d*(CountingTerminalSchedule.capacityBits A+1+4*(h+A.d)) := by + have hb (i : Fin (dimension A)) : + Nat.clog 2 (freeRange A (index A i)+1) ≤ CountingTerminalSchedule.capacityBits A+1 := by + let t := index A i + have hs : (A.b t.val.1 t.val.2+1).size ≤ CountingTerminalSchedule.capacityBits A := by + change (A.b t.val.1 t.val.2+1).size ≤ ∑ a : I×J,(A.b a.1 a.2+1).size + exact Finset.single_le_sum (f := fun a : I×J => (A.b a.1 a.2+1).size) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ (t.val.1,t.val.2)) + have hp := Nat.lt_size_self (A.b t.val.1 t.val.2+1) + apply Nat.clog_le_of_le_pow + have hpow := Nat.pow_le_pow_right (by decide : 1 ≤ 2) hs + change A.b t.val.1 t.val.2+1+1 ≤ 2^(CountingTerminalSchedule.capacityBits A+1) + rw [pow_succ] + omega + unfold binWordBits + calc + _ ≤ ∑ _i : Fin (dimension A), + (CountingTerminalSchedule.capacityBits A+1+4*(h+A.d)) := by + apply Finset.sum_le_sum + intro i _ + exact Nat.add_le_add_right (hb i) _ + _ = dimension A*(CountingTerminalSchedule.capacityBits A+1+4*(h+A.d)) := by simp + _ ≤ _ := Nat.mul_le_mul_right _ (ForestScaledPenalty.free_card_le A) + +lemma oracle_time_bound (A : Instance I J) (C K E : ℕ) (theta : ℚ) + (hE : 1/theta ≤ (E:ℚ)) : + oracleTime A C K 1 theta ≤ + 2*(10000*A.d^2*K)^2*(rationalHeight A C+A.d*K+2+16*E) := by + unfold oracleTime + apply Nat.ceil_le.mpr + have ht : (1:ℝ)/(theta:ℝ) ≤ (E:ℝ) := by exact_mod_cast hE + have hh := mul_le_mul_of_nonneg_left + (add_le_add_left (mul_le_mul_of_nonneg_left ht (show (0:ℝ) ≤ 16 by norm_num)) + (height A C+(A.d:ℝ)*K+2)) + (show 0 ≤ mixingConstant A K by unfold mixingConstant; positivity) + convert hh using 1 <;> + simp only [mixingConstant,←rationalHeight_cast A C,Nat.cast_mul,Nat.cast_add, + Nat.cast_pow,Nat.cast_ofNat,Nat.cast_one] <;> ring + +lemma samples_bound (j E : ℕ) (delta : ℚ) (hd : 0 < delta) + (hE : 1/delta ≤ (E:ℚ)) : sampleCount j delta 1 ≤ 65536*(j+1)*E^2 := by + unfold sampleCount + apply Nat.ceil_le.mpr + have he0 : 0 ≤ 1/delta := (one_div_pos.mpr hd).le + have hs : (1/delta)^2 ≤ (E:ℚ)^2 := by nlinarith + have hh := mul_le_mul_of_nonneg_left hs (show (0:ℚ) ≤ 65536*(j+1) by positivity) + convert hh using 1 <;> push_cast <;> ring + +lemma offset_bound (A : Instance I J) (E : ℕ) (delta : ℚ) + (hE : 1/delta ≤ (E:ℚ)) : offsetAccuracy A delta ≤ 4096*A.d*E := by + unfold offsetAccuracy + apply Nat.ceil_le.mpr + have hh := mul_le_mul_of_nonneg_left hE (show (0:ℚ) ≤ 4096*A.d by positivity) + convert hh using 1 <;> push_cast <;> ring + +def timeBound (M E : ℕ) : ℕ := + 2*(10000*M^2*M)^2*(M+M*M+2+4096*E) +def sampleBound (M E : ℕ) : ℕ := 65536*(M+1)*E^2 +def binBound (M E : ℕ) : ℕ := M*(M+1+4*(4096*M*E+M)) +def estimatorBound (M E : ℕ) : ℕ := + M*(sampleBound M E*(timeBound M E*(9*M)))+ + sampleBound M E*(timeBound M E*(9*M)+binBound M E) + +lemma oracle_time_uniform (A : Instance I J) (C K M E : ℕ) (theta : ℚ) + (hd : A.d ≤ M) (hK : K ≤ M) (hH : rationalHeight A C ≤ M) + (hE : 1/theta ≤ ((256*E:ℕ):ℚ)) : + oracleTime A C K 1 theta ≤ timeBound M E := by + apply (oracle_time_bound A C K (256*E) theta hE).trans + unfold timeBound + apply Nat.mul_le_mul + · exact Nat.mul_le_mul_left 2 (Nat.pow_le_pow_left + (Nat.mul_le_mul (Nat.mul_le_mul_left 10000 (Nat.pow_le_pow_left hd 2)) hK) 2) + · have hk := Nat.mul_le_mul hd hK + omega + +lemma estimator_bound (A : Instance I J) (C K j M E : ℕ) (delta : ℚ) + (hd : A.d ≤ M) (hK : K ≤ M) (hH : rationalHeight A C ≤ M) + (hj : j ≤ M) (hL : CountingTerminalSchedule.capacityBits A ≤ M) + (hdelta : 0 < delta) (hE : 1/delta ≤ (E:ℚ)) : + estimatorWordBits A C K j delta 1 ≤ estimatorBound M E := by + have hE' : 1/delta ≤ ((256*E:ℕ):ℚ) := hE.trans (by exact_mod_cast (show E ≤ 256*E by omega)) + have ht := oracle_time_uniform A C K M E delta hd hK hH hE' + have hcorr : 1/(delta/256) ≤ ((256*E:ℕ):ℚ) := by + have hh := mul_le_mul_of_nonneg_left hE (show (0:ℚ) ≤ 256 by norm_num) + convert hh using 1 <;> push_cast <;> field_simp + have htc : oracleTime A C K 1 (correctionTheta delta) ≤ timeBound M E := by + simpa only [correctionTheta,Rat.cast_div,Rat.cast_ofNat] using + oracle_time_uniform A C K M E (delta/256) hd hK hH hcorr + have hs : sampleCount j delta 1 ≤ sampleBound M E := + (samples_bound j E delta hdelta hE).trans (Nat.mul_le_mul_right _ + (Nat.mul_le_mul_left 65536 (Nat.add_le_add_right hj 1))) + have ha : offsetAccuracy A delta ≤ 4096*M*E := + (offset_bound A E delta hE).trans (Nat.mul_le_mul_right E (Nat.mul_le_mul_left 4096 hd)) + have hb : binWordBits A (offsetAccuracy A delta) ≤ binBound M E := by + apply (binWordBits_bound A _).trans + unfold binBound + exact Nat.mul_le_mul hd (Nat.add_le_add (Nat.add_le_add_right hL 1) + (Nat.mul_le_mul_left 4 (Nat.add_le_add ha hd))) + have hw : oracleStepBits A C ≤ 9*M := by + have hl : Nat.clog 2 (8*A.d) ≤ 8*A.d := + Nat.clog_le_of_le_pow (Nat.le_of_lt Nat.lt_two_pow_self) + unfold oracleStepBits + omega + unfold estimatorWordBits estimatorBound oracleIntegerBits + exact Nat.add_le_add (Nat.mul_le_mul hj (Nat.mul_le_mul hs (Nat.mul_le_mul ht hw))) + (Nat.mul_le_mul hs (Nat.add_le_add (Nat.mul_le_mul htc hw) hb)) + +def innerPolynomial : Polynomial ℕ := 400*(X+1)*X +def timePolynomial : Polynomial ℕ := + 2*(10000*X^2*X)^2*(X+X*X+2+4096*innerPolynomial) +def samplePolynomial : Polynomial ℕ := 65536*(X+1)*innerPolynomial^2 +def binPolynomial : Polynomial ℕ := X*(X+1+4*(4096*X*innerPolynomial+X)) +def estimatorPolynomial : Polynomial ℕ := + X*(samplePolynomial*(timePolynomial*(9*X)))+ + samplePolynomial*(timePolynomial*(9*X)+binPolynomial) +def medianPolynomial : Polynomial ℕ := 64*(X+1)*estimatorPolynomial + +lemma estimatorPolynomial_eval (M : ℕ) : + estimatorPolynomial.eval M=estimatorBound M (400*(M+1)*M) := by + simp only [estimatorPolynomial,samplePolynomial,timePolynomial,innerPolynomial,binPolynomial, + estimatorBound,sampleBound,timeBound,binBound,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_pow,Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + +lemma median_bound_separate (A : Instance I J) (C K j M : ℕ) (xi delta : ℚ) + (hd : A.d ≤ M) (hK : K ≤ M) (hH : rationalHeight A C ≤ M) + (hj : j ≤ M) (hL : CountingTerminalSchedule.capacityBits A ≤ M) + (hxi : 0 < xi) (hi : 1/xi ≤ (M:ℚ)) + (hr : CommonBasesFPRAS.repetitionCount delta ≤ 64*(M+1)) : + medianEstimatorBits A C K j xi delta ≤ medianPolynomial.eval M := by + have hdelta : 0 < innerTolerance (xi/2) j := by unfold innerTolerance; positivity + have heq : 1/innerTolerance (xi/2) j=(400:ℚ)*(j+1)*(1/xi) := by + unfold innerTolerance + field_simp + ring + have he : 1/innerTolerance (xi/2) j ≤ ((400*(M+1)*M:ℕ):ℚ) := by + rw [heq] + have hh := mul_le_mul + (show (400:ℚ)*(j+1) ≤ 400*(M+1) by exact_mod_cast Nat.mul_le_mul_left 400 (Nat.add_le_add_right hj 1)) + hi (one_div_pos.mpr hxi).le (by positivity) + simpa only [Nat.cast_mul,Nat.cast_add,Nat.cast_ofNat,Nat.cast_one] using hh + have hb := estimator_bound A C K j M (400*(M+1)*M) (innerTolerance (xi/2) j) + hd hK hH hj hL hdelta he + unfold medianEstimatorBits + rw [medianPolynomial,Polynomial.eval_mul,Polynomial.eval_mul,Polynomial.eval_add, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one,estimatorPolynomial_eval] + exact Nat.mul_le_mul hr hb + +lemma median_bound (A : Instance I J) (C K j M : ℕ) (xi : ℚ) + (hd : A.d ≤ M) (hK : K ≤ M) (hH : rationalHeight A C ≤ M) + (hj : j ≤ M) (hL : CountingTerminalSchedule.capacityBits A ≤ M) + (hxi : 0 < xi) (hi : 1/xi ≤ (M:ℚ)) + (hr : CommonBasesFPRAS.repetitionCount xi ≤ 64*(M+1)) : + medianEstimatorBits A C K j xi xi ≤ medianPolynomial.eval M := + median_bound_separate A C K j M xi xi hd hK hH hj hL hxi hi hr + +end +end ContingencyTables.CountingOracleWordBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseParametersProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseParametersProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..9fcf50cd0118215d7873f321f83fac2f17560a60 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseParametersProgram.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseScalarProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingOracleScheduleProgram + +namespace OAI + +/-! # Executable rational controls for the adaptive counting phases -/ + +namespace ContingencyTables.CountingPhaseParametersProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped +open CountingOracleScheduleProgram ScalarScheduleProgram + +abbrev Input := List ℕ × Fraction + +def scalar (e : Expr) (z : Input) : ℕ := e.eval z.1 +def scalarRealizer (e : Expr) : Realizer (scalar e) := + composition (f := fun z : Input => z.1) (g := e.eval) first e.realizer +lemma polynomial_scalar (e : Expr) : PolynomialTime (scalarRealizer e) := + polynomial_composition polynomial_first e.polynomial + +def scalarFraction (e : Expr) (z : Input) : Fraction := natural (scalar e z) +def scalarFractionRealizer (e : Expr) : Realizer (scalarFraction e) := + composition (f := scalar e) (g := natural) (scalarRealizer e) naturalRealizer +lemma polynomial_scalarFraction (e : Expr) : PolynomialTime (scalarFractionRealizer e) := + polynomial_composition (polynomial_scalar e) polynomial_natural + +def toleranceDenominator : Expr := 800*(CountingPhaseScalarProgram.h+1) +def tolerance (z : Input) : Fraction := TreeFraction.div (z.2,scalarFraction toleranceDenominator z) +def toleranceRealizer : Realizer tolerance := + composition (f := fun z : Input => (z.2,scalarFraction toleranceDenominator z)) + (g := TreeFraction.div) (pair second (scalarFractionRealizer toleranceDenominator)) + TreeFraction.divRealizer +lemma polynomial_tolerance : PolynomialTime toleranceRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_scalarFraction toleranceDenominator)) TreeFraction.polynomial_div + +lemma tolerance_val (P W H T N R L : ℕ) (e : Fraction) : + TreeFraction.val (tolerance ([P,W,H,T,N,R,L],e))= + CountingPhaseSchedule.tolerance H (TreeFraction.val e) := by + rw [tolerance,TreeFraction.div_val,scalarFraction,natural_val] + simp [scalar,toleranceDenominator,CountingPhaseScalarProgram.h,Expr.eval, + CountingPhaseSchedule.tolerance] + +def toleranceSquare (z : Input) : Fraction := TreeFraction.mul (tolerance z,tolerance z) +def toleranceSquareRealizer : Realizer toleranceSquare := + composition (f := fun z : Input => (tolerance z,tolerance z)) (g := TreeFraction.mul) + (pair toleranceRealizer toleranceRealizer) TreeFraction.mulRealizer +lemma polynomial_toleranceSquare : PolynomialTime toleranceSquareRealizer := + polynomial_composition (polynomial_pair polynomial_tolerance polynomial_tolerance) + TreeFraction.polynomial_mul + +def observationRatio (z : Input) : Fraction := + TreeFraction.div (scalarFraction CountingPhaseScalarProgram.observationNumerator z, + toleranceSquare z) +def observationRatioRealizer : Realizer observationRatio := + composition (f := fun z : Input => + (scalarFraction CountingPhaseScalarProgram.observationNumerator z,toleranceSquare z)) + (g := TreeFraction.div) + (pair (scalarFractionRealizer CountingPhaseScalarProgram.observationNumerator) + toleranceSquareRealizer) TreeFraction.divRealizer +lemma polynomial_observationRatio : PolynomialTime observationRatioRealizer := + polynomial_composition (polynomial_pair + (polynomial_scalarFraction CountingPhaseScalarProgram.observationNumerator) + polynomial_toleranceSquare) TreeFraction.polynomial_div + +def observations (z : Input) : ℕ := ceiling (observationRatio z)+1 +def observationsRealizer : Realizer observations := + composition (f := fun z : Input => ceiling (observationRatio z)) (g := Nat.succ) + (composition (f := observationRatio) (g := ceiling) observationRatioRealizer ceilingRealizer) + successor +lemma polynomial_observations : PolynomialTime observationsRealizer := + polynomial_composition (polynomial_composition polynomial_observationRatio polynomial_ceiling) + polynomial_successor + +lemma observations_val (P W H T N R L : ℕ) (e : Fraction) : + observations ([P,W,H,T,N,R,L],e)= + CountingPhaseSchedule.observations P W H + (CountingPhaseSchedule.tolerance H (TreeFraction.val e)) := by + rw [observations,ceiling_val,observationRatio,TreeFraction.div_val, + scalarFraction,natural_val,toleranceSquare,TreeFraction.mul_val,tolerance_val] + change ⌈((CountingPhaseScalarProgram.observationNumerator.eval [P,W,H,T,N,R,L]:ℕ):ℚ)/ + (CountingPhaseSchedule.tolerance H (TreeFraction.val e)* + CountingPhaseSchedule.tolerance H (TreeFraction.val e))⌉₊+1= _ + rw [CountingPhaseScalarProgram.observationNumerator_value] + simp only [CountingPhaseSchedule.observations,Nat.cast_mul,Nat.cast_ofNat, + Nat.cast_add,Nat.cast_one,pow_two] + +def reciprocalTolerance (z : Input) : Fraction := TreeFraction.div ((1,1),tolerance z) +def reciprocalToleranceRealizer : Realizer reciprocalTolerance := + composition (f := fun z : Input => ((1,1),tolerance z)) (g := TreeFraction.div) + (pair (constant (1,1)) toleranceRealizer) TreeFraction.divRealizer +lemma polynomial_reciprocalTolerance : PolynomialTime reciprocalToleranceRealizer := + polynomial_composition (polynomial_pair (polynomial_constant (1,1)) polynomial_tolerance) + TreeFraction.polynomial_div + +def reciprocalCeiling (z : Input) : ℕ := ceiling (reciprocalTolerance z) +def reciprocalCeilingRealizer : Realizer reciprocalCeiling := + composition (f := reciprocalTolerance) (g := ceiling) reciprocalToleranceRealizer ceilingRealizer +lemma polynomial_reciprocalCeiling : PolynomialTime reciprocalCeilingRealizer := + polynomial_composition polynomial_reciprocalTolerance polynomial_ceiling + +def precision (z : Input) : ℕ := scalar CountingPhaseScalarProgram.precisionBase z+reciprocalCeiling z +def precisionRealizer : Realizer precision := + composition (f := fun z : Input => (scalar CountingPhaseScalarProgram.precisionBase z, + reciprocalCeiling z)) (g := fun p : ℕ×ℕ => p.1+p.2) + (pair (scalarRealizer CountingPhaseScalarProgram.precisionBase) reciprocalCeilingRealizer) add +lemma polynomial_precision : PolynomialTime precisionRealizer := + polynomial_composition (polynomial_pair (polynomial_scalar CountingPhaseScalarProgram.precisionBase) + polynomial_reciprocalCeiling) polynomial_add + +lemma precision_val (P W H T N R L : ℕ) (e : Fraction) : + precision ([P,W,H,T,N,R,L],e)= + CountingPhaseSchedule.precision H T N R + (CountingPhaseSchedule.tolerance H (TreeFraction.val e)) := by + rw [precision,reciprocalCeiling,ceiling_val,reciprocalTolerance,TreeFraction.div_val,tolerance_val] + simp only [TreeFraction.val,Nat.cast_one,div_one] + change CountingPhaseScalarProgram.precisionBase.eval [P,W,H,T,N,R,L]+ + ⌈1/CountingPhaseSchedule.tolerance H (TreeFraction.val e)⌉₊= _ + rw [CountingPhaseScalarProgram.precisionBase_value] + simp only [CountingPhaseSchedule.precision,TreeFraction.val] + omega + +def noise (z : Input) : Fraction := (1,precision z) +def noiseRealizer : Realizer noise := pair (constant 1) precisionRealizer +lemma polynomial_noise : PolynomialTime noiseRealizer := + polynomial_pair (polynomial_constant 1) polynomial_precision + +lemma noise_val (P W H T N R L : ℕ) (e : Fraction) : + TreeFraction.val (noise ([P,W,H,T,N,R,L],e))= + CountingPhaseSchedule.noise H T N R + (CountingPhaseSchedule.tolerance H (TreeFraction.val e)) := by + simp only [noise,TreeFraction.val,Nat.cast_one,precision_val,CountingPhaseSchedule.noise] + +end ContingencyTables.CountingPhaseParametersProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseScalarProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseScalarProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..388ad56f45824d92ee0cf77e959efd5dfa748a97 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseScalarProgram.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ScalarScheduleProgram +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingSchedule + +namespace OAI + +/-! # Fixed arithmetic circuits for the phase scalar controls -/ + +namespace ContingencyTables.CountingPhaseScalarProgram +open ScalarScheduleProgram +open MatchingFPRAS.TreeTyped + +/-- Field order: label count, cutoff, phase count, restart time, +observation count, return cap, capacity-bit allowance. -/ +def p : Expr := .input 0 +def w : Expr := .input 1 +def h : Expr := .input 2 +def tau : Expr := .input 3 +def observations : Expr := .input 4 +def returns : Expr := .input 5 +def capacityBits : Expr := .input 6 + +def observable : Expr := 10*p^4*(9*(p*(1+8*p*w^4))+2*(8+32*p*w^6)) +def observationNumerator : Expr := 1024*(h+1)*(32000*p^8*observable) +def restartTime : Expr := 4*observable*(h+p+capacityBits+5) +def returnCap : Expr := 65536*(h+1)^2*(tau+1)*(p^2+1) +def precisionBase : Expr := 1024*(h+1)*(8*(observations+1)+8*h*tau*(returns+1))+1 +def initialPrecision : Expr := 2048*(h+1) + +lemma observable_value (P W H T N R L : ℕ) : + observable.eval [P,W,H,T,N,R,L]=CountingPhaseSchedule.observable P W := by + simp [observable,p,w,Expr.eval,CountingPhaseSchedule.observable] + +lemma observationNumerator_value (P W H T N R L : ℕ) : + observationNumerator.eval [P,W,H,T,N,R,L]= + 1024*(H+1)*CountingPhaseSchedule.observationCoefficient P W := by + simp [observationNumerator,observable,p,w,h,Expr.eval, + CountingPhaseSchedule.observationCoefficient,CountingPhaseSchedule.observable] + +lemma returnCap_value (P W H T N R L : ℕ) : + returnCap.eval [P,W,H,T,N,R,L]=CountingPhaseSchedule.returnCap P H T := by + simp [returnCap,p,h,tau,Expr.eval,CountingPhaseSchedule.returnCap] + +lemma precisionBase_value (P W H T N R L : ℕ) : + precisionBase.eval [P,W,H,T,N,R,L]= + 1024*(H+1)*CountingPhaseSchedule.noiseCoefficient H T N R+1 := by + simp [precisionBase,h,tau,observations,returns,Expr.eval,CountingPhaseSchedule.noiseCoefficient] + +lemma initialPrecision_value (P W H T N R L : ℕ) : + initialPrecision.eval [P,W,H,T,N,R,L]=CountingPhaseSchedule.initialPrecision H := by + simp [initialPrecision,h,Expr.eval,CountingPhaseSchedule.initialPrecision] + +lemma restartTime_instance {I J : Type} [Fintype I] [Fintype J] + (A : CompanionFactorialApplication.Instance I J) (H L T N R : ℕ) : + restartTime.eval [Fintype.card (CompanionFactorialApplication.Labels A),A.W,H,T,N,R,L]= + CompanionTargetMixing.restartTime A H L := by + simp [restartTime,observable,p,w,h,capacityBits,Expr.eval, + CompanionTargetMixing.restartTime,CompanionTrace.time,CompanionTrace.integerConstant] + ring + +/-- Every circuit above has a fixed polynomial binary-time implementation. -/ +lemma polynomial (e : Expr) : PolynomialTime e.realizer := e.polynomial + +end ContingencyTables.CountingPhaseScalarProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseSchedule.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..5654747e3560a3bcd88211645387eabfd6e624e8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPhaseSchedule.lean @@ -0,0 +1,214 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedHistoryStep + +namespace OAI + +/-! # Explicit scalar schedules for the adaptive counting phases + +Every precision and sample length below is a rational or natural arithmetic +expression. In particular the dyadic exponents use a polynomial reciprocal +allowance, so no real logarithm is evaluated by the algorithm. +-/ + +namespace ContingencyTables.CountingPhaseSchedule + +open scoped BigOperators + +/-- Per-phase logarithmic tolerance. -/ +def tolerance (H : ℕ) (epsilon : ℚ) : ℚ := epsilon/(800*(H+1)) + +/-- The integer form of the manuscript's observable coefficient. -/ +def observable (p W : ℕ) : ℕ := + 10*p^4*(9*(p*(1+8*p*W^4))+2*(8+32*p*W^6)) + +def observationCoefficient (p W : ℕ) : ℕ := 32000*p^8*observable p W + +def observations (p W H : ℕ) (eta : ℚ) : ℕ := + ⌈(1024:ℚ)*(H+1)*observationCoefficient p W/eta^2⌉₊+1 + +def returnCap (p H tau : ℕ) : ℕ := 65536*(H+1)^2*(tau+1)*(p^2+1) + +def noiseCoefficient (H tau N n : ℕ) : ℕ := 8*(N+1)+8*H*tau*(n+1) + +def precision (H tau N n : ℕ) (eta : ℚ) : ℕ := + 1024*(H+1)*noiseCoefficient H tau N n+⌈1/eta⌉₊+1 + +def noise (H tau N n : ℕ) (eta : ℚ) : ℚ := + 1/(precision H tau N n eta:ℚ) + +def initialPrecision (H : ℕ) : ℕ := 2048*(H+1) + +lemma tolerance_pos (H : ℕ) (epsilon : ℚ) (he : 0 < epsilon) : + 0 < tolerance H epsilon := by + unfold tolerance + positivity + +lemma tolerance_le_quarter (H : ℕ) (epsilon : ℚ) (he0 : 0 < epsilon) + (he1 : epsilon < 1) : tolerance H epsilon ≤ 1/4 := by + unfold tolerance + apply (div_le_iff₀ (by positivity : (0:ℚ) < 800*(H+1))).mpr + have hH : (1:ℚ) ≤ H+1 := by have h0 := Nat.cast_nonneg (α := ℚ) H; linarith + nlinarith + +lemma observations_pos (p W H : ℕ) (eta : ℚ) : 0 < observations p W H eta := by + unfold observations + omega + +lemma returnCap_pos (p H tau : ℕ) : 0 < returnCap p H tau := by + unfold returnCap + positivity + +lemma precision_pos (H tau N n : ℕ) (eta : ℚ) : 0 < precision H tau N n eta := by + unfold precision + omega + +lemma noise_pos (H tau N n : ℕ) (eta : ℚ) : 0 < noise H tau N n eta := by + unfold noise + exact one_div_pos.mpr (by exact_mod_cast precision_pos H tau N n eta) + +lemma noise_le_tolerance (H tau N n : ℕ) (eta : ℚ) (he : 0 < eta) : + noise H tau N n eta ≤ eta := by + have hceil := Nat.le_ceil (1/eta) + have hbound : (1/eta:ℚ) ≤ precision H tau N n eta := by + apply hceil.trans + exact_mod_cast (show ⌈1/eta⌉₊ ≤ precision H tau N n eta by unfold precision; omega) + have hp : (0:ℚ) < precision H tau N n eta := by + exact_mod_cast precision_pos H tau N n eta + unfold noise + apply (div_le_iff₀ hp).mpr + have hb := (div_le_iff₀ he).mp hbound + nlinarith + +lemma reciprocal_two_pow (k : ℕ) (hk : 0 < k) : + 1/(2:ℝ)^k ≤ 1/(k:ℝ) := by + have hnat : k ≤ 2^k := Nat.lt_two_pow_self.le + exact one_div_le_one_div_of_le (by exact_mod_cast hk) (by exact_mod_cast hnat) + +lemma precision_error (H tau N n : ℕ) (eta : ℚ) : + 1/(2:ℝ)^(precision H tau N n eta) ≤ (noise H tau N n eta:ℝ) := by + simpa only [noise,Rat.cast_div,Rat.cast_one,Rat.cast_natCast] using + reciprocal_two_pow (precision H tau N n eta) (precision_pos H tau N n eta) + +lemma initial_error (H : ℕ) : + 2/(2:ℝ)^(initialPrecision H) ≤ 1/(1024*((H:ℝ)+1)) := by + have hk : 0 < initialPrecision H := by unfold initialPrecision; positivity + have hp := mul_le_mul_of_nonneg_left (reciprocal_two_pow (initialPrecision H) hk) + (show (0:ℝ) ≤ 2 by norm_num) + have he : 2*(1/(initialPrecision H:ℝ))=1/(1024*((H:ℝ)+1)) := by + simp only [initialPrecision,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_add,Nat.cast_one] + field_simp + ring + calc + 2/(2:ℝ)^(initialPrecision H)=2*(1/(2:ℝ)^(initialPrecision H)) := by ring + _ ≤ 2*(1/(initialPrecision H:ℝ)) := hp + _ = _ := he + +lemma observations_error (p W H : ℕ) (eta : ℚ) (he : 0 < eta) : + (observationCoefficient p W:ℝ)/ + (((observations p W H eta+1:ℕ):ℝ)*(eta:ℝ)^2) ≤ + 1/(1024*((H:ℝ)+1)) := by + have heta : (0:ℝ) < eta := by exact_mod_cast he + have hceil := Nat.le_ceil ((1024:ℚ)*(H+1)*observationCoefficient p W/eta^2) + have hraw : (1024:ℝ)*((H:ℝ)+1)*observationCoefficient p W/(eta:ℝ)^2 ≤ + observations p W H eta+1 := by + have hn : ⌈(1024:ℚ)*(H+1)*observationCoefficient p W/eta^2⌉₊ ≤ + observations p W H eta+1 := by unfold observations; omega + have hh := hceil.trans (show + (⌈(1024:ℚ)*(H+1)*observationCoefficient p W/eta^2⌉₊:ℚ) ≤ + observations p W H eta+1 by exact_mod_cast hn) + exact_mod_cast hh + have hmul := (div_le_iff₀ (sq_pos_of_pos heta)).mp hraw + rw [div_le_div_iff₀ (by positivity) (by positivity)] + push_cast + nlinarith + +lemma cap_error (p H tau : ℕ) : + 40*(H:ℝ)*tau*p^2/(returnCap p H tau:ℝ) ≤ 1/(1024*((H:ℝ)+1)) := by + have hnat : 40960*H*tau*p^2*(H+1) ≤ returnCap p H tau := by + unfold returnCap + calc + _ = 40960*(H*(H+1))*tau*p^2 := by ring + _ ≤ 65536*((H+1)^2)*(tau+1)*(p^2+1) := by + have hHH : H*(H+1) ≤ (H+1)^2 := by nlinarith + exact Nat.mul_le_mul + (Nat.mul_le_mul (Nat.mul_le_mul (by decide : 40960 ≤ 65536) hHH) + (Nat.le_succ tau)) (Nat.le_succ (p^2)) + have hr : (0:ℝ) < returnCap p H tau := by exact_mod_cast returnCap_pos p H tau + rw [div_le_div_iff₀ hr (by positivity)] + have hb : ((40960*H*tau*p^2*(H+1):ℕ):ℝ) ≤ returnCap p H tau := by exact_mod_cast hnat + push_cast at hb + nlinarith + +lemma noise_error (H tau N n : ℕ) (eta : ℚ) : + (noiseCoefficient H tau N n:ℝ)*(noise H tau N n eta:ℝ) ≤ + 1/(1024*((H:ℝ)+1)) := by + have hnat : 1024*(H+1)*noiseCoefficient H tau N n ≤ precision H tau N n eta := by + unfold precision + omega + have hp : (0:ℝ) < precision H tau N n eta := by + exact_mod_cast precision_pos H tau N n eta + simp only [noise,Rat.cast_div,Rat.cast_one,Rat.cast_natCast,mul_one_div] + rw [div_le_div_iff₀ hp (by positivity)] + have hb : ((1024*(H+1)*noiseCoefficient H tau N n:ℕ):ℝ) ≤ + precision H tau N n eta := by exact_mod_cast hnat + push_cast at hb + nlinarith + +lemma logarithmic_error (H tau N n : ℕ) (epsilon : ℚ) (he : 0 < epsilon) : + (H:ℝ)*(4*(noise H tau N n (tolerance H epsilon):ℝ)+ + 4*(tolerance H epsilon:ℝ)) ≤ (epsilon:ℝ)/50 := by + have hxi := noise_le_tolerance H tau N n (tolerance H epsilon) (tolerance_pos H epsilon he) + have hxiR : (noise H tau N n (tolerance H epsilon):ℝ) ≤ tolerance H epsilon := by + exact_mod_cast hxi + have heR : (0:ℝ) < epsilon := by exact_mod_cast he + have heq : (tolerance H epsilon:ℝ)=(epsilon:ℝ)/(800*((H:ℝ)+1)) := by + simp only [tolerance,Rat.cast_div,Rat.cast_mul,Rat.cast_ofNat,Rat.cast_add, + Rat.cast_natCast,Rat.cast_one] + have hm : (H:ℝ)+1 > 0 := by positivity + have ht : (tolerance H epsilon:ℝ)*(800*((H:ℝ)+1))=(epsilon:ℝ) := by + rw [heq] + exact div_mul_cancel₀ _ (by positivity) + have htol : (0:ℝ) < tolerance H epsilon := by exact_mod_cast tolerance_pos H epsilon he + nlinarith + +/-- The four error terms correspond to empirical observations, +initialization, restart caps and the accumulated query/transition error. -/ +lemma combine_error (p H tau N n k h : ℕ) (c eta xi allowance : ℝ) + (hxi : 0 ≤ xi) (hprec : 1/(2:ℝ)^k ≤ xi) + (hobs : c/(((N+1:ℕ):ℝ)*eta^2) ≤ allowance) + (hinit : 2/(2:ℝ)^h ≤ allowance) + (hcap : 40*(H:ℝ)*tau*p^2/(n:ℝ) ≤ allowance) + (hnoise : (noiseCoefficient H tau N n:ℝ)*xi ≤ allowance) : + c/(((N+1:ℕ):ℝ)*eta^2)+ + (N:ℝ)*((6*xi+1/(2:ℝ)^k)/2)+ + 2*(1/(2:ℝ)^h+(H:ℝ)*((tau:ℝ)* + (20*(p:ℝ)^2/n+((n+1:ℕ):ℝ)*((6*xi+1/(2:ℝ)^k)/2))))+ + 2*((N+1:ℕ):ℝ)*xi ≤ 4*allowance := by + let e := (6*xi+1/(2:ℝ)^k)/2 + have he : e ≤ 4*xi := by dsimp only [e]; linarith + have hrow : (N:ℝ)*e+2*(H:ℝ)*tau*((n+1:ℕ):ℝ)*e+ + 2*((N+1:ℕ):ℝ)*xi ≤ (noiseCoefficient H tau N n:ℝ)*xi := by + calc + _ = ((N:ℝ)+2*(H:ℝ)*tau*((n+1:ℕ):ℝ))*e+ + 2*((N+1:ℕ):ℝ)*xi := by ring + _ ≤ ((N:ℝ)+2*(H:ℝ)*tau*((n+1:ℕ):ℝ))*(4*xi)+ + 2*((N+1:ℕ):ℝ)*xi := by + exact _root_.add_le_add (mul_le_mul_of_nonneg_left he (by positivity)) (le_refl _) + _ ≤ (noiseCoefficient H tau N n:ℝ)*xi := by + simp only [noiseCoefficient,Nat.cast_add,Nat.cast_mul,Nat.cast_ofNat,Nat.cast_one] + nlinarith [mul_nonneg (Nat.cast_nonneg N : (0:ℝ) ≤ N) hxi] + have heq : c/(((N+1:ℕ):ℝ)*eta^2)+ + (N:ℝ)*((6*xi+1/(2:ℝ)^k)/2)+ + 2*(1/(2:ℝ)^h+(H:ℝ)*((tau:ℝ)* + (20*(p:ℝ)^2/n+((n+1:ℕ):ℝ)*((6*xi+1/(2:ℝ)^k)/2))))+ + 2*((N+1:ℕ):ℝ)*xi = + c/(((N+1:ℕ):ℝ)*eta^2)+2/(2:ℝ)^h+ + 40*(H:ℝ)*tau*p^2/n+ + ((N:ℝ)*e+2*(H:ℝ)*tau*((n+1:ℕ):ℝ)*e+2*((N+1:ℕ):ℝ)*xi) := by + dsimp only [e] + ring + rw [heq] + linarith + +end ContingencyTables.CountingPhaseSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..0954c56b47aafd54244a3a1bf2a2e73f9eb0a334 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveProgram.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingAdaptiveInputProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionUniformPhaseWidth +import OAI.Combinatorics.ContingencyTables.Counting.CompanionHistorySize + +namespace OAI + +/-! # One executed positive-label counting run + +The supplied word is partitioned into equally padded phase words. The phase +count only truncates a supplied list, so malformed scalar inputs do +not create an unbounded loop. +-/ +namespace ContingencyTables.CountingPositiveProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +abbrev Request := CountingDirectProgram.Request +abbrev Input := CountingDirectProgram.Input +abbrev Prepared := CompanionPhaseContextProgram.Prepared + +def prepared (req : Request) : Prepared := CountingPreparedState.output req.1 +def preparedRealizer : Realizer prepared := + composition (f := Prod.fst) (g := CountingPreparedState.output) + first CountingPreparedState.outputRealizer +lemma polynomial_prepared : PolynomialTime preparedRealizer := + polynomial_composition polynomial_first CountingPreparedState.polynomial_output + +def phaseCount (req : Request) : ℕ := + CountingPhaseParametersProgram.scalar (.input 2) (prepared req).2 +def phaseCountRealizer : Realizer phaseCount := + composition (f := fun req : Request => (prepared req).2) + (g := CountingPhaseParametersProgram.scalar (.input 2)) + (composition (f := prepared) (g := Prod.snd) preparedRealizer second) + (CountingPhaseParametersProgram.scalarRealizer (.input 2)) +lemma polynomial_phaseCount : PolynomialTime phaseCountRealizer := + polynomial_composition (polynomial_composition polynomial_prepared polynomial_second) + (CountingPhaseParametersProgram.polynomial_scalar (.input 2)) + +def phaseWidth (req : Request) : ℕ := CompanionUniformPhaseWidth.width (prepared req) +def phaseWidthRealizer : Realizer phaseWidth := + composition (f := prepared) (g := CompanionUniformPhaseWidth.width) + preparedRealizer CompanionUniformPhaseWidth.widthRealizer +lemma polynomial_phaseWidth : PolynomialTime phaseWidthRealizer := + polynomial_composition polynomial_prepared CompanionUniformPhaseWidth.polynomial_width + +def bitCount (req : Request) : ℕ := phaseCount req*phaseWidth req +def bitCountRealizer : Realizer bitCount := + composition (f := fun req : Request => (phaseCount req,phaseWidth req)) + (g := fun p : ℕ×ℕ => p.1*p.2) (pair phaseCountRealizer phaseWidthRealizer) multiply +theorem polynomial_bitCount : PolynomialTime bitCountRealizer := + polynomial_composition (polynomial_pair polynomial_phaseCount polynomial_phaseWidth) polynomial_multiply + +def words (z : Input) : List (List Bool) := + (wordChunks (phaseWidth z.1,z.2)).take (phaseCount z.1) +def wordsRealizer : Realizer words := + composition (f := fun z : Input => (wordChunks (phaseWidth z.1,z.2),phaseCount z.1)) + (g := fun p : List (List Bool)×ℕ => p.1.take p.2) + (pair (composition (f := fun z : Input => (phaseWidth z.1,z.2)) (g := wordChunks) + (pair (composition (f := Prod.fst) (g := phaseWidth) first phaseWidthRealizer) second) + wordChunksRealizer) + (composition (f := Prod.fst) (g := phaseCount) first phaseCountRealizer)) takeFast +lemma polynomial_words : PolynomialTime wordsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_phaseWidth) polynomial_second) + polynomial_wordChunks) + (polynomial_composition polynomial_first polynomial_phaseCount)) polynomial_takeFast + +def start (z : Input) : CompanionOuterHistoryProgram.Fixed := + (CountingAdaptiveInputProgram.runInput z).1 +def startRealizer : Realizer start := + composition (f := CountingAdaptiveInputProgram.runInput) (g := Prod.fst) + CountingAdaptiveInputProgram.runInputRealizer first +lemma polynomial_start : PolynomialTime startRealizer := + polynomial_composition CountingAdaptiveInputProgram.polynomial_runInput polynomial_first + +def historyInput (z : Input) : CompanionOuterHistoryProgram.Input := (start z,words z) +def historyInputRealizer : Realizer historyInput := pair startRealizer wordsRealizer +lemma polynomial_historyInput : PolynomialTime historyInputRealizer := + polynomial_pair polynomial_start polynomial_words + +attribute [local irreducible] historyInput + +def finalStored (z : Input) : CompanionOuterHistoryProgram.Stored := + CompanionOuterHistoryProgram.output (historyInput z) +def finalStoredRealizer : Realizer finalStored := + composition (f := historyInput) (g := CompanionOuterHistoryProgram.output) + historyInputRealizer CompanionOuterHistoryProgram.outputRealizer +lemma polynomial_finalStored : PolynomialTime finalStoredRealizer := + polynomial_composition polynomial_historyInput CompanionOuterHistoryProgram.polynomial_output + +def output (z : Input) : TreeFraction.Fraction := (finalStored z).2 +def outputRealizer : Realizer output := + composition (f := finalStored) (g := Prod.snd) finalStoredRealizer second +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_finalStored polynomial_second + +theorem phaseWidth_pos (req : Request) : 0 < phaseWidth req := + CompanionUniformPhaseWidth.width_pos _ + +theorem words_ofFn (req : Request) (bits : Fin (bitCount req)→Bool) : + words (req,List.ofFn bits)=List.ofFn (fun i : Fin (phaseCount req) => + List.ofFn (fun j : Fin (phaseWidth req) => bits (finProdFinEquiv (i,j)))) := by + change (wordChunks (phaseWidth req,List.ofFn bits)).take (phaseCount req)=_ + have hc := wordChunks_ofFn (n := phaseCount req) (k := phaseWidth req) (phaseWidth_pos req) bits + apply (congrArg (fun xs : List (List Bool) => xs.take (phaseCount req)) hc).trans + exact List.take_of_length_le (by simp only [List.length_ofFn]; exact le_rfl) + +end ContingencyTables.CountingPositiveProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..28fb3163b148947f1d889accc4fd0e13286c2857 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveSemantics.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingAdaptiveInputSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CompanionUniformPhaseBounds +import OAI.Combinatorics.ContingencyTables.Counting.CountingAdaptiveReserve + +namespace OAI + +/-! # Original-input semantics of the positive counting adapter -/ +namespace ContingencyTables.CountingPositiveProgram +open MatchingFPRAS CompanionFactorialApplication CompanionComputedProposal GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +theorem prepared_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : TreeFraction.Fraction) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + prepared ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta)= + CompanionUniformPhaseWidth.data A s + (CountingBaseProgram.half (TreeFraction.repr epsilon)) (fun _ => 0) + (CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he)) := by + exact CountingAdaptiveInputProgram.prepared_data hEK r c b hne epsilon he [] + +theorem phaseCount_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : TreeFraction.Fraction) : + phaseCount ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta)= + (ComputedCountingParameters.settings hEK r c b hne epsilon he).H := by + unfold phaseCount + rw [prepared_data hEK r c b hne epsilon he delta] + rfl + +theorem start_prepared (z : Input) : (start z).1=prepared z.1 := rfl + +theorem start_ofFn (req : Request) (N : ℕ) (bits : Fin N→Bool) : + start (req,List.ofFn bits)=start (req,List.replicate N false) := + CountingAdaptiveInputProgram.output_ofFn req.1 N bits + +theorem start_view (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : TreeFraction.Fraction) (bits : List Bool) + (hlen : 2*Fintype.card (Labels (ComputedCountingParameters.data hEK r c b hne epsilon he)) ≤ bits.length) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + CompanionPhaseFinishProgram.view + ((start (((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta),bits)).2)= + CompanionPhaseFinishProgram.storedView A (pairLabels A) (RootedStoredEstimate.initialStored A) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let x : CountingAdaptiveInputProgram.Input := + ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),bits) + have hp := CountingAdaptiveInputProgram.prepared_data hEK r c b hne epsilon he bits + have hc : CountingPreparedState.catalog x.1=RootedForestCatalog.data A := + CountingComputedSettings.catalog_data hEK r c b hne epsilon he + have hw : CountingAdaptiveInputProgram.labelWidth x=2*Fintype.card (Labels A) := by + unfold CountingAdaptiveInputProgram.labelWidth + rw [CountingComputedSettings.labelCount_data hEK r c b hne epsilon he] + exact CountingAdaptiveInputProgram.initial_view x A s.C s.K s.H + (CompanionTargetMixing.restartTime A s.H s.L) s.N s.n s.L + (CountingBaseProgram.half (TreeFraction.repr epsilon)) (fun _ => 0) + (CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he)) + hp hc hw hlen + +theorem output_ofFn (req : Request) (bits : Fin (bitCount req)→Bool) : + output (req,List.ofFn bits)= + (CompanionOuterHistoryProgram.output + (start (req,List.ofFn bits),List.ofFn (fun i : Fin (phaseCount req) => + List.ofFn (fun j : Fin (phaseWidth req) => bits (finProdFinEquiv (i,j)))))).2 := by + unfold output finalStored historyInput + rw [words_ofFn] + +theorem phases_pos (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + 0 < (ComputedCountingParameters.settings hEK r c b hne epsilon he).H := by + have hC := ComputedCountingParameters.coefficient_pos r c b epsilon he + have hd : 0 < ComputedCountingParameters.dimensionAllowance (m := m) (n := n) := by + unfold ComputedCountingParameters.dimensionAllowance + omega + change 0 < ComputedCountingParameters.phases r c b epsilon + unfold ComputedCountingParameters.phases + positivity + +theorem phaseWidth_covers (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : TreeFraction.Fraction) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let W := phaseWidth ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta) + RootedPhaseHistory.totalWidth A s ≤ W ∧ + (∀ j,j ≤ s.H → + PowerOfTwoApproximation.rootDegree + (CompanionOracleDensity.roundingTolerance (CompanionOracleDensity.innerTolerance (s.xi/2) j))+ + PowerOfTwoApproximation.depth + (CompanionOracleDensity.roundingTolerance (CompanionOracleDensity.innerTolerance (s.xi/2) j)) ≤ W) ∧ + 2*Fintype.card (Labels A) ≤ W := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let e := CountingBaseProgram.half (TreeFraction.repr epsilon) + let v := CountingPreparedState.start A s.K + (ComputedCountingParameters.binCount_pos r c b epsilon he) + have hk := CountingComputedSettings.precision_data hEK r c b hne epsilon he + rw [CountingComputedSettings.parameters_data hEK r c b hne epsilon he] at hk + have hp : 0 < s.k := CountingPhaseSchedule.precision_pos _ _ _ _ _ + have hc := CompanionUniformPhaseWidth.width_covers A s e (fun _ => 0) v hk + (show s.h=CountingPhaseSchedule.initialPrecision s.H from rfl) + (show s.xi=1/(s.k:ℚ) from rfl) hp + (phases_pos hEK r c b hne epsilon he) (le_refl _) + have hw := congrArg CompanionUniformPhaseWidth.width + (prepared_data hEK r c b hne epsilon he delta) + change phaseWidth ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta)= + CompanionUniformPhaseWidth.width (CompanionUniformPhaseWidth.data A s e (fun _ => 0) v) at hw + dsimp only + rw [hw] + exact hc + +theorem initialReserve_le (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) + (delta : TreeFraction.Fraction) : + 2*Fintype.card (Labels (ComputedCountingParameters.data hEK r c b hne epsilon he)) ≤ + bitCount ((NetworkVertexCode.data r c b,TreeFraction.repr epsilon),delta) := by + have hc := (phaseWidth_covers hEK r c b hne epsilon he delta).2.2 + have hH := phases_pos hEK r c b hne epsilon he + unfold bitCount + rw [phaseCount_data hEK r c b hne epsilon he delta] + exact hc.trans (by simpa only [Nat.one_mul] using Nat.mul_le_mul_right _ hH) + +end +end ContingencyTables.CountingPositiveProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveWordBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveWordBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..d89ab163181b0c290029b905a3dd3c06d1b3ce34 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveWordBound.lean @@ -0,0 +1,136 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveSemantics +import OAI.Combinatorics.ContingencyTables.Counting.CountingAmplifiedLaw +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchBudgetBound + +namespace OAI + +/-! # Public polynomial bounds for the executed positive counting words -/ +namespace ContingencyTables.CountingPositiveWordBound +open MatchingFPRAS MatchingFPRAS.TreeTyped CompanionFactorialApplication CountingPublicInputBounds Polynomial +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def measurePolynomial : Polynomial ℕ := 13*CountingPublicWordBound.controlPolynomial+1 +def widthPolynomial : Polynomial ℕ := + CountingWordsBound.wordPolynomial+CountingMarkerBounds.paddingPolynomial+2*X+1 +def singlePolynomial : Polynomial ℕ := + CountingPublicWordBound.controlPolynomial*(widthPolynomial.comp measurePolynomial) +def amplifiedPolynomial : Polynomial ℕ := CountingAmplifiedProgram.budgetPolynomial singlePolynomial + +private lemma control_parts (S : ℕ) : + let M := CountingPublicWordBound.controlPolynomial.eval S + CountingPublicControls.inputPolynomial.eval S ≤ M ∧ + CountingPublicControls.observationPolynomial.eval S ≤ M ∧ + CountingPublicControls.returnPolynomial.eval S ≤ M ∧ + CountingPublicControls.precisionPolynomial.eval S ≤ M ∧ + CountingTerminalBounds.gridPolynomial.eval S ≤ M ∧ + 2048*(CountingTerminalBounds.phasePolynomial.eval S+1) ≤ M ∧ S ≤ M := by + simp only [CountingPublicWordBound.controlPolynomial,eval_add,eval_mul,eval_ofNat,eval_one,eval_X] + omega + +lemma phaseCount_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + CountingPositiveProgram.phaseCount (CountingDirectProgram.request r c b epsilon delta) ≤ + CountingPublicWordBound.controlPolynomial.eval (size r c b epsilon delta) := by + rw [CountingDirectProgram.request,CountingPositiveProgram.phaseCount_data hEK r c b hne epsilon he] + change ComputedCountingParameters.phases r c b epsilon ≤ _ + have hs := CountingPublicControls.scalar_bound hEK r c b hne epsilon delta he + exact (hs _ (by simp only [List.mem_cons,eq_self,true_or,or_true])).trans + (control_parts (size r c b epsilon delta)).1 + +lemma measure_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + CompanionUniformPhaseWidth.measure + (CountingPositiveProgram.prepared (CountingDirectProgram.request r c b epsilon delta)) ≤ + measurePolynomial.eval (size r c b epsilon delta) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let S := size r c b epsilon delta + let M := CountingPublicWordBound.controlPolynomial.eval S + have hparts := control_parts S + have hs : ∀ x∈[Fintype.card (Labels A),A.W,s.H, + CompanionTargetMixing.restartTime A s.H s.L,s.L], + x ≤ CountingPublicControls.inputPolynomial.eval S := + CountingPublicControls.scalar_bound hEK r c b hne epsilon delta he + have hp : Fintype.card (Labels A) ≤ M := + (hs _ (by simp only [List.mem_cons,eq_self,true_or])).trans hparts.1 + have hW : A.W ≤ M := + (hs _ (by simp only [List.mem_cons,eq_self,true_or,or_true])).trans hparts.1 + have hH : s.H ≤ M := + (hs _ (by simp only [List.mem_cons,eq_self,true_or,or_true])).trans hparts.1 + have hT : CompanionTargetMixing.restartTime A s.H s.L ≤ M := + (hs _ (by simp only [List.mem_cons,eq_self,true_or,or_true])).trans hparts.1 + have hL : s.L ≤ M := + (hs _ (by simp only [List.mem_cons,eq_self,true_or,or_true])).trans hparts.1 + have hc := CountingPublicControls.settings_bounds hEK r c b hne epsilon delta he + have hN : s.N ≤ M := hc.1.trans hparts.2.1 + have hn : s.n ≤ M := hc.2.1.trans hparts.2.2.1 + have hk : s.k ≤ M := hc.2.2.trans hparts.2.2.2.1 + have ht := CountingPublicTerminalBounds.terminal_public hEK r c b hne epsilon delta he + have hK : s.K ≤ M := ht.1.trans hparts.2.2.2.2.1 + have hh : s.h ≤ M := + (Nat.mul_le_mul_left 2048 (Nat.add_le_add_right ht.2.2 1)).trans hparts.2.2.2.2.2.1 + have hd : A.d ≤ M := (dimension_le r c b epsilon delta).trans hparts.2.2.2.2.2.2 + have hheight : CompanionOracleDensity.rationalHeight A s.C ≤ M := hH + have hkdata := CountingComputedSettings.precision_data hEK r c b hne epsilon he + rw [CountingComputedSettings.parameters_data hEK r c b hne epsilon he] at hkdata + have hf := CompanionUniformPhaseWidth.fields_data A s + (CountingBaseProgram.half (TreeFraction.repr epsilon)) (fun _ => 0) + (CountingPreparedState.start A s.K (ComputedCountingParameters.binCount_pos r c b epsilon he)) + hkdata (show s.h=CountingPhaseSchedule.initialPrecision s.H from rfl) + rw [CountingDirectProgram.request,CountingPositiveProgram.prepared_data hEK r c b hne epsilon he] + unfold CompanionUniformPhaseWidth.measure + rw [hf] + simp only [List.sum_cons,List.sum_nil,measurePolynomial,eval_add,eval_mul,eval_ofNat,eval_one] + dsimp only [M,S] at hp hW hH hT hL hN hn hk hK hh hd hheight + omega + +lemma width_value (req : CountingDirectProgram.Request) : + CountingPositiveProgram.phaseWidth req=widthPolynomial.eval + (CompanionUniformPhaseWidth.measure (CountingPositiveProgram.prepared req)) := by + simp only [CountingPositiveProgram.phaseWidth,CompanionUniformPhaseWidth.width_value, + widthPolynomial,eval_add,eval_mul,eval_ofNat,eval_X,eval_one] + +theorem single_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + CountingPositiveProgram.bitCount (CountingDirectProgram.request r c b epsilon delta) ≤ + singlePolynomial.eval (size r c b epsilon delta) := by + have hH := phaseCount_public hEK r c b hne epsilon delta he + have hM := measure_public hEK r c b hne epsilon delta he + have hW := polynomial_eval_monotone widthPolynomial hM + dsimp only at hW + rw [←width_value] at hW + simpa only [CountingPositiveProgram.bitCount,singlePolynomial,eval_mul,eval_comp] using + Nat.mul_le_mul hH hW + +theorem amplified_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) + (he : 0 < epsilon) (hd : 0 < delta) : + CountingAmplifiedProgram.budget CountingPositiveProgram.bitCount + (CountingDirectProgram.request r c b epsilon delta) ≤ + amplifiedPolynomial.eval (size r c b epsilon delta) := + CountingAmplifiedProgram.budget_bound CountingPositiveProgram.bitCount singlePolynomial + r c b epsilon delta hd (single_public hEK r c b hne epsilon delta he) + +theorem branch_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (m n : ℕ) (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (he : 0 < epsilon) (hd : 0 < delta) : + CountingBranchProgram.publicBudget + (CountingAmplifiedProgram.budget CountingPositiveProgram.bitCount) + (Algorithms.encodeCountingInput r c b epsilon delta) ≤ + (CountingBranchProgram.budgetPolynomial amplifiedPolynomial).eval + (size r c b epsilon delta) := by + exact CountingBranchProgram.publicBudget_bound hEK + (CountingAmplifiedProgram.budget CountingPositiveProgram.bitCount) amplifiedPolynomial + (fun _ _ r c b hne epsilon delta he hd => amplified_public hEK r c b hne epsilon delta he hd) + m n r c b epsilon delta he hd + +end +end ContingencyTables.CountingPositiveWordBound + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveWordLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveWordLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..faa39e6a0f951b4d3b588e1fc473218ce8a5530f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPositiveWordLaw.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveSemantics +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport + +namespace OAI + +/-! # Flattening the positive run while preserving its complete output law -/ +namespace ContingencyTables.CountingPositiveProgram +open MatchingFPRAS CommonBasesFPRAS GridBoundary FiniteObservableTransport +open scoped Classical +noncomputable section + +def independentOutput (req : Request) + (words : Fin (phaseCount req)→Fin (phaseWidth req)→Bool) : TreeFraction.Fraction := + (CompanionOuterHistoryProgram.output + (start (req,List.replicate (bitCount req) false), + List.ofFn (fun i => List.ofFn (words i)))).2 + +theorem output_sameLaw (req : Request) : + SameLaw (fun bits : Fin (bitCount req)→Bool => output (req,List.ofFn bits)) + (independentOutput req) := by + intro phi + have he := uniformAverage_equiv (gridWordEquiv (phaseCount req) (phaseWidth req)) + (fun words => phi (independentOutput req words)) + have hp : (fun bits : Fin (bitCount req)→Bool => phi (output (req,List.ofFn bits)))= + (fun bits => phi (independentOutput req + (gridWordEquiv (phaseCount req) (phaseWidth req) bits))) := by + funext bits + rw [output_ofFn,start_ofFn] + rfl + rw [hp] + exact he + +theorem value_sameLaw (req : Request) : + SameLaw (fun bits : Fin (bitCount req)→Bool => TreeFraction.val (output (req,List.ofFn bits))) + (fun words => TreeFraction.val (independentOutput req words)) := + (output_sameLaw req).map TreeFraction.val + +end +end ContingencyTables.CountingPositiveProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPreparedState.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPreparedState.lean new file mode 100644 index 0000000000000000000000000000000000000000..4851e4fe4188e5023069e12a745b0c717b50c4a1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPreparedState.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingSettingsCorrect +import OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleWalkProgram + +namespace OAI + +/-! # Constructing the immutable rooted state from the public bounded input -/ + +namespace ContingencyTables.CountingPreparedState +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms +abbrev Input := CountingBaseProgram.Input + +def catalog (z : Input) : RootedForestCatalog.Data := CountingComputedSettings.catalog z +def catalogRealizer : Realizer catalog := CountingComputedSettings.catalogRealizer +lemma polynomial_catalog : PolynomialTime catalogRealizer := CountingComputedSettings.polynomial_catalog + +def baseline (z : Input) : MatrixCode := TightenedInputProgram.baseline z.1 +def baselineRealizer : Realizer baseline := + composition (f := fun z : Input => z.1) (g := TightenedInputProgram.baseline) + first TightenedInputProgram.baselineRealizer +lemma polynomial_baseline : PolynomialTime baselineRealizer := + polynomial_composition polynomial_first TightenedInputProgram.polynomial_baseline + +def capacity (z : Input) : MatrixCode := (catalog z).2 +def capacityRealizer : Realizer capacity := composition catalogRealizer second +lemma polynomial_capacity : PolynomialTime capacityRealizer := polynomial_composition polynomial_catalog polynomial_second + +def zeroMatrix (z : Input) : MatrixCode := (capacity z).map (fun row => row.map (fun _ => 0)) +def zeroMatrixRealizer : Realizer zeroMatrix := + composition capacityRealizer (map (map (constant 0))) +lemma polynomial_zeroMatrix : PolynomialTime zeroMatrixRealizer := + polynomial_composition polynomial_capacity (polynomial_map (polynomial_map (polynomial_constant 0))) + +def demand (z : Input) : RootedDemandProgram.Input := + (catalog z,(baseline z,(zeroMatrix z,capacity z))) +def demandRealizer : Realizer demand := pair catalogRealizer (pair baselineRealizer (pair zeroMatrixRealizer capacityRealizer)) +lemma polynomial_demand : PolynomialTime demandRealizer := + polynomial_pair polynomial_catalog (polynomial_pair polynomial_baseline + (polynomial_pair polynomial_zeroMatrix polynomial_capacity)) + +def parameters (z : Input) : RootedPenaltyEvaluateProgram.Parameters := + ((CountingBaseProgram.dimension z.1,CountingTerminalProgram.cutoff z),(CountingBaseProgram.coefficient z,0)) +def parametersRealizer : Realizer parameters := + pair (pair (composition (f := fun z : Input => z.1) (g := CountingBaseProgram.dimension) + first CountingBaseProgram.dimensionRealizer) CountingTerminalProgram.cutoffRealizer) + (pair CountingBaseProgram.coefficientRealizer (constant 0)) +lemma polynomial_parameters : PolynomialTime parametersRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first CountingBaseProgram.polynomial_dimension) + CountingTerminalProgram.polynomial_cutoff) (polynomial_pair CountingBaseProgram.polynomial_coefficient + (polynomial_constant 0)) + +def zeroGrid (z : Input) : List ℕ := (RootedForestCatalog.catalog (catalog z,false)).map (fun _ => 0) +def zeroGridRealizer : Realizer zeroGrid := + composition (composition (f := fun z : Input => (catalog z,false)) (g := RootedForestCatalog.catalog) + (pair catalogRealizer (constant false)) RootedForestCatalog.catalogRealizer) (map (constant 0)) +lemma polynomial_zeroGrid : PolynomialTime zeroGridRealizer := + polynomial_composition (polynomial_composition (polynomial_pair polynomial_catalog (polynomial_constant false)) + RootedForestCatalog.polynomial_catalog) (polynomial_map (polynomial_constant 0)) + +def state (z : Input) : RootedOracleWalkProgram.State := + ((CountingTerminalProgram.binCount z,(parameters z,demand z)),zeroGrid z) +def stateRealizer : Realizer state := + pair (pair CountingTerminalProgram.binCountRealizer (pair parametersRealizer demandRealizer)) zeroGridRealizer +lemma polynomial_state : PolynomialTime stateRealizer := + polynomial_pair (polynomial_pair CountingTerminalProgram.polynomial_binCount + (polynomial_pair polynomial_parameters polynomial_demand)) polynomial_zeroGrid + +def output (z : Input) : RootedOracleWalkProgram.State×CountingPhaseParametersProgram.Input := + (state z,CountingComputedSettings.parameters z) +def outputRealizer : Realizer output := pair stateRealizer CountingComputedSettings.parametersRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_pair polynomial_state CountingComputedSettings.polynomial_parameters + +open CompanionFactorialApplication ForestAssignmentSplit +open scoped Classical +variable {m n : ℕ} + +lemma demand_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + demand (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + RootedDemandProgram.data (ComputedCountingParameters.data hEK r c b hne epsilon he) + (fun _ _ => 0) (ComputedCountingParameters.data hEK r c b hne epsilon he).b := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + have hc : catalog (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)=RootedForestCatalog.data A := + CountingComputedSettings.catalog_data hEK r c b hne epsilon he + have hb : baseline (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + matrixCode (fun i j => (A.X i j).toNat) := by + exact ComputedRootedInput.baseline_instance hEK r c b hne _ (ComputedCountingParameters.cutoff_two r c b epsilon he) + have hcap : capacity (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)=matrixCode A.b := by + rw [capacity,hc] + rfl + have hz : zeroMatrix (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)=matrixCode (fun (_ : Fin m) (_ : Fin n) => 0) := by + rw [zeroMatrix,hcap] + simp only [matrixCode,List.map_ofFn,Function.comp_def] + unfold demand RootedDemandProgram.data + rw [hc,hb,hz,hcap] + +noncomputable def start (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 < K) : + GridBoundary.Grid (I := Fin (RootedCatalogGrid.freeCount A)) K := + fun _ => ⟨0,le_rfl,by omega⟩ + +lemma state_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let C := ComputedCountingParameters.coefficient r c b epsilon + let K := ComputedCountingParameters.binCount r c b epsilon + state (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + RootedOracleWalkProgram.data A C 0 K (fun _ => 0) + (start A K (ComputedCountingParameters.binCount_pos r c b epsilon he)) := by + dsimp only + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + have hp : parameters (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + ((A.d,A.W),(ComputedCountingParameters.coefficient r c b epsilon,0)) := by + unfold parameters + rw [CountingBaseProgram.dimension_data,CountingTerminalProgram.cutoff_data r c b epsilon he, + CountingBaseProgram.coefficient_data r c b epsilon he] + rfl + have hz : ForestCountIdentification.smallX A.small (fun _ => 0)=(fun _ _ => 0) := by + funext i j + simp [ForestCountIdentification.smallX] + have hq : (fun i j => A.b i j-ForestCountIdentification.smallY A.small (fun _ => 0) i j)=A.b := by + funext i j + simp [ForestCountIdentification.smallY] + unfold state RootedOracleWalkProgram.data + rw [CountingTerminalProgram.binCount_data r c b epsilon he,hp,hz,hq,demand_data hEK r c b hne epsilon he] + apply congrArg (fun coords => ((ComputedCountingParameters.binCount r c b epsilon, + (((A.d,A.W),(ComputedCountingParameters.coefficient r c b epsilon,0)), + RootedDemandProgram.data A (fun _ _ => 0) A.b)),coords)) + unfold zeroGrid catalog + rw [CountingComputedSettings.catalog_data hEK r c b hne epsilon he] + simp [DensePrograms.gridNatCode,start,GridBoundary.corner,RootedCatalogGrid.freeCount] + +lemma start_transport (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let K := ComputedCountingParameters.binCount r c b epsilon + RootedCatalogGrid.gridEquiv A K + (start A K (ComputedCountingParameters.binCount_pos r c b epsilon he))= + ComputedCountingParameters.start hEK r c b hne epsilon he := by + rfl + +end ContingencyTables.CountingPreparedState + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicAccuracy.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicAccuracy.lean new file mode 100644 index 0000000000000000000000000000000000000000..ed956fa020b64d065f0513f2a1befb86cd5bcd9d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicAccuracy.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingExecutedMachine +import OAI.Combinatorics.ContingencyTables.Counting.CountingBranchSuccess +import OAI.Combinatorics.ContingencyTables.Counting.CountingMachineMainEvent + +namespace OAI + +/-! # Transporting the concrete counting accuracy event to public machine tapes -/ +namespace ContingencyTables.CountingExecutedMachine +open MatchingFPRAS MatchingFPRAS.PhysicalStream CommonBasesFPRAS CompanionFactorialApplication GridBoundary +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma accurate_iff (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (epsilon q : ℚ) : + ((1-epsilon)*(Algorithms.count r c b:ℚ)≤q ∧ + q≤(1+epsilon)*(Algorithms.count r c b:ℚ)) ↔ + CountingBranchProgram.Accurate r c b epsilon q := by + unfold CountingBranchProgram.Accurate Algorithms.count + constructor <;> rintro ⟨hl,hu⟩ <;> constructor + · exact_mod_cast hl + · exact_mod_cast hu + · exact_mod_cast hl + · exact_mod_cast hu + +attribute [local irreducible] CountingPositiveProgram.output CountingAmplifiedProgram.output + CountingBranchProgram.output CountingBranchProgram.publicOutput CountingBranchProgram.machine + CountingExecutedMachine.machine + +theorem public_success (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (hPL : ∀ q,PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : ∀ q k,PublishedInputs.FiniteCheeger (Grid (I := Fin q) k)) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) (he : 0 + if CountingBranchProgram.Accurate r c b epsilon (TreeFraction.val (positive + (CountingDirectProgram.request r c b epsilon delta,List.ofFn bits))) then (1:ℝ) else 0)) + (t : ℕ) (ht : machineTime (Algorithms.encodeCountingInput r c b epsilon delta)≤t) : + 1-delta ≤ ((Algorithms.goodCountingTapes machine r c b epsilon delta t).card:ℚ)/(2:ℚ)^t := by + let P := fun q : ℚ => (1-epsilon)*(Algorithms.count r c b:ℚ)≤q ∧ + q≤(1+epsilon)*(Algorithms.count r c b:ℚ) + have hraw := CountingBranchProgram.success hEK hPL hCheeger positive positiveWidth + r c b epsilon delta he he1 hd hpositive + have hs : 1-(delta:ℝ) ≤ uniformAverage + (fun bits : Bits (wordCount (Algorithms.encodeCountingInput r c b epsilon delta)) => + if P (sourceValue (Algorithms.encodeCountingInput r c b epsilon delta) bits) then (1:ℝ) else 0) := by + simp only [P,accurate_iff,sourceValue,CountingBranchProgram.sourceValue, + CountingBranchProgram.parsedInput_public] + unfold wordCount CountingBranchProgram.publicBudget + rw [CountingInputParser.public_spec] + exact hraw + rw [show machine=FiniteWordExecution.machine + (CountingBranchProgram.publicBudgetRealizer positiveWidth positiveWidthRealizer) + (CountingBranchProgram.publicOutputRealizer positive positiveRealizer) from by + unfold machine CountingBranchProgram.machine; rfl] + exact CountingMachineEvents.goodTapes_success + (CountingBranchProgram.publicBudgetRealizer positiveWidth positiveWidthRealizer) + (CountingBranchProgram.publicOutputRealizer positive positiveRealizer) + r c b epsilon delta + (fun bs a ha => (CountingBranchProgram.publicOutput_symbols positive _ a ha).2) + (sourceValue (Algorithms.encodeCountingInput r c b epsilon delta)) + (CountingBranchProgram.sourceValue_output positive positiveWidth _) + hs t ht + +end +end ContingencyTables.CountingExecutedMachine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicControls.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicControls.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b4a2e9cfae0f97b670ffecb37a404b1631be2c8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicControls.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPublicTerminalBounds +import OAI.Combinatorics.ContingencyTables.Counting.CountingControlBounds + +namespace OAI + +/-! # All dynamic scalar controls are polynomial in the public input -/ + +namespace ContingencyTables.CountingPublicControls +open CountingPublicInputBounds CountingPublicTerminalBounds CountingControlBounds +open CompanionFactorialApplication Polynomial +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def inputPolynomial : Polynomial ℕ := basicPolynomial+restartPolynomial+X +def observationPolynomial : Polynomial ℕ := CountingControlBounds.observationPolynomial.comp inputPolynomial +def returnPolynomial : Polynomial ℕ := CountingControlBounds.returnPolynomial.comp inputPolynomial +def precisionPolynomial : Polynomial ℕ := CountingControlBounds.precisionPolynomial.comp inputPolynomial + +lemma scalar_bound (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let H := ComputedCountingParameters.phases r c b epsilon + let L := ComputedCountingParameters.capacityBits r c b + ∀ x∈[Fintype.card (Labels A),A.W,H,CompanionTargetMixing.restartTime A H L,L], + x ≤ inputPolynomial.eval (size r c b epsilon delta) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let H := ComputedCountingParameters.phases r c b epsilon + let L := ComputedCountingParameters.capacityBits r c b + have hs : ∀ x∈[Fintype.card (Labels A),A.W,H,0,0,0,L], + x ≤ basicPolynomial.eval (size r c b epsilon delta) := + scalar_public hEK r c b hne epsilon delta he + have ht := restart_public hEK r c b hne epsilon delta he + have hp := hs (Fintype.card (Labels A)) (by simp only [List.mem_cons, eq_self, true_or]) + have hw := hs A.W (by simp only [List.mem_cons, eq_self, true_or, or_true]) + have hh := hs H (by simp only [List.mem_cons, eq_self, true_or, or_true]) + have hl := hs L (by simp only [List.mem_cons, eq_self, true_or, or_true]) + change ∀ x∈[Fintype.card (Labels A),A.W,H,CompanionTargetMixing.restartTime A H L,L], + x ≤ inputPolynomial.eval (size r c b epsilon delta) + intro x hx + simp only [List.mem_cons,List.not_mem_nil,or_false] at hx + simp only [inputPolynomial,Polynomial.eval_add,Polynomial.eval_X] + change CompanionTargetMixing.restartTime A H L ≤ _ at ht + omega + +lemma settings_bounds (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + s.N ≤ observationPolynomial.eval (size r c b epsilon delta) ∧ + s.n ≤ returnPolynomial.eval (size r c b epsilon delta) ∧ + s.k ≤ precisionPolynomial.eval (size r c b epsilon delta) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let H := ComputedCountingParameters.phases r c b epsilon + let L := ComputedCountingParameters.capacityBits r c b + let T := CompanionTargetMixing.restartTime A H L + let M := inputPolynomial.eval (size r c b epsilon delta) + have hs : ∀ x∈[Fintype.card (Labels A),A.W,H,T,L],x ≤ M := + scalar_bound hEK r c b hne epsilon delta he + have hp : Fintype.card (Labels A) ≤ M := hs _ (by simp only [List.mem_cons,eq_self,true_or]) + have hw : A.W ≤ M := hs _ (by simp only [List.mem_cons,eq_self,true_or,or_true]) + have hh : H ≤ M := hs _ (by simp only [List.mem_cons,eq_self,true_or,or_true]) + have ht : T ≤ M := hs _ (by simp only [List.mem_cons,eq_self,true_or,or_true]) + have hSM : size r c b epsilon delta ≤ M := by + dsimp only [M] + simp only [inputPolynomial,Polynomial.eval_add,Polynomial.eval_X] + omega + have hi : 1/epsilon ≤ (M:ℚ) := (inverse_le r c b epsilon delta).trans (by exact_mod_cast hSM) + refine ⟨?_,?_,?_⟩ + · change CountingPhaseSchedule.observations (Fintype.card (Labels A)) A.W H + (CountingPhaseSchedule.tolerance H (epsilon/2)) ≤ _ + simpa only [observationPolynomial,Polynomial.eval_comp,M] using + observations_bound _ _ _ M epsilon he hp hw hh hi + · change CountingPhaseSchedule.returnCap (Fintype.card (Labels A)) H T ≤ _ + simpa only [returnPolynomial,Polynomial.eval_comp,M] using return_bound _ _ _ M hp hh ht + · change CountingPhaseSchedule.precision H T + (CountingPhaseSchedule.observations (Fintype.card (Labels A)) A.W H + (CountingPhaseSchedule.tolerance H (epsilon/2))) + (CountingPhaseSchedule.returnCap (Fintype.card (Labels A)) H T) + (CountingPhaseSchedule.tolerance H (epsilon/2)) ≤ _ + simpa only [precisionPolynomial,Polynomial.eval_comp,M] using + precision_bound _ _ _ _ M epsilon he hp hw hh ht hi + +end +end ContingencyTables.CountingPublicControls + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicInputBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicInputBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..63846092e200c2328bb3353a1c99fde5a2fc127f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicInputBounds.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalBounds +import OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingParameters +import OAI.Combinatorics.ContingencyTables.AlgorithmStatements + +namespace OAI + +/-! # Bounding counting parameters by the public binary input -/ + +namespace ContingencyTables.CountingPublicInputBounds +open MatchingFPRAS Algorithms +open scoped BigOperators +noncomputable section + +def size {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon delta : ℚ) : ℕ := + (encodeCountingInput r c b epsilon delta).length+⌈epsilon⁻¹⌉₊+Nat.clog 2 ⌈delta⁻¹⌉₊+1 + +lemma nat_length (x : ℕ) : (encodeNat x).length=x.size+1 := by + simp only [encodeNat,List.length_append,List.length_map,List.length_singleton,Nat.size_eq_bits_len] + +lemma successor_size (x : ℕ) : (x+1).size ≤ x.size+1 := by + apply Nat.size_le.mpr + have h := Nat.lt_size_self x + have hp : 0 < 2^x.size := by positivity + rw [pow_succ] + omega + +lemma matrix_length {m n : ℕ} (b : Fin m→Fin n→ℕ) : + (encodeMatrix b).length=∑ a : Fin m×Fin n,((b a.1 a.2).size+1) := by + simp [encodeMatrix,List.length_flatten,List.map_ofFn,List.sum_ofFn,nat_length, + Fintype.sum_prod_type,Function.comp_def] + +lemma cells_le_matrix_length {m n : ℕ} (b : Fin m→Fin n→ℕ) : + m*n ≤ (encodeMatrix b).length := by + rw [matrix_length] + calc + m*n = ∑ _a : Fin m×Fin n,1 := by simp + _ ≤ _ := Finset.sum_le_sum (fun _ _ => by omega) + +lemma matrix_le_input {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) + (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + (encodeMatrix b).length ≤ (encodeCountingInput r c b epsilon delta).length := by + simp only [encodeCountingInput,List.length_append] + omega + +lemma dimension_le {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) + (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + ComputedCountingParameters.dimensionAllowance (m:=m) (n:=n) ≤ size r c b epsilon delta := by + have hc := (cells_le_matrix_length b).trans (matrix_le_input r c b epsilon delta) + unfold ComputedCountingParameters.dimensionAllowance size + omega + +lemma capacityBits_le {m n : ℕ} (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) : + ComputedCountingParameters.capacityBits r c b ≤ size r c b epsilon delta := by + have hb : ComputedCountingParameters.capacityBits r c b ≤ (encodeMatrix b).length := by + rw [ComputedCountingParameters.capacityBits,matrix_length] + apply Finset.sum_le_sum + intro a _ + have hu := ComputedTableTightening.upper_le_bound hEK r c b hne a.1 a.2 + have hn : ComputedTableTightening.newBounds r c b a.1 a.2 ≤ b a.1 a.2 := by + exact (Nat.sub_le _ _).trans hu + exact (Nat.size_le_size (Nat.add_le_add_right hn 1)).trans (successor_size _) + have hi := hb.trans (matrix_le_input r c b epsilon delta) + unfold size + omega + +lemma inverse_le {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) + (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + 1/epsilon ≤ (size r c b epsilon delta:ℚ) := by + have hc := Nat.le_ceil (epsilon⁻¹) + have hn : ⌈epsilon⁻¹⌉₊ ≤ size r c b epsilon delta := by unfold size; omega + have hc' : 1/epsilon ≤ (⌈epsilon⁻¹⌉₊:ℚ) := by simpa only [one_div] using hc + exact hc'.trans (by exact_mod_cast hn) + +lemma repeats_le {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) + (b : Fin m→Fin n→ℕ) (epsilon delta : ℚ) : + 64*(delta.den.bits.length+1) ≤ 64*size r c b epsilon delta := by + have hd : delta.den.bits.length+1 ≤ (encodeCountingInput r c b epsilon delta).length := by + simp only [encodeCountingInput,encodeRat,List.length_append,nat_length,Nat.size_eq_bits_len] + omega + exact Nat.mul_le_mul_left 64 (hd.trans (by unfold size; omega)) + +end +end ContingencyTables.CountingPublicInputBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicTerminalBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicTerminalBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d69e58e8fd8806d783f928cc9ec9476a6750ca9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicTerminalBounds.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPublicInputBounds +import OAI.Combinatorics.ContingencyTables.Counting.CountingLabelCountProgram +import OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseScalarProgram +import OAI.Combinatorics.ContingencyTables.Machines.ScalarScheduleBounds + +namespace OAI + +/-! # Public polynomial bounds for the terminal grid and phase controls -/ + +namespace ContingencyTables.CountingPublicTerminalBounds +open CountingTerminalBounds CountingPublicInputBounds CompanionFactorialApplication +open ScalarScheduleProgram Polynomial +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma coefficient_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + ComputedCountingParameters.coefficient r c b epsilon ≤ + coefficientPolynomial.eval (size r c b epsilon delta) := + coefficient_bound _ _ (size r c b epsilon delta) _ epsilon he (inverse_le r c b epsilon delta) + (capacityBits_le hEK r c b hne epsilon delta) (dimension_le r c b epsilon delta) (le_refl _) + +lemma terminal_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + ComputedCountingParameters.binCount r c b epsilon ≤ gridPolynomial.eval (size r c b epsilon delta) ∧ + ComputedCountingParameters.cutoff r c b epsilon ≤ cutoffPolynomial.eval (size r c b epsilon delta) ∧ + ComputedCountingParameters.phases r c b epsilon ≤ phasePolynomial.eval (size r c b epsilon delta) := + terminal_bounds _ _ _ _ _ (coefficient_public hEK r c b hne epsilon delta he) + (dimension_le r c b epsilon delta) rfl rfl + +lemma label_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + Fintype.card (Labels (ComputedCountingParameters.data hEK r c b hne epsilon he)) ≤ + (size r c b epsilon delta)*cutoffPolynomial.eval (size r c b epsilon delta) := by + have hl := CountingLabelCountProgram.count_bound (ComputedCountingParameters.data hEK r c b hne epsilon he) + exact hl.trans (Nat.mul_le_mul (dimension_le r c b epsilon delta) + (terminal_public hEK r c b hne epsilon delta he).2.1) + +def basicPolynomial : Polynomial ℕ := X*cutoffPolynomial+cutoffPolynomial+phasePolynomial+X+1 + +def restartPolynomial : Polynomial ℕ := CountingPhaseScalarProgram.restartTime.bound.comp basicPolynomial + +lemma scalar_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let H := ComputedCountingParameters.phases r c b epsilon + let L := ComputedCountingParameters.capacityBits r c b + ∀ x∈[Fintype.card (Labels A),A.W,H,0,0,0,L], + x ≤ basicPolynomial.eval (size r c b epsilon delta) := by + dsimp only + have hp := label_public hEK r c b hne epsilon delta he + have hw := (terminal_public hEK r c b hne epsilon delta he).2.1 + have hh := (terminal_public hEK r c b hne epsilon delta he).2.2 + have hl := capacityBits_le hEK r c b hne epsilon delta + intro x hx + simp only [List.mem_cons,List.not_mem_nil,or_false] at hx + simp only [basicPolynomial,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one] + change x=Fintype.card (Labels (ComputedCountingParameters.data hEK r c b hne epsilon he)) ∨ + x=ComputedCountingParameters.cutoff r c b epsilon ∨ + x=ComputedCountingParameters.phases r c b epsilon ∨ x=0 ∨ x=0 ∨ x=0 ∨ + x=ComputedCountingParameters.capacityBits r c b at hx + omega + +lemma restart_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + CompanionTargetMixing.restartTime A (ComputedCountingParameters.phases r c b epsilon) + (ComputedCountingParameters.capacityBits r c b) ≤ restartPolynomial.eval (size r c b epsilon delta) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let H := ComputedCountingParameters.phases r c b epsilon + let L := ComputedCountingParameters.capacityBits r c b + have hb := CountingPhaseScalarProgram.restartTime.eval_le_of_mem + [Fintype.card (Labels A),A.W,H,0,0,0,L] + (basicPolynomial.eval (size r c b epsilon delta)) + (scalar_public hEK r c b hne epsilon delta he) + rw [CountingPhaseScalarProgram.restartTime_instance A H L 0 0 0] at hb + simpa only [restartPolynomial,Polynomial.eval_comp] using hb + +end +end ContingencyTables.CountingPublicTerminalBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicWordBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicWordBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..14c800eb169218cab10b2102d82c428b433ec141 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingPublicWordBound.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPublicControls +import OAI.Combinatorics.ContingencyTables.Counting.CountingWordsBound + +namespace OAI + +/-! # The complete counting word is polynomial in the original input -/ + +namespace ContingencyTables.CountingPublicWordBound +open CompanionFactorialApplication CountingPublicInputBounds Polynomial +open scoped Classical +noncomputable section +variable {m n : ℕ} + +def controlPolynomial : Polynomial ℕ := + CountingPublicControls.inputPolynomial+CountingPublicControls.observationPolynomial+ + CountingPublicControls.returnPolynomial+CountingPublicControls.precisionPolynomial+ + CountingTerminalBounds.gridPolynomial+2048*(CountingTerminalBounds.phasePolynomial+1)+X+1 + +def wordPolynomial : Polynomial ℕ := CountingWordsBound.wordPolynomial.comp controlPolynomial + +def amplifiedPolynomial : Polynomial ℕ := 64*X*wordPolynomial + +lemma reciprocal_controls (k M : ℕ) (hk : 0 < k) (hM : k ≤ M) : + 0 < (1/(k:ℚ)) ∧ 1/(1/(k:ℚ)) ≤ (M:ℚ) ∧ + CommonBasesFPRAS.repetitionCount (1/(k:ℚ)) ≤ 64*(M+1) := by + have hkq : (0:ℚ) < k := by exact_mod_cast hk + refine ⟨one_div_pos.mpr hkq,?_,?_⟩ + · simpa only [one_div_one_div] using (show (k:ℚ) ≤ M by exact_mod_cast hM) + · unfold CommonBasesFPRAS.repetitionCount + rw [one_div,Rat.inv_natCast_den_of_pos hk,Nat.size_eq_bits_len] + exact Nat.mul_le_mul_left 64 (Nat.add_le_add_right + ((Nat.size_le.mpr Nat.lt_two_pow_self).trans hM) 1) + +lemma bitCount_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + RootedCountingWords.bitCount A s ≤ wordPolynomial.eval (size r c b epsilon delta) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + let S := size r c b epsilon delta + let M := controlPolynomial.eval S + have hm0 : CountingPublicControls.inputPolynomial.eval S ≤ M := by + simp only [M,controlPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hmN : CountingPublicControls.observationPolynomial.eval S ≤ M := by + simp only [M,controlPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hmn : CountingPublicControls.returnPolynomial.eval S ≤ M := by + simp only [M,controlPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hmk : CountingPublicControls.precisionPolynomial.eval S ≤ M := by + simp only [M,controlPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hmK : CountingTerminalBounds.gridPolynomial.eval S ≤ M := by + simp only [M,controlPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hmh : 2048*(CountingTerminalBounds.phasePolynomial.eval S+1) ≤ M := by + simp only [M,controlPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hSM : S ≤ M := by + simp only [M,controlPolynomial,Polynomial.eval_add,Polynomial.eval_mul, + Polynomial.eval_ofNat,Polynomial.eval_X,Polynomial.eval_one] + omega + have hsc : ∀ x∈[Fintype.card (Labels A),A.W,s.H, + CompanionTargetMixing.restartTime A s.H s.L,s.L], + x ≤ CountingPublicControls.inputPolynomial.eval S := + CountingPublicControls.scalar_bound hEK r c b hne epsilon delta he + have hp : Fintype.card (Labels A) ≤ M := + (hsc _ (by simp only [List.mem_cons,eq_self,true_or])).trans hm0 + have hW : A.W ≤ M := + (hsc _ (by simp only [List.mem_cons,eq_self,true_or,or_true])).trans hm0 + have hH : s.H ≤ M := + (hsc _ (by simp only [List.mem_cons,eq_self,true_or,or_true])).trans hm0 + have ht : CompanionTargetMixing.restartTime A s.H s.L ≤ M := + (hsc _ (by simp only [List.mem_cons,eq_self,true_or,or_true])).trans hm0 + have hcontrols := CountingPublicControls.settings_bounds hEK r c b hne epsilon delta he + have hN : s.N ≤ M := hcontrols.1.trans hmN + have hn : s.n ≤ M := hcontrols.2.1.trans hmn + have hk : s.k ≤ M := hcontrols.2.2.trans hmk + have hterminal := CountingPublicTerminalBounds.terminal_public hEK r c b hne epsilon delta he + have hK : s.K ≤ M := hterminal.1.trans hmK + have hh : s.h ≤ M := + (Nat.mul_le_mul_left 2048 (Nat.add_le_add_right hterminal.2.2 1)).trans hmh + have hd : A.d ≤ M := (dimension_le r c b epsilon delta).trans hSM + have hcapacity : CountingTerminalSchedule.capacityBits A ≤ M := + (capacityBits_le hEK r c b hne epsilon delta).trans hSM + have hkpos : 0 < s.k := CountingPhaseSchedule.precision_pos _ _ _ _ _ + have hrec := reciprocal_controls s.k M hkpos hk + have hb := CountingWordsBound.bitCount_bound A s M hd hW hK hH hk hn hN hh + hH hcapacity hp ht hrec.1 hrec.2.1 hrec.2.2 + simpa only [wordPolynomial,Polynomial.eval_comp] using hb + +lemma amplified_public (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon delta : ℚ) (he : 0 < epsilon) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + RootedCountingAmplification.bitCount A s delta ≤ amplifiedPolynomial.eval (size r c b epsilon delta) := by + have hw := bitCount_public hEK r c b hne epsilon delta he + have hr := repeats_le r c b epsilon delta + dsimp only + simp only [RootedCountingAmplification.bitCount,CommonBasesFPRAS.repetitionCount, + amplifiedPolynomial,Polynomial.eval_mul,Polynomial.eval_ofNat,Polynomial.eval_X] + exact Nat.mul_le_mul hr hw + +end +end ContingencyTables.CountingPublicWordBound + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingScheduleSizes.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingScheduleSizes.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a34bee00cda1b62dd4cc95b8b5c546a050144e1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingScheduleSizes.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseSchedule + +namespace OAI + +/-! # Polynomial numeric bounds for the explicit counting schedules -/ + +namespace ContingencyTables.CountingPhaseSchedule + +/-- A natural reciprocal-accuracy allowance bounds the rational inverse +tolerance; no logarithmic operation is used. -/ +lemma inverse_tolerance_le (H E : ℕ) (epsilon : ℚ) (he : 0 < epsilon) + (hE : 1/epsilon ≤ (E:ℚ)) : + 1/tolerance H epsilon ≤ (800*(H+1)*E:ℕ) := by + have heq : 1/tolerance H epsilon=(800:ℚ)*(H+1)*(1/epsilon) := by + unfold tolerance + field_simp + rw [heq] + have hh := mul_le_mul_of_nonneg_left hE (show (0:ℚ) ≤ 800*(H+1) by positivity) + simpa only [Nat.cast_mul,Nat.cast_add,Nat.cast_ofNat,Nat.cast_one] using hh + +def observationBound (p W H E : ℕ) : ℕ := + 1024*(H+1)*observationCoefficient p W*(800*(H+1)*E)^2+2 + +lemma observations_le (p W H E : ℕ) (epsilon : ℚ) (he : 0 < epsilon) + (hE : 1/epsilon ≤ (E:ℚ)) : + observations p W H (tolerance H epsilon) ≤ observationBound p W H E := by + have heta := tolerance_pos H epsilon he + have hinv := inverse_tolerance_le H E epsilon he hE + have hinv0 : (0:ℚ) ≤ 1/tolerance H epsilon := (one_div_pos.mpr heta).le + have hs : (1/tolerance H epsilon)^2 ≤ ((800*(H+1)*E:ℕ):ℚ)^2 := by + nlinarith + have hb : (1024:ℚ)*(H+1)*observationCoefficient p W/(tolerance H epsilon)^2 ≤ + (1024*(H+1)*observationCoefficient p W*(800*(H+1)*E)^2:ℕ) := by + calc + _ = ((1024:ℚ)*(H+1)*observationCoefficient p W)*(1/tolerance H epsilon)^2 := by ring + _ ≤ ((1024:ℚ)*(H+1)*observationCoefficient p W)*((800*(H+1)*E:ℕ):ℚ)^2 := + mul_le_mul_of_nonneg_left hs (by positivity) + _ = _ := by push_cast; ring + have hc := Nat.ceil_le.mpr hb + unfold observations observationBound + omega + +def precisionBound (p W H tau E : ℕ) : ℕ := + 1024*(H+1)*noiseCoefficient H tau (observationBound p W H E) (returnCap p H tau)+ + 800*(H+1)*E+2 + +lemma precision_le (p W H tau E : ℕ) (epsilon : ℚ) (he : 0 < epsilon) + (hE : 1/epsilon ≤ (E:ℚ)) : + precision H tau (observations p W H (tolerance H epsilon)) (returnCap p H tau) + (tolerance H epsilon) ≤ precisionBound p W H tau E := by + have hN := observations_le p W H E epsilon he hE + have hceil : ⌈1/tolerance H epsilon⌉₊ ≤ 800*(H+1)*E := + Nat.ceil_le.mpr (inverse_tolerance_le H E epsilon he hE) + have hcoef : noiseCoefficient H tau + (observations p W H (tolerance H epsilon)) (returnCap p H tau) ≤ + noiseCoefficient H tau (observationBound p W H E) (returnCap p H tau) := by + unfold noiseCoefficient + exact Nat.add_le_add_right (Nat.mul_le_mul_left 8 (Nat.add_le_add_right hN 1)) _ + unfold precision precisionBound + exact (Nat.add_le_add_right (Nat.add_le_add (Nat.mul_le_mul_left _ hcoef) hceil) 1).trans + (by omega) + +lemma returnCap_eq (p H tau : ℕ) : + returnCap p H tau=65536*(H+1)^2*(tau+1)*(p^2+1) := rfl + +lemma initialPrecision_eq (H : ℕ) : initialPrecision H=2048*(H+1) := rfl + +end ContingencyTables.CountingPhaseSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingSettingsCorrect.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingSettingsCorrect.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd5b674158a93048b6513ce4c37e1884f10cd163 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingSettingsCorrect.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingComputedSettings + +namespace OAI + +/-! # The computed controls are the proven counting schedule -/ + +namespace ContingencyTables.CountingComputedSettings +open MatchingFPRAS CompanionFactorialApplication +open CountingPhaseParametersProgram +open scoped Classical +noncomputable section +variable {m n : ℕ} + +lemma parameters_values (z : Input) (P W H L : ℕ) + (hz : preliminary z=[P,W,H,0,0,0,L]) : + parameters z= + (let T := 4*CountingPhaseSchedule.observable P W*(H+P+L+5) + let eta := CountingPhaseSchedule.tolerance H (TreeFraction.val z.2/2) + ([P,W,H,T,CountingPhaseSchedule.observations P W H eta, + CountingPhaseSchedule.returnCap P H T,L],CountingBaseProgram.half z.2)) := by + unfold parameters basic + rw [hz,basic_values,fillObservations_values,CountingBaseProgram.half_val] + +lemma parameters_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let s := ComputedCountingParameters.settings hEK r c b hne epsilon he + parameters (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + ([Fintype.card (Labels A),A.W,s.H,CompanionTargetMixing.restartTime A s.H s.L, + s.N,s.n,s.L],CountingBaseProgram.half (TreeFraction.repr epsilon)) := by + let A := ComputedCountingParameters.data hEK r c b hne epsilon he + let H := ComputedCountingParameters.phases r c b epsilon + let L := ComputedCountingParameters.capacityBits r c b + have hp : preliminary (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + [Fintype.card (Labels A),A.W,H,0,0,0,L] := by + unfold preliminary + rw [labelCount_data hEK r c b hne epsilon he, + CountingTerminalProgram.cutoff_data r c b epsilon he, + CountingTerminalProgram.phases_data r c b epsilon he,CountingBaseProgram.capacityBits_data] + rfl + rw [parameters_values _ _ _ _ _ hp,TreeFraction.val_repr he.le] + have ht : 4*CountingPhaseSchedule.observable (Fintype.card (Labels A)) A.W* + (H+Fintype.card (Labels A)+L+5)=CompanionTargetMixing.restartTime A H L := by + simp only [CountingPhaseSchedule.observable,CompanionTargetMixing.restartTime, + CompanionTrace.time,CompanionTrace.integerConstant] + ring + dsimp only + rw [ht] + rfl + +lemma precision_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + precision (parameters (NetworkVertexCode.data r c b,TreeFraction.repr epsilon))= + (ComputedCountingParameters.settings hEK r c b hne epsilon he).k := by + rw [parameters_data hEK r c b hne epsilon he,precision_val, + CountingBaseProgram.half_val,TreeFraction.val_repr he.le] + rfl + +lemma noise_data (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (hne : ∃ X,TableTightening.Feasible r c b X) (epsilon : ℚ) (he : 0 < epsilon) : + TreeFraction.val (noise (parameters (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)))= + (ComputedCountingParameters.settings hEK r c b hne epsilon he).xi := by + rw [parameters_data hEK r c b hne epsilon he,noise_val, + CountingBaseProgram.half_val,TreeFraction.val_repr he.le] + rfl + +end +end ContingencyTables.CountingComputedSettings + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e285da634d82aa16f53dc39618218f1e45fe84d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalBounds.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingCoefficientBounds + +namespace OAI + +/-! # Polynomial numeric bounds for the three terminal controls -/ + +namespace ContingencyTables.CountingTerminalBounds +open Polynomial CountingCoefficientBounds +noncomputable section + +def coefficientPolynomial : Polynomial ℕ := CountingCoefficientBounds.coefficientPolynomial.comp (2*X) +def gridPolynomial : Polynomial ℕ := 16*coefficientPolynomial*X^2 +def cutoffPolynomial : Polynomial ℕ := 100*X*gridPolynomial +def phasePolynomial : Polynomial ℕ := 10*coefficientPolynomial*X^2*(cutoffPolynomial+1) + +lemma coefficient_bound (L d E M : ℕ) (epsilon : ℚ) (he : 0 < epsilon) + (hE : 1/epsilon ≤ (E:ℚ)) (hL : L ≤ M) (hd : d ≤ M) (hEM : E ≤ M) : + CountingTerminalSchedule.coefficient L d (epsilon/2) ≤ coefficientPolynomial.eval M := by + have hhalf : 1/(epsilon/2) ≤ ((2*E:ℕ):ℚ) := by + have hh := mul_le_mul_of_nonneg_left hE (show (0:ℚ) ≤ 2 by norm_num) + convert hh using 1 <;> push_cast <;> ring + have hb := CountingCoefficientBounds.coefficient_polynomial L d (2*E) (2*M) + (epsilon/2) (by positivity) hhalf (by omega) (by omega) (by omega) + simpa only [coefficientPolynomial,eval_comp,eval_mul,eval_ofNat,eval_X] using hb + +lemma terminal_bounds (C d W H M : ℕ) + (hC : C ≤ coefficientPolynomial.eval M) (hd : d ≤ M) + (hW : W=100*d*(16*C*d^2)) (hH : H=10*C*d^2*(W+1)) : + 16*C*d^2 ≤ gridPolynomial.eval M ∧ + W ≤ cutoffPolynomial.eval M ∧ H ≤ phasePolynomial.eval M := by + have hgrid : 16*C*d^2 ≤ gridPolynomial.eval M := by + simp only [gridPolynomial,eval_mul,eval_ofNat,eval_pow,eval_X] + exact Nat.mul_le_mul (Nat.mul_le_mul_left 16 hC) (Nat.pow_le_pow_left hd 2) + have hw : W ≤ cutoffPolynomial.eval M := by + rw [hW] + simp only [cutoffPolynomial,eval_mul,eval_ofNat,eval_X] + exact Nat.mul_le_mul (Nat.mul_le_mul_left 100 hd) hgrid + refine ⟨hgrid,hw,?_⟩ + rw [hH] + simp only [phasePolynomial,eval_mul,eval_ofNat,eval_pow,eval_X,eval_add,eval_one] + exact Nat.mul_le_mul + (Nat.mul_le_mul (Nat.mul_le_mul_left 10 hC) (Nat.pow_le_pow_left hd 2)) + (Nat.add_le_add_right hw 1) + +end +end ContingencyTables.CountingTerminalBounds + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c033cdd22e600fae710ea6918f32abf82642a7ab --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalProgram.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingBaseProgram + +namespace OAI + +/-! # The executed terminal grid width, cutoff and phase count -/ + +namespace ContingencyTables.CountingTerminalProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev Input := CountingBaseProgram.Input + +def base (z : Input) : ℕ := + CountingBaseProgram.coefficient z * CountingBaseProgram.dimension z.1 * CountingBaseProgram.dimension z.1 +def baseRealizer : Realizer base := + composition (f := fun z : Input => + (CountingBaseProgram.coefficient z*CountingBaseProgram.dimension z.1,CountingBaseProgram.dimension z.1)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (pair CountingBaseProgram.coefficientRealizer + (composition (f := fun z : Input => z.1) (g := CountingBaseProgram.dimension) + first CountingBaseProgram.dimensionRealizer)) multiply) + (composition (f := fun z : Input => z.1) (g := CountingBaseProgram.dimension) + first CountingBaseProgram.dimensionRealizer)) multiply +lemma polynomial_base : PolynomialTime baseRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair CountingBaseProgram.polynomial_coefficient + (polynomial_composition polynomial_first CountingBaseProgram.polynomial_dimension)) polynomial_multiply) + (polynomial_composition polynomial_first CountingBaseProgram.polynomial_dimension)) polynomial_multiply + +def binCount (z : Input) : ℕ := 16*base z +def binCountRealizer : Realizer binCount := + composition (f := fun z : Input => (16,base z)) (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 16) baseRealizer) multiply +lemma polynomial_binCount : PolynomialTime binCountRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 16) polynomial_base) polynomial_multiply + +def cutoff (z : Input) : ℕ := 100*CountingBaseProgram.dimension z.1*binCount z +def cutoffRealizer : Realizer cutoff := + composition (f := fun z : Input => (100*CountingBaseProgram.dimension z.1,binCount z)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (f := fun z : Input => (100,CountingBaseProgram.dimension z.1)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 100) (composition (f := fun z : Input => z.1) + (g := CountingBaseProgram.dimension) first CountingBaseProgram.dimensionRealizer)) multiply) + binCountRealizer) multiply +lemma polynomial_cutoff : PolynomialTime cutoffRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 100) + (polynomial_composition polynomial_first CountingBaseProgram.polynomial_dimension)) polynomial_multiply) + polynomial_binCount) polynomial_multiply + +def phases (z : Input) : ℕ := 10*base z*(cutoff z+1) +def phasesRealizer : Realizer phases := + composition (f := fun z : Input => (10*base z,cutoff z+1)) (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition (f := fun z : Input => (10,base z)) (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 10) baseRealizer) multiply) + (composition (f := cutoff) (g := fun n : ℕ => n+1) cutoffRealizer successor)) multiply +lemma polynomial_phases : PolynomialTime phasesRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 10) polynomial_base) polynomial_multiply) + (polynomial_composition polynomial_cutoff polynomial_successor)) polynomial_multiply + +lemma binCount_data {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) (he : 0 < epsilon) : + binCount (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + ComputedCountingParameters.binCount r c b epsilon := by + unfold binCount base + rw [CountingBaseProgram.coefficient_data r c b epsilon he, + CountingBaseProgram.dimension_data] + unfold ComputedCountingParameters.binCount + ring + +lemma cutoff_data {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) (he : 0 < epsilon) : + cutoff (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + ComputedCountingParameters.cutoff r c b epsilon := by + unfold cutoff + rw [CountingBaseProgram.dimension_data,binCount_data r c b epsilon he] + rfl + +lemma phases_data {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (epsilon : ℚ) (he : 0 < epsilon) : + phases (NetworkVertexCode.data r c b,TreeFraction.repr epsilon)= + ComputedCountingParameters.phases r c b epsilon := by + unfold phases base + rw [CountingBaseProgram.coefficient_data r c b epsilon he, + CountingBaseProgram.dimension_data,cutoff_data r c b epsilon he] + unfold ComputedCountingParameters.phases + ring + +end ContingencyTables.CountingTerminalProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalSchedule.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalSchedule.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d4648c92f1081828a48b1e51f64ba6b6ce46935 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingTerminalSchedule.lean @@ -0,0 +1,107 @@ +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingSchedule +import Mathlib.Data.Rat.Floor + +namespace OAI + +/-! # Executing the terminal coefficient without real logarithms + +The source's ceiling of log₂(1/epsilon) is exactly the natural ceiling +logarithm of ceil(1/epsilon). All terminal metadata can therefore be +computed with natural and rational arithmetic. +-/ + +namespace ContingencyTables.CountingTerminalSchedule + +open CompanionFactorialApplication CompanionOracleDensity +open scoped BigOperators Classical + +noncomputable section + +lemma natCeil_ratCast (q : ℚ) : ⌈(q:ℝ)⌉₊=⌈q⌉₊ := by + apply le_antisymm + · apply Nat.ceil_le.mpr + exact_mod_cast Nat.le_ceil q + · apply Nat.ceil_le.mpr + exact_mod_cast Nat.le_ceil (q:ℝ) + +def precision (epsilon : ℚ) : ℕ := Nat.clog 2 ⌈1/epsilon⌉₊ +def allowance (L d : ℕ) (epsilon : ℚ) : ℕ := 20*(L+d+precision epsilon+1) +def coefficient (L d : ℕ) (epsilon : ℚ) : ℕ := + ⌈(2048:ℚ)*d*(allowance L d epsilon)^2/epsilon⌉₊ + +lemma precision_eq (epsilon : ℚ) (he : 0 < epsilon) : + precision epsilon=CompanionTerminalParameters.precision (epsilon:ℝ) := by + have heR : (0:ℝ) < epsilon := by exact_mod_cast he + have hequiv (n : ℕ) : + CompanionTerminalParameters.precision (epsilon:ℝ) ≤ n ↔ precision epsilon ≤ n := by + rw [CompanionTerminalParameters.precision,Nat.ceil_le,precision, + Nat.clog_le_iff_le_pow (by decide : 1 < (2:ℕ)),Nat.ceil_le] + rw [Real.logb_le_iff_le_rpow (by norm_num : (1:ℝ) < 2) (by positivity),Real.rpow_natCast] + exact_mod_cast (Iff.rfl : (1/epsilon:ℚ) ≤ (2:ℚ)^n ↔ (1/epsilon:ℚ) ≤ (2:ℚ)^n) + exact le_antisymm ((hequiv _).mp le_rfl) ((hequiv _).mpr le_rfl) + +lemma allowance_eq (L d : ℕ) (epsilon : ℚ) (he : 0 < epsilon) : + allowance L d epsilon=CompanionTerminalParameters.allowance L d (epsilon:ℝ) := by + rw [allowance,precision_eq epsilon he,CompanionTerminalParameters.allowance] + +lemma coefficient_eq (L d : ℕ) (hd : 1 ≤ d) (epsilon : ℚ) (he : 0 < epsilon) : + coefficient L d epsilon=CompanionTerminalParameters.coefficient L d (epsilon:ℝ) := by + have hdR : (d:ℝ) ≠ 0 := by exact_mod_cast (show d ≠ 0 by omega) + have heR : (epsilon:ℝ) ≠ 0 := by exact_mod_cast he.ne' + have ha : (CompanionTerminalParameters.allowance L d (epsilon:ℝ):ℝ) ≠ 0 := by + exact_mod_cast (CompanionTerminalParameters.allowance_positive L d (epsilon:ℝ)).ne' + have hratio : (4:ℝ)*CompanionTerminalParameters.allowance L d (epsilon:ℝ)/ + CompanionTerminalParameters.gamma L d (epsilon:ℝ)= + ((2048:ℚ)*d*(allowance L d epsilon)^2/epsilon:ℚ) := by + rw [allowance_eq L d epsilon he] + simp only [Rat.cast_div,Rat.cast_mul,Rat.cast_ofNat,Rat.cast_natCast,Rat.cast_pow] + unfold CompanionTerminalParameters.gamma + field_simp [hdR,heR,ha] + ring + rw [CompanionTerminalParameters.coefficient,hratio,natCeil_ratCast] + rfl + +variable {I J : Type} [Fintype I] [Fintype J] + +/-- The full product allowance is computed from the input capacities' +binary lengths, rather than supplied as a counting hypothesis. -/ +def capacityBits (A : Instance I J) : ℕ := + ∑ a : I×J,(A.b a.1 a.2+1).size + +lemma capacity_product_bound (A : Instance I J) : + (∏ a : I×J,(A.b a.1 a.2+1)) ≤ 2^capacityBits A := by + calc + _ ≤ ∏ a : I×J,2^(A.b a.1 a.2+1).size := + Finset.prod_le_prod (fun a _ => (Nat.lt_size_self (A.b a.1 a.2+1)).le) + _ = _ := Finset.prod_pow_eq_pow_sum _ _ _ + +lemma small_product_bound (A : Instance I J) : + (∏ a : SmallCell A,((A.b a.val.1 a.val.2:ℝ)+1)) ≤ + (2:ℝ)^capacityBits A := by + have he := Fintype.prod_subtype_mul_prod_subtype + (fun a : I×J => A.small a.1 a.2=true) (fun a => A.b a.1 a.2+1) + have hr : 1 ≤ ∏ a : {a : I×J // ¬A.small a.1 a.2=true},(A.b a.val.1 a.val.2+1) := by + apply Finset.one_le_prod + intro a _ + omega + have hs : (∏ a : SmallCell A,(A.b a.val.1 a.val.2+1)) ≤ + ∏ a : I×J,(A.b a.1 a.2+1) := by + rw [←he] + exact Nat.le_mul_of_pos_right _ (by omega) + exact_mod_cast hs.trans (capacity_product_bound A) + +lemma finalPhase_eq (A : Instance I J) (L : ℕ) (epsilon : ℚ) (he : 0 < epsilon) : + CompanionTerminalApplication.finalPhase A L (epsilon:ℝ)= + rationalHeight A (coefficient L A.d epsilon) := by + rw [CompanionTerminalApplication.finalPhase,←coefficient_eq L A.d A.hd epsilon he] + rfl + +lemma coefficient_pos (L d : ℕ) (hd : 1 ≤ d) (epsilon : ℚ) (he : 0 < epsilon) : + 0 < coefficient L d epsilon := by + rw [coefficient_eq L d hd epsilon he] + exact CompanionTerminalParameters.coefficient_positive L d (epsilon:ℝ) hd (by exact_mod_cast he) + +end +end ContingencyTables.CountingTerminalSchedule + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingWordsBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingWordsBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..acc7de4101877603b97e415c9c0eb08bf167d865 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/CountingWordsBound.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingOracleWordBounds +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingWords +import OAI.Combinatorics.ContingencyTables.Counting.CompanionScaleSizes + +namespace OAI + +/-! # A polynomial bound for the complete adaptive counting word + +The bound includes every reserved restart, oracle and observation word, +including the words unused on unsuccessful paths. +-/ + +namespace ContingencyTables.CountingWordsBound +open CompanionFactorialApplication CompanionOracleDensity RootedPhaseHistory +open CountingOracleWordBounds Polynomial +open scoped BigOperators Classical +noncomputable section +variable {I J : Type} [Fintype I] [Fintype J] + +def initialPolynomial : Polynomial ℕ := X*(X+1)*(X*(3*X+1)+1+X) +def stepPolynomial : Polynomial ℕ := 1+(X^2+((medianPolynomial+medianPolynomial)+X)) +def stagePolynomial : Polynomial ℕ := X*((X+1)*stepPolynomial) +def phasePolynomial : Polynomial ℕ := + initialPolynomial+X*stagePolynomial+(X*stepPolynomial+(X+1)*(medianPolynomial+medianPolynomial)) +def wordPolynomial : Polynomial ℕ := X*(X*phasePolynomial) + +lemma bitCount_bound (A : Instance I J) (s : Settings A) (M : ℕ) + (hd : A.d ≤ M) (hW : A.W ≤ M) (hK : s.K ≤ M) (hH : s.H ≤ M) + (hk : s.k ≤ M) (hn : s.n ≤ M) (hN : s.N ≤ M) (hh : s.h ≤ M) + (hheight : rationalHeight A s.C ≤ M) + (hcapacity : CountingTerminalSchedule.capacityBits A ≤ M) + (hlabels : Fintype.card (Labels A) ≤ M) + (htau : CompanionTargetMixing.restartTime A s.H s.L ≤ M) + (hxi : 0 < s.xi) (hinverse : 1/s.xi ≤ (M:ℚ)) + (hrepeats : CommonBasesFPRAS.repetitionCount s.xi ≤ 64*(M+1)) : + RootedCountingWords.bitCount A s ≤ wordPolynomial.eval M := by + have hmedian (j : ℕ) (hj : j ≤ s.H) : + medianEstimatorBits A s.C s.K j s.xi s.xi ≤ medianPolynomial.eval M := + median_bound A s.C s.K j M s.xi hd hK hheight (hj.trans hH) hcapacity hxi hinverse hrepeats + have hstep (j : ℕ) (hj : j ≤ s.H) : + CompanionBooleanPhase.stepBits A s.C s.K j s.k s.xi ≤ stepPolynomial.eval M := by + have hm := hmedian j hj + have hp : CompanionBooleanPhase.proposalBits A ≤ M^2 := + (Nat.clog_le_of_le_pow (Nat.le_of_lt Nat.lt_two_pow_self)).trans + (Nat.pow_le_pow_left hlabels 2) + simp only [stepPolynomial,Polynomial.eval_add,Polynomial.eval_pow, + Polynomial.eval_X,Polynomial.eval_one] + unfold CompanionBooleanPhase.stepBits + omega + have hstage (i : ℕ) (hi : i+1 ≤ s.H) : + RootedRestartWords.stageWidth A s.C s.K s.H s.L s.k s.n s.xi i ≤ stagePolynomial.eval M := by + simp only [RootedRestartWords.stageWidth,CompanionReturnWords.returnBits, + stagePolynomial,Polynomial.eval_mul,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_one] + exact Nat.mul_le_mul htau (Nat.mul_le_mul (Nat.add_le_add_right hn 1) (hstep (i+1) hi)) + have hinitial : CompanionInitialDraw.initialBits A (CompanionInitialDraw.precision A s.h) ≤ + initialPolynomial.eval M := by + apply (CompanionScaleSizes.initialBits_polynomial_bound A s.h).trans + simp only [initialPolynomial,Polynomial.eval_mul,Polynomial.eval_add,Polynomial.eval_ofNat, + Polynomial.eval_X,Polynomial.eval_one] + exact Nat.mul_le_mul (Nat.mul_le_mul hd (Nat.add_le_add_right hW 1)) + (Nat.add_le_add (Nat.add_le_add_right + (Nat.mul_le_mul hd (Nat.add_le_add_right (Nat.mul_le_mul_left 3 hW) 1)) 1) hh) + have hwidth (j : ℕ) (hj : j < s.H) : width A s j ≤ phasePolynomial.eval M := by + have hsum : (∑ i : Fin j,RootedRestartWords.stageWidth A s.C s.K s.H s.L s.k s.n s.xi i.val) ≤ + M*stagePolynomial.eval M := by + calc + _ ≤ ∑ _i : Fin j,stagePolynomial.eval M := + Finset.sum_le_sum (fun i _ => hstage i.val (by omega)) + _ = j*stagePolynomial.eval M := by simp + _ ≤ _ := Nat.mul_le_mul_right _ (by omega) + have hobs : CompanionPhaseWords.phaseBits A s.C s.K j (s.N+1) s.xi ≤ + (M+1)*(medianPolynomial.eval M+medianPolynomial.eval M) := by + unfold CompanionPhaseWords.phaseBits CompanionPhaseWords.observationBits + exact Nat.mul_le_mul (Nat.add_le_add_right hN 1) + (Nat.add_le_add (hmedian j (by omega)) (hmedian (j+1) (by omega))) + simp only [width,RootedRestartWords.initialStageBits,phasePolynomial,Polynomial.eval_add, + Polynomial.eval_mul,Polynomial.eval_X,Polynomial.eval_one] + exact Nat.add_le_add (Nat.add_le_add hinitial hsum) + (Nat.add_le_add (Nat.mul_le_mul hN (hstep j (by omega))) hobs) + have htotal : totalWidth A s ≤ M*phasePolynomial.eval M := by + calc + _ ≤ ∑ _j : Fin s.H,phasePolynomial.eval M := Finset.sum_le_sum (fun j _ => hwidth j.val j.isLt) + _ = s.H*phasePolynomial.eval M := by simp + _ ≤ _ := Nat.mul_le_mul_right _ hH + simp only [RootedCountingWords.bitCount,wordPolynomial,Polynomial.eval_mul,Polynomial.eval_X] + exact Nat.mul_le_mul hH htotal + +end +end ContingencyTables.CountingWordsBound + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/EstimatorWordBanks.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/EstimatorWordBanks.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee02597529cef12da40ff884fefa90cd939d31f2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/EstimatorWordBanks.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseMetropolisSemantics + +namespace OAI + +/-! # The exact disjoint word layout of one weight estimator + +There is one bank of ratio samples for every phase, followed by one bank +of correction samples. Each correction sample has its own walk and bin +words. This is the literal layout used by the executable allocator. +-/ + +namespace ContingencyTables.EstimatorWordBanks + +open DensePrograms GridBoundary FairBits +open scoped Classical + +abbrev Banks (j S r t b : ℕ) := + (Fin j → Fin S → Fin r → Bool) × + (Fin S → (Fin t → Bool) × (Fin b → Bool)) + +def wordEquiv (j S r t b : ℕ) : + (Fin (j*(S*r)+S*(t+b)) → Bool) ≃ Banks j S r t b := + (splitWordEquiv _ _).trans (Equiv.prodCongr + ((gridWordEquiv j (S*r)).trans + (Equiv.piCongrRight (fun _ => gridWordEquiv S r))) + ((gridWordEquiv S (t+b)).trans + (Equiv.piCongrRight (fun _ => splitWordEquiv t b)))) + +lemma ratio_chunks (j S r t b : ℕ) (hr : 0 < r) + (bits : Fin (j*(S*r)+S*(t+b)) → Bool) (a : Fin j) : + wordChunks (r,wordChunk ((S*r,(List.ofFn bits).take (j*(S*r))),a.val))= + List.ofFn (fun i : Fin S => List.ofFn ((wordEquiv j S r t b bits).1 a i)) := by + rw [ofFn_split_take,wordChunk_ofFn] + rw [wordChunks_ofFn hr] + rfl + +lemma ratio_rows (j S r t b : ℕ) (hs : 0 < S) (hr : 0 < r) + (bits : Fin (j*(S*r)+S*(t+b)) → Bool) : + completeWordRows (S*r,(List.ofFn bits).take (j*(S*r)))=List.range j := by + rw [ofFn_split_take] + simp only [completeWordRows,List.length_ofFn,Nat.mul_div_cancel _ (Nat.mul_pos hs hr)] + +lemma correction_chunks (j S r t b : ℕ) (ht : 0 < t+b) + (bits : Fin (j*(S*r)+S*(t+b)) → Bool) : + (wordChunks (t+b,(List.ofFn bits).drop (j*(S*r)))).take S= + List.ofFn (fun i : Fin S => List.ofFn + (gridWordEquiv S (t+b) (splitWordEquiv (j*(S*r)) (S*(t+b)) bits).2 i)) := by + rw [ofFn_split_drop,wordChunks_ofFn ht] + exact List.take_of_length_le (by simp) + +lemma correction_take (j S r t b : ℕ) + (bits : Fin (j*(S*r)+S*(t+b)) → Bool) (i : Fin S) : + (List.ofFn (gridWordEquiv S (t+b) + (splitWordEquiv (j*(S*r)) (S*(t+b)) bits).2 i)).take t= + List.ofFn ((wordEquiv j S r t b bits).2 i).1 := by + rw [ofFn_split_take] + rfl + +lemma correction_drop (j S r t b : ℕ) + (bits : Fin (j*(S*r)+S*(t+b)) → Bool) (i : Fin S) : + (List.ofFn (gridWordEquiv S (t+b) + (splitWordEquiv (j*(S*r)) (S*(t+b)) bits).2 i)).drop t= + List.ofFn ((wordEquiv j S r t b bits).2 i).2 := by + rw [ofFn_split_drop] + rfl + +end ContingencyTables.EstimatorWordBanks + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/InitialMultiplierValues.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/InitialMultiplierValues.lean new file mode 100644 index 0000000000000000000000000000000000000000..264fe844f2016c7723e01484845f539c788283f9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/InitialMultiplierValues.lean @@ -0,0 +1,173 @@ +import OAI.Combinatorics.ContingencyTables.Transport.InitialDefectChoices +import OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialization + +namespace OAI + +/-! # Exact source initial multipliers for actual labelled defects -/ + +namespace ContingencyTables.InitialMultiplierValues + +open scoped BigOperators Classical +open CommonBasesFPRAS TwoLiftStates InitialTransversals InitializationBrackets + +variable {C : Type*} [Fintype C] (b : C → ℕ) + +lemma bracket_hole_of_pos (n : ℕ) (hn : 0< n) : bracket n 1 0=1 := by + obtain ⟨k,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt hn) + exact bracket_hole k + +lemma bracket_full_of_pos (n : ℕ) (hn : 0< n) : + bracket n 0 1=((n:ℝ)+1)*((n:ℝ)+2)/6 := by + obtain ⟨k,rfl⟩ := Nat.exists_eq_succ_of_ne_zero (Nat.ne_of_gt hn) + rw [bracket_full] + push_cast + ring + +lemma bracket_both_of_two (n : ℕ) (hn : 2≤ n) : bracket n 1 1=((n:ℝ)+1)/6 := by + have he : n=(n-2)+2 := by omega + conv_lhs => rw [he] + rw [bracket_both] + have hc : (n:ℝ)=((n-2:ℕ):ℝ)+2 := by exact_mod_cast he + rw [hc] + ring + +omit [Fintype C] in +lemma same_cell_capacity (p q : Copy b) (hpq : p≠q) (hcell : p.1=q.1) : 2≤ b p.1 := by + rcases p with ⟨c,p⟩ + rcases q with ⟨c',q⟩ + simp only at hcell + subst c' + have hne : p≠q := fun h => hpq (congrArg (Sigma.mk c) h) + have hp := p.isLt + have hq := q.isLt + have hv : p.val≠q.val := fun h => hne (Fin.ext h) + change 2≤b c + omega + +noncomputable def value (p q : Copy b) : ℝ := + if p.1=q.1 then 6 else 6*((b p.1:ℝ)+1)/((b q.1:ℝ)+2) + +omit [Fintype C] in +lemma value_positive (p q : Copy b) : 0< value b p q := by + unfold value + split_ifs <;> positivity + +lemma bracket_product_same (p q : Copy b) (hpq : p≠q) (hcell : p.1=q.1) : + (∏ c,bracket (b c) (if p.1=c then 1 else 0) (if q.1=c then 1 else 0))= + (∏ c,((b c:ℝ)+1))/6 := by + have he (c : C) : + bracket (b c) (if p.1=c then 1 else 0) (if q.1=c then 1 else 0)= + ((b c:ℝ)+1)*(if c=p.1 then (1/6:ℝ) else 1) := by + by_cases hc : p.1=c + · subst c + simp only [hcell,ite_true,bracket_both_of_two (b q.1) (by + simpa only [hcell] using same_cell_capacity b p q hpq hcell)] + ring + · have hcq : q.1≠c := by rwa [← hcell] + simp [hc,hcq,Ne.symm hc,bracket_neither] + simp_rw [he] + rw [Finset.prod_mul_distrib] + simp + ring + +lemma bracket_product_different (p q : Copy b) (hcell : p.1≠q.1) : + (∏ c,bracket (b c) (if p.1=c then 1 else 0) (if q.1=c then 1 else 0))= + (∏ c,((b c:ℝ)+1))*(((b q.1:ℝ)+2)/(6*((b p.1:ℝ)+1))) := by + have he (c : C) : + bracket (b c) (if p.1=c then 1 else 0) (if q.1=c then 1 else 0)= + ((b c:ℝ)+1)* + ((if c=p.1 then 1/((b p.1:ℝ)+1) else 1)* + (if c=q.1 then ((b q.1:ℝ)+2)/6 else 1)) := by + by_cases hp : p.1=c + · subst c + have hq : q.1≠p.1 := Ne.symm hcell + simp only [ite_true,hq,ite_false,hcell,bracket_hole_of_pos (b p.1) (by have := p.2.isLt; omega), + mul_one] + field_simp + · by_cases hq : q.1=c + · subst c + simp only [hp,ite_false,ite_true,Ne.symm hp, + bracket_full_of_pos (b q.1) (by have := q.2.isLt; omega),one_mul] + ring + · simp [hp,hq,Ne.symm hp,Ne.symm hq,bracket_neither] + simp_rw [he] + rw [Finset.prod_mul_distrib,Finset.prod_mul_distrib] + simp only [Finset.prod_ite_eq',Finset.mem_univ,ite_true] + field_simp + +/-- The exact finite transversal/defect ratio is six in a shared cell, +and otherwise six times (b_hole+1)/(b_full+2). -/ +theorem ideal_constant [DecidableEq C] (p q : Copy b) (hpq : p≠q) (M : ℝ) (hM : 0< M) : + slotTotal pairs (LabelledFactorial.firstLift (group (cell b)) (fun _ => M) + (InitialTransversals.denominator b)) ∅/ + slotDefect pairs (LabelledFactorial.firstLift (group (cell b)) (fun _ => M) + (InitialTransversals.denominator b)) ∅ (TwoLiftStates.pair p) (TwoLiftStates.pair q)=value b p q := by + have hd : (inferInstance : DecidableEq C)=Classical.decEq C := Subsingleton.elim _ _ + cases hd + rw [slotTotal_constant,InitialDefectChoices.slotDefect_constant b p q hpq] + have hprod : (∏ c,((b c:ℝ)+1))≠0 := ne_of_gt (Finset.prod_pos (fun _ _ => by positivity)) + by_cases hcell : p.1=q.1 + · rw [bracket_product_same b p q hpq hcell] + simp only [value,hcell,ite_true] + field_simp [hM.ne',hprod] + · rw [bracket_product_different b p q hcell] + simp only [value,hcell,ite_false] + field_simp [hM.ne',hprod] + +end ContingencyTables.InitialMultiplierValues +namespace ContingencyTables.CompanionInitialMultipliers + +open scoped BigOperators Classical +open CommonBasesFPRAS CompanionFactorialApplication CompanionInitialization LabelledFactorial TwoLiftStates + +variable {I J : Type*} [Fintype I] [Fintype J] + +noncomputable def multiplier (A : Instance I J) + (p q : (Labels A×Bool)×(Labels A×Bool)) : ℝ := + InitialMultiplierValues.value (fun s : SmallCell A => A.b s.val.1 s.val.2) p.1.1 q.1.1 + +lemma multiplier_positive (A : Instance I J) (p q : (Labels A×Bool)×(Labels A×Bool)) : + 0< multiplier A p q := InitialMultiplierValues.value_positive _ _ _ + +lemma freeTotal_positive (A : Instance I J) : 0< freeTotal A := by + apply Finset.prod_pos + intro a _ + exact Nat.cast_pos.mpr (Nat.succ_pos _) + +/-- The explicit rational initial multiplier equals the ideal for the +literal source count, not just for an abstract constant lift. -/ +theorem ideal_at_zero (A : Instance I J) (p q : Labels A) (hpq : p≠q) : + slotTotal pairs (f A 0) ∅/slotDefect pairs (f A 0) ∅ (TwoLiftStates.pair p) (TwoLiftStates.pair q)= + multiplier A (TwoLiftStates.pair p) (TwoLiftStates.pair q) := by + have he : f A 0=firstLift (group (labelCell A)) (fun _ => freeTotal A) + (CompanionFactorialApplication.denominator A) := by + funext S + unfold f firstLift + rw [h_zero] + rw [he,denominator_eq] + convert InitialMultiplierValues.ideal_constant + (fun s : SmallCell A => A.b s.val.1 s.val.2) p q hpq (freeTotal A) (freeTotal_positive A) using 1 + congr 1 + +/-- Initialization has exact ideals, hence satisfies every good- +multiplier inequality for the actual chain without a sampling event. -/ +theorem initial_good (A : Instance I J) : GoodMultipliers pairs (f A 0) (multiplier A) := by + refine ⟨multiplier_positive A,?_,?_⟩ + · intro p hp q hq hpq + obtain ⟨a,_,rfl⟩ := List.mem_map.mp (show p∈Finset.univ.toList.map TwoLiftStates.pair from hp) + obtain ⟨b,_,rfl⟩ := List.mem_map.mp (show q∈Finset.univ.toList.map TwoLiftStates.pair from hq) + have hab : a≠b := fun h => hpq (congrArg TwoLiftStates.pair h) + rw [mul_comm (4:ℝ),← div_div,ideal_at_zero A a b hab] + have hpos := multiplier_positive A (TwoLiftStates.pair a) (TwoLiftStates.pair b) + linarith + · intro p hp q hq hpq + obtain ⟨a,_,rfl⟩ := List.mem_map.mp (show p∈Finset.univ.toList.map TwoLiftStates.pair from hp) + obtain ⟨b,_,rfl⟩ := List.mem_map.mp (show q∈Finset.univ.toList.map TwoLiftStates.pair from hq) + have hab : a≠b := fun h => hpq (congrArg TwoLiftStates.pair h) + rw [mul_div_assoc,ideal_at_zero A a b hab] + have hpos := multiplier_positive A (TwoLiftStates.pair a) (TwoLiftStates.pair b) + linarith + +end ContingencyTables.CompanionInitialMultipliers + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Counting/InitializationBrackets.lean b/lean/OAI/Combinatorics/ContingencyTables/Counting/InitializationBrackets.lean new file mode 100644 index 0000000000000000000000000000000000000000..f8fc7a3e553376e21c491222e8e18d7c939e64ec --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Counting/InitializationBrackets.lean @@ -0,0 +1,125 @@ +import Mathlib + +namespace OAI + +/-! +# Exact local factorial sums for the companion's initial multipliers + +These are the four brackets in the manuscript's exact initialization +formula. The full-pair case reduces to an explicitly evaluated quadratic +sum, so the rational initializer uses no factorial evaluation oracle. +-/ + +namespace ContingencyTables.InitializationBrackets + +open scoped BigOperators +open Nat + +noncomputable def bracket (b u v : ℕ) : ℝ := + (∑ k ∈ Finset.range (b-u-v+1), + ((b-u-v).choose k:ℝ)*((k+v)!:ℝ)*((b-u-v-k+v)!:ℝ))/(b !:ℝ) + +private lemma choose_factorial (n k : ℕ) (hk : k≤n) : + (n.choose k:ℝ)*(k !:ℝ)*((n-k)!:ℝ)=(n !:ℝ) := by + exact_mod_cast Nat.choose_mul_factorial_mul_factorial hk + +private lemma shifted_choose_factorial (n k : ℕ) (hk : k≤n) : + (n.choose k:ℝ)*((k+1)!:ℝ)*((n-k+1)!:ℝ)= + (n !:ℝ)*((k:ℝ)+1)*((n-k:ℕ)+1:ℝ) := by + rw [Nat.factorial_succ,Nat.factorial_succ] + push_cast + calc + _ = ((n.choose k:ℝ)*(k !:ℝ)*((n-k)!:ℝ))*((k:ℝ)+1)*((n-k:ℕ)+1:ℝ) := by ring + _ = _ := by rw [choose_factorial n k hk] + +private lemma linear_sum (n : ℕ) : + (∑ k ∈ Finset.range (n+1), ((k:ℝ)+1))=((n:ℝ)+1)*((n:ℝ)+2)/2 := by + induction n with + | zero => norm_num + | succ n ih => + rw [Finset.sum_range_succ,ih] + push_cast + ring + +private lemma quadratic_sum (n : ℕ) : + (∑ k ∈ Finset.range (n+1), ((k:ℝ)+1)*((n-k:ℕ)+1:ℝ))= + ((n:ℝ)+1)*((n:ℝ)+2)*((n:ℝ)+3)/6 := by + induction n with + | zero => norm_num + | succ n ih => + rw [Finset.sum_range_succ] + have hterms : + (∑ k ∈ Finset.range (n+1), ((k:ℝ)+1)*((n+1-k:ℕ)+1:ℝ))= + (∑ k ∈ Finset.range (n+1), ((k:ℝ)+1)*((n-k:ℕ)+1:ℝ))+ + ∑ k ∈ Finset.range (n+1), ((k:ℝ)+1) := by + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro k hk + have he : n+1-k=(n-k)+1 := by have := Finset.mem_range.mp hk; omega + rw [he] + push_cast + ring + rw [hterms,ih,linear_sum] + simp only [Nat.sub_self,Nat.cast_zero,zero_add] + push_cast + ring + +private lemma unshifted_sum (n : ℕ) : + (∑ k ∈ Finset.range (n+1), (n.choose k:ℝ)*(k !:ℝ)*((n-k)!:ℝ))= + ((n:ℝ)+1)*(n !:ℝ) := by + calc + _ = ∑ _k ∈ Finset.range (n+1), (n !:ℝ) := by + apply Finset.sum_congr rfl + intro k hk + exact choose_factorial n k (by have := Finset.mem_range.mp hk; omega) + _ = _ := by simp + +private lemma shifted_sum (n : ℕ) : + (∑ k ∈ Finset.range (n+1), (n.choose k:ℝ)*((k+1)!:ℝ)*((n-k+1)!:ℝ))= + (n !:ℝ)*(((n:ℝ)+1)*((n:ℝ)+2)*((n:ℝ)+3)/6) := by + calc + _ = ∑ k ∈ Finset.range (n+1), (n !:ℝ)*(((k:ℝ)+1)*((n-k:ℕ)+1:ℝ)) := by + apply Finset.sum_congr rfl + intro k hk + rw [shifted_choose_factorial n k (by have := Finset.mem_range.mp hk; omega)] + ring + _ = _ := by rw [← Finset.mul_sum,quadratic_sum] + +theorem bracket_neither (b : ℕ) : bracket b 0 0=(b:ℝ)+1 := by + unfold bracket + simp only [Nat.sub_zero,Nat.add_zero] + rw [unshifted_sum] + exact mul_div_cancel_right₀ _ (Nat.cast_ne_zero.mpr (Nat.factorial_ne_zero b)) + +theorem bracket_hole (n : ℕ) : bracket (n+1) 1 0=1 := by + unfold bracket + simp only [Nat.add_sub_cancel,Nat.sub_zero,Nat.add_zero] + rw [unshifted_sum,Nat.factorial_succ] + push_cast + exact div_self (mul_ne_zero (by positivity) (Nat.cast_ne_zero.mpr (Nat.factorial_ne_zero n))) + +theorem bracket_full (n : ℕ) : + bracket (n+1) 0 1=((n:ℝ)+2)*((n:ℝ)+3)/6 := by + unfold bracket + simp only [Nat.sub_zero,Nat.add_sub_cancel] + rw [shifted_sum,Nat.factorial_succ] + push_cast + have hf : (n !:ℝ)≠0 := Nat.cast_ne_zero.mpr (Nat.factorial_ne_zero n) + have hn : (n:ℝ)+1≠0 := by positivity + field_simp [hf,hn] + +theorem bracket_both (n : ℕ) : bracket (n+2) 1 1=((n:ℝ)+3)/6 := by + unfold bracket + have he : n+2-1-1=n := by omega + rw [he,shifted_sum] + rw [show n+2=(n+1)+1 by omega,Nat.factorial_succ,Nat.factorial_succ] + push_cast + have hf : (n !:ℝ)≠0 := Nat.cast_ne_zero.mpr (Nat.factorial_ne_zero n) + have hn : (n:ℝ)+1≠0 := by positivity + have hn' : (n:ℝ)+2≠0 := by positivity + field_simp [hf,hn,hn'] + ring + +end ContingencyTables.InitializationBrackets + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/AffineRegion.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/AffineRegion.lean new file mode 100644 index 0000000000000000000000000000000000000000..4233056f3f361110fa92d7258bfbc437492929a6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/AffineRegion.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.ContingencyTables.Transport.AffinePenalty +import Mathlib.MeasureTheory.Measure.Lebesgue.EqHaar + +namespace OAI + +/-! +# Inner and relaxed affine feasibility regions + +The strict feasible point yields the two homothetic inclusions used in +the dense rejection proof. Volume scaling follows from the Lebesgue/Haar +change-of-variables theorem. +-/ + +namespace ContingencyTables.AffinePenalty + +open MeasureTheory +open scoped BigOperators Pointwise + +noncomputable section + +variable {I G : Type*} [Fintype I] + +def region (offset : G → ℝ) (coeff : G → I → ℝ) (γ : ℝ) : Set (I → ℝ) := + {x | ∀ g, γ ≤ affineValue (offset g) (coeff g) x} + +theorem inner_region_map (offset : G → ℝ) (coeff : G → I → ℝ) + (center : I → ℝ) (η α : ℝ) (hα : 0 ≤ α) (hα₁ : α ≤ 1) + (hc : center ∈ region offset coeff η) : + (fun x => (1 - α) • x + α • center) '' region offset coeff 0 ⊆ + region offset coeff (α * η) := by + rintro y ⟨x, hx, rfl⟩ g + rw [affineValue_combine _ _ _ _ _ _ (by ring)] + have ha := mul_nonneg (sub_nonneg.mpr hα₁) (hx g) + have hb := mul_le_mul_of_nonneg_left (hc g) hα + linarith + +theorem relaxed_region_pullback (offset : G → ℝ) (coeff : G → I → ℝ) + (center : I → ℝ) (d γ : ℝ) (hd : 0 < d) (hγ : 0 ≤ γ) + (hc : center ∈ region offset coeff (1 / (2 * d))) + (x : I → ℝ) (hx : x ∈ region offset coeff (-γ)) : + (1 / (1 + 2 * d * γ)) • x + (2 * d * γ / (1 + 2 * d * γ)) • center ∈ + region offset coeff 0 := by + have hden : 0 < 1 + 2 * d * γ := by positivity + have hab : 1 / (1 + 2 * d * γ) + 2 * d * γ / (1 + 2 * d * γ) = 1 := by + field_simp [ne_of_gt hden] + intro g + rw [affineValue_combine _ _ _ _ _ _ hab] + calc + 0 = (1 / (1 + 2 * d * γ)) * (-γ) + + (2 * d * γ / (1 + 2 * d * γ)) * (1 / (2 * d)) := by + field_simp [ne_of_gt hd, ne_of_gt hden] + ring + _ ≤ _ := add_le_add (mul_le_mul_of_nonneg_left (hx g) (by positivity)) + (mul_le_mul_of_nonneg_left (hc g) (by positivity)) + +theorem relaxed_region_subset_expansion (offset : G → ℝ) (coeff : G → I → ℝ) + (center : I → ℝ) (d γ : ℝ) (hd : 0 < d) (hγ : 0 ≤ γ) + (hc : center ∈ region offset coeff (1 / (2 * d))) : + region offset coeff (-γ) ⊆ + (fun z => center + (1 + 2 * d * γ) • (z - center)) '' region offset coeff 0 := by + intro x hx + refine ⟨_, relaxed_region_pullback offset coeff center d γ hd hγ hc x hx, ?_⟩ + have hden : 1 + 2 * d * γ ≠ 0 := ne_of_gt (by positivity : 0 < 1 + 2 * d * γ) + ext i + simp only [Pi.add_apply, Pi.sub_apply, Pi.smul_apply, smul_eq_mul] + field_simp [hden] + ring + +private theorem volume_image_translate (c : I → ℝ) (S : Set (I → ℝ)) : + volume ((fun x => c + x) '' S) = volume S := by + have heq : (fun x => c + x) '' S = (fun x => -c + x) ⁻¹' S := by + ext x + constructor + · rintro ⟨y, hy, rfl⟩ + simpa using hy + · intro hx + exact ⟨-c + x, hx, by simp⟩ + rw [heq, measure_preimage_add] + +theorem volume_homothety (center : I → ℝ) (a : ℝ) (ha : 0 ≤ a) (S : Set (I → ℝ)) : + volume ((fun z => center + a • (z - center)) '' S) = + ENNReal.ofReal (a ^ Fintype.card I) * volume S := by + have heq : (fun z => center + a • (z - center)) '' S = + (fun z => center + z) '' (a • ((fun z => -center + z) '' S)) := by + simp only [← Set.image_smul, Set.image_image] + congr 1 + funext z + rw [sub_eq_neg_add] + rw [heq, volume_image_translate, Measure.addHaar_smul_of_nonneg volume ha, + volume_image_translate, Module.finrank_fintype_fun_eq_card] + +theorem relaxed_region_volume (offset : G → ℝ) (coeff : G → I → ℝ) + (center : I → ℝ) (d γ : ℝ) (hd : 0 < d) (hγ : 0 ≤ γ) + (hc : center ∈ region offset coeff (1 / (2 * d))) : + volume (region offset coeff (-γ)) ≤ + ENNReal.ofReal ((1 + 2 * d * γ) ^ Fintype.card I) * volume (region offset coeff 0) := by + calc + _ ≤ volume ((fun z => center + (1 + 2 * d * γ) • (z - center)) '' region offset coeff 0) := + measure_mono (relaxed_region_subset_expansion offset coeff center d γ hd hγ hc) + _ = _ := volume_homothety center _ (by positivity) _ + +end + +end ContingencyTables.AffinePenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/AffineRegionVolume.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/AffineRegionVolume.lean new file mode 100644 index 0000000000000000000000000000000000000000..eddf9d4fb829fa961729d9b6bb7ad1b83952e079 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/AffineRegionVolume.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.ContingencyTables.Dense.AffineRegion +import Mathlib.Analysis.SpecialFunctions.Exp + +namespace OAI + +/-! # Volume comparisons used by dense rejection -/ + +namespace ContingencyTables.AffinePenalty + +open MeasureTheory +open scoped BigOperators Pointwise + +noncomputable section + +variable {I G : Type*} [Fintype I] + +theorem inner_region_volume (offset : G → ℝ) (coeff : G → I → ℝ) + (center : I → ℝ) (η α : ℝ) (hα : 0 ≤ α) (hα₁ : α ≤ 1) + (hc : center ∈ region offset coeff η) : + ENNReal.ofReal ((1 - α) ^ Fintype.card I) * volume (region offset coeff 0) ≤ + volume (region offset coeff (α * η)) := by + rw [← volume_homothety center (1 - α) (sub_nonneg.mpr hα₁)] + have heq : (fun x : I → ℝ => center + (1 - α) • (x - center)) = + (fun x => (1 - α) • x + α • center) := by + ext x i + simp only [Pi.add_apply, Pi.sub_apply, Pi.smul_apply, smul_eq_mul] + ring + rw [heq] + exact measure_mono (inner_region_map offset coeff center η α hα hα₁ hc) + +theorem relaxed_region_volume_exp (offset : G → ℝ) (coeff : G → I → ℝ) + (center : I → ℝ) (d γ : ℝ) (hd : 0 < d) (hγ : 0 ≤ γ) + (hdim : (Fintype.card I : ℝ) ≤ d) + (hc : center ∈ region offset coeff (1 / (2 * d))) : + volume (region offset coeff (-γ)) ≤ + ENNReal.ofReal (Real.exp (2 * d ^ 2 * γ)) * volume (region offset coeff 0) := by + have hpoly : (1 + 2 * d * γ) ^ Fintype.card I ≤ Real.exp (2 * d ^ 2 * γ) := by + calc + _ ≤ (Real.exp (2 * d * γ)) ^ Fintype.card I := + pow_le_pow_left₀ (by positivity) (by linarith [Real.add_one_le_exp (2 * d * γ)]) _ + _ = Real.exp ((Fintype.card I : ℝ) * (2 * d * γ)) := (Real.exp_nat_mul _ _).symm + _ ≤ _ := Real.exp_le_exp.mpr (by + have h := mul_le_mul_of_nonneg_right hdim (show 0 ≤ 2 * d * γ by positivity) + nlinarith) + exact (relaxed_region_volume offset coeff center d γ hd hγ hc).trans + (mul_le_mul_left (ENNReal.ofReal_le_ofReal hpoly) _) + +end + +end ContingencyTables.AffinePenalty + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerCoarea.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerCoarea.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f6e2ad9b709fa1af3760b533f389028abe3601f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerCoarea.lean @@ -0,0 +1,134 @@ +import OAI.Combinatorics.ContingencyTables.Dense.PublishedCheeger +import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic + +namespace OAI + +/-! # Weighted finite coarea for the published Cheeger input -/ +namespace ContingencyTables.CheegerProof +open MeasureTheory CommonBasesFPRAS +open scoped BigOperators Classical +noncomputable section + +def level (a t : ℝ) : ℝ := if 0 ≤ t ∧ t < a then 1 else 0 + +lemma level_eq (a : ℝ) : + level a = Set.indicator (Set.Ico 0 a) (fun _ => (1:ℝ)) := by + funext t + simp [level,Set.indicator_apply,Set.mem_Ico] + +lemma level_integrable (a : ℝ) : Integrable (level a) := by + rw [level_eq] + exact (integrableOn_const (isCompact_Icc.measure_lt_top.ne) : + IntegrableOn (fun _ : ℝ => (1:ℝ)) (Set.Icc 0 a)).mono_set + Set.Ico_subset_Icc_self |>.integrable_indicator measurableSet_Ico + +lemma level_integral {a : ℝ} (ha : 0 ≤ a) : ∫ t, level a t = a := by + rw [level_eq,integral_indicator measurableSet_Ico] + simp [ha] + +lemma level_abs_sub (a b t : ℝ) : + |level a t-level b t| = level a t+level b t-2*level (min a b) t := by + simp only [level,lt_min_iff] + by_cases h₀ : 0 ≤ t <;> by_cases ha : t < a <;> by_cases hb : t < b <;> + norm_num [h₀,ha,hb] + +lemma level_abs_integrable (a b : ℝ) : Integrable (fun t => |level a t-level b t|) := + ((level_integrable a).sub (level_integrable b)).abs + +lemma level_abs_integral {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) : + ∫ t, |level a t-level b t| = |a-b| := by + simp_rw [level_abs_sub] + rw [integral_sub (f := fun t => level a t+level b t) + ((level_integrable a).add (level_integrable b)) + ((level_integrable (min a b)).const_mul 2), + integral_add (level_integrable a) (level_integrable b),integral_const_mul, + level_integral ha,level_integral hb,level_integral (le_min ha hb)] + rcases le_total a b with h | h + · rw [min_eq_left h,abs_of_nonpos (sub_nonpos.mpr h)]; ring + · rw [min_eq_right h,abs_of_nonneg (sub_nonneg.mpr h)]; ring + +variable {X : Type*} [Fintype X] (C : FiniteChain X) + +def mass (S : Finset X) : ℝ := ∑ x ∈ S, C.π x +def cut (S : Finset X) : ℝ := ∑ x ∈ S, ∑ y ∈ Sᶜ, C.π x*C.P x y + +lemma mass_nonneg (S : Finset X) : 0 ≤ mass C S := + Finset.sum_nonneg fun x _ => (C.positive x).le + +lemma mass_mono {S T : Finset X} (h : S ⊆ T) : mass C S ≤ mass C T := + Finset.sum_le_sum_of_subset_of_nonneg h (fun x _ _ => (C.positive x).le) + +lemma mass_compl (S : Finset X) : mass C Sᶜ = 1-mass C S := by + have h := Finset.sum_compl_add_sum S C.π + rw [C.normalized] at h + dsimp [mass] + linarith + +lemma cut_indicator (S : Finset X) : + (∑ x, ∑ y, C.π x*C.P x y* + |(if x ∈ S then (1:ℝ) else 0)-(if y ∈ S then (1:ℝ) else 0)|) = 2*cut C S := by + have hs (x y : X) : C.π x*C.P x y* + |(if x ∈ S then (1:ℝ) else 0)-(if y ∈ S then (1:ℝ) else 0)| = + (if x ∈ S ∧ y ∉ S then C.π x*C.P x y else 0)+ + (if y ∈ S ∧ x ∉ S then C.π x*C.P x y else 0) := by + by_cases hx : x ∈ S <;> by_cases hy : y ∈ S <;> simp [hx,hy] + simp_rw [hs,Finset.sum_add_distrib] + have hforward : (∑ x, ∑ y, if x ∈ S ∧ y ∉ S then C.π x*C.P x y else 0) = cut C S := by + simp only [ite_and,Finset.sum_ite_irrel,Finset.sum_const_zero] + rw [← Finset.sum_filter] + simp only [Finset.filter_mem_eq_inter,Finset.univ_inter] + apply Finset.sum_congr rfl + intro x hx + rw [← Finset.sum_filter] + congr 1 + ext y + simp + have hback : (∑ x, ∑ y, if y ∈ S ∧ x ∉ S then C.π x*C.P x y else 0) = cut C S := by + rw [Finset.sum_comm] + simpa only [C.reversible] using hforward + rw [hforward,hback] + ring + +/-- Coarea on a function supported on a set of stationary mass at most one half. -/ +theorem coarea (κ : ℝ) + (hcut : ∀ S : Finset X, κ*min (mass C S) (mass C Sᶜ) ≤ cut C S) + (g : X → ℝ) (hg : ∀ x, 0 ≤ g x) + (hsmall : mass C (Finset.univ.filter fun x => 0 < g x) ≤ 1/2) : + 2*κ*(∑ x, C.π x*g x) ≤ ∑ x, ∑ y, C.π x*C.P x y*|g x-g y| := by + let F : ℝ → ℝ := fun t => 2*κ*∑ x, C.π x*level (g x) t + let J : ℝ → ℝ := fun t => ∑ x, ∑ y, C.π x*C.P x y*|level (g x) t-level (g y) t| + have hF : Integrable F := + (integrable_finsetSum _ (fun x _ => (level_integrable (g x)).const_mul (C.π x))).const_mul _ + have hJ : Integrable J := integrable_finsetSum _ fun x _ => + integrable_finsetSum _ fun y _ => (level_abs_integrable (g x) (g y)).const_mul _ + have hle (t : ℝ) : F t ≤ J t := by + let S := Finset.univ.filter fun x => 0 ≤ t ∧ t < g x + have hi (x : X) : level (g x) t = if x ∈ S then 1 else 0 := by simp [level,S] + have hm : mass C S ≤ 1/2 := (mass_mono C (by + intro x hx + simp only [S,Finset.mem_filter,Finset.mem_univ,true_and] at hx + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _,hx.1.trans_lt hx.2⟩)).trans hsmall + have hc := hcut S + rw [mass_compl,min_eq_left (by linarith : mass C S ≤ 1-mass C S)] at hc + have hl : (∑ x, C.π x*level (g x) t) = mass C S := by + simp only [hi,mul_ite,mul_one,mul_zero,mass] + rw [← Finset.sum_filter] + simp + dsimp [F,J] + rw [hl] + simp only [hi,cut_indicator] + linarith + have H := integral_mono hF hJ hle + dsimp [F,J] at H + rw [integral_const_mul,integral_finsetSum _ (fun x _ => (level_integrable (g x)).const_mul _)] at H + simp_rw [integral_const_mul,level_integral (hg _)] at H + rw [integral_finsetSum _ (fun x _ => integrable_finsetSum _ + (fun y _ => (level_abs_integrable (g x) (g y)).const_mul _))] at H + simp_rw [integral_finsetSum _ (fun y _ => (level_abs_integrable _ _).const_mul _), + integral_const_mul,level_abs_integral (hg _) (hg _)] at H + exact H + +end +end ContingencyTables.CheegerProof + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerMedian.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerMedian.lean new file mode 100644 index 0000000000000000000000000000000000000000..89bc81fdb6cb1c792fb413b527d41364fc86b523 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerMedian.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Dense.CheegerCoarea + +namespace OAI + +/-! # A stationary weighted median on a finite chain -/ +namespace ContingencyTables.CheegerProof +open CommonBasesFPRAS +open scoped BigOperators Classical +noncomputable section +variable {X : Type*} [Fintype X] (C : FiniteChain X) + +theorem exists_median (f : X → ℝ) : ∃ a : ℝ, + mass C (Finset.univ.filter fun x => f x < a) ≤ 1/2 ∧ + mass C (Finset.univ.filter fun x => a < f x) ≤ 1/2 := by + have hne : (Finset.univ : Finset X).Nonempty := by + by_contra hn + have hz := Finset.not_nonempty_iff_eq_empty.mp hn + have h := C.normalized + rw [hz,Finset.sum_empty] at h + norm_num at h + let M := Finset.univ.filter fun x => + 1/2 ≤ mass C (Finset.univ.filter fun y => f y ≤ f x) + have hM : M.Nonempty := by + obtain ⟨x,hx,hm⟩ := Finset.exists_max_image Finset.univ f hne + have he : (Finset.univ.filter fun y => f y ≤ f x) = Finset.univ := by + ext y + simp only [Finset.mem_filter,Finset.mem_univ,true_and] + exact iff_true_intro (hm y (Finset.mem_univ _)) + refine ⟨x,Finset.mem_filter.mpr ⟨hx,?_⟩⟩ + rw [he] + simp only [mass,C.normalized] + norm_num + obtain ⟨x,hx,hmin⟩ := Finset.exists_min_image M f hM + have hxM : 1/2 ≤ mass C (Finset.univ.filter fun y => f y ≤ f x) := + (Finset.mem_filter.mp hx).2 + refine ⟨f x,?_,?_⟩ + · let L := Finset.univ.filter fun y => f y < f x + change mass C L ≤ 1/2 + by_contra hn + have hL : 1/2 < mass C L := lt_of_not_ge hn + have hLn : L.Nonempty := by + by_contra he + rw [Finset.not_nonempty_iff_eq_empty.mp he] at hL + norm_num [mass] at hL + obtain ⟨y,hy,hymax⟩ := Finset.exists_max_image L f hLn + have hyx : f y < f x := (Finset.mem_filter.mp hy).2 + have he : (Finset.univ.filter fun z => f z ≤ f y) = L := by + ext z + simp only [L,Finset.mem_filter,Finset.mem_univ,true_and] + exact ⟨fun hz => hz.trans_lt hyx,fun hz => hymax z (Finset.mem_filter.mpr ⟨Finset.mem_univ _,hz⟩)⟩ + have hyM : y ∈ M := by + apply Finset.mem_filter.mpr + refine ⟨Finset.mem_univ _,?_⟩ + rw [he] + exact hL.le + exact (not_lt_of_ge (hmin y hyM)) hyx + · have he : (Finset.univ.filter fun y => f y ≤ f x)ᶜ = + Finset.univ.filter (fun y => f x < f y) := by + ext y + simp + have h := mass_compl C (Finset.univ.filter fun y => f y ≤ f x) + rw [he] at h + linarith + +theorem variance_le_centered (f : X → ℝ) (a : ℝ) : + C.variance f ≤ ∑ x, C.π x*(f x-a)^2 := by + have he : (∑ x, C.π x*(f x-a)^2) = C.inner f f-2*a*C.mean f+a^2 := by + calc + _ = (∑ x, C.π x*f x*f x)-2*a*(∑ x,C.π x*f x)+a^2*(∑ x,C.π x) := by + simp only [Finset.mul_sum,← Finset.sum_sub_distrib,← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + ring + _ = _ := by rw [C.normalized,mul_one]; rfl + rw [C.variance_formula,he] + nlinarith [sq_nonneg (C.mean f-a)] + +end +end ContingencyTables.CheegerProof + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerPositive.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerPositive.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ebbb2c6f67cc86bf31125393789cac2798d1cc0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/CheegerPositive.lean @@ -0,0 +1,96 @@ +import OAI.Combinatorics.ContingencyTables.Dense.CheegerCoarea + +namespace OAI + +/-! # Cheeger energy bound for functions supported on half the mass -/ +namespace ContingencyTables.CheegerProof +open CommonBasesFPRAS +open scoped BigOperators Classical +noncomputable section + +private lemma weighted_cauchy {ι : Type*} [Fintype ι] + (w a b : ι → ℝ) (hw : ∀ i, 0 ≤ w i) : + (∑ i, w i*a i*b i)^2 ≤ (∑ i, w i*(a i)^2)*(∑ i, w i*(b i)^2) := by + have h := Finset.sum_mul_sq_le_sq_mul_sq Finset.univ + (fun i => Real.sqrt (w i)*a i) (fun i => Real.sqrt (w i)*b i) + have hmul (i : ι) : (Real.sqrt (w i)*a i)*(Real.sqrt (w i)*b i) = w i*a i*b i := by + calc + _ = (Real.sqrt (w i))^2*a i*b i := by ring + _ = _ := by rw [Real.sq_sqrt (hw i)] + have hsq (f : ι → ℝ) (i : ι) : (Real.sqrt (w i)*f i)^2 = w i*(f i)^2 := by + rw [mul_pow,Real.sq_sqrt (hw i)] + simpa only [hmul,hsq] using h + +variable {X : Type*} [Fintype X] (C : FiniteChain X) + +lemma sum_pair_squares (g : X → ℝ) : + (∑ x, ∑ y, C.π x*C.P x y*((g x)^2+(g y)^2)) = 2*(∑ x, C.π x*(g x)^2) := by + simp_rw [mul_add,Finset.sum_add_distrib] + have hleft : (∑ x, ∑ y, C.π x*C.P x y*(g x)^2) = ∑ x, C.π x*(g x)^2 := by + simp_rw [← Finset.sum_mul,← Finset.mul_sum,C.stochastic,mul_one] + have hright : (∑ x, ∑ y, C.π x*C.P x y*(g y)^2) = ∑ y, C.π y*(g y)^2 := by + rw [Finset.sum_comm] + simp_rw [← Finset.sum_mul,C.stationary] + rw [hleft,hright] + ring + +lemma sum_pair_add_square_le (g : X → ℝ) : + (∑ x, ∑ y, C.π x*C.P x y*(g x+g y)^2) ≤ 4*(∑ x, C.π x*(g x)^2) := by + calc + _ ≤ ∑ x, ∑ y, 2*(C.π x*C.P x y*((g x)^2+(g y)^2)) := by + apply Finset.sum_le_sum + intro x _ + apply Finset.sum_le_sum + intro y _ + have hQ := mul_nonneg (C.positive x).le (C.nonnegative x y) + have hsq : (g x+g y)^2 ≤ 2*((g x)^2+(g y)^2) := by nlinarith [sq_nonneg (g x-g y)] + nlinarith [mul_le_mul_of_nonneg_left hsq hQ] + _ = _ := by simp_rw [← Finset.mul_sum]; rw [sum_pair_squares]; ring + +theorem positive_energy (κ : ℝ) (hk : 0 < κ) + (hcut : ∀ S : Finset X, κ*min (mass C S) (mass C Sᶜ) ≤ cut C S) + (g : X → ℝ) (hg : ∀ x, 0 ≤ g x) + (hsmall : mass C (Finset.univ.filter fun x => 0 < g x) ≤ 1/2) : + κ^2*(∑ x, C.π x*(g x)^2) ≤ 2*C.energy g := by + let N := ∑ x, C.π x*(g x)^2 + let W := ∑ x, ∑ y, C.π x*C.P x y*|(g x)^2-(g y)^2| + have hE : 0 ≤ C.energy g := C.energy_nonneg g + have hN : 0 ≤ N := Finset.sum_nonneg fun x _ => mul_nonneg (C.positive x).le (sq_nonneg _) + have hW : 0 ≤ W := Finset.sum_nonneg fun x _ => Finset.sum_nonneg fun y _ => + mul_nonneg (mul_nonneg (C.positive x).le (C.nonnegative x y)) (abs_nonneg _) + have hsquare : mass C (Finset.univ.filter fun x => 0 < (g x)^2) ≤ 1/2 := by + apply le_trans (mass_mono C ?_) hsmall + intro x hx + simp only [Finset.mem_filter,Finset.mem_univ,true_and] at hx ⊢ + nlinarith [hg x] + have hc : 2*κ*N ≤ W := coarea C κ hcut (fun x => (g x)^2) (fun _ => sq_nonneg _) hsquare + have hsqW : (2*κ*N)^2 ≤ W^2 := (sq_le_sq₀ (by positivity) hW).mpr hc + have ha (x y : X) : |(g x)^2-(g y)^2| = |g x-g y| * (g x+g y) := by + rw [show (g x)^2-(g y)^2 = (g x-g y)*(g x+g y) by ring, + abs_mul,abs_of_nonneg (add_nonneg (hg x) (hg y))] + have hcs := weighted_cauchy + (fun z : X×X => C.π z.1*C.P z.1 z.2) + (fun z => |g z.1-g z.2|) (fun z => g z.1+g z.2) + (fun z => mul_nonneg (C.positive _).le (C.nonnegative _ _)) + simp only [Fintype.sum_prod_type,sq_abs] at hcs + have he : (∑ x, ∑ y, C.π x*C.P x y*(g x-g y)^2) = 2*C.energy g := by + rw [C.energy_eq]; ring + have hW' : W = ∑ x, ∑ y, C.π x*C.P x y*|g x-g y| * (g x+g y) := by + dsimp [W] + simp_rw [ha,mul_assoc] + rw [← hW',he] at hcs + have hb := sum_pair_add_square_le C g + have hall : (2*κ*N)^2 ≤ (2*C.energy g)*(4*N) := + (hsqW.trans hcs).trans (mul_le_mul_of_nonneg_left hb (by positivity : 0 ≤ 2*C.energy g)) + rcases hN.eq_or_lt with hz | hp + · change κ^2*N ≤ _ + rw [← hz,mul_zero] + positivity + · change κ^2*N ≤ _ + have h : 4*N*(κ^2*N) ≤ 4*N*(2*C.energy g) := by nlinarith [hall] + exact (mul_le_mul_iff_right₀ (by positivity : 0 < 4*N)).mp h + +end +end ContingencyTables.CheegerProof + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAcceptance.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..13d2ce7534d40f86e8c79121732b14e6e4210747 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAcceptance.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseGoodBins + +namespace OAI + +/-! # Constant stationary mass of wholly feasible dense bins -/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators ENNReal Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +/-- Every within-bin offset in these bins is feasible. Their stationary +mass is at least 1/32, and hence at least the paper's claimed 1/64. -/ +theorem dense_good_bin_probability (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) : + (1 / 32 : ℝ) ≤ + (∑ a ∈ goodBins R P d e (K := 4 * d ^ 8), denseBinWeight R P d e a) / + (∑ a : Grid (I := Fin q) (4 * d ^ 8), denseBinWeight R P d e a) := by + let V := volume {x | denseGridFeasible R P d e x} + let G := goodBins R P d e (K := 4 * d ^ 8) + let Z := ∑ a : Grid (I := Fin q) (4 * d ^ 8), denseBinWeight R P d e a + have hV : V ≠ ⊤ := by + dsimp [V] + rw [denseGridFeasible_volume] + exact (DenseAffine.dense_feasible_compact R P d hd hR hP htotal).measure_ne_top + have hG : V.toReal / 2 ≤ (G.card : ℝ) := by + have h := ENNReal.toReal_mono (by simp) + (goodBins_volume_lower R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e) + simpa only [ENNReal.toReal_mul, ENNReal.toReal_div, ENNReal.toReal_one, + ENNReal.toReal_ofNat, ENNReal.toReal_natCast, one_div_mul_eq_div] using h + have hZ : Z ≤ 16 * V.toReal := by + have h := ENNReal.toReal_mono (ENNReal.mul_ne_top (by norm_num) hV) + (denseBin_normalizer_bound R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e) + have hznonneg : 0 ≤ Z := Finset.sum_nonneg + (fun a _ => (DenseWeights.binWeight_pos _ _ _).le) + change (ENNReal.ofReal Z).toReal ≤ (16 * V).toReal at h + simpa only [ENNReal.toReal_ofReal hznonneg, ENNReal.toReal_mul, ENNReal.toReal_ofNat] using h + have hK := denseGridSize_pos d hd + let : Nonempty (Grid (I := Fin q) (4 * d ^ 8)) := + ⟨fun _ => ⟨0, by constructor <;> omega⟩⟩ + have hZpos : 0 < Z := Finset.sum_pos (fun a _ => DenseWeights.binWeight_pos _ _ _) Finset.univ_nonempty + have hsum : (∑ a ∈ G, denseBinWeight R P d e a) = G.card := by + calc + _ = ∑ _a ∈ G, (1 : ℝ) := by + apply Finset.sum_congr rfl + intro a ha + exact goodBin_weight_one R P d hd hR hP hRmax hPmax hfree e a (Finset.mem_filter.mp ha).2 + _ = _ := by simp only [Finset.sum_const, nsmul_eq_mul, mul_one] + change (1 / 32 : ℝ) ≤ (∑ a ∈ G, denseBinWeight R P d e a) / Z + rw [hsum] + apply (le_div_iff₀ hZpos).mpr + linarith + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAffine.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAffine.lean new file mode 100644 index 0000000000000000000000000000000000000000..a04f9431614a5f86fd1d85a56b6264d1947074b7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAffine.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Transport.AffinePenalty +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Algebra.BigOperators.Field + +namespace OAI + +/-! +# Free coordinates of a dense completion block + +`none` denotes the pivot row or column. The free coordinates are the other +cells. These are the manuscript's actual affine completion formulas; the +row and column constraints hold identically, and feasible tables are +uniquely determined by their free cells. +-/ + +namespace ContingencyTables.DenseAffine + +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] + +def table (R : Option I → ℝ) (P : Option J → ℝ) (w : I → J → ℝ) + (u : I × J → ℝ) : Option I → Option J → ℝ + | some i, some j => w i j * u (i, j) + | some i, none => R (some i) - ∑ j, w i j * u (i, j) + | none, some j => P (some j) - ∑ i, w i j * u (i, j) + | none, none => R none - ∑ j, P (some j) + ∑ i, ∑ j, w i j * u (i, j) + +theorem table_rows (R : Option I → ℝ) (P : Option J → ℝ) (w : I → J → ℝ) + (u : I × J → ℝ) (i : Option I) : ∑ j, table R P w u i j = R i := by + rw [Fintype.sum_option] + cases i with + | some i => simp only [table]; ring + | none => + simp only [table, Finset.sum_sub_distrib] + rw [Finset.sum_comm (f := fun i j => w i j * u (i, j))] + ring + +theorem table_columns (R : Option I → ℝ) (P : Option J → ℝ) (w : I → J → ℝ) + (u : I × J → ℝ) (htotal : ∑ i, R i = ∑ j, P j) (j : Option J) : + ∑ i, table R P w u i j = P j := by + rw [Fintype.sum_option] + cases j with + | some j => simp only [table]; ring + | none => + simp only [table, Finset.sum_sub_distrib] + simp only [Fintype.sum_option] at htotal + linarith + +theorem table_unique (X Y : Option I → Option J → ℝ) + (hrows : ∀ i, ∑ j, X i j = ∑ j, Y i j) + (hcols : ∀ j, ∑ i, X i j = ∑ i, Y i j) + (hfree : ∀ i j, X (some i) (some j) = Y (some i) (some j)) : X = Y := by + have hr (i : I) : X (some i) none = Y (some i) none := by + have h := hrows (some i) + simp only [Fintype.sum_option, hfree] at h + linarith + have hc (j : J) : X none (some j) = Y none (some j) := by + have h := hcols (some j) + simp only [Fintype.sum_option, hfree] at h + linarith + have hnn : X none none = Y none none := by + have h := hrows none + simp only [Fintype.sum_option, hc] at h + linarith + funext i j + cases i <;> cases j + · exact hnn + · exact hc _ + · exact hr _ + · exact hfree _ _ + +/-- Recover an actual table from its scaled free coordinates. -/ +theorem table_recover (R : Option I → ℝ) (P : Option J → ℝ) (w : I → J → ℝ) + (hw : ∀ i j, w i j ≠ 0) (X : Option I → Option J → ℝ) + (hR : ∀ i, ∑ j, X i j = R i) (hP : ∀ j, ∑ i, X i j = P j) : + table R P w (fun p => X (some p.1) (some p.2) / w p.1 p.2) = X := by + have htotal : ∑ i, R i = ∑ j, P j := by + simp_rw [← hR, ← hP] + exact Finset.sum_comm + apply table_unique + · intro i + rw [table_rows, hR] + · intro j + rw [table_columns _ _ _ _ htotal, hP] + · intro i j + simp only [table] + exact mul_div_cancel₀ _ (hw i j) + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisBits.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d6768eb465eb8372e7ec6f28c305df24eadb461 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisBits.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseAxisProposal +import OAI.Combinatorics.ContingencyTables.Dense.GridMetropolis +import Mathlib.Logic.Equiv.Fin.Basic + +namespace OAI + +/-! # Exact proposal frequencies from a bounded fair-bit integer -/ + +namespace ContingencyTables.GridBoundary + +open scoped Classical + +def directionCodeEquiv (q : ℕ) : Fin q × Bool ≃ Fin (q * 2) := + (Equiv.prodCongr (Equiv.refl (Fin q)) finTwoEquiv.symm).trans finProdFinEquiv + +def axisCodeStep {q K M : ℕ} (a : Grid (I := Fin q) K) (z : Fin M) : + Option (Grid (I := Fin q) K) := + if hz : z.val < q * 2 then + let dir := (directionCodeEquiv q).symm ⟨z.val, hz⟩ + axisStep a dir.1 dir.2 + else none + +theorem axisCodeStep_sound {q K M : ℕ} (a b : Grid (I := Fin q) K) (z : Fin M) + (h : axisCodeStep a z = some b) : Neighbor a b := by + unfold axisCodeStep at h + split_ifs at h with hz + exact ⟨_, _, axisStep_sound _ _ _ _ h⟩ + +theorem axisCodeStep_unique {q K M : ℕ} (a b : Grid (I := Fin q) K) + (z z' : Fin M) (h : axisCodeStep a z = some b) (h' : axisCodeStep a z' = some b) : z = z' := by + unfold axisCodeStep at h h' + split_ifs at h with hz + split_ifs at h' with hz' + have hd := oriented_direction_unique a b _ _ _ _ + (axisStep_sound _ _ _ _ h) (axisStep_sound _ _ _ _ h') + have he := congrArg (directionCodeEquiv q) hd + have he' : (⟨z.val, hz⟩ : Fin (q * 2)) = ⟨z'.val, hz'⟩ := by + simpa only [Prod.mk.eta, Equiv.apply_symm_apply] using he + exact Fin.ext (congrArg (fun x : Fin (q * 2) => x.val) he') + +theorem axisCodeStep_exists {q K M : ℕ} (hM : q * 2 ≤ M) + (a b : Grid (I := Fin q) K) (h : Neighbor a b) : + ∃ z : Fin M, axisCodeStep a z = some b := by + obtain ⟨i, sign, hi⟩ := h + let dir := directionCodeEquiv q (i, sign) + let z : Fin M := ⟨dir.val, dir.isLt.trans_le hM⟩ + refine ⟨z, ?_⟩ + unfold axisCodeStep + have hz : z.val < q * 2 := dir.isLt + rw [dite_eq_left hz] + change axisStep a ((directionCodeEquiv q).symm dir).1 + ((directionCodeEquiv q).symm dir).2 = some b + rw [Equiv.symm_apply_apply] + exact axisStep_complete a b i sign hi + +/-- Every valid signed direction has exactly one fair-bit integer code; +all unused codes and boundary steps are rejected. -/ +theorem axisCodeStep_count {q K M : ℕ} (hM : q * 2 ≤ M) + (a b : Grid (I := Fin q) K) : + (Finset.univ.filter (fun z : Fin M => axisCodeStep a z = some b)).card = + if Neighbor a b then 1 else 0 := by + by_cases hab : Neighbor a b + · rw [ite_eq_left hab, Finset.card_eq_one_iff_existsUnique] + obtain ⟨z, hz⟩ := axisCodeStep_exists hM a b hab + refine ⟨z, by simpa, ?_⟩ + intro z' hz' + exact axisCodeStep_unique a b z' z (by simpa using hz') hz + · rw [ite_eq_right hab, Finset.card_eq_zero] + apply Finset.eq_empty_iff_forall_notMem.mpr + intro z hz + exact hab (axisCodeStep_sound a b z (by simpa using hz)) + +theorem dense_proposal_code_bound (d q : ℕ) (hq : q ≤ d) : + q * 2 ≤ 2 ^ Nat.clog 2 (8 * d) := by + exact (by omega : q * 2 ≤ 8 * d).trans (Nat.le_pow_clog (by decide) (8 * d)) + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc7f2826fc948dd4aab498ab9bc6476321948a5c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisProgram.lean @@ -0,0 +1,73 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeProgram +import OAI.Combinatorics.ContingencyTables.Machines.ListWordProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseAxisProposal + +namespace OAI + +/-! # Bounded binary coordinate moves in the dense grid -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms + +abbrev AxisData := ((ℕ×List ℕ)×ℕ)×Bool + +def axisListStep (z : AxisData) : Option (List ℕ) := + let K := z.1.1.1 + let xs := z.1.1.2 + let i := z.1.2 + if i z.1.1.1) := + composition (composition first first) first + let X : Realizer (fun z : AxisData => z.1.1.2) := + composition (composition first first) second + let I : Realizer (fun z : AxisData => z.1.2) := composition first second + let L := composition X listLength + let V := composition (pair X I) (getDFast 0) + let up := composition (composition (pair X (pair I L)) listExchangeRealizer) TreeTyped.some + let down := composition (composition (pair X (pair L I)) listExchangeRealizer) TreeTyped.some + exact (choose (composition (pair I L) less) + (choose second (choose (composition (pair (composition V successor) K) less) + up (constant none)) + (choose (composition (pair (constant 0) V) less) down (constant none))) + (constant none)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq,axisListStep]) + +/-- An invalid or boundary move terminates immediately. Its index is +never used as an iteration count. -/ +theorem polynomial_axisListStep : PolynomialTime axisListStepRealizer := by + have hK : PolynomialTime (composition + (composition (first (A := (ℕ×List ℕ)×ℕ) (B := Bool)) first) first) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first + have hX : PolynomialTime (composition + (composition (first (A := (ℕ×List ℕ)×ℕ) (B := Bool)) first) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + have hI : PolynomialTime (composition + (first (A := (ℕ×List ℕ)×ℕ) (B := Bool)) second) := + polynomial_composition polynomial_first polynomial_second + have hL := polynomial_composition hX polynomial_listLength + have hV := polynomial_composition (polynomial_pair hX hI) (polynomial_getDFast 0) + have hup := polynomial_composition (polynomial_composition + (polynomial_pair hX (polynomial_pair hI hL)) polynomial_listExchange) polynomial_some + have hdown := polynomial_composition (polynomial_composition + (polynomial_pair hX (polynomial_pair hL hI)) polynomial_listExchange) polynomial_some + unfold axisListStepRealizer + exact polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair hI hL) polynomial_less) + (polynomial_choose polynomial_second + (polynomial_choose (polynomial_composition (polynomial_pair + (polynomial_composition hV polynomial_successor) hK) polynomial_less) + hup (polynomial_constant none)) + (polynomial_choose (polynomial_composition (polynomial_pair (polynomial_constant 0) hV) + polynomial_less) hdown (polynomial_constant none))) (polynomial_constant none)) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisProposal.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisProposal.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2ec91b387d5b5333ed6b3e44380e68a927263c3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisProposal.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridAdjacency + +namespace OAI + +/-! # Integer signed-coordinate proposals for the dense grid -/ + +namespace ContingencyTables.GridBoundary + +open scoped Classical + +variable {I : Type*} [DecidableEq I] {K : ℕ} + +/-- A signed step is rejected at the boundary of the declared finite grid. -/ +def axisStep (a : Grid (I := I) K) (i : I) (sign : Bool) : Option (Grid (I := I) K) := + if sign then + if h : corner a i + 1 ≤ (K : ℤ) - 1 then + some (Function.update a i ⟨corner a i + 1, by + constructor + · have ha : 0 ≤ corner a i := (a i).property.1; omega + · exact h⟩) + else none + else + if h : 0 ≤ corner a i - 1 then + some (Function.update a i ⟨corner a i - 1, by + constructor + · exact h + · have ha : corner a i ≤ (K : ℤ) - 1 := (a i).property.2; omega⟩) + else none + +theorem axisStep_sound (a b : Grid (I := I) K) (i : I) (sign : Bool) + (h : axisStep a i sign = some b) : OrientedNeighbor a b i sign := by + cases sign + · unfold axisStep at h + simp only [Bool.false_eq_true, ite_false] at h + split_ifs at h with hc + · have hb := Option.some.inj h + rw [← hb] + change IsGridEdge _ + constructor + · simp only [corner, Function.update_self] + omega + · intro j hj + change j ≠ i at hj + simp [Function.update_of_ne hj] + · unfold axisStep at h + simp only [ite_true] at h + split_ifs at h with hc + · have hb := Option.some.inj h + rw [← hb] + change IsGridEdge _ + constructor + · simp [corner] + · intro j hj + change j ≠ i at hj + simp [Function.update_of_ne hj] + +theorem axisStep_complete (a b : Grid (I := I) K) (i : I) (sign : Bool) + (h : OrientedNeighbor a b i sign) : axisStep a i sign = some b := by + cases sign + · change IsGridEdge (b, a, i) at h + have hc : 0 ≤ corner a i - 1 := by + have := (b i).property.1 + have he := h.1 + change corner a i = corner b i + 1 at he + change 0 ≤ corner b i at this + omega + unfold axisStep + simp only [Bool.false_eq_true, ite_false, dite_eq_left hc, Option.some.injEq] + funext j + apply Subtype.ext + by_cases hj : j = i + · subst j + simp only [Function.update_self] + have he := h.1 + change corner a i = corner b i + 1 at he + change corner a i - 1 = corner b i + omega + · simp only [Function.update_of_ne hj] + exact congrArg Subtype.val (h.2 j hj) + · change IsGridEdge (a, b, i) at h + have hc : corner a i + 1 ≤ (K : ℤ) - 1 := by + have := (b i).property.2 + have he := h.1 + change corner b i = corner a i + 1 at he + change corner b i ≤ (K : ℤ) - 1 at this + omega + unfold axisStep + simp only [ite_true, dite_eq_left hc, Option.some.injEq] + funext j + apply Subtype.ext + by_cases hj : j = i + · subst j + simp only [Function.update_self] + exact h.1.symm + · simp only [Function.update_of_ne hj] + exact congrArg Subtype.val (h.2 j hj).symm + +theorem axisStep_some_iff (a b : Grid (I := I) K) (i : I) (sign : Bool) : + axisStep a i sign = some b ↔ OrientedNeighbor a b i sign := + ⟨axisStep_sound a b i sign, axisStep_complete a b i sign⟩ + +/-- Each neighbouring bin has exactly one signed-coordinate proposal. -/ +theorem oriented_direction_unique (a b : Grid (I := I) K) (i j : I) (s t : Bool) + (hi : OrientedNeighbor a b i s) (hj : OrientedNeighbor a b j t) : (i, s) = (j, t) := by + have hij : i = j := by + by_contra hne + have he : corner a i = corner b i := by + cases t + · exact congrArg Subtype.val (hj.2 i hne) + · exact (congrArg Subtype.val (hj.2 i hne)).symm + cases s + · have hp := hi.1 + change corner a i = corner b i + 1 at hp + omega + · have hp := hi.1 + change corner b i = corner a i + 1 at hp + omega + subst j + have hst : s = t := by + cases s <;> cases t + · rfl + · have h₁ := hi.1 + have h₂ := hj.1 + change corner a i = corner b i + 1 at h₁ + change corner b i = corner a i + 1 at h₂ + omega + · have h₁ := hi.1 + have h₂ := hj.1 + change corner b i = corner a i + 1 at h₁ + change corner a i = corner b i + 1 at h₂ + omega + · rfl + subst t + rfl + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..666080e92f66955d39cefdc2efdb1267cfc64737 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseAxisSemantics.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseAxisProgram + +namespace OAI + +/-! # Natural coordinate encodings of dense axis moves -/ + +namespace ContingencyTables.DensePrograms +open ProfilePrograms GridBoundary +open scoped Classical + +lemma listExchange_increment {q : ℕ} (v : Fin q → ℕ) (i : Fin q) : + listExchange (List.ofFn v,(i.val,q))= + List.ofFn (Function.update v i (v i+1)) := by + apply List.ext_getElem + · simp only [listExchange,List.length_map,List.length_range,List.length_ofFn] + · intro j hj _ + have hjq : j hji (Fin.ext h) + simp only [hne,ite_false,Nat.add_zero,Function.update_of_ne hji] + +lemma listExchange_decrement {q : ℕ} (v : Fin q → ℕ) (i : Fin q) : + listExchange (List.ofFn v,(q,i.val))= + List.ofFn (Function.update v i (v i-1)) := by + apply List.ext_getElem + · simp only [listExchange,List.length_map,List.length_range,List.length_ofFn] + · intro j hj _ + have hjq : j hji (Fin.ext h) + simp only [hne,ite_false,Nat.sub_zero,Function.update_of_ne hji] + +def gridNatCode {q K : ℕ} (a : Grid (I := Fin q) K) : List ℕ := + List.ofFn (fun i => (corner a i).toNat) + +lemma gridNatCode_getD {q K : ℕ} (a : Grid (I := Fin q) K) (i : Fin q) : + (gridNatCode a).getD i.val 0=(corner a i).toNat := by + simp only [gridNatCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt, + dite_true,Option.getD_some,Fin.eta] + +lemma gridNatCode_update {q K : ℕ} (a : Grid (I := Fin q) K) (i : Fin q) + (v : Set.Icc (0 : ℤ) ((K : ℤ)-1)) : + gridNatCode (Function.update a i v)= + List.ofFn (Function.update (fun j => (corner a j).toNat) i v.val.toNat) := by + apply congrArg List.ofFn + funext j + by_cases hji : j=i + · subst j + simp only [Function.update_self,corner] + · simp only [Function.update_of_ne hji,corner] + +/-- The bounded list operation implements exactly the signed geometric +axis proposal, including both boundary rejections. -/ +theorem axisListStep_eq {q K : ℕ} (a : Grid (I := Fin q) K) (i : Fin q) (sign : Bool) : + axisListStep (((K,gridNatCode a),i.val),sign)= + (axisStep a i sign).map gridNatCode := by + have hlen : (gridNatCode a).length=q := by simp only [gridNatCode,List.length_ofFn] + have hnonneg : 0≤corner a i := (a i).property.1 + have hupper : corner a i≤(K : ℤ)-1 := (a i).property.2 + have hcast : ((corner a i).toNat : ℤ)=corner a i := Int.toNat_of_nonneg hnonneg + cases sign with + | false => + simp only [axisListStep,hlen,i.isLt,ite_true,Bool.false_eq_true,ite_false, + gridNatCode_getD,axisStep] + by_cases h : 0≤corner a i-1 + · have hn : 0<(corner a i).toNat := by omega + rw [ite_eq_left hn,dite_eq_left h,Option.map_some] + let v : Set.Icc (0 : ℤ) ((K : ℤ)-1) := ⟨corner a i-1,h,by omega⟩ + have hc := gridNatCode_update a i v + have he : v.val.toNat=(corner a i).toNat-1 := by dsimp only [v]; omega + rw [he] at hc + exact congrArg some ((listExchange_decrement (fun j => (corner a j).toNat) i).trans hc.symm) + · have hn : ¬0<(corner a i).toNat := by omega + rw [ite_eq_right hn,dite_eq_right h,Option.map_none] + | true => + simp only [axisListStep,hlen,i.isLt,ite_true,gridNatCode_getD,axisStep] + by_cases h : corner a i+1≤(K : ℤ)-1 + · have hn : (corner a i).toNat+1 (corner a j).toNat) i).trans hc.symm) + · have hn : ¬(corner a i).toNat+1 StackAddition.value z.2) := composition second bitValue + let I := composition (pair V (constant 2)) quotient + let S := composition (pair (composition (pair V (constant 2)) remainder) (constant 1)) natEqual + exact composition (pair (pair first I) S) axisListStepRealizer + +theorem polynomial_axisWordStep : PolynomialTime axisWordStepRealizer := by + have hv : PolynomialTime (composition + (second (A := ℕ×List ℕ) (B := List Bool)) bitValue) := + polynomial_composition polynomial_second polynomial_bitValue + have hi := polynomial_composition (polynomial_pair hv (polynomial_constant 2)) polynomial_quotient + have hs := polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair hv (polynomial_constant 2)) polynomial_remainder) + (polynomial_constant 1)) polynomial_natEqual + unfold axisWordStepRealizer + exact polynomial_composition (polynomial_pair (polynomial_pair polynomial_first hi) hs) + polynomial_axisListStep + +lemma directionCode_first {q : ℕ} (v : Fin (q*2)) : + ((directionCodeEquiv q).symm v).1.val=v.val/2 := rfl + +lemma directionCode_second {q : ℕ} (v : Fin (q*2)) : + ((directionCodeEquiv q).symm v).2=decide (v.val%2=1) := by + have hf (b : Fin 2) : finTwoEquiv b=decide (b.val=1) := by + fin_cases b <;> rfl + exact hf _ + +/-- A binary index gives exactly the signed coordinate code used by +the finite dense-chain transition; unused indices still reject. -/ +theorem axisWordStep_eq {q K k : ℕ} (a : Grid (I := Fin q) K) (bits : Fin k → Bool) : + axisWordStep ((K,gridNatCode a),List.ofFn bits)= + (axisCodeStep a (FairBits.binaryWordEquiv k bits)).map gridNatCode := by + rw [axisWordStep,bitValue_eq_word] + let v := FairBits.binaryWordEquiv k bits + change axisListStep (((K,gridNatCode a),v.val/2),decide (v.val%2=1))= + (axisCodeStep a v).map gridNatCode + by_cases hv : v.val trialSuccess R P d e htotal (denseBooleanTrial R P d hd hR hP e h a word)) + fallback (d ^ 4 * (h + 1)) (gridWordEquiv (d ^ 4 * (h + 1)) (denseTrialBits R P d e h) bits) + +def denseBooleanDrawLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (htotal : ∑ i, R i = ∑ j, P j) (h : ℕ) + (a : Grid (I := Fin q) (4 * d ^ 8)) (fallback : Table R P) : RationalLaw (Table R P) := + mapLaw (uniformLaw (α := Fin (denseDrawBits R P d e h) → Bool)) + (denseBooleanDraw R P d hd hR hP e htotal h a fallback) + +theorem denseBooleanDrawLaw_eq (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (h : ℕ) (a : Grid (I := Fin q) (4 * d ^ 8)) (fallback : Table R P) : + denseBooleanDrawLaw R P d hd hR hP e htotal h a fallback = + denseBoundedLaw R P d hd hR hP hfree e htotal h a fallback := by + unfold denseBooleanDrawLaw denseBooleanDraw + change mapLaw (uniformLaw (α := Fin ((d^4*(h+1))*denseTrialBits R P d e h) → Bool)) + (fun bits => wordRetry + (fun word => trialSuccess R P d e htotal (denseBooleanTrial R P d hd hR hP e h a word)) + fallback (d^4*(h+1)) (gridWordEquiv (d^4*(h+1)) (denseTrialBits R P d e h) bits)) = _ + rw [← map_equiv (gridWordEquiv (d ^ 4 * (h + 1)) (denseTrialBits R P d e h)), uniform_equiv] + change wordRetryLaw + (fun word => trialSuccess R P d e htotal (denseBooleanTrial R P d hd hR hP e h a word)) + fallback (d ^ 4 * (h + 1)) = _ + rw [wordRetryLaw_eq, ← retryLaw_map, + denseBooleanTrialLaw_eq R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e h a] + rfl + +/-- The actual finite Boolean draw always has codomain the feasible tables +and its law satisfies the desired dense approximation guarantee. -/ +theorem denseBooleanDraw_variation (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4 * d ^ 8))) + (h : ℕ) (a : Grid (I := Fin q) (4 * d ^ 8)) (fallback : Table R P) : + let _ : Nonempty (Table R P) := ⟨fallback⟩ + (variation (denseBooleanDrawLaw R P d hd hR hP e htotal h a fallback) + (uniformLaw (α := Table R P)) : ℝ) ≤ (2 : ℝ) ^ (-(h : ℝ)) := by + let : Nonempty (Table R P) := ⟨fallback⟩ + rw [denseBooleanDrawLaw_eq R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e h a fallback] + exact denseBoundedLaw_variation R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal + e hPL hCheeger h a fallback + +omit [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] in +/-- The full Boolean source has polynomial length in the declared dense +parameters. -/ +theorem denseDrawBits_polynomial (R : Option I → ℕ) (P : Option J → ℕ) + (d C b h : ℕ) (e : I × J ≃ Fin q) (hq : q ≤ d) + (hwidth : ∀ p, integerWidth R P d p ≤ C) (hb : Nat.clog 2 (C + 2) ≤ b) : + denseDrawBits R P d e h ≤ 25 * (d + b + h + 1) ^ 62 := by + have hoff : (∑ j : Fin q, offsetBitLength (integerWidth R P d (e.symm j)) h d) ≤ + d * (b + 1 + 4 * (h + d)) := by + calc + _ ≤ ∑ _j : Fin q, (b + 1 + 4 * (h + d)) := + Finset.sum_le_sum (fun j _ => denseOffsetBits_upper _ C b h d (hwidth _) hb) + _ = q * (b + 1 + 4 * (h + d)) := by simp + _ ≤ _ := Nat.mul_le_mul_right _ hq + apply (show denseDrawBits R P d e h ≤ denseRandomBitBudget d b h from ?_).trans + (denseRandomBitBudget_polynomial d b h) + unfold denseDrawBits denseTrialBits denseRandomBitBudget + exact Nat.mul_le_mul_left _ (Nat.add_le_add_left hoff _) + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanOffsets.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanOffsets.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd6a55a79814d74c36e50bae5f5dd8461db62d2d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanOffsets.lean @@ -0,0 +1,48 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseBoundedTrial +import OAI.Combinatorics.ContingencyTables.Transport.FiniteScaledDraw +import OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts + +namespace OAI + +/-! # Independent actual Boolean offset draws realize the bounded offset law -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess FairBits + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] {q : ℕ} + +abbrev OffsetWords (e : I × J ≃ Fin q) (w : I × J → ℕ) (h d : ℕ) := + ∀ j : Fin q, Fin (offsetBitLength (w (e.symm j)) h d) → Bool + +def drawOffsetWords (e : I × J ≃ Fin q) (w : I × J → ℕ) + (hw : ∀ p, 0 < w p) (h d : ℕ) (bits : OffsetWords e w h d) : Offset w := + offsetCoordinateEquiv e w (fun j => + scaledBitInteger (w (e.symm j)) (offsetBitLength (w (e.symm j)) h d) (hw _) (bits j)) + +/-- Every coordinate uses its declared independent bounded Boolean word; +the resulting offset vector has the bounded quotient-offset law. -/ +theorem drawOffsetWordsLaw_eq (e : I × J ≃ Fin q) (w : I × J → ℕ) + [DecidableEq (Offset w)] + (hw : ∀ p, 0 < w p) (h d : ℕ) : + mapLaw (uniformLaw (α := OffsetWords e w h d)) (drawOffsetWords e w hw h d) = + boundedOffsetLaw e w hw h d := by + unfold drawOffsetWords boundedOffsetLaw + refine (mapLaw_equiv_output (offsetCoordinateEquiv e w) + (uniformLaw (α := OffsetWords e w h d)) (fun bits j => + scaledBitInteger (w (e.symm j)) (offsetBitLength (w (e.symm j)) h d) (hw _) + (bits j))).trans ?_ + congr 1 + rw [← pi_uniformLaw, pi_mapLaw] + congr 1 + funext j + exact scaledBitIntegerLaw_eq (w (e.symm j)) (offsetBitLength (w (e.symm j)) h d) (hw _) + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanStep.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanStep.lean new file mode 100644 index 0000000000000000000000000000000000000000..041c8df168b87df5bc443bfa49b96f89f4f2cdd5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanStep.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseFiniteTransition +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits + +namespace OAI + +/-! # A fixed Boolean word realizes each exact dense transition -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess FairBits + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def denseStepBits (d : ℕ) : ℕ := Nat.clog 2 (8 * d) + 8 * d ^ 5 + +def denseBitStep (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) + (bits : Fin (denseStepBits d) → Bool) : Grid (I := Fin q) (4 * d ^ 8) := + let z := pairWordEquiv (Nat.clog 2 (8 * d)) (8 * d ^ 5) bits + match axisCodeStep a z.1 with + | none => a + | some b => if z.2.val < 2 ^ (8 * d ^ 5 - (denseExponent R P d e b - denseExponent R P d e a)) + then b else a + +def denseBitStepLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + RationalLaw (Grid (I := Fin q) (4 * d ^ 8)) := + mapLaw (uniformLaw (α := Fin (denseStepBits d) → Bool)) (denseBitStep R P d e a) + +omit [DecidableEq I] [DecidableEq J] in +theorem denseBitStepLaw_eq_finite (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + denseBitStepLaw R P d e a = finiteDenseStepLaw R P d e a := by + let E := pairWordEquiv (Nat.clog 2 (8 * d)) (8 * d ^ 5) + let f := finiteAcceptStep a + (fun z : Fin (2 ^ Nat.clog 2 (8 * d)) => axisCodeStep a z) + (fun b => FairBits.acceptDyadic + (denseExponent R P d e b - denseExponent R P d e a) (8 * d ^ 5)) + have hf : denseBitStep R P d e a = fun bits => f (E bits) := by + funext bits + dsimp [denseBitStep, f, E, finiteAcceptStep] + simp only [FairBits.acceptDyadic] + cases axisCodeStep a ((pairWordEquiv (Nat.clog 2 (8 * d)) (8 * d ^ 5)) bits).1 with + | none => rfl + | some b => dsimp only; split_ifs <;> rfl + unfold denseBitStepLaw + rw [hf] + change mapLaw (uniformLaw (α := Fin (Nat.clog 2 (8 * d) + 8 * d ^ 5) → Bool)) + (fun bits => f (E bits)) = _ + rw [← map_equiv E, uniform_equiv] + rw [← uniform_product] + rfl + +/-- The declared q_bin+8d^5 independent unbiased bits implement exactly +the transition law whose mixing bound was proved. -/ +theorem denseBitStepLaw_eq (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + denseBitStepLaw R P d e a = rationalTransitionLaw R P d hd hfree e a := by + rw [denseBitStepLaw_eq_finite] + exact finiteDenseStepLaw_eq R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e a + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanTrial.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..5658ebb1dfe5f23b20986a8f6759c3569820bda8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanTrial.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalk +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanOffsets + +namespace OAI + +/-! # The full dense trial as one bounded unbiased Boolean word -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess FairBits + +noncomputable section + +def dependentWordEquiv {q : ℕ} (k : Fin q → ℕ) : + (Fin (∑ j, k j) → Bool) ≃ (∀ j, Fin (k j) → Bool) := + (Equiv.arrowCongr finSigmaFinEquiv.symm (Equiv.refl Bool)).trans (Equiv.piCurry (fun _ _ => Bool)) + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def denseTrialBits (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (h : ℕ) : ℕ := + (d ^ 50 * (h + 1) ^ 2) * denseStepBits d + + ∑ j : Fin q, offsetBitLength (integerWidth R P d (e.symm j)) h d + +def trialWordEquiv (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (h : ℕ) : (Fin (denseTrialBits R P d e h) → Bool) ≃ + ((Fin ((d ^ 50 * (h + 1) ^ 2) * denseStepBits d) → Bool) × + OffsetWords e (integerWidth R P d) h d) := + (splitWordEquiv _ _).trans (Equiv.prodCongr (Equiv.refl _) + (dependentWordEquiv (fun j => offsetBitLength (integerWidth R P d (e.symm j)) h d))) + +def denseBooleanTrial (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (h : ℕ) (a : Grid (I := Fin q) (4 * d ^ 8)) + (bits : Fin (denseTrialBits R P d e h) → Bool) : DenseTrial R P d q := + let z := trialWordEquiv R P d e h bits + (denseBooleanWalk R P d e a (d ^ 50 * (h + 1) ^ 2) z.1, + drawOffsetWords e (integerWidth R P d) (integerWidth_pos R P d hd hR hP) h d z.2) + +/-- This is the exact law of the full declared Boolean trial, including +all independent quotient offsets, before its integer acceptance test. -/ +theorem denseBooleanTrialLaw_eq (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (h : ℕ) (a : Grid (I := Fin q) (4 * d ^ 8)) : + mapLaw (uniformLaw (α := Fin (denseTrialBits R P d e h) → Bool)) + (denseBooleanTrial R P d hd hR hP e h a) = boundedTrialLaw R P d hd hR hP hfree e h a := by + unfold denseBooleanTrial + rw [← map_equiv (trialWordEquiv R P d e h) + (uniformLaw (α := Fin (denseTrialBits R P d e h) → Bool)) + (fun z => (denseBooleanWalk R P d e a (d ^ 50 * (h+1)^2) z.1, + drawOffsetWords e (integerWidth R P d) (integerWidth_pos R P d hd hR hP) h d z.2)), + uniform_equiv, ← uniform_product, mapLaw_product] + rw [show mapLaw (uniformLaw (α := Fin ((d ^ 50 * (h + 1) ^ 2) * denseStepBits d) → Bool)) + (denseBooleanWalk R P d e a (d ^ 50 * (h + 1) ^ 2)) = + rationalWalkLaw R P d hd hfree e (d ^ 50 * (h + 1) ^ 2) a from + denseBooleanWalkLaw_eq R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e a _] + unfold boundedTrialLaw + congr 1 + exact drawOffsetWordsLaw_eq e (integerWidth R P d) (integerWidth_pos R P d hd hR hP) h d + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanWalk.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..63842464801811acb227e1e4c8746a515d2a729e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanWalk.lean @@ -0,0 +1,52 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanStep +import OAI.Combinatorics.ContingencyTables.Dense.DenseFiniteWalk +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordWalk + +namespace OAI + +/-! # The dense bin draw as one bounded unbiased Boolean word -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess FairBits + +noncomputable section + +def gridWordEquiv (n k : ℕ) : (Fin (n * k) → Bool) ≃ (Fin n → Fin k → Bool) := + (Equiv.arrowCongr finProdFinEquiv.symm (Equiv.refl Bool)).trans (Equiv.curry _ _ _) + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def denseBooleanWalk (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) (n : ℕ) + (bits : Fin (n * denseStepBits d) → Bool) : Grid (I := Fin q) (4 * d ^ 8) := + wordWalk (denseBitStep R P d e) a n (gridWordEquiv n (denseStepBits d) bits) + +def denseBooleanWalkLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) (n : ℕ) : + RationalLaw (Grid (I := Fin q) (4 * d ^ 8)) := + mapLaw (uniformLaw (α := Fin (n * denseStepBits d) → Bool)) (denseBooleanWalk R P d e a n) + +/-- Exactly n*(q_bin+8d^5) unbiased bits give the rational n-step law. -/ +theorem denseBooleanWalkLaw_eq (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) (n : ℕ) : + denseBooleanWalkLaw R P d e a n = rationalWalkLaw R P d hd hfree e n a := by + have hk : (fun s => mapLaw (uniformLaw (α := Fin (denseStepBits d) → Bool)) (denseBitStep R P d e s)) = + finiteDenseStepLaw R P d e := funext (denseBitStepLaw_eq_finite R P d e) + unfold denseBooleanWalkLaw denseBooleanWalk + rw [← map_equiv (gridWordEquiv n (denseStepBits d)), uniform_equiv] + change wordWalkLaw (denseBitStep R P d e) a n = _ + rw [wordWalkLaw_eq, hk] + exact finiteDenseWalkLaw_eq R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e a n + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanWalkProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanWalkProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..2305ad520ea531dd70440a9caa716e5f5ec49b6c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseBooleanWalkProgram.lean @@ -0,0 +1,61 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseWalkSemantics + +namespace OAI + +/-! # A polynomial program for the complete flat-word dense walk -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped GridBoundary ProfilePrograms + +def denseWidthRealizer : Realizer denseStepBits := by + let index := composition (composition (pair (constant 8) identity) multiply) ceilLogTwoRealizer + let coins := composition (pair (constant 8) fifthPower) multiply + exact composition (pair index coins) add + +theorem polynomial_denseWidth : PolynomialTime denseWidthRealizer := by + unfold denseWidthRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_constant 8) polynomial_identity) polynomial_multiply) + polynomial_ceilLogTwo) + (polynomial_composition (polynomial_pair (polynomial_constant 8) polynomial_fifthPower) + polynomial_multiply)) polynomial_add + +def flatWordWalk (z : FlatExponentData×List Bool) : FlatExponentData := + walkWords (z.1,wordChunks (denseStepBits z.1.2,z.2)) + +def flatWordWalkRealizer : Realizer flatWordWalk := + composition (pair first (composition (pair + (composition (composition first second) denseWidthRealizer) second) wordChunksRealizer)) + walkWordsRealizer + +theorem polynomial_flatWordWalk : PolynomialTime flatWordWalkRealizer := + polynomial_composition (polynomial_pair polynomial_first (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_denseWidth) + polynomial_second) polynomial_wordChunks)) polynomial_walkWords + +lemma denseStepBits_pos {d : ℕ} (hd : 0 Fin (w p)) e).symm + +def boundedOffsetLaw (e : I × J ≃ Fin q) (w : I × J → ℕ) + (hw : ∀ p, 0 < w p) (h d : ℕ) : RationalLaw (Offset w) := + equivLaw (offsetCoordinateEquiv e w) + (piLaw (fun j => scaledLaw (w (e.symm j)) (offsetBitLength (w (e.symm j)) h d) (hw _))) + +def uniformOffsetLaw (e : I × J ≃ Fin q) (w : I × J → ℕ) + (hw : ∀ p, 0 < w p) : RationalLaw (Offset w) := + equivLaw (offsetCoordinateEquiv e w) (piLaw (fun j => uniformIntLaw (w (e.symm j)) (hw _))) + +theorem uniformOffsetLaw_mass (e : I × J ≃ Fin q) (w : I × J → ℕ) + (hw : ∀ p, 0 < w p) (o : Offset w) : + (uniformOffsetLaw e w hw).mass o = 1 / Fintype.card (Offset w) := by + have hc := Fintype.card_congr (offsetCoordinateEquiv e w) + simp only [Fintype.card_pi, Fintype.card_fin] at hc + change (∏ j : Fin q, (1 : ℚ) / w (e.symm j)) = _ + rw [Finset.prod_div_distrib, Finset.prod_const_one, ← Nat.cast_prod, hc] + simp [Offset] + +theorem boundedOffsetLaw_variation (e : I × J ≃ Fin q) (w : I × J → ℕ) + (hw : ∀ p, 0 < w p) (h d : ℕ) (hq : q ≤ d) : + variation (boundedOffsetLaw e w hw h d) (uniformOffsetLaw e w hw) ≤ + (d : ℚ) / (2 : ℚ) ^ (4 * (h + d)) := by + rw [boundedOffsetLaw, uniformOffsetLaw, variation_equiv] + exact dense_offset_product_variation q h d (fun j => w (e.symm j)) (fun j => hw _) hq + +def boundedTrialLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) (h : ℕ) + (a : Grid (I := Fin q) (4 * d ^ 8)) : RationalLaw (DenseTrial R P d q) := + productLaw (rationalWalkLaw R P d hd hfree e (d ^ 50 * (h + 1) ^ 2) a) + (boundedOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP) h d) + +theorem stationaryTrialLaw_eq (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) : + productLaw (rationalStationaryLaw R P d hd e) + (uniformOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP)) = + rationalTrialLaw R P d hd hR hP e := by + apply RationalLaw.ext + funext t + change (rationalStationaryLaw R P d hd e).mass t.1 * + (uniformOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP)).mass t.2 = _ + rw [uniformOffsetLaw_mass] + change (rationalBinWeight R P d e t.1 / ∑ b, rationalBinWeight R P d e b) * + (1 / Fintype.card (Offset (integerWidth R P d))) = rationalTrialMass R P d e t + unfold rationalTrialMass + ring + +theorem inverse_two_pow_cast (n : ℕ) : + ((1 / (2 : ℚ) ^ n : ℚ) : ℝ) = (2 : ℝ) ^ (-(n : ℝ)) := by + simp only [Rat.cast_div, Rat.cast_one, Rat.cast_pow, Rat.cast_ofNat] + rw [Real.rpow_neg (by norm_num), Real.rpow_natCast] + exact one_div _ + +/-- A complete finite dense trial has bin-mixing error plus the bounded +offset error, with the manuscript's actual walk and offset schedules. -/ +theorem boundedTrialLaw_variation (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4 * d ^ 8))) + (h : ℕ) (a : Grid (I := Fin q) (4 * d ^ 8)) : + (variation (boundedTrialLaw R P d hd hR hP hfree e h a) + (rationalTrialLaw R P d hd hR hP e) : ℝ) ≤ + (1 + (d : ℝ)) * (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) := by + have hq : q ≤ d := by + have hc := Fintype.card_congr e + rw [Fintype.card_fin] at hc + omega + have ho := boundedOffsetLaw_variation e (integerWidth R P d) + (integerWidth_pos R P d hd hR hP) h d hq + have hoc : (variation (boundedOffsetLaw e (integerWidth R P d) + (integerWidth_pos R P d hd hR hP) h d) + (uniformOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP)) : ℝ) ≤ + ((d : ℚ) / (2 : ℚ) ^ (4 * (h + d)) : ℚ) := by exact_mod_cast ho + have he : (((d : ℚ) / (2 : ℚ) ^ (4 * (h + d)) : ℚ) : ℝ) = + (d : ℝ) * (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) := by + rw [div_eq_mul_one_div, Rat.cast_mul, Rat.cast_natCast, inverse_two_pow_cast] + congr 2 + push_cast + ring + rw [he] at hoc + rw [← stationaryTrialLaw_eq R P d hd hR hP e] + unfold boundedTrialLaw + have hv := variation_product (rationalWalkLaw R P d hd hfree e (d ^ 50 * (h + 1) ^ 2) a) + (rationalStationaryLaw R P d hd e) + (boundedOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP) h d) + (uniformOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP)) + have hvc : (variation + (productLaw (rationalWalkLaw R P d hd hfree e (d ^ 50 * (h + 1) ^ 2) a) + (boundedOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP) h d)) + (productLaw (rationalStationaryLaw R P d hd e) + (uniformOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP))) : ℝ) ≤ + (variation (rationalWalkLaw R P d hd hfree e (d ^ 50 * (h + 1) ^ 2) a) + (rationalStationaryLaw R P d hd e) : ℝ) + + (variation (boundedOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP) h d) + (uniformOffsetLaw e (integerWidth R P d) (integerWidth_pos R P d hd hR hP)) : ℝ) := by + exact_mod_cast hv + have hm := rationalWalkLaw_variation R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal + e hPL hCheeger h a + exact hvc.trans (by nlinarith) + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCandidateCounts.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCandidateCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..819104704e2ed43a393481729dba043bebf04289 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCandidateCounts.lean @@ -0,0 +1,142 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CompletionEnumerationProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialCountProgram + +namespace OAI + +/-! # Exact accepted counts throughout the enumerated completion box -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary +open scoped BigOperators Classical + +abbrev TrialCountContext := (List ℕ×List Bool)×CanonicalParameters + +def candidateCountInput (z : TrialCountContext×MatrixCode) : TrialCountData := + (z.1.1,(((z.1.2.1,z.2),z.1.2.2.1),z.1.2.2.2)) + +def candidateCountInputRealizer : Realizer candidateCountInput := + pair (composition first first) + (pair (pair (pair (composition (composition first second) first) second) + (composition (composition (composition first second) second) first)) + (composition (composition (composition first second) second) second)) + +lemma polynomial_candidateCountInput : PolynomialTime candidateCountInputRealizer := by + unfold candidateCountInputRealizer + exact polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) polynomial_second) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_second) polynomial_first)) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_second) polynomial_second)) + +def candidateCount (z : TrialCountContext×Option MatrixCode) : ℕ := + z.2.elim 0 (fun X => trialTableCount (candidateCountInput (z.1,X))) + +def candidateCountRealizer : Realizer candidateCount := + optionCases (constant 0) (composition candidateCountInputRealizer trialTableCountRealizer) + +lemma polynomial_candidateCount : PolynomialTime candidateCountRealizer := + polynomial_optionCases (polynomial_constant 0) + (polynomial_composition polynomial_candidateCountInput polynomial_trialTableCount) + +def candidateCounts (z : TrialCountContext) : List ℕ := + (completionCandidates z.2.1).map (fun o => candidateCount (z,o)) + +def candidateCountsRealizer : Realizer candidateCounts := + composition (pair identity + (composition (composition second first) completionCandidatesRealizer)) + (mapWith candidateCountRealizer) + +def candidateCountMeasure (z : TrialCountContext) : ℕ := + gridStateCount (completionEnumerationData z.2.1)+weight z + +/-- Work is polynomial in the number of candidate free vectors and the +cached walk vector; no random tapes are enumerated. -/ +theorem work_candidateCounts : WorkBound candidateCountsRealizer candidateCountMeasure := by + have hm : WorkBound (composition (second (A := List ℕ×List Bool) + (B := CanonicalParameters)) first) candidateCountMeasure := + work_of_polynomial (polynomial_composition polynomial_second polynomial_first) + Polynomial.X (fun z => by simp only [candidateCountMeasure,Polynomial.eval_X]; omega) + obtain ⟨p,hp⟩ := hm + have he : WorkBound (composition (composition second first) completionCandidatesRealizer) + candidateCountMeasure := by + apply work_composition ⟨p,hp⟩ work_completionCandidates (Polynomial.X+p) + intro z + have hw := hp z + simp only [completionEnumerationMeasure,candidateCountMeasure, + Polynomial.eval_add,Polynomial.eval_X] + change _≤p.eval (candidateCountMeasure z) at hw + unfold candidateCountMeasure at hw + dsimp only [Function.comp_apply] at hw ⊢ + omega + unfold candidateCountsRealizer + apply work_then_polynomial _ (polynomial_mapWith polynomial_candidateCount) + exact work_pair (work_of_polynomial polynomial_identity Polynomial.X (fun z => by + simp only [candidateCountMeasure,Polynomial.eval_X]; omega)) he Polynomial.X + (fun z => by simp only [candidateCountMeasure,Polynomial.eval_X]; omega) + +theorem candidateCount_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (h : ℕ) (cap : List Bool) + (hcap : ∀ j : Fin (m*n),FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm j)) h d≤cap.length) + (o : Option (Table R P)) : + candidateCount + (((tabulateDenseWalk ((marginCode R,marginCode P),(d,h)),cap), + ((marginCode R,marginCode P),(d,h))),o.map tableOutput)= + o.elim 0 (fun X => (denseTrialCounts R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega))).count + (tableTrial R P d hd hR hP finProdFinEquiv X)) := by + cases o with + | none => rfl + | some X => exact trialTableCount_actual R P hd hq hR hP h cap hcap X + +/-- The sum of all enumerated successful counts is exactly the accepted +mass numerator. Rejected integer completions contribute zero. -/ +theorem candidateCounts_sum {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (cap : List Bool) + (hcap : ∀ j : Fin (m*n),FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm j)) h d≤cap.length) : + (candidateCounts ((tabulateDenseWalk ((marginCode R,marginCode P),(d,h)),cap), + ((marginCode R,marginCode P),(d,h)))).sum= + ∑ X : Table R P,(denseTrialCounts R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega))).count + (tableTrial R P d hd hR hP finProdFinEquiv X) := by + unfold candidateCounts + rw [completionCandidates_code R P htotal,List.map_ofFn,List.sum_ofFn] + simp only [Function.comp_apply] + simp_rw [candidateCount_actual R P hd hq hR hP h cap hcap] + let w : Table R P → ℕ := fun X => + (denseTrialCounts R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega))).count + (tableTrial R P d hd hR hP finProdFinEquiv X) + have hs := (finFunctionFinEquiv : BoxCompletion.Box m n (∑ i,R i) ≃ + Fin (((∑ i,R i)+1)^(m*n))).symm.sum_comp + (fun z => (BoxCompletion.decode R P htotal (∑ i,R i) z).elim 0 w) + exact hs.trans (BoxCompletion.sum_decode R P htotal (le_refl _) w) + +/-- The computed subtraction includes every rejected completion and +every unused dyadic slot in the actual dense trial. -/ +theorem candidateCounts_failure {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (cap : List Bool) + (hcap : ∀ j : Fin (m*n),FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm j)) h d≤cap.length) : + 2^denseTrialBits R P d finProdFinEquiv h- + (candidateCounts ((tabulateDenseWalk ((marginCode R,marginCode P),(d,h)),cap), + ((marginCode R,marginCode P),(d,h)))).sum= + ((denseTrialCounts R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega))).push + (trialSuccess R P d finProdFinEquiv htotal)).count none := by + rw [candidateCounts_sum R P hd hq hR hP htotal h cap hcap] + exact (denseTrial_failure_count R P d hd hR hP finProdFinEquiv htotal h + (canonicalOrigin (m*n) d (by omega))).symm + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCanonicalProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCanonicalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cc974739ca80c788b3cb3a0c9911b381b2644a7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCanonicalProgram.lean @@ -0,0 +1,64 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseNormalizeSemantics +import OAI.Combinatorics.ContingencyTables.Sampling.GreedyTableComplexity + +namespace OAI + +/-! # Dense sampling from margins with a computed grid and fallback -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms + +abbrev CanonicalParameters := (List ℕ×List ℕ)×(ℕ×ℕ) +abbrev CanonicalDrawData := CanonicalParameters×List Bool + +def zeroGrid (z : List ℕ×List ℕ) : List ℕ := + (cellPairs (z.1.tail,z.2.tail)).map (fun _ => 0) + +def zeroGridRealizer : Realizer zeroGrid := + composition (composition (pair (composition first tail) (composition second tail)) + cellPairsRealizer) (map (constant 0)) + +theorem polynomial_zeroGrid : PolynomialTime zeroGridRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_tail) + (polynomial_composition polynomial_second polynomial_tail)) polynomial_cellPairs) + (polynomial_map (polynomial_constant 0)) + +def canonicalInput (z : CanonicalDrawData) : DenseDrawData := + (((((z.1.1,zeroGrid z.1.1),z.1.2.1),z.1.2.2), + GreedyFeasibleTable.listMatrix z.1.1.1 z.1.1.2),z.2) + +def canonicalInputRealizer : Realizer canonicalInput := by + let margins : Realizer (fun z : CanonicalDrawData => z.1.1) := composition first first + let parameters : Realizer (fun z : CanonicalDrawData => z.1.2) := composition first second + let grid := composition margins zeroGridRealizer + let fallback := composition margins GreedyFeasibleTable.tableRealizer + exact pair (pair (pair (pair (pair margins grid) (composition parameters first)) + (composition parameters second)) fallback) second + +theorem polynomial_canonicalInput : PolynomialTime canonicalInputRealizer := by + have hm : PolynomialTime (composition + (first (A := CanonicalParameters) (B := List Bool)) first) := + polynomial_composition polynomial_first polynomial_first + have hp : PolynomialTime (composition + (first (A := CanonicalParameters) (B := List Bool)) second) := + polynomial_composition polynomial_first polynomial_second + unfold canonicalInputRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_pair (polynomial_pair hm (polynomial_composition hm polynomial_zeroGrid)) + (polynomial_composition hp polynomial_first)) + (polynomial_composition hp polynomial_second)) + (polynomial_composition hm GreedyFeasibleTable.polynomial_table)) polynomial_second + +def canonicalDenseDraw (z : CanonicalDrawData) : MatrixCode := + normalizedDenseCode (canonicalInput z) + +def canonicalDenseDrawRealizer : Realizer canonicalDenseDraw := + composition canonicalInputRealizer normalizedDenseCodeRealizer + +theorem polynomial_canonicalDenseDraw : PolynomialTime canonicalDenseDrawRealizer := + polynomial_composition polynomial_canonicalInput polynomial_normalizedDenseCode + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCanonicalSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCanonicalSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9f26d90177dc4541e5619ef7b38e764caf79063 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCanonicalSemantics.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseCanonicalProgram + +namespace OAI + +/-! # Correctness of dense sampling with computed initialization -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary FairBits ResidualMixture FirstSuccess +open scoped BigOperators Classical + +noncomputable section + +def canonicalOrigin (q d : ℕ) (hd : 0 < d) : Grid (I := Fin q) (4*d^8) := + fun _ => ⟨0,le_rfl,by + have hp : 1≤4*d^8 := by + have := one_le_pow₀ (n := 8) (Nat.succ_le_iff.mpr hd) + omega + have hz : (1:ℤ)≤(4*d^8:ℕ) := by exact_mod_cast hp + omega⟩ + +lemma zeroGrid_code {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 0 < d) : + zeroGrid (marginCode R,marginCode P)=gridNatCode (canonicalOrigin (m*n) d hd) := by + apply List.ext_getElem + · simp only [zeroGrid,ProfilePrograms.cellPairs,List.length_map,List.length_range, + marginCode,List.tail_cons,List.length_ofFn,gridNatCode] + · intro i hi hj + simp only [zeroGrid,List.getElem_map,gridNatCode,List.getElem_ofFn,corner, + canonicalOrigin,Int.toNat_zero] + +def canonicalFallback {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (htotal : (∑ i,R i)=∑ j,P j) : Table R P := + (tableReindex (finSuccEquiv m) (finSuccEquiv n) R P).symm + (GreedyFeasibleTable.table (fun i => R (finSuccEquiv m i)) + (fun j => P (finSuccEquiv n j)) (by + rw [(finSuccEquiv m).sum_comp,(finSuccEquiv n).sum_comp] + exact htotal)) + +lemma canonicalFallback_output {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (htotal : (∑ i,R i)=∑ j,P j) : + tableOutput (canonicalFallback R P htotal)= + GreedyFeasibleTable.listMatrix (marginCode R) (marginCode P) := by + rw [marginCode_ofFn,marginCode_ofFn,GreedyFeasibleTable.listMatrix_ofFn] + unfold tableOutput canonicalFallback + change matrixCode (fun i j => + GreedyFeasibleTable.matrix (fun i => R (finSuccEquiv m i)) + (fun j => P (finSuccEquiv n j)) + ((finSuccEquiv m).symm (finSuccEquiv m i)) + ((finSuccEquiv n).symm (finSuccEquiv n j)))=_ + simp only [Equiv.symm_apply_apply,matrixCode] + +lemma canonicalInput_code {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 0 < d) (htotal : (∑ i,R i)=∑ j,P j) (h : ℕ) (bits : List Bool) : + canonicalInput (((marginCode R,marginCode P),(d,h)),bits)= + drawInput R P h (canonicalOrigin (m*n) d hd) (canonicalFallback R P htotal) bits := by + unfold canonicalInput drawInput + rw [zeroGrid_code R P hd,canonicalFallback_output] + +/-- No caller-supplied grid or feasible fallback is needed by the +binary dense program. Every output is the analyzed table-valued draw. -/ +theorem canonicalDenseDraw_eq {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (htotal : (∑ i,R i)=∑ j,P j) (h : ℕ) + (bits : Fin (normalizedDrawBits R P d h) → Bool) : + canonicalDenseDraw (((marginCode R,marginCode P),(d,h)),List.ofFn bits)= + tableOutput (normalizedBooleanDraw R P hd hR hP htotal h + (canonicalOrigin (m*n) d (by omega)) (canonicalFallback R P htotal) bits) := by + unfold canonicalDenseDraw + rw [canonicalInput_code R P (by omega) htotal] + exact normalizedDenseCode_eq R P hd hR hP htotal h _ _ bits + +/-- The initialized dense call retains the stated error for every +margin ordering and uses only the published analytic inputs. -/ +theorem canonicalDenseDraw_variation {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (hdimR : Fintype.card (Option (Fin m))≤d) (hdimP : Fintype.card (Option (Fin n))≤d) + (hfree : Fintype.card (Fin m×Fin n)≤d) (htotal : (∑ i,R i)=∑ j,P j) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (m*n)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (m*n)) (4*d^8))) (h : ℕ) : + let _ : Nonempty (Table R P) := ⟨canonicalFallback R P htotal⟩ + (variation (mapLaw (uniformLaw (α := Fin (normalizedDrawBits R P d h) → Bool)) + (normalizedBooleanDraw R P hd hR hP htotal h + (canonicalOrigin (m*n) d (by omega)) (canonicalFallback R P htotal))) + (uniformLaw (α := Table R P)) : ℝ)≤(2:ℝ)^(-(h:ℝ)) := + normalizedBooleanDraw_variation R P hd hR hP hdimR hdimP hfree htotal hPL hCheeger h _ _ + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseChain.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseChain.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d60cb10339e03c70f9218a2a396698c06e76448 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseChain.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridMinCut +import OAI.Combinatorics.ContingencyTables.Dense.GridCutFlow +import OAI.Combinatorics.ContingencyTables.Dense.GridMetropolis + +namespace OAI + +/-! +# Conditional Poincaré bound for the actual dense bin chain + +Both published inputs are explicit: finite-box Prékopa interpolation and +finite-chain Cheeger. All margin, penalty, cut, and proposal obligations +for this chain follow from the dense completion geometry. +-/ + +namespace ContingencyTables.GridBoundary + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q K : ℕ} + +def denseBinWeight (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : ℝ := + DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner a) + +def denseBinChain (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hfree : Fintype.card (I × J) ≤ d) + (e : I × J ≃ Fin q) (hK : 1 ≤ K) : FiniteChain (Grid (I := Fin q) K) := by + have hq : q ≤ d := by + have hc := Fintype.card_congr e + rw [Fintype.card_fin] at hc + omega + exact gridChain d hd hq hK (denseBinWeight R P d e) (fun a => DenseWeights.binWeight_pos _ _ _) + +def denseCutConstant (d K : ℕ) : ℝ := binProposal d / (128 * (d : ℝ) * K) + +private theorem corner_injective : Function.Injective (corner (I := Fin q) (K := K)) := by + intro a b h + funext j + apply Subtype.ext + exact congrFun h j + +theorem denseBinChain_poincare (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) (hK : 1 ≤ K) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) K)) : + ∀ f : Grid (I := Fin q) K → ℝ, + (denseBinChain R P d hd hfree e hK).variance f ≤ + (2 / (denseCutConstant d K) ^ 2) * (denseBinChain R P d hd hfree e hK).energy f := by + classical + let : DecidableEq (Grid (I := Fin q) K) := Classical.decEq _ + let : Nonempty (Grid (I := Fin q) K) := ⟨fun _ => ⟨0, by constructor <;> omega⟩⟩ + let w := denseBinWeight R P d e (K := K) + have hw : ∀ a, 0 < w a := fun a => DenseWeights.binWeight_pos _ _ _ + have hq : q ≤ d := by + have hc := Fintype.card_congr e + rw [Fintype.card_fin] at hc + omega + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hK₀ : (0 : ℝ) < K := by exact_mod_cast (show 0 < K by omega) + have hβ := (binProposal_bounds d hd).1 + have hκ : 0 < denseCutConstant d K := by unfold denseCutConstant; positivity + apply MetropolisChain.poincare_of_weighted_cut w hw Neighbor neighbor_symm (binProposal d) hβ.le + (2 * q) (fun a => by simpa using neighbor_degree a) + ((binProposal_degree q d hd hq).trans (by norm_num)) hCheeger (denseCutConstant d K) hκ + intro S + change denseCutConstant d K * min (∑ a ∈ S, w a) (∑ a ∈ Sᶜ, w a) ≤ + binProposal d * (∑ a ∈ S, ∑ b ∈ Sᶜ, if Neighbor a b then min (w a) (w b) else 0) + have hSw : 0 ≤ ∑ a ∈ S, w a := Finset.sum_nonneg (fun a _ => (hw a).le) + have hScw : 0 ≤ ∑ a ∈ Sᶜ, w a := Finset.sum_nonneg (fun a _ => (hw a).le) + by_cases hs : S.Nonempty + · by_cases hsc : Sᶜ.Nonempty + · let Q : (Fin q → ℤ) → Prop := fun z => ∃ a ∈ S, corner a = z + have hQ (a : Grid (I := Fin q) K) : Q (corner a) ↔ a ∈ S := by + constructor + · rintro ⟨b, hb, he⟩ + exact corner_injective he ▸ hb + · intro ha + exact ⟨a, ha, rfl⟩ + have hne : Nonempty (Selected K Q) := by + obtain ⟨a, ha⟩ := hs + exact ⟨⟨a, (hQ a).mpr ha⟩⟩ + have hne' : Nonempty (Selected K (fun a => ¬ Q a)) := by + obtain ⟨a, ha⟩ := hsc + exact ⟨⟨a, fun h => (Finset.mem_compl.mp ha) ((hQ a).mp h)⟩⟩ + have hdense := denseGrid_min_cut R P d hd hR hP hRmax hPmax hfree e hPL hK Q hne hne' + change (1 / (128 * (d : ℝ) * K)) * + min (∑ a : Selected K Q, w a.val) (∑ a : Selected K (fun a => ¬ Q a), w a.val) ≤ + ∑ edge : CutEdge K Q, min (w edge.val.1) (w edge.val.2.1) at hdense + have hsum : (∑ a : Selected K Q, w a.val) = ∑ a ∈ S, w a := by + rw [selected_sum_eq_filter Q w] + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext a + simp only [Finset.mem_filter, Finset.mem_univ, true_and, hQ] + have hsum' : (∑ a : Selected K (fun a => ¬ Q a), w a.val) = ∑ a ∈ Sᶜ, w a := by + rw [selected_sum_eq_filter (fun a => ¬ Q a) w] + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext a + simp only [Finset.mem_filter, Finset.mem_univ, true_and, hQ, Finset.mem_compl] + rw [hsum, hsum'] at hdense + have hflow := cut_faces_le_neighbor_flow Q w (fun a => (hw a).le) + have hflow' : (∑ edge : CutEdge K Q, min (w edge.val.1) (w edge.val.2.1)) ≤ + ∑ a ∈ S, ∑ b ∈ Sᶜ, if Neighbor a b then min (w a) (w b) else 0 := by + convert hflow using 1 + apply Finset.sum_congr ?_ ?_ + · ext a + simp only [Finset.mem_filter, Finset.mem_univ, true_and, hQ] + · intro a _ + apply Finset.sum_congr ?_ (fun _ _ => rfl) + ext b + simp only [Finset.mem_filter, Finset.mem_univ, true_and, hQ, Finset.mem_compl] + have hbound := hdense.trans hflow' + calc + _ = binProposal d * ((1 / (128 * (d : ℝ) * K)) * + min (∑ a ∈ S, w a) (∑ a ∈ Sᶜ, w a)) := by unfold denseCutConstant; ring + _ ≤ _ := mul_le_mul_of_nonneg_left hbound hβ.le + · have he : Sᶜ = ∅ := Finset.not_nonempty_iff_eq_empty.mp hsc + rw [he] + simp only [Finset.sum_empty, min_eq_right hSw, mul_zero, Finset.sum_const_zero] + exact le_rfl + · have he : S = ∅ := Finset.not_nonempty_iff_eq_empty.mp hs + rw [he] at hScw ⊢ + simp only [Finset.sum_empty, min_eq_left hScw, mul_zero] + exact le_rfl + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCoefficients.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCoefficients.lean new file mode 100644 index 0000000000000000000000000000000000000000..6917f3f309034eacab4e6fe2488677b885245849 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCoefficients.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseAffine + +namespace OAI + +/-! +# Coefficients of normalized dense entries + +Reordering maximum margins to the pivot makes each contributing free-cell +scale no larger than the dependent-cell scale. Thus every normalized +coefficient is bounded by `1/B`, as required by the actual penalty proof. +-/ + +namespace ContingencyTables.DenseAffine + +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +def entryOffset (R : Option I → ℝ) (P : Option J → ℝ) : Option I × Option J → ℝ + | (some _, some _) => 0 + | (some i, none) => R (some i) + | (none, some j) => P (some j) + | (none, none) => R none - ∑ j, P (some j) + +def entryCoeff (w : I → J → ℝ) : (Option I × Option J) → (I × J) → ℝ + | (some i, some j), p => if p = (i, j) then w i j else 0 + | (some i, none), p => if p.1 = i then -w p.1 p.2 else 0 + | (none, some j), p => if p.2 = j then -w p.1 p.2 else 0 + | (none, none), p => w p.1 p.2 + +theorem table_affine (R : Option I → ℝ) (P : Option J → ℝ) (w : I → J → ℝ) + (u : I × J → ℝ) (g : Option I × Option J) : + table R P w u g.1 g.2 = + AffinePenalty.affineValue (entryOffset R P g) (entryCoeff w g) u := by + rcases g with ⟨i, j⟩ + cases i <;> cases j + · simp [table, AffinePenalty.affineValue, entryOffset, entryCoeff, Fintype.sum_prod_type] + · simp [table, AffinePenalty.affineValue, entryOffset, entryCoeff, + Fintype.sum_prod_type, ite_mul, Finset.sum_neg_distrib, sub_eq_add_neg] + · simp [table, AffinePenalty.affineValue, entryOffset, entryCoeff, + Fintype.sum_prod_type, ite_mul, Finset.sum_neg_distrib, sub_eq_add_neg] + · simp [table, AffinePenalty.affineValue, entryOffset, entryCoeff, ite_mul] + +def cellScale (R : Option I → ℝ) (P : Option J → ℝ) + (g : Option I × Option J) : ℝ := min (R g.1) (P g.2) + +omit [Fintype I] [Fintype J] in +theorem entryCoeff_bound (R : Option I → ℝ) (P : Option J → ℝ) (w : I → J → ℝ) + (B : ℝ) (hB : 0 < B) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hw : ∀ i j, 0 ≤ w i j) + (hwidth : ∀ i j, w i j ≤ cellScale R P (some i, some j) / B) + (hscale : ∀ g, 0 ≤ cellScale R P g) (g : Option I × Option J) (p : I × J) : + |entryCoeff w g p| ≤ cellScale R P g / B := by + rcases g with ⟨i, j⟩ + cases i with + | none => + cases j with + | none => + simp only [entryCoeff, abs_of_nonneg (hw p.1 p.2)] + exact (hwidth p.1 p.2).trans (div_le_div_of_nonneg_right + (min_le_min (hRmax p.1) (hPmax p.2)) hB.le) + | some j => + by_cases hp : p.2 = j + · simp only [entryCoeff, hp, ite_true, abs_neg, abs_of_nonneg (hw p.1 j)] + exact (hwidth p.1 j).trans (div_le_div_of_nonneg_right + (min_le_min_right _ (hRmax p.1)) hB.le) + · simp only [entryCoeff, hp, ite_false, abs_zero] + exact div_nonneg (hscale _) hB.le + | some i => + cases j with + | none => + by_cases hp : p.1 = i + · simp only [entryCoeff, hp, ite_true, abs_neg, abs_of_nonneg (hw i p.2)] + exact (hwidth i p.2).trans (div_le_div_of_nonneg_right + (min_le_min_left _ (hPmax p.2)) hB.le) + · simp only [entryCoeff, hp, ite_false, abs_zero] + exact div_nonneg (hscale _) hB.le + | some j => + by_cases hp : p = (i, j) + · simp only [entryCoeff, hp, ite_true, abs_of_nonneg (hw i j)] + exact hwidth i j + · simp only [entryCoeff, hp, ite_false, abs_zero] + exact div_nonneg (hscale _) hB.le + +theorem normalized_table_affine (R : Option I → ℝ) (P : Option J → ℝ) + (w : I → J → ℝ) (u : I × J → ℝ) (g : Option I × Option J) : + table R P w u g.1 g.2 / cellScale R P g = + AffinePenalty.affineValue (entryOffset R P g / cellScale R P g) + (fun p => entryCoeff w g p / cellScale R P g) u := by + rw [table_affine] + unfold AffinePenalty.affineValue + rw [add_div, Finset.sum_div] + congr 1 + apply Finset.sum_congr rfl + intro p _ + ring + +omit [Fintype I] [Fintype J] in +theorem normalized_coeff_bound (R : Option I → ℝ) (P : Option J → ℝ) + (w : I → J → ℝ) (B : ℝ) (hB : 0 < B) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hw : ∀ i j, 0 ≤ w i j) + (hwidth : ∀ i j, w i j ≤ cellScale R P (some i, some j) / B) + (hscale : ∀ g, 0 < cellScale R P g) (g : Option I × Option J) (p : I × J) : + |entryCoeff w g p / cellScale R P g| ≤ 1 / B := by + rw [abs_div, abs_of_pos (hscale g)] + calc + _ ≤ (cellScale R P g / B) / cellScale R P g := + div_le_div_of_nonneg_right (entryCoeff_bound R P w B hB hRmax hPmax hw hwidth + (fun g => (hscale g).le) g p) (hscale g).le + _ = 1 / B := by field_simp [ne_of_gt (hscale g), ne_of_gt hB] + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletedMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletedMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..55799db511c46aa74f8e7aef10be8184f45fe0a5 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletedMatrixProgram.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseCompletionTest + +namespace OAI + +/-! # Binary construction of the completed integer matrix -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped Polynomial + +def completedEntry (z : CompletionCell) : ℕ := (completionParts z).1-(completionParts z).2 + +def completedEntryRealizer : Realizer completedEntry := + composition (composition completionPartsRealizer (pair first second)) subtract + +theorem polynomial_completedEntry : PolynomialTime completedEntryRealizer := + polynomial_composition (polynomial_composition polynomial_completionParts + (polynomial_pair polynomial_first polynomial_second)) polynomial_subtract + +def completionRows (z : CompletionData) : List ℕ := List.range z.1.1.length +def completionColumns (z : CompletionData) : List ℕ := List.range z.1.2.length + +def completionRowsRealizer : Realizer completionRows := + composition (composition (composition first first) listLength) range +def completionColumnsRealizer : Realizer completionColumns := + composition (composition (composition first second) listLength) range + +lemma polynomial_completionRows : PolynomialTime completionRowsRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_listLength) X + intro z + simp only [Function.comp_apply,eval_X] + exact (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +lemma polynomial_completionColumns : PolynomialTime completionColumnsRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_listLength) X + intro z + simp only [Function.comp_apply,eval_X] + exact (list_length_le_weight z.1.2).trans ((weight_snd z.1).trans (weight_fst z)) + +def completedRowEntry (z : (CompletionData×ℕ)×ℕ) : ℕ := completedEntry (z.1.1,(z.1.2,z.2)) +def completedRowEntryRealizer : Realizer completedRowEntry := + composition (pair (composition first first) (pair (composition first second) second)) completedEntryRealizer + +lemma polynomial_completedRowEntry : PolynomialTime completedRowEntryRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_completedEntry + +def completedRow (z : CompletionData×ℕ) : List ℕ := + (completionColumns z.1).map (fun j => completedRowEntry (z,j)) +def completedRowRealizer : Realizer completedRow := + composition (pair identity (composition first completionColumnsRealizer)) (mapWith completedRowEntryRealizer) + +lemma polynomial_completedRow : PolynomialTime completedRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_completionColumns)) + (polynomial_mapWith polynomial_completedRowEntry) + +def completedMatrix (z : CompletionData) : MatrixCode := + (completionRows z).map (fun i => completedRow (z,i)) +def completedMatrixRealizer : Realizer completedMatrix := + composition (pair identity completionRowsRealizer) (mapWith completedRowRealizer) + +theorem polynomial_completedMatrix : PolynomialTime completedMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_completionRows) + (polynomial_mapWith polynomial_completedRow) + +lemma completedEntry_code {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (z : Fin m → Fin n → ℕ) (i : Option (Fin m)) (j : Option (Fin n)) : + completedEntry (((marginCode R,marginCode P),matrixCode z),(optionIndex i,optionIndex j))= + DenseAffine.naturalTable R P (fun ij => z ij.1 ij.2) i j := by + have h := completionParts_signed R P z i j + unfold completedEntry DenseAffine.naturalTable + dsimp only at h + rw [←h] + omega + +lemma optionIndex_finSucc {m : ℕ} (i : Fin (m+1)) : optionIndex (finSuccEquiv m i)=i.val := by + refine Fin.cases ?_ (fun j => ?_) i + · simp only [finSuccEquiv_zero,optionIndex,Fin.val_zero] + · simp only [finSuccEquiv_succ,optionIndex,Fin.val_succ] + +private lemma completedRow_code {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (z : Fin m → Fin n → ℕ) (i : Fin (m+1)) : + completedRow (((marginCode R,marginCode P),matrixCode z),i.val)= + List.ofFn (fun j : Fin (n+1) => DenseAffine.naturalTable R P + (fun ij => z ij.1 ij.2) (finSuccEquiv m i) (finSuccEquiv n j)) := by + have hc : completionColumns ((marginCode R,marginCode P),matrixCode z)=List.range (n+1) := by + simp only [completionColumns,marginCode,List.length_cons,List.length_ofFn] + unfold completedRow + rw [hc] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro j hj _ + have hjn : j < n+1 := by simpa only [List.length_map,List.length_range] using hj + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn,completedRowEntry] + simpa only [optionIndex_finSucc] using + completedEntry_code R P z (finSuccEquiv m i) (finSuccEquiv n ⟨j,hjn⟩) + +theorem completedMatrix_code {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (z : Fin m → Fin n → ℕ) : + completedMatrix ((marginCode R,marginCode P),matrixCode z)= + matrixCode (fun i : Fin (m+1) => fun j : Fin (n+1) => + DenseAffine.naturalTable R P (fun ij => z ij.1 ij.2) (finSuccEquiv m i) (finSuccEquiv n j)) := by + have hr : completionRows ((marginCode R,marginCode P),matrixCode z)=List.range (m+1) := by + simp only [completionRows,marginCode,List.length_cons,List.length_ofFn] + unfold completedMatrix + rw [hr] + unfold matrixCode + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have him : i < m+1 := by simpa only [List.length_map,List.length_range] using hi + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + exact completedRow_code R P z ⟨i,him⟩ + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletionProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletionProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e048ea88263c4d2fb483c72de0ff0782bca600c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletionProgram.lean @@ -0,0 +1,135 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseExponentArithmetic + +namespace OAI + +/-! # Signed dependent entries from binary margin and matrix lists -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped +open scoped BigOperators + +abbrev CompletionData := (List ℕ×List ℕ)×MatrixCode +abbrev CompletionCell := CompletionData×(ℕ×ℕ) + +/-- Index zero denotes the distinguished dependent row or column. -/ +def completionParts (z : CompletionCell) : ℕ×ℕ := + if z.2.1=0 then + if z.2.2=0 then + (z.1.1.1.headD 0+matrixTotal z.1.2,z.1.1.2.tail.sum) + else (z.1.1.2.getD z.2.2 0,columnTotal (z.1.2,z.2.2-1)) + else if z.2.2=0 then + (z.1.1.1.getD z.2.1 0,rowTotal (z.1.2,z.2.1-1)) + else (matrixEntry (z.1.2,(z.2.1-1,z.2.2-1)),0) + +def completionPartsRealizer : Realizer completionParts := by + let R : Realizer (fun z : CompletionCell => z.1.1.1) := + composition (composition first first) first + let C : Realizer (fun z : CompletionCell => z.1.1.2) := + composition (composition first first) second + let Z : Realizer (fun z : CompletionCell => z.1.2) := composition first second + let I : Realizer (fun z : CompletionCell => z.2.1) := composition second first + let J : Realizer (fun z : CompletionCell => z.2.2) := composition second second + let Im := composition (pair I (constant 1)) subtract + let Jm := composition (pair J (constant 1)) subtract + let Rval := composition (pair R I) (getDFast 0) + let Cval := composition (pair C J) (getDFast 0) + let Rsum := composition (pair Z Im) rowTotalRealizer + let Csum := composition (pair Z Jm) columnTotalRealizer + let total := pair + (composition (pair (composition R (head 0)) (composition Z matrixTotalRealizer)) add) + (composition (composition C tail) listSum) + let entry := pair (composition (pair Z (pair Im Jm)) matrixEntryRealizer) (constant 0) + exact (choose (composition (pair I (constant 0)) natEqual) + (choose (composition (pair J (constant 0)) natEqual) total (pair Cval Csum)) + (choose (composition (pair J (constant 0)) natEqual) (pair Rval Rsum) entry)).congr + (by intro z; simp only [Function.comp_apply,decide_eq_true_eq,completionParts]) + +theorem polynomial_completionParts : PolynomialTime completionPartsRealizer := by + have hR : PolynomialTime (composition + (composition (first (A := CompletionData) (B := ℕ×ℕ)) first) first) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first + have hC : PolynomialTime (composition + (composition (first (A := CompletionData) (B := ℕ×ℕ)) first) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + have hZ : PolynomialTime (composition + (first (A := CompletionData) (B := ℕ×ℕ)) second) := + polynomial_composition polynomial_first polynomial_second + have hI : PolynomialTime (composition + (second (A := CompletionData) (B := ℕ×ℕ)) first) := + polynomial_composition polynomial_second polynomial_first + have hJ : PolynomialTime (composition + (second (A := CompletionData) (B := ℕ×ℕ)) second) := + polynomial_composition polynomial_second polynomial_second + have hi := polynomial_composition (polynomial_pair hI (polynomial_constant 0)) polynomial_natEqual + have hj := polynomial_composition (polynomial_pair hJ (polynomial_constant 0)) polynomial_natEqual + have him := polynomial_composition (polynomial_pair hI (polynomial_constant 1)) polynomial_subtract + have hjm := polynomial_composition (polynomial_pair hJ (polynomial_constant 1)) polynomial_subtract + have hr := polynomial_composition (polynomial_pair hR hI) (polynomial_getDFast 0) + have hc := polynomial_composition (polynomial_pair hC hJ) (polynomial_getDFast 0) + have hrs := polynomial_composition (polynomial_pair hZ him) polynomial_rowTotal + have hcs := polynomial_composition (polynomial_pair hZ hjm) polynomial_columnTotal + have ht := polynomial_pair (polynomial_composition (polynomial_pair + (polynomial_composition hR (polynomial_head 0)) + (polynomial_composition hZ polynomial_matrixTotal)) polynomial_add) + (polynomial_composition (polynomial_composition hC polynomial_tail) polynomial_listSum) + have he := polynomial_pair (polynomial_composition + (polynomial_pair hZ (polynomial_pair him hjm)) polynomial_matrixEntry) (polynomial_constant 0) + unfold completionPartsRealizer + exact polynomial_congr _ (polynomial_choose hi (polynomial_choose hj ht + (polynomial_pair hc hcs)) (polynomial_choose hj (polynomial_pair hr hrs) he)) + +def marginCode {m : ℕ} (R : Option (Fin m) → ℕ) : List ℕ := + R none::List.ofFn (fun i => R (some i)) + +def optionIndex {m : ℕ} : Option (Fin m) → ℕ + | none => 0 + | some i => i.val+1 + +lemma marginCode_getD {m : ℕ} (R : Option (Fin m) → ℕ) (i : Option (Fin m)) : + (marginCode R).getD (optionIndex i) 0=R i := by + cases i with + | none => rfl + | some i => + simp only [marginCode,optionIndex,List.getD_eq_getElem?_getD,List.getElem?_cons_succ, + List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some,Fin.eta] + +theorem completionParts_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (z : Fin m → Fin n → ℕ) + (i : Option (Fin m)) (j : Option (Fin n)) : + completionParts (((marginCode R,marginCode P),matrixCode z),(optionIndex i,optionIndex j))= + GridBoundary.integerParts R P (fun p => z p.1 p.2) i j := by + cases i with + | none => + cases j with + | none => + simp only [completionParts,optionIndex,ite_true,marginCode,List.headD_cons, + List.tail_cons,List.sum_ofFn,matrixTotal_code,GridBoundary.integerParts] + | some j => + simp only [completionParts,optionIndex,ite_true,Nat.add_one_ne_zero,ite_false, + Nat.add_sub_cancel,columnTotal_code,GridBoundary.integerParts] + exact congrArg (fun a => (a,∑ i,z i j)) (marginCode_getD P (some j)) + | some i => + cases j with + | none => + simp only [completionParts,optionIndex,Nat.add_one_ne_zero,ite_false,ite_true, + Nat.add_sub_cancel,rowTotal_code,GridBoundary.integerParts] + exact congrArg (fun a => (a,∑ j,z i j)) (marginCode_getD R (some i)) + | some j => + simp only [completionParts,optionIndex,Nat.add_one_ne_zero,ite_false, + Nat.add_sub_cancel,matrixEntry_code,GridBoundary.integerParts] + +/-- The difference of the computed pair is the exact signed completion entry. -/ +theorem completionParts_signed {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (z : Fin m → Fin n → ℕ) + (i : Option (Fin m)) (j : Option (Fin n)) : + let p := completionParts + (((marginCode R,marginCode P),matrixCode z),(optionIndex i,optionIndex j)) + (p.1 : ℤ)-p.2=DenseAffine.integerTable R P (fun ij => z ij.1 ij.2) i j := by + dsimp only + rw [completionParts_code] + exact GridBoundary.integerParts_sub R P _ i j + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletionTest.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletionTest.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3d586f0a09a870082ae05c0a2ea345eb88f7728 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCompletionTest.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseExponentListSemantics + +namespace OAI + +/-! # A polynomial exact acceptance test for a free integer matrix -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms + +def completionNonnegative (z : CompletionCell) : Bool := + decide ((completionParts z).2≤(completionParts z).1) + +def completionNonnegativeRealizer : Realizer completionNonnegative := + composition (composition completionPartsRealizer (pair second first)) leNat + +theorem polynomial_completionNonnegative : PolynomialTime completionNonnegativeRealizer := + polynomial_composition (polynomial_composition polynomial_completionParts + (polynomial_pair polynomial_second polynomial_first)) polynomial_leNat + +def completionValid (z : CompletionData) : Bool := + (cellPairs z.1).all (fun ij => completionNonnegative (z,ij)) + +def completionValidRealizer : Realizer completionValid := + (composition (composition (pair identity (composition first cellPairsRealizer)) + (mapWith completionNonnegativeRealizer)) all).congr (by + intro z + simp only [Function.comp_apply,List.all_map,Function.comp_def,id_eq,completionValid]) + +theorem polynomial_completionValid : PolynomialTime completionValidRealizer := + polynomial_congr _ (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_composition polynomial_first polynomial_cellPairs)) + (polynomial_mapWith polynomial_completionNonnegative)) polynomial_all) + +theorem completionNonnegative_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (z : Fin m → Fin n → ℕ) + (i : Option (Fin m)) (j : Option (Fin n)) : + completionNonnegative (((marginCode R,marginCode P),matrixCode z), + (optionIndex i,optionIndex j))=true ↔ + 0≤DenseAffine.integerTable R P (fun ij => z ij.1 ij.2) i j := by + have h := completionParts_signed R P z i j + simp only [completionNonnegative,decide_eq_true_eq] + dsimp only at h + omega + +theorem completionValid_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (z : Fin m → Fin n → ℕ) : + completionValid ((marginCode R,marginCode P),matrixCode z)=true ↔ + ∀ i j,0≤DenseAffine.integerTable R P (fun ij => z ij.1 ij.2) i j := by + simp only [completionValid,List.all_eq_true] + constructor + · intro h i j + apply (completionNonnegative_code R P z i j).mp + apply h + apply (mem_cellPairs _ _ _ _).mpr + simpa only [marginCode,List.length_cons,List.length_ofFn] using + And.intro (optionIndex_lt i) (optionIndex_lt j) + · intro h ij hij + obtain ⟨i,j⟩ := ij + have hh := (mem_cellPairs _ _ i j).mp hij + simp only [marginCode,List.length_cons,List.length_ofFn] at hh + obtain ⟨a,ha⟩ := exists_optionIndex i hh.1 + obtain ⟨b,hb⟩ := exists_optionIndex j hh.2 + subst i + subst j + exact (completionNonnegative_code R P z a b).mpr (h a b) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCountProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCountProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfa69243e9c3c63c97c9904ee0855990c8db9701 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCountProgram.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Transport.AxisProposalTest +import OAI.Combinatorics.ContingencyTables.Machines.BinaryPowerProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseMetropolisProgram + +namespace OAI + +/-! # Executable dense off-diagonal counts without acceptance-word enumeration -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary +open scoped Classical + +abbrev CountInput := FlatExponentData×List ℕ + +def countProposalInput (z : CountInput) : ProposalTestData := + ((4*z.1.2^8,z.1.1.2),z.2) + +def countProposalInputRealizer : Realizer countProposalInput := by + let D : Realizer (fun z : CountInput => z.1.2) := composition first second + let K := composition (pair (constant 4) (composition D eighthPower)) multiply + let X : Realizer (fun z : CountInput => z.1.1.2) := + composition (composition first first) second + exact pair (pair K X) second + +lemma polynomial_countProposalInput : PolynomialTime countProposalInputRealizer := by + have hd : PolynomialTime (composition (first (A := FlatExponentData) (B := List ℕ)) second) := + polynomial_composition polynomial_first polynomial_second + have hK := polynomial_composition (polynomial_pair (polynomial_constant 4) + (polynomial_composition hd polynomial_eighthPower)) polynomial_multiply + unfold countProposalInputRealizer + exact polynomial_pair (polynomial_pair + hK + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) polynomial_second + +def countPowerInput (z : CountInput) : ℕ×ℕ := + (2,8*z.1.2^5-(flatExponent (replaceFlat (z.1,z.2))-flatExponent z.1)) + +def countPowerInputRealizer : Realizer countPowerInput := + pair (constant 2) (composition (pair + (composition (pair (constant 8) (composition (composition first second) fifthPower)) multiply) + (composition (pair (composition (composition (pair first second) replaceFlatRealizer) + flatExponentRealizer) (composition first flatExponentRealizer)) subtract)) subtract) + +lemma polynomial_countPowerInput : PolynomialTime countPowerInputRealizer := + polynomial_pair (polynomial_constant 2) (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 8) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_fifthPower)) polynomial_multiply) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_first polynomial_second) polynomial_replaceFlat) + polynomial_flatExponent) + (polynomial_composition polynomial_first polynomial_flatExponent)) polynomial_subtract)) + polynomial_subtract) + +def offCountCode (z : CountInput) : ℕ := + if hasProposal (countProposalInput z) then BinaryPowerPrograms.power (countPowerInput z) else 0 + +def offCountCodeRealizer : Realizer offCountCode := + choose (composition countProposalInputRealizer hasProposalRealizer) + (composition countPowerInputRealizer BinaryPowerPrograms.powerRealizer) (constant 0) + +def countMeasure (z : CountInput) : ℕ := z.1.2^5+weight z + +/-- Even a huge acceptance denominator only increases binary integer +length. The exponent and the supplied state encodings bound the work. -/ +theorem work_offCountCode : WorkBound offCountCodeRealizer countMeasure := by + have hb {X : Type} [Codec X] {f : CountInput → X} {F : Realizer f} + (hF : PolynomialTime F) : WorkBound F countMeasure := + work_of_polynomial hF Polynomial.X (fun z => by + simp only [Polynomial.eval_X,countMeasure] + omega) + unfold offCountCodeRealizer + apply work_choose (hb (polynomial_composition polynomial_countProposalInput polynomial_hasProposal)) + _ (hb (polynomial_constant 0)) Polynomial.X + (fun z => by simp only [Polynomial.eval_X,countMeasure]; omega) + apply work_composition (hb polynomial_countPowerInput) BinaryPowerPrograms.work_power + (8*Polynomial.X+9) + intro z + have hw : weight (2:ℕ)≤9 := by decide + simp only [countPowerInput,Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat, + Polynomial.eval_X,countMeasure] + omega + +theorem offCountCode_eq {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (a b : Grid (I := Fin (m*n)) (4*d^8)) : + offCountCode ((((marginCode R,marginCode P),gridNatCode a),d),gridNatCode b)= + if Neighbor a b then + 2^(8*d^5-(denseExponent R P d finProdFinEquiv b-denseExponent R P d finProdFinEquiv a)) + else 0 := by + unfold offCountCode countProposalInput countPowerInput replaceFlat + rw [BinaryPowerPrograms.power_eq,flatExponent_code,flatExponent_code] + by_cases h : Neighbor a b + · simp [(hasProposal_code a b).mpr h,h] + · have hp : hasProposal ((4*d^8,gridNatCode a),gridNatCode b)=false := + Bool.eq_false_iff.mpr (fun he => h ((hasProposal_code a b).mp he)) + simp [hp,h] + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCutParameters.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCutParameters.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b238d98ef772d815d2591b3be1da1a08f6765de --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseCutParameters.lean @@ -0,0 +1,45 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseScales +import Mathlib.Analysis.SpecialFunctions.Pow.Real + +namespace OAI + +/-! # Numerical interpolation parameters of the dense bin chain -/ + +namespace ContingencyTables.GridBoundary + +noncomputable def denseInterpolation (d K : ℕ) : ℝ := 1 / (4 * (d : ℝ) * K) + +theorem denseInterpolation_bounds (d K q : ℕ) (hd : 14 ≤ d) (hK : 1 ≤ K) (hq : q ≤ d) : + 0 < denseInterpolation d K ∧ denseInterpolation d K < 1 ∧ + denseInterpolation d K * K ≤ 1 / 4 ∧ + (q - 1 : ℕ) * (2 * (denseInterpolation d K * K)) ≤ (1 / 2 : ℝ) := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hd₁ : (1 : ℝ) ≤ d := by exact_mod_cast (show 1 ≤ d by omega) + have hK₀ : (0 : ℝ) < K := by exact_mod_cast (show 0 < K by omega) + have hK₁ : (1 : ℝ) ≤ K := by exact_mod_cast hK + have heq : denseInterpolation d K * K = 1 / (4 * (d : ℝ)) := by + unfold denseInterpolation + field_simp + refine ⟨by unfold denseInterpolation; positivity, ?_, ?_, ?_⟩ + · unfold denseInterpolation + apply (div_lt_one (by positivity)).mpr + nlinarith + · rw [heq] + apply (div_le_iff₀ (by positivity)).mpr + linarith + · rw [heq] + have hqd : ((q - 1 : ℕ) : ℝ) ≤ d := by exact_mod_cast (Nat.sub_le q 1).trans hq + calc + _ ≤ (d : ℝ) * (2 * (1 / (4 * (d : ℝ)))) := by gcongr + _ = 1 / 2 := by field_simp; ring + +theorem two_rpow_gain (t : ℝ) (ht : 0 ≤ t) : t / 2 ≤ (2 : ℝ) ^ t - 1 := by + have hl := Real.one_sub_inv_le_log_of_pos (show (0 : ℝ) < 2 by norm_num) + norm_num at hl + have he := Real.add_one_le_exp (Real.log 2 * t) + rw [Real.rpow_def_of_pos (by norm_num : (0 : ℝ) < 2)] + nlinarith [mul_le_mul_of_nonneg_right hl ht] + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..687ec89fd61aef945d1ed1d2aa1d93bcfd89cb7a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawProgram.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialProgram +import OAI.Combinatorics.ContingencyTables.Machines.FirstSuccessProgram + +namespace OAI + +/-! # The bounded dense draw as a single polynomial binary program -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms + +abbrev DenseDrawParameters := FlatExponentData×ℕ +abbrev DenseDrawData := (DenseDrawParameters×MatrixCode)×List Bool + +def trialWidth (z : DenseDrawParameters) : ℕ := + trialWalkBits (z,[])+(offsetLengths (flatToGridData z.1,z.2)).sum + +def trialWidthRealizer : Realizer trialWidth := by + let blank : Realizer (fun z : DenseDrawParameters => (z,([] : List Bool))) := + pair identity (constant []) + let widths := composition (pair (composition first flatToGridDataRealizer) second) + offsetLengthsRealizer + exact composition (pair (composition blank trialWalkBitsRealizer) + (composition widths listSum)) add + +theorem polynomial_trialWidth : PolynomialTime trialWidthRealizer := by + unfold trialWidthRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant [])) + polynomial_trialWalkBits) + (polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_flatToGridData) polynomial_second) + polynomial_offsetLengths) polynomial_listSum)) polynomial_add + +def drawChunks (z : DenseDrawData) : List (List Bool) := + wordChunks (trialWidth z.1.1,z.2) + +def drawChunksRealizer : Realizer drawChunks := + composition (pair (composition (composition first first) trialWidthRealizer) second) + wordChunksRealizer + +theorem polynomial_drawChunks : PolynomialTime drawChunksRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_trialWidth) polynomial_second) polynomial_wordChunks + +def denseDrawCode (z : DenseDrawData) : MatrixCode := + FirstSuccessProgram.retry denseTrialCode (z.1,drawChunks z) + +def denseDrawCodeRealizer : Realizer denseDrawCode := + composition (pair first drawChunksRealizer) (FirstSuccessProgram.retryRealizer denseTrialCodeRealizer) + +/-- Every finite input has polynomial binary cost. On a valid dense input, +the first successful trial is selected, or the supplied feasible fallback. -/ +theorem polynomial_denseDrawCode : PolynomialTime denseDrawCodeRealizer := + polynomial_composition (polynomial_pair polynomial_first polynomial_drawChunks) + (FirstSuccessProgram.polynomial_retry polynomial_denseTrialCode) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..23a473bed508596354c5228d1696c8c3b6e12931 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawSemantics.lean @@ -0,0 +1,68 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseDrawProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialSemantics +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanDraw + +namespace OAI + +/-! # The bounded binary draw is exactly the analyzed Boolean sampler -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary FairBits +open scoped BigOperators Classical + +noncomputable section + +lemma trialWidth_code {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (h : ℕ) (a : Grid (I := Fin (m*n)) (4*d^8)) : + trialWidth ((((marginCode R,marginCode P),gridNatCode a),d),h)= + denseTrialBits R P d finProdFinEquiv h := by + unfold trialWidth + rw [flatToGridData_code,offsetLengths_code,List.sum_ofFn] + rfl + +lemma denseTrialBits_pos {m n d : ℕ} (hd : 0 < d) + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) (h : ℕ) : + 0 < denseTrialBits R P d finProdFinEquiv h := by + have hw := denseStepBits_pos hd + have ht : 0 < (d^50*(h+1)^2)*denseStepBits d := by positivity + unfold denseTrialBits + omega + +def drawInput {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (h : ℕ) (a : Grid (I := Fin (m*n)) (4*d^8)) (fallback : Table R P) + (bits : List Bool) : DenseDrawData := + ((((((marginCode R,marginCode P),gridNatCode a),d),h),tableOutput fallback),bits) + +/-- This identifies every output, including the all-rejections fallback, +with the actual finite Boolean sampler whose total-variation bound is proved. -/ +theorem denseDrawCode_eq {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14 ≤ d) (hR : ∀ i,d^12 ≤ R i) (hP : ∀ j,d^12 ≤ P j) + (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) (fallback : Table R P) + (bits : Fin (denseDrawBits R P d finProdFinEquiv h) → Bool) : + denseDrawCode (drawInput R P h a fallback (List.ofFn bits))= + tableOutput (denseBooleanDraw R P d hd hR hP finProdFinEquiv htotal h a fallback bits) := by + have hd0 : 0 < d := by omega + unfold denseDrawCode drawChunks drawInput + dsimp only [Prod.fst,Prod.snd] + rw [trialWidth_code] + have hc := wordChunks_ofFn (n := d^4*(h+1)) (denseTrialBits_pos hd0 R P h) bits + let params : DenseDrawParameters := ((((marginCode R,marginCode P),gridNatCode a),d),h) + have he := congrArg (fun ws => FirstSuccessProgram.retry denseTrialCode + ((params,tableOutput fallback),ws)) hc + refine he.trans ?_ + rw [FirstSuccessProgram.retry_ofFn] + have ht : (fun word => denseTrialCode + (((((marginCode R,marginCode P),gridNatCode a),d),h),List.ofFn word))= + fun word => (trialSuccess R P d finProdFinEquiv htotal + (denseBooleanTrial R P d hd hR hP finProdFinEquiv h a word)).map tableOutput := by + funext word + exact denseTrialCode_eq R P hd hR hP htotal h a word + rw [ht,FirstSuccessProgram.wordRetry_map] + rfl + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawTabulation.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawTabulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..b61407daecdb55e0cfa5d4d42a2065aef1c4518a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseDrawTabulation.lean @@ -0,0 +1,240 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseIndexedCounts +import OAI.Combinatorics.ContingencyTables.Machines.TableIndexProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseReservedWord + +namespace OAI + +/-! # Computing the full integer law of an initialized dense draw -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary +open scoped BigOperators Classical + +def rawDrawParameters (z : CanonicalParameters) : DenseDrawParameters := + (((z.1,zeroGrid z.1),z.2.1),z.2.2) + +def rawDrawParametersRealizer : Realizer rawDrawParameters := by + let margins : Realizer (fun z : CanonicalParameters => z.1) := first + let grid := composition margins zeroGridRealizer + let result := pair (pair (pair margins grid) (composition second first)) + (composition second second) + exact result + +lemma polynomial_rawDrawParameters : PolynomialTime rawDrawParametersRealizer := by + unfold rawDrawParametersRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair polynomial_first + (polynomial_composition polynomial_first polynomial_zeroGrid)) + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_composition polynomial_second polynomial_second) + +def rawTrialBits (z : CanonicalParameters) : ℕ := trialWidth (rawDrawParameters z) + +def rawTrialBitsRealizer : Realizer rawTrialBits := + composition rawDrawParametersRealizer trialWidthRealizer + +lemma polynomial_rawTrialBits : PolynomialTime rawTrialBitsRealizer := + polynomial_composition polynomial_rawDrawParameters polynomial_trialWidth + +def rawRepeat (z : CanonicalParameters) : ℕ := z.2.1^4*(z.2.2+1) + +def rawRepeatRealizer : Realizer rawRepeat := by + let d : Realizer (fun z : CanonicalParameters => z.2.1) := composition second first + let h : Realizer (fun z : CanonicalParameters => z.2.2) := composition second second + let result := composition (pair (composition d fourthPower) + (composition h successor)) multiply + exact result + +lemma polynomial_rawRepeat : PolynomialTime rawRepeatRealizer := by + unfold rawRepeatRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_fourthPower) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_successor)) polynomial_multiply + +def rawCountContext (z : CanonicalParameters) : TrialCountContext := + ((tabulateDenseWalk z,unaryMarkers (rawTrialBits z)),z) + +def rawCountContextRealizer : Realizer rawCountContext := by + let cap := composition rawTrialBitsRealizer unaryMarkersRealizer + let result := pair (pair tabulateDenseWalkRealizer cap) identity + exact result + +def rawFallbackIndex (z : CanonicalParameters) : ℕ := + tableIndex (z.1,GreedyFeasibleTable.listMatrix z.1.1 z.1.2) + +def rawFallbackIndexRealizer : Realizer rawFallbackIndex := + composition (pair first (composition first GreedyFeasibleTable.tableRealizer)) tableIndexRealizer + +lemma polynomial_rawFallbackIndex : PolynomialTime rawFallbackIndexRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_first GreedyFeasibleTable.polynomial_table)) polynomial_tableIndex + +def rawVectorInput (z : CanonicalParameters) : VectorRetryPrograms.Input := + ((unaryMarkers (rawRepeat z),BinaryPowerPrograms.power (2,rawTrialBits z)), + (candidateCounts (rawCountContext z),rawFallbackIndex z)) + +def rawVectorInputRealizer : Realizer rawVectorInput := by + let markers := composition rawRepeatRealizer unaryMarkersRealizer + let denominator := composition (pair (constant 2) rawTrialBitsRealizer) + BinaryPowerPrograms.powerRealizer + let counts := composition rawCountContextRealizer candidateCountsRealizer + let result := pair (pair markers denominator) (pair counts rawFallbackIndexRealizer) + exact result + +def rawDrawCounts (z : CanonicalParameters) : List ℕ := + VectorRetryPrograms.counts (rawVectorInput z) + +def rawDrawCountsRealizer : Realizer rawDrawCounts := + composition rawVectorInputRealizer VectorRetryPrograms.countsRealizer + +def rawTabulationMeasure (z : CanonicalParameters) : ℕ := + tabulationMeasure z+gridStateCount (completionEnumerationData z.1)+rawTrialBits z+rawRepeat z + +private lemma weight_le_rawMeasure (z : CanonicalParameters) : weight z≤rawTabulationMeasure z := by + unfold rawTabulationMeasure tabulationMeasure + omega + +private lemma polynomial_work {A : Type} [Codec A] {f : CanonicalParameters → A} + {F : Realizer f} (hF : PolynomialTime F) : WorkBound F rawTabulationMeasure := + work_of_polynomial hF Polynomial.X (fun z => by simpa using weight_le_rawMeasure z) + +private lemma paired_work {A B : Type} [Codec A] [Codec B] + {f : CanonicalParameters → A} {g : CanonicalParameters → B} + {F : Realizer f} {G : Realizer g} + (hF : WorkBound F rawTabulationMeasure) (hG : WorkBound G rawTabulationMeasure) : + WorkBound (pair F G) rawTabulationMeasure := + work_pair hF hG Polynomial.X (fun z => by simpa using weight_le_rawMeasure z) + +lemma work_rawCountContext : WorkBound rawCountContextRealizer rawTabulationMeasure := by + have hw : WorkBound tabulateDenseWalkRealizer rawTabulationMeasure := by + obtain ⟨p,hp⟩ := work_tabulateDenseWalk + refine ⟨p,fun z => (hp z).trans ?_⟩ + apply polynomial_eval_monotone + unfold rawTabulationMeasure + omega + have hc : WorkBound (composition rawTrialBitsRealizer unaryMarkersRealizer) + rawTabulationMeasure := by + apply work_composition (polynomial_work polynomial_rawTrialBits) work_unaryMarkers Polynomial.X + intro z + simp only [id_eq,Polynomial.eval_X,rawTabulationMeasure] + omega + unfold rawCountContextRealizer + exact paired_work (paired_work hw hc) (polynomial_work polynomial_identity) + +lemma work_rawCandidateCounts : WorkBound + (composition rawCountContextRealizer candidateCountsRealizer) rawTabulationMeasure := by + obtain ⟨p,hp⟩ := work_rawCountContext + apply work_composition ⟨p,hp⟩ work_candidateCounts (Polynomial.X+p) + intro z + have hw := hp z + simp only [candidateCountMeasure,rawCountContext,Polynomial.eval_add,Polynomial.eval_X] + change _≤p.eval (rawTabulationMeasure z) at hw + dsimp only [rawCountContext] at hw + unfold rawTabulationMeasure at * + omega + +lemma work_rawVectorInput : WorkBound rawVectorInputRealizer rawTabulationMeasure := by + have hj : WorkBound (composition rawRepeatRealizer unaryMarkersRealizer) + rawTabulationMeasure := by + apply work_composition (polynomial_work polynomial_rawRepeat) work_unaryMarkers Polynomial.X + intro z + simp only [id_eq,Polynomial.eval_X,rawTabulationMeasure] + omega + have hq : WorkBound (composition (pair (constant 2) rawTrialBitsRealizer) + BinaryPowerPrograms.powerRealizer) rawTabulationMeasure := by + apply work_composition (polynomial_work (polynomial_pair (polynomial_constant 2) + polynomial_rawTrialBits)) BinaryPowerPrograms.work_power (Polynomial.X+9) + intro z + have htwo : weight (2:ℕ)≤9 := by decide + simp only [Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_ofNat,rawTabulationMeasure] + omega + unfold rawVectorInputRealizer + exact paired_work (paired_work hj hq) + (paired_work work_rawCandidateCounts (polynomial_work polynomial_rawFallbackIndex)) + +section +attribute [local irreducible] rawVectorInputRealizer VectorRetryPrograms.countsRealizer + +/-- Full draw-law tabulation is polynomial in the finite box and grid +sizes and in the numerical precision schedules. -/ +theorem work_rawDrawCounts : WorkBound rawDrawCountsRealizer rawTabulationMeasure := by + obtain ⟨p,hp⟩ := work_rawVectorInput + obtain ⟨q,hq⟩ := VectorRetryPrograms.polynomial_counts + refine ⟨p+q.comp p,fun z => ?_⟩ + have h1 := hp z + have h2 := hq (rawVectorInput z) + have h3 := polynomial_eval_monotone q + ((Nat.le_add_left _ _).trans h1) + dsimp only at h3 + simp only [Polynomial.eval_add,Polynomial.eval_comp] + change rawVectorInputRealizer.cost z+ + VectorRetryPrograms.countsRealizer.cost (rawVectorInput z)+ + weight (VectorRetryPrograms.counts (rawVectorInput z))≤_ + omega + +end + +lemma rawTrialBits_code {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 0 FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm k)) h d) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ j) + exact hs.trans (by unfold denseTrialBits; omega) + unfold rawDrawCounts rawVectorInput rawCountContext rawFallbackIndex + rw [hbits,BinaryPowerPrograms.power_eq, + ←canonicalFallback_output R P htotal, + tableIndex_actual] + have he := denseRetryVector_actual R P hd hq hR hP htotal h + (unaryMarkers (denseTrialBits R P d finProdFinEquiv h)) + (unaryMarkers (rawRepeat ((marginCode R,marginCode P),(d,h)))) + hc (canonicalFallback R P htotal) + rw [unaryMarkers_length] at he + simpa only [rawRepeat] using he + +/-- Looking up a feasible table returns its exact numerator in the +implemented finite Boolean dense draw. -/ +theorem rawDrawCounts_at {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (X : Table R P) : + (rawDrawCounts ((marginCode R,marginCode P),(d,h))).getD + (tableIndex ((marginCode R,marginCode P),tableOutput X)) 0= + (denseDrawCounts R P d hd hR hP finProdFinEquiv htotal h + (canonicalOrigin (m*n) d (by omega)) (canonicalFallback R P htotal)).count X := by + rw [rawDrawCounts_actual R P hd hq hR hP htotal,tableIndex_actual] + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,Fin.isLt,dite_true, + Option.getD_some,Fin.eta] + exact IndexedTableLaw.retry_count_index R P htotal (le_refl (∑ i,R i)) _ + (canonicalFallback R P htotal) X (d^4*(h+1)) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseEnumeratedMatrix.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseEnumeratedMatrix.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad40da92748aa76186e3091867017687f7fdfc19 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseEnumeratedMatrix.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixWalk +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGridWords + +namespace OAI + +/-! # Computing every state of the dense transition table -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary +open scoped BigOperators + +abbrev EnumeratedMatrixInput := CountMatrixContext×List Bool + +def enumerationData (z : EnumeratedMatrixInput) : GridEnumerationData := + (z.2,4*z.1.2.2^8) + +def enumerationDataRealizer : Realizer enumerationData := by + let d : Realizer (fun z : EnumeratedMatrixInput => z.1.2.2) := + composition (composition first second) second + let K := composition (pair (constant 4) (composition d eighthPower)) multiply + exact pair second K + +lemma polynomial_enumerationData : PolynomialTime enumerationDataRealizer := by + have hd : PolynomialTime (composition (composition + (first (A := CountMatrixContext) (B := List Bool)) second) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second + unfold enumerationDataRealizer + exact polynomial_pair polynomial_second (polynomial_composition + (polynomial_pair (polynomial_constant 4) (polynomial_composition hd polynomial_eighthPower)) + polynomial_multiply) + +def enumeratedMatrixInput (z : EnumeratedMatrixInput) : CountMatrixData := + (z.1,gridWords (enumerationData z)) + +def enumeratedMatrixInputRealizer : Realizer enumeratedMatrixInput := + pair first (composition enumerationDataRealizer gridWordsRealizer) + +def enumerationMeasure (z : EnumeratedMatrixInput) : ℕ := + gridStateCount (enumerationData z)+weight z + +lemma work_enumeratedMatrixInput : WorkBound enumeratedMatrixInputRealizer enumerationMeasure := by + have hp : WorkBound enumerationDataRealizer enumerationMeasure := + work_of_polynomial polynomial_enumerationData Polynomial.X (fun z => by + simp only [enumerationMeasure,Polynomial.eval_X]; omega) + obtain ⟨p,hp'⟩ := hp + have hg : WorkBound (composition enumerationDataRealizer gridWordsRealizer) + enumerationMeasure := by + apply work_composition ⟨p,hp'⟩ work_gridWords (Polynomial.X+p) + intro z + have hw := hp' z + simp only [enumerationMeasure,Polynomial.eval_add,Polynomial.eval_X] + change gridStateCount (enumerationData z)+weight (enumerationData z) ≤ _ + change _≤p.eval (enumerationMeasure z) at hw + unfold enumerationMeasure at hw + omega + unfold enumeratedMatrixInputRealizer + exact work_pair (work_of_polynomial polynomial_first Polynomial.X (fun z => by + simp only [enumerationMeasure,Polynomial.eval_X]; omega)) hg Polynomial.X + (fun z => by simp only [enumerationMeasure,Polynomial.eval_X]; omega) + +def enumeratedMatrix (z : EnumeratedMatrixInput) : List (List ℕ) := + countMatrix (enumeratedMatrixInput z) + +def enumeratedMatrixRealizer : Realizer enumeratedMatrix := + composition enumeratedMatrixInputRealizer countMatrixRealizer + +/-- All states are generated from the dimension marker and grid size. +The work is polynomial in their count and the supplied binary data. -/ +theorem work_enumeratedMatrix : WorkBound enumeratedMatrixRealizer enumerationMeasure := + work_then_polynomial work_enumeratedMatrixInput polynomial_countMatrix + +theorem enumeratedMatrix_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hq : m*n≤d) + (xs dims : List Bool) (hxs : xs.length=8*d^5) (hdims : dims.length=m*n) : + enumeratedMatrix ((((xs,2^denseStepBits d),((marginCode R,marginCode P),d)),dims))= + List.ofFn (fun j => List.ofFn (fun i => + denseTransitionCount R P d finProdFinEquiv + (gridEnumeration (m*n) (4*d^8) i) (gridEnumeration (m*n) (4*d^8) j))) := by + unfold enumeratedMatrix enumeratedMatrixInput enumerationData + rw [gridWords_eq_length dims (4*d^8) (m*n) hdims] + exact countMatrix_actual R P hq (gridEnumeration (m*n) (4*d^8)) xs hxs + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseErrorArithmetic.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseErrorArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..cdb66d78dad22824c23426e896d2c769a47f09a2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseErrorArithmetic.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseMixing + +namespace OAI + +/-! # Error budget of the bounded dense rejection schedule -/ + +namespace ContingencyTables.GridBoundary + +theorem succ_le_two_pow (h : ℕ) : h + 1 ≤ 2 ^ h := by + exact Nat.succ_le_of_lt Nat.lt_two_pow_self + +theorem square_le_two_pow (d : ℕ) (hd : 4 ≤ d) : d ^ 2 ≤ 2 ^ d := by + induction d, hd using Nat.le_induction with + | base => norm_num + | succ d hd ih => + calc + (d + 1) ^ 2 ≤ 2 * d ^ 2 := by nlinarith + _ ≤ 2 * 2 ^ d := Nat.mul_le_mul_left _ ih + _ = 2 ^ (d + 1) := by rw [pow_succ, Nat.mul_comm] + +theorem dense_trial_error_budget (d h : ℕ) (hd : 14 ≤ d) : + ((d ^ 4 * (h + 1) * (1 + d) : ℕ) : ℝ) * + (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) ≤ (2 : ℝ) ^ (-(h : ℝ) - 2) := by + have hd2 : (d : ℝ) ^ 2 ≤ (2 : ℝ) ^ d := by exact_mod_cast square_le_two_pow d (by omega) + have hd4 : (d : ℝ) ^ 4 ≤ (2 : ℝ) ^ (2 * d) := by + calc + _ = ((d : ℝ) ^ 2) ^ 2 := by ring + _ ≤ ((2 : ℝ) ^ d) ^ 2 := pow_le_pow_left₀ (by positivity) hd2 _ + _ = _ := by rw [← pow_mul]; congr 1; omega + have hh : (h : ℝ) + 1 ≤ (2 : ℝ) ^ h := by + exact_mod_cast succ_le_two_pow h + have hd1 : (1 : ℝ) + d ≤ (2 : ℝ) ^ d := by + exact_mod_cast (show 1 + d ≤ 2 ^ d by simpa only [Nat.add_comm] using succ_le_two_pow d) + have hprod : ((d ^ 4 * (h + 1) * (1 + d) : ℕ) : ℝ) ≤ + (2 : ℝ) ^ ((h : ℝ) + 3 * d) := by + push_cast + calc + _ ≤ (2 : ℝ) ^ (2 * d) * (2 : ℝ) ^ h * (2 : ℝ) ^ d := by gcongr + _ = _ := by + rw [← pow_add, ← pow_add, ← Real.rpow_natCast] + congr 1 + push_cast + ring + calc + _ ≤ (2 : ℝ) ^ ((h : ℝ) + 3 * d) * (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) := + mul_le_mul_of_nonneg_right hprod (by positivity) + _ = (2 : ℝ) ^ (-(3 * (h : ℝ) + d)) := by + rw [← Real.rpow_add (by norm_num)] + congr 1 + ring + _ ≤ _ := Real.rpow_le_rpow_of_exponent_le (by norm_num) (by + have hd' : (14 : ℝ) ≤ d := by exact_mod_cast hd + have hh' : (0 : ℝ) ≤ h := Nat.cast_nonneg _ + linarith) + +theorem dense_failure_error_budget (d h : ℕ) (hd : 14 ≤ d) : + (63 / 64 : ℝ) ^ (d ^ 4 * (h + 1)) ≤ (2 : ℝ) ^ (-(h : ℝ) - 2) := by + have hd4 : 128 ≤ d ^ 4 := by nlinarith [show 14 ^ 4 ≤ d ^ 4 from Nat.pow_le_pow_left hd _] + have hs : (63 / 64 : ℝ) ≤ Real.exp (-(1 / 64 : ℝ)) := by + linarith [Real.add_one_le_exp (-(1 / 64 : ℝ))] + calc + _ ≤ (Real.exp (-(1 / 64 : ℝ))) ^ (d ^ 4 * (h + 1)) := + pow_le_pow_left₀ (by norm_num) hs _ + _ = Real.exp (-(((d ^ 4 * (h + 1) : ℕ) : ℝ) / 64)) := by + rw [← Real.exp_nat_mul] + congr 1 + ring + _ ≤ Real.exp (-(2 * ((h : ℝ) + 1))) := by + apply Real.exp_le_exp.mpr + have h' : (128 : ℝ) ≤ (d : ℝ) ^ 4 := by exact_mod_cast hd4 + push_cast + nlinarith [show (0 : ℝ) ≤ h from Nat.cast_nonneg h] + _ ≤ (2 : ℝ) ^ (-(2 * ((h : ℝ) + 1))) := by + rw [Real.rpow_def_of_pos (by norm_num)] + apply Real.exp_le_exp.mpr + have hl : Real.log 2 ≤ 1 := by linarith [Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2)] + have hh' : (0 : ℝ) ≤ h := Nat.cast_nonneg _ + nlinarith + _ ≤ _ := Real.rpow_le_rpow_of_exponent_le (by norm_num) (by + have hh' : (0 : ℝ) ≤ h := Nat.cast_nonneg _ + linarith) + +theorem dense_total_error_budget (d h : ℕ) (hd : 14 ≤ d) : + (63 / 64 : ℝ) ^ (d ^ 4 * (h + 1)) + + ((d ^ 4 * (h + 1) * (1 + d) : ℕ) : ℝ) * + (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) ≤ (2 : ℝ) ^ (-(h : ℝ)) := by + have hf := dense_failure_error_budget d h hd + have ht := dense_trial_error_budget d h hd + have heq : (2 : ℝ) ^ (-(h : ℝ) - 2) = (2 : ℝ) ^ (-(h : ℝ)) / 4 := by + rw [Real.rpow_sub (by norm_num)] + norm_num + rw [heq] at hf ht + linarith [Real.rpow_pos_of_pos (by norm_num : (0 : ℝ) < 2) (-(h : ℝ))] + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentArithmetic.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae1f544fca402607de76efdd1ed353b98758baa0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentArithmetic.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseRational + +namespace OAI + +/-! # Natural arithmetic for the dense acceptance exponent + +Each integral completion entry is represented by a difference of two +natural numbers. The rational floor in the geometric definition is then +an ordinary natural quotient, including zero denominators. +-/ + +namespace ContingencyTables.GridBoundary +open scoped BigOperators Classical + +def componentExponent (d s positive negative : ℕ) : ℕ := + (d^4*d^8*negative-d^4*(d^8*positive+d*s))/(s*d^8) + +lemma floor_signed_quotient (positive negative denominator : ℕ) : + ⌊((positive : ℚ)-negative)/denominator⌋₊ = + (positive-negative)/denominator := by + rw [Nat.floor_div_natCast,Nat.floor_sub_natCast,Nat.floor_natCast] + +lemma componentExponent_eq (d s positive negative : ℕ) : + componentExponent d s positive negative = + ⌊(d : ℚ)^4*(-((positive : ℚ)-negative)/s-(d : ℚ)/(d : ℚ)^8)⌋₊ := by + by_cases hd : d=0 + · simp [hd,componentExponent] + by_cases hs : s=0 + · simp only [hs,componentExponent,Nat.zero_mul,Nat.div_zero,Nat.cast_zero, + div_zero,zero_sub] + symm + apply Nat.floor_of_nonpos + apply mul_nonpos_of_nonneg_of_nonpos (by positivity) + exact neg_nonpos.mpr (by positivity) + have hdq : (d : ℚ)≠0 := by exact_mod_cast hd + have hsq : (s : ℚ)≠0 := by exact_mod_cast hs + have he : (d : ℚ)^4*(-((positive : ℚ)-negative)/s-(d : ℚ)/(d : ℚ)^8)= + (((d^4*d^8*negative : ℕ) : ℚ)-((d^4*(d^8*positive+d*s) : ℕ) : ℚ))/ + ((s*d^8 : ℕ) : ℚ) := by + push_cast + field_simp [hdq,hsq] + ring + rw [he,floor_signed_quotient] + rfl + +variable {I J : Type*} [Fintype I] [Fintype J] + +def integerParts (R : Option I → ℕ) (P : Option J → ℕ) (z : I×J → ℕ) : + Option I → Option J → ℕ×ℕ + | some i,some j => (z (i,j),0) + | some i,none => (R (some i),∑ j,z (i,j)) + | none,some j => (P (some j),∑ i,z (i,j)) + | none,none => (R none+∑ i,∑ j,z (i,j),∑ j,P (some j)) + +lemma integerParts_sub (R : Option I → ℕ) (P : Option J → ℕ) + (z : I×J → ℕ) (i : Option I) (j : Option J) : + ((integerParts R P z i j).1 : ℤ)-(integerParts R P z i j).2= + DenseAffine.integerTable R P z i j := by + cases i <;> cases j + all_goals simp only [integerParts,DenseAffine.integerTable,Nat.cast_zero,sub_zero, + Nat.cast_sum,Nat.cast_add] + ring + +lemma integerParts_sub_rat (R : Option I → ℕ) (P : Option J → ℕ) + (z : I×J → ℕ) (i : Option I) (j : Option J) : + ((integerParts R P z i j).1 : ℚ)-(integerParts R P z i j).2= + (DenseAffine.integerTable R P z i j : ℚ) := by + exact_mod_cast integerParts_sub R P z i j + +variable {q K : ℕ} + +def arithmeticExponentAt (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I×J ≃ Fin q) (a : Grid (I := Fin q) K) : + Option (Option I×Option J) → ℕ + | none => 0 + | some g => + let parts := integerParts R P (cornerFree R P d e a) g.1 g.2 + componentExponent d (min (R g.1) (P g.2)) parts.1 parts.2 + +lemma arithmeticExponentAt_eq (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I×J ≃ Fin q) (a : Grid (I := Fin q) K) + (g : Option (Option I×Option J)) : + arithmeticExponentAt R P d e a g= + ⌊(d : ℚ)^4*rationalComponent R P d e a g⌋₊ := by + cases g with + | none => simp [arithmeticExponentAt,rationalComponent] + | some g => + simp only [arithmeticExponentAt,componentExponent_eq,integerParts_sub_rat, + rationalComponent] + +/-- A finite maximum of explicitly computable natural quotients is exactly +the exponent used in the dense Metropolis acceptance probability. -/ +theorem denseExponent_eq_arithmetic (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I×J ≃ Fin q) (a : Grid (I := Fin q) K) : + denseExponent R P d e a= + Finset.univ.sup' Finset.univ_nonempty (arithmeticExponentAt R P d e a) := by + have hm : Monotone (fun x : ℚ => ⌊(d : ℚ)^4*x⌋₊) := by + intro x y hxy + exact Nat.floor_mono (mul_le_mul_of_nonneg_left hxy (by positivity)) + unfold denseExponent rationalPenalty + rw [Finset.apply_sup'_eq_sup'_comp _ (fun x : ℚ => ⌊(d : ℚ)^4*x⌋₊) hm.map_sup] + apply Finset.sup'_congr Finset.univ_nonempty rfl + intro g _ + exact (arithmeticExponentAt_eq R P d e a g).symm + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentBound.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentBound.lean new file mode 100644 index 0000000000000000000000000000000000000000..04213fe53a3a2420fdeee5390704189e99a409e8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentBound.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ContingencyTables.Transport.DyadicAcceptance + +namespace OAI + +/-! # Bounded bit allowance for every dense Metropolis decision -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +theorem denseExponent_upper (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + denseExponent R P d e a ≤ 4 * d ^ 5 := by + have hcube (p : I × J) : 0 ≤ realCorner a (e p) ∧ realCorner a (e p) ≤ 4 * (d : ℝ) ^ 8 := by + have hlo : (0 : ℤ) ≤ corner a (e p) := (a (e p)).property.1 + have hhi : corner a (e p) ≤ (4 * d ^ 8 : ℕ) := by + have h : corner a (e p) ≤ (4 * d ^ 8 : ℕ) - 1 := (a (e p)).property.2 + omega + constructor + · change (0 : ℝ) ≤ (corner a (e p) : ℝ) + exact_mod_cast hlo + · change (corner a (e p) : ℝ) ≤ 4 * (d : ℝ) ^ 8 + exact_mod_cast hhi + have hp := (DenseAffine.densePenalty_cube_bound R P d hd hR hP hRmax hPmax + hdimR hdimP hfree htotal _ hcube).2 + have he : (denseExponent R P d e a : ℝ) = + (⌊(d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a)⌋ : ℤ) := by + exact_mod_cast denseExponent_eq_floor R P d e a + have hf := Int.floor_le ((d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a)) + have hmul := mul_le_mul_of_nonneg_left hp (show (0 : ℝ) ≤ (d : ℝ) ^ 4 by positivity) + change (d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a) ≤ (d : ℝ) ^ 4 * (4 * d) at hmul + have hbound : (denseExponent R P d e a : ℝ) ≤ 4 * (d : ℝ) ^ 5 := by + rw [he] + nlinarith + exact_mod_cast hbound + +/-- The paper's fixed allowance implements every possible acceptance +probability exactly, including a proposed move whose probability is one. -/ +theorem denseMetropolis_finite_coin (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (a b : Grid (I := Fin q) (4 * d ^ 8)) : + ((Finset.univ.filter (FairBits.acceptDyadic + (denseExponent R P d e b - denseExponent R P d e a) (8 * d ^ 5))).card : ℝ) / + (2 : ℝ) ^ (8 * d ^ 5) = + min 1 (denseBinWeight R P d e b / denseBinWeight R P d e a) := by + rw [FairBits.acceptDyadic_probability] + · exact (dense_acceptance_dyadic R P d e a b).symm + · exact (Nat.sub_le _ _).trans ((denseExponent_upper R P d hd hR hP hRmax hPmax + hdimR hdimP hfree htotal e b).trans (by omega)) + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentListProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentListProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..48a5b9ca6d0b120767c6701a1d045e9823c4af18 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentListProgram.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseCompletionProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseExponentProgram + +namespace OAI + +/-! # Computing all dense exponent components and their maximum -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ContingencyTables.ProfilePrograms Polynomial +open scoped BigOperators + +def listMaximum (z : List ℕ×ℕ) : ℕ := z.1.foldl (fun a b => max b a) z.2 + +def listMaximumRealizer : Realizer listMaximum := fold maximum + +lemma polynomial_maximum : PolynomialTime maximum := by + unfold maximum + exact polynomial_congr _ (polynomial_choose polynomial_less polynomial_second polynomial_first) + +lemma foldMaximum_size (xs : List ℕ) (a S : ℕ) (ha : a.size≤S) + (hx : ∀ b∈xs,b.size≤S) : + (xs.foldl (fun a b => max b a) a).size≤S := by + induction xs generalizing a with + | nil => exact ha + | cons b bs ih => + apply ih + · rcases le_total b a with h|h + · simpa only [max_eq_right h] using ha + · simpa only [max_eq_left h] using hx b (by simp) + · intro c hc + exact hx c (by simp [hc]) + +theorem polynomial_listMaximum : PolynomialTime listMaximumRealizer := by + apply polynomial_fold polynomial_maximum (4*X+1) + intro xs a pre post he + let S := weight (xs,a) + have ha : a.size≤S := (size_le_weight a).trans (weight_snd (xs,a)) + have hb : ∀ b∈pre,b.size≤S := by + intro b hb + exact (size_le_weight b).trans ((weight_mem (as := xs) (by simp [he,hb])).trans + (weight_fst (xs,a))) + have hs := foldMaximum_size pre a S ha hb + have hw := weight_nat_le (pre.foldl (fun a b => max b a) a) + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_one] + change _≤4*S+1 + omega + +lemma listMaximum_le (xs : List ℕ) (a M : ℕ) : + listMaximum (xs,a)≤M ↔ a≤M ∧ ∀ b∈xs,b≤M := by + induction xs generalizing a with + | nil => simp [listMaximum] + | cons b bs ih => + simp only [listMaximum,List.foldl_cons] at ih ⊢ + rw [ih] + simp only [max_le_iff,List.mem_cons] + constructor + · rintro ⟨⟨hb,ha⟩,hbs⟩ + refine ⟨ha,?_⟩ + intro c hc + rcases hc with rfl|hc + · exact hb + · exact hbs c hc + · rintro ⟨ha,hxs⟩ + exact ⟨⟨hxs b (Or.inl rfl),ha⟩,fun c hc => hxs c (Or.inr hc)⟩ + +lemma le_listMaximum_default (xs : List ℕ) (a : ℕ) : a≤listMaximum (xs,a) := by + exact ((listMaximum_le xs a _).mp le_rfl).1 + +lemma le_listMaximum_member (xs : List ℕ) (a b : ℕ) (hb : b∈xs) : + b≤listMaximum (xs,a) := ((listMaximum_le xs a _).mp le_rfl).2 b hb + +abbrev ExponentData := CompletionData×ℕ + +def exponentCellData (z : ExponentData×(ℕ×ℕ)) : ComponentData := + ((z.1.2,min (z.1.1.1.1.getD z.2.1 0) (z.1.1.1.2.getD z.2.2 0)), + completionParts (z.1.1,z.2)) + +def exponentCellDataRealizer : Realizer exponentCellData := by + let R : Realizer (fun z : ExponentData×(ℕ×ℕ) => z.1.1.1.1) := + composition (composition (composition first first) first) first + let C : Realizer (fun z : ExponentData×(ℕ×ℕ) => z.1.1.1.2) := + composition (composition (composition first first) first) second + let I : Realizer (fun z : ExponentData×(ℕ×ℕ) => z.2.1) := composition second first + let J : Realizer (fun z : ExponentData×(ℕ×ℕ) => z.2.2) := composition second second + exact pair (pair (composition first second) + (composition (pair (composition (pair R I) (getDFast 0)) + (composition (pair C J) (getDFast 0))) minimum)) + (composition (pair (composition first first) second) completionPartsRealizer) + +theorem polynomial_exponentCellData : PolynomialTime exponentCellDataRealizer := by + unfold exponentCellDataRealizer + apply polynomial_pair + · apply polynomial_pair (polynomial_composition polynomial_first polynomial_second) + apply polynomial_composition _ polynomial_minimum + apply polynomial_pair + · apply polynomial_composition _ (polynomial_getDFast 0) + exact polynomial_pair (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_first) + (polynomial_composition polynomial_second polynomial_first) + · apply polynomial_composition _ (polynomial_getDFast 0) + exact polynomial_pair (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) + (polynomial_composition polynomial_second polynomial_second) + · exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_completionParts + +def exponentCell (z : ExponentData×(ℕ×ℕ)) : ℕ := componentValue (exponentCellData z) + +def exponentCellRealizer : Realizer exponentCell := + composition exponentCellDataRealizer componentRealizer + +theorem polynomial_exponentCell : PolynomialTime exponentCellRealizer := + polynomial_composition polynomial_exponentCellData polynomial_component + +def exponentCells (z : ExponentData) : List (ℕ×ℕ) := cellPairs z.1.1 + +def exponentCellsRealizer : Realizer exponentCells := + composition (composition first first) cellPairsRealizer + +theorem polynomial_exponentCells : PolynomialTime exponentCellsRealizer := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_cellPairs + +def exponentValues (z : ExponentData) : List ℕ := + (exponentCells z).map (fun ij => exponentCell (z,ij)) + +def exponentValuesRealizer : Realizer exponentValues := + composition (pair identity exponentCellsRealizer) (mapWith exponentCellRealizer) + +theorem polynomial_exponentValues : PolynomialTime exponentValuesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_exponentCells) + (polynomial_mapWith polynomial_exponentCell) + +def fullExponent (z : ExponentData) : ℕ := listMaximum (exponentValues z,0) + +def fullExponentRealizer : Realizer fullExponent := + composition (pair exponentValuesRealizer (constant 0)) listMaximumRealizer + +/-- The exponent evaluation traverses only the supplied matrix dimensions. -/ +theorem polynomial_fullExponent : PolynomialTime fullExponentRealizer := + polynomial_composition (polynomial_pair polynomial_exponentValues (polynomial_constant 0)) + polynomial_listMaximum + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentListSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentListSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9228d3e62fd7ee9969bc117e60760a2ad75f01d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentListSemantics.lean @@ -0,0 +1,85 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseExponentListProgram + +namespace OAI + +/-! # The binary list exponent equals the geometric dense exponent -/ + +namespace ContingencyTables.DensePrograms +open scoped BigOperators Classical +open GridBoundary ProfilePrograms + +variable {m n : ℕ} + +def exponentDataCode (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (z : Fin m → Fin n → ℕ) : ExponentData := + (((marginCode R,marginCode P),matrixCode z),d) + +lemma optionIndex_lt (i : Option (Fin m)) : optionIndex i < m + 1 := by + cases i with + | none => simp [optionIndex] + | some i => simpa only [optionIndex,Nat.add_lt_add_iff_right] using i.isLt + +lemma exists_optionIndex (a : ℕ) (ha : a < m + 1) : + ∃ i : Option (Fin m),optionIndex i=a := by + cases a with + | zero => exact ⟨none,rfl⟩ + | succ a => exact ⟨some ⟨a,by omega⟩,rfl⟩ + +lemma exponentCell_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (z : Fin m → Fin n → ℕ) (i : Option (Fin m)) (j : Option (Fin n)) : + exponentCell (exponentDataCode R P d z,(optionIndex i,optionIndex j))= + componentExponent d (min (R i) (P j)) + (integerParts R P (fun p => z p.1 p.2) i j).1 + (integerParts R P (fun p => z p.1 p.2) i j).2 := by + simp only [exponentCell,exponentCellData,exponentDataCode,componentValue, + marginCode_getD,completionParts_code] + +lemma mem_exponentCells_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (z : Fin m → Fin n → ℕ) (i : Option (Fin m)) (j : Option (Fin n)) : + (optionIndex i,optionIndex j)∈exponentCells (exponentDataCode R P d z) := by + apply (mem_cellPairs _ _ _ _).mpr + simpa only [marginCode,List.length_cons,List.length_ofFn] using + And.intro (optionIndex_lt i) (optionIndex_lt j) + +/-- The list maximum contains every cell once; its initial zero accounts +for the extra zero component in the nonnegative rational penalty. -/ +theorem fullExponent_code {q K : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (e : Fin m×Fin n ≃ Fin q) + (a : Grid (I := Fin q) K) : + fullExponent (exponentDataCode R P d (fun i j => cornerFree R P d e a (i,j)))= + denseExponent R P d e a := by + let z := fun i j => cornerFree R P d e a (i,j) + let data := exponentDataCode R P d z + rw [denseExponent_eq_arithmetic] + apply le_antisymm + · apply (listMaximum_le (exponentValues data) 0 _).mpr + refine ⟨Nat.zero_le _,?_⟩ + intro b hb + obtain ⟨ij,hij,rfl⟩ := List.mem_map.mp hb + have hbound := (mem_cellPairs _ _ ij.1 ij.2).mp hij + have hi : ij.1 < m + 1 := by + simpa only [data,exponentDataCode,marginCode,List.length_cons,List.length_ofFn] using hbound.1 + have hj : ij.2 < n + 1 := by + simpa only [data,exponentDataCode,marginCode,List.length_cons,List.length_ofFn] using hbound.2 + obtain ⟨i,hi⟩ := exists_optionIndex ij.1 hi + obtain ⟨j,hj⟩ := exists_optionIndex ij.2 hj + have he : ij=(optionIndex i,optionIndex j) := Prod.ext hi.symm hj.symm + rw [he] + change exponentCell (exponentDataCode R P d z,(optionIndex i,optionIndex j))≤_ + rw [exponentCell_code] + exact Finset.le_sup' (arithmeticExponentAt R P d e a) (Finset.mem_univ (some (i,j))) + · apply Finset.sup'_le + intro g _ + cases g with + | none => exact Nat.zero_le _ + | some ij => + have hmem : exponentCell (data,(optionIndex ij.1,optionIndex ij.2))∈exponentValues data := + List.mem_map.mpr ⟨(optionIndex ij.1,optionIndex ij.2), + mem_exponentCells_code R P d z ij.1 ij.2,rfl⟩ + have hle := le_listMaximum_member (exponentValues data) 0 _ hmem + rw [show data=exponentDataCode R P d z from rfl,exponentCell_code] at hle + exact hle + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..864396cf5a9b9035678efbdda8f7883e8fa55515 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseExponentProgram.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseExponentArithmetic +import OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPreparedProposal + +namespace OAI + +/-! # Binary execution of one dense exponent component -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ContingencyTables.ProfilePrograms + +abbrev ComponentData := (ℕ×ℕ)×(ℕ×ℕ) + +def eighthPower : Realizer (fun n : ℕ => n^8) := + (composition fourthPower squareNat).congr (by + intro n + simp only [Function.comp_apply] + ring) + +lemma polynomial_eighthPower : PolynomialTime eighthPower := + polynomial_congr _ (polynomial_composition polynomial_fourthPower polynomial_squareNat) + +def componentValue (z : ComponentData) : ℕ := + GridBoundary.componentExponent z.1.1 z.1.2 z.2.1 z.2.2 + +def componentRealizer : Realizer componentValue := by + let D : Realizer (fun z : ComponentData => z.1.1) := composition first first + let S : Realizer (fun z : ComponentData => z.1.2) := composition first second + let P : Realizer (fun z : ComponentData => z.2.1) := composition second first + let N : Realizer (fun z : ComponentData => z.2.2) := composition second second + let D4 := composition D fourthPower + let D8 := composition D eighthPower + let pos := composition (pair D4 + (composition (pair (composition (pair D8 P) multiply) + (composition (pair D S) multiply)) add)) multiply + let neg := composition (pair (composition (pair D4 D8) multiply) N) multiply + let den := composition (pair S D8) multiply + exact (composition (pair (composition (pair neg pos) subtract) den) quotient).congr + (by intro z; rfl) + +/-- Cost is polynomial in the binary data, even when the represented +margin values and the quotient are large. -/ +theorem polynomial_component : PolynomialTime componentRealizer := by + have hD : PolynomialTime (composition + (first (A := ℕ×ℕ) (B := ℕ×ℕ)) first) := + polynomial_composition polynomial_first polynomial_first + have hS : PolynomialTime (composition + (first (A := ℕ×ℕ) (B := ℕ×ℕ)) second) := + polynomial_composition polynomial_first polynomial_second + have hP : PolynomialTime (composition + (second (A := ℕ×ℕ) (B := ℕ×ℕ)) first) := + polynomial_composition polynomial_second polynomial_first + have hN : PolynomialTime (composition + (second (A := ℕ×ℕ) (B := ℕ×ℕ)) second) := + polynomial_composition polynomial_second polynomial_second + have h4 := polynomial_composition hD polynomial_fourthPower + have h8 := polynomial_composition hD polynomial_eighthPower + have hp := polynomial_composition (polynomial_pair h4 + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair h8 hP) polynomial_multiply) + (polynomial_composition (polynomial_pair hD hS) polynomial_multiply)) polynomial_add)) + polynomial_multiply + have hn := polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair h4 h8) polynomial_multiply) hN) polynomial_multiply + have hd := polynomial_composition (polynomial_pair hS h8) polynomial_multiply + unfold componentRealizer + exact polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair hn hp) polynomial_subtract) hd) polynomial_quotient) + +theorem componentValue_eq_floor (d s positive negative : ℕ) : + componentValue ((d,s),(positive,negative))= + ⌊(d : ℚ)^4*(-((positive : ℚ)-negative)/s-(d : ℚ)/(d : ℚ)^8)⌋₊ := + GridBoundary.componentExponent_eq d s positive negative + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFiniteTransition.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFiniteTransition.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f863be3cc84ab0b38443900c686d9d0bd335608 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFiniteTransition.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseAxisBits +import OAI.Combinatorics.ContingencyTables.Dense.DenseExponentBound +import OAI.Combinatorics.ContingencyTables.Dense.DenseRationalKernel +import OAI.Combinatorics.ContingencyTables.Transport.FiniteMetropolis + +namespace OAI + +/-! # The bounded finite fair-bit experiment implements the dense transition -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess CommonBasesFPRAS + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def finiteDenseStepLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + RationalLaw (Grid (I := Fin q) (4 * d ^ 8)) := + finiteAcceptLaw a + (fun z : Fin (2 ^ Nat.clog 2 (8 * d)) => axisCodeStep a z) + (fun b => FairBits.acceptDyadic + (denseExponent R P d e b - denseExponent R P d e a) (8 * d ^ 5)) + +/-- A proposal integer followed by the fixed acceptance allowance realizes +the entire dense transition law, including unused codes and rejected moves. -/ +theorem finiteDenseStepLaw_eq (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + finiteDenseStepLaw R P d e a = rationalTransitionLaw R P d hd hfree e a := by + have hq : q ≤ d := by + have hc := Fintype.card_congr e + rw [Fintype.card_fin] at hc + omega + apply RationalLaw.eq_of_off_diagonal _ _ a + intro b hba + apply Rat.cast_injective (α := ℝ) + change ((finiteAcceptLaw a + (fun z : Fin (2 ^ Nat.clog 2 (8 * d)) => axisCodeStep a z) + (fun b => FairBits.acceptDyadic + (denseExponent R P d e b - denseExponent R P d e a) (8 * d ^ 5))).mass b : ℝ) = + (rationalTransition R P d e a b : ℝ) + rw [finiteAcceptLaw_off_diagonal a b _ _ hba.symm, + axisCodeStep_count (dense_proposal_code_bound d q hq)] + simp only [Rat.cast_mul, Rat.cast_div, Rat.cast_natCast, Fintype.card_fin, + Nat.cast_pow, Nat.cast_ofNat] + push_cast + rw [Finset.filter_congr_decidable (Finset.univ : Finset (Fin (2 ^ (8 * d ^ 5)))) + (FairBits.acceptDyadic (denseExponent R P d e b - denseExponent R P d e a) (8 * d ^ 5)) + (fun z => Classical.propDecidable _)] + rw [denseMetropolis_finite_coin R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e a b] + unfold rationalTransition + rw [ite_eq_right hba.symm, add_zero, rationalMove_cast] + unfold MetropolisChain.move binProposal + by_cases hab : Neighbor a b <;> simp [hab] + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFiniteWalk.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFiniteWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf1b89580d56bf392ce958cb27c4a0e3dc3807e9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFiniteWalk.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseFiniteTransition +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalks + +namespace OAI + +/-! # Independent bounded dense transitions realize the mixed bin law -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def finiteDenseWalkLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) (n : ℕ) : + RationalLaw (Grid (I := Fin q) (4 * d ^ 8)) := + walkLaw (finiteDenseStepLaw R P d e) a n + +theorem finiteDenseWalkLaw_eq (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) (n : ℕ) : + finiteDenseWalkLaw R P d e a n = rationalWalkLaw R P d hd hfree e n a := by + induction n with + | zero => + apply RationalLaw.ext + funext b + change (if b = a then (1 : ℚ) else 0) = if a = b then 1 else 0 + simp [eq_comm] + | succ n ih => + apply RationalLaw.ext + funext b + change (∑ c, (finiteDenseWalkLaw R P d e a n).mass c * (finiteDenseStepLaw R P d e c).mass b) = + ∑ c, rationalWalk R P d e n a c * rationalTransition R P d e c b + rw [ih] + apply Finset.sum_congr rfl + intro c _ + rw [finiteDenseStepLaw_eq R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e c] + rfl + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFlatExponentProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFlatExponentProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..392015fb0cb561ea7ee7a718e090609243e9584b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseFlatExponentProgram.lean @@ -0,0 +1,39 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixLayoutProgram + +namespace OAI + +/-! # Evaluating the dense exponent on the flat coordinate encoding -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped GridBoundary + +abbrev FlatExponentData := GridFlatData×ℕ + +def flatToGridData (z : FlatExponentData) : ExponentData := + ((z.1.1,unflattenGrid z.1),z.2) + +def flatToGridDataRealizer : Realizer flatToGridData := + pair (pair (composition first first) (composition first unflattenGridRealizer)) second + +theorem polynomial_flatToGridData : PolynomialTime flatToGridDataRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_first polynomial_unflattenGrid)) polynomial_second + +def flatExponent (z : FlatExponentData) : ℕ := gridExponent (flatToGridData z) + +def flatExponentRealizer : Realizer flatExponent := composition flatToGridDataRealizer gridExponentRealizer + +theorem polynomial_flatExponent : PolynomialTime flatExponentRealizer := + polynomial_composition polynomial_flatToGridData polynomial_gridExponent + +theorem flatExponent_code {m n K : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (a : Grid (I := Fin (m*n)) K) : + flatExponent (((marginCode R,marginCode P),gridNatCode a),d)= + denseExponent R P d finProdFinEquiv a := by + unfold flatExponent flatToGridData gridNatCode + rw [unflattenGrid_code] + exact gridExponent_code R P d a finProdFinEquiv + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGeometry.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f1efd9be299f7432a17c4be3dca23d80d2bea28 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGeometry.lean @@ -0,0 +1,121 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseRegularity +import OAI.Combinatorics.ContingencyTables.Transport.RealCompletion + +namespace OAI + +/-! +# Feasible region and interior point of the dense block + +These statements use the actual integer margins and quotient widths. Every +feasible real completion lies in the declared scaled cube, and one scaled +completion has normalized slack at least `1/(2d)` in every cell. +-/ + +namespace ContingencyTables.DenseAffine + +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +def Feasible (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (u : I × J → ℝ) : Prop := + ∀ i j, 0 ≤ table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) (denseWidth R P d) u i j + +omit [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] in +theorem denseWidth_pos (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) (i : I) (j : J) : + 0 < denseWidth R P d i j := by + unfold denseWidth + exact_mod_cast dense_width_positive d (min (R (some i)) (P (some j))) hd + (le_min (hR _) (hP _)) + +omit [DecidableEq I] [DecidableEq J] in +private theorem table_entry_upper (R : Option I → ℝ) (P : Option J → ℝ) + (w : I → J → ℝ) (u : I × J → ℝ) (htotal : ∑ i, R i = ∑ j, P j) + (hfeas : ∀ i j, 0 ≤ table R P w u i j) (i : Option I) (j : Option J) : + table R P w u i j ≤ min (R i) (P j) := by + apply le_min + · have h := Finset.single_le_sum (fun k _ => hfeas i k) (Finset.mem_univ j) + rwa [table_rows] at h + · have h := Finset.single_le_sum (fun k _ => hfeas k j) (Finset.mem_univ i) + rwa [table_columns _ _ _ _ htotal] at h + +omit [DecidableEq I] [DecidableEq J] in +theorem feasible_in_cube (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (htotal : ∑ i, R i = ∑ j, P j) (u : I × J → ℝ) (hu : Feasible R P d u) : + ∀ p, 0 ≤ u p ∧ u p ≤ 2 * (d : ℝ) ^ 8 := by + intro p + have hw := denseWidth_pos R P d hd hR hP p.1 p.2 + have hlo := hu (some p.1) (some p.2) + have ht : (∑ i, (R i : ℝ)) = ∑ j, (P j : ℝ) := by exact_mod_cast htotal + have hhi := table_entry_upper (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) + (denseWidth R P d) u ht hu (some p.1) (some p.2) + change denseWidth R P d p.1 p.2 * u p ≤ min (R (some p.1) : ℝ) (P (some p.2) : ℝ) at hhi + change 0 ≤ denseWidth R P d p.1 p.2 * u p at hlo + have hwidth := (dense_width_bounds d (min (R (some p.1)) (P (some p.2))) hd + (le_min (hR _) (hP _))).1 + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hs : min (R (some p.1) : ℝ) (P (some p.2) : ℝ) ≤ + denseWidth R P d p.1 p.2 * (2 * (d : ℝ) ^ 8) := by + apply (div_le_iff₀ (show (0 : ℝ) < 2 * (d : ℝ) ^ 8 by positivity)).mp + simpa only [Nat.cast_min, denseWidth] using hwidth + exact ⟨nonneg_of_mul_nonneg_right hlo hw, le_of_mul_le_mul_left (hhi.trans hs) hw⟩ + +omit [DecidableEq I] [DecidableEq J] in +/-- Real residual completion constructs the strict interior point. -/ +theorem dense_interior_exists (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (htotal : ∑ i, R i = ∑ j, P j) : + ∃ u : I × J → ℝ, Feasible R P d u ∧ + (∀ p, 0 ≤ u p ∧ u p ≤ 2 * (d : ℝ) ^ 8) ∧ + ∀ g : Option I × Option J, + 1 / (2 * (d : ℝ)) ≤ + table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) (denseWidth R P d) u g.1 g.2 / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hscale (g : Option I × Option J) : + 0 < cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g := by + change 0 < min (R g.1 : ℝ) (P g.2 : ℝ) + apply lt_min + · exact_mod_cast (lt_of_lt_of_le (pow_pos (show 0 < d by omega) _) (hR _)) + · exact_mod_cast (lt_of_lt_of_le (pow_pos (show 0 < d by omega) _) (hP _)) + obtain ⟨X, hX, hXR, hXP⟩ := strict_real_completion + (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) (d : ℝ) hd₀ + (fun _ => Nat.cast_nonneg _) (fun _ => Nat.cast_nonneg _) + (by exact_mod_cast hdimR) (by exact_mod_cast hdimP) (by exact_mod_cast htotal) + let u : I × J → ℝ := fun p => X (some p.1) (some p.2) / denseWidth R P d p.1 p.2 + have heq : table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) (denseWidth R P d) u = X := + table_recover _ _ _ (fun i j => ne_of_gt (denseWidth_pos R P d hd hR hP i j)) X hXR hXP + have hfeas : Feasible R P d u := by + intro i j + rw [heq] + exact (div_nonneg (hscale (i, j)).le (by positivity)).trans (hX i j) + refine ⟨u, hfeas, feasible_in_cube R P d hd hR hP htotal u hfeas, ?_⟩ + intro g + rw [heq] + apply (le_div_iff₀ (hscale g)).mpr + simpa only [cellScale, div_mul_eq_mul_div, one_mul] using hX g.1 g.2 + +theorem densePenalty_eq_zero_of_feasible (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (u : I × J → ℝ) (hu : Feasible R P d u) : densePenalty R P d u = 0 := by + apply le_antisymm + · unfold densePenalty AffinePenalty.penalty + apply Finset.sup'_le + intro g _ + cases g with + | none => exact le_rfl + | some g => + change -AffinePenalty.affineValue _ _ u - (d : ℝ) / (d : ℝ) ^ 8 ≤ 0 + rw [← normalized_table_affine] + have hnorm : 0 ≤ table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) + (denseWidth R P d) u g.1 g.2 / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g := + div_nonneg (hu g.1 g.2) (le_min (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + linarith [show (0 : ℝ) ≤ (d : ℝ) / (d : ℝ) ^ 8 by positivity] + · exact AffinePenalty.penalty_nonnegative _ _ _ _ + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGoodBins.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGoodBins.lean new file mode 100644 index 0000000000000000000000000000000000000000..947f4ab27c9d641842b2546e8495a68400715128 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGoodBins.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseNormalizer + +namespace OAI + +/-! # Wholly feasible bins covering the inner polytope -/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators ENNReal Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q K : ℕ} + +def closedBinSet (a : Grid (I := Fin q) K) : Set (Fin q → ℝ) := + Set.Icc (realCorner a) (fun j => realCorner a j + 1) + +theorem mem_closedBinSet (a : Grid (I := Fin q) K) (x : Fin q → ℝ) : + x ∈ closedBinSet a ↔ ClosedBin (corner a) x := by + constructor + · intro hx j + exact ⟨hx.1 j, hx.2 j⟩ + · intro hx + exact ⟨fun j => (hx j).1, fun j => (hx j).2⟩ + +theorem closedBinSet_volume (a : Grid (I := Fin q) K) : volume (closedBinSet a) = 1 := by + rw [closedBinSet, Real.volume_Icc_pi] + simp only [add_sub_cancel_left, ENNReal.ofReal_one, Finset.prod_const_one] + +def goodBin (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : Prop := + ∀ x, ClosedBin (corner a) x → denseGridFeasible R P d e x + +def goodBins (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) : Finset (Grid (I := Fin q) K) := + Finset.univ.filter (goodBin R P d e) + +def denseGridInner (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) : Set (Fin q → ℝ) := + {x | (fun p => x (e p)) ∈ DenseAffine.normalizedRegion R P d (2 * (d : ℝ) / (d : ℝ) ^ 8)} + +theorem inner_bin_good (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (a : Grid (I := Fin q) K) (x : Fin q → ℝ) + (hx : x ∈ denseGridInner R P d e) (hbin : ClosedBin (corner a) x) : + goodBin R P d e a := by + intro y hy + have hdist (p : I × J) : |y (e p) - x (e p)| ≤ 1 := by + apply abs_le.mpr + constructor <;> linarith [(hy (e p)).1, (hy (e p)).2, (hbin (e p)).1, (hbin (e p)).2] + have hzero : (fun p => y (e p)) ∈ DenseAffine.normalizedRegion R P d 0 := by + intro g + have hb := DenseAffine.normalizedEntry_change R P d hd hR hP hRmax hPmax hfree + (fun p => y (e p)) (fun p => x (e p)) 1 (by norm_num) hdist g + have hs := hx g + have heq : 2 * (d : ℝ) / (d : ℝ) ^ 8 = 2 * ((d : ℝ) / (d : ℝ) ^ 8) := by ring + rw [heq] at hs + have hl := (abs_le.mp hb).1 + have hnonneg : (0 : ℝ) ≤ (d : ℝ) / (d : ℝ) ^ 8 := by positivity + linarith + rw [DenseAffine.normalizedRegion_zero R P d hd hR hP] at hzero + exact hzero + +theorem goodBin_weight_one (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (a : Grid (I := Fin q) K) (ha : goodBin R P d e a) : denseBinWeight R P d e a = 1 := by + have hx : ClosedBin (corner a) (realCorner a) := fun _ => ⟨le_rfl, by dsimp [realCorner]; linarith⟩ + exact denseBinWeight_eq_one R P d hd hR hP hRmax hPmax hfree e a (realCorner a) hx (ha _ hx) + +theorem dense_inner_covered_by_good_bins (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) : + denseGridInner R P d e ⊆ + ⋃ a ∈ goodBins R P d e (K := 4 * d ^ 8), closedBinSet a := by + intro x hx + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hxzero : (fun p => x (e p)) ∈ DenseAffine.normalizedRegion R P d 0 := + fun g => (show (0 : ℝ) ≤ 2 * (d : ℝ) / (d : ℝ) ^ 8 by positivity).trans (hx g) + rw [DenseAffine.normalizedRegion_zero R P d hd hR hP] at hxzero + have hcube := DenseAffine.feasible_in_cube R P d hd hR hP htotal _ hxzero + have hcoords (j : Fin q) : 0 ≤ x j ∧ x j < (4 * d ^ 8 : ℕ) := by + have hj := hcube (e.symm j) + simp only [Equiv.apply_symm_apply] at hj + constructor + · exact hj.1 + · push_cast + have hb : (0 : ℝ) < (d : ℝ) ^ 8 := pow_pos hd₀ _ + linarith [hj.2] + have hfloor (j : Fin q) : ⌊x j⌋ ∈ Set.Icc (0 : ℤ) ((4 * d ^ 8 : ℕ) - 1) := by + refine ⟨Int.floor_nonneg.mpr (hcoords j).1, ?_⟩ + have hlt : ⌊x j⌋ < (4 * d ^ 8 : ℕ) := Int.floor_lt.mpr (by exact_mod_cast (hcoords j).2) + omega + let a : Grid (I := Fin q) (4 * d ^ 8) := fun j => ⟨⌊x j⌋, hfloor j⟩ + have hclosed : ClosedBin (corner a) x := fun j => ⟨Int.floor_le _, (Int.lt_floor_add_one _).le⟩ + have hgood := inner_bin_good R P d hd hR hP hRmax hPmax hfree e a x hx hclosed + refine Set.mem_iUnion.mpr ⟨a, Set.mem_iUnion.mpr ⟨?_, (mem_closedBinSet a x).mpr hclosed⟩⟩ + exact Finset.mem_filter.mpr ⟨Finset.mem_univ _, hgood⟩ + +theorem goodBins_volume_lower (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) : + (1 / 2 : ℝ≥0∞) * volume {x | denseGridFeasible R P d e x} ≤ + (goodBins R P d e (K := 4 * d ^ 8)).card := by + have hinner : (1 / 2 : ℝ≥0∞) * volume {x | denseGridFeasible R P d e x} ≤ + volume (denseGridInner R P d e) := by + rw [denseGridInner, volume_dense_reindex, denseGridFeasible_volume] + exact DenseAffine.dense_inner_volume R P d hd hR hP hdimR hdimP hfree htotal + calc + _ ≤ volume (denseGridInner R P d e) := hinner + _ ≤ volume (⋃ a ∈ goodBins R P d e (K := 4 * d ^ 8), closedBinSet a) := + measure_mono (dense_inner_covered_by_good_bins R P d hd hR hP hRmax hPmax hfree htotal e) + _ ≤ ∑ a ∈ goodBins R P d e (K := 4 * d ^ 8), volume (closedBinSet a) := + measure_biUnion_finset_le _ _ + _ = _ := by simp only [closedBinSet_volume, Finset.sum_const, nsmul_eq_mul, mul_one] + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGrid.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGrid.lean new file mode 100644 index 0000000000000000000000000000000000000000..d12b976af62641d71001a0153859c17dccc28193 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGrid.lean @@ -0,0 +1,181 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseRegularity +import OAI.Combinatorics.ContingencyTables.Dense.GridConductance + +namespace OAI + +/-! +# Conductance geometry for the actual dense penalty + +The free table coordinates are reindexed by `Fin q`. The bin and cut-tube +density comparisons below follow from the actual margins and integer +widths. Thus the weighted cut theorem has no assumed penalty regularity +or bin comparison when used for the dense completion sampler. +-/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def realCorner {K : ℕ} (a : Grid (I := Fin q) K) : Fin q → ℝ := + fun j => (corner a j : ℝ) + +def denseGridPenalty (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (x : Fin q → ℝ) : ℝ := + DenseAffine.densePenalty R P d (fun p => x (e p)) + +theorem denseGridPenalty_continuous (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (e : I × J ≃ Fin q) : Continuous (denseGridPenalty R P d e) := by + exact (DenseAffine.densePenalty_continuous R P d).comp + (continuous_pi fun p => continuous_apply (e p)) + +theorem denseGridPenalty_convex (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (e : I × J ≃ Fin q) : + ConvexOn ℝ Set.univ (denseGridPenalty R P d e) := by + refine ⟨convex_univ, ?_⟩ + intro x _ y _ a b ha hb hab + exact (DenseAffine.densePenalty_convex R P d Set.univ convex_univ).2 + (Set.mem_univ _) (Set.mem_univ _) ha hb hab + +theorem denseGridPenalty_change (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (x y : Fin q → ℝ) (r : ℝ) (hr : 0 ≤ r) (hxy : ∀ j, |x j - y j| ≤ r) : + |(d : ℝ) ^ 4 * denseGridPenalty R P d e x - + (d : ℝ) ^ 4 * denseGridPenalty R P d e y| ≤ r := + DenseAffine.densePenalty_scaled_change R P d hd hR hP hRmax hPmax hfree + _ _ r hr (fun p => hxy (e p)) + +private theorem closedBin_distance {K : ℕ} (a : Grid (I := Fin q) K) + (x : Fin q → ℝ) (hx : ClosedBin (corner a) x) : + ∀ j, |x j - realCorner a j| ≤ 1 := by + intro j + change |x j - (corner a j : ℝ)| ≤ 1 + apply abs_le.mpr + constructor <;> linarith [(hx j).1, (hx j).2] + +private theorem tube_distances {K : ℕ} {Q : (Fin q → ℤ) → Prop} + (edge : CutEdge K Q) (r : ℝ) (_hr : 0 ≤ r) (x : Fin q → ℝ) + (hx : x ∈ edgeTube edge r) : + (∀ j, |x j - realCorner edge.val.1 j| ≤ 1 + r) ∧ + (∀ j, |x j - realCorner edge.val.2.1 j| ≤ 1 + r) := by + have hcoord (j : Fin q) := hx j (Set.mem_univ j) + constructor + · intro j + have h := hcoord j + dsimp [tubeLower, tubeUpper] at h + change |x j - (corner edge.val.1 j : ℝ)| ≤ 1 + r + by_cases hj : j = edge.val.2.2 + · subst j + simp only [ite_true] at h + apply abs_le.mpr + constructor <;> linarith [h.1, h.2] + · simp only [ite_eq_right hj] at h + apply abs_le.mpr + constructor <;> linarith [h.1, h.2] + · intro j + have h := hcoord j + dsimp [tubeLower, tubeUpper] at h + change |x j - (corner edge.val.2.1 j : ℝ)| ≤ 1 + r + by_cases hj : j = edge.val.2.2 + · have hadj : (corner edge.val.2.1 j : ℝ) = + (corner edge.val.1 j : ℝ) + 1 := by + simpa only [hj, Int.cast_add, Int.cast_one] using + congrArg (fun z : ℤ => (z : ℝ)) edge.property.1.1 + simp only [ite_eq_left hj] at h + rw [hadj] + apply abs_le.mpr + constructor <;> linarith [h.1, h.2] + · have heq : corner edge.val.2.1 j = corner edge.val.1 j := + congrArg Subtype.val (edge.property.1.2 j hj) + simp only [ite_eq_right hj] at h + rw [heq] + apply abs_le.mpr + constructor <;> linarith [h.1, h.2] + +theorem denseGrid_bin_comparison (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + {K : ℕ} (a : Grid (I := Fin q) K) (x : Fin q → ℝ) + (hx : ClosedBin (corner a) x) : + DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner a) / 4 ≤ + DenseWeights.density ((d : ℝ) ^ 4) (denseGridPenalty R P d e) x ∧ + DenseWeights.density ((d : ℝ) ^ 4) (denseGridPenalty R P d e) x ≤ + 2 * DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner a) := + DenseWeights.bin_density_comparison _ _ _ _ + (denseGridPenalty_change R P d hd hR hP hRmax hPmax hfree e x _ 1 + (by norm_num) (closedBin_distance a x hx)) + +theorem denseGrid_tube_comparison (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + {K : ℕ} {Q : (Fin q → ℤ) → Prop} (edge : CutEdge K Q) (r : ℝ) + (hr : 0 ≤ r) (hr₁ : r ≤ 1) (x : Fin q → ℝ) (hx : x ∈ edgeTube edge r) : + DenseWeights.density ((d : ℝ) ^ 4) (denseGridPenalty R P d e) x ≤ + 4 * min + (DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner edge.val.1)) + (DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner edge.val.2.1)) := by + obtain ⟨hlo, hhi⟩ := tube_distances edge r hr x hx + rw [mul_min_of_nonneg _ _ (by norm_num : (0 : ℝ) ≤ 4)] + apply le_min + · apply DenseWeights.tube_density_comparison + exact (denseGridPenalty_change R P d hd hR hP hRmax hPmax hfree e x _ (1 + r) + (by positivity) hlo).trans (by linarith) + · apply DenseWeights.tube_density_comparison + exact (denseGridPenalty_change R P d hd hR hP hRmax hPmax hfree e x _ (1 + r) + (by positivity) hhi).trans (by linarith) + +/-- Actual dyadic dense weights satisfy the interpolation cut bound, +conditionally only on the published finite-box integral inequality. -/ +theorem denseGrid_weighted_cut (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + {K : ℕ} (Q : (Fin q → ℤ) → Prop) (t : ℝ) (ht : 0 < t) (ht₁ : t < 1) + (hr : t * K ≤ 1 / 4) (hsize : (q - 1 : ℕ) * (2 * (t * K)) ≤ (1 / 2 : ℝ)) + (hSmass : 0 < ∫ x in selectedBins K Q, + DenseWeights.density ((d : ℝ) ^ 4) (denseGridPenalty R P d e) x) + (hcut : 2 * (∫ x in selectedBins K Q, + DenseWeights.density ((d : ℝ) ^ 4) (denseGridPenalty R P d e) x) ≤ + ∫ x in {x | Cube K x}, + DenseWeights.density ((d : ℝ) ^ 4) (denseGridPenalty R P d e) x) : + (((2 : ℝ) ^ t - 1) / 16) * + (∑ a : Selected K Q, DenseWeights.binWeight ((d : ℝ) ^ 4) + (denseGridPenalty R P d e) (realCorner a.val)) ≤ + ∑ edge : CutEdge K Q, min + (DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner edge.val.1)) + (DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner edge.val.2.1)) := by + apply weighted_cut_of_interpolation hPL Q t ht ht₁ hr hsize + (DenseWeights.density ((d : ℝ) ^ 4) (denseGridPenalty R P d e)) + (fun a => DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner a)) + · intro a + exact (DenseWeights.binWeight_pos _ _ _).le + · exact (DenseWeights.density_continuous _ _ (denseGridPenalty_continuous R P d e)).continuousOn + · intro x _ + exact DenseWeights.density_pos _ _ _ + · intro x _ y _ s hs hs₁ + exact DenseWeights.density_logConcave _ (by positivity) _ Set.univ + (denseGridPenalty_convex R P d e) x (Set.mem_univ _) y (Set.mem_univ _) s hs hs₁ + · intro a x hx + exact (denseGrid_bin_comparison R P d hd hR hP hRmax hPmax hfree e a x + (fun j => ⟨(hx j).1.le, (hx j).2.le⟩)).1 + · intro edge x hx + exact denseGrid_tube_comparison R P d hd hR hP hRmax hPmax hfree e edge (t * K) + (mul_nonneg ht.le (Nat.cast_nonneg _)) (by linarith) x hx.1 + · exact hSmass + · exact hcut + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGridExponentProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGridExponentProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..936eccaabe9bef5302dd63003400e46b14e0ead8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseGridExponentProgram.lean @@ -0,0 +1,38 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseScaleMatrixProgram + +namespace OAI + +/-! # Computing the dense exponent directly from a binary grid matrix -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped GridBoundary + +def scaledData (z : ExponentData) : ExponentData := ((z.1.1,scaleMatrix z),z.2) + +def scaledDataRealizer : Realizer scaledData := + pair (pair (composition first first) scaleMatrixRealizer) second + +theorem polynomial_scaledData : PolynomialTime scaledDataRealizer := + polynomial_pair (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_scaleMatrix) polynomial_second + +def gridExponent (z : ExponentData) : ℕ := fullExponent (scaledData z) + +def gridExponentRealizer : Realizer gridExponent := + composition scaledDataRealizer fullExponentRealizer + +theorem polynomial_gridExponent : PolynomialTime gridExponentRealizer := + polynomial_composition polynomial_scaledData polynomial_fullExponent + +theorem gridExponent_code {m n q K : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (a : Grid (I := Fin q) K) + (e : Fin m×Fin n ≃ Fin q) : + gridExponent (exponentDataCode R P d (fun i j => (corner a (e (i,j))).toNat))= + denseExponent R P d e a := by + unfold gridExponent scaledData + rw [scaleMatrix_code] + exact fullExponent_code R P d e a + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIdealRejection.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIdealRejection.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc7f26dc1d84f33884764838853f36f3ba9b6f46 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIdealRejection.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseRationalTrial +import OAI.Combinatorics.ContingencyTables.Dense.DenseErrorArithmetic + +namespace OAI + +/-! # Bounded rejection of independent actual ideal dense trials -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +/-- The finite first-success law uses the actual per-table trial masses. +The sole bias after ideal trials comes from the feasible fallback. -/ +theorem dense_ideal_rejection_variation (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (J₀ : ℕ) (fallback : Table R P) : + let g := rationalTableMass R P d hd hR hP e + (((∑ X : Table R P, + |outputMass g (1 - ∑ Y, g Y) J₀ fallback X - uniformMass (α := Table R P)|) / 2 : ℚ) : ℝ) ≤ + (63 / 64 : ℝ) ^ J₀ := by + let : Nonempty (Table R P) := ⟨fallback⟩ + let g := rationalTableMass R P d hd hR hP e + let s : ℚ := ∑ X, g X + have hcast : (s : ℝ) = denseAcceptanceMass R P d e := by + dsimp [s, g] + rw [Rat.cast_sum] + exact rationalTableMass_total R P d hd hR hP e htotal + have hs : (1 / 32 : ℚ) ≤ s := by + have h := denseAcceptanceMass_lower R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e + rw [← hcast] at h + have hc : ((1 / 32 : ℚ) : ℝ) ≤ (s : ℝ) := by norm_num; exact h + exact_mod_cast hc + have hs1 : s ≤ 1 := by + have h := denseAcceptanceMass_le_one R P d hd hR hP e + rw [← hcast] at h + exact_mod_cast h + have hs0 : 0 < s := lt_of_lt_of_le (by norm_num) hs + have hg : g = fun _ => s * uniformMass (α := Table R P) := by + funext X + have h := rationalTableMass_uniform R P d hd hR hP hRmax hPmax hfree e X + change g X / s = uniformMass (α := Table R P) at h + simpa only [mul_comm] using (div_eq_iff (ne_of_gt hs0)).mp h + have hv := stationary_variation s hs0.le hs1 J₀ fallback + rw [← hg] at hv + have hv' : (((∑ X : Table R P, + |outputMass g (1 - s) J₀ fallback X - uniformMass (α := Table R P)|) / 2 : ℚ) : ℝ) ≤ + ((1 - s : ℚ) : ℝ) ^ J₀ := by exact_mod_cast hv + apply hv'.trans + apply pow_le_pow_left₀ + · exact_mod_cast sub_nonneg.mpr hs1 + · have h : (1 - s : ℚ) ≤ 63 / 64 := by linarith + have hc : ((1 - s : ℚ) : ℝ) ≤ ((63 / 64 : ℚ) : ℝ) := by exact_mod_cast h + simpa only [Rat.cast_div, Rat.cast_ofNat] using hc + +/-- With the manuscript's actual trial count, the ideal fallback error +already consumes at most one quarter of the requested error budget. -/ +theorem dense_ideal_rejection_schedule (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (h : ℕ) (fallback : Table R P) : + let g := rationalTableMass R P d hd hR hP e + (((∑ X : Table R P, + |outputMass g (1 - ∑ Y, g Y) (d ^ 4 * (h + 1)) fallback X - + uniformMass (α := Table R P)|) / 2 : ℚ) : ℝ) ≤ (2 : ℝ) ^ (-(h : ℝ) - 2) := + (dense_ideal_rejection_variation R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e _ fallback).trans + (dense_failure_error_budget d h hd) + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIndexedCounts.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIndexedCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..fffac356dce02bf3c9ee05e263869f3e6b026c95 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIndexedCounts.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseCandidateCounts +import OAI.Combinatorics.ContingencyTables.Transport.IndexedTableLaw +import OAI.Combinatorics.ContingencyTables.Machines.VectorRetryProgram + +namespace OAI + +/-! # Complete indexed integer law of a bounded dense draw -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary +open scoped BigOperators Classical +noncomputable section + +theorem candidateCounts_indexed {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (cap : List Bool) + (hcap : ∀ j : Fin (m*n),FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm j)) h d≤cap.length) : + candidateCounts ((tabulateDenseWalk ((marginCode R,marginCode P),(d,h)),cap), + ((marginCode R,marginCode P),(d,h)))= + List.ofFn (fun k => (IndexedTableLaw.law R P (le_refl (∑ i,R i)) + ((denseTrialCounts R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega))).push + (trialSuccess R P d finProdFinEquiv htotal))).count (some k)) := by + unfold candidateCounts + rw [completionCandidates_code R P htotal,List.map_ofFn] + apply congrArg List.ofFn + funext k + simp only [Function.comp_apply] + rw [candidateCount_actual R P hd hq hR hP h cap hcap, + IndexedTableLaw.count_some R P htotal] + unfold IndexedTableLaw.tableAt + simp_rw [denseTrial_success_count R P d hd hR hP finProdFinEquiv htotal] + +/-- Full retry numerators are obtained by the polynomial binary vector +recurrence, after the accepted-trial vector has been tabulated once. -/ +theorem denseRetryVector_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (cap xs : List Bool) + (hcap : ∀ j : Fin (m*n),FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm j)) h d≤cap.length) + (fallback : Table R P) : + VectorRetryPrograms.counts ((xs,2^denseTrialBits R P d finProdFinEquiv h), + (candidateCounts ((tabulateDenseWalk ((marginCode R,marginCode P),(d,h)),cap), + ((marginCode R,marginCode P),(d,h))), + (IndexedTableLaw.index R P (le_refl (∑ i,R i)) fallback).val))= + List.ofFn (((IndexedTableLaw.law R P (le_refl (∑ i,R i)) + ((denseTrialCounts R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega))).push + (trialSuccess R P d finProdFinEquiv htotal))).retry + (IndexedTableLaw.index R P (le_refl (∑ i,R i)) fallback) xs.length).count) := by + rw [candidateCounts_indexed R P hd hq hR hP htotal h cap hcap] + exact VectorRetryPrograms.counts_actual _ xs _ + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..1dcdb04a181f7abb836d9145a1d144583e12f88e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerLaw.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTransitionCounts +import OAI.Combinatorics.ContingencyTables.Transport.IntegerLaw +import OAI.Combinatorics.ContingencyTables.Machines.OffsetCountProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanDraw + +namespace OAI + +/-! # Integer tables for the actual dense completion draw -/ + +namespace ContingencyTables.GridBoundary +open ResidualMixture FirstSuccess FairBits +open scoped BigOperators Classical +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def denseWalkCounts (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4*d^8)) (N : ℕ) : + IntegerLaw (Grid (I := Fin q) (4*d^8)) (2^(N*denseStepBits d)) := + IntegerLaw.ofMass (denseBooleanWalkLaw R P d e a N) + (IntegerPropagation.numerators (denseTransitionCount R P d e) a N) + (by positivity) (fun b => by + simpa only [Nat.cast_pow,Nat.cast_ofNat] using denseWalkCount_mass R P d e a b N) + +omit [DecidableEq I] [DecidableEq J] in +lemma denseWalkCounts_law (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4*d^8)) (N : ℕ) : + (denseWalkCounts R P d e a N).toRational (by positivity)=denseBooleanWalkLaw R P d e a N := + IntegerLaw.toRational_ofMass _ _ _ _ + +def offsetExponent (e : I × J ≃ Fin q) (w : I × J → ℕ) (h d : ℕ) : ℕ := + ∑ j : Fin q,offsetBitLength (w (e.symm j)) h d + +def offsetCounts (e : I × J ≃ Fin q) (w : I × J → ℕ) (hw : ∀ p,0 ∏ j : Fin q,OffsetCountPrograms.offsetCount + ((w (e.symm j),2^offsetBitLength (w (e.symm j)) h d), + ((offsetCoordinateEquiv e w).symm o j).val)) (by positivity) (by + intro o + change ((∏ j : Fin q,OffsetCountPrograms.offsetCount + ((w (e.symm j),2^offsetBitLength (w (e.symm j)) h d), + ((offsetCoordinateEquiv e w).symm o j).val):ℕ):ℚ)/ + (2^offsetExponent e w h d:ℕ)= + ∏ j : Fin q,(scaledLaw (w (e.symm j)) (offsetBitLength (w (e.symm j)) h d) + (hw _)).mass ((offsetCoordinateEquiv e w).symm o j) + simp_rw [OffsetCountPrograms.scaledLaw_mass] + rw [Finset.prod_div_distrib,←Nat.cast_prod] + simp only [Nat.cast_pow,Nat.cast_ofNat,offsetExponent,Finset.prod_pow_eq_pow_sum]) + +lemma offsetCounts_law (e : I × J ≃ Fin q) (w : I × J → ℕ) (hw : ∀ p,0 (denseBooleanWalk R P d e a (d^50*(h+1)^2) z.1, + drawOffsetWords e (integerWidth R P d) (integerWidth_pos R P d hd hR hP) h d z.2)), + uniform_equiv,←uniform_product,mapLaw_product,drawOffsetWordsLaw_eq] + rfl + +theorem denseTrialCounts_law (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (e : I × J ≃ Fin q) (h : ℕ) (a : Grid (I := Fin q) (4*d^8)) : + (denseTrialCounts R P d hd hR hP e h a).toRational (by positivity)= + mapLaw (uniformLaw (α := Fin (denseTrialBits R P d e h) → Bool)) + (denseBooleanTrial R P d hd hR hP e h a) := by + rw [denseTrialCounts,IntegerLaw.toRational_rebase,IntegerLaw.toRational_product, + denseWalkCounts_law,offsetCounts_law,denseBooleanTrial_product] <;> positivity + +def denseDrawCounts (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (e : I × J ≃ Fin q) (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin q) (4*d^8)) (fallback : Table R P) : + IntegerLaw (Table R P) (2^denseDrawBits R P d e h) := + (((denseTrialCounts R P d hd hR hP e h a).push (trialSuccess R P d e htotal)).retry + fallback (d^4*(h+1))).rebase (by rw [←pow_mul,Nat.mul_comm]; rfl) + +/-- Full first-success dense completion counts agree with the implemented +Boolean draw. Bin states and offset tuples are the only spaces summed. -/ +theorem denseDrawCounts_law (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (e : I × J ≃ Fin q) (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin q) (4*d^8)) (fallback : Table R P) : + (denseDrawCounts R P d hd hR hP e htotal h a fallback).toRational (by positivity)= + denseBooleanDrawLaw R P d hd hR hP e htotal h a fallback := by + rw [denseDrawCounts,IntegerLaw.toRational_rebase,IntegerLaw.toRational_retry, + IntegerLaw.toRational_push,denseTrialCounts_law,retryLaw_map,retryLaw_map] + simp only [id_eq] + change _ = mapLaw + (uniformLaw (α := Fin ((d^4*(h+1))*denseTrialBits R P d e h) → Bool)) + (fun bits => wordRetry + (fun word => trialSuccess R P d e htotal (denseBooleanTrial R P d hd hR hP e h a word)) + fallback (d^4*(h+1)) (gridWordEquiv (d^4*(h+1)) (denseTrialBits R P d e h) bits)) + rw [←map_equiv (gridWordEquiv (d^4*(h+1)) (denseTrialBits R P d e h)),uniform_equiv] + exact (wordRetryLaw_eq _ _ _).symm + all_goals positivity + +end +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3618793814d6d7ef23b3c9022cf0c2e3cdff067 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerProgram.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerTable +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeProgram +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialSums + +namespace OAI + +/-! # Binary list arithmetic for integral dense completion -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped +open scoped BigOperators + +abbrev MatrixCode := List (List ℕ) + +def columnRead (z : ℕ×List ℕ) : ℕ := z.2.getD z.1 0 + +def columnReadRealizer : Realizer columnRead := + composition (pair second first) (getDFast 0) + +lemma polynomial_columnRead : PolynomialTime columnReadRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_first) (polynomial_getDFast 0) + +def columnTotal (z : MatrixCode×ℕ) : ℕ := (z.1.map (fun row => row.getD z.2 0)).sum + +def columnTotalRealizer : Realizer columnTotal := + composition (composition (pair second first) (mapWith columnReadRealizer)) listSum + +theorem polynomial_columnTotal : PolynomialTime columnTotalRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_columnRead)) polynomial_listSum + +def rowTotal (z : MatrixCode×ℕ) : ℕ := (z.1.getD z.2 []).sum + +def rowTotalRealizer : Realizer rowTotal := composition (getDFast []) listSum + +theorem polynomial_rowTotal : PolynomialTime rowTotalRealizer := + polynomial_composition (polynomial_getDFast []) polynomial_listSum + +def matrixTotal (z : MatrixCode) : ℕ := (z.map List.sum).sum + +def matrixTotalRealizer : Realizer matrixTotal := composition (map listSum) listSum + +theorem polynomial_matrixTotal : PolynomialTime matrixTotalRealizer := + polynomial_composition (polynomial_map polynomial_listSum) polynomial_listSum + +def matrixEntry (z : MatrixCode×(ℕ×ℕ)) : ℕ := (z.1.getD z.2.1 []).getD z.2.2 0 + +def matrixEntryRealizer : Realizer matrixEntry := + composition (pair (composition (pair first (composition second first)) (getDFast [])) + (composition second second)) (getDFast 0) + +theorem polynomial_matrixEntry : PolynomialTime matrixEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) (polynomial_getDFast [])) + (polynomial_composition polynomial_second polynomial_second)) (polynomial_getDFast 0) + +def matrixCode {m n : ℕ} (z : Fin m → Fin n → ℕ) : MatrixCode := + List.ofFn (fun i => List.ofFn (z i)) + +lemma matrixEntry_code {m n : ℕ} (z : Fin m → Fin n → ℕ) (i : Fin m) (j : Fin n) : + matrixEntry (matrixCode z,(i.val,j.val))=z i j := by + simp only [matrixEntry,matrixCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + i.isLt,j.isLt,dite_true,Option.getD_some,Fin.eta] + +lemma rowTotal_code {m n : ℕ} (z : Fin m → Fin n → ℕ) (i : Fin m) : + rowTotal (matrixCode z,i.val)=∑ j,z i j := by + simp only [rowTotal,matrixCode,List.getD_eq_getElem?_getD,List.getElem?_ofFn, + i.isLt,dite_true,Option.getD_some,Fin.eta,List.sum_ofFn] + +lemma columnTotal_code {m n : ℕ} (z : Fin m → Fin n → ℕ) (j : Fin n) : + columnTotal (matrixCode z,j.val)=∑ i,z i j := by + simp only [columnTotal,matrixCode,List.map_ofFn,Function.comp_apply,List.getD_eq_getElem?_getD, + List.getElem?_ofFn,j.isLt,dite_true,Option.getD_some,Fin.eta,List.sum_ofFn] + +lemma matrixTotal_code {m n : ℕ} (z : Fin m → Fin n → ℕ) : + matrixTotal (matrixCode z)=∑ i,∑ j,z i j := by + simp only [matrixTotal,matrixCode,List.map_ofFn,Function.comp_apply,List.sum_ofFn] + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerTable.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f5d962c23e7d22dd65370466b7b3f12f52e51a1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseIntegerTable.lean @@ -0,0 +1,129 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseAcceptance + +namespace OAI + +/-! +# Integral dense completion formulas + +The sampler fills dependent cells by integer sums and differences. The +acceptance test is exactly nonnegativity of these integers; accepted +outputs have the prescribed natural margins. +-/ + +namespace ContingencyTables.DenseAffine + +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] + +def integerTable (R : Option I → ℕ) (P : Option J → ℕ) (z : I × J → ℕ) : + Option I → Option J → ℤ + | some i, some j => z (i, j) + | some i, none => R (some i) - ∑ j, (z (i, j) : ℤ) + | none, some j => P (some j) - ∑ i, (z (i, j) : ℤ) + | none, none => R none - ∑ j, (P (some j) : ℤ) + ∑ i, ∑ j, (z (i, j) : ℤ) + +def naturalTable (R : Option I → ℕ) (P : Option J → ℕ) (z : I × J → ℕ) : + Option I → Option J → ℕ := fun i j => (integerTable R P z i j).toNat + +theorem integerTable_cast (R : Option I → ℕ) (P : Option J → ℕ) + (z : I × J → ℕ) (i : Option I) (j : Option J) : + (integerTable R P z i j : ℝ) = + table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) (fun _ _ => 1) (fun p => (z p : ℝ)) i j := by + cases i <;> cases j <;> + simp only [integerTable, table, Int.cast_natCast, Int.cast_sub, Int.cast_add, + Int.cast_sum, one_mul] + +theorem scaled_integerTable_cast (R : Option I → ℕ) (P : Option J → ℕ) + (w : I → J → ℕ) (hw : ∀ i j, 0 < w i j) (z : I × J → ℕ) : + table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) (fun i j => (w i j : ℝ)) + (fun p => (z p : ℝ) / (w p.1 p.2 : ℝ)) = + (fun i j => (integerTable R P z i j : ℝ)) := by + have hfree (i : I) (j : J) : (w i j : ℝ) * ((z (i, j) : ℝ) / (w i j : ℝ)) = z (i, j) := + mul_div_cancel₀ _ (by exact_mod_cast ne_of_gt (hw i j)) + funext i j + rw [integerTable_cast] + cases i <;> cases j <;> simp only [table, hfree, one_mul] + +theorem integerTable_recover (R : Option I → ℕ) (P : Option J → ℕ) + (X : Option I → Option J → ℕ) (hR : ∀ i, ∑ j, X i j = R i) + (hP : ∀ j, ∑ i, X i j = P j) : + integerTable R P (fun p => X (some p.1) (some p.2)) = (fun i j => (X i j : ℤ)) := by + have hr : ∀ i, ∑ j, (X i j : ℝ) = (R i : ℝ) := by + intro i + exact_mod_cast hR i + have hc : ∀ j, ∑ i, (X i j : ℝ) = (P j : ℝ) := by + intro j + exact_mod_cast hP j + have heq := table_recover (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) + (fun _ _ => 1) (fun _ _ => by norm_num) (fun i j => (X i j : ℝ)) hr hc + simp only [div_one] at heq + funext i j + apply Int.cast_injective (α := ℝ) + rw [integerTable_cast] + exact congrFun (congrFun heq i) j + +theorem integer_acceptance_iff (R : Option I → ℕ) (P : Option J → ℕ) + (w : I → J → ℕ) (hw : ∀ i j, 0 < w i j) (z : I × J → ℕ) : + (∀ i j, 0 ≤ table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) + (fun i j => (w i j : ℝ)) (fun p => (z p : ℝ) / (w p.1 p.2 : ℝ)) i j) ↔ + ∀ i j, 0 ≤ integerTable R P z i j := by + rw [scaled_integerTable_cast R P w hw z] + constructor + · intro h i j + have hij := h i j + change (0 : ℝ) ≤ (integerTable R P z i j : ℝ) at hij + exact_mod_cast hij + · intro h i j + change (0 : ℝ) ≤ (integerTable R P z i j : ℝ) + exact_mod_cast h i j + +theorem naturalTable_cast (R : Option I → ℕ) (P : Option J → ℕ) (z : I × J → ℕ) + (hz : ∀ i j, 0 ≤ integerTable R P z i j) (i : Option I) (j : Option J) : + (naturalTable R P z i j : ℝ) = (integerTable R P z i j : ℝ) := by + exact_mod_cast Int.toNat_of_nonneg (hz i j) + +theorem naturalTable_rows (R : Option I → ℕ) (P : Option J → ℕ) (z : I × J → ℕ) + (hz : ∀ i j, 0 ≤ integerTable R P z i j) (i : Option I) : + ∑ j, naturalTable R P z i j = R i := by + apply Nat.cast_injective (R := ℝ) + push_cast + simp_rw [naturalTable_cast R P z hz, integerTable_cast] + exact table_rows _ _ _ _ i + +theorem naturalTable_columns (R : Option I → ℕ) (P : Option J → ℕ) (z : I × J → ℕ) + (hz : ∀ i j, 0 ≤ integerTable R P z i j) (htotal : ∑ i, R i = ∑ j, P j) (j : Option J) : + ∑ i, naturalTable R P z i j = P j := by + apply Nat.cast_injective (R := ℝ) + push_cast + simp_rw [naturalTable_cast R P z hz, integerTable_cast] + exact table_columns _ _ _ _ (by exact_mod_cast htotal) j + +theorem naturalTable_free (R : Option I → ℕ) (P : Option J → ℕ) (z : I × J → ℕ) (i : I) (j : J) : + naturalTable R P z (some i) (some j) = z (i, j) := by + simp only [naturalTable, integerTable, Int.toNat_natCast] + +theorem naturalTable_unique (R : Option I → ℕ) (P : Option J → ℕ) (z : I × J → ℕ) + (hz : ∀ i j, 0 ≤ integerTable R P z i j) + (X : Option I → Option J → ℕ) (hR : ∀ i, ∑ j, X i j = R i) + (hP : ∀ j, ∑ i, X i j = P j) (hX : ∀ i j, X (some i) (some j) = z (i, j)) : + naturalTable R P z = X := by + have htotal : ∑ i, R i = ∑ j, P j := by + simp_rw [← hR, ← hP] + exact Finset.sum_comm + have heq : (fun i j => (naturalTable R P z i j : ℝ)) = (fun i j => (X i j : ℝ)) := by + apply table_unique + · intro i + have ha := naturalTable_rows R P z hz i + exact_mod_cast ha.trans (hR i).symm + · intro j + have ha := naturalTable_columns R P z hz htotal j + exact_mod_cast ha.trans (hP j).symm + · intro i j + rw [naturalTable_free, hX] + funext i j + exact Nat.cast_injective (congrFun (congrFun heq i) j) + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseInteriorVolume.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseInteriorVolume.lean new file mode 100644 index 0000000000000000000000000000000000000000..73ed8d427a06cd8f8c13c35935c22b34a6ee331e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseInteriorVolume.lean @@ -0,0 +1,98 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseGeometry +import Mathlib.MeasureTheory.Measure.Lebesgue.Basic + +namespace OAI + +/-! # Positive volume of the actual dense completion polytope -/ + +namespace ContingencyTables.DenseAffine + +open MeasureTheory +open scoped BigOperators + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +noncomputable def normalizedEntry (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (u : I × J → ℝ) (g : Option I × Option J) : ℝ := + table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) (denseWidth R P d) u g.1 g.2 / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g + +theorem normalizedEntry_change (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (x y : I × J → ℝ) (r : ℝ) + (hr : 0 ≤ r) (hxy : ∀ p, |x p - y p| ≤ r) (g : Option I × Option J) : + |normalizedEntry R P d x g - normalizedEntry R P d y g| ≤ + ((d : ℝ) / (d : ℝ) ^ 8) * r := by + unfold normalizedEntry + rw [normalized_table_affine, normalized_table_affine] + have hb := AffinePenalty.affineValue_change + (entryOffset (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + (fun p => entryCoeff (denseWidth R P d) g p / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + x y (1 / (d : ℝ) ^ 8) r + (by positivity) (dense_normalized_coeff_bound R P d hd hR hP hRmax hPmax g) hxy + have hc : (Fintype.card (I × J) : ℝ) ≤ d := by exact_mod_cast hfree + calc + _ ≤ Fintype.card (I × J) * (1 / (d : ℝ) ^ 8) * r := hb + _ ≤ (d : ℝ) * (1 / (d : ℝ) ^ 8) * r := by gcongr + _ = _ := by ring + +theorem dense_change_below_interior_slack (d : ℕ) (hd : 14 ≤ d) : + (d : ℝ) / (d : ℝ) ^ 8 ≤ 1 / (2 * (d : ℝ)) := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hnat : 2 * d ^ 2 ≤ d ^ 8 := by + have hsix : 2 ≤ d ^ 6 := (show 2 ≤ d by omega).trans (Nat.le_self_pow (by decide) d) + calc + 2 * d ^ 2 ≤ d ^ 6 * d ^ 2 := Nat.mul_le_mul_right _ hsix + _ = d ^ 8 := by ring + apply (div_le_div_iff₀ (pow_pos hd₀ _) (show 0 < 2 * (d : ℝ) by positivity)).mpr + have hreal : 2 * (d : ℝ) ^ 2 ≤ (d : ℝ) ^ 8 := by exact_mod_cast hnat + nlinarith + +/-- A full open unit box around the constructed interior point is +feasible. Consequently the feasible polytope has positive Lebesgue volume, +including the zero-dimensional convention. -/ +theorem dense_feasible_volume_pos (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) : + 0 < volume {u : I × J → ℝ | Feasible R P d u} := by + obtain ⟨u, _, _, hcenter⟩ := dense_interior_exists R P d hd hR hP hdimR hdimP htotal + let box : Set (I × J → ℝ) := Set.pi Set.univ (fun p => Set.Ioo (u p - 1) (u p + 1)) + have hbox : box ⊆ {x | Feasible R P d x} := by + intro x hx i j + have hxy (p : I × J) : |x p - u p| ≤ 1 := by + have hp := hx p (Set.mem_univ p) + apply abs_le.mpr + constructor <;> linarith [hp.1, hp.2] + have hc := normalizedEntry_change R P d hd hR hP hRmax hPmax hfree + x u 1 (by norm_num) hxy (i, j) + have hbound := dense_change_below_interior_slack d hd + have hnonneg : 0 ≤ normalizedEntry R P d x (i, j) := by + have hl := (abs_le.mp hc).1 + have hs := hcenter (i, j) + change 1 / (2 * (d : ℝ)) ≤ normalizedEntry R P d u (i, j) at hs + linarith + have hscale : 0 < cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) (i, j) := by + change 0 < min (R i : ℝ) (P j : ℝ) + apply lt_min + · exact_mod_cast (lt_of_lt_of_le (pow_pos (show 0 < d by omega) _) (hR _)) + · exact_mod_cast (lt_of_lt_of_le (pow_pos (show 0 < d by omega) _) (hP _)) + have h := (le_div_iff₀ hscale).mp hnonneg + simpa only [zero_mul] using h + have hv : 0 < volume box := by + rw [Real.volume_pi_Ioo] + apply bot_lt_iff_ne_bot.mpr + apply Finset.prod_ne_zero_iff.mpr + intro p _ + apply ne_of_gt + apply ENNReal.ofReal_pos.mpr + linarith + exact hv.trans_le (measure_mono hbox) + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseLayerArithmetic.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseLayerArithmetic.lean new file mode 100644 index 0000000000000000000000000000000000000000..130f77025377ce72b08578b82ccef867cdf2669a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseLayerArithmetic.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseMixing +import Mathlib.Algebra.Order.Field.GeomSum + +namespace OAI + +/-! # Numerical finite-layer sum for dense rejection -/ + +namespace ContingencyTables.DenseAffine + +open scoped BigOperators + +theorem dense_layer_sum (d : ℕ) (hd : 14 ≤ d) (N : ℕ) : + 4 * (∑ j ∈ Finset.range N, (2 : ℝ) ^ (-(j : ℝ)) * + Real.exp (2 * (d : ℝ) ^ 2 * ((d : ℝ) / (d : ℝ) ^ 8 + ((j : ℝ) + 1) / (d : ℝ) ^ 4))) ≤ 16 := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + let a := 2 / (d : ℝ) ^ 2 + let b := 2 / (d : ℝ) ^ 5 + have ha : 0 ≤ a := by positivity + have hb : 0 ≤ b := by positivity + have htwo : (16 : ℝ) ≤ (d : ℝ) ^ 2 := by + exact_mod_cast (show 16 ≤ d ^ 2 from + (by norm_num : 16 ≤ 4 ^ 2).trans (Nat.pow_le_pow_left (by omega : 4 ≤ d) 2)) + have hfive : (16 : ℝ) ≤ (d : ℝ) ^ 5 := by + exact_mod_cast (show 16 ≤ d ^ 5 from + (by norm_num : 16 ≤ 4 ^ 5).trans (Nat.pow_le_pow_left (by omega : 4 ≤ d) 5)) + have ha₈ : a ≤ 1 / 8 := by + dsimp [a] + apply (div_le_iff₀ (pow_pos hd₀ 2)).mpr + nlinarith + have hb₈ : b ≤ 1 / 8 := by + dsimp [b] + apply (div_le_iff₀ (pow_pos hd₀ 5)).mpr + nlinarith + have hquarter : Real.exp (1 / 4 : ℝ) ≤ 4 / 3 := by + have h := Real.exp_bound_div_one_sub_of_interval + (by norm_num : (0 : ℝ) ≤ 1 / 4) (by norm_num : (1 / 4 : ℝ) < 1) + norm_num at h ⊢ + exact h + have hexp : Real.exp (a + b) ≤ 4 / 3 := + (Real.exp_le_exp.mpr (by linarith : a + b ≤ 1 / 4)).trans hquarter + have hratio : Real.exp a / 2 ≤ 2 / 3 := by + have h := (Real.exp_le_exp.mpr (by linarith : a ≤ 1 / 4)).trans hquarter + linarith + have hterm (j : ℕ) : (2 : ℝ) ^ (-(j : ℝ)) * + Real.exp (2 * (d : ℝ) ^ 2 * ((d : ℝ) / (d : ℝ) ^ 8 + ((j : ℝ) + 1) / (d : ℝ) ^ 4)) ≤ + (4 / 3 : ℝ) * (2 / 3 : ℝ) ^ j := by + have heq : 2 * (d : ℝ) ^ 2 * ((d : ℝ) / (d : ℝ) ^ 8 + ((j : ℝ) + 1) / (d : ℝ) ^ 4) = + (a + b) + (j : ℝ) * a := by + dsimp [a, b] + field_simp + ring + calc + _ = Real.exp (a + b) * (Real.exp a / 2) ^ j := by + rw [heq, Real.exp_add, Real.exp_nat_mul, Real.rpow_neg (by norm_num), Real.rpow_natCast, + div_pow] + ring + _ ≤ _ := mul_le_mul hexp (pow_le_pow_left₀ (by positivity) hratio j) + (by positivity) (by norm_num) + have hgeom : (∑ j ∈ Finset.range N, (2 / 3 : ℝ) ^ j) ≤ 3 := by + have h := geom_sum_mul_neg (2 / 3 : ℝ) N + have hp : 0 ≤ (2 / 3 : ℝ) ^ N := by positivity + nlinarith + have hsum := Finset.sum_le_sum (fun j (_ : j ∈ Finset.range N) => hterm j) + rw [← Finset.mul_sum] at hsum + nlinarith + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseLocalGeometry.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseLocalGeometry.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f90e4c918721864f236697d0170e9aa8c40d8cf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseLocalGeometry.lean @@ -0,0 +1,191 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseInteriorVolume +import OAI.Combinatorics.ContingencyTables.Dense.DenseChain + +namespace OAI + +/-! +# Feasible bins and exponent bounds for dense rejection + +These bounds use the actual quotient widths and margin-derived penalty. +In particular, every bin containing a feasible point has weight one. +-/ + +namespace ContingencyTables.DenseAffine + +open scoped BigOperators + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +theorem densePenalty_change (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (x y : I × J → ℝ) (r : ℝ) + (hr : 0 ≤ r) (hxy : ∀ p, |x p - y p| ≤ r) : + |densePenalty R P d x - densePenalty R P d y| ≤ ((d : ℝ) / (d : ℝ) ^ 8) * r := by + have hb := AffinePenalty.penalty_change + (fun g => entryOffset (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + (fun g p => entryCoeff (denseWidth R P d) g p / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + ((d : ℝ) / (d : ℝ) ^ 8) x y (1 / (d : ℝ) ^ 8) r (by positivity) hr + (dense_normalized_coeff_bound R P d hd hR hP hRmax hPmax) hxy + have hc : (Fintype.card (I × J) : ℝ) ≤ d := by exact_mod_cast hfree + calc + _ ≤ Fintype.card (I × J) * (1 / (d : ℝ) ^ 8) * r := hb + _ ≤ (d : ℝ) * (1 / (d : ℝ) ^ 8) * r := by gcongr + _ = _ := by ring + +theorem densePenalty_cube_bound (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (x : I × J → ℝ) (hx : ∀ p, 0 ≤ x p ∧ x p ≤ 4 * (d : ℝ) ^ 8) : + 0 ≤ densePenalty R P d x ∧ densePenalty R P d x ≤ 4 * d := by + obtain ⟨u, hu, hcube, _⟩ := dense_interior_exists R P d hd hR hP hdimR hdimP htotal + have hxy (p : I × J) : |x p - u p| ≤ 4 * (d : ℝ) ^ 8 := by + apply abs_le.mpr + constructor <;> linarith [(hx p).1, (hx p).2, (hcube p).1, (hcube p).2, + show (0 : ℝ) ≤ (d : ℝ) ^ 8 by positivity] + have hb := densePenalty_change R P d hd hR hP hRmax hPmax hfree x u + (4 * (d : ℝ) ^ 8) (by positivity) hxy + rw [densePenalty_eq_zero_of_feasible R P d u hu, sub_zero] at hb + have hd₀ : (d : ℝ) ≠ 0 := by exact_mod_cast (show d ≠ 0 by omega) + have heq : ((d : ℝ) / (d : ℝ) ^ 8) * (4 * (d : ℝ) ^ 8) = 4 * d := by + field_simp + exact ⟨AffinePenalty.penalty_nonnegative _ _ _ _, (le_abs_self _).trans (hb.trans_eq heq)⟩ + +theorem densePenalty_corner_zero (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (v x : I × J → ℝ) + (hx : Feasible R P d x) (hvx : ∀ p, |v p - x p| ≤ 1) : + densePenalty R P d v = 0 := by + apply le_antisymm + · unfold densePenalty AffinePenalty.penalty + apply Finset.sup'_le + intro g _ + cases g with + | none => exact le_rfl + | some g => + change -AffinePenalty.affineValue _ _ v - (d : ℝ) / (d : ℝ) ^ 8 ≤ 0 + rw [← normalized_table_affine] + change -normalizedEntry R P d v g - (d : ℝ) / (d : ℝ) ^ 8 ≤ 0 + have hb := normalizedEntry_change R P d hd hR hP hRmax hPmax hfree v x 1 + (by norm_num) hvx g + have hnonneg : 0 ≤ normalizedEntry R P d x g := + div_nonneg (hx g.1 g.2) (le_min (Nat.cast_nonneg _) (Nat.cast_nonneg _)) + have hl := (abs_le.mp hb).1 + linarith + · exact AffinePenalty.penalty_nonnegative _ _ _ _ + +end + +end ContingencyTables.DenseAffine + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q K : ℕ} + +theorem denseGridSize_pos (d : ℕ) (hd : 14 ≤ d) : 1 ≤ 4 * d ^ 8 := by + have hd₀ : 0 < d := by omega + exact Nat.succ_le_of_lt (Nat.mul_pos (by decide) (pow_pos hd₀ _)) + +theorem denseBinWeight_eq_one (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (a : Grid (I := Fin q) K) (x : Fin q → ℝ) (hx : ClosedBin (corner a) x) + (hfeas : DenseAffine.Feasible R P d (fun p => x (e p))) : + denseBinWeight R P d e a = 1 := by + have hz := DenseAffine.densePenalty_corner_zero R P d hd hR hP hRmax hPmax hfree + (fun p => realCorner a (e p)) (fun p => x (e p)) hfeas (fun p => by + change |(corner a (e p) : ℝ) - x (e p)| ≤ 1 + apply abs_le.mpr + constructor <;> linarith [(hx (e p)).1, (hx (e p)).2]) + simp only [denseBinWeight, denseGridPenalty, DenseWeights.binWeight, hz, mul_zero, + Int.floor_zero, Int.cast_zero, neg_zero, Real.rpow_zero] + +theorem denseBinWeight_le_one (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : + denseBinWeight R P d e a ≤ 1 := by + have hp : 0 ≤ denseGridPenalty R P d e (realCorner a) := + AffinePenalty.penalty_nonnegative _ _ _ _ + have hfloor : (0 : ℤ) ≤ ⌊(d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a)⌋ := + Int.floor_nonneg.mpr (mul_nonneg (by positivity) hp) + unfold denseBinWeight DenseWeights.binWeight + calc + _ ≤ (2 : ℝ) ^ (0 : ℝ) := Real.rpow_le_rpow_of_exponent_le (by norm_num) (by + have hf : (0 : ℝ) ≤ (⌊(d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a)⌋ : ℤ) := + by exact_mod_cast hfloor + linarith) + _ = 1 := Real.rpow_zero _ + +theorem denseBinWeight_lower (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + (2 : ℝ) ^ (-(4 * (d : ℝ) ^ 5)) ≤ denseBinWeight R P d e a := by + have hcube (p : I × J) : 0 ≤ realCorner a (e p) ∧ realCorner a (e p) ≤ 4 * (d : ℝ) ^ 8 := by + have hlo : (0 : ℤ) ≤ corner a (e p) := (a (e p)).property.1 + have hhi : corner a (e p) ≤ (4 * d ^ 8 : ℕ) - 1 := (a (e p)).property.2 + constructor + · change (0 : ℝ) ≤ (corner a (e p) : ℝ) + exact_mod_cast hlo + · have hupper : corner a (e p) ≤ (4 * d ^ 8 : ℕ) := by + omega + change (corner a (e p) : ℝ) ≤ 4 * (d : ℝ) ^ 8 + exact_mod_cast hupper + have hp := (DenseAffine.densePenalty_cube_bound R P d hd hR hP hRmax hPmax + hdimR hdimP hfree htotal _ hcube).2 + have hf := Int.floor_le ((d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a)) + have hm := mul_le_mul_of_nonneg_left hp (show (0 : ℝ) ≤ (d : ℝ) ^ 4 by positivity) + change (d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a) ≤ (d : ℝ) ^ 4 * (4 * d) at hm + unfold denseBinWeight DenseWeights.binWeight + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + change denseGridPenalty R P d e (realCorner a) ≤ 4 * d at hp + nlinarith [show (d : ℝ) ^ 4 * (4 * d) = 4 * (d : ℝ) ^ 5 by ring] + +theorem grid_card (q K : ℕ) : Fintype.card (Grid (I := Fin q) K) = K ^ q := by + have hc : Fintype.card (Set.Icc (0 : ℤ) ((K : ℤ) - 1)) = K := by + have h := Int.card_fintype_Icc_of_le 0 ((K : ℤ) - 1) + (show (0 : ℤ) ≤ (K : ℤ) - 1 + 1 by omega) + omega + simp only [Grid, Fintype.card_fun, Fintype.card_fin, hc] + +theorem denseBinChain_pi_lower (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + (2 : ℝ) ^ (-(4 * (d : ℝ) ^ 5)) / ((4 * (d : ℝ) ^ 8) ^ q) ≤ + (denseBinChain R P d hd hfree e (denseGridSize_pos d hd)).π a := by + let : Nonempty (Grid (I := Fin q) (4 * d ^ 8)) := ⟨a⟩ + let w := denseBinWeight R P d e (K := 4 * d ^ 8) + have hw : ∀ z, 0 < w z := fun z => DenseWeights.binWeight_pos _ _ _ + have hz : 0 < ∑ z, w z := Finset.sum_pos (fun z _ => hw z) Finset.univ_nonempty + have hsum : (∑ z, w z) ≤ (4 * (d : ℝ) ^ 8) ^ q := by + calc + _ ≤ ∑ _z : Grid (I := Fin q) (4 * d ^ 8), (1 : ℝ) := + Finset.sum_le_sum (fun z _ => denseBinWeight_le_one R P d e z) + _ = _ := by simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_one, + grid_card, Nat.cast_pow, Nat.cast_mul, Nat.cast_ofNat] + change _ ≤ w a / (∑ z, w z) + exact div_le_div₀ (hw a).le + (denseBinWeight_lower R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e a) hz hsum + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixLayoutProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixLayoutProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9a1c62d49df98e6e9456d58576f7df899a89b65 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixLayoutProgram.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseGridExponentProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseAxisWordProgram + +namespace OAI + +/-! # Polynomial conversion between flat and rectangular grid encodings -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped Polynomial + +abbrev GridFlatData := (List ℕ×List ℕ)×List ℕ + +def sliceRow (z : (ℕ×List ℕ)×ℕ) : List ℕ := + (z.1.2.drop (z.2*z.1.1)).take z.1.1 + +def sliceRowRealizer : Realizer sliceRow := + composition (pair + (composition (pair (composition first second) + (composition (pair second (composition first first)) multiply)) dropFast) + (composition first first)) takeFast + +theorem polynomial_sliceRow : PolynomialTime sliceRowRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_first)) polynomial_multiply)) + polynomial_dropFast) + (polynomial_composition polynomial_first polynomial_first)) polynomial_takeFast + +def layoutRows (z : GridFlatData) : List ℕ := List.range z.1.1.tail.length + +def layoutRowsRealizer : Realizer layoutRows := + composition (composition (composition (composition first first) tail) listLength) range + +theorem polynomial_layoutRows : PolynomialTime layoutRowsRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_tail) polynomial_listLength) X + intro z + simp only [Function.comp_apply,eval_X,List.length_tail] + exact (Nat.sub_le _ _).trans ((list_length_le_weight z.1.1).trans + ((weight_fst z.1).trans (weight_fst z))) + +def layoutRow (z : GridFlatData×ℕ) : List ℕ := + sliceRow ((z.1.1.2.tail.length,z.1.2),z.2) + +def layoutRowRealizer : Realizer layoutRow := + composition (pair (pair + (composition (composition (composition (composition first first) second) tail) listLength) + (composition first second)) second) sliceRowRealizer + +theorem polynomial_layoutRow : PolynomialTime layoutRowRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_tail) polynomial_listLength) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second) polynomial_sliceRow + +def unflattenGrid (z : GridFlatData) : MatrixCode := + (layoutRows z).map (fun i => layoutRow (z,i)) + +def unflattenGridRealizer : Realizer unflattenGrid := + composition (pair identity layoutRowsRealizer) (mapWith layoutRowRealizer) + +theorem polynomial_unflattenGrid : PolynomialTime unflattenGridRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_layoutRows) + (polynomial_mapWith polynomial_layoutRow) + +lemma flatten_matrixCode {m n : ℕ} (f : Fin (m*n) → ℕ) : + (matrixCode (fun i j => f (finProdFinEquiv (i,j)))).flatten=List.ofFn f := by + rw [List.ofFn_mul] + apply congrArg List.flatten + apply congrArg List.ofFn + funext i + apply congrArg List.ofFn + funext j + apply congrArg f + apply Fin.ext + change j.val+n*i.val=i.val*n+j.val + ac_rfl + +lemma sliceRow_ofFn {m n : ℕ} (f : Fin (m*n) → ℕ) (i : Fin m) : + sliceRow ((n,List.ofFn f),i.val)= + List.ofFn (fun j : Fin n => f (finProdFinEquiv (i,j))) := by + have hbound : n ≤ m*n-i.val*n := by + have h := Nat.mul_le_mul_right n (Nat.succ_le_of_lt i.isLt) + apply Nat.le_sub_of_add_le + simpa only [Nat.succ_mul, Nat.add_comm] using h + apply List.ext_getElem + · simp only [sliceRow,List.length_take,List.length_drop,List.length_ofFn,min_eq_left hbound] + · intro j _ _ + simp only [sliceRow,List.getElem_take,List.getElem_drop,List.getElem_ofFn] + apply congrArg f + apply Fin.ext + change i.val*n+j=j+n*i.val + ac_rfl + +theorem unflattenGrid_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (f : Fin (m*n) → ℕ) : + unflattenGrid ((marginCode R,marginCode P),List.ofFn f)= + matrixCode (fun i j => f (finProdFinEquiv (i,j))) := by + have hrows : layoutRows ((marginCode R,marginCode P),List.ofFn f)=List.range m := by + simp only [layoutRows,marginCode,List.tail_cons,List.length_ofFn] + have hcols : (marginCode P).tail.length=n := by + simp only [marginCode,List.tail_cons,List.length_ofFn] + unfold unflattenGrid matrixCode + rw [hrows] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have him : i < m := by simpa only [List.length_map,List.length_range] using hi + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn,layoutRow,hcols] + exact sliceRow_ofFn f ⟨i,him⟩ + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..79c6cecef4dcabe242c1d3e00250fe5fcf16cad9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixProgram.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixTable +import OAI.Combinatorics.ContingencyTables.Machines.IntegerMatrixProgram + +namespace OAI + +/-! # Polynomial assembly of the dense count matrix in column order -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary +open scoped BigOperators Classical + +abbrev CountMatrixContext := (List Bool×ℕ)×((List ℕ×List ℕ)×ℕ) +abbrev CountMatrixData := CountMatrixContext×List (List ℕ) + +def countMatrixEntryInput (z : (CountMatrixData×List ℕ)×List ℕ) : CountRowData×List ℕ := + ((((z.1.1.1.1,((z.1.1.1.2.1,z.2),z.1.1.1.2.2)),z.1.1.2)),z.1.2) + +def countMatrixEntryInputRealizer : Realizer countMatrixEntryInput := by + let data : Realizer (fun z : (CountMatrixData×List ℕ)×List ℕ => z.1.1) := + composition first first + let ctx := composition data first + let margins := composition (composition ctx second) first + let d := composition (composition ctx second) second + let rowData := pair (pair (composition ctx first) (pair (pair margins second) d)) + (composition data second) + exact pair rowData (composition first second) + +lemma polynomial_countMatrixEntryInput : PolynomialTime countMatrixEntryInputRealizer := by + have hd : PolynomialTime (composition + (first (A := CountMatrixData×List ℕ) (B := List ℕ)) first) := + polynomial_composition polynomial_first polynomial_first + have hc := polynomial_composition hd polynomial_first + have hm := polynomial_composition (polynomial_composition hc polynomial_second) polynomial_first + have hp := polynomial_composition (polynomial_composition hc polynomial_second) polynomial_second + unfold countMatrixEntryInputRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition hc polynomial_first) + (polynomial_pair (polynomial_pair hm polynomial_second) hp)) + (polynomial_composition hd polynomial_second)) + (polynomial_composition polynomial_first polynomial_second) + +def countMatrixEntry (z : (CountMatrixData×List ℕ)×List ℕ) : ℕ := + rowEntry (countMatrixEntryInput z) + +def countMatrixEntryRealizer : Realizer countMatrixEntry := + composition countMatrixEntryInputRealizer rowEntryRealizer + +lemma polynomial_countMatrixEntry : PolynomialTime countMatrixEntryRealizer := + polynomial_composition polynomial_countMatrixEntryInput polynomial_rowEntry + +def countColumn (z : CountMatrixData×List ℕ) : List ℕ := + z.1.2.map (fun a => countMatrixEntry (z,a)) + +def countColumnRealizer : Realizer countColumn := + composition (pair identity (composition first second)) (mapWith countMatrixEntryRealizer) + +lemma polynomial_countColumn : PolynomialTime countColumnRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_second)) + (polynomial_mapWith polynomial_countMatrixEntry) + +def countMatrix (z : CountMatrixData) : List (List ℕ) := + z.2.map (fun b => countColumn (z,b)) + +def countMatrixRealizer : Realizer countMatrix := + composition (pair identity second) (mapWith countColumnRealizer) + +/-- Preparation explicitly contains all states and one unary acceptance +allowance. Matrix construction is polynomial in precisely that data. -/ +theorem polynomial_countMatrix : PolynomialTime countMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_second) + (polynomial_mapWith polynomial_countColumn) + +lemma countMatrix_actual {m n d N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hq : m*n≤d) + (e : Fin N ≃ Grid (I := Fin (m*n)) (4*d^8)) + (xs : List Bool) (hxs : xs.length=8*d^5) : + countMatrix ((((xs,2^denseStepBits d),((marginCode R,marginCode P),d)), + List.ofFn (fun i => gridNatCode (e i))))= + List.ofFn (fun j => List.ofFn (fun i => + denseTransitionCount R P d finProdFinEquiv (e i) (e j))) := by + simp only [countMatrix,countColumn,List.map_ofFn] + apply congrArg List.ofFn + funext j + apply congrArg List.ofFn + funext i + exact rowEntry_actual R P hq e xs hxs (e i) (e j) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixTable.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixTable.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea9d7d443bd8d9b9c02d0daaaea2bc41b9578950 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixTable.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PreparedDenseCount +import OAI.Combinatorics.ContingencyTables.Machines.NatListEquality + +namespace OAI + +/-! # Constructing the actual dense transition matrix from its finite states -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary +open scoped BigOperators Classical + +/-- Shared unary allowance and binary denominator, current exponent data, +and the enumeration of all states. -/ +abbrev CountRowData := ((List Bool×ℕ)×FlatExponentData)×List (List ℕ) + +def rowOffEntry (z : CountRowData×List ℕ) : ℕ := + preparedOffCount (z.1.1.1.1,(z.1.1.2,z.2)) + +def rowOffEntryRealizer : Realizer rowOffEntry := + composition (pair + (composition (composition (composition first first) first) first) + (pair (composition (composition first first) second) second)) preparedOffCountRealizer + +lemma polynomial_rowOffEntry : PolynomialTime rowOffEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_second)) polynomial_preparedOffCount + +def rowOffCounts (z : CountRowData) : List ℕ := z.2.map (fun b => rowOffEntry (z,b)) + +def rowOffCountsRealizer : Realizer rowOffCounts := + composition (pair identity second) (mapWith rowOffEntryRealizer) + +lemma polynomial_rowOffCounts : PolynomialTime rowOffCountsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_second) + (polynomial_mapWith polynomial_rowOffEntry) + +def rowEntry (z : CountRowData×List ℕ) : ℕ := + if NatListEquality.listEqual (z.1.1.2.1.2,z.2) then + z.1.1.1.2-(rowOffCounts z.1).sum else rowOffEntry z + +def rowEntryRealizer : Realizer rowEntry := by + let current : Realizer (fun z : CountRowData×List ℕ => z.1.1.2.1.2) := + composition (composition (composition (composition first first) second) first) second + let Q : Realizer (fun z : CountRowData×List ℕ => z.1.1.1.2) := + composition (composition (composition first first) first) second + let total := composition (composition + (first (A := CountRowData) (B := List ℕ)) rowOffCountsRealizer) listSum + exact choose (composition (pair current second) NatListEquality.listEqualRealizer) + (composition (pair Q total) subtract) rowOffEntryRealizer + +lemma polynomial_rowEntry : PolynomialTime rowEntryRealizer := by + have hc : PolynomialTime (composition (composition (composition + (composition (first (A := CountRowData) (B := List ℕ)) first) second) first) second) := + polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) polynomial_first) + polynomial_second + have hQ : PolynomialTime (composition (composition (composition + (first (A := CountRowData) (B := List ℕ)) first) first) second) := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second + unfold rowEntryRealizer + exact polynomial_choose (polynomial_composition (polynomial_pair hc polynomial_second) + NatListEquality.polynomial_listEqual) + (polynomial_composition (polynomial_pair hQ + (polynomial_composition (polynomial_composition polynomial_first polynomial_rowOffCounts) + polynomial_listSum)) polynomial_subtract) polynomial_rowOffEntry + +lemma rowEntry_actual {m n d N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hq : m*n≤d) + (e : Fin N ≃ Grid (I := Fin (m*n)) (4*d^8)) + (xs : List Bool) (hxs : xs.length=8*d^5) + (a b : Grid (I := Fin (m*n)) (4*d^8)) : + rowEntry (((((xs,2^denseStepBits d), + (((marginCode R,marginCode P),gridNatCode a),d)), + List.ofFn (fun i => gridNatCode (e i)))),gridNatCode b)= + denseTransitionCount R P d finProdFinEquiv a b := by + have hoff (b : Grid (I := Fin (m*n)) (4*d^8)) : + rowOffEntry (((((xs,2^denseStepBits d), + (((marginCode R,marginCode P),gridNatCode a),d)), + List.ofFn (fun i => gridNatCode (e i)))),gridNatCode b)= + FiniteAcceptCounts.offCount a + (fun z : Fin (2^Nat.clog 2 (8*d)) => axisCodeStep a z) + (fun b => denseExponent R P d finProdFinEquiv b- + denseExponent R P d finProdFinEquiv a) (8*d^5) b := by + unfold rowOffEntry + rw [preparedOffCount_eq xs _ hxs] + exact offCountCode_actual R P hq a b + have hs : (rowOffCounts ((((xs,2^denseStepBits d), + (((marginCode R,marginCode P),gridNatCode a),d)), + List.ofFn (fun i => gridNatCode (e i))))).sum= + ∑ b,FiniteAcceptCounts.offCount a + (fun z : Fin (2^Nat.clog 2 (8*d)) => axisCodeStep a z) + (fun b => denseExponent R P d finProdFinEquiv b- + denseExponent R P d finProdFinEquiv a) (8*d^5) b := by + simp only [rowOffCounts,List.map_ofFn,Function.comp_apply,hoff,List.sum_ofFn] + exact e.sum_comp _ + have he : NatListEquality.listEqual (gridNatCode a,gridNatCode b)=true ↔ a=b := by + rw [NatListEquality.listEqual_true] + exact ⟨fun h => gridNatCode_injective h,fun h => congrArg gridNatCode h⟩ + unfold rowEntry denseTransitionCount FiniteAcceptCounts.row + rw [hs,hoff] + by_cases hab : a=b + · subst b + have hh : FiniteAcceptCounts.offCount a + (fun z : Fin (2^Nat.clog 2 (8*d)) => axisCodeStep a z) + (fun b => denseExponent R P d finProdFinEquiv b- + denseExponent R P d finProdFinEquiv a) (8*d^5) a=0 := by + simp [FiniteAcceptCounts.offCount] + simp [he,hh,FiniteAcceptCounts.denominator,denseStepBits,pow_add] + · have hh : NatListEquality.listEqual (gridNatCode a,gridNatCode b)=false := + Bool.eq_false_iff.mpr (fun h => hab (he.mp h)) + simp [hh,Ne.symm hab] + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixWalk.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..df5fb635fe2ff92a23028b926bc366f1945b00aa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMatrixWalk.lean @@ -0,0 +1,137 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixProgram + +namespace OAI + +/-! # Binary matrix propagation of the implemented dense walk -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary +open scoped BigOperators Classical + +abbrev MatrixWalkData := (List Bool×CountMatrixData)×List ℕ + +def initialEntry (z : List ℕ×List ℕ) : ℕ := + if NatListEquality.listEqual z then 1 else 0 + +def initialEntryRealizer : Realizer initialEntry := + choose NatListEquality.listEqualRealizer (constant 1) (constant 0) + +lemma polynomial_initialEntry : PolynomialTime initialEntryRealizer := + polynomial_choose NatListEquality.polynomial_listEqual + (polynomial_constant 1) (polynomial_constant 0) + +def initialVector (z : List (List ℕ)×List ℕ) : List ℕ := + z.1.map (fun a => initialEntry (z.2,a)) + +def initialVectorRealizer : Realizer initialVector := + composition (pair second first) (mapWith initialEntryRealizer) + +lemma polynomial_initialVector : PolynomialTime initialVectorRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_initialEntry) + +def matrixWalkInput (z : MatrixWalkData) : ℕ×(List (List ℕ)×List ℕ) := + (z.1.1.length,(countMatrix z.1.2,initialVector (z.1.2.2,z.2))) + +def matrixWalkInputRealizer : Realizer matrixWalkInput := + pair (composition (composition first first) listLength) + (pair (composition (composition first second) countMatrixRealizer) + (composition (pair (composition (composition first second) second) second) + initialVectorRealizer)) + +lemma polynomial_matrixWalkInput : PolynomialTime matrixWalkInputRealizer := + polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_listLength) + (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_countMatrix) + (polynomial_composition (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_second) polynomial_initialVector)) + +def matrixWalk (z : MatrixWalkData) : List ℕ := + IntegerMatrixPrograms.iterate (matrixWalkInput z) + +def matrixWalkRealizer : Realizer matrixWalk := + composition matrixWalkInputRealizer IntegerMatrixPrograms.iterateRealizer + +/-- The number of matrix steps is supplied by a unary list. All entries +and the propagated vector use binary integers. -/ +theorem polynomial_matrixWalk : PolynomialTime matrixWalkRealizer := by + obtain ⟨p,hp⟩ := polynomial_matrixWalkInput + apply work_composition ⟨p,hp⟩ IntegerMatrixPrograms.work_iterate (Polynomial.X+p) + intro z + have hl : z.1.1.length ≤ weight z := (list_length_le_weight z.1.1).trans + ((weight_fst z.1).trans (weight_fst z)) + have hw := weight_snd (matrixWalkInput z) + have hc := hp z + simp only [Polynomial.eval_add,Polynomial.eval_X,matrixWalkInput] at * + omega + +lemma initialVector_actual {m n d N : ℕ} + (e : Fin N ≃ Grid (I := Fin (m*n)) (4*d^8)) (start : Fin N) : + initialVector (List.ofFn (fun i => gridNatCode (e i)),gridNatCode (e start))= + List.ofFn (fun i => if i=start then 1 else 0) := by + simp only [initialVector,List.map_ofFn] + apply congrArg List.ofFn + funext i + have he : NatListEquality.listEqual (gridNatCode (e start),gridNatCode (e i))=true ↔ + i=start := by + rw [NatListEquality.listEqual_true] + constructor + · intro h + exact (e.injective (gridNatCode_injective h)).symm + · rintro rfl + rfl + change (if NatListEquality.listEqual (gridNatCode (e start),gridNatCode (e i))=true + then (1:ℕ) else 0)=(if i=start then 1 else 0) + by_cases hi : i=start + · simp only [ite_eq_left (he.mpr hi),ite_eq_left hi] + · have hh : NatListEquality.listEqual (gridNatCode (e start),gridNatCode (e i))=false := + Bool.eq_false_iff.mpr (fun h => hi (he.mp h)) + simp [hh,hi] + +private lemma numerators_reindex {A B : Type*} [Fintype A] [Fintype B] + [DecidableEq A] [DecidableEq B] (e : A ≃ B) (M : B → B → ℕ) + (start : A) (N : ℕ) (y : A) : + IntegerPropagation.numerators (fun x y => M (e x) (e y)) start N y= + IntegerPropagation.numerators M (e start) N (e y) := by + induction N generalizing y with + | zero => simp [IntegerPropagation.numerators,e.injective.eq_iff] + | succ N ih => + simp only [IntegerPropagation.numerators,ih] + exact e.sum_comp (fun x => IntegerPropagation.numerators M (e start) N x*M x (e y)) + +/-- The matrix is the count matrix of the actual Boolean walk, including +all rejected proposals and unused proposal codes. -/ +theorem matrixWalk_actual {m n d N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hq : m*n≤d) + (e : Fin N ≃ Grid (I := Fin (m*n)) (4*d^8)) + (xs steps : List Bool) (hxs : xs.length=8*d^5) (start : Fin N) : + matrixWalk ((steps,(((xs,2^denseStepBits d),((marginCode R,marginCode P),d)), + List.ofFn (fun i => gridNatCode (e i)))),gridNatCode (e start))= + List.ofFn (fun i => IntegerPropagation.numerators + (denseTransitionCount R P d finProdFinEquiv) (e start) steps.length (e i)) := by + unfold matrixWalk matrixWalkInput + rw [countMatrix_actual R P hq e xs hxs,initialVector_actual] + rw [IntegerMatrixPrograms.iterate_ofFn] + congr 1 + funext i + exact numerators_reindex e _ start steps.length i + +/-- A matrix-vector entry, normalized by its known dyadic denominator, +is the mass of the implemented finite-bit walk. -/ +theorem matrixWalk_mass {m n d N : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hq : m*n≤d) + (e : Fin N ≃ Grid (I := Fin (m*n)) (4*d^8)) + (xs steps : List Bool) (hxs : xs.length=8*d^5) (start i : Fin N) : + ((matrixWalk ((steps,(((xs,2^denseStepBits d),((marginCode R,marginCode P),d)), + List.ofFn (fun i => gridNatCode (e i)))),gridNatCode (e start))).getD i.val 0:ℚ)/ + (2:ℚ)^(steps.length*denseStepBits d)= + (denseBooleanWalkLaw R P d finProdFinEquiv (e start) steps.length).mass (e i) := by + rw [matrixWalk_actual R P hq e xs steps hxs start] + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt] + exact denseWalkCount_mass R P d finProdFinEquiv (e start) (e i) steps.length + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMaximalReindex.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMaximalReindex.lean new file mode 100644 index 0000000000000000000000000000000000000000..388d61cbc7aa79dc7b8cb6aaa4d8231194785240 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMaximalReindex.lean @@ -0,0 +1,113 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanDraw +import OAI.Combinatorics.ContingencyTables.Transport.TableReindex +import Mathlib.Data.Finset.Max + +namespace OAI + +/-! # Dense draws with arbitrary choices of the reference row and column -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess FairBits + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +omit [DecidableEq I] in +private lemma maximal_index_exists (R : Option I → ℕ) : ∃ i,∀ j,R j ≤ R i := by + obtain ⟨i,_,hi⟩ := Finset.exists_max_image Finset.univ R Finset.univ_nonempty + exact ⟨i,fun j => hi j (Finset.mem_univ j)⟩ + +def maximalIndex (R : Option I → ℕ) : Option I := Classical.choose (maximal_index_exists R) + +def maximalReindex (R : Option I → ℕ) : Option I ≃ Option I := + Equiv.swap none (maximalIndex R) + +abbrev maximalMargin (R : Option I → ℕ) : Option I → ℕ := fun i => R (maximalReindex R i) + +lemma maximalMargin_max (R : Option I → ℕ) (i : I) : + maximalMargin R (some i) ≤ maximalMargin R none := by + unfold maximalMargin maximalReindex + rw [Equiv.swap_apply_left] + exact Classical.choose_spec (maximal_index_exists R) _ + +lemma maximalMargin_lower (R : Option I → ℕ) (L : ℕ) (hR : ∀ i,L ≤ R i) : + ∀ i,L ≤ maximalMargin R i := fun _i => hR _ + +lemma maximalMargin_total (R : Option I → ℕ) : ∑ i,maximalMargin R i=∑ i,R i := + (maximalReindex R).sum_comp R + +variable {q : ℕ} + +abbrev reindexedDrawBits (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I×J ≃ Fin q) (h : ℕ) : ℕ := + denseDrawBits (maximalMargin R) (maximalMargin P) d e h + +/-- Move a largest row and column to the distinguished indices inside the +sampler, then transport the output back to the fixed original indices. -/ +def reindexedBooleanDraw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i,d^12 ≤ R i) (hP : ∀ j,d^12 ≤ P j) + (e : I×J ≃ Fin q) (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin q) (4*d^8)) (fallback : Table R P) + (bits : Fin (reindexedDrawBits R P d e h) → Bool) : Table R P := + (tableReindex (maximalReindex R) (maximalReindex P) R P).symm + (denseBooleanDraw (maximalMargin R) (maximalMargin P) d hd + (maximalMargin_lower R _ hR) (maximalMargin_lower P _ hP) e + (by rw [maximalMargin_total,maximalMargin_total]; exact htotal) h a + ((tableReindex (maximalReindex R) (maximalReindex P) R P) fallback) bits) + +def reindexedBooleanDrawLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i,d^12 ≤ R i) (hP : ∀ j,d^12 ≤ P j) + (e : I×J ≃ Fin q) (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin q) (4*d^8)) (fallback : Table R P) : RationalLaw (Table R P) := + mapLaw (uniformLaw (α := Fin (reindexedDrawBits R P d e h) → Bool)) + (reindexedBooleanDraw R P d hd hR hP e htotal h a fallback) + +/-- The fixed reference used by the outer chain need not maximize either +residual margin. The actual Boolean draw retains the same TV guarantee. -/ +theorem reindexedBooleanDraw_variation (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i,d^12 ≤ R i) (hP : ∀ j,d^12 ≤ P j) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I×J) ≤ d) (htotal : ∑ i,R i=∑ j,P j) + (e : I×J ≃ Fin q) (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4*d^8))) + (h : ℕ) (a : Grid (I := Fin q) (4*d^8)) (fallback : Table R P) : + let _ : Nonempty (Table R P) := ⟨fallback⟩ + (variation (reindexedBooleanDrawLaw R P d hd hR hP e htotal h a fallback) + (uniformLaw (α := Table R P)) : ℝ) ≤ (2:ℝ)^(-(h:ℝ)) := by + let E := tableReindex (maximalReindex R) (maximalReindex P) R P + let : Nonempty (Table R P) := ⟨fallback⟩ + let : Nonempty (Table (maximalMargin R) (maximalMargin P)) := ⟨E fallback⟩ + have heq : (∑ i,maximalMargin R i)=∑ j,maximalMargin P j := by + rw [maximalMargin_total,maximalMargin_total] + exact htotal + have hdraw := denseBooleanDraw_variation (maximalMargin R) (maximalMargin P) d hd + (maximalMargin_lower R _ hR) (maximalMargin_lower P _ hP) + (maximalMargin_max R) (maximalMargin_max P) hdimR hdimP hfree heq e hPL hCheeger h a (E fallback) + dsimp only at ⊢ + unfold reindexedBooleanDrawLaw reindexedBooleanDraw + rw [mapLaw_equiv_output] + change (variation (equivLaw E.symm (denseBooleanDrawLaw (maximalMargin R) (maximalMargin P) + d hd (maximalMargin_lower R _ hR) (maximalMargin_lower P _ hP) e heq h a (E fallback))) + (uniformLaw (α := Table R P)) : ℝ) ≤ _ + rw [← uniform_equiv E.symm,variation_equiv] + exact hdraw + + +/-- Relabeling preserves the polynomial Boolean-source bound. A bound on +row margins already bounds every integer quotient width. -/ +theorem reindexedDrawBits_polynomial (R : Option I → ℕ) (P : Option J → ℕ) + (d C b h : ℕ) (e : I×J ≃ Fin q) (hq : q ≤ d) + (hR : ∀ i,R i ≤ C) (hb : Nat.clog 2 (C+2) ≤ b) : + reindexedDrawBits R P d e h ≤ 25*(d+b+h+1)^62 := by + apply denseDrawBits_polynomial (maximalMargin R) (maximalMargin P) d C b h e hq + · intro p + exact (Nat.div_le_self _ _).trans ((min_le_left _ _).trans (hR _)) + · exact hb + +end +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMetropolisProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMetropolisProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..94071d4af9851e25095552adc0b5c2de2f421f3e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMetropolisProgram.lean @@ -0,0 +1,91 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseFlatExponentProgram +import OAI.Combinatorics.ContingencyTables.Machines.DyadicWordProgram + +namespace OAI + +/-! # A polynomial binary program for a full dense Metropolis step -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev FlatStepData := FlatExponentData×(List Bool×List Bool) + +def replaceFlat (z : FlatExponentData×List ℕ) : FlatExponentData := + ((z.1.1.1,z.2),z.1.2) + +def replaceFlatRealizer : Realizer replaceFlat := + pair (pair (composition (composition first first) first) second) (composition first second) + +lemma polynomial_replaceFlat : PolynomialTime replaceFlatRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_second) (polynomial_composition polynomial_first polynomial_second) + +def flatAcceptCandidate (z : FlatStepData×List ℕ) : List ℕ := + if dyadicWordAccept (z.1.2.2, + flatExponent (replaceFlat (z.1.1,z.2))-flatExponent z.1.1) then z.2 else z.1.1.1.2 + +def flatAcceptCandidateRealizer : Realizer flatAcceptCandidate := by + let data : Realizer (fun z : FlatStepData×List ℕ => z.1.1) := composition first first + let candidate := composition (composition (pair data second) replaceFlatRealizer) flatExponentRealizer + let current := composition data flatExponentRealizer + let gap := composition (pair candidate current) subtract + let coins : Realizer (fun z : FlatStepData×List ℕ => z.1.2.2) := + composition (composition first second) second + exact choose (composition (pair coins gap) dyadicWordAcceptRealizer) second + (composition (composition data first) second) + +theorem polynomial_flatAcceptCandidate : PolynomialTime flatAcceptCandidateRealizer := by + have hd : PolynomialTime (composition + (first (A := FlatStepData) (B := List ℕ)) first) := + polynomial_composition polynomial_first polynomial_first + have hc := polynomial_composition (polynomial_composition + (polynomial_pair hd polynomial_second) polynomial_replaceFlat) polynomial_flatExponent + have hx := polynomial_composition hd polynomial_flatExponent + have hg := polynomial_composition (polynomial_pair hc hx) polynomial_subtract + have hb : PolynomialTime (composition + (composition (first (A := FlatStepData) (B := List ℕ)) second) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second + unfold flatAcceptCandidateRealizer + exact polynomial_choose (polynomial_composition (polynomial_pair hb hg) polynomial_dyadicWordAccept) + polynomial_second (polynomial_composition (polynomial_composition hd polynomial_first) polynomial_second) + +def flatStepCandidate (z : FlatStepData) : Option (List ℕ) := + axisWordStep ((4*z.1.2^8,z.1.1.2),z.2.1) + +def flatStepCandidateRealizer : Realizer flatStepCandidate := by + let d : Realizer (fun z : FlatStepData => z.1.2) := composition first second + let K := composition (pair (constant 4) (composition d eighthPower)) multiply + let xs : Realizer (fun z : FlatStepData => z.1.1.2) := + composition (composition first first) second + exact composition (pair (pair K xs) (composition second first)) axisWordStepRealizer + +theorem polynomial_flatStepCandidate : PolynomialTime flatStepCandidateRealizer := by + have hd : PolynomialTime (composition + (first (A := FlatExponentData) (B := List Bool×List Bool)) second) := + polynomial_composition polynomial_first polynomial_second + have hK := polynomial_composition (polynomial_pair (polynomial_constant 4) + (polynomial_composition hd polynomial_eighthPower)) polynomial_multiply + unfold flatStepCandidateRealizer + exact polynomial_composition (polynomial_pair (polynomial_pair hK + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second)) + (polynomial_composition polynomial_second polynomial_first)) polynomial_axisWordStep + +def flatMetropolisStep (z : FlatStepData) : List ℕ := + (flatStepCandidate z).elim z.1.1.2 (fun xs => flatAcceptCandidate (z,xs)) + +def flatMetropolisStepRealizer : Realizer flatMetropolisStep := + composition (pair identity flatStepCandidateRealizer) + (optionCases (composition (composition first first) second) flatAcceptCandidateRealizer) + +/-- Includes proposal decoding, exact integer exponent evaluation and the +independent acceptance word. Every finite input terminates in polynomial time. -/ +theorem polynomial_flatMetropolisStep : PolynomialTime flatMetropolisStepRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_flatStepCandidate) + (polynomial_optionCases + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_flatAcceptCandidate) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMetropolisSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMetropolisSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..af24d1556ce3b1a10ea4cfc791d5af323404f314 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMetropolisSemantics.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanStep + +namespace OAI + +/-! # The binary dense program realizes the exact finite transition -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary FairBits +open scoped Classical + +noncomputable section + +theorem flatMetropolisStep_pair {m n d p k : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) + (proposal : Fin p → Bool) (coins : Fin k → Bool) : + flatMetropolisStep ((((marginCode R,marginCode P),gridNatCode a),d), + (List.ofFn proposal,List.ofFn coins)) = + gridNatCode (match axisCodeStep a (binaryWordEquiv p proposal) with + | none => a + | some b => if acceptDyadic + (denseExponent R P d finProdFinEquiv b-denseExponent R P d finProdFinEquiv a) + k (binaryWordEquiv k coins) then b else a) := by + have hc : flatStepCandidate ((((marginCode R,marginCode P),gridNatCode a),d), + (List.ofFn proposal,List.ofFn coins)) = + (axisCodeStep a (binaryWordEquiv p proposal)).map gridNatCode := + axisWordStep_eq a proposal + unfold flatMetropolisStep + rw [hc] + cases h : axisCodeStep a (binaryWordEquiv p proposal) with + | none => rfl + | some b => + simp only [Option.map_some,Option.elim_some,flatAcceptCandidate,replaceFlat] + simp only [flatExponent_code,dyadicWordAccept_ofFn,decide_eq_true_eq] + split_ifs <;> rfl + +lemma ofFn_split_take {p k : ℕ} (bits : Fin (p+k) → Bool) : + (List.ofFn bits).take p=List.ofFn ((splitWordEquiv p k bits).1) := by + apply List.ext_getElem + · simp only [List.length_take,List.length_ofFn,Nat.min_eq_left (Nat.le_add_right p k)] + · intro i hi hj + simp only [List.getElem_take,List.getElem_ofFn] + rfl + +lemma ofFn_split_drop {p k : ℕ} (bits : Fin (p+k) → Bool) : + (List.ofFn bits).drop p=List.ofFn ((splitWordEquiv p k bits).2) := by + apply List.ext_getElem + · simp only [List.length_drop,List.length_ofFn,Nat.add_sub_cancel_left] + · intro i hi hj + simp only [List.getElem_drop,List.getElem_ofFn] + apply congrArg bits + apply Fin.ext + change p+i=p+i + rfl + +/-- Exact pointwise agreement, hence every finite-word law and mixing +bound for `denseBitStep` applies to the polynomial list implementation. -/ +theorem flatWordStep_code {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) (bits : Fin (denseStepBits d) → Bool) : + flatWordStep ((((marginCode R,marginCode P),gridNatCode a),d),List.ofFn bits)= + gridNatCode (denseBitStep R P d finProdFinEquiv a bits) := by + dsimp only [flatWordStep,proposalWidth] + have ht := ofFn_split_take (p := Nat.clog 2 (8*d)) (k := 8*d^5) bits + have hd := ofFn_split_drop (p := Nat.clog 2 (8*d)) (k := 8*d^5) bits + have hp : ((List.ofFn bits).take (Nat.clog 2 (8*d)), + (List.ofFn bits).drop (Nat.clog 2 (8*d))) = + (List.ofFn (splitWordEquiv (Nat.clog 2 (8*d)) (8*d^5) bits).1, + List.ofFn (splitWordEquiv (Nat.clog 2 (8*d)) (8*d^5) bits).2) := by + apply Prod.ext + · exact ht + · exact hd + have h := congrArg (fun z => flatMetropolisStep + ((((marginCode R,marginCode P),gridNatCode a),d),z)) hp + refine h.trans ((flatMetropolisStep_pair R P a + (splitWordEquiv (Nat.clog 2 (8*d)) (8*d^5) bits).1 + (splitWordEquiv (Nat.clog 2 (8*d)) (8*d^5) bits).2).trans ?_) + change gridNatCode (match axisCodeStep a (pairWordEquiv (Nat.clog 2 (8*d)) (8*d^5) bits).1 with + | none => a + | some b => if acceptDyadic + (denseExponent R P d finProdFinEquiv b-denseExponent R P d finProdFinEquiv a) + (8*d^5) (pairWordEquiv (Nat.clog 2 (8*d)) (8*d^5) bits).2 then b else a)=_ + unfold denseBitStep + dsimp only + cases axisCodeStep a (pairWordEquiv (Nat.clog 2 (8*d)) (8*d^5) bits).1 with + | none => rfl + | some b => + dsimp only + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMixing.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMixing.lean new file mode 100644 index 0000000000000000000000000000000000000000..e75266b44d51c53c434444487c3e2f97361db1d9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseMixing.lean @@ -0,0 +1,209 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseLocalGeometry + +namespace OAI + +/-! # Numerical Poincaré and point mixing for the dense bin sampler -/ + +namespace ContingencyTables.GridBoundary + +open CommonBasesFPRAS +open scoped BigOperators + +noncomputable section + +theorem denseCutConstant_lower (d : ℕ) (hd : 14 ≤ d) : + 1 / (8192 * (d : ℝ) ^ 10) ≤ denseCutConstant d (4 * d ^ 8) := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + calc + _ = (1 / (16 * (d : ℝ))) / (128 * (d : ℝ) * (4 * d ^ 8 : ℕ)) := by + push_cast + field_simp + ring + _ ≤ _ := div_le_div_of_nonneg_right (binProposal_bounds d hd).2.1 (by positivity) + +theorem densePoincareConstant_upper (d : ℕ) (hd : 14 ≤ d) : + 2 / (denseCutConstant d (4 * d ^ 8)) ^ 2 ≤ (d : ℝ) ^ 32 := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hk := denseCutConstant_lower d hd + have hc : (134217728 : ℝ) ≤ (d : ℝ) ^ 12 := by + exact_mod_cast (show 134217728 ≤ d ^ 12 from + (by norm_num : 134217728 ≤ 14 ^ 12).trans (Nat.pow_le_pow_left hd 12)) + calc + _ ≤ 2 / (1 / (8192 * (d : ℝ) ^ 10)) ^ 2 := by + apply div_le_div_of_nonneg_left (by norm_num) (by positivity) + exact pow_le_pow_left₀ (by positivity) hk 2 + _ = 134217728 * (d : ℝ) ^ 20 := by field_simp; ring + _ ≤ (d : ℝ) ^ 12 * (d : ℝ) ^ 20 := by gcongr + _ = _ := by ring + +theorem dense_min_mass_exponential (d q : ℕ) (hd : 14 ≤ d) (hq : q ≤ d) : + Real.exp (-(d : ℝ) ^ 10) ≤ + (2 : ℝ) ^ (-(4 * (d : ℝ) ^ 5)) / (4 * (d : ℝ) ^ 8) ^ q := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hd₁ : (1 : ℝ) ≤ d := by exact_mod_cast (show 1 ≤ d by omega) + have hk : (0 : ℝ) < 4 * (d : ℝ) ^ 8 := by positivity + have hl₂ : Real.log 2 ≤ 1 := by + have h := Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2) + linarith + have hlK : Real.log (4 * (d : ℝ) ^ 8) ≤ 4 * (d : ℝ) ^ 8 := by + have h := Real.log_le_sub_one_of_pos hk + linarith + have hq' : (q : ℝ) ≤ d := by exact_mod_cast hq + have hp : (d : ℝ) ^ 5 ≤ (d : ℝ) ^ 9 := pow_le_pow_right₀ hd₁ (by decide) + have hsum : 4 * (d : ℝ) ^ 5 * Real.log 2 + + (q : ℝ) * Real.log (4 * (d : ℝ) ^ 8) ≤ (d : ℝ) ^ 10 := by + calc + _ ≤ 4 * (d : ℝ) ^ 5 + (q : ℝ) * (4 * (d : ℝ) ^ 8) := by + have h1 := mul_le_mul_of_nonneg_left hl₂ (show (0 : ℝ) ≤ 4 * (d : ℝ) ^ 5 by positivity) + have h2 := mul_le_mul_of_nonneg_left hlK (show (0 : ℝ) ≤ q by positivity) + linarith + _ ≤ 4 * (d : ℝ) ^ 9 + d * (4 * (d : ℝ) ^ 8) := by gcongr + _ = 8 * (d : ℝ) ^ 9 := by ring + _ ≤ d * (d : ℝ) ^ 9 := by + apply mul_le_mul_of_nonneg_right (by exact_mod_cast (show 8 ≤ d by omega)) (by positivity) + _ = _ := by ring + have hpow : (4 * (d : ℝ) ^ 8) ^ q = + Real.exp ((q : ℝ) * Real.log (4 * (d : ℝ) ^ 8)) := by + rw [Real.exp_nat_mul, Real.exp_log hk] + rw [Real.rpow_def_of_pos (by norm_num : (0 : ℝ) < 2), hpow, ← Real.exp_sub] + apply Real.exp_le_exp.mpr + nlinarith + +theorem dense_mixing_time_arithmetic (d q h : ℕ) (hd : 14 ≤ d) (hq : q ≤ d) : + Real.exp (-((d ^ 50 * (h + 1) ^ 2 : ℕ) : ℝ) / (d : ℝ) ^ 32) / + ((2 : ℝ) ^ (-(4 * (d : ℝ) ^ 5)) / (4 * (d : ℝ) ^ 8) ^ q) ≤ + (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have h₉ : 8 ≤ d ^ 9 := (show 8 ≤ d by omega).trans (Nat.le_self_pow (by decide) d) + have h₈ : 2 ≤ d ^ 8 := (show 2 ≤ d by omega).trans (Nat.le_self_pow (by decide) d) + have h₁₀ : 8 * d ≤ d ^ 10 := by + calc + _ ≤ d ^ 9 * d := Nat.mul_le_mul_right d h₉ + _ = _ := by ring + have h₁₈ : 2 * d ^ 10 ≤ d ^ 18 := by + calc + _ ≤ d ^ 8 * d ^ 10 := Nat.mul_le_mul_right _ h₈ + _ = _ := by ring + have hbase : (d : ℝ) ^ 10 + 4 * d + 4 ≤ (d : ℝ) ^ 18 := by + exact_mod_cast (show d ^ 10 + 4 * d + 4 ≤ d ^ 18 by omega) + have hh : (0 : ℝ) ≤ h := by positivity + have hquad : (h : ℝ) + 1 ≤ ((h : ℝ) + 1) ^ 2 := by nlinarith + have htime : (d : ℝ) ^ 10 + 4 * ((h : ℝ) + d) ≤ + (d : ℝ) ^ 18 * ((h : ℝ) + 1) ^ 2 := by + have h1 := mul_le_mul_of_nonneg_right hbase (show 0 ≤ (h : ℝ) + 1 by positivity) + have h2 := mul_le_mul_of_nonneg_left hquad (show (0 : ℝ) ≤ (d : ℝ) ^ 18 by positivity) + nlinarith [show (0 : ℝ) ≤ (d : ℝ) ^ 10 * h by positivity] + calc + _ ≤ Real.exp (-((d ^ 50 * (h + 1) ^ 2 : ℕ) : ℝ) / (d : ℝ) ^ 32) / + Real.exp (-(d : ℝ) ^ 10) := + div_le_div_of_nonneg_left (Real.exp_pos _).le (Real.exp_pos _) + (dense_min_mass_exponential d q hd hq) + _ = Real.exp (-(d : ℝ) ^ 18 * ((h : ℝ) + 1) ^ 2 + (d : ℝ) ^ 10) := by + rw [← Real.exp_sub] + congr 1 + push_cast + field_simp + ring + _ ≤ Real.exp (-(4 * ((h : ℝ) + d))) := Real.exp_le_exp.mpr (by linarith) + _ ≤ (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) := by + rw [Real.rpow_def_of_pos (by norm_num : (0 : ℝ) < 2)] + apply Real.exp_le_exp.mpr + have hl := Real.log_le_sub_one_of_pos (by norm_num : (0 : ℝ) < 2) + nlinarith + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +theorem denseBinChain_polynomial_poincare (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4 * d ^ 8))) : + let hK : 1 ≤ 4 * d ^ 8 := denseGridSize_pos d hd + ∀ f : Grid (I := Fin q) (4 * d ^ 8) → ℝ, + (denseBinChain R P d hd hfree e hK).variance f ≤ + (d : ℝ) ^ 32 * (denseBinChain R P d hd hfree e hK).energy f := by + dsimp only + intro f + exact (denseBinChain_poincare R P d hd hR hP hRmax hPmax hfree e _ hPL hCheeger f).trans + (mul_le_mul_of_nonneg_right (densePoincareConstant_upper d hd) (FiniteChain.energy_nonneg _ f)) + +theorem denseBinChain_point_mixing (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4 * d ^ 8))) + (n : ℕ) (a b : Grid (I := Fin q) (4 * d ^ 8)) : + let hK : 1 ≤ 4 * d ^ 8 := denseGridSize_pos d hd + let C := denseBinChain R P d hd hfree e hK + |C.iterate n (C.pointDensity b) a - 1| ≤ + Real.exp (-(n : ℝ) / (d : ℝ) ^ 32) / + ((2 : ℝ) ^ (-(4 * (d : ℝ) ^ 5)) / (4 * (d : ℝ) ^ 8) ^ q) := by + dsimp only + have hd₁ : (1 : ℝ) ≤ d := by exact_mod_cast (show 1 ≤ d by omega) + apply FiniteChain.point_mixing_exp + · exact one_le_pow₀ hd₁ + · positivity + · exact denseBinChain_pi_lower R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal e + · exact denseBinChain_polynomial_poincare R P d hd hR hP hRmax hPmax hfree e hPL hCheeger + +theorem denseBinChain_relative_mixing (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4 * d ^ 8))) + (h : ℕ) (a b : Grid (I := Fin q) (4 * d ^ 8)) : + let C := denseBinChain R P d hd hfree e (denseGridSize_pos d hd) + |C.iterate (d ^ 50 * (h + 1) ^ 2) (C.pointDensity b) a - 1| ≤ + (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) := by + have hq : q ≤ d := by + have hc := Fintype.card_congr e + rw [Fintype.card_fin] at hc + omega + exact (denseBinChain_point_mixing R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal + e hPL hCheeger _ a b).trans (dense_mixing_time_arithmetic d q h hd hq) + +/-- Total variation for the actual law, written as its density against the +proved stationary distribution. The pointwise relative bound is stronger +than the manuscript's total-variation conclusion. -/ +theorem denseBinChain_total_variation (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4 * d ^ 8))) + (h : ℕ) (b : Grid (I := Fin q) (4 * d ^ 8)) : + let C := denseBinChain R P d hd hfree e (denseGridSize_pos d hd) + (∑ a, |C.π a * C.iterate (d ^ 50 * (h + 1) ^ 2) (C.pointDensity b) a - C.π a|) / 2 ≤ + (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) := by + let C := denseBinChain R P d hd hfree e (denseGridSize_pos d hd) + let δ := (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) + have hpoint (a : Grid (I := Fin q) (4 * d ^ 8)) : + |C.π a * C.iterate (d ^ 50 * (h + 1) ^ 2) (C.pointDensity b) a - C.π a| ≤ C.π a * δ := by + calc + _ = C.π a * |C.iterate (d ^ 50 * (h + 1) ^ 2) (C.pointDensity b) a - 1| := by + calc + _ = |C.π a * (C.iterate (d ^ 50 * (h + 1) ^ 2) (C.pointDensity b) a - 1)| := by + congr 1 + ring + _ = _ := by rw [abs_mul, abs_of_pos (C.positive a)] + _ ≤ _ := mul_le_mul_of_nonneg_left + (denseBinChain_relative_mixing R P d hd hR hP hRmax hPmax hdimR hdimP hfree htotal + e hPL hCheeger h a b) (C.positive a).le + have hsum := Finset.sum_le_sum (fun a (_ : a ∈ Finset.univ) => hpoint a) + rw [← Finset.sum_mul, C.normalized, one_mul] at hsum + change _ ≤ δ + have hδ : 0 ≤ δ := (Real.rpow_pos_of_pos (by norm_num) _).le + linarith + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizeProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizeProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c76fa8927e151ea7936b33bfeaa25513ba0496d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizeProgram.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseSwapProgram + +namespace OAI + +/-! # Moving maximal margins into the distinguished positions -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped + +def swapMargins (z : (ℕ×ℕ)×(List ℕ×List ℕ)) : List ℕ×List ℕ := + (swapZeroList (z.1.1,z.2.1),swapZeroList (z.1.2,z.2.2)) + +def swapMarginsRealizer : Realizer swapMargins := + pair (composition (pair (composition first first) (composition second first)) swapZeroListRealizer) + (composition (pair (composition first second) (composition second second)) swapZeroListRealizer) + +theorem polynomial_swapMargins : PolynomialTime swapMarginsRealizer := + polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) polynomial_swapZeroList) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) polynomial_swapZeroList) + +def swapFlatData (z : (ℕ×ℕ)×FlatExponentData) : FlatExponentData := + ((swapMargins (z.1,z.2.1.1),z.2.1.2),z.2.2) + +def swapFlatDataRealizer : Realizer swapFlatData := by + let data : Realizer (fun z : (ℕ×ℕ)×FlatExponentData => z.2) := second + let margins := composition (pair first (composition (composition data first) first)) swapMarginsRealizer + exact pair (pair margins (composition (composition data first) second)) (composition data second) + +theorem polynomial_swapFlatData : PolynomialTime swapFlatDataRealizer := by + unfold swapFlatDataRealizer + exact polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_first)) + polynomial_swapMargins) + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_second)) + (polynomial_composition polynomial_second polynomial_second) + +def permuteDrawData (z : (ℕ×ℕ)×DenseDrawData) : DenseDrawData := + (((swapFlatData (z.1,z.2.1.1.1),z.2.1.1.2),swapMatrix (z.1,z.2.1.2)),z.2.2) + +def permuteDrawDataRealizer : Realizer permuteDrawData := by + let draw : Realizer (fun z : (ℕ×ℕ)×DenseDrawData => z.2) := second + let params := composition (composition draw first) first + let data := composition (pair first (composition params first)) swapFlatDataRealizer + let fallback := composition (pair first (composition (composition draw first) second)) swapMatrixRealizer + exact pair (pair (pair data (composition params second)) fallback) (composition draw second) + +theorem polynomial_permuteDrawData : PolynomialTime permuteDrawDataRealizer := by + unfold permuteDrawDataRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_first) polynomial_first)) polynomial_swapFlatData) + (polynomial_composition (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_first) polynomial_second)) + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_second)) + polynomial_swapMatrix)) (polynomial_composition polynomial_second polynomial_second) + +def marginIndices (z : List ℕ×List ℕ) : ℕ×ℕ := (maximumIndex z.1,maximumIndex z.2) +def marginIndicesRealizer : Realizer marginIndices := + pair (composition first maximumIndexRealizer) (composition second maximumIndexRealizer) + +theorem polynomial_marginIndices : PolynomialTime marginIndicesRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_maximumIndex) + (polynomial_composition polynomial_second polynomial_maximumIndex) + +def drawIndices (z : DenseDrawData) : ℕ×ℕ := marginIndices z.1.1.1.1.1 + +def drawIndicesRealizer : Realizer drawIndices := by + let margins : Realizer (fun z : DenseDrawData => z.1.1.1.1.1) := + composition (composition (composition (composition first first) first) first) first + exact composition margins marginIndicesRealizer + +theorem polynomial_drawIndices : PolynomialTime drawIndicesRealizer := by + unfold drawIndicesRealizer + exact polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_first) polynomial_first) polynomial_first) + polynomial_marginIndices + +def preparedDraw (z : DenseDrawData) : DenseDrawData := + permuteDrawData (drawIndices z,z) + +def preparedDrawRealizer : Realizer preparedDraw := + composition (pair drawIndicesRealizer identity) permuteDrawDataRealizer + +theorem polynomial_preparedDraw : PolynomialTime preparedDrawRealizer := + polynomial_composition (polynomial_pair polynomial_drawIndices polynomial_identity) + polynomial_permuteDrawData + +def normalizedDraw (z : DenseDrawData) : MatrixCode := denseDrawCode (preparedDraw z) + +def normalizedDrawRealizer : Realizer normalizedDraw := + composition preparedDrawRealizer denseDrawCodeRealizer + +theorem polynomial_normalizedDraw : PolynomialTime normalizedDrawRealizer := + polynomial_composition polynomial_preparedDraw polynomial_denseDrawCode + +def normalizedDenseCode (z : DenseDrawData) : MatrixCode := + swapMatrix (drawIndices z,normalizedDraw z) + +def normalizedDenseCodeRealizer : Realizer normalizedDenseCode := + composition (pair drawIndicesRealizer normalizedDrawRealizer) swapMatrixRealizer + +/-- Maximal-margin selection, forward permutation, the full dense draw, +and the inverse permutation all have polynomial binary cost. -/ +theorem polynomial_normalizedDenseCode : PolynomialTime normalizedDenseCodeRealizer := + polynomial_composition (polynomial_pair polynomial_drawIndices polynomial_normalizedDraw) + polynomial_swapMatrix + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizeSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizeSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..205d684af2b8a7013323a845561bb1d7c3650412 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizeSemantics.lean @@ -0,0 +1,193 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseNormalizeProgram +import OAI.Combinatorics.ContingencyTables.Transport.TableReindex + +namespace OAI + +/-! # Correctness of computed maximal-margin normalization -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary FairBits ResidualMixture FirstSuccess +open scoped BigOperators Classical + +noncomputable section + +lemma marginCode_ofFn {m : ℕ} (R : Option (Fin m) → ℕ) : + marginCode R=List.ofFn (fun i : Fin (m+1) => R (finSuccEquiv m i)) := by + rw [List.ofFn_succ] + simp only [marginCode,finSuccEquiv_zero,finSuccEquiv_succ] + +def marginPosition {m : ℕ} (R : Option (Fin m) → ℕ) : Fin (m+1) := + maximumPosition (fun i => R (finSuccEquiv m i)) + +def indexPermutation {m : ℕ} (p : Fin (m+1)) : Option (Fin m) ≃ Option (Fin m) := + (finSuccEquiv m).symm.trans ((Equiv.swap 0 p).trans (finSuccEquiv m)) + +def normalizedMargin {m : ℕ} (R : Option (Fin m) → ℕ) : Option (Fin m) → ℕ := + fun i => R (indexPermutation (marginPosition R) i) + +lemma finSuccEquiv_symm_none (m : ℕ) : (finSuccEquiv m).symm none=0 := by + apply (finSuccEquiv m).injective + simp only [Equiv.apply_symm_apply,finSuccEquiv_zero] + +lemma normalizedMargin_max {m : ℕ} (R : Option (Fin m) → ℕ) (i : Fin m) : + normalizedMargin R (some i)≤normalizedMargin R none := by + unfold normalizedMargin indexPermutation + simp only [Equiv.trans_apply,finSuccEquiv_symm_none,Equiv.swap_apply_left] + exact maximumPosition_spec (fun i => R (finSuccEquiv m i)) _ + +lemma normalizedMargin_lower {m : ℕ} (R : Option (Fin m) → ℕ) (L : ℕ) + (hR : ∀ i,L≤R i) : ∀ i,L≤normalizedMargin R i := fun _ => hR _ + +lemma normalizedMargin_total {m : ℕ} (R : Option (Fin m) → ℕ) : + ∑ i,normalizedMargin R i=∑ i,R i := (indexPermutation (marginPosition R)).sum_comp R + +lemma marginPosition_val {m : ℕ} (R : Option (Fin m) → ℕ) : + (marginPosition R).val=maximumIndex (marginCode R) := by + rw [marginCode_ofFn] + rfl + +lemma marginCode_swap {m : ℕ} (R : Option (Fin m) → ℕ) (p : Fin (m+1)) : + swapZeroList (p.val,marginCode R)=marginCode (fun i => R (indexPermutation p i)) := by + rw [marginCode_ofFn,swapZeroList_ofFn,marginCode_ofFn] + apply congrArg List.ofFn + funext i + simp only [indexPermutation,Equiv.trans_apply,Equiv.symm_apply_apply] + +lemma indexPermutation_finSucc {m : ℕ} (p i : Fin (m+1)) : + indexPermutation p (finSuccEquiv m i)=finSuccEquiv m (Equiv.swap 0 p i) := by + change finSuccEquiv m (Equiv.swap 0 p ((finSuccEquiv m).symm (finSuccEquiv m i)))=_ + rw [Equiv.symm_apply_apply] + +lemma indexPermutation_symm_finSucc {m : ℕ} (p i : Fin (m+1)) : + (indexPermutation p).symm (finSuccEquiv m i)=finSuccEquiv m (Equiv.swap 0 p i) := by + change finSuccEquiv m (Equiv.swap 0 p ((finSuccEquiv m).symm (finSuccEquiv m i)))=_ + rw [Equiv.symm_apply_apply] + +lemma tableOutput_swap {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (p : Fin (m+1)) (q : Fin (n+1)) (X : Table R P) : + swapMatrix ((p.val,q.val),tableOutput X)= + tableOutput (tableReindex (indexPermutation p) (indexPermutation q) R P X) := by + unfold tableOutput + rw [swapMatrix_code] + apply congrArg matrixCode + funext i j + change X.val (finSuccEquiv m (Equiv.swap 0 p i)) (finSuccEquiv n (Equiv.swap 0 q j))= + X.val (indexPermutation p (finSuccEquiv m i)) (indexPermutation q (finSuccEquiv n j)) + rw [indexPermutation_finSucc,indexPermutation_finSucc] + +lemma tableOutput_inverse_swap {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (p : Fin (m+1)) (q : Fin (n+1)) + (X : Table (fun i => R (indexPermutation p i)) (fun j => P (indexPermutation q j))) : + swapMatrix ((p.val,q.val),tableOutput X)= + tableOutput ((tableReindex (indexPermutation p) (indexPermutation q) R P).symm X) := by + unfold tableOutput + rw [swapMatrix_code] + apply congrArg matrixCode + funext i j + change X.val (finSuccEquiv m (Equiv.swap 0 p i)) (finSuccEquiv n (Equiv.swap 0 q j))= + X.val ((indexPermutation p).symm (finSuccEquiv m i)) ((indexPermutation q).symm (finSuccEquiv n j)) + rw [indexPermutation_symm_finSucc,indexPermutation_symm_finSucc] + +lemma drawIndices_code {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (h : ℕ) (a : Grid (I := Fin (m*n)) (4*d^8)) (fallback : Table R P) (bits : List Bool) : + drawIndices (drawInput R P h a fallback bits)=((marginPosition R).val,(marginPosition P).val) := by + simp only [drawIndices,drawInput,marginIndices,marginPosition_val] + +lemma permuteDrawData_code {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (h : ℕ) (a : Grid (I := Fin (m*n)) (4*d^8)) (fallback : Table R P) (bits : List Bool) : + permuteDrawData (((marginPosition R).val,(marginPosition P).val), + drawInput R P h a fallback bits)= + drawInput (normalizedMargin R) (normalizedMargin P) h a + (tableReindex (indexPermutation (marginPosition R)) (indexPermutation (marginPosition P)) R P fallback) bits := by + unfold permuteDrawData swapFlatData swapMargins drawInput + rw [marginCode_swap,marginCode_swap,tableOutput_swap] + rfl + +def normalizedDrawBits {m n : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d h : ℕ) : ℕ := denseDrawBits (normalizedMargin R) (normalizedMargin P) d finProdFinEquiv h + +def normalizedBooleanDraw {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) (fallback : Table R P) + (bits : Fin (normalizedDrawBits R P d h) → Bool) : Table R P := + let E : Table R P ≃ Table (normalizedMargin R) (normalizedMargin P) := + tableReindex (indexPermutation (marginPosition R)) (indexPermutation (marginPosition P)) R P + E.symm (denseBooleanDraw (normalizedMargin R) (normalizedMargin P) d hd + (normalizedMargin_lower R _ hR) (normalizedMargin_lower P _ hP) finProdFinEquiv + (by rw [normalizedMargin_total,normalizedMargin_total]; exact htotal) h a (E fallback) bits) + +/-- The computed maximum and both physical permutations agree with the +finite table-valued experiment on every Boolean input. -/ +theorem normalizedDenseCode_eq {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) (fallback : Table R P) + (bits : Fin (normalizedDrawBits R P d h) → Bool) : + normalizedDenseCode (drawInput R P h a fallback (List.ofFn bits))= + tableOutput (normalizedBooleanDraw R P hd hR hP htotal h a fallback bits) := by + unfold normalizedDenseCode normalizedDraw preparedDraw + rw [drawIndices_code,permuteDrawData_code] + let E : Table R P ≃ Table (normalizedMargin R) (normalizedMargin P) := + tableReindex (indexPermutation (marginPosition R)) (indexPermutation (marginPosition P)) R P + let fb : Table (normalizedMargin R) (normalizedMargin P) := E fallback + have ht : (∑ i,normalizedMargin R i)=∑ j,normalizedMargin P j := by + rw [normalizedMargin_total,normalizedMargin_total] + exact htotal + have hs := denseDrawCode_eq (normalizedMargin R) (normalizedMargin P) hd + (normalizedMargin_lower R _ hR) (normalizedMargin_lower P _ hP) ht h a fb bits + refine (congrArg (fun X => swapMatrix (((marginPosition R).val,(marginPosition P).val),X)) hs).trans ?_ + exact tableOutput_inverse_swap R P _ _ _ + +/-- The computed choice of maximal rows and columns retains the dense +sampler's uniform-error guarantee for arbitrary original row order. -/ +theorem normalizedBooleanDraw_variation {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (hdimR : Fintype.card (Option (Fin m))≤d) (hdimP : Fintype.card (Option (Fin n))≤d) + (hfree : Fintype.card (Fin m×Fin n)≤d) (htotal : ∑ i,R i=∑ j,P j) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler (m*n)) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin (m*n)) (4*d^8))) + (h : ℕ) (a : Grid (I := Fin (m*n)) (4*d^8)) (fallback : Table R P) : + let _ : Nonempty (Table R P) := ⟨fallback⟩ + (variation (mapLaw (uniformLaw (α := Fin (normalizedDrawBits R P d h) → Bool)) + (normalizedBooleanDraw R P hd hR hP htotal h a fallback)) + (uniformLaw (α := Table R P)) : ℝ)≤(2:ℝ)^(-(h:ℝ)) := by + let E : Table R P ≃ Table (normalizedMargin R) (normalizedMargin P) := + tableReindex (indexPermutation (marginPosition R)) (indexPermutation (marginPosition P)) R P + let : Nonempty (Table R P) := ⟨fallback⟩ + let : Nonempty (Table (normalizedMargin R) (normalizedMargin P)) := ⟨E fallback⟩ + have ht : (∑ i,normalizedMargin R i)=∑ j,normalizedMargin P j := by + rw [normalizedMargin_total,normalizedMargin_total] + exact htotal + have he := denseBooleanDraw_variation (normalizedMargin R) (normalizedMargin P) d hd + (normalizedMargin_lower R _ hR) (normalizedMargin_lower P _ hP) + (normalizedMargin_max R) (normalizedMargin_max P) hdimR hdimP hfree ht + finProdFinEquiv hPL hCheeger h a (E fallback) + dsimp only at ⊢ + change (variation (mapLaw (uniformLaw (α := Fin (denseDrawBits (normalizedMargin R) + (normalizedMargin P) d finProdFinEquiv h) → Bool)) + (fun bits => E.symm (denseBooleanDraw (normalizedMargin R) (normalizedMargin P) d hd + (normalizedMargin_lower R _ hR) (normalizedMargin_lower P _ hP) + finProdFinEquiv ht h a (E fallback) bits))) (uniformLaw (α := Table R P)) : ℝ)≤_ + rw [mapLaw_equiv_output] + change (variation (equivLaw E.symm (denseBooleanDrawLaw (normalizedMargin R) (normalizedMargin P) + d hd (normalizedMargin_lower R _ hR) (normalizedMargin_lower P _ hP) + finProdFinEquiv ht h a (E fallback))) (uniformLaw (α := Table R P)) : ℝ)≤_ + rw [←uniform_equiv E.symm,variation_equiv] + exact he + +theorem normalizedDrawBits_polynomial {m n : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) (d C b h : ℕ) + (hq : m*n≤d) (hR : ∀ i,R i≤C) (hb : Nat.clog 2 (C+2)≤b) : + normalizedDrawBits R P d h≤25*(d+b+h+1)^62 := by + apply denseDrawBits_polynomial (normalizedMargin R) (normalizedMargin P) d C b h + finProdFinEquiv hq + · intro p + exact (Nat.div_le_self _ _).trans ((min_le_left _ _).trans (hR _)) + · exact hb + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizer.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizer.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d2aa8ed6591783dd6e2b4e42b23bd0946a4c423 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseNormalizer.lean @@ -0,0 +1,111 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseReindexedVolume +import OAI.Combinatorics.ContingencyTables.Dense.DenseLayerArithmetic +import OAI.Combinatorics.ContingencyTables.Dense.GridPartition + +namespace OAI + +/-! # Normalizer bound for the actual dense bin weights -/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators ENNReal + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +/-- The finite layer estimate gives the stronger constant 16 in place of +the manuscript's 32. No interpolation or Cheeger input is needed here. -/ +theorem denseBin_normalizer_bound (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) : + ENNReal.ofReal (∑ a : Grid (I := Fin q) (4 * d ^ 8), denseBinWeight R P d e a) ≤ + 16 * volume {x | denseGridFeasible R P d e x} := by + let K := 4 * d ^ 8 + let A := (d : ℝ) ^ 4 + let p := denseGridPenalty R P d e + let ρ := DenseWeights.density A p + let V := volume {x | denseGridFeasible R P d e x} + let N := 4 * d ^ 5 + let t (j : ℕ) := (2 : ℝ) ^ (-(j : ℝ)) * + Real.exp (2 * (d : ℝ) ^ 2 * ((d : ℝ) / (d : ℝ) ^ 8 + ((j : ℝ) + 1) / (d : ℝ) ^ 4)) + have hp : Continuous p := denseGridPenalty_continuous R P d e + have hρ : Continuous ρ := DenseWeights.density_continuous A p hp + have hi : IntegrableOn ρ (ambientBox q K) := hρ.integrableOn_Icc + have hc : MeasurableSet {x : Fin q → ℝ | Cube K x} := (cube_finiteBox (q := q) (K := K)).isOpen.measurableSet + have hsub : {x : Fin q → ℝ | Cube K x} ⊆ ambientBox q K := + fun x hx => ⟨fun j => (hx j).1.le, fun j => (hx j).2.le⟩ + have hbin (a : Grid (I := Fin q) K) : denseBinWeight R P d e a / 4 ≤ ∫ x in binSet a, ρ x := by + have hb := setIntegral_ge_of_const_le_real (binSet_measurable a) + (show volume (binSet a) ≠ ⊤ by rw [binSet_volume]; simp) + (fun x hx => (denseGrid_bin_comparison R P d hd hR hP hRmax hPmax hfree e a x + (fun j => ⟨(hx j).1.le, (hx j).2.le⟩)).1) + (hi.mono_set (binSet_subset_ambient a)) + simpa only [Measure.real, binSet_volume, ENNReal.toReal_one, mul_one, denseBinWeight] using hb + have hmass : (∑ a : Grid (I := Fin q) K, denseBinWeight R P d e a) ≤ + 4 * ∫ x in {x | Cube K x}, ρ x := by + have hs := Finset.sum_le_sum (fun a (_ : a ∈ Finset.univ) => hbin a) + rw [← Finset.sum_div, ← cube_integral_bins ρ hi] at hs + linarith + have hZ : ENNReal.ofReal (∑ a : Grid (I := Fin q) K, denseBinWeight R P d e a) ≤ + 4 * ∫⁻ x in {x | Cube K x}, ENNReal.ofReal (ρ x) := by + have h := ENNReal.ofReal_le_ofReal hmass + rw [ENNReal.ofReal_mul (by norm_num : (0 : ℝ) ≤ 4), + ofReal_integral_eq_lintegral_ofReal (hi.mono_set hsub) + (Filter.Eventually.of_forall (fun x => (DenseWeights.density_pos A p x).le))] at h + simpa only [ENNReal.ofReal_ofNat] using h + have hbound (x : Fin q → ℝ) (hx : Cube K x) : 0 ≤ A * p x ∧ A * p x ≤ N := by + have hcube (z : I × J) : 0 ≤ x (e z) ∧ x (e z) ≤ 4 * (d : ℝ) ^ 8 := by + refine ⟨(hx (e z)).1.le, ?_⟩ + simpa only [K, Nat.cast_mul, Nat.cast_ofNat, Nat.cast_pow] using (hx (e z)).2.le + have hpen := DenseAffine.densePenalty_cube_bound R P d hd hR hP hRmax hPmax + hdimR hdimP hfree htotal _ hcube + have hm := mul_le_mul_of_nonneg_left hpen.2 (show (0 : ℝ) ≤ A by positivity) + constructor + · exact mul_nonneg (by positivity) hpen.1 + · change (d : ℝ) ^ 4 * p x ≤ (4 * d ^ 5 : ℕ) + change (d : ℝ) ^ 4 * p x ≤ (d : ℝ) ^ 4 * (4 * d) at hm + push_cast + nlinarith [show (d : ℝ) ^ 4 * (4 * d) = 4 * (d : ℝ) ^ 5 by ring] + have hL := DenseWeights.density_lintegral_le_layers volume A p hp.measurable + {x | Cube K x} hc N hbound + have hL' : (∫⁻ x in {x | Cube K x}, ENNReal.ofReal (ρ x)) ≤ + ENNReal.ofReal (∑ j ∈ Finset.range (N + 1), t j) * V := by + apply hL.trans + calc + _ ≤ ∑ j ∈ Finset.range (N + 1), + ENNReal.ofReal ((2 : ℝ) ^ (-(j : ℝ))) * + (ENNReal.ofReal (Real.exp (2 * (d : ℝ) ^ 2 * + ((d : ℝ) / (d : ℝ) ^ 8 + ((j : ℝ) + 1) / (d : ℝ) ^ 4))) * V) := by + apply Finset.sum_le_sum + intro j _ + apply mul_le_mul_right + exact (measure_mono Set.inter_subset_right).trans + (denseGrid_layer_volume R P d hd hR hP hdimR hdimP hfree htotal e j) + _ = (∑ j ∈ Finset.range (N + 1), ENNReal.ofReal (t j)) * V := by + rw [Finset.sum_mul] + apply Finset.sum_congr rfl + intro j _ + rw [← mul_assoc, ← ENNReal.ofReal_mul (by positivity : (0 : ℝ) ≤ (2 : ℝ) ^ (-(j : ℝ)))] + _ = _ := by + rw [ENNReal.ofReal_sum_of_nonneg (fun j _ => show 0 ≤ t j by positivity)] + calc + _ ≤ 4 * ∫⁻ x in {x | Cube K x}, ENNReal.ofReal (ρ x) := hZ + _ ≤ 4 * (ENNReal.ofReal (∑ j ∈ Finset.range (N + 1), t j) * V) := mul_le_mul_right hL' 4 + _ = ENNReal.ofReal (4 * (∑ j ∈ Finset.range (N + 1), t j)) * V := by + rw [ENNReal.ofReal_mul (by norm_num : (0 : ℝ) ≤ 4), ENNReal.ofReal_ofNat, mul_assoc] + _ ≤ 16 * V := by + apply mul_le_mul_left + have h := ENNReal.ofReal_le_ofReal (DenseAffine.dense_layer_sum d hd (N + 1)) + simpa only [ENNReal.ofReal_ofNat] using h + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8563297bced7c6bf42f29a82a113db925d8c175 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetProgram.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseScaleMatrixProgram +import OAI.Combinatorics.ContingencyTables.Machines.ScaledWordProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanOffsets + +namespace OAI + +/-! # Binary quotient offsets and the resulting free matrix -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary + +abbrev OffsetData := ExponentData×List (List Bool) + +def offsetBits (z : OffsetData×(ℕ×ℕ)) : List Bool := + z.1.2.getD (z.2.1*z.1.1.1.1.2.tail.length+z.2.2) [] + +def offsetBitsRealizer : Realizer offsetBits := by + let N : Realizer (fun z : OffsetData×(ℕ×ℕ) => z.1.1.1.1.2.tail) := + composition (composition (composition (composition + (composition first first) first) first) second) tail + let width := composition N listLength + let index := composition (pair + (composition (pair (composition second first) width) multiply) + (composition second second)) add + exact composition (pair (composition first second) index) (getDFast []) + +theorem polynomial_offsetBits : PolynomialTime offsetBitsRealizer := by + unfold offsetBitsRealizer + apply polynomial_composition _ (polynomial_getDFast []) + apply polynomial_pair (polynomial_composition polynomial_first polynomial_second) + apply polynomial_composition _ polynomial_add + apply polynomial_pair _ (polynomial_composition polynomial_second polynomial_second) + apply polynomial_composition _ polynomial_multiply + apply polynomial_pair (polynomial_composition polynomial_second polynomial_first) + exact polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition (polynomial_composition + polynomial_first polynomial_first) polynomial_first) polynomial_first) polynomial_second) + polynomial_tail) polynomial_listLength + +def offsetFreeEntry (z : OffsetData×(ℕ×ℕ)) : ℕ := + gridCellValue (z.1.1,z.2)+scaledWordValue (gridCellWidth (z.1.1,z.2),offsetBits z) + +def offsetFreeEntryRealizer : Realizer offsetFreeEntry := by + let cell : Realizer (fun z : OffsetData×(ℕ×ℕ) => (z.1.1,z.2)) := + pair (composition first first) second + exact composition (pair (composition cell gridCellValueRealizer) + (composition (pair (composition cell gridCellWidthRealizer) offsetBitsRealizer) + scaledWordRealizer)) add + +theorem polynomial_offsetFreeEntry : PolynomialTime offsetFreeEntryRealizer := by + have hc : PolynomialTime (pair + (composition (first (A := OffsetData) (B := ℕ×ℕ)) first) second) := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_second + unfold offsetFreeEntryRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition hc polynomial_gridCellValue) + (polynomial_composition (polynomial_pair + (polynomial_composition hc polynomial_gridCellWidth) polynomial_offsetBits) + polynomial_scaledWord)) polynomial_add + +def offsetRowEntry (z : (OffsetData×ℕ)×ℕ) : ℕ := + offsetFreeEntry (z.1.1,(z.1.2,z.2)) + +def offsetRowEntryRealizer : Realizer offsetRowEntry := + composition (pair (composition first first) (pair (composition first second) second)) + offsetFreeEntryRealizer + +theorem polynomial_offsetRowEntry : PolynomialTime offsetRowEntryRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_offsetFreeEntry + +def offsetRow (z : OffsetData×ℕ) : List ℕ := + (scaleColumns z.1.1).map (fun j => offsetRowEntry (z,j)) + +def offsetRowRealizer : Realizer offsetRow := + composition (pair identity (composition (composition first first) scaleColumnsRealizer)) + (mapWith offsetRowEntryRealizer) + +theorem polynomial_offsetRow : PolynomialTime offsetRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_scaleColumns)) + (polynomial_mapWith polynomial_offsetRowEntry) + +def offsetMatrix (z : OffsetData) : MatrixCode := + (scaleRows z.1).map (fun i => offsetRow (z,i)) + +def offsetMatrixRealizer : Realizer offsetMatrix := + composition (pair identity (composition first scaleRowsRealizer)) (mapWith offsetRowRealizer) + +theorem polynomial_offsetMatrix : PolynomialTime offsetMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_scaleRows)) (polynomial_mapWith polynomial_offsetRow) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..8184f9b192c25d2b6ed6603f16314da9db34c8a3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetSemantics.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetProgram + +namespace OAI + +/-! # The binary offset program computes the geometric free matrix -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary ProfilePrograms +open scoped Classical + +noncomputable section +variable {m n q K : ℕ} + +lemma gridCellWidth_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (a : Grid (I := Fin q) K) (e : Fin m×Fin n ≃ Fin q) + (i : Fin m) (j : Fin n) : + gridCellWidth (exponentDataCode R P d + (fun i j => (corner a (e (i,j))).toNat),(i.val,j.val))= + integerWidth R P d (i,j) := by + have hR := marginCode_getD R (some i) + have hP := marginCode_getD P (some j) + change (marginCode R).getD (i.val+1) 0=R (some i) at hR + change (marginCode P).getD (j.val+1) 0=P (some j) at hP + simp only [gridCellWidth,shiftedCell,exponentCellData,exponentDataCode,hR,hP,integerWidth] + +lemma offsetBits_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (z : Fin m → Fin n → ℕ) (words : Fin (m*n) → List Bool) + (i : Fin m) (j : Fin n) : + offsetBits ((exponentDataCode R P d z,List.ofFn words),(i.val,j.val))= + words (finProdFinEquiv (i,j)) := by + have hv : i.val*n+j.val=(finProdFinEquiv (i,j)).val := by + change i.val*n+j.val=j.val+n*i.val + ac_rfl + simp only [offsetBits,exponentDataCode,marginCode,List.tail_cons,List.length_ofFn,hv] + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,(finProdFinEquiv (i,j)).isLt, + dite_true,Option.getD_some,Fin.eta] + +lemma offsetFreeEntry_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (a : Grid (I := Fin (m*n)) K) (words : Fin (m*n) → List Bool) + (i : Fin m) (j : Fin n) : + offsetFreeEntry ((exponentDataCode R P d + (fun i j => (corner a (finProdFinEquiv (i,j))).toNat),List.ofFn words),(i.val,j.val))= + cornerFree R P d finProdFinEquiv a (i,j)+ + scaledWordValue (integerWidth R P d (i,j),words (finProdFinEquiv (i,j))) := by + simp only [offsetFreeEntry,gridCellValue_code,gridCellWidth_code,offsetBits_code] + +private lemma offsetRow_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (a : Grid (I := Fin (m*n)) K) (words : Fin (m*n) → List Bool) (i : Fin m) : + offsetRow ((exponentDataCode R P d + (fun i j => (corner a (finProdFinEquiv (i,j))).toNat),List.ofFn words),i.val)= + List.ofFn (fun j => cornerFree R P d finProdFinEquiv a (i,j)+ + scaledWordValue (integerWidth R P d (i,j),words (finProdFinEquiv (i,j)))) := by + have hcols : scaleColumns (exponentDataCode R P d + (fun i j => (corner a (finProdFinEquiv (i,j))).toNat))=List.range n := by + simp only [scaleColumns,exponentDataCode,marginCode,List.tail_cons,List.length_ofFn] + unfold offsetRow + rw [hcols] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro j hj _ + have hjn : j (corner a (finProdFinEquiv (i,j))).toNat),List.ofFn words)= + matrixCode (fun i j => cornerFree R P d finProdFinEquiv a (i,j)+ + scaledWordValue (integerWidth R P d (i,j),words (finProdFinEquiv (i,j)))) := by + have hrows : scaleRows (exponentDataCode R P d + (fun i j => (corner a (finProdFinEquiv (i,j))).toNat))=List.range m := by + simp only [scaleRows,exponentDataCode,marginCode,List.tail_cons,List.length_ofFn] + unfold offsetMatrix matrixCode + rw [hrows] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have him : i < m := by simpa only [List.length_map,List.length_range] using hi + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + exact offsetRow_code R P d a words ⟨i,him⟩ + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetTrial.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a4ed219542bdec2eb57876a75d45c2a07067a49 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetTrial.lean @@ -0,0 +1,51 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetSemantics +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrial + +namespace OAI + +/-! # The quotient program computes the full free part of a dense trial -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary ProfilePrograms +open scoped Classical + +noncomputable section + +private lemma fin_transport_val {α : Sort*} {n : α → ℕ} {a b : α} + (h : a=b) (x : Fin (n a)) : ((h ▸ x) : Fin (n b)).val=x.val := by + cases h + rfl + +lemma drawOffsetWords_value {I J : Type*} [Fintype I] [Fintype J] + [DecidableEq I] [DecidableEq J] {q : ℕ} + (e : I×J ≃ Fin q) (w : I×J → ℕ) (hw : ∀ p,0 (corner a (finProdFinEquiv (i,j))).toNat), + List.ofFn (fun i => List.ofFn (bits i)))= + matrixCode (fun i j => trialFree R P d finProdFinEquiv + (a,drawOffsetWords finProdFinEquiv (integerWidth R P d) hw h d bits) (i,j)) := by + rw [offsetMatrix_code] + apply congrArg matrixCode + funext i j + rw [trialFree,trialBoxEquiv_val,drawOffsetWords_value] + simp only [cornerFree] + exact Nat.add_comm _ _ + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetWidths.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetWidths.lean new file mode 100644 index 0000000000000000000000000000000000000000..466042ef1ea1ac5716581a15ce4171b6515ab15c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsetWidths.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetTrial +import OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram +import OAI.Combinatorics.ContingencyTables.Machines.DependentWordProgram + +namespace OAI + +/-! # Computing the actual variable-width offset word layout -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary FairBits + +abbrev OffsetWidthData := ExponentData×ℕ + +def offsetLength (z : OffsetWidthData×(ℕ×ℕ)) : ℕ := + Nat.clog 2 (gridCellWidth (z.1.1,z.2)+1)+4*(z.1.2+z.1.1.2) + +def offsetLengthRealizer : Realizer offsetLength := by + let cell : Realizer (fun z : OffsetWidthData×(ℕ×ℕ) => (z.1.1,z.2)) := + pair (composition first first) second + let width := composition (composition (composition cell gridCellWidthRealizer) successor) + ceilLogTwoRealizer + let H : Realizer (fun z : OffsetWidthData×(ℕ×ℕ) => z.1.2) := composition first second + let D : Realizer (fun z : OffsetWidthData×(ℕ×ℕ) => z.1.1.2) := + composition (composition first first) second + let hd := composition (pair H D) add + let accuracy := composition (pair (constant 4) hd) multiply + exact composition (pair width accuracy) add + +theorem polynomial_offsetLength : PolynomialTime offsetLengthRealizer := by + have hc : PolynomialTime (pair + (composition (first (A := OffsetWidthData) (B := ℕ×ℕ)) first) second) := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_second + unfold offsetLengthRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition hc polynomial_gridCellWidth) polynomial_successor) polynomial_ceilLogTwo) + (polynomial_composition (polynomial_pair (polynomial_constant 4) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second)) + polynomial_add)) polynomial_multiply)) polynomial_add + +def freeCells (z : OffsetWidthData) : List (ℕ×ℕ) := + cellPairs (z.1.1.1.1.tail,z.1.1.1.2.tail) + +def freeCellsRealizer : Realizer freeCells := + composition (pair + (composition (composition (composition (composition first first) first) first) tail) + (composition (composition (composition (composition first first) first) second) tail)) cellPairsRealizer + +theorem polynomial_freeCells : PolynomialTime freeCellsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) polynomial_tail) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) polynomial_tail)) + polynomial_cellPairs + +def offsetLengths (z : OffsetWidthData) : List ℕ := + (freeCells z).map (fun ij => offsetLength (z,ij)) + +def offsetLengthsRealizer : Realizer offsetLengths := + composition (pair identity freeCellsRealizer) (mapWith offsetLengthRealizer) + +theorem polynomial_offsetLengths : PolynomialTime offsetLengthsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_freeCells) + (polynomial_mapWith polynomial_offsetLength) + +lemma cellPairs_ofFn {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : + cellPairs (List.ofFn r,List.ofFn c)=List.ofFn (fun v : Fin (m*n) => + (((finProdFinEquiv : Fin m×Fin n ≃ Fin (m*n)).symm v).1.val, + ((finProdFinEquiv : Fin m×Fin n ≃ Fin (m*n)).symm v).2.val)) := by + apply List.ext_getElem + · simp only [cellPairs,List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + simp only [cellPairs,List.getElem_map,List.getElem_range,List.getElem_ofFn,pairAt,List.length_ofFn] + rfl + +noncomputable section +open scoped Classical + +lemma offsetLength_code {m n q K : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d h : ℕ) (a : Grid (I := Fin q) K) (e : Fin m×Fin n ≃ Fin q) (i : Fin m) (j : Fin n) : + offsetLength ((exponentDataCode R P d + (fun i j => (corner a (e (i,j))).toNat),h),(i.val,j.val))= + offsetBitLength (integerWidth R P d (i,j)) h d := by + change Nat.clog 2 (gridCellWidth (exponentDataCode R P d + (fun i j => (corner a (e (i,j))).toNat),(i.val,j.val))+1)+4*(h+d)=_ + rw [gridCellWidth_code] + rfl + +theorem offsetLengths_code {m n K : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d h : ℕ) (a : Grid (I := Fin (m*n)) K) : + offsetLengths (exponentDataCode R P d + (fun i j => (corner a (finProdFinEquiv (i,j))).toNat),h)= + List.ofFn (fun v : Fin (m*n) => offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm v)) h d) := by + unfold offsetLengths freeCells + simp only [exponentDataCode,marginCode,List.tail_cons] + rw [cellPairs_ofFn,List.map_ofFn] + apply congrArg List.ofFn + funext v + exact offsetLength_code R P d h a finProdFinEquiv + (finProdFinEquiv.symm v).1 (finProdFinEquiv.symm v).2 + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsets.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsets.lean new file mode 100644 index 0000000000000000000000000000000000000000..553aa45595341a5470c0f760fea4b8c88126d839 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseOffsets.lean @@ -0,0 +1,103 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerTable +import OAI.Combinatorics.ContingencyTables.Model +import Mathlib.Logic.Equiv.Fin.Basic + +namespace OAI + +/-! # Unique bin and offset encoding of free integer entries -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators + +def gridCoordinateFin (K : ℕ) : Set.Icc (0 : ℤ) ((K : ℤ) - 1) ≃ Fin K where + toFun z := ⟨z.val.toNat, by + have hcast : (z.val.toNat : ℤ) = z.val := Int.toNat_of_nonneg z.property.1 + have hhi := z.property.2 + omega⟩ + invFun v := ⟨(v.val : ℤ), by constructor <;> omega⟩ + left_inv z := by + apply Subtype.ext + exact Int.toNat_of_nonneg z.property.1 + right_inv v := by + apply Fin.ext + exact Int.toNat_natCast _ + +variable {I J : Type*} [Fintype I] [Fintype J] +variable {q : ℕ} + +abbrev Offset (w : I × J → ℕ) := ∀ p, Fin (w p) +abbrev FreeBox (w : I × J → ℕ) (K : ℕ) := ∀ p, Fin (K * w p) + +def trialBoxEquiv (e : I × J ≃ Fin q) (w : I × J → ℕ) (K : ℕ) : + Grid (I := Fin q) K × Offset w ≃ FreeBox w K where + toFun t p := finProdFinEquiv (gridCoordinateFin K (t.1 (e p)), t.2 p) + invFun z := + (fun j => (gridCoordinateFin K).symm + (((finProdFinEquiv : Fin K × Fin (w (e.symm j)) ≃ Fin (K * w (e.symm j))).symm + (z (e.symm j))).1), + fun p => ((finProdFinEquiv : Fin K × Fin (w p) ≃ Fin (K * w p)).symm (z p)).2) + left_inv t := by + rcases t with ⟨a, o⟩ + apply Prod.ext + · funext j + simp only [Equiv.symm_apply_apply, Equiv.apply_symm_apply] + · funext p + simp only [Equiv.symm_apply_apply] + right_inv z := by + funext p + simp only [Equiv.apply_symm_apply] + have hb : ((finProdFinEquiv : Fin K × Fin (w (e.symm (e p))) ≃ + Fin (K * w (e.symm (e p)))).symm (z (e.symm (e p)))).1 = + ((finProdFinEquiv : Fin K × Fin (w p) ≃ Fin (K * w p)).symm (z p)).1 := by + apply Fin.ext + change (z (e.symm (e p))).val / w (e.symm (e p)) = (z p).val / w p + rw [Equiv.symm_apply_apply] + rw [hb] + exact finProdFinEquiv.apply_symm_apply (z p) + +omit [Fintype I] [Fintype J] in +theorem trialBoxEquiv_val (e : I × J ≃ Fin q) (w : I × J → ℕ) (K : ℕ) + (a : Grid (I := Fin q) K) (o : Offset w) (p : I × J) : + (trialBoxEquiv e w K (a, o) p).val = (o p).val + w p * (corner a (e p)).toNat := rfl + +def integerWidth (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) (p : I × J) : ℕ := + min (R (some p.1)) (P (some p.2)) / d ^ 8 + +omit [Fintype I] [Fintype J] in +theorem integerWidth_pos (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) (p : I × J) : + 0 < integerWidth R P d p := + DenseAffine.dense_width_positive d _ hd (le_min (hR _) (hP _)) + +omit [Fintype I] [Fintype J] in +theorem free_entry_lt_box (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (p : I × J) (z : ℕ) (hz : z ≤ min (R (some p.1)) (P (some p.2))) : + z < (4 * d ^ 8) * integerWidth R P d p := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hb := (DenseAffine.dense_width_bounds d (min (R (some p.1)) (P (some p.2))) hd + (le_min (hR _) (hP _))).1 + have hs : min (R (some p.1)) (P (some p.2)) ≤ + (2 * d ^ 8) * integerWidth R P d p := by + have h := (div_le_iff₀ (show (0 : ℝ) < 2 * (d : ℝ) ^ 8 by positivity)).mp hb + have h' : min (R (some p.1)) (P (some p.2)) ≤ + integerWidth R P d p * (2 * d ^ 8) := by exact_mod_cast h + simpa only [Nat.mul_comm] using h' + have hw := integerWidth_pos R P d hd hR hP p + have hd8 : 0 < d ^ 8 := pow_pos (show 0 < d by omega) _ + nlinarith [Nat.mul_pos hd8 hw] + +def tableFreeBox (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (X : Table R P) : FreeBox (integerWidth R P d) (4 * d ^ 8) := fun p => + ⟨X.val (some p.1) (some p.2), free_entry_lt_box R P d hd hR hP p _ (by + apply le_min + · exact entry_le_row X.property _ _ + · rw [← X.property.2 (some p.2)] + exact Finset.single_le_sum (f := fun i : Option I => X.val i (some p.2)) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ (some p.1)))⟩ + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRational.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRational.lean new file mode 100644 index 0000000000000000000000000000000000000000..91945b35be54bfbe7cf8e9ce8371ff8d613043bf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRational.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialAcceptance +import Mathlib.Data.Rat.Floor + +namespace OAI + +/-! # Exact rational evaluation of the dense bin exponent + +Only integer completion, rational comparison and division are needed to +compute a bin's weight exponent. The real penalty used in the geometric +proof is exactly the cast of this finite rational maximum. +-/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical + +variable {I J : Type*} [Fintype I] [Fintype J] +variable {q K : ℕ} + +def cornerFree (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : I × J → ℕ := + fun p => integerWidth R P d p * (corner a (e p)).toNat + +omit [Fintype I] [Fintype J] in +theorem cornerFree_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) (p : I × J) : + (cornerFree R P d e a p : ℝ) = + DenseAffine.denseWidth R P d p.1 p.2 * realCorner a (e p) := by + have hc : (((corner a (e p)).toNat : ℕ) : ℝ) = (corner a (e p) : ℝ) := by + exact_mod_cast Int.toNat_of_nonneg (a (e p)).property.1 + simp only [cornerFree, Nat.cast_mul, hc] + rfl + +theorem corner_integerTable_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) (i : Option I) (j : Option J) : + (DenseAffine.integerTable R P (cornerFree R P d e a) i j : ℝ) = + DenseAffine.table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) + (DenseAffine.denseWidth R P d) (fun p => realCorner a (e p)) i j := by + rw [DenseAffine.integerTable_cast] + cases i <;> cases j <;> + simp only [DenseAffine.table, one_mul, cornerFree_cast] + +def rationalComponent (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : + Option (Option I × Option J) → ℚ + | none => 0 + | some g => -(DenseAffine.integerTable R P (cornerFree R P d e a) g.1 g.2 : ℚ) / + ((min (R g.1) (P g.2) : ℕ) : ℚ) - (d : ℚ) / (d : ℚ) ^ 8 + +def rationalPenalty (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : ℚ := + Finset.univ.sup' Finset.univ_nonempty (rationalComponent R P d e a) + +theorem rationalPenalty_nonnegative (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : 0 ≤ rationalPenalty R P d e a := + Finset.le_sup' (rationalComponent R P d e a) (Finset.mem_univ none) + +variable [DecidableEq I] [DecidableEq J] + +theorem rationalComponent_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) (g : Option (Option I × Option J)) : + (rationalComponent R P d e a g : ℝ) = + AffinePenalty.component + (fun g => DenseAffine.entryOffset (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g / + DenseAffine.cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + (fun g p => DenseAffine.entryCoeff (DenseAffine.denseWidth R P d) g p / + DenseAffine.cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + ((d : ℝ) / (d : ℝ) ^ 8) g (fun p => realCorner a (e p)) := by + cases g with + | none => simp only [rationalComponent, Rat.cast_zero, AffinePenalty.component] + | some g => + simp only [rationalComponent, Rat.cast_sub, Rat.cast_div, Rat.cast_neg, + Rat.cast_intCast, Rat.cast_natCast, Rat.cast_pow, AffinePenalty.component, + Nat.cast_min, Rat.cast_min, neg_div] + rw [corner_integerTable_cast] + change -(_ / DenseAffine.cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) - _ = _ + rw [DenseAffine.normalized_table_affine] + +theorem rationalPenalty_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : + (rationalPenalty R P d e a : ℝ) = denseGridPenalty R P d e (realCorner a) := by + unfold rationalPenalty denseGridPenalty DenseAffine.densePenalty AffinePenalty.penalty + rw [Finset.apply_sup'_eq_sup'_comp _ (fun x : ℚ => (x : ℝ)) + (fun x y => Rat.cast_max x y)] + apply Finset.sup'_congr Finset.univ_nonempty rfl + intro g _ + exact rationalComponent_cast R P d e a g + +def denseExponent (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : ℕ := + ⌊(d : ℚ) ^ 4 * rationalPenalty R P d e a⌋₊ + +theorem denseExponent_eq_floor (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : + (denseExponent R P d e a : ℤ) = + ⌊(d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a)⌋ := by + have hp := rationalPenalty_nonnegative R P d e a + rw [denseExponent, Int.natCast_floor_eq_floor (mul_nonneg (pow_nonneg (Nat.cast_nonneg _) _) hp)] + have hcast : (((d : ℚ) ^ 4 * rationalPenalty R P d e a : ℚ) : ℝ) = + (d : ℝ) ^ 4 * denseGridPenalty R P d e (realCorner a) := by + simp only [Rat.cast_mul, Rat.cast_pow, Rat.cast_natCast, rationalPenalty_cast] + rw [← hcast, Rat.floor_cast] + +theorem denseBinWeight_eq_dyadic (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) K) : + denseBinWeight R P d e a = 1 / (2 : ℝ) ^ denseExponent R P d e a := by + unfold denseBinWeight DenseWeights.binWeight + rw [← denseExponent_eq_floor] + simp only [Int.cast_natCast, Real.rpow_neg (by norm_num : (0 : ℝ) ≤ 2), + Real.rpow_natCast, one_div] + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRationalKernel.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRationalKernel.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0c8a01e99cb5cb8018b45742b8fddc57300fa16 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRationalKernel.lean @@ -0,0 +1,157 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseRationalTrial +import OAI.Combinatorics.ContingencyTables.Dense.DenseMixing + +namespace OAI + +/-! # Rational transition and walk laws for the actual dense bin chain -/ + +namespace ContingencyTables.GridBoundary + +open CommonBasesFPRAS ResidualMixture FirstSuccess +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def rationalProposal (d : ℕ) : ℚ := 1 / (2 : ℚ) ^ Nat.clog 2 (8 * d) + +def rationalMove (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a b : Grid (I := Fin q) (4 * d ^ 8)) : ℚ := + if Neighbor a b then rationalProposal d * min 1 (rationalBinWeight R P d e b / rationalBinWeight R P d e a) + else 0 + +def rationalTransition (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a b : Grid (I := Fin q) (4 * d ^ 8)) : ℚ := + rationalMove R P d e a b + if a = b then 1 - ∑ c, rationalMove R P d e a c else 0 + +theorem rationalMove_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a b : Grid (I := Fin q) (4 * d ^ 8)) : + (rationalMove R P d e a b : ℝ) = + MetropolisChain.move (denseBinWeight R P d e) Neighbor (binProposal d) a b := by + unfold rationalMove MetropolisChain.move + split_ifs + · simp only [Rat.cast_mul, Rat.cast_min, Rat.cast_one, Rat.cast_div, + rationalBinWeight_cast, rationalProposal, binProposal, Rat.cast_pow, Rat.cast_ofNat] + · exact Rat.cast_zero + +theorem rationalTransition_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (a b : Grid (I := Fin q) (4 * d ^ 8)) : + (rationalTransition R P d e a b : ℝ) = + (denseBinChain R P d hd hfree e (denseGridSize_pos d hd)).P a b := by + unfold rationalTransition + dsimp only [denseBinChain, gridChain, MetropolisChain.chain, FiniteChain.ofMoves] + by_cases hab : a = b <;> + simp only [hab, ite_true, ite_false, Rat.cast_add, Rat.cast_sub, Rat.cast_sum, + Rat.cast_one, Rat.cast_zero, rationalMove_cast] + +def rationalTransitionLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (a : Grid (I := Fin q) (4 * d ^ 8)) : RationalLaw (Grid (I := Fin q) (4 * d ^ 8)) where + mass := rationalTransition R P d e a + nonnegative := fun b => by + have h := (denseBinChain R P d hd hfree e (denseGridSize_pos d hd)).nonnegative a b + rw [← rationalTransition_cast R P d hd hfree e] at h + exact_mod_cast h + total := by + apply Rat.cast_injective (α := ℝ) + simp only [Rat.cast_sum, rationalTransition_cast R P d hd hfree e, Rat.cast_one] + exact (denseBinChain R P d hd hfree e (denseGridSize_pos d hd)).stochastic a + +def rationalWalk (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) : ℕ → Grid (I := Fin q) (4 * d ^ 8) → Grid (I := Fin q) (4 * d ^ 8) → ℚ + | 0, a, b => if a = b then 1 else 0 + | n + 1, a, b => ∑ c, rationalWalk R P d e n a c * rationalTransition R P d e c b + +theorem rationalWalk_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (n : ℕ) (a b : Grid (I := Fin q) (4 * d ^ 8)) : + (rationalWalk R P d e n a b : ℝ) = + ((denseBinChain R P d hd hfree e (denseGridSize_pos d hd)).kernel.power n).P a b := by + induction n generalizing a b with + | zero => simp only [rationalWalk, FiniteKernel.power, FiniteKernel.identity] + split_ifs <;> norm_num + | succ n ih => + simp only [rationalWalk, Rat.cast_sum, Rat.cast_mul, ih, rationalTransition_cast R P d hd hfree e, + FiniteKernel.power, FiniteKernel.comp, FiniteChain.kernel] + +def rationalWalkLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (n : ℕ) (a : Grid (I := Fin q) (4 * d ^ 8)) : RationalLaw (Grid (I := Fin q) (4 * d ^ 8)) where + mass := rationalWalk R P d e n a + nonnegative := fun b => by + have h := ((denseBinChain R P d hd hfree e (denseGridSize_pos d hd)).kernel.power n).nonnegative a b + rw [← rationalWalk_cast R P d hd hfree e] at h + exact_mod_cast h + total := by + apply Rat.cast_injective (α := ℝ) + simp only [Rat.cast_sum, rationalWalk_cast R P d hd hfree e, Rat.cast_one] + exact (denseBinChain R P d hd hfree e (denseGridSize_pos d hd)).kernel_power_stochastic n a + +def rationalStationaryLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (e : I × J ≃ Fin q) : RationalLaw (Grid (I := Fin q) (4 * d ^ 8)) := by + let : Nonempty (Grid (I := Fin q) (4 * d ^ 8)) := + ⟨fun _ => ⟨0, by have h := denseGridSize_pos d hd; constructor <;> omega⟩⟩ + let w := rationalBinWeight R P d e + have hw : ∀ a : Grid (I := Fin q) (4 * d ^ 8), 0 < w a := fun a => by + unfold w rationalBinWeight + positivity + have hZ : 0 < ∑ a, w a := Finset.sum_pos (fun a _ => hw a) Finset.univ_nonempty + exact ⟨fun a => w a / ∑ b, w b, fun a => (div_pos (hw a) hZ).le, + by rw [← Finset.sum_div]; exact div_self (ne_of_gt hZ)⟩ + +theorem rationalStationaryLaw_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (a : Grid (I := Fin q) (4 * d ^ 8)) : + ((rationalStationaryLaw R P d hd e).mass a : ℝ) = + (denseBinChain R P d hd hfree e (denseGridSize_pos d hd)).π a := by + change ((rationalBinWeight R P d e a / ∑ b, rationalBinWeight R P d e b : ℚ) : ℝ) = _ + simp only [Rat.cast_div, Rat.cast_sum, rationalBinWeight_cast] + rfl + +/-- The exact rational finite-walk law satisfies the dense sampler's mixing +bound. The hypotheses are precisely the two published geometric inputs. -/ +theorem rationalWalkLaw_variation (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (hCheeger : PublishedInputs.FiniteCheeger (Grid (I := Fin q) (4 * d ^ 8))) + (h : ℕ) (a : Grid (I := Fin q) (4 * d ^ 8)) : + (variation (rationalWalkLaw R P d hd hfree e (d ^ 50 * (h + 1) ^ 2) a) + (rationalStationaryLaw R P d hd e) : ℝ) ≤ + (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) := by + let C := denseBinChain R P d hd hfree e (denseGridSize_pos d hd) + let δ := (2 : ℝ) ^ (-(4 * ((h : ℝ) + d))) + let n := d ^ 50 * (h + 1) ^ 2 + have hpoint (b : Grid (I := Fin q) (4 * d ^ 8)) : + |(C.kernel.power n).P a b - C.π b| ≤ C.π b * δ := by + have hm := denseBinChain_relative_mixing R P d hd hR hP hRmax hPmax + hdimR hdimP hfree htotal e hPL hCheeger h a b + change |C.iterate n (C.pointDensity b) a - 1| ≤ δ at hm + rw [← C.kernel_power_density] at hm + calc + _ = C.π b * |(C.kernel.power n).P a b / C.π b - 1| := by + calc + _ = |C.π b * ((C.kernel.power n).P a b / C.π b - 1)| := by + congr 1 + field_simp [ne_of_gt (C.positive b)] + _ = _ := by rw [abs_mul, abs_of_pos (C.positive b)] + _ ≤ _ := mul_le_mul_of_nonneg_left hm (C.positive b).le + have hsum := Finset.sum_le_sum (fun b (_ : b ∈ Finset.univ) => hpoint b) + rw [← Finset.sum_mul, C.normalized, one_mul] at hsum + unfold variation + simp only [Rat.cast_div, Rat.cast_sum, Rat.cast_abs, Rat.cast_sub, Rat.cast_ofNat, + rationalWalkLaw, rationalWalk_cast R P d hd hfree e, rationalStationaryLaw_cast R P d hd hfree e] + change (∑ b, |(C.kernel.power n).P a b - C.π b|) / 2 ≤ δ + have hδ : 0 ≤ δ := (Real.rpow_pos_of_pos (by norm_num) _).le + linarith + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRationalTrial.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRationalTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..42359f2f65e9473299505069240f840af103a121 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRationalTrial.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseRational +import OAI.Combinatorics.ContingencyTables.Transport.FirstSuccess + +namespace OAI + +/-! # The rational ideal dense rejection law -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def rationalBinWeight (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : ℚ := + 1 / (2 : ℚ) ^ denseExponent R P d e a + +theorem rationalBinWeight_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4 * d ^ 8)) : + (rationalBinWeight R P d e a : ℝ) = denseBinWeight R P d e a := by + rw [denseBinWeight_eq_dyadic] + simp only [rationalBinWeight, Rat.cast_div, Rat.cast_one, Rat.cast_pow, Rat.cast_ofNat] + +def rationalTrialMass (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (t : DenseTrial R P d q) : ℚ := + rationalBinWeight R P d e t.1 / + (∑ a : Grid (I := Fin q) (4 * d ^ 8), rationalBinWeight R P d e a) / + Fintype.card (Offset (integerWidth R P d)) + +theorem rationalTrialMass_cast (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (t : DenseTrial R P d q) : + (rationalTrialMass R P d e t : ℝ) = denseTrialMass R P d e t := by + simp only [rationalTrialMass, denseTrialMass, Rat.cast_div, Rat.cast_sum, + Rat.cast_natCast, rationalBinWeight_cast] + +def rationalTrialLaw (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) : RationalLaw (DenseTrial R P d q) where + mass := rationalTrialMass R P d e + nonnegative := fun t => by + have h := (denseTrialMass_pos R P d hd hR hP e t).le + rw [← rationalTrialMass_cast] at h + exact_mod_cast h + total := by + apply Rat.cast_injective (α := ℝ) + simp only [Rat.cast_sum, rationalTrialMass_cast, Rat.cast_one] + exact denseTrialMass_sum R P d hd hR hP e + +def rationalTableMass (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (X : Table R P) : ℚ := + rationalTrialMass R P d e (tableTrial R P d hd hR hP e X) + +theorem rationalTableMass_total (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (htotal : ∑ i, R i = ∑ j, P j) : + ((∑ X : Table R P, rationalTableMass R P d hd hR hP e X) : ℝ) = + denseAcceptanceMass R P d e := by + rw [denseAcceptanceMass, ← Finset.sum_filter] + have hs : (∑ t : {t : DenseTrial R P d q // TrialAccepted R P d e t}, + denseTrialMass R P d e t.val) = + ∑ t ∈ Finset.univ.filter (TrialAccepted R P d e), denseTrialMass R P d e t := by + exact (Finset.sum_subtype (p := TrialAccepted R P d e) + (Finset.univ.filter (TrialAccepted R P d e)) (fun _ => by simp) + (denseTrialMass R P d e)).symm + rw [← hs] + symm + apply Fintype.sum_equiv (acceptedTrialEquiv R P d hd hR hP e htotal) + intro t + simp only [rationalTableMass, rationalTrialMass_cast] + congr 1 + exact (tableTrial_trialTable R P d hd hR hP e htotal t.val t.property).symm + +theorem rationalTableMass_uniform (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) (X : Table R P) : + rationalTableMass R P d hd hR hP e X / + (∑ Y : Table R P, rationalTableMass R P d hd hR hP e Y) = + 1 / Fintype.card (Table R P) := by + apply Rat.cast_injective (α := ℝ) + simp only [Rat.cast_div, Rat.cast_sum, Rat.cast_one, Rat.cast_natCast, + rationalTableMass, rationalTrialMass_cast] + exact denseTrial_conditional_uniform R P d hd hR hP hRmax hPmax hfree e X + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRegionVolume.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRegionVolume.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd673deb569f624117e2075a005feed9d9e413cf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRegionVolume.lean @@ -0,0 +1,191 @@ +import OAI.Combinatorics.ContingencyTables.Dense.AffineRegionVolume +import OAI.Combinatorics.ContingencyTables.Dense.DenseLocalGeometry + +namespace OAI + +/-! # Inner-polytope and penalty-sublevel volume for the actual margins -/ + +namespace ContingencyTables.DenseAffine + +open MeasureTheory +open scoped BigOperators ENNReal + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +def normalizedOffset (R : Option I → ℕ) (P : Option J → ℕ) (g : Option I × Option J) : ℝ := + entryOffset (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g + +def normalizedCoeff (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (g : Option I × Option J) (p : I × J) : ℝ := + entryCoeff (denseWidth R P d) g p / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g + +def normalizedRegion (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (γ : ℝ) : Set (I × J → ℝ) := {x | ∀ g, γ ≤ normalizedEntry R P d x g} + +theorem normalizedRegion_eq_affine (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (γ : ℝ) : + normalizedRegion R P d γ = + AffinePenalty.region (normalizedOffset R P) (normalizedCoeff R P d) γ := by + ext x + simp only [normalizedRegion, AffinePenalty.region, Set.mem_ofPred_eq, + normalizedEntry, normalized_table_affine, normalizedOffset] + rfl + +theorem normalizedEntry_continuous (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (g : Option I × Option J) : Continuous (fun x => normalizedEntry R P d x g) := by + have heq : (fun x => normalizedEntry R P d x g) = + (fun x => AffinePenalty.affineValue (normalizedOffset R P g) (normalizedCoeff R P d g) x) := by + funext x + exact normalized_table_affine _ _ _ _ _ + rw [heq] + exact continuous_const.add (continuous_finsetSum Finset.univ + (fun p _ => continuous_const.mul (continuous_apply p))) + +theorem normalizedRegion_closed (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (γ : ℝ) : IsClosed (normalizedRegion R P d γ) := by + have heq : normalizedRegion R P d γ = + ⋂ g, {x | γ ≤ normalizedEntry R P d x g} := by + ext x + simp only [normalizedRegion, Set.mem_ofPred_eq, Set.mem_iInter] + rw [heq] + exact isClosed_iInter (fun g => isClosed_le continuous_const (normalizedEntry_continuous R P d g)) + +omit [DecidableEq I] [DecidableEq J] in +theorem normalizedRegion_zero (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) : + normalizedRegion R P d 0 = {x | Feasible R P d x} := by + have hs (g : Option I × Option J) : + 0 < cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g := by + change 0 < min (R g.1 : ℝ) (P g.2 : ℝ) + apply lt_min + · exact_mod_cast (lt_of_lt_of_le (pow_pos (show 0 < d by omega) _) (hR _)) + · exact_mod_cast (lt_of_lt_of_le (pow_pos (show 0 < d by omega) _) (hP _)) + ext x + constructor + · intro hx i j + have h := hx (i, j) + change 0 ≤ _ / cellScale _ _ (i, j) at h + simpa only [zero_mul] using (le_div_iff₀ (hs (i, j))).mp h + · intro hx g + exact div_nonneg (hx g.1 g.2) (hs g).le + +theorem dense_feasible_compact (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (htotal : ∑ i, R i = ∑ j, P j) : + IsCompact {x : I × J → ℝ | Feasible R P d x} := by + have hclosed : IsClosed {x : I × J → ℝ | Feasible R P d x} := by + rw [← normalizedRegion_zero R P d hd hR hP] + exact normalizedRegion_closed R P d 0 + apply isCompact_Icc.of_isClosed_subset hclosed + intro x hx + have h := feasible_in_cube R P d hd hR hP htotal x hx + exact ⟨fun p => (h p).1, fun p => (h p).2⟩ + +theorem dense_inner_contraction (d : ℕ) (hd : 14 ≤ d) (q : ℕ) (hq : q ≤ d) : + 0 ≤ 4 * (d : ℝ) ^ 2 / (d : ℝ) ^ 8 ∧ + 4 * (d : ℝ) ^ 2 / (d : ℝ) ^ 8 ≤ 1 ∧ + (1 / 2 : ℝ) ≤ (1 - 4 * (d : ℝ) ^ 2 / (d : ℝ) ^ 8) ^ q := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hd₁ : (1 : ℝ) ≤ d := by exact_mod_cast (show 1 ≤ d by omega) + let α := 4 * (d : ℝ) ^ 2 / (d : ℝ) ^ 8 + have hα : 0 ≤ α := by positivity + have hp : 8 * d ^ 3 ≤ d ^ 8 := by + have hfive : 8 ≤ d ^ 5 := (show 8 ≤ d by omega).trans (Nat.le_self_pow (by decide) d) + calc + _ ≤ d ^ 5 * d ^ 3 := Nat.mul_le_mul_right _ hfive + _ = _ := by ring + have hsmall : (d : ℝ) * α ≤ 1 / 2 := by + have hp' : 8 * (d : ℝ) ^ 3 ≤ (d : ℝ) ^ 8 := by exact_mod_cast hp + have heq : (d : ℝ) * α = 4 * (d : ℝ) ^ 3 / (d : ℝ) ^ 8 := by dsimp [α]; ring + rw [heq] + apply (div_le_iff₀ (pow_pos hd₀ 8)).mpr + nlinarith + have hα₁ : α ≤ 1 := by + have h := mul_le_mul_of_nonneg_right hd₁ hα + nlinarith + have hq' : (q : ℝ) ≤ d := by exact_mod_cast hq + have hbern := one_add_mul_le_pow (a := -α) (by linarith : -2 ≤ -α) q + have hqα := mul_le_mul_of_nonneg_right hq' hα + refine ⟨hα, hα₁, ?_⟩ + change (1 / 2 : ℝ) ≤ (1 - α) ^ q + have heq : 1 + -α = 1 - α := by ring + rw [heq] at hbern + nlinarith + +theorem dense_inner_volume (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) : + (1 / 2 : ℝ≥0∞) * volume {x : I × J → ℝ | Feasible R P d x} ≤ + volume (normalizedRegion R P d (2 * (d : ℝ) / (d : ℝ) ^ 8)) := by + obtain ⟨u, _, _, hu⟩ := dense_interior_exists R P d hd hR hP hdimR hdimP htotal + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hα := dense_inner_contraction d hd (Fintype.card (I × J)) hfree + have hc : u ∈ AffinePenalty.region (normalizedOffset R P) (normalizedCoeff R P d) + (1 / (2 * (d : ℝ))) := by + rw [← normalizedRegion_eq_affine] + exact hu + have hvol := AffinePenalty.inner_region_volume (normalizedOffset R P) (normalizedCoeff R P d) + u (1 / (2 * (d : ℝ))) (4 * (d : ℝ) ^ 2 / (d : ℝ) ^ 8) hα.1 hα.2.1 hc + have heq : (4 * (d : ℝ) ^ 2 / (d : ℝ) ^ 8) * (1 / (2 * (d : ℝ))) = + 2 * (d : ℝ) / (d : ℝ) ^ 8 := by field_simp; ring + rw [heq, ← normalizedRegion_eq_affine, ← normalizedRegion_eq_affine, + normalizedRegion_zero R P d hd hR hP] at hvol + apply le_trans _ hvol + apply mul_le_mul_left + have hb := ENNReal.ofReal_le_ofReal hα.2.2 + simpa only [ENNReal.ofReal_div_of_pos (by norm_num : (0 : ℝ) < 2), + ENNReal.ofReal_one, ENNReal.ofReal_ofNat] using hb + +theorem dense_relaxed_volume (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (γ : ℝ) (hγ : 0 ≤ γ) : + volume (normalizedRegion R P d (-γ)) ≤ + ENNReal.ofReal (Real.exp (2 * (d : ℝ) ^ 2 * γ)) * + volume {x : I × J → ℝ | Feasible R P d x} := by + obtain ⟨u, _, _, hu⟩ := dense_interior_exists R P d hd hR hP hdimR hdimP htotal + have hc : u ∈ AffinePenalty.region (normalizedOffset R P) (normalizedCoeff R P d) + (1 / (2 * (d : ℝ))) := by + rw [← normalizedRegion_eq_affine] + exact hu + have hvol := AffinePenalty.relaxed_region_volume_exp (normalizedOffset R P) (normalizedCoeff R P d) + u (d : ℝ) γ (by exact_mod_cast (show 0 < d by omega)) hγ (by exact_mod_cast hfree) hc + rw [← normalizedRegion_eq_affine, ← normalizedRegion_eq_affine, + normalizedRegion_zero R P d hd hR hP] at hvol + exact hvol + +theorem dense_sublevel_volume (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (s : ℝ) (hs : 0 ≤ s) : + volume {x : I × J → ℝ | densePenalty R P d x ≤ s} ≤ + ENNReal.ofReal (Real.exp (2 * (d : ℝ) ^ 2 * ((d : ℝ) / (d : ℝ) ^ 8 + s))) * + volume {x : I × J → ℝ | Feasible R P d x} := by + have hsub : {x : I × J → ℝ | densePenalty R P d x ≤ s} ⊆ + normalizedRegion R P d (-((d : ℝ) / (d : ℝ) ^ 8 + s)) := by + intro x hx g + change densePenalty R P d x ≤ s at hx + have hb := AffinePenalty.component_le_penalty (normalizedOffset R P) (normalizedCoeff R P d) + ((d : ℝ) / (d : ℝ) ^ 8) x (some g) + change -AffinePenalty.affineValue _ _ x - (d : ℝ) / (d : ℝ) ^ 8 ≤ densePenalty R P d x at hb + change -((d : ℝ) / (d : ℝ) ^ 8 + s) ≤ normalizedEntry R P d x g + have heq : normalizedEntry R P d x g = + AffinePenalty.affineValue (normalizedOffset R P g) (normalizedCoeff R P d g) x := + normalized_table_affine _ _ _ _ _ + rw [heq] + linarith + exact (measure_mono hsub).trans (dense_relaxed_volume R P d hd hR hP hdimR hdimP hfree + htotal _ (add_nonneg (by positivity) hs)) + +end + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRegularity.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRegularity.lean new file mode 100644 index 0000000000000000000000000000000000000000..779b6341f32fd6f31423d38056f946ddce0bf1b1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseRegularity.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseCoefficients +import OAI.Combinatorics.ContingencyTables.Dense.DenseScales + +namespace OAI + +/-! +# Regularity of the dense sampler's actual penalty + +The natural margins, maximum pivots, integer quotient widths, and actual +parameters A=d⁴, B=d⁸ determine the penalty. Its regularity and scaled +change bounds follow from the normalized affine coefficients. +-/ + +namespace ContingencyTables.DenseAffine + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +def denseWidth (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) (i : I) (j : J) : ℝ := + ((min (R (some i)) (P (some j)) / d ^ 8 : ℕ) : ℝ) + +noncomputable def densePenalty (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) : + (I × J → ℝ) → ℝ := + AffinePenalty.penalty + (fun g => entryOffset (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + (fun g p => entryCoeff (denseWidth R P d) g p / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + ((d : ℝ) / (d : ℝ) ^ 8) + +omit [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] in +private theorem dense_cellScale_pos (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (g : Option I × Option J) : + 0 < cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g := by + change 0 < min (R g.1 : ℝ) (P g.2 : ℝ) + apply lt_min + · exact_mod_cast (lt_of_lt_of_le (pow_pos (show 0 < d by omega) _) (hR g.1)) + · exact_mod_cast (lt_of_lt_of_le (pow_pos (show 0 < d by omega) _) (hP g.2)) + +omit [Fintype I] [Fintype J] in +theorem dense_normalized_coeff_bound (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (g : Option I × Option J) (p : I × J) : + |entryCoeff (denseWidth R P d) g p / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g| ≤ 1 / (d : ℝ) ^ 8 := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + apply normalized_coeff_bound _ _ _ _ (by positivity) + (fun i => by exact_mod_cast hRmax i) (fun j => by exact_mod_cast hPmax j) + (fun i j => Nat.cast_nonneg _) + (fun i j => ?_) (dense_cellScale_pos R P d hd hR hP) g p + have hmin : d ^ 12 ≤ min (R (some i)) (P (some j)) := le_min (hR _) (hP _) + simpa only [denseWidth, cellScale, Nat.cast_min] using + (dense_width_bounds d _ hd hmin).2 + +theorem densePenalty_continuous (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) : + Continuous (densePenalty R P d) := AffinePenalty.penalty_continuous _ _ _ + +theorem densePenalty_convex (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (K : Set (I × J → ℝ)) (hK : Convex ℝ K) : ConvexOn ℝ K (densePenalty R P d) := + AffinePenalty.penalty_convex _ _ _ K hK + +/-- A coordinate displacement at most `r` changes the actual scaled +penalty A*p by at most `r`. In particular this is at most one in a bin +and at most two in the cut-face tubes. -/ +theorem densePenalty_scaled_change (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (x y : I × J → ℝ) (r : ℝ) (hr : 0 ≤ r) + (hxy : ∀ p, |x p - y p| ≤ r) : + |(d : ℝ) ^ 4 * densePenalty R P d x - (d : ℝ) ^ 4 * densePenalty R P d y| ≤ r := by + have hbase := AffinePenalty.penalty_change + (fun g => entryOffset (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + (fun g p => entryCoeff (denseWidth R P d) g p / + cellScale (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) g) + ((d : ℝ) / (d : ℝ) ^ 8) x y (1 / (d : ℝ) ^ 8) r (by positivity) hr + (dense_normalized_coeff_bound R P d hd hR hP hRmax hPmax) hxy + have hcard : (Fintype.card (I × J) : ℝ) ≤ d := by exact_mod_cast hfree + have hscale : (d : ℝ) ^ 4 * Fintype.card (I × J) / (d : ℝ) ^ 8 ≤ 1 := by + calc + _ ≤ (d : ℝ) ^ 4 * d / (d : ℝ) ^ 8 := by gcongr + _ ≤ 1 := dense_exponent_change_scale d hd + calc + _ = (d : ℝ) ^ 4 * |densePenalty R P d x - densePenalty R P d y| := by + rw [← mul_sub, abs_mul, abs_of_nonneg (by positivity : (0 : ℝ) ≤ (d : ℝ) ^ 4)] + _ ≤ (d : ℝ) ^ 4 * (Fintype.card (I × J) * (1 / (d : ℝ) ^ 8) * r) := + mul_le_mul_of_nonneg_left hbase (by positivity) + _ = ((d : ℝ) ^ 4 * Fintype.card (I × J) / (d : ℝ) ^ 8) * r := by ring + _ ≤ r := by simpa using mul_le_mul_of_nonneg_right hscale hr + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseReindexedVolume.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseReindexedVolume.lean new file mode 100644 index 0000000000000000000000000000000000000000..537feb0bc10e27242d962914f8d6084c5c58c805 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseReindexedVolume.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseRegionVolume +import OAI.Combinatorics.ContingencyTables.Dense.DensityLayers +import Mathlib.MeasureTheory.Constructions.Pi + +namespace OAI + +/-! # Volume-preserving free-coordinate indexing for the dense sampler -/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators ENNReal + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def denseGridFeasible (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (x : Fin q → ℝ) : Prop := + DenseAffine.Feasible R P d (fun p => x (e p)) + +omit [DecidableEq I] [DecidableEq J] in +theorem volume_dense_reindex (e : I × J ≃ Fin q) (S : Set (I × J → ℝ)) : + volume {x : Fin q → ℝ | (fun p => x (e p)) ∈ S} = volume S := by + have hm : (MeasurableEquiv.piCongrLeft (fun _ : I × J => ℝ) e.symm : + (Fin q → ℝ) → (I × J → ℝ)) = (fun x p => x (e p)) := by + ext x p + have h := MeasurableEquiv.piCongrLeft_apply_apply (β := fun _ : I × J => ℝ) e.symm x (e p) + simpa only [Equiv.symm_apply_apply] using h + have h := (volume_measurePreserving_piCongrLeft (fun _ : I × J => ℝ) e.symm).measure_preimage_equiv S + rw [hm] at h + exact h + +omit [DecidableEq I] [DecidableEq J] in +theorem denseGridFeasible_volume (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (e : I × J ≃ Fin q) : + volume {x | denseGridFeasible R P d e x} = + volume {x : I × J → ℝ | DenseAffine.Feasible R P d x} := by + exact volume_dense_reindex e {x | DenseAffine.Feasible R P d x} + +theorem denseGrid_layer_volume (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) (j : ℕ) : + volume (DenseWeights.layerSet ((d : ℝ) ^ 4) (denseGridPenalty R P d e) j) ≤ + ENNReal.ofReal (Real.exp (2 * (d : ℝ) ^ 2 * + ((d : ℝ) / (d : ℝ) ^ 8 + ((j : ℝ) + 1) / (d : ℝ) ^ 4))) * + volume {x | denseGridFeasible R P d e x} := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hset : DenseWeights.layerSet ((d : ℝ) ^ 4) (denseGridPenalty R P d e) j = + {x | denseGridPenalty R P d e x ≤ ((j : ℝ) + 1) / (d : ℝ) ^ 4} := by + ext x + change (d : ℝ) ^ 4 * denseGridPenalty R P d e x ≤ (j : ℝ) + 1 ↔ + denseGridPenalty R P d e x ≤ ((j : ℝ) + 1) / (d : ℝ) ^ 4 + rw [le_div_iff₀ (pow_pos hd₀ 4), mul_comm] + rw [hset, denseGridFeasible_volume] + have hv := volume_dense_reindex e {x | DenseAffine.densePenalty R P d x ≤ + ((j : ℝ) + 1) / (d : ℝ) ^ 4} + change volume {x | denseGridPenalty R P d e x ≤ ((j : ℝ) + 1) / (d : ℝ) ^ 4} = _ at hv + rw [hv] + exact DenseAffine.dense_sublevel_volume R P d hd hR hP hdimR hdimP hfree htotal _ (by positivity) + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseReservedWord.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseReservedWord.lean new file mode 100644 index 0000000000000000000000000000000000000000..9eea9a0f8cbab0581468fab919e3df83085758d3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseReservedWord.lean @@ -0,0 +1,108 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseCanonicalSemantics +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordPadding + +namespace OAI + +/-! # Computing and consuming the exact dense-word prefix -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms FirstSuccess + +def denseParameterBits (z : DenseDrawParameters) : ℕ := + (z.1.2^4*(z.2+1))*trialWidth z + +def denseParameterBitsRealizer : Realizer denseParameterBits := + composition (pair (composition (pair (composition (composition first second) fourthPower) + (composition second successor)) multiply) trialWidthRealizer) multiply + +theorem polynomial_denseParameterBits : PolynomialTime denseParameterBitsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_fourthPower) (polynomial_composition polynomial_second polynomial_successor)) + polynomial_multiply) polynomial_trialWidth) polynomial_multiply + +def preparedCanonicalParameters (z : CanonicalParameters) : DenseDrawParameters := + (preparedDraw (canonicalInput (z,[]))).1.1 + +def preparedCanonicalParametersRealizer : Realizer preparedCanonicalParameters := by + let blank : Realizer (fun z : CanonicalParameters => (z,([] : List Bool))) := + pair identity (constant []) + let input : Realizer (fun z : CanonicalParameters => canonicalInput (z,[])) := + composition (f := fun z : CanonicalParameters => (z,([] : List Bool))) + (g := canonicalInput) blank canonicalInputRealizer + let prep : Realizer (fun z : CanonicalParameters => preparedDraw (canonicalInput (z,[]))) := + composition (f := fun z : CanonicalParameters => canonicalInput (z,[])) + (g := preparedDraw) input preparedDrawRealizer + exact composition (f := fun z : CanonicalParameters => preparedDraw (canonicalInput (z,[]))) + (g := fun z : DenseDrawData => z.1.1) prep (composition first first) + +theorem polynomial_preparedCanonicalParameters : PolynomialTime preparedCanonicalParametersRealizer := by + unfold preparedCanonicalParametersRealizer + exact polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_constant [])) polynomial_canonicalInput) + polynomial_preparedDraw) (polynomial_composition polynomial_first polynomial_first) + +def canonicalBitCount (z : CanonicalParameters) : ℕ := + denseParameterBits (preparedCanonicalParameters z) + +def canonicalBitCountRealizer : Realizer canonicalBitCount := + composition preparedCanonicalParametersRealizer denseParameterBitsRealizer + +theorem polynomial_canonicalBitCount : PolynomialTime canonicalBitCountRealizer := + polynomial_composition polynomial_preparedCanonicalParameters polynomial_denseParameterBits + +def reservedCanonicalDraw (z : CanonicalDrawData) : MatrixCode := + canonicalDenseDraw (z.1,z.2.take (canonicalBitCount z.1)) + +def reservedCanonicalDrawRealizer : Realizer reservedCanonicalDraw := + composition (pair first (composition (pair second + (composition first canonicalBitCountRealizer)) takeFast)) canonicalDenseDrawRealizer + +theorem polynomial_reservedCanonicalDraw : PolynomialTime reservedCanonicalDrawRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_canonicalBitCount)) polynomial_takeFast)) + polynomial_canonicalDenseDraw + +open GridBoundary +open scoped BigOperators Classical +noncomputable section + +theorem canonicalBitCount_code {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 0 < d) (htotal : (∑ i,R i)=∑ j,P j) (h : ℕ) : + canonicalBitCount ((marginCode R,marginCode P),(d,h))=normalizedDrawBits R P d h := by + unfold canonicalBitCount preparedCanonicalParameters + rw [canonicalInput_code R P hd htotal] + unfold preparedDraw + rw [drawIndices_code,permuteDrawData_code] + change (d^4*(h+1))*trialWidth + ((((marginCode (normalizedMargin R),marginCode (normalizedMargin P)), + gridNatCode (canonicalOrigin (m*n) d hd)),d),h)=_ + rw [trialWidth_code] + rfl + +lemma take_ofFn_prefix {k N : ℕ} (hk : k ≤ N) (bits : Fin N → Bool) : + (List.ofFn bits).take k=List.ofFn (prefixWord hk bits) := by + apply List.ext_getElem + · simp only [List.length_take,List.length_ofFn,Nat.min_eq_left hk] + · intro i hi hj + simp only [List.getElem_take,List.getElem_ofFn,prefixWord,Fin.castLE] + +theorem reservedCanonicalDraw_code {m n d N : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14 ≤ d) (hR : ∀ i,d^12 ≤ R i) (hP : ∀ j,d^12 ≤ P j) + (htotal : (∑ i,R i)=∑ j,P j) (h : ℕ) + (hN : normalizedDrawBits R P d h ≤ N) (bits : Fin N → Bool) : + reservedCanonicalDraw (((marginCode R,marginCode P),(d,h)),List.ofFn bits)= + tableOutput (normalizedBooleanDraw R P hd hR hP htotal h + (canonicalOrigin (m*n) d (by omega)) (canonicalFallback R P htotal) (prefixWord hN bits)) := by + unfold reservedCanonicalDraw + rw [canonicalBitCount_code R P (by omega) htotal,take_ofFn_prefix hN] + exact canonicalDenseDraw_eq R P hd hR hP htotal h _ + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScaleCellProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScaleCellProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..783cd07f62c33936f016b998ee70c4fec017e795 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScaleCellProgram.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseExponentListSemantics + +namespace OAI + +/-! # Binary conversion from a grid coordinate to a free integer entry -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped +open GridBoundary + +def shiftedCell (z : ExponentData×(ℕ×ℕ)) : ExponentData×(ℕ×ℕ) := + (z.1,(z.2.1+1,z.2.2+1)) + +def shiftedCellRealizer : Realizer shiftedCell := + pair first (pair (composition (composition second first) successor) + (composition (composition second second) successor)) + +lemma polynomial_shiftedCell : PolynomialTime shiftedCellRealizer := + polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_successor) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) polynomial_successor)) + +def gridCellWidth (z : ExponentData×(ℕ×ℕ)) : ℕ := + (exponentCellData (shiftedCell z)).1.2/z.1.2^8 + +def gridCellWidthRealizer : Realizer gridCellWidth := + composition (pair + (composition (composition (composition shiftedCellRealizer exponentCellDataRealizer) first) second) + (composition (composition first second) eighthPower)) quotient + +theorem polynomial_gridCellWidth : PolynomialTime gridCellWidthRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_shiftedCell polynomial_exponentCellData) polynomial_first) + polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_eighthPower)) polynomial_quotient + +def gridCellValue (z : ExponentData×(ℕ×ℕ)) : ℕ := + gridCellWidth z*matrixEntry (z.1.1.2,z.2) + +def gridCellValueRealizer : Realizer gridCellValue := + composition (pair gridCellWidthRealizer + (composition (pair (composition (composition first first) second) second) matrixEntryRealizer)) + multiply + +theorem polynomial_gridCellValue : PolynomialTime gridCellValueRealizer := + polynomial_composition (polynomial_pair polynomial_gridCellWidth + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_second) polynomial_matrixEntry)) polynomial_multiply + +variable {m n q K : ℕ} + +theorem gridCellValue_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (a : Grid (I := Fin q) K) (e : Fin m×Fin n ≃ Fin q) + (i : Fin m) (j : Fin n) : + gridCellValue (exponentDataCode R P d + (fun i j => (corner a (e (i,j))).toNat),(i.val,j.val))= + cornerFree R P d e a (i,j) := by + have hR := marginCode_getD R (some i) + have hP := marginCode_getD P (some j) + change (marginCode R).getD (i.val+1) 0=R (some i) at hR + change (marginCode P).getD (j.val+1) 0=P (some j) at hP + simp only [gridCellValue,gridCellWidth,shiftedCell,exponentCellData,exponentDataCode, + hR,hP,matrixEntry_code,cornerFree,integerWidth] + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScaleMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScaleMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..f0ff58f731ca1b8a55622d0282b8bf4cfbc357b2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScaleMatrixProgram.lean @@ -0,0 +1,116 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseScaleCellProgram + +namespace OAI + +/-! # Scaling a binary grid matrix to its integer bin corner -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped Polynomial GridBoundary + +def scaleRows (z : ExponentData) : List ℕ := List.range z.1.1.1.tail.length +def scaleColumns (z : ExponentData) : List ℕ := List.range z.1.1.2.tail.length + +def scaleRowsRealizer : Realizer scaleRows := + composition (composition (composition (composition (composition first first) first) tail) + listLength) range + +def scaleColumnsRealizer : Realizer scaleColumns := + composition (composition (composition (composition (composition first first) second) tail) + listLength) range + +lemma polynomial_scaleRows : PolynomialTime scaleRowsRealizer := by + change PolynomialTime (composition _ range) + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) + polynomial_tail) polynomial_listLength) X + intro z + have h := list_length_le_weight z.1.1.1 + simp only [Function.comp_apply,eval_X,List.length_tail] + exact (Nat.sub_le _ _).trans (h.trans ((weight_fst z.1.1).trans + ((weight_fst z.1).trans (weight_fst z)))) + +lemma polynomial_scaleColumns : PolynomialTime scaleColumnsRealizer := by + change PolynomialTime (composition _ range) + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_tail) polynomial_listLength) X + intro z + have h := list_length_le_weight z.1.1.2 + simp only [Function.comp_apply,eval_X,List.length_tail] + exact (Nat.sub_le _ _).trans (h.trans ((weight_snd z.1.1).trans + ((weight_fst z.1).trans (weight_fst z)))) + +def scaleRowEntry (z : (ExponentData×ℕ)×ℕ) : ℕ := + gridCellValue (z.1.1,(z.1.2,z.2)) + +def scaleRowEntryRealizer : Realizer scaleRowEntry := + composition (pair (composition first first) (pair (composition first second) second)) + gridCellValueRealizer + +lemma polynomial_scaleRowEntry : PolynomialTime scaleRowEntryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_gridCellValue + +def scaleRow (z : ExponentData×ℕ) : List ℕ := + (scaleColumns z.1).map (fun j => scaleRowEntry (z,j)) + +def scaleRowRealizer : Realizer scaleRow := + composition (pair identity (composition first scaleColumnsRealizer)) (mapWith scaleRowEntryRealizer) + +lemma polynomial_scaleRow : PolynomialTime scaleRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_scaleColumns)) + (polynomial_mapWith polynomial_scaleRowEntry) + +def scaleMatrix (z : ExponentData) : MatrixCode := + (scaleRows z).map (fun i => scaleRow (z,i)) + +def scaleMatrixRealizer : Realizer scaleMatrix := + composition (pair identity scaleRowsRealizer) (mapWith scaleRowRealizer) + +theorem polynomial_scaleMatrix : PolynomialTime scaleMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_scaleRows) + (polynomial_mapWith polynomial_scaleRow) + +variable {m n q K : ℕ} + +private lemma scaleRow_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (a : Grid (I := Fin q) K) (e : Fin m×Fin n ≃ Fin q) (i : Fin m) : + scaleRow (exponentDataCode R P d (fun i j => (corner a (e (i,j))).toNat),i.val)= + List.ofFn (fun j => cornerFree R P d e a (i,j)) := by + have hcol : scaleColumns (exponentDataCode R P d + (fun i j => (corner a (e (i,j))).toNat))=List.range n := by + simp only [scaleColumns,exponentDataCode,marginCode,List.tail_cons,List.length_ofFn] + unfold scaleRow + rw [hcol] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro j hj _ + have hjn : j < n := by simpa only [List.length_map,List.length_range] using hj + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn,scaleRowEntry] + exact gridCellValue_code R P d a e i ⟨j,hjn⟩ + +/-- Every free entry is the integer width times the selected grid corner. -/ +theorem scaleMatrix_code (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (a : Grid (I := Fin q) K) (e : Fin m×Fin n ≃ Fin q) : + scaleMatrix (exponentDataCode R P d (fun i j => (corner a (e (i,j))).toNat))= + matrixCode (fun i j => cornerFree R P d e a (i,j)) := by + have hrow : scaleRows (exponentDataCode R P d + (fun i j => (corner a (e (i,j))).toNat))=List.range m := by + simp only [scaleRows,exponentDataCode,marginCode,List.tail_cons,List.length_ofFn] + unfold scaleMatrix matrixCode + rw [hrow] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have him : i < m := by simpa only [List.length_map,List.length_range] using hi + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + exact scaleRow_code R P d a e ⟨i,him⟩ + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScales.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScales.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe43bc346fbcc83a7c100f1aaf6a2335345e5385 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseScales.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ContingencyTables.Parameters +import Mathlib.Data.Nat.Cast.Order.Field + +namespace OAI + +/-! +# Integer bin widths for dense blocks + +The free-cell width is the actual integer quotient `floor(s/B)`, where +`s=min(Rᵢ,Pⱼ)`. Large margins give the two-sided scale comparison used in +the dense rejection sampler. +-/ + +namespace ContingencyTables.DenseAffine + +theorem integer_width_bounds (s B : ℕ) (hB : 0 < B) (hs : 2 * B ≤ s) : + (s : ℝ) / (2 * B) ≤ (s / B : ℕ) ∧ (s / B : ℕ) ≤ (s : ℝ) / B := by + have hq : 0 < s / B := Nat.div_pos (by omega) hB + have hmod := Nat.mod_lt s hB + have hid := Nat.mod_add_div s B + have hscale : s ≤ 2 * B * (s / B) := by nlinarith + constructor + · apply (div_le_iff₀ (show (0 : ℝ) < 2 * B by positivity)).mpr + have hscale' : (s : ℝ) ≤ 2 * (B : ℝ) * (s / B : ℕ) := by exact_mod_cast hscale + nlinarith + · exact Nat.cast_div_le + +theorem dense_width_positive (d s : ℕ) (hd : 14 ≤ d) (hs : d ^ 12 ≤ s) : + 0 < s / d ^ 8 := by + have hd₀ : 0 < d := by omega + have hpow : d ^ 8 ≤ d ^ 12 := by + apply Nat.pow_le_pow_right (by omega : 1 ≤ d) + decide + exact Nat.div_pos (hpow.trans hs) (pow_pos hd₀ _) + +theorem dense_width_bounds (d s : ℕ) (hd : 14 ≤ d) (hs : d ^ 12 ≤ s) : + (s : ℝ) / (2 * (d : ℝ) ^ 8) ≤ (s / d ^ 8 : ℕ) ∧ + (s / d ^ 8 : ℕ) ≤ (s : ℝ) / (d : ℝ) ^ 8 := by + have hd₀ : 0 < d := by omega + have hfour : 2 ≤ d ^ 4 := by + have h := Nat.le_self_pow (show 4 ≠ 0 by decide) d + omega + have hscale : 2 * d ^ 8 ≤ d ^ 12 := by + calc + 2 * d ^ 8 ≤ d ^ 4 * d ^ 8 := Nat.mul_le_mul_right _ hfour + _ = d ^ 12 := by ring + simpa only [Nat.cast_pow] using + integer_width_bounds s (d ^ 8) (pow_pos hd₀ _) (hscale.trans hs) + +/-- The product `A*d/B=d⁻³` is at most one with the actual integer +parameter choices. This controls the density within each unit bin. -/ +theorem dense_exponent_change_scale (d : ℕ) (hd : 14 ≤ d) : + (d : ℝ) ^ 4 * d / (d : ℝ) ^ 8 ≤ 1 := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hd₁ : (1 : ℝ) ≤ d := by exact_mod_cast (show 1 ≤ d by omega) + apply (div_le_one (pow_pos hd₀ _)).mpr + calc + (d : ℝ) ^ 4 * d = (d : ℝ) ^ 5 := by ring + _ ≤ (d : ℝ) ^ 8 := pow_le_pow_right₀ hd₁ (by decide) + +end ContingencyTables.DenseAffine + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseStepGrowth.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseStepGrowth.lean new file mode 100644 index 0000000000000000000000000000000000000000..00bea6c9b400595c3a62c93dc6c96242e7b2c8a2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseStepGrowth.lean @@ -0,0 +1,79 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram + +namespace OAI + +/-! # Binary size bounds for repeated dense steps on arbitrary input -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms + +lemma getD_size_bound (xs : List ℕ) (S i : ℕ) + (h : ∀ a∈xs,a.size≤S) : (xs.getD i 0).size≤S := by + by_cases hi : i decide + have hb := nat_size_add (xs.getD k 0) (if k=i then 1 else 0) + have hs := Nat.size_le_size (Nat.sub_le + (xs.getD k 0+(if k=i then 1 else 0)) (if k=j then 1 else 0)) + change (xs.getD k 0+(if k=i then 1 else 0)-(if k=j then 1 else 0)).size≤S+2 + omega + +lemma axisListStep_growth (z : AxisData) (ys : List ℕ) (S : ℕ) + (h : axisListStep z=some ys) (hx : ∀ a∈z.1.1.2,a.size≤S) : + ys.length=z.1.1.2.length ∧ ∀ a∈ys,a.size≤S+2 := by + rcases z with ⟨⟨⟨K,xs⟩,i⟩,sign⟩ + by_cases hi : i + by_cases hp : 0 + by_cases hp : xs.getD i 0+1 (hx a ha).trans (Nat.le_add_right _ _)⟩ + unfold flatMetropolisStep + cases h : flatStepCandidate z with + | none => exact hstay + | some ys => + have hy := axisListStep_growth + (((4*z.1.2^8,z.1.1.2),MatchingFPRAS.StackAddition.value z.2.1/2), + decide (MatchingFPRAS.StackAddition.value z.2.1%2=1)) ys S h hx + simp only [Option.elim_some,flatAcceptCandidate] + split <;> assumption + +lemma flatWordStep_growth (z : FlatExponentData×List Bool) (S : ℕ) + (hx : ∀ a∈z.1.1.2,a.size≤S) : + (flatWordStep z).length=z.1.1.2.length ∧ + ∀ a∈flatWordStep z,a.size≤S+2 := + flatMetropolisStep_growth _ S hx + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseSuccessCounts.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseSuccessCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..d5a097c272d7cfba838482eb39ce0622d560d8e1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseSuccessCounts.lean @@ -0,0 +1,63 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerLaw + +namespace OAI + +/-! # One entry per accepted dense table, with no trial-fibre enumeration -/ + +namespace ContingencyTables.GridBoundary +open FairBits +open scoped BigOperators Classical +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +/-- The unique bin-offset trial for a table supplies its entire success +count. This removes a sum over all trials from each output lookup. -/ +theorem denseTrial_success_count (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (e : I×J ≃ Fin q) (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin q) (4*d^8)) (X : Table R P) : + ((denseTrialCounts R P d hd hR hP e h a).push (trialSuccess R P d e htotal)).count + (some X)= + (denseTrialCounts R P d hd hR hP e h a).count (tableTrial R P d hd hR hP e X) := by + change (∑ t,if trialSuccess R P d e htotal t=some X then + (denseTrialCounts R P d hd hR hP e h a).count t else 0)=_ + simp_rw [trialSuccess_some_iff R P d hd hR hP e htotal] + simp + +/-- The rejected count is determined by the known common denominator +and the accepted table counts, including all invalid completions. -/ +theorem denseTrial_failure_count (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (e : I×J ≃ Fin q) (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin q) (4*d^8)) : + ((denseTrialCounts R P d hd hR hP e h a).push (trialSuccess R P d e htotal)).count none= + 2^denseTrialBits R P d e h- + ∑ X : Table R P,(denseTrialCounts R P d hd hR hP e h a).count + (tableTrial R P d hd hR hP e X) := by + have ht := ((denseTrialCounts R P d hd hR hP e h a).push + (trialSuccess R P d e htotal)).total + rw [Fintype.sum_option] at ht + simp_rw [denseTrial_success_count R P d hd hR hP e htotal] at ht + omega + +/-- Evaluation uses one propagated bin numerator and one product of +closed-form offset counts; it never enumerates the acceptance bits. -/ +theorem denseTrial_table_count (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (e : I×J ≃ Fin q) (h : ℕ) + (a : Grid (I := Fin q) (4*d^8)) (X : Table R P) : + (denseTrialCounts R P d hd hR hP e h a).count (tableTrial R P d hd hR hP e X)= + IntegerPropagation.numerators (denseTransitionCount R P d e) a (d^50*(h+1)^2) + (tableTrial R P d hd hR hP e X).1 * + ∏ j : Fin q,OffsetCountPrograms.offsetCount + ((integerWidth R P d (e.symm j), + 2^offsetBitLength (integerWidth R P d (e.symm j)) h d), + ((offsetCoordinateEquiv e (integerWidth R P d)).symm + (tableTrial R P d hd hR hP e X).2 j).val) := rfl + +end +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseSuppliedFallback.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseSuppliedFallback.lean new file mode 100644 index 0000000000000000000000000000000000000000..c17c4488e739327e6a4f808b7023ede7039362dd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseSuppliedFallback.lean @@ -0,0 +1,127 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseDrawTabulation + +namespace OAI + +/-! # Dense law tabulation retains the supplied feasible fallback -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary +open scoped BigOperators Classical + +abbrev SuppliedTabulation := CanonicalParameters×MatrixCode + +def replaceVectorFallback (z : VectorRetryPrograms.Input×ℕ) : VectorRetryPrograms.Input := + (z.1.1,(z.1.2.1,z.2)) + +def replaceVectorFallbackRealizer : Realizer replaceVectorFallback := + pair (composition first first) (pair (composition (composition first second) first) second) + +lemma polynomial_replaceVectorFallback : PolynomialTime replaceVectorFallbackRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition (polynomial_composition polynomial_first + polynomial_second) polynomial_first) polynomial_second) + +def suppliedVectorInput (z : SuppliedTabulation) : VectorRetryPrograms.Input := + replaceVectorFallback (rawVectorInput z.1,tableIndex (z.1.1,z.2)) + +def suppliedVectorInputRealizer : Realizer suppliedVectorInput := by + let base := composition (first (A := CanonicalParameters) (B := MatrixCode)) + rawVectorInputRealizer + let margins : Realizer (fun z : SuppliedTabulation => z.1.1) := composition first first + let query := pair margins (second (A := CanonicalParameters) (B := MatrixCode)) + let index := composition query tableIndexRealizer + let result := composition (pair base index) replaceVectorFallbackRealizer + exact result + +def suppliedTabulationMeasure (z : SuppliedTabulation) : ℕ := rawTabulationMeasure z.1+weight z + +lemma work_suppliedVectorInput : WorkBound suppliedVectorInputRealizer suppliedTabulationMeasure := by + have hb : WorkBound (composition first rawVectorInputRealizer) suppliedTabulationMeasure := by + apply work_composition (work_of_polynomial polynomial_first Polynomial.X + (fun z => by simp only [suppliedTabulationMeasure,Polynomial.eval_X]; omega)) + work_rawVectorInput Polynomial.X + intro z + simp only [Polynomial.eval_X,suppliedTabulationMeasure] + omega + have hi : WorkBound (composition (pair (composition first first) second) tableIndexRealizer) + suppliedTabulationMeasure := + work_of_polynomial (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_tableIndex) Polynomial.X + (fun z => by simp only [suppliedTabulationMeasure,Polynomial.eval_X]; omega) + unfold suppliedVectorInputRealizer + apply work_then_polynomial _ polynomial_replaceVectorFallback + exact work_pair hb hi Polynomial.X + (fun z => by simp only [suppliedTabulationMeasure,Polynomial.eval_X]; omega) + +def suppliedDrawCounts (z : SuppliedTabulation) : List ℕ := + VectorRetryPrograms.counts (suppliedVectorInput z) + +def suppliedDrawCountsRealizer : Realizer suppliedDrawCounts := + composition suppliedVectorInputRealizer VectorRetryPrograms.countsRealizer + +theorem work_suppliedDrawCounts : WorkBound suppliedDrawCountsRealizer suppliedTabulationMeasure := by + obtain ⟨p,hp⟩ := work_suppliedVectorInput + obtain ⟨q,hq⟩ := VectorRetryPrograms.polynomial_counts + refine ⟨p+q.comp p,fun z => ?_⟩ + have h1 := hp z + have h2 := hq (suppliedVectorInput z) + have h3 := polynomial_eval_monotone q ((Nat.le_add_left _ _).trans h1) + dsimp only at h3 + simp only [Polynomial.eval_add,Polynomial.eval_comp] + change suppliedVectorInputRealizer.cost z+ + VectorRetryPrograms.countsRealizer.cost (suppliedVectorInput z)+ + weight (VectorRetryPrograms.counts (suppliedVectorInput z))≤_ + omega + +/-- The fallback is transported by the caller's normalization, rather +than being recomputed in the normalized margin order. -/ +theorem suppliedDrawCounts_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (fallback : Table R P) : + suppliedDrawCounts (((marginCode R,marginCode P),(d,h)),tableOutput fallback)= + List.ofFn (((IndexedTableLaw.law R P (le_refl (∑ i,R i)) + ((denseTrialCounts R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega))).push + (trialSuccess R P d finProdFinEquiv htotal))).retry + (IndexedTableLaw.index R P (le_refl (∑ i,R i)) fallback) (d^4*(h+1))).count) := by + have hc : ∀ j : Fin (m*n),FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm j)) h d≤ + (unaryMarkers (denseTrialBits R P d finProdFinEquiv h)).length := by + intro j + rw [unaryMarkers_length] + have hs : FairBits.offsetBitLength (integerWidth R P d (finProdFinEquiv.symm j)) h d≤ + ∑ k : Fin (m*n),FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm k)) h d := + Finset.single_le_sum + (f := fun k : Fin (m*n) => FairBits.offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm k)) h d) + (fun _ _ => Nat.zero_le _) (Finset.mem_univ j) + exact hs.trans (by unfold denseTrialBits; omega) + unfold suppliedDrawCounts suppliedVectorInput replaceVectorFallback rawVectorInput rawCountContext + rw [rawTrialBits_code (d := d) R P (show 0 swapZeroEntry (z,i)) + +def swapZeroListRealizer : Realizer (swapZeroList (A := A)) := + composition (pair identity swapZeroIndicesRealizer) (mapWith swapZeroEntryRealizer) + +theorem polynomial_swapZeroList : PolynomialTime (swapZeroListRealizer (A := A)) := + polynomial_composition (polynomial_pair polynomial_identity polynomial_swapZeroIndices) + (polynomial_mapWith polynomial_swapZeroEntry) + +def swapMatrixColumns (z : ℕ×MatrixCode) : MatrixCode := + z.2.map (fun row => swapZeroList (z.1,row)) + +def swapMatrixColumnsRealizer : Realizer swapMatrixColumns := mapWith swapZeroListRealizer + +theorem polynomial_swapMatrixColumns : PolynomialTime swapMatrixColumnsRealizer := + polynomial_mapWith polynomial_swapZeroList + +def swapMatrix (z : (ℕ×ℕ)×MatrixCode) : MatrixCode := + swapMatrixColumns (z.1.2,swapZeroList (z.1.1,z.2)) + +def swapMatrixRealizer : Realizer swapMatrix := + composition (pair (composition first second) + (composition (pair (composition first first) second) swapZeroListRealizer)) swapMatrixColumnsRealizer + +theorem polynomial_swapMatrix : PolynomialTime swapMatrixRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_swapZeroList)) polynomial_swapMatrixColumns + +open scoped Classical + +lemma swapZeroIndex_val {n : ℕ} (p i : Fin (n+1)) : + swapZeroIndex (p.val,i.val)=(Equiv.swap 0 p i).val := by + by_cases hi : i=0 + · subst i + rw [Equiv.swap_apply_left] + simp only [swapZeroIndex,Fin.val_zero,ite_true] + · have hi0 : i.val≠0 := fun h => hi (Fin.ext h) + by_cases hp : i=p + · subst i + rw [Equiv.swap_apply_right] + simp only [swapZeroIndex,hi0,ite_false,ite_true,Fin.val_zero] + · have hip : i.val≠p.val := fun h => hp (Fin.ext h) + rw [Equiv.swap_apply_of_ne_of_ne hi hp] + simp only [swapZeroIndex,hi0,hip,ite_false] + +omit [Codec A] in +theorem swapZeroList_ofFn {n : ℕ} (p : Fin (n+1)) (f : Fin (n+1) → A) : + swapZeroList (p.val,List.ofFn f)=List.ofFn (fun i => f (Equiv.swap 0 p i)) := by + apply List.ext_getElem + · simp only [swapZeroList,swapZeroIndices,List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have hin : i < n+1 := by + simpa only [swapZeroList,swapZeroIndices,List.length_map,List.length_range,List.length_ofFn] using hi + simp only [swapZeroList,swapZeroIndices,List.getElem_map,List.getElem_range,List.getElem_ofFn, + swapZeroEntry] + rw [swapZeroIndex_val p ⟨i,hin⟩] + rw [List.getD_eq_getElem (List.ofFn f) default (by simpa only [List.length_ofFn] using (Equiv.swap 0 p ⟨i,hin⟩).isLt)] + simp only [List.getElem_ofFn,Fin.eta] + +theorem swapMatrix_code {m n : ℕ} (i : Fin (m+1)) (j : Fin (n+1)) + (X : Fin (m+1) → Fin (n+1) → ℕ) : + swapMatrix ((i.val,j.val),matrixCode X)= + matrixCode (fun a b => X (Equiv.swap 0 i a) (Equiv.swap 0 j b)) := by + unfold swapMatrix matrixCode + rw [swapZeroList_ofFn] + unfold swapMatrixColumns + rw [List.map_ofFn] + apply congrArg List.ofFn + funext a + exact swapZeroList_ofFn j _ + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTableCoordinates.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTableCoordinates.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e2e25e62add5814e8cffb73821391c890a5fab9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTableCoordinates.lean @@ -0,0 +1,181 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetWidths +import OAI.Combinatorics.ContingencyTables.Machines.TranslationDecisionProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseSuccessCounts + +namespace OAI + +/-! # Reading the unique bin and offset of an accepted table -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary ProfilePrograms +open scoped BigOperators Classical + +def tableFreeValue (z : ExponentData×(ℕ×ℕ)) : ℕ := + matrixEntry (z.1.1.2,(z.2.1+1,z.2.2+1)) + +def tableFreeValueRealizer : Realizer tableFreeValue := + composition (pair (composition (composition first first) second) + (composition shiftedCellRealizer second)) matrixEntryRealizer + +lemma polynomial_tableFreeValue : PolynomialTime tableFreeValueRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_shiftedCell polynomial_second)) polynomial_matrixEntry + +def tableBinCoordinate (z : ExponentData×(ℕ×ℕ)) : ℕ := tableFreeValue z/gridCellWidth z + +def tableBinCoordinateRealizer : Realizer tableBinCoordinate := + composition (pair tableFreeValueRealizer gridCellWidthRealizer) quotient + +lemma polynomial_tableBinCoordinate : PolynomialTime tableBinCoordinateRealizer := + polynomial_composition (polynomial_pair polynomial_tableFreeValue polynomial_gridCellWidth) + polynomial_quotient + +def tableOffsetCoordinate (z : ExponentData×(ℕ×ℕ)) : ℕ := tableFreeValue z%gridCellWidth z + +def tableOffsetCoordinateRealizer : Realizer tableOffsetCoordinate := + composition (pair tableFreeValueRealizer gridCellWidthRealizer) remainder + +lemma polynomial_tableOffsetCoordinate : PolynomialTime tableOffsetCoordinateRealizer := + polynomial_composition (polynomial_pair polynomial_tableFreeValue polynomial_gridCellWidth) + polynomial_remainder + +def tableFreeCells (z : ExponentData) : List (ℕ×ℕ) := freeCells (z,0) + +def tableFreeCellsRealizer : Realizer tableFreeCells := + composition (pair identity (constant 0)) freeCellsRealizer + +lemma polynomial_tableFreeCells : PolynomialTime tableFreeCellsRealizer := + polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant 0)) + polynomial_freeCells + +def tableBinCoordinates (z : ExponentData) : List ℕ := + (tableFreeCells z).map (fun ij => tableBinCoordinate (z,ij)) + +def tableBinCoordinatesRealizer : Realizer tableBinCoordinates := + composition (pair identity tableFreeCellsRealizer) (mapWith tableBinCoordinateRealizer) + +lemma polynomial_tableBinCoordinates : PolynomialTime tableBinCoordinatesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_tableFreeCells) + (polynomial_mapWith polynomial_tableBinCoordinate) + +def tableOffsetCoordinates (z : ExponentData) : List ℕ := + (tableFreeCells z).map (fun ij => tableOffsetCoordinate (z,ij)) + +def tableOffsetCoordinatesRealizer : Realizer tableOffsetCoordinates := + composition (pair identity tableFreeCellsRealizer) (mapWith tableOffsetCoordinateRealizer) + +lemma polynomial_tableOffsetCoordinates : PolynomialTime tableOffsetCoordinatesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_tableFreeCells) + (polynomial_mapWith polynomial_tableOffsetCoordinate) + +def tableWidths (z : ExponentData) : List ℕ := + (tableFreeCells z).map (fun ij => gridCellWidth (z,ij)) + +def tableWidthsRealizer : Realizer tableWidths := + composition (pair identity tableFreeCellsRealizer) (mapWith gridCellWidthRealizer) + +lemma polynomial_tableWidths : PolynomialTime tableWidthsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_tableFreeCells) + (polynomial_mapWith polynomial_gridCellWidth) + +def tableCoordinatesCode {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (X : Table R P) : ExponentData := + (((marginCode R,marginCode P),tableOutput X),d) + +lemma tableFreeValue_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (X : Table R P) (i : Fin m) (j : Fin n) : + tableFreeValue (tableCoordinatesCode R P d X,(i.val,j.val))=X.val (some i) (some j) := by + exact tableOutput_entry R P X (some i) (some j) + +lemma tableCellWidth_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (X : Table R P) (i : Fin m) (j : Fin n) : + gridCellWidth (tableCoordinatesCode R P d X,(i.val,j.val))=integerWidth R P d (i,j) := by + have hr := marginCode_getD R (some i) + have hc := marginCode_getD P (some j) + change (marginCode R).getD (i.val+1) 0=R (some i) at hr + change (marginCode P).getD (j.val+1) 0=P (some j) at hc + simp only [gridCellWidth,shiftedCell,exponentCellData,tableCoordinatesCode,hr,hc] + rfl + +lemma tableBinCoordinate_code {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (X : Table R P) (i : Fin m) (j : Fin n) : + tableBinCoordinate (tableCoordinatesCode R P d X,(i.val,j.val))= + (corner (tableTrial R P d hd hR hP finProdFinEquiv X).1 + (finProdFinEquiv (i,j))).toNat := by + rw [tableBinCoordinate,tableFreeValue_code,tableCellWidth_code] + change _ = X.val (some ((finProdFinEquiv : Fin m×Fin n ≃ Fin (m*n)).symm + (finProdFinEquiv (i,j))).1) + (some (finProdFinEquiv.symm (finProdFinEquiv (i,j))).2)/ + integerWidth R P d (finProdFinEquiv.symm (finProdFinEquiv (i,j))) + rw [Equiv.symm_apply_apply] + +lemma tableOffsetCoordinate_code {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (X : Table R P) (i : Fin m) (j : Fin n) : + tableOffsetCoordinate (tableCoordinatesCode R P d X,(i.val,j.val))= + ((tableTrial R P d hd hR hP finProdFinEquiv X).2 (i,j)).val := by + rw [tableOffsetCoordinate,tableFreeValue_code,tableCellWidth_code] + rfl + +lemma tableFreeCells_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (X : Table R P) : + tableFreeCells (tableCoordinatesCode R P d X)=List.ofFn (fun v : Fin (m*n) => + (((finProdFinEquiv : Fin m×Fin n ≃ Fin (m*n)).symm v).1.val, + (finProdFinEquiv.symm v).2.val)) := by + simp only [tableFreeCells,freeCells,tableCoordinatesCode,marginCode,List.tail_cons] + exact cellPairs_ofFn _ _ + +lemma tableBinCoordinates_code {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (X : Table R P) : + tableBinCoordinates (tableCoordinatesCode R P d X)= + gridNatCode (tableTrial R P d hd hR hP finProdFinEquiv X).1 := by + rw [tableBinCoordinates,tableFreeCells_code,List.map_ofFn] + apply congrArg List.ofFn + funext v + have he := tableBinCoordinate_code R P hd hR hP X + ((finProdFinEquiv : Fin m×Fin n ≃ Fin (m*n)).symm v).1 + (finProdFinEquiv.symm v).2 + simpa only [Function.comp_apply,Prod.mk.eta,Equiv.apply_symm_apply] using he + +lemma tableOffsetCoordinates_code {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) + (X : Table R P) : + tableOffsetCoordinates (tableCoordinatesCode R P d X)=List.ofFn (fun v : Fin (m*n) => + ((tableTrial R P d hd hR hP finProdFinEquiv X).2 (finProdFinEquiv.symm v)).val) := by + rw [tableOffsetCoordinates,tableFreeCells_code,List.map_ofFn] + apply congrArg List.ofFn + funext v + exact tableOffsetCoordinate_code R P hd hR hP X + ((finProdFinEquiv : Fin m×Fin n ≃ Fin (m*n)).symm v).1 + (finProdFinEquiv.symm v).2 + +lemma tableWidths_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d : ℕ) (X : Table R P) : + tableWidths (tableCoordinatesCode R P d X)=List.ofFn (fun v : Fin (m*n) => + integerWidth R P d (finProdFinEquiv.symm v)) := by + rw [tableWidths,tableFreeCells_code,List.map_ofFn] + apply congrArg List.ofFn + funext v + exact tableCellWidth_code R P d X + ((finProdFinEquiv : Fin m×Fin n ≃ Fin (m*n)).symm v).1 + (finProdFinEquiv.symm v).2 + +lemma tableOffsetLengths_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d h : ℕ) (X : Table R P) : + offsetLengths (tableCoordinatesCode R P d X,h)=List.ofFn (fun v : Fin (m*n) => + FairBits.offsetBitLength (integerWidth R P d (finProdFinEquiv.symm v)) h d) := by + change (tableFreeCells (tableCoordinatesCode R P d X)).map _=_ + rw [tableFreeCells_code,List.map_ofFn] + apply congrArg List.ofFn + funext v + unfold offsetLength + dsimp only [Function.comp_apply] + rw [tableCellWidth_code] + rfl + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTabulationScalarBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTabulationScalarBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..2d1a4e2d0a0e882e11827e3b00513034b0872168 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTabulationScalarBounds.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseDrawTabulation +import OAI.Combinatorics.ContingencyTables.Machines.EnumerationPointBounds +import OAI.Combinatorics.ContingencyTables.Sampling.PaddedEnumerationBounds + +namespace OAI + +/-! # Numeric dense-tabulation schedules versus binary margin size -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary Polynomial + +lemma clog_succ_le_weight (n : ℕ) : Nat.clog 2 (n+1) ≤ weight n := by + exact (Nat.clog_le_of_le_pow (Nat.succ_le_iff.mpr (Nat.lt_size_self n))).trans + (size_le_weight n) + +def offsetNumericMeasure (z : OffsetWidthData) : ℕ := z.1.2+z.2+weight z + +theorem offsetLengths_sum_polynomial : ∃ p : Polynomial ℕ,∀ z, + (offsetLengths z).sum ≤ p.eval (offsetNumericMeasure z) := by + obtain ⟨p,hp⟩ := polynomial_freeCells + obtain ⟨q,hq⟩ := polynomial_gridCellWidth + let input : Polynomial ℕ := 1+X+p + let entry : Polynomial ℕ := q.comp input+4*X + refine ⟨p*entry,?_⟩ + intro z + let M := offsetNumericMeasure z + have hz : weight z ≤ M := by unfold M offsetNumericMeasure; omega + have hfree := (hp z).trans (polynomial_eval_monotone p hz) + have hlen : (freeCells z).length ≤ p.eval M := + (list_length_le_weight _).trans ((Nat.le_add_left _ _).trans hfree) + have he (ij : ℕ×ℕ) (hij : ij∈freeCells z) : offsetLength (z,ij) ≤ entry.eval M := by + have hw : weight ij ≤ p.eval M := (weight_mem hij).trans ((Nat.le_add_left _ _).trans hfree) + have hi : weight (z.1,ij) ≤ input.eval M := by + have hfirst : weight z.1 ≤ M := (weight_fst z).trans hz + simp only [weight_prod,input,eval_add,eval_one,eval_X] + omega + have hg : weight (gridCellWidth (z.1,ij)) ≤ q.eval (input.eval M) := + (Nat.le_add_left _ _).trans ((hq _).trans (polynomial_eval_monotone q hi)) + have hn : z.2+z.1.2 ≤ M := by unfold M offsetNumericMeasure; omega + have hc := (clog_succ_le_weight (gridCellWidth (z.1,ij))).trans hg + change Nat.clog 2 (gridCellWidth (z.1,ij)+1)+4*(z.2+z.1.2) ≤ _ + simp only [entry,eval_add,eval_comp,eval_mul,eval_ofNat,eval_X] + omega + have hs := list_sum_le_length_mul (offsetLengths z) (entry.eval M) (by + intro a ha + rw [offsetLengths] at ha + obtain ⟨ij,hij,rfl⟩ := List.mem_map.mp ha + exact he ij hij) + simp only [offsetLengths,List.length_map] at hs + exact hs.trans (by rw [eval_mul]; exact Nat.mul_le_mul_right _ hlen) + +def trialNumericMeasure (z : DenseDrawParameters) : ℕ := z.1.2+z.2+weight z + +theorem trialWidth_polynomial : ∃ p : Polynomial ℕ,∀ z, + trialWidth z ≤ p.eval (trialNumericMeasure z) := by + have ht : PolynomialTime + (pair (composition (first (B := ℕ)) flatToGridDataRealizer) second) := + polynomial_pair (polynomial_composition polynomial_first polynomial_flatToGridData) polynomial_second + obtain ⟨p,hp⟩ := ht + obtain ⟨q,hq⟩ := offsetLengths_sum_polynomial + let walk : Polynomial ℕ := X^50*(X+1)^2*(16*X^5) + refine ⟨walk+q.comp (X+p),?_⟩ + intro z + let M := trialNumericMeasure z + have hz : weight z ≤ M := by unfold M trialNumericMeasure; omega + have hd : z.1.2 ≤ M := by unfold M trialNumericMeasure; omega + have hh : z.2 ≤ M := by unfold M trialNumericMeasure; omega + have hp' := (hp z).trans (polynomial_eval_monotone p hz) + have hw : weight (flatToGridData z.1,z.2) ≤ p.eval M := (Nat.le_add_left _ _).trans hp' + have hm : offsetNumericMeasure (flatToGridData z.1,z.2) ≤ (X+p).eval M := by + change z.1.2+z.2+weight (flatToGridData z.1,z.2) ≤ _ + simp only [eval_add,eval_X] + unfold M trialNumericMeasure at * + omega + have ho := (hq (flatToGridData z.1,z.2)).trans (polynomial_eval_monotone q hm) + have hb := denseStepBits_upper z.1.2 + have hwalk : trialWalkBits (z,[]) ≤ walk.eval M := by + simp only [trialWalkBits,walk,eval_mul,eval_pow,eval_add,eval_X,eval_one,eval_ofNat] + exact Nat.mul_le_mul + (Nat.mul_le_mul (Nat.pow_le_pow_left hd _) (Nat.pow_le_pow_left (by omega) _)) + (hb.trans (Nat.mul_le_mul_left 16 (Nat.pow_le_pow_left hd _))) + simpa only [trialWidth,eval_add,eval_comp] using Nat.add_le_add hwalk ho + +def canonicalNumericMeasure (z : CanonicalParameters) : ℕ := z.2.1+z.2.2+weight z + +theorem rawTrialBits_polynomial : ∃ p : Polynomial ℕ,∀ z, + rawTrialBits z ≤ p.eval (canonicalNumericMeasure z) := by + obtain ⟨p,hp⟩ := polynomial_rawDrawParameters + obtain ⟨q,hq⟩ := trialWidth_polynomial + refine ⟨q.comp (X+p),?_⟩ + intro z + have hz : weight z ≤ canonicalNumericMeasure z := by unfold canonicalNumericMeasure; omega + have hw : weight (rawDrawParameters z) ≤ p.eval (canonicalNumericMeasure z) := + (Nat.le_add_left _ _).trans ((hp z).trans (polynomial_eval_monotone p hz)) + have hm : trialNumericMeasure (rawDrawParameters z) ≤ (X+p).eval (canonicalNumericMeasure z) := by + change z.2.1+z.2.2+weight (rawDrawParameters z) ≤ _ + simp only [eval_add,eval_X] + unfold canonicalNumericMeasure at hw ⊢ + omega + simpa only [rawTrialBits,eval_comp] using + (hq (rawDrawParameters z)).trans (polynomial_eval_monotone q hm) + +/-- Only the two finite boxes contribute an exponential factor; the +numeric walk, rejection and reserved-word schedules are polynomial. -/ +def rawBoxMeasure (z : CanonicalParameters) : ℕ := + (4*z.2.1^8)^tabulationDimension z+ + gridStateCount (completionEnumerationData z.1)+canonicalNumericMeasure z + +theorem rawTabulationMeasure_polynomial : ∃ p : Polynomial ℕ,∀ z, + rawTabulationMeasure z ≤ p.eval (rawBoxMeasure z) := by + obtain ⟨p,hp⟩ := rawTrialBits_polynomial + refine ⟨4*X+24*X^5+X^50*(X+1)^2+p+X^4*(X+1),?_⟩ + intro z + let M := rawBoxMeasure z + have hd : z.2.1 ≤ M := by unfold M rawBoxMeasure canonicalNumericMeasure; omega + have hh : z.2.2 ≤ M := by unfold M rawBoxMeasure canonicalNumericMeasure; omega + have hw : weight z ≤ M := by unfold M rawBoxMeasure canonicalNumericMeasure; omega + have hg : (4*z.2.1^8)^tabulationDimension z ≤ M := by unfold M rawBoxMeasure; omega + have hc : gridStateCount (completionEnumerationData z.1) ≤ M := by unfold M rawBoxMeasure; omega + have ha : 8*z.2.1^5 ≤ 8*M^5 := Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hd _) + have hb : denseStepBits z.2.1 ≤ 16*M^5 := + (denseStepBits_upper _).trans (Nat.mul_le_mul_left _ (Nat.pow_le_pow_left hd _)) + have hs : z.2.1^50*(z.2.2+1)^2 ≤ M^50*(M+1)^2 := + Nat.mul_le_mul (Nat.pow_le_pow_left hd _) (Nat.pow_le_pow_left (by omega) _) + have hr : z.2.1^4*(z.2.2+1) ≤ M^4*(M+1) := + Nat.mul_le_mul (Nat.pow_le_pow_left hd _) (by omega) + have ht : rawTrialBits z ≤ p.eval M := + (hp z).trans (polynomial_eval_monotone p (by unfold M rawBoxMeasure; omega)) + change (4*z.2.1^8)^tabulationDimension z+8*z.2.1^5+denseStepBits z.2.1+ + z.2.1^50*(z.2.2+1)^2+weight z+gridStateCount (completionEnumerationData z.1)+ + rawTrialBits z+z.2.1^4*(z.2.2+1) ≤ _ + change _ ≤ (4*X+24*X^5+X^50*(X+1)^2+p+X^4*(X+1)).eval M + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_pow,eval_one] + omega + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTransitionCounts.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTransitionCounts.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2490d29451469f1813653ad8399cda0ad1e2060 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTransitionCounts.lean @@ -0,0 +1,88 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteAcceptCounts +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanStep +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalk + +namespace OAI + +/-! # Exact integer tabulation of the implemented dense bin walk -/ + +namespace ContingencyTables.GridBoundary +open ResidualMixture FirstSuccess +open scoped BigOperators Classical + +noncomputable section +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def denseTransitionCount (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a b : Grid (I := Fin q) (4*d^8)) : ℕ := + FiniteAcceptCounts.row a (fun z : Fin (2^Nat.clog 2 (8*d)) => axisCodeStep a z) + (fun b => denseExponent R P d e b-denseExponent R P d e a) (8*d^5) b + +omit [DecidableEq I] [DecidableEq J] in +lemma denseTransitionCount_total (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4*d^8)) : + ∑ b,denseTransitionCount R P d e a b=2^denseStepBits d := by + have h:=FiniteAcceptCounts.row_total a + (fun z : Fin (2^Nat.clog 2 (8*d)) => axisCodeStep a z) + (fun b => denseExponent R P d e b-denseExponent R P d e a) (8*d^5) + simpa only [denseTransitionCount,FiniteAcceptCounts.denominator,Fintype.card_fin, + denseStepBits,pow_add] using h + +omit [DecidableEq I] [DecidableEq J] in +lemma denseTransitionCount_off_diagonal (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hq : q≤d) (e : I × J ≃ Fin q) + (a b : Grid (I := Fin q) (4*d^8)) (hba : b≠a) : + denseTransitionCount R P d e a b= + if Neighbor a b then 2^(8*d^5-(denseExponent R P d e b-denseExponent R P d e a)) + else 0 := by + simp only [denseTransitionCount,FiniteAcceptCounts.row,FiniteAcceptCounts.offCount, + ite_eq_right hba,add_zero] + rw [axisCodeStep_count (dense_proposal_code_bound d q hq)] + split_ifs <;> simp + +omit [DecidableEq I] [DecidableEq J] in +/-- The tabulated integer matrix is the actual Boolean step law, including +all unused proposal codes and all rejections. -/ +theorem denseTransitionCount_kernel (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a : Grid (I := Fin q) (4*d^8)) : + IntegerPropagation.kernel (denseTransitionCount R P d e) (2^denseStepBits d) + (by positivity) (denseTransitionCount_total R P d e) a = + denseBitStepLaw R P d e a := by + rw [denseBitStepLaw_eq_finite] + apply RationalLaw.eq_of_off_diagonal _ _ a + intro b hba + change (denseTransitionCount R P d e a b:ℚ)/((2^denseStepBits d:ℕ):ℚ)=_ + have h:=FiniteAcceptCounts.offCount_mass a b + (fun z : Fin (2^Nat.clog 2 (8*d)) => axisCodeStep a z) + (fun b => denseExponent R P d e b-denseExponent R P d e a) (8*d^5) hba + simpa only [denseTransitionCount,FiniteAcceptCounts.row,ite_eq_right hba,add_zero, + FiniteAcceptCounts.denominator,Fintype.card_fin,denseStepBits,pow_add,Nat.cast_mul, + Nat.cast_pow,Nat.cast_ofNat,finiteDenseStepLaw] using h + +omit [DecidableEq I] [DecidableEq J] in +/-- Matrix propagation tabulates the complete adaptive bin walk with +one integer per bin; the precision affects integer lengths, not the +number of bins enumerated. -/ +theorem denseWalkCount_mass (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (a b : Grid (I := Fin q) (4*d^8)) (N : ℕ) : + (IntegerPropagation.numerators (denseTransitionCount R P d e) a N b:ℚ) / + (2:ℚ)^(N*denseStepBits d) = (denseBooleanWalkLaw R P d e a N).mass b := by + have h:=IntegerPropagation.numerators_walkLaw (denseTransitionCount R P d e) + (2^denseStepBits d) (by positivity) (denseTransitionCount_total R P d e) a N b + have he : denseBooleanWalkLaw R P d e a N= + walkLaw (denseBitStepLaw R P d e) a N := by + unfold denseBooleanWalkLaw denseBooleanWalk + rw [←FairBits.map_equiv (gridWordEquiv N (denseStepBits d)),FairBits.uniform_equiv] + exact wordWalkLaw_eq _ _ _ + rw [he] + have hk : IntegerPropagation.kernel (denseTransitionCount R P d e) (2^denseStepBits d) + (by positivity) (denseTransitionCount_total R P d e)=denseBitStepLaw R P d e := + funext (denseTransitionCount_kernel R P d e) + rw [hk] at h + simpa only [Nat.cast_pow,Nat.cast_ofNat,←pow_mul,Nat.mul_comm (denseStepBits d) N] using h + +end +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrial.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrial.lean new file mode 100644 index 0000000000000000000000000000000000000000..80e9d97b7e0e6c108ea716d073d20a9c582a6e57 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrial.lean @@ -0,0 +1,87 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseOffsets + +namespace OAI + +/-! # Accepted dense trials are in bijection with the actual tables -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] +variable {q : ℕ} + +abbrev DenseTrial (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) (q : ℕ) := + Grid (I := Fin q) (4 * d ^ 8) × Offset (integerWidth R P d) + +def trialFree (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) (e : I × J ≃ Fin q) + (t : DenseTrial R P d q) : I × J → ℕ := + fun p => (trialBoxEquiv e (integerWidth R P d) (4 * d ^ 8) t p).val + +def TrialAccepted (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) (e : I × J ≃ Fin q) + (t : DenseTrial R P d q) : Prop := ∀ i j, 0 ≤ DenseAffine.integerTable R P (trialFree R P d e t) i j + +def trialTable (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) (e : I × J ≃ Fin q) + (htotal : ∑ i, R i = ∑ j, P j) (t : DenseTrial R P d q) (ht : TrialAccepted R P d e t) : + Table R P := ⟨DenseAffine.naturalTable R P (trialFree R P d e t), + DenseAffine.naturalTable_rows R P _ ht, DenseAffine.naturalTable_columns R P _ ht htotal⟩ + +def tableTrial (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (X : Table R P) : DenseTrial R P d q := + (trialBoxEquiv e (integerWidth R P d) (4 * d ^ 8)).symm (tableFreeBox R P d hd hR hP X) + +theorem trialFree_tableTrial (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (X : Table R P) (p : I × J) : + trialFree R P d e (tableTrial R P d hd hR hP e X) p = X.val (some p.1) (some p.2) := by + exact congrArg Fin.val (congrFun + ((trialBoxEquiv e (integerWidth R P d) (4 * d ^ 8)).apply_symm_apply + (tableFreeBox R P d hd hR hP X)) p) + +theorem tableTrial_accepted (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (X : Table R P) : + TrialAccepted R P d e (tableTrial R P d hd hR hP e X) := by + have hf : trialFree R P d e (tableTrial R P d hd hR hP e X) = + (fun p => X.val (some p.1) (some p.2)) := funext (trialFree_tableTrial R P d hd hR hP e X) + intro i j + rw [hf, DenseAffine.integerTable_recover R P X.val X.property.1 X.property.2] + exact Int.natCast_nonneg _ + +theorem trialTable_tableTrial (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (htotal : ∑ i, R i = ∑ j, P j) (X : Table R P) : + trialTable R P d e htotal (tableTrial R P d hd hR hP e X) + (tableTrial_accepted R P d hd hR hP e X) = X := by + apply Subtype.ext + exact DenseAffine.naturalTable_unique R P _ (tableTrial_accepted R P d hd hR hP e X) + X.val X.property.1 X.property.2 (fun i j => (trialFree_tableTrial R P d hd hR hP e X (i, j)).symm) + +theorem tableTrial_trialTable (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (htotal : ∑ i, R i = ∑ j, P j) + (t : DenseTrial R P d q) (ht : TrialAccepted R P d e t) : + tableTrial R P d hd hR hP e (trialTable R P d e htotal t ht) = t := by + apply (trialBoxEquiv e (integerWidth R P d) (4 * d ^ 8)).injective + rw [tableTrial, Equiv.apply_symm_apply] + funext p + apply Fin.ext + exact DenseAffine.naturalTable_free R P (trialFree R P d e t) p.1 p.2 + +def acceptedTrialEquiv (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (htotal : ∑ i, R i = ∑ j, P j) : + {t : DenseTrial R P d q // TrialAccepted R P d e t} ≃ Table R P where + toFun t := trialTable R P d e htotal t.val t.property + invFun X := ⟨tableTrial R P d hd hR hP e X, tableTrial_accepted R P d hd hR hP e X⟩ + left_inv t := Subtype.ext (tableTrial_trialTable R P d hd hR hP e htotal t.val t.property) + right_inv X := trialTable_tableTrial R P d hd hR hP e htotal X + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialAcceptance.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialAcceptance.lean new file mode 100644 index 0000000000000000000000000000000000000000..5381ef7528c75a7d0311fb40c7fcd4a64c51f56e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialAcceptance.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialWeights + +namespace OAI + +/-! # Acceptance probability of the actual ideal dense trial -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] +variable {q : ℕ} + +def denseAcceptanceMass (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) : ℝ := + ∑ t : DenseTrial R P d q, if TrialAccepted R P d e t then denseTrialMass R P d e t else 0 + +omit [DecidableEq I] [DecidableEq J] in +theorem goodBin_trialAccepted (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (t : DenseTrial R P d q) (ht : goodBin R P d e t.1) : + TrialAccepted R P d e t := + (trialReal_feasible_iff R P d hd hR hP e t).mp + (ht (trialReal R P d e t) (trialReal_closed R P d hd hR hP e t)) + +theorem denseAcceptanceMass_le_one (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) : denseAcceptanceMass R P d e ≤ 1 := by + rw [← denseTrialMass_sum R P d hd hR hP e] + apply Finset.sum_le_sum + intro t _ + split_ifs + · exact le_rfl + · exact (denseTrialMass_pos R P d hd hR hP e t).le + +/-- Wholly feasible bins accept every integral offset, so their proved +stationary mass is a lower bound on the actual trial acceptance mass. -/ +theorem denseAcceptanceMass_lower (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hdimR : Fintype.card (Option I) ≤ d) (hdimP : Fintype.card (Option J) ≤ d) + (hfree : Fintype.card (I × J) ≤ d) (htotal : ∑ i, R i = ∑ j, P j) + (e : I × J ≃ Fin q) : (1 / 32 : ℝ) ≤ denseAcceptanceMass R P d e := by + let : Nonempty (Offset (integerWidth R P d)) := + ⟨fun p => ⟨0, integerWidth_pos R P d hd hR hP p⟩⟩ + have hO : (Fintype.card (Offset (integerWidth R P d)) : ℝ) ≠ 0 := by + exact_mod_cast ne_of_gt (Fintype.card_pos (α := Offset (integerWidth R P d))) + have hgood := dense_good_bin_probability R P d hd hR hP hRmax hPmax + hdimR hdimP hfree htotal e + have hle : + (∑ t : DenseTrial R P d q, + if goodBin R P d e t.1 then denseTrialMass R P d e t else 0) ≤ + denseAcceptanceMass R P d e := by + apply Finset.sum_le_sum + intro t _ + by_cases hg : goodBin R P d e t.1 + · rw [ite_eq_left hg, ite_eq_left (goodBin_trialAccepted R P d hd hR hP e t hg)] + · rw [ite_eq_right hg] + split_ifs + · exact (denseTrialMass_pos R P d hd hR hP e t).le + · exact le_rfl + apply hgood.trans + convert hle using 1 + rw [Fintype.sum_prod_type] + change _ = ∑ a : Grid (I := Fin q) (4 * d ^ 8), + ∑ _o : Offset (integerWidth R P d), if goodBin R P d e a then + (denseBinWeight R P d e a / + (∑ b : Grid (I := Fin q) (4 * d ^ 8), denseBinWeight R P d e b)) / + (Fintype.card (Offset (integerWidth R P d)) : ℝ) else 0 + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul, mul_ite, mul_zero] + simp_rw [mul_div_cancel₀ _ hO] + rw [goodBins, Finset.sum_filter, Finset.sum_div] + apply Finset.sum_congr rfl + intro a _ + split_ifs <;> simp + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialCountProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialCountProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b383c913a2c9f597e04cdd03e61360aac79e21be --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialCountProgram.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PreparedOffsetCount +import OAI.Combinatorics.ContingencyTables.Dense.GridIndexProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseTableCoordinates +import OAI.Combinatorics.ContingencyTables.Dense.DenseWalkTabulation + +namespace OAI + +/-! # Computing one accepted-table numerator from the cached bin vector -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary +open scoped BigOperators Classical + +/-- Cached walk vector, shared bit allowance, and the table/margin data +with the requested precision. -/ +abbrev TrialCountData := (List ℕ×List Bool)×OffsetWidthData + +def trialCountIndexInput (z : TrialCountData) : GridIndexData := + (tableBinCoordinates z.2.1,4*z.2.1.2^8) + +def trialCountIndexInputRealizer : Realizer trialCountIndexInput := by + let data : Realizer (fun z : TrialCountData => z.2.1) := composition second first + let d := composition data second + let K := composition (pair (constant 4) (composition d eighthPower)) multiply + exact pair (composition data tableBinCoordinatesRealizer) K + +lemma polynomial_trialCountIndexInput : PolynomialTime trialCountIndexInputRealizer := by + have hd : PolynomialTime (composition + (second (A := List ℕ×List Bool) (B := OffsetWidthData)) first) := + polynomial_composition polynomial_second polynomial_first + have hK := polynomial_composition (polynomial_pair (polynomial_constant 4) + (polynomial_composition (polynomial_composition hd polynomial_second) + polynomial_eighthPower)) polynomial_multiply + unfold trialCountIndexInputRealizer + exact polynomial_pair (polynomial_composition hd polynomial_tableBinCoordinates) hK + +def trialCountOffsetInput (z : TrialCountData) : PreparedOffsetData := + (((z.1.2,tableWidths z.2.1),offsetLengths z.2),tableOffsetCoordinates z.2.1) + +def trialCountOffsetInputRealizer : Realizer trialCountOffsetInput := by + let data : Realizer (fun z : TrialCountData => z.2.1) := composition second first + exact pair (pair (pair (composition first second) (composition data tableWidthsRealizer)) + (composition second offsetLengthsRealizer)) (composition data tableOffsetCoordinatesRealizer) + +lemma polynomial_trialCountOffsetInput : PolynomialTime trialCountOffsetInputRealizer := by + have hd : PolynomialTime (composition + (second (A := List ℕ×List Bool) (B := OffsetWidthData)) first) := + polynomial_composition polynomial_second polynomial_first + unfold trialCountOffsetInputRealizer + exact polynomial_pair (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition hd polynomial_tableWidths)) + (polynomial_composition polynomial_second polynomial_offsetLengths)) + (polynomial_composition hd polynomial_tableOffsetCoordinates) + +def trialTableCount (z : TrialCountData) : ℕ := + z.1.1.getD (gridIndex (trialCountIndexInput z)) 0* + preparedOffsetProduct (trialCountOffsetInput z) + +def trialTableCountRealizer : Realizer trialTableCount := by + let idx := composition trialCountIndexInputRealizer gridIndexRealizer + let bin := composition (pair (composition first first) idx) (getDFast 0) + let offs := composition trialCountOffsetInputRealizer preparedOffsetProductRealizer + let result := composition (pair bin offs) multiply + exact result + +/-- Once the bin vector is cached, one accepted-table numerator uses +polynomial binary arithmetic and one lookup. -/ +theorem polynomial_trialTableCount : PolynomialTime trialTableCountRealizer := by + unfold trialTableCountRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_trialCountIndexInput polynomial_gridIndex)) + (polynomial_getDFast 0)) + (polynomial_composition polynomial_trialCountOffsetInput polynomial_preparedOffsetProduct)) + polynomial_multiply + +/-- The program computes the count of the unique accepted trial for this +table, using canonical walk tabulation. -/ +theorem trialTableCount_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (h : ℕ) + (cap : List Bool) + (hcap : ∀ j : Fin (m*n), + FairBits.offsetBitLength (integerWidth R P d (finProdFinEquiv.symm j)) h d≤cap.length) + (X : Table R P) : + trialTableCount ((tabulateDenseWalk ((marginCode R,marginCode P),(d,h)),cap), + (tableCoordinatesCode R P d X,h))= + (denseTrialCounts R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega))).count + (tableTrial R P d hd hR hP finProdFinEquiv X) := by + unfold trialTableCount trialCountIndexInput trialCountOffsetInput + change (tabulateDenseWalk ((marginCode R,marginCode P),(d,h))).getD + (gridIndex (tableBinCoordinates (tableCoordinatesCode R P d X),4*d^8)) 0* + preparedOffsetProduct (((cap,tableWidths (tableCoordinatesCode R P d X)), + offsetLengths (tableCoordinatesCode R P d X,h)), + tableOffsetCoordinates (tableCoordinatesCode R P d X))=_ + rw [tableBinCoordinates_code R P hd hR hP X,gridIndex_code, + tableWidths_code,tableOffsetLengths_code,tableOffsetCoordinates_code R P hd hR hP X, + preparedOffsetProduct_ofFn cap _ _ _ hcap, + tabulateDenseWalk_actual R P hq (by omega) h] + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,Fin.isLt, + dite_true,Option.getD_some,Fin.eta,Equiv.apply_symm_apply] + exact denseTrial_table_count R P d hd hR hP finProdFinEquiv h + (canonicalOrigin (m*n) d (by omega)) X |>.symm + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7550f750b0bebd15f53627e6d3ed2cb9befc18f9 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialProgram.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalkProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetWidths +import OAI.Combinatorics.ContingencyTables.Dense.DenseCompletedMatrixProgram + +namespace OAI + +/-! # The complete dense trial as a polynomial binary program -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped ProfilePrograms + +abbrev DenseTrialData := (FlatExponentData×ℕ)×List Bool + +def fiftiethPower : Realizer (fun n : ℕ => n^50) := + (composition (composition fifthPower squareNat) fifthPower).congr (by + intro n + simp only [Function.comp_apply] + ring) + +theorem polynomial_fiftiethPower : PolynomialTime fiftiethPower := + polynomial_congr _ (polynomial_composition + (polynomial_composition polynomial_fifthPower polynomial_squareNat) polynomial_fifthPower) + +def trialWalkBits (z : DenseTrialData) : ℕ := + (z.1.1.2^50*(z.1.2+1)^2)*GridBoundary.denseStepBits z.1.1.2 + +def trialWalkBitsRealizer : Realizer trialWalkBits := by + let D : Realizer (fun z : DenseTrialData => z.1.1.2) := + composition (composition first first) second + let H : Realizer (fun z : DenseTrialData => z.1.2) := composition first second + let time := composition (pair (composition D fiftiethPower) + (composition (composition H successor) squareNat)) multiply + exact (composition (pair time (composition D denseWidthRealizer)) multiply).congr (by + intro z + simp only [Function.comp_apply,trialWalkBits,pow_two,Nat.succ_eq_add_one]) + +theorem polynomial_trialWalkBits : PolynomialTime trialWalkBitsRealizer := by + have hd : PolynomialTime (composition + (composition (first (A := FlatExponentData×ℕ) (B := List Bool)) first) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + unfold trialWalkBitsRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_composition hd polynomial_fiftiethPower) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_second) polynomial_successor) + polynomial_squareNat)) polynomial_multiply) + (polynomial_composition hd polynomial_denseWidth)) polynomial_multiply + +def trialGrid (z : DenseTrialData) : ExponentData := + flatToGridData (flatWordWalk (z.1.1,z.2.take (trialWalkBits z))) + +def trialGridRealizer : Realizer trialGrid := by + let data : Realizer (fun z : DenseTrialData => z.1.1) := composition first first + let bits := composition (pair (second (A := FlatExponentData×ℕ) (B := List Bool)) + trialWalkBitsRealizer) takeFast + let source := pair data bits + let walk := composition source flatWordWalkRealizer + let result := composition walk flatToGridDataRealizer + exact result + +theorem polynomial_trialGrid : PolynomialTime trialGridRealizer := by + unfold trialGridRealizer + exact polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_pair polynomial_second polynomial_trialWalkBits) polynomial_takeFast)) + polynomial_flatWordWalk) polynomial_flatToGridData + +def trialOffsets (z : DenseTrialData) : List (List Bool) := + dependentChunks (offsetLengths (trialGrid z,z.1.2),z.2.drop (trialWalkBits z)) + +def trialOffsetsRealizer : Realizer trialOffsets := + composition (pair + (composition (pair trialGridRealizer (composition first second)) offsetLengthsRealizer) + (composition (pair second trialWalkBitsRealizer) dropFast)) dependentChunksRealizer + +theorem polynomial_trialOffsets : PolynomialTime trialOffsetsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_trialGrid + (polynomial_composition polynomial_first polynomial_second)) polynomial_offsetLengths) + (polynomial_composition (polynomial_pair polynomial_second polynomial_trialWalkBits) polynomial_dropFast)) + polynomial_dependentChunks + +def trialCompletion (z : DenseTrialData) : CompletionData := + ((trialGrid z).1.1,offsetMatrix (trialGrid z,trialOffsets z)) + +def trialCompletionRealizer : Realizer trialCompletion := + pair (composition (composition trialGridRealizer first) first) + (composition (pair trialGridRealizer trialOffsetsRealizer) offsetMatrixRealizer) + +theorem polynomial_trialCompletion : PolynomialTime trialCompletionRealizer := + polynomial_pair (polynomial_composition (polynomial_composition polynomial_trialGrid polynomial_first) polynomial_first) + (polynomial_composition (polynomial_pair polynomial_trialGrid polynomial_trialOffsets) polynomial_offsetMatrix) + +def acceptCompletion (z : CompletionData) : Option MatrixCode := + if completionValid z then some (completedMatrix z) else none + +def acceptCompletionRealizer : Realizer acceptCompletion := + choose completionValidRealizer (composition completedMatrixRealizer MatchingFPRAS.TreeTyped.some) (constant none) + +theorem polynomial_acceptCompletion : PolynomialTime acceptCompletionRealizer := + polynomial_choose polynomial_completionValid + (polynomial_composition polynomial_completedMatrix polynomial_some) (polynomial_constant none) + +def denseTrialCode (z : DenseTrialData) : Option MatrixCode := acceptCompletion (trialCompletion z) + +def denseTrialCodeRealizer : Realizer denseTrialCode := + composition trialCompletionRealizer acceptCompletionRealizer + +/-- Includes the full walk, every quotient offset, signed-entry checking, +and binary output construction. Runtime is polynomial for every input. -/ +theorem polynomial_denseTrialCode : PolynomialTime denseTrialCodeRealizer := + polynomial_composition polynomial_trialCompletion polynomial_acceptCompletion + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..61dee708c0f4dfb29ff4d1fac2e5be93f671b47e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialSemantics.lean @@ -0,0 +1,118 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrialProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanTrial +import OAI.Combinatorics.ContingencyTables.Dense.DenseBoundedRejection + +namespace OAI + +/-! # The complete trial program uses the manuscript's finite-bit experiment -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary FairBits +open scoped BigOperators Classical + +noncomputable section + +def trialInput {m n d : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (h : ℕ) (a : Grid (I := Fin (m*n)) (4*d^8)) (bits : List Bool) : DenseTrialData := + (((((marginCode R,marginCode P),gridNatCode a),d),h),bits) + +lemma flatToGridData_code {m n K : ℕ} (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (d : ℕ) (a : Grid (I := Fin (m*n)) K) : + flatToGridData (((marginCode R,marginCode P),gridNatCode a),d)= + exponentDataCode R P d (fun i j => (corner a (finProdFinEquiv (i,j))).toNat) := by + unfold flatToGridData gridNatCode + rw [unflattenGrid_code] + rfl + +lemma trialGrid_code {m n d : ℕ} (hd : 0 < d) + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) (h : ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) + (bits : Fin (denseTrialBits R P d finProdFinEquiv h) → Bool) : + trialGrid (trialInput R P h a (List.ofFn bits))= + exponentDataCode R P d (fun i j => + (corner (denseBooleanWalk R P d finProdFinEquiv a (d^50*(h+1)^2) + (trialWordEquiv R P d finProdFinEquiv h bits).1) (finProdFinEquiv (i,j))).toNat) := by + dsimp only [trialGrid,trialInput,trialWalkBits] + have ht := ofFn_split_take (p := (d^50*(h+1)^2)*denseStepBits d) + (k := ∑ j : Fin (m*n),offsetBitLength (integerWidth R P d (finProdFinEquiv.symm j)) h d) bits + have he := congrArg (fun w => flatToGridData + (flatWordWalk ((((marginCode R,marginCode P),gridNatCode a),d),w))) ht + refine he.trans ?_ + rw [flatWordWalk_code hd] + exact flatToGridData_code R P d _ + +lemma trialOffsets_code {m n d : ℕ} (hd : 0 < d) + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) (h : ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) + (bits : Fin (denseTrialBits R P d finProdFinEquiv h) → Bool) : + trialOffsets (trialInput R P h a (List.ofFn bits))= + List.ofFn (fun j => List.ofFn ((trialWordEquiv R P d finProdFinEquiv h bits).2 j)) := by + unfold trialOffsets + rw [trialGrid_code hd,offsetLengths_code] + dsimp only [trialInput,trialWalkBits] + have ht := ofFn_split_drop (p := (d^50*(h+1)^2)*denseStepBits d) + (k := ∑ j : Fin (m*n),offsetBitLength (integerWidth R P d (finProdFinEquiv.symm j)) h d) bits + have he := congrArg (fun w => dependentChunks + (List.ofFn (fun j : Fin (m*n) => offsetBitLength + (integerWidth R P d (finProdFinEquiv.symm j)) h d),w)) ht + refine he.trans ?_ + rw [dependentChunks_ofFn] + rfl + +theorem trialCompletion_code {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14 ≤ d) (hR : ∀ i,d^12 ≤ R i) (hP : ∀ j,d^12 ≤ P j) (h : ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) + (bits : Fin (denseTrialBits R P d finProdFinEquiv h) → Bool) : + trialCompletion (trialInput R P h a (List.ofFn bits))= + ((marginCode R,marginCode P),matrixCode (fun i j => trialFree R P d finProdFinEquiv + (denseBooleanTrial R P d hd hR hP finProdFinEquiv h a bits) (i,j))) := by + have hd0 : 0 < d := by omega + unfold trialCompletion + rw [trialGrid_code hd0,trialOffsets_code hd0] + apply Prod.ext + · rfl + · exact offsetMatrix_trialFree R P (integerWidth_pos R P d hd hR hP) h _ _ + +def tableOutput {m n : ℕ} {R : Option (Fin m) → ℕ} {P : Option (Fin n) → ℕ} + (X : Table R P) : MatrixCode := + matrixCode (fun i : Fin (m+1) => fun j : Fin (n+1) => + X.val (finSuccEquiv m i) (finSuccEquiv n j)) + +lemma acceptCompletion_trialFree {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (htotal : ∑ i,R i=∑ j,P j) (t : DenseTrial R P d (m*n)) : + acceptCompletion ((marginCode R,marginCode P), + matrixCode (fun i j => trialFree R P d finProdFinEquiv t (i,j)))= + (trialSuccess R P d finProdFinEquiv htotal t).map tableOutput := by + have hv := completionValid_code R P (fun i j => trialFree R P d finProdFinEquiv t (i,j)) + by_cases ht : TrialAccepted R P d finProdFinEquiv t + · have hc := hv.mpr ht + simp only [acceptCompletion,hc,ite_true,trialSuccess,dite_eq_left ht,Option.map_some] + rw [completedMatrix_code] + rfl + · have hc : completionValid ((marginCode R,marginCode P), + matrixCode (fun i j => trialFree R P d finProdFinEquiv t (i,j)))≠true := by + intro h + exact ht (hv.mp h) + simp only [acceptCompletion,hc,Bool.false_eq_true,ite_false,trialSuccess,dite_eq_right ht,Option.map_none] + +/-- The physical binary program returns exactly the successful table of the +declared finite Boolean experiment, with the same rejection event. -/ +theorem denseTrialCode_eq {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (hd : 14 ≤ d) (hR : ∀ i,d^12 ≤ R i) (hP : ∀ j,d^12 ≤ P j) + (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) + (bits : Fin (denseTrialBits R P d finProdFinEquiv h) → Bool) : + denseTrialCode (trialInput R P h a (List.ofFn bits))= + (trialSuccess R P d finProdFinEquiv htotal + (denseBooleanTrial R P d hd hR hP finProdFinEquiv h a bits)).map tableOutput := by + unfold denseTrialCode + rw [trialCompletion_code R P hd hR hP] + exact acceptCompletion_trialFree R P htotal _ + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialWeights.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialWeights.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fbf503e5f2be3868a100f927053bf6171519ea6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseTrialWeights.lean @@ -0,0 +1,138 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseTrial + +namespace OAI + +/-! # Equal weight of all accepted dense trials + +The bin is sampled with its stationary weight, and the integral offset +uniformly. The unique trial producing any given table lies in a bin of +weight one. Conditioning this finite law on acceptance is therefore +exactly uniform on the actual tables. +-/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical + +noncomputable section + +variable {I J : Type*} [Fintype I] [Fintype J] +variable {q : ℕ} + +def trialReal (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (t : DenseTrial R P d q) : Fin q → ℝ := + fun j => (trialFree R P d e t (e.symm j) : ℝ) / (integerWidth R P d (e.symm j) : ℝ) + +omit [Fintype I] [Fintype J] in +theorem trialReal_closed (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (t : DenseTrial R P d q) : + ClosedBin (corner t.1) (trialReal R P d e t) := by + intro j + have hw : (0 : ℝ) < integerWidth R P d (e.symm j) := by + exact_mod_cast integerWidth_pos R P d hd hR hP (e.symm j) + have ho : (0 : ℝ) ≤ (t.2 (e.symm j)).val := Nat.cast_nonneg _ + have ho' : ((t.2 (e.symm j)).val : ℝ) < integerWidth R P d (e.symm j) := by + exact_mod_cast (t.2 (e.symm j)).isLt + have hc : (((corner t.1 j).toNat : ℕ) : ℝ) = (corner t.1 j : ℝ) := by + exact_mod_cast Int.toNat_of_nonneg (t.1 j).property.1 + have hz : (trialFree R P d e t (e.symm j) : ℝ) = + (t.2 (e.symm j)).val + (integerWidth R P d (e.symm j) : ℝ) * (corner t.1 j : ℝ) := by + change ((trialBoxEquiv e (integerWidth R P d) (4 * d ^ 8) (t.1, t.2) (e.symm j)).val : ℝ) = _ + rw [trialBoxEquiv_val, Equiv.apply_symm_apply, Nat.cast_add, Nat.cast_mul, hc] + change (corner t.1 j : ℝ) ≤ _ / _ ∧ _ / _ ≤ (corner t.1 j : ℝ) + 1 + constructor + · apply (le_div_iff₀ hw).mpr + rw [hz] + nlinarith + · apply (div_le_iff₀ hw).mpr + rw [hz] + nlinarith + +theorem trialReal_feasible_iff (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (t : DenseTrial R P d q) : + denseGridFeasible R P d e (trialReal R P d e t) ↔ TrialAccepted R P d e t := by + have h := DenseAffine.integer_acceptance_iff R P + (fun i j => integerWidth R P d (i, j)) + (fun i j => integerWidth_pos R P d hd hR hP (i, j)) (trialFree R P d e t) + change (∀ i j, 0 ≤ DenseAffine.table (fun i => (R i : ℝ)) (fun j => (P j : ℝ)) + (fun i j => (integerWidth R P d (i, j) : ℝ)) + (fun p => trialReal R P d e t (e p)) i j) ↔ _ + simpa only [trialReal, Equiv.symm_apply_apply, TrialAccepted] using h + +variable [DecidableEq I] [DecidableEq J] + +theorem acceptedTrial_binWeight_one (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (t : DenseTrial R P d q) (ht : TrialAccepted R P d e t) : + denseBinWeight R P d e t.1 = 1 := + denseBinWeight_eq_one R P d hd hR hP hRmax hPmax hfree e t.1 + (trialReal R P d e t) (trialReal_closed R P d hd hR hP e t) + ((trialReal_feasible_iff R P d hd hR hP e t).mpr ht) + +def denseTrialMass (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (e : I × J ≃ Fin q) (t : DenseTrial R P d q) : ℝ := + denseBinWeight R P d e t.1 / + (∑ a : Grid (I := Fin q) (4 * d ^ 8), denseBinWeight R P d e a) / + Fintype.card (Offset (integerWidth R P d)) + +theorem denseTrialMass_pos (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) (t : DenseTrial R P d q) : + 0 < denseTrialMass R P d e t := by + let : Nonempty (Grid (I := Fin q) (4 * d ^ 8)) := ⟨t.1⟩ + let : Nonempty (Offset (integerWidth R P d)) := + ⟨fun p => ⟨0, integerWidth_pos R P d hd hR hP p⟩⟩ + have hZ : 0 < ∑ a : Grid (I := Fin q) (4 * d ^ 8), denseBinWeight R P d e a := + Finset.sum_pos (fun _ _ => DenseWeights.binWeight_pos _ _ _) Finset.univ_nonempty + have hO : (0 : ℝ) < Fintype.card (Offset (integerWidth R P d)) := by + exact_mod_cast Fintype.card_pos (α := Offset (integerWidth R P d)) + exact div_pos (div_pos (DenseWeights.binWeight_pos _ _ _) hZ) hO + +theorem denseTrialMass_sum (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (e : I × J ≃ Fin q) : + ∑ t : DenseTrial R P d q, denseTrialMass R P d e t = 1 := by + let : Nonempty (Grid (I := Fin q) (4 * d ^ 8)) := + ⟨fun _ => ⟨0, by have h := denseGridSize_pos d hd; constructor <;> omega⟩⟩ + let : Nonempty (Offset (integerWidth R P d)) := + ⟨fun p => ⟨0, integerWidth_pos R P d hd hR hP p⟩⟩ + have hZ : (∑ a : Grid (I := Fin q) (4 * d ^ 8), denseBinWeight R P d e a) ≠ 0 := + ne_of_gt (Finset.sum_pos (fun _ _ => DenseWeights.binWeight_pos _ _ _) Finset.univ_nonempty) + have hO : (Fintype.card (Offset (integerWidth R P d)) : ℝ) ≠ 0 := by + exact_mod_cast ne_of_gt (Fintype.card_pos (α := Offset (integerWidth R P d))) + rw [Fintype.sum_prod_type] + simp only [denseTrialMass, Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + simp_rw [mul_div_cancel₀ _ hO] + rw [← Finset.sum_div, div_self hZ] + +/-- Conditioning the actual stationary-bin/uniform-offset trial law on +acceptance assigns each table exactly the reciprocal of the table count. -/ +theorem denseTrial_conditional_uniform (R : Option I → ℕ) (P : Option J → ℕ) (d : ℕ) + (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) (X : Table R P) : + denseTrialMass R P d e (tableTrial R P d hd hR hP e X) / + (∑ Y : Table R P, denseTrialMass R P d e (tableTrial R P d hd hR hP e Y)) = + 1 / Fintype.card (Table R P) := by + have heq (Y : Table R P) : denseTrialMass R P d e (tableTrial R P d hd hR hP e Y) = + 1 / (∑ a : Grid (I := Fin q) (4 * d ^ 8), denseBinWeight R P d e a) / + Fintype.card (Offset (integerWidth R P d)) := by + unfold denseTrialMass + rw [acceptedTrial_binWeight_one R P d hd hR hP hRmax hPmax hfree e _ + (tableTrial_accepted R P d hd hR hP e Y)] + have ha := denseTrialMass_pos R P d hd hR hP e (tableTrial R P d hd hR hP e X) + rw [heq X] at ha + simp_rw [heq] + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + rw [mul_comm (Fintype.card (Table R P) : ℝ)] + simpa only [one_div] using div_mul_cancel_left₀ (ne_of_gt ha) (Fintype.card (Table R P) : ℝ) + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..31fe485223bb0fcabb156d9eca7611cb05e608eb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkProgram.lean @@ -0,0 +1,102 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseStepGrowth + +namespace OAI + +/-! # A polynomial loop of binary dense transition words -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped Polynomial + +def advance (z : List Bool×FlatExponentData) : FlatExponentData := + replaceFlat (z.2,flatWordStep (z.2,z.1)) + +def advanceRealizer : Realizer advance := by + let swap : Realizer (fun z : List Bool×FlatExponentData => (z.2,z.1)) := pair second first + let next := composition swap flatWordStepRealizer + exact composition (pair second next) replaceFlatRealizer + +theorem polynomial_advance : PolynomialTime advanceRealizer := by + unfold advanceRealizer + exact polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_flatWordStep)) + polynomial_replaceFlat + +lemma advance_parameters (data : FlatExponentData) (bits : List Bool) : + (advance (bits,data)).1.1=data.1.1 ∧ (advance (bits,data)).2=data.2 := ⟨rfl,rfl⟩ + +lemma advance_growth (data : FlatExponentData) (bits : List Bool) (S : ℕ) + (h : ∀ a∈data.1.2,a.size≤S) : + (advance (bits,data)).1.2.length=data.1.2.length ∧ + ∀ a∈(advance (bits,data)).1.2,a.size≤S+2 := flatWordStep_growth _ S h + +def walkWords (z : FlatExponentData×List (List Bool)) : FlatExponentData := + z.2.foldl (fun data bits => advance (bits,data)) z.1 + +def walkWordsRealizer : Realizer walkWords := + composition (pair second first) (fold advanceRealizer) + +lemma fold_advance_parameters (bits : List (List Bool)) (data : FlatExponentData) : + let out := bits.foldl (fun data bits => advance (bits,data)) data + out.1.1=data.1.1 ∧ out.2=data.2 ∧ out.1.2.length=data.1.2.length := by + induction bits generalizing data with + | nil => exact ⟨rfl,rfl,rfl⟩ + | cons b bs ih => + have h := ih (advance (b,data)) + have hl : (advance (b,data)).1.2.length=data.1.2.length := by + have hx := advance_growth data b (data.1.2.map Nat.size).sum + (fun a ha => List.single_le_sum (fun _ _ => Nat.zero_le _) a.size + (List.mem_map.mpr ⟨a,ha,rfl⟩)) + exact hx.1 + exact ⟨h.1,h.2.1,h.2.2.trans hl⟩ + +lemma fold_advance_sizes (bits : List (List Bool)) (data : FlatExponentData) (S : ℕ) + (h : ∀ a∈data.1.2,a.size≤S) : + ∀ a∈(bits.foldl (fun data bits => advance (bits,data)) data).1.2, + a.size≤S+2*bits.length := by + induction bits generalizing data S with + | nil => simpa using h + | cons b bs ih => + have hg := advance_growth data b S h + have ht := ih (advance (b,data)) (S+2) hg.2 + intro a ha + have h := ht a ha + simpa only [List.length_cons,List.foldl_cons] using + h.trans_eq (by omega : S+2+2*bs.length=S+2*(bs.length+1)) + +theorem polynomial_walkWords : PolynomialTime walkWordsRealizer := by + apply polynomial_composition (polynomial_pair polynomial_second polynomial_first) + apply polynomial_fold polynomial_advance (20*(X+1)^2) + intro bits data pre post he + let S := weight (bits,data) + let out := pre.foldl (fun data bits => advance (bits,data)) data + have hd : weight data≤S := weight_snd (bits,data) + have hp : pre.length≤S := (list_length_le_weight pre).trans + ((weight_prefix he).trans (weight_fst (bits,data))) + have hxs : weight data.1.2≤S := (weight_snd data.1).trans ((weight_fst data).trans hd) + have hn : data.1.2.length≤S := (list_length_le_weight _).trans hxs + have hi : ∀ a∈data.1.2,a.size≤S := fun a ha => + (size_le_weight a).trans ((weight_mem ha).trans hxs) + have hs := fold_advance_sizes pre data S hi + have ht := fold_advance_parameters pre data + have hw : weight out.1.2≤out.1.2.length*(4*(S+2*pre.length)+2)+1 := by + have h := weight_map_bound (f := id) (as := out.1.2) (N := 4*(S+2*pre.length)+1) + (fun a ha => (weight_nat_le a).trans (by have h := hs a ha; omega)) + simpa only [List.map_id_fun,id_eq,Nat.add_assoc] using h + have hm : weight out.1.1≤S := by + rw [ht.1] + exact (weight_fst data.1).trans ((weight_fst data).trans hd) + have hd' : weight out.2≤S := by + rw [ht.2.1] + exact (weight_snd data).trans hd + have hl : out.1.2.length≤S := ht.2.2.trans_le hn + have hmul : out.1.2.length*(4*(S+2*pre.length)+2)≤S*(12*S+2) := + Nat.mul_le_mul hl (by omega) + simp only [eval_mul,eval_ofNat,eval_pow,eval_add,eval_X,eval_one] + change weight out≤20*(S+1)^2 + have heq : weight out=1+(1+weight out.1.1+weight out.1.2)+weight out.2 := by + rw [weight_prod,weight_prod] + nlinarith + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6e4d1bc4d59d4f3e76663dd919b6401f8c38ae4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkSemantics.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseWalkProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseMetropolisSemantics +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalk + +namespace OAI + +/-! # Pointwise agreement of the binary dense loop and the finite walk -/ + +namespace ContingencyTables.DensePrograms +open GridBoundary FirstSuccess +open scoped Classical + +noncomputable section + +lemma advance_code {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) (bits : Fin (denseStepBits d) → Bool) : + advance (List.ofFn bits,(((marginCode R,marginCode P),gridNatCode a),d))= + (((marginCode R,marginCode P), + gridNatCode (denseBitStep R P d finProdFinEquiv a bits)),d) := by + unfold advance replaceFlat + rw [flatWordStep_code] + +theorem walkWords_ofFn {m n d : ℕ} + (R : Option (Fin m) → ℕ) (P : Option (Fin n) → ℕ) + (a : Grid (I := Fin (m*n)) (4*d^8)) (steps : ℕ) + (bits : Fin steps → Fin (denseStepBits d) → Bool) : + walkWords ((((marginCode R,marginCode P),gridNatCode a),d), + List.ofFn (fun i => List.ofFn (bits i)))= + (((marginCode R,marginCode P), + gridNatCode (wordWalk (denseBitStep R P d finProdFinEquiv) a steps bits)),d) := by + induction steps with + | zero => rfl + | succ steps ih => + unfold walkWords at ih ⊢ + rw [List.ofFn_succ',List.concat_eq_append,List.foldl_append] + change advance (List.ofFn (bits (Fin.last steps)), + (List.ofFn (fun i => List.ofFn ((Fin.init bits) i))).foldl + (fun data bits => advance (bits,data)) (((marginCode R,marginCode P),gridNatCode a),d)) = _ + rw [ih (Fin.init bits)] + exact advance_code R P _ _ + +end +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkTabulation.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkTabulation.lean new file mode 100644 index 0000000000000000000000000000000000000000..66ebd36aa562725c1f55280b1a08e5ba57b8f072 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWalkTabulation.lean @@ -0,0 +1,212 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseEnumeratedMatrix +import OAI.Combinatorics.ContingencyTables.Transport.UnaryMarkers +import OAI.Combinatorics.ContingencyTables.Dense.DenseCanonicalSemantics + +namespace OAI + +/-! # Canonical dense-walk tabulation from binary margins and precision -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms GridBoundary +open scoped BigOperators Classical + +abbrev TabulationData := CanonicalParameters + +def tabulationDimension (z : TabulationData) : ℕ := + z.1.1.tail.length*z.1.2.tail.length + +def tabulationSteps (z : TabulationData) : ℕ := z.2.1^50*(z.2.2+1)^2 + +def tabulationStepsRealizer : Realizer tabulationSteps := by + let d : Realizer (fun z : TabulationData => z.2.1) := composition second first + let h : Realizer (fun z : TabulationData => z.2.2) := composition second second + exact (composition (pair (composition d fiftiethPower) + (composition (composition h successor) squareNat)) multiply).congr (by + intro z; simp only [Function.comp_apply,tabulationSteps,Nat.succ_eq_add_one,pow_two]) + +lemma polynomial_tabulationSteps : PolynomialTime tabulationStepsRealizer := by + unfold tabulationStepsRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_fiftiethPower) + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_second polynomial_second) polynomial_successor) + polynomial_squareNat)) polynomial_multiply + +def tabulationAllowance (z : TabulationData) : ℕ := 8*z.2.1^5 + +def tabulationAllowanceRealizer : Realizer tabulationAllowance := by + let d : Realizer (fun z : TabulationData => z.2.1) := composition second first + let result := composition (pair (constant 8) (composition d fifthPower)) multiply + exact result + +lemma polynomial_tabulationAllowance : PolynomialTime tabulationAllowanceRealizer := by + have hd : PolynomialTime (composition + (second (A := List ℕ×List ℕ) (B := ℕ×ℕ)) first) := + polynomial_composition polynomial_second polynomial_first + unfold tabulationAllowanceRealizer + exact polynomial_composition (polynomial_pair (polynomial_constant 8) + (polynomial_composition hd polynomial_fifthPower)) polynomial_multiply + +def tabulationDenominatorInput (z : TabulationData) : ℕ×ℕ := + (2,denseStepBits z.2.1) + +def tabulationDenominatorInputRealizer : Realizer tabulationDenominatorInput := + pair (constant 2) (composition (composition second first) denseWidthRealizer) + +lemma polynomial_tabulationDenominatorInput : PolynomialTime tabulationDenominatorInputRealizer := + polynomial_pair (polynomial_constant 2) (polynomial_composition + (polynomial_composition polynomial_second polynomial_first) polynomial_denseWidth) + +def tabulationDenominator (z : TabulationData) : ℕ := + BinaryPowerPrograms.power (tabulationDenominatorInput z) + +def tabulationDenominatorRealizer : Realizer tabulationDenominator := + composition tabulationDenominatorInputRealizer BinaryPowerPrograms.powerRealizer + +def tabulationDimensions (z : TabulationData) : List Bool := + (zeroGrid z.1).map (fun _ => false) + +def tabulationDimensionsRealizer : Realizer tabulationDimensions := by + let grid := composition (first (A := List ℕ×List ℕ) (B := ℕ×ℕ)) zeroGridRealizer + let result := composition grid (map (constant false)) + exact result + +lemma polynomial_tabulationDimensions : PolynomialTime tabulationDimensionsRealizer := by + unfold tabulationDimensionsRealizer + exact polynomial_composition (polynomial_composition polynomial_first polynomial_zeroGrid) + (polynomial_map (polynomial_constant false)) + +lemma tabulationDimensions_length (z : TabulationData) : + (tabulationDimensions z).length=tabulationDimension z := by + simp [tabulationDimensions,zeroGrid,cellPairs,tabulationDimension] + +def tabulationCountInput (z : TabulationData) : EnumeratedMatrixInput := + ((((unaryMarkers (tabulationAllowance z),tabulationDenominator z), + (z.1,z.2.1))),tabulationDimensions z) + +def tabulationCountInputRealizer : Realizer tabulationCountInput := by + let marks := composition tabulationAllowanceRealizer unaryMarkersRealizer + let header := pair (pair marks tabulationDenominatorRealizer) + (pair (first (A := List ℕ×List ℕ) (B := ℕ×ℕ)) (composition second first)) + exact pair header tabulationDimensionsRealizer + +def tabulationMeasure (z : TabulationData) : ℕ := + (4*z.2.1^8)^tabulationDimension z+tabulationAllowance z+ + denseStepBits z.2.1+tabulationSteps z+weight z + +private lemma weight_le_measure (z : TabulationData) : weight z≤tabulationMeasure z := by + unfold tabulationMeasure + omega + +private lemma polynomial_work {X : Type} [Codec X] {f : TabulationData → X} + {F : Realizer f} (hF : PolynomialTime F) : WorkBound F tabulationMeasure := + work_of_polynomial hF Polynomial.X (by intro z; simpa using weight_le_measure z) + +private lemma paired_work {X Y : Type} [Codec X] [Codec Y] + {f : TabulationData → X} {g : TabulationData → Y} {F : Realizer f} {G : Realizer g} + (hF : WorkBound F tabulationMeasure) (hG : WorkBound G tabulationMeasure) : + WorkBound (pair F G) tabulationMeasure := + work_pair hF hG Polynomial.X (by intro z; simpa using weight_le_measure z) + +lemma work_tabulationDenominator : WorkBound tabulationDenominatorRealizer tabulationMeasure := by + apply work_composition (polynomial_work polynomial_tabulationDenominatorInput) + BinaryPowerPrograms.work_power (Polynomial.X+9) + intro z + have hw : weight (2:ℕ)≤9 := by decide + simp only [tabulationDenominatorInput,Polynomial.eval_add,Polynomial.eval_X, + Polynomial.eval_ofNat,tabulationMeasure] + omega + +lemma work_tabulationCountInput : WorkBound tabulationCountInputRealizer tabulationMeasure := by + have ha : WorkBound (composition tabulationAllowanceRealizer unaryMarkersRealizer) + tabulationMeasure := by + apply work_composition (polynomial_work polynomial_tabulationAllowance) + work_unaryMarkers Polynomial.X + intro z + simp only [id_eq,Polynomial.eval_X,tabulationMeasure] + omega + unfold tabulationCountInputRealizer + exact paired_work (paired_work (paired_work ha work_tabulationDenominator) + (polynomial_work (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)))) + (polynomial_work polynomial_tabulationDimensions) + +lemma tabulation_enumerationMeasure (z : TabulationData) : + enumerationMeasure (tabulationCountInput z)= + (4*z.2.1^8)^tabulationDimension z+weight (tabulationCountInput z) := by + simp only [enumerationMeasure,enumerationData,tabulationCountInput,gridStateCount_eq, + tabulationDimensions_length] + +lemma work_tabulationEnumeration : WorkBound + (composition tabulationCountInputRealizer enumeratedMatrixInputRealizer) tabulationMeasure := by + obtain ⟨p,hp⟩ := work_tabulationCountInput + apply work_composition ⟨p,hp⟩ work_enumeratedMatrixInput (Polynomial.X+p) + intro z + rw [tabulation_enumerationMeasure] + have hw := hp z + simp only [Polynomial.eval_add,Polynomial.eval_X] + unfold tabulationMeasure at * + omega + +def tabulationInput (z : TabulationData) : MatrixWalkData := + ((unaryMarkers (tabulationSteps z),enumeratedMatrixInput (tabulationCountInput z)),zeroGrid z.1) + +def tabulationInputRealizer : Realizer tabulationInput := by + let steps := composition tabulationStepsRealizer unaryMarkersRealizer + let enum := composition tabulationCountInputRealizer enumeratedMatrixInputRealizer + let grid := composition (first (A := List ℕ×List ℕ) (B := ℕ×ℕ)) zeroGridRealizer + exact pair (pair steps enum) grid + +lemma work_tabulationInput : WorkBound tabulationInputRealizer tabulationMeasure := by + have ht : WorkBound (composition tabulationStepsRealizer unaryMarkersRealizer) + tabulationMeasure := by + apply work_composition (polynomial_work polynomial_tabulationSteps) + work_unaryMarkers Polynomial.X + intro z + simp only [id_eq,Polynomial.eval_X,tabulationMeasure] + omega + unfold tabulationInputRealizer + exact paired_work (paired_work ht work_tabulationEnumeration) + (polynomial_work (polynomial_composition polynomial_first polynomial_zeroGrid)) + +def tabulateDenseWalk (z : TabulationData) : List ℕ := matrixWalk (tabulationInput z) + +def tabulateDenseWalkRealizer : Realizer tabulateDenseWalk := + composition tabulationInputRealizer matrixWalkRealizer + +/-- Binary matrix propagation computes all walk numerators in polynomial +work in the explicit state count and the scheduled number of steps. -/ +theorem work_tabulateDenseWalk : WorkBound tabulateDenseWalkRealizer tabulationMeasure := + work_then_polynomial work_tabulationInput polynomial_matrixWalk + +lemma tabulationDimension_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (d h : ℕ) : + tabulationDimension ((marginCode R,marginCode P),(d,h))=m*n := by + simp [tabulationDimension,marginCode] + +/-- The caller computes its grid, zero starting state and full iteration +schedule from the margins. No state list or probability oracle is supplied. -/ +theorem tabulateDenseWalk_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hq : m*n≤d) (hd : 0 IntegerPropagation.numerators + (denseTransitionCount R P d finProdFinEquiv) + (canonicalOrigin (m*n) d hd) (d^50*(h+1)^2) + (gridEnumeration (m*n) (4*d^8) i)) := by + let e := gridEnumeration (m*n) (4*d^8) + let start := e.symm (canonicalOrigin (m*n) d hd) + have he : e start=canonicalOrigin (m*n) d hd := e.apply_symm_apply _ + have hdim : (tabulationDimensions ((marginCode R,marginCode P),(d,h))).length=m*n := by + rw [tabulationDimensions_length,tabulationDimension_code] + unfold tabulateDenseWalk tabulationInput enumeratedMatrixInput enumerationData + simp only [tabulationCountInput,tabulationDenominator,tabulationDenominatorInput, + BinaryPowerPrograms.power_eq] + rw [gridWords_eq_length _ _ _ hdim,zeroGrid_code R P hd,←he] + rw [matrixWalk_actual R P hq e _ _ (by simp [tabulationAllowance,unaryMarkers_length]) start] + simp only [unaryMarkers_length,tabulationSteps,he,e] + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWeights.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWeights.lean new file mode 100644 index 0000000000000000000000000000000000000000..55332cfc4b20e5dbcceaa5223a6605b76d3ba036 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWeights.lean @@ -0,0 +1,114 @@ +import OAI.Combinatorics.ContingencyTables.PublishedInputs +import Mathlib.Algebra.Order.Floor.Ring +import Mathlib.Analysis.Convex.Function +import Mathlib.Analysis.SpecialFunctions.Pow.Continuity +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Ring + +namespace OAI + +/-! +# Continuous and dyadic bin weights + +The actual floor-rounded weights used by the dense grid sampler. Convexity +of the penalty implies log-concavity of its density, and local changes of +the scaled penalty give explicit comparisons with the dyadic bin weights. +-/ + +namespace ContingencyTables.DenseWeights + +noncomputable section + +def density {X : Type*} (A : ℝ) (p : X → ℝ) (x : X) : ℝ := + (2 : ℝ) ^ (-(A * p x)) + +def binWeight {X : Type*} (A : ℝ) (p : X → ℝ) (v : X) : ℝ := + (2 : ℝ) ^ (-((⌊A * p v⌋ : ℤ) : ℝ)) + +theorem density_pos {X : Type*} (A : ℝ) (p : X → ℝ) (x : X) : + 0 < density A p x := Real.rpow_pos_of_pos (by norm_num) _ + +theorem binWeight_pos {X : Type*} (A : ℝ) (p : X → ℝ) (v : X) : + 0 < binWeight A p v := Real.rpow_pos_of_pos (by norm_num) _ + +/-- Rounding the exponent down changes a weight by at most a factor two. -/ +theorem binWeight_comparison {X : Type*} (A : ℝ) (p : X → ℝ) (v : X) : + density A p v ≤ binWeight A p v ∧ binWeight A p v ≤ 2 * density A p v := by + have hlo := Int.floor_le (A * p v) + have hhi := Int.lt_floor_add_one (A * p v) + constructor + · exact Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + · calc + binWeight A p v ≤ (2 : ℝ) ^ (-(A * p v) + 1) := + Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + _ = 2 * density A p v := by + rw [Real.rpow_add (by norm_num)] + simp [density, mul_comm] + +/-- A scaled-penalty change at most `s` gives the tube density bound. -/ +theorem density_le_binWeight {X : Type*} (A : ℝ) (p : X → ℝ) + (x v : X) (s : ℝ) (hchange : |A * p x - A * p v| ≤ s) : + density A p x ≤ (2 : ℝ) ^ s * binWeight A p v := by + have hlo := Int.floor_le (A * p v) + have h := (abs_le.mp hchange).1 + calc + density A p x ≤ (2 : ℝ) ^ (s - (⌊A * p v⌋ : ℝ)) := + Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + _ = (2 : ℝ) ^ s * binWeight A p v := by + rw [sub_eq_add_neg, Real.rpow_add (by norm_num)] + rfl + +theorem binWeight_le_density {X : Type*} (A : ℝ) (p : X → ℝ) + (x v : X) (s : ℝ) (hchange : |A * p x - A * p v| ≤ s) : + binWeight A p v ≤ (2 : ℝ) ^ (s + 1) * density A p x := by + have hhi := Int.lt_floor_add_one (A * p v) + have h := (abs_le.mp hchange).2 + calc + binWeight A p v ≤ (2 : ℝ) ^ ((s + 1) - A * p x) := + Real.rpow_le_rpow_of_exponent_le (by norm_num) (by linarith) + _ = (2 : ℝ) ^ (s + 1) * density A p x := by + rw [sub_eq_add_neg, Real.rpow_add (by norm_num)] + rfl + +theorem bin_density_comparison {X : Type*} (A : ℝ) (p : X → ℝ) + (x v : X) (hchange : |A * p x - A * p v| ≤ 1) : + binWeight A p v / 4 ≤ density A p x ∧ density A p x ≤ 2 * binWeight A p v := by + have hl := binWeight_le_density A p x v 1 hchange + have hu := density_le_binWeight A p x v 1 hchange + norm_num at hl hu + constructor <;> linarith + +theorem tube_density_comparison {X : Type*} (A : ℝ) (p : X → ℝ) + (x v : X) (hchange : |A * p x - A * p v| ≤ 2) : + density A p x ≤ 4 * binWeight A p v := by + have h := density_le_binWeight A p x v 2 hchange + norm_num at h + exact h + +theorem density_continuous {X : Type*} [TopologicalSpace X] + (A : ℝ) (p : X → ℝ) (hp : Continuous p) : Continuous (density A p) := by + exact Real.continuous_const_rpow (by norm_num) |>.comp ((continuous_const.mul hp).neg) + +/-- The continuous density used by the sampler is log-concave on every +convex domain on which its penalty is convex. -/ +theorem density_logConcave {q : ℕ} (A : ℝ) (hA : 0 ≤ A) + (p : PublishedInputs.Point q → ℝ) (K : Set (PublishedInputs.Point q)) + (hp : ConvexOn ℝ K p) : PublishedInputs.LogConcaveOn (density A p) K := by + intro x hx y hy t ht ht₁ + have hc := hp.2 hx hy (sub_nonneg.mpr ht₁.le) ht.le (show (1 - t) + t = 1 by ring) + simp only [smul_eq_mul] at hc + have he : (density A p x) ^ (1 - t) * (density A p y) ^ t = + (2 : ℝ) ^ (-A * ((1 - t) * p x + t * p y)) := by + simp only [density, ← Real.rpow_mul (by norm_num : (0 : ℝ) ≤ 2), + ← Real.rpow_add (by norm_num : (0 : ℝ) < 2)] + congr 1 + ring + rw [he] + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + nlinarith [mul_le_mul_of_nonneg_left hc hA] + +end + +end ContingencyTables.DenseWeights + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWordProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..58972cd4498ed3c2a6eff4003cb6080202ae3c74 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DenseWordProgram.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseMetropolisProgram + +namespace OAI + +/-! # Splitting the actual dense transition word in polynomial time -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped + +lemma clog_two_eq_size_pred (n : ℕ) : Nat.clog 2 n=(n-1).size := by + cases n with + | zero => simp + | succ n => + apply Nat.le_antisymm + · apply (Nat.clog_le_iff_le_pow (by decide)).mpr + have h := Nat.lt_size_self n + simpa only [Nat.add_sub_cancel] using Nat.succ_le_of_lt h + · apply Nat.size_le.mpr + have h := Nat.le_pow_clog (by decide : 1<2) (n+1) + simpa only [Nat.add_sub_cancel] using Nat.lt_of_succ_le h + +def ceilLogTwoRealizer : Realizer (Nat.clog 2) := + (composition predecessor bitSize).congr (fun n => (clog_two_eq_size_pred n).symm) + +theorem polynomial_ceilLogTwo : PolynomialTime ceilLogTwoRealizer := + polynomial_congr _ (polynomial_composition polynomial_predecessor polynomial_bitSize) + +def proposalWidth (z : FlatExponentData×List Bool) : ℕ := Nat.clog 2 (8*z.1.2) + +def proposalWidthRealizer : Realizer proposalWidth := by + let D : Realizer (fun z : FlatExponentData×List Bool => z.1.2) := composition first second + let M := composition (pair (constant 8) D) multiply + exact composition M ceilLogTwoRealizer + +theorem polynomial_proposalWidth : PolynomialTime proposalWidthRealizer := by + have hd : PolynomialTime (composition + (first (A := FlatExponentData) (B := List Bool)) second) := + polynomial_composition polynomial_first polynomial_second + unfold proposalWidthRealizer + exact polynomial_composition (polynomial_composition + (polynomial_pair (polynomial_constant 8) hd) polynomial_multiply) polynomial_ceilLogTwo + +def flatWordStep (z : FlatExponentData×List Bool) : List ℕ := + flatMetropolisStep (z.1, + (z.2.take (proposalWidth z),z.2.drop (proposalWidth z))) + +def flatWordStepRealizer : Realizer flatWordStep := + composition (pair first (pair + (composition (pair second proposalWidthRealizer) takeFast) + (composition (pair second proposalWidthRealizer) dropFast))) flatMetropolisStepRealizer + +theorem polynomial_flatWordStep : PolynomialTime flatWordStepRealizer := + polynomial_composition (polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_second polynomial_proposalWidth) polynomial_takeFast) + (polynomial_composition (polynomial_pair polynomial_second polynomial_proposalWidth) polynomial_dropFast))) + polynomial_flatMetropolisStep + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/DensityLayers.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/DensityLayers.lean new file mode 100644 index 0000000000000000000000000000000000000000..cbe54e1b64a077674d442094e111f4d70a2a996c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/DensityLayers.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseWeights +import Mathlib.MeasureTheory.Integral.Lebesgue.Basic + +namespace OAI + +/-! +# A finite penalty-layer bound + +The actual dense cube has bounded exponent, so a finite layer sum suffices +for its normalizer. This avoids any infinite layer decomposition. +-/ + +namespace ContingencyTables.DenseWeights + +open MeasureTheory +open scoped BigOperators ENNReal + +noncomputable section + +def layerSet {X : Type*} (A : ℝ) (p : X → ℝ) (j : ℕ) : Set X := + {x | A * p x ≤ (j : ℝ) + 1} + +theorem density_le_finite_layers {X : Type*} (A : ℝ) (p : X → ℝ) (N : ℕ) + (x : X) (hx₀ : 0 ≤ A * p x) (hxN : A * p x ≤ N) : + ENNReal.ofReal (density A p x) ≤ + ∑ j ∈ Finset.range (N + 1), + (layerSet A p j).indicator (fun _ => ENNReal.ofReal ((2 : ℝ) ^ (-(j : ℝ)))) x := by + let j := (⌊A * p x⌋ : ℤ).toNat + have hf : (0 : ℤ) ≤ ⌊A * p x⌋ := Int.floor_nonneg.mpr hx₀ + have hjcast : (j : ℝ) = (⌊A * p x⌋ : ℤ) := by + exact_mod_cast Int.toNat_of_nonneg hf + have hj : j ∈ Finset.range (N + 1) := by + apply Finset.mem_range.mpr + have hb : (j : ℝ) ≤ N := by + rw [hjcast] + exact (Int.floor_le _).trans hxN + have hn : j ≤ N := by exact_mod_cast hb + omega + have hxj : x ∈ layerSet A p j := by + change A * p x ≤ (j : ℝ) + 1 + rw [hjcast] + exact (Int.lt_floor_add_one _).le + have hweight : density A p x ≤ (2 : ℝ) ^ (-(j : ℝ)) := by + apply Real.rpow_le_rpow_of_exponent_le (by norm_num) + rw [hjcast] + linarith [Int.floor_le (A * p x)] + calc + _ ≤ ENNReal.ofReal ((2 : ℝ) ^ (-(j : ℝ))) := ENNReal.ofReal_le_ofReal hweight + _ = (layerSet A p j).indicator (fun _ => ENNReal.ofReal ((2 : ℝ) ^ (-(j : ℝ)))) x := by + rw [Set.indicator_of_mem hxj] + _ ≤ _ := Finset.single_le_sum + (f := fun k : ℕ => (layerSet A p k).indicator + (fun _ => ENNReal.ofReal ((2 : ℝ) ^ (-(k : ℝ)))) x) (fun _ _ => bot_le) hj + +theorem density_lintegral_le_layers {X : Type*} [MeasurableSpace X] + (μ : Measure X) (A : ℝ) (p : X → ℝ) (hp : Measurable p) + (K : Set X) (hK : MeasurableSet K) (N : ℕ) + (hbound : ∀ x ∈ K, 0 ≤ A * p x ∧ A * p x ≤ N) : + (∫⁻ x in K, ENNReal.ofReal (density A p x) ∂μ) ≤ + ∑ j ∈ Finset.range (N + 1), + ENNReal.ofReal ((2 : ℝ) ^ (-(j : ℝ))) * μ (K ∩ layerSet A p j) := by + have hmeas (j : ℕ) : MeasurableSet (layerSet A p j) := + measurableSet_le (measurable_const.mul hp) measurable_const + calc + _ ≤ ∫⁻ x in K, ∑ j ∈ Finset.range (N + 1), + (layerSet A p j).indicator (fun _ => ENNReal.ofReal ((2 : ℝ) ^ (-(j : ℝ)))) x ∂μ := by + apply lintegral_mono_ae + filter_upwards [ae_restrict_mem hK] with x hx + exact density_le_finite_layers A p N x (hbound x hx).1 (hbound x hx).2 + _ = _ := by + rw [lintegral_finsetSum] + · apply Finset.sum_congr rfl + intro j _ + rw [lintegral_indicator (hmeas j), lintegral_const, Measure.restrict_restrict (hmeas j), + Measure.restrict_apply_univ, Set.inter_comm] + · intro j _ + exact (measurable_const : Measurable (fun _ : X => + ENNReal.ofReal ((2 : ℝ) ^ (-(j : ℝ))))).indicator (hmeas j) + +end + +end ContingencyTables.DenseWeights + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/FiniteBoxPrekopa.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/FiniteBoxPrekopa.lean new file mode 100644 index 0000000000000000000000000000000000000000..b21e76b324edff9e7ef8260af9b7995d07e4e426 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/FiniteBoxPrekopa.lean @@ -0,0 +1,98 @@ +import OAI.Analysis.KLS.Convexity.PrekopaLeindler +import OAI.Combinatorics.ContingencyTables.PublishedInputs +import Mathlib.MeasureTheory.Function.LocallyIntegrable + +namespace OAI + +/-! # Discharging the finite-box Prékopa–Leindler input + +The finite-function-space Prékopa–Leindler inequality applies to the nonnegative +indicators of the three box unions. Compact-box continuity supplies all +measurability and integrability obligations without assumptions outside +the common box. +-/ +namespace ContingencyTables.PublishedInputs +open MeasureTheory Set +open scoped ENNReal +noncomputable section + +private theorem integral_interpolation {q : ℕ} {f g h : Point q → ℝ} + (hf0 : ∀ x, 0 ≤ f x) (hg0 : ∀ x, 0 ≤ g x) (hh0 : ∀ x, 0 ≤ h x) + (hf : Measurable f) (hg : Measurable g) (hh : Measurable h) + (hfi : Integrable f) (hgi : Integrable g) (hhi : Integrable h) + {t : ℝ} (ht : 0 < t) (ht1 : t < 1) + (hfg : ∀ x y, f x ^ t * g y ^ (1-t) ≤ h (t • x+(1-t) • y)) : + (∫ x, f x)^t * (∫ y, g y)^(1-t) ≤ ∫ z, h z := by + have hp := AsymptoticStatistics.prekopaLeindler hf.ennreal_ofReal hg.ennreal_ofReal + hh.ennreal_ofReal ht ht1 (fun x y => by + rw [ENNReal.ofReal_rpow_of_nonneg (hf0 x) ht.le, + ENNReal.ofReal_rpow_of_nonneg (hg0 y) (sub_pos.mpr ht1).le, + ← ENNReal.ofReal_mul (Real.rpow_nonneg (hf0 x) t)] + exact ENNReal.ofReal_le_ofReal (hfg x y)) + rw [← ofReal_integral_eq_lintegral_ofReal hfi (ae_of_all _ hf0), + ← ofReal_integral_eq_lintegral_ofReal hgi (ae_of_all _ hg0), + ← ofReal_integral_eq_lintegral_ofReal hhi (ae_of_all _ hh0)] at hp + rw [ENNReal.ofReal_rpow_of_nonneg (integral_nonneg hf0) ht.le, + ENNReal.ofReal_rpow_of_nonneg (integral_nonneg hg0) (sub_pos.mpr ht1).le, + ← ENNReal.ofReal_mul (Real.rpow_nonneg (integral_nonneg hf0) t)] at hp + exact (ENNReal.ofReal_le_ofReal_iff (integral_nonneg hh0)).mp hp + +theorem IsFiniteBoxUnion.isOpen {q : ℕ} {S : Set (Point q)} + (hS : IsFiniteBoxUnion S) : IsOpen S := by + obtain ⟨n,lower,upper,rfl⟩ := hS + have ho : IsOpen (⋃ k : Fin n, ⋂ i : Fin q, + {x : Point q | lower k i < x i ∧ x i < upper k i}) := + isOpen_iUnion fun k => isOpen_iInter_of_finite fun i => + (isOpen_lt continuous_const (continuous_apply i)).inter + (isOpen_lt (continuous_apply i) continuous_const) + convert ho using 1 + ext x + simp + +private theorem box_indicator {q : ℕ} {lower upper : Point q} {S : Set (Point q)} + {f : Point q → ℝ} (hS : IsFiniteBoxUnion S) + (hbox : closure S ⊆ Icc lower upper) (hf : ContinuousOn f (Icc lower upper)) + (hp : ∀ x ∈ Icc lower upper, 0 < f x) : + (∀ x, 0 ≤ S.indicator f x) ∧ Measurable (S.indicator f) ∧ + Integrable (S.indicator f) := by + classical + have hs := hS.isOpen.measurableSet + have hsub : S ⊆ Icc lower upper := subset_closure.trans hbox + refine ⟨?_,?_,?_⟩ + · intro x + by_cases hx : x ∈ S + · simpa only [indicator_of_mem hx] using (hp x (hsub hx)).le + · simp only [indicator_of_notMem hx, le_refl] + · change Measurable (S.piecewise f (fun _ => 0)) + exact (hf.mono hsub).measurable_piecewise continuousOn_const hs + · exact (hf.integrableOn_Icc.mono_set hsub).integrable_indicator hs + +/-- The exact published analytic hypothesis required by both manuscripts. -/ +theorem finiteBoxPrekopaLeindler (q : ℕ) : FiniteBoxPrekopaLeindler q := by + intro t ht ht1 lower upper S₀ S₁ S₂ f₀ f₁ f₂ hS₀ hS₁ hS₂ + hb₀ hb₁ hb₂ hc₀ hc₁ hc₂ hp₀ hp₁ hp₂ hcover hle + obtain ⟨h₀,hm₀,hi₀⟩ := box_indicator hS₀ hb₀ hc₀ hp₀ + obtain ⟨h₁,hm₁,hi₁⟩ := box_indicator hS₁ hb₁ hc₁ hp₁ + obtain ⟨h₂,hm₂,hi₂⟩ := box_indicator hS₂ hb₂ hc₂ hp₂ + have ht' : 0 < 1-t := sub_pos.mpr ht1 + have ht1' : 1-t < 1 := by linarith + have H := integral_interpolation h₁ h₂ h₀ hm₁ hm₂ hm₀ hi₁ hi₂ hi₀ ht' ht1' + (fun x y => by + rw [show 1-(1-t)=t by ring] + by_cases hx : x ∈ S₁ + · by_cases hy : y ∈ S₂ + · have hz : (1-t) • x+t • y ∈ S₀ := hcover ⟨x,hx,y,hy,rfl⟩ + simpa only [indicator_of_mem hx,indicator_of_mem hy,indicator_of_mem hz] + using hle x hx y hy + · rw [indicator_of_notMem hy,Real.zero_rpow (ne_of_gt ht),mul_zero] + exact h₀ _ + · rw [indicator_of_notMem hx,Real.zero_rpow (ne_of_gt ht'),zero_mul] + exact h₀ _) + simpa only [integral_indicator hS₀.isOpen.measurableSet, + integral_indicator hS₁.isOpen.measurableSet,integral_indicator hS₂.isOpen.measurableSet, + sub_sub_cancel] using H + +end +end ContingencyTables.PublishedInputs + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/FiniteCheegerProof.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/FiniteCheegerProof.lean new file mode 100644 index 0000000000000000000000000000000000000000..026833748838e7918740e23cbab37e21e8c09492 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/FiniteCheegerProof.lean @@ -0,0 +1,86 @@ +import OAI.Combinatorics.ContingencyTables.Dense.CheegerPositive +import OAI.Combinatorics.ContingencyTables.Dense.CheegerMedian + +namespace OAI + +/-! # Discharging the finite-chain Cheeger input by coarea and a weighted median -/ +namespace ContingencyTables.CheegerProof +open CommonBasesFPRAS +open scoped BigOperators Classical +noncomputable section + +private lemma split_square (u : ℝ) : (max u 0)^2+(max (-u) 0)^2 = u^2 := by + by_cases hu : 0 ≤ u + · rw [max_eq_left hu,max_eq_right (neg_nonpos.mpr hu)] + ring + · rw [max_eq_right (le_of_not_ge hu),max_eq_left (by linarith)] + ring + +private lemma split_difference (u v : ℝ) : + (max u 0-max v 0)^2+(max (-u) 0-max (-v) 0)^2 ≤ (u-v)^2 := by + by_cases hu : 0 ≤ u <;> by_cases hv : 0 ≤ v + · rw [max_eq_left hu,max_eq_left hv,max_eq_right (neg_nonpos.mpr hu), + max_eq_right (neg_nonpos.mpr hv)] + simp + · have hv' : v ≤ 0 := le_of_not_ge hv + rw [max_eq_left hu,max_eq_right hv',max_eq_right (neg_nonpos.mpr hu), + max_eq_left (neg_nonneg.mpr hv')] + nlinarith [mul_nonpos_of_nonneg_of_nonpos hu hv'] + · have hu' : u ≤ 0 := le_of_not_ge hu + rw [max_eq_right hu',max_eq_left hv,max_eq_left (neg_nonneg.mpr hu'), + max_eq_right (neg_nonpos.mpr hv)] + nlinarith [mul_nonpos_of_nonpos_of_nonneg hu' hv] + · have hu' : u ≤ 0 := le_of_not_ge hu + have hv' : v ≤ 0 := le_of_not_ge hv + rw [max_eq_right hu',max_eq_right hv',max_eq_left (neg_nonneg.mpr hu'), + max_eq_left (neg_nonneg.mpr hv')] + nlinarith + +variable {X : Type*} [Fintype X] + +/-- Levin–Peres Theorem 13.10 lower bound, in the exact finite Poincaré form used here. -/ +theorem finiteCheeger : PublishedInputs.FiniteCheeger X := by + intro C κ hk hcut f + obtain ⟨a,hbelow,habove⟩ := exists_median C f + let p : X → ℝ := fun x => max (f x-a) 0 + let n : X → ℝ := fun x => max (a-f x) 0 + have hp : mass C (Finset.univ.filter fun x => 0 < p x) ≤ 1/2 := by + simpa only [p,lt_max_iff,lt_self_iff_false,or_false,sub_pos] using habove + have hn : mass C (Finset.univ.filter fun x => 0 < n x) ≤ 1/2 := by + simpa only [n,lt_max_iff,lt_self_iff_false,or_false,sub_pos] using hbelow + have hcut' : ∀ S : Finset X, κ*min (mass C S) (mass C Sᶜ) ≤ cut C S := hcut + have hpe := positive_energy C κ hk hcut' p (fun _ => le_max_right _ _) hp + have hne := positive_energy C κ hk hcut' n (fun _ => le_max_right _ _) hn + have hnorm : (∑ x, C.π x*(p x)^2)+(∑ x, C.π x*(n x)^2) = + ∑ x, C.π x*(f x-a)^2 := by + rw [← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro x _ + dsimp [p,n] + rw [← mul_add,show a-f x = -(f x-a) by ring,split_square] + have he : C.energy p+C.energy n ≤ C.energy f := by + rw [C.energy_eq,C.energy_eq,C.energy_eq,← add_div, + ← Finset.sum_add_distrib] + apply div_le_div_of_nonneg_right _ (by norm_num) + apply Finset.sum_le_sum + intro x _ + rw [← Finset.sum_add_distrib] + apply Finset.sum_le_sum + intro y _ + rw [← mul_add] + apply mul_le_mul_of_nonneg_left _ (mul_nonneg (C.positive x).le (C.nonnegative x y)) + dsimp [p,n] + convert split_difference (f x-a) (f y-a) using 1 <;> ring_nf + have hv := mul_le_mul_of_nonneg_left (variance_le_centered C f a) (sq_nonneg κ) + have hb : κ^2*C.variance f ≤ 2*C.energy f := by + rw [← hnorm] at hv + nlinarith [hpe,hne,he] + have hk2 : 0 < κ^2 := sq_pos_of_pos hk + calc + C.variance f ≤ (2*C.energy f)/κ^2 := (le_div_iff₀ hk2).mpr (by nlinarith [hb]) + _ = (2/κ^2)*C.energy f := by ring + +end +end ContingencyTables.CheegerProof + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridAdjacency.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridAdjacency.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3a305cfb774cf4b2cbbf20b948e92b2627bfa4f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridAdjacency.lean @@ -0,0 +1,95 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridCover +import Mathlib.Data.Fintype.Card + +namespace OAI + +/-! # Actual axis neighbours and the `2q` proposal-degree bound -/ + +namespace ContingencyTables.GridBoundary + +open scoped Classical + +noncomputable section + +variable {I : Type*} [Fintype I] [DecidableEq I] {K : ℕ} + +def OrientedNeighbor (a b : Grid (I := I) K) (i : I) (sign : Bool) : Prop := + if sign then IsGridEdge (a, b, i) else IsGridEdge (b, a, i) + +def Neighbor (a b : Grid (I := I) K) : Prop := ∃ i sign, OrientedNeighbor a b i sign + +omit [Fintype I] [DecidableEq I] in +theorem neighbor_symm (a b : Grid (I := I) K) : Neighbor a b ↔ Neighbor b a := by + constructor <;> rintro ⟨i, sign, h⟩ <;> refine ⟨i, !sign, ?_⟩ <;> + cases sign <;> exact h + +omit [Fintype I] [DecidableEq I] in +theorem neighbor_ne (a b : Grid (I := I) K) (h : Neighbor a b) : a ≠ b := by + rintro rfl + obtain ⟨i, sign, hs⟩ := h + cases sign + · have hh : corner a i = corner a i + 1 := hs.1 + omega + · have hh : corner a i = corner a i + 1 := hs.1 + omega + +omit [Fintype I] [DecidableEq I] in +private theorem oriented_target_unique (a b c : Grid (I := I) K) (i : I) (sign : Bool) + (hb : OrientedNeighbor a b i sign) (hc : OrientedNeighbor a c i sign) : b = c := by + funext j + apply Subtype.ext + change corner b j = corner c j + cases sign <;> change IsGridEdge _ at hb hc + · by_cases hj : j = i + · subst j + have hbi : corner a i = corner b i + 1 := hb.1 + have hci : corner a i = corner c i + 1 := hc.1 + omega + · have hbj := congrArg Subtype.val (hb.2 j hj) + have hcj := congrArg Subtype.val (hc.2 j hj) + exact hbj.symm.trans hcj + · by_cases hj : j = i + · subst j + exact hb.1.trans hc.1.symm + · have hbj := congrArg Subtype.val (hb.2 j hj) + have hcj := congrArg Subtype.val (hc.2 j hj) + exact hbj.trans hcj.symm + +def neighborDirection (a : Grid (I := I) K) (b : {b // Neighbor a b}) : I × Bool := + ⟨Classical.choose b.property, Classical.choose (Classical.choose_spec b.property)⟩ + +omit [Fintype I] [DecidableEq I] in +private theorem neighborDirection_spec (a : Grid (I := I) K) (b : {b // Neighbor a b}) : + OrientedNeighbor a b.val (neighborDirection a b).1 (neighborDirection a b).2 := + Classical.choose_spec (Classical.choose_spec b.property) + +omit [Fintype I] [DecidableEq I] in +theorem neighborDirection_injective (a : Grid (I := I) K) : + Function.Injective (neighborDirection a) := by + intro b c h + have hi := congrArg Prod.fst h + have hs := congrArg Prod.snd h + apply Subtype.ext + apply oriented_target_unique a b.val c.val (neighborDirection a b).1 (neighborDirection a b).2 + (neighborDirection_spec a b) + simpa only [hi, hs] using neighborDirection_spec a c + +theorem neighbor_degree (a : Grid (I := I) K) : + (Finset.univ.filter (Neighbor a)).card ≤ 2 * Fintype.card I := by + have h := Fintype.card_le_of_injective (neighborDirection a) (neighborDirection_injective a) + rw [Fintype.card_subtype] at h + simpa only [Fintype.card_prod, Fintype.card_bool, Nat.mul_comm] using h + +omit [Fintype I] [DecidableEq I] in +theorem edge_axis_unique (a b : Grid (I := I) K) (i j : I) + (hi : IsGridEdge (a, b, i)) (hj : IsGridEdge (a, b, j)) : i = j := by + by_contra h + have heq : corner b i = corner a i := congrArg Subtype.val (hj.2 i h) + have hplus : corner b i = corner a i + 1 := hi.1 + omega + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridBoundary.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridBoundary.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cce309f03f98f43c1953125335011901e176374 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridBoundary.lean @@ -0,0 +1,164 @@ +import Mathlib.Data.Finset.Basic +import Mathlib.Data.Fintype.Basic +import Mathlib.Basic.Real.Basic +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.NormNum +import Lean.Elab.Tactic.Omega + +namespace OAI + +/-! +# Cut faces of a unit grid + +The geometric step in the dense sampler's conductance proof: two points +in differently labelled open bins at sup distance less than `r ≤ 1` are +within `r` of a common closed face of oppositely labelled axis neighbours. +A coordinate path avoids any general-position assumption at simultaneous +grid crossings. +-/ + +namespace ContingencyTables.GridBoundary + +variable {I : Type*} [DecidableEq I] + +def mixed (a b : I → ℤ) (S : Finset I) : I → ℤ := + fun i => if i ∈ S then b i else a i + +private theorem cut_edge_aux (P : (I → ℤ) → Prop) (a b : I → ℤ) + (ha : P a) (K : Finset I) (hb : ¬ P (mixed a b K)) : + ∃ S i, S ⊆ K ∧ i ∈ K ∧ i ∉ S ∧ P (mixed a b S) ∧ + ¬ P (mixed a b (insert i S)) := by + classical + induction K using Finset.induction_on with + | empty => + have heq : mixed a b ∅ = a := by ext i; simp [mixed] + exact False.elim (hb (heq.symm ▸ ha)) + | @insert i K hi ih => + by_cases hK : P (mixed a b K) + · exact ⟨K, i, Finset.subset_insert _ _, Finset.mem_insert_self _ _, hi, hK, hb⟩ + · obtain ⟨S, j, hS, hj, hjS, hPS, hPj⟩ := ih hK + exact ⟨S, j, hS.trans (Finset.subset_insert _ _), Finset.mem_insert_of_mem hj, + hjS, hPS, hPj⟩ + +/-- A change of labels along a coordinate path occurs on an axis edge. -/ +theorem cut_edge [Fintype I] (P : (I → ℤ) → Prop) (a b : I → ℤ) + (ha : P a) (hb : ¬ P b) : + ∃ S i, i ∉ S ∧ P (mixed a b S) ∧ ¬ P (mixed a b (insert i S)) := by + have heq : mixed a b Finset.univ = b := by ext i; simp [mixed] + have hb' : ¬ P (mixed a b Finset.univ) := by rw [heq]; exact hb + obtain ⟨S, i, _, _, hi, hS, hSi⟩ := cut_edge_aux P a b ha Finset.univ hb' + exact ⟨S, i, hi, hS, hSi⟩ + +def OpenBin (a : I → ℤ) (x : I → ℝ) : Prop := + ∀ i, (a i : ℝ) < x i ∧ x i < (a i : ℝ) + 1 + +def ClosedBin (a : I → ℤ) (x : I → ℝ) : Prop := + ∀ i, (a i : ℝ) ≤ x i ∧ x i ≤ (a i : ℝ) + 1 + +private theorem short_bin_indices (a b : ℤ) (x z r : ℝ) + (hx : (a : ℝ) < x ∧ x < (a : ℝ) + 1) + (hz : (b : ℝ) < z ∧ z < (b : ℝ) + 1) + (hd : |z - x| < r) (hr : r ≤ 1) (hab : a ≠ b) : + b = a + 1 ∨ a = b + 1 := by + have hd' := abs_lt.mp hd + have hba : b < a + 2 := by + exact_mod_cast (show (b : ℝ) < (a : ℝ) + 2 by linarith) + have hab' : a < b + 2 := by + exact_mod_cast (show (a : ℝ) < (b : ℝ) + 2 by linarith) + omega + +private theorem clamp_near (a x z r : ℝ) + (hx : a < x ∧ x < a + 1) (hd : |z - x| < r) : + ∃ w, a ≤ w ∧ w ≤ a + 1 ∧ |z - w| < r := by + have hr : 0 < r := lt_of_le_of_lt (abs_nonneg _) hd + have hd' := abs_lt.mp hd + by_cases hza : z < a + · refine ⟨a, le_rfl, by linarith, ?_⟩ + rw [abs_of_neg (by linarith : z - a < 0)] + linarith + · by_cases haz : a + 1 < z + · refine ⟨a + 1, by linarith, le_rfl, ?_⟩ + rw [abs_of_pos (by linarith : 0 < z - (a + 1))] + linarith + · exact ⟨z, le_of_not_gt hza, le_of_not_gt haz, by simpa using hr⟩ + +private theorem adjacent_boundary (a b : ℤ) (x z r : ℝ) + (hx : (a : ℝ) < x ∧ x < (a : ℝ) + 1) + (hz : (b : ℝ) < z ∧ z < (b : ℝ) + 1) + (hd : |z - x| < r) (hab : b = a + 1 ∨ a = b + 1) : + (a : ℝ) ≤ max (a : ℝ) b ∧ max (a : ℝ) b ≤ (a : ℝ) + 1 ∧ + (b : ℝ) ≤ max (a : ℝ) b ∧ max (a : ℝ) b ≤ (b : ℝ) + 1 ∧ + |z - max (a : ℝ) b| < r := by + have hd' := abs_lt.mp hd + rcases hab with hab | hab + · have heq : (b : ℝ) = (a : ℝ) + 1 := by exact_mod_cast hab + rw [max_eq_right (by linarith : (a : ℝ) ≤ b)] + refine ⟨by linarith, by linarith, le_rfl, by linarith, ?_⟩ + rw [abs_of_pos (by linarith : 0 < z - (b : ℝ))] + linarith + · have heq : (a : ℝ) = (b : ℝ) + 1 := by exact_mod_cast hab + rw [max_eq_left (by linarith : (b : ℝ) ≤ a)] + refine ⟨le_rfl, by linarith, by linarith, by linarith, ?_⟩ + rw [abs_of_neg (by linarith : z - (a : ℝ) < 0)] + linarith + +/-- The terminal point of a short displacement lies near an actual cut +face. The intermediate bins use only the two endpoint indices in each +coordinate, so they stay inside any rectangular grid containing them. -/ +theorem near_cut_face [Fintype I] (P : (I → ℤ) → Prop) + (a b : I → ℤ) (x z : I → ℝ) (r : ℝ) + (ha : OpenBin a x) (hb : OpenBin b z) + (hd : ∀ i, |z i - x i| < r) (hr : r ≤ 1) + (hPa : P a) (hPb : ¬ P b) : + ∃ S i w, i ∉ S ∧ P (mixed a b S) ∧ ¬ P (mixed a b (insert i S)) ∧ + (b i = a i + 1 ∨ a i = b i + 1) ∧ + ClosedBin (mixed a b S) w ∧ ClosedBin (mixed a b (insert i S)) w ∧ + (∀ j, |z j - w j| < r) := by + classical + obtain ⟨S, i, hi, hS, hSi⟩ := cut_edge P a b hPa hPb + have hneq : a i ≠ b i := by + intro heq + apply hSi + have hmix : mixed a b (insert i S) = mixed a b S := by + ext j + by_cases hj : j = i + · subst j + simp [mixed, hi, heq] + · simp [mixed, hj] + rwa [hmix] + have hadj := short_bin_indices (a i) (b i) (x i) (z i) r (ha i) (hb i) (hd i) hr hneq + have hface := adjacent_boundary (a i) (b i) (x i) (z i) r (ha i) (hb i) (hd i) hadj + have hnear (j : I) : ∃ w, ((mixed a b S j : ℤ) : ℝ) ≤ w ∧ + w ≤ (mixed a b S j : ℝ) + 1 ∧ |z j - w| < r := by + by_cases hj : j ∈ S + · refine ⟨z j, ?_, ?_, ?_⟩ + · simpa [mixed, hj] using (hb j).1.le + · simpa [mixed, hj] using (hb j).2.le + · simpa using lt_of_le_of_lt (abs_nonneg _) (hd j) + · simpa [mixed, hj] using clamp_near (a j) (x j) (z j) r (ha j) (hd j) + choose v hv using hnear + let w : I → ℝ := Function.update v i (max (a i : ℝ) (b i)) + refine ⟨S, i, w, hi, hS, hSi, hadj, ?_, ?_, ?_⟩ + · intro j + by_cases hj : j = i + · subst j + have hp := And.intro hface.1 hface.2.1 + simpa [w, mixed, hi] using hp + · have hp := And.intro (hv j).1 (hv j).2.1 + simpa [w, hj] using hp + · intro j + by_cases hj : j = i + · subst j + have hp := And.intro hface.2.2.1 hface.2.2.2.1 + simpa [w, mixed] using hp + · have hp := And.intro (hv j).1 (hv j).2.1 + simpa [w, mixed, hj] using hp + · intro j + by_cases hj : j = i + · subst j + simpa [w] using hface.2.2.2.2 + · simpa [w, hj] using (hv j).2.2 + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridConductance.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridConductance.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecee17f4e05f0edbe3c731d3f31806588d07f0cc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridConductance.lean @@ -0,0 +1,106 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridMass + +namespace OAI + +/-! +# Conditional weighted grid-cut estimate + +The finite-box Prékopa input is the only published hypothesis here. The +shell cover, tube volume, integral cover, and discrete/continuous mass +comparison yield the discrete cut estimate. +-/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators + +/-- The actual weighted cut bound before the proposal probability is +inserted. The selected side is the smaller continuous side; the conclusion +uses its own discrete weight and therefore also bounds the smaller discrete +side without identifying the two notions of smaller side. -/ +theorem weighted_cut_of_interpolation {q K : ℕ} + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (P : (Fin q → ℤ) → Prop) (t : ℝ) (ht : 0 < t) (ht₁ : t < 1) + (hr : t * K ≤ 1 / 4) (hsize : (q - 1 : ℕ) * (2 * (t * K)) ≤ (1 / 2 : ℝ)) + (ρ : (Fin q → ℝ) → ℝ) (w : Grid (I := Fin q) K → ℝ) + (hw : ∀ a, 0 ≤ w a) + (hρ : ContinuousOn ρ (ambientBox q K)) + (hpos : ∀ x ∈ ambientBox q K, 0 < ρ x) + (hlc : PublishedInputs.LogConcaveOn ρ (ambientBox q K)) + (hbin : ∀ a x, x ∈ binSet a → w a / 4 ≤ ρ x) + (htube : ∀ (e : CutEdge K P) x, x ∈ edgeTube e (t * K) ∩ {x | Cube K x} → + ρ x ≤ 4 * min (w e.val.1) (w e.val.2.1)) + (hSmass : 0 < ∫ x in selectedBins K P, ρ x) + (hcut : 2 * (∫ x in selectedBins K P, ρ x) ≤ ∫ x in {x | Cube K x}, ρ x) : + (((2 : ℝ) ^ t - 1) / 16) * (∑ a : Selected K P, w a.val) ≤ + ∑ e : CutEdge K P, min (w e.val.1) (w e.val.2.1) := by + let S := selectedBins K P + let D := {x : Fin q → ℝ | Cube K x} + let M := PublishedInputs.interpolate t S D + let E : CutEdge K P → Set (Fin q → ℝ) := fun e => edgeTube e (t * K) ∩ D + have hS := selectedBins_finiteBox (K := K) P + have hD := cube_finiteBox (q := q) (K := K) + have hM := hS.interpolate hD t ht ht₁ + have hMsub : M ⊆ D := by + rintro z ⟨x, ⟨a, _, hx⟩, y, hy, rfl⟩ + have hx' := openBin_in_cube a x hx + intro j + have hxt := mul_pos (sub_pos.mpr ht₁) (hx' j).1 + have hyt := mul_pos ht (hy j).1 + have hxu := mul_lt_mul_of_pos_left (hx' j).2 (sub_pos.mpr ht₁) + have hyu := mul_lt_mul_of_pos_left (hy j).2 ht + change 0 < (1 - t) * x j + t * y j ∧ (1 - t) * x j + t * y j < (K : ℝ) + constructor <;> nlinarith + have hsub : S ⊆ M := by + rintro x hx + refine ⟨x, hx, x, ?_, ?_⟩ + · obtain ⟨a, _, ha⟩ := hx + exact openBin_in_cube a x ha + · ext j + simp only [Pi.add_apply, Pi.smul_apply, smul_eq_mul] + ring + have hi : IntegrableOn ρ (ambientBox q K) := hρ.integrableOn_Icc + have hMc : closure M ⊆ ambientBox q K := + PublishedInputs.interpolation_closure_in_box + (selectedBins_closure P) cube_closure t ht.le ht₁.le + have hiShell : IntegrableOn ρ (M \ S) := hi.mono_set + (fun x hx => hMc (subset_closure hx.1)) + have hcover : ∀ᵐ x ∂volume, x ∈ M \ S → ∃ e, x ∈ E e := by + have hc := interpolation_shell_cover_ae P t ht ht₁ (show t * K ≤ 1 by linarith) + filter_upwards [hc] with x hx + intro hxS + obtain ⟨e, he⟩ := hx hxS + exact ⟨e, he, hMsub hxS.1⟩ + have hESub (e : CutEdge K P) : E e ⊆ ambientBox q K := + fun x hx => ⟨fun j => (hx.2 j).1.le, fun j => (hx.2 j).2.le⟩ + have hEm (e : CutEdge K P) : MeasurableSet (E e) := + (faceTube_measurable _ _ _).inter hD.isOpen.measurableSet + have hcoverInt := ContingencyTables.integral_finite_cover (M \ S) E ρ + (hM.isOpen.measurableSet.diff hS.isOpen.measurableSet) hEm hiShell + (fun e => hi.mono_set (hESub e)) + (fun e x hx => (hpos x (hESub e hx)).le) hcover + have hr₀ : 0 ≤ t * (K : ℝ) := mul_nonneg ht.le (Nat.cast_nonneg _) + have hupper : (∫ x in M \ S, ρ x) ≤ + 4 * ∑ e : CutEdge K P, min (w e.val.1) (w e.val.2.1) := by + calc + _ ≤ ∑ e : CutEdge K P, ∫ x in E e, ρ x := hcoverInt + _ ≤ ∑ e : CutEdge K P, 4 * min (w e.val.1) (w e.val.2.1) := by + apply Finset.sum_le_sum + intro e _ + exact edgeTube_mass_upper P e (t * K) hr₀ hr hsize ρ w hw hi (htube e) + _ = _ := by rw [Finset.mul_sum] + have hgain := PublishedInputs.interpolation_shell_gain hPL t ht ht₁ + (fun _ => 0) (fun _ => (K : ℝ)) S D ρ hS hD + (selectedBins_closure P) cube_closure hρ hpos hlc hsub hSmass hcut + have hlower := selectedBins_mass_lower P ρ w hi hbin + have hg : 0 ≤ (2 : ℝ) ^ t - 1 := by + have h := Real.rpow_le_rpow_of_exponent_le (by norm_num : (1 : ℝ) ≤ 2) ht.le + exact sub_nonneg.mpr (by simpa using h) + have hscaled := mul_le_mul_of_nonneg_left hlower hg + dsimp only [S, D, M] at hupper hgain + nlinarith + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridCover.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridCover.lean new file mode 100644 index 0000000000000000000000000000000000000000..3634235eca9b61ae21af628ac655a8b7d6361ee4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridCover.lean @@ -0,0 +1,165 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridMeasure +import OAI.Combinatorics.ContingencyTables.Transport.BoxGeometry +import Mathlib.Data.Int.Interval +import Mathlib.Algebra.Order.Floor.Ring +import Mathlib.Data.Fintype.Pi + +namespace OAI + +/-! +# Finite cut-face cover of the interpolation shell + +The continuous shell in the conductance argument is covered, except for +the null grid hyperplanes, by the finite collection of interior cut-face +tubes. No exterior faces or segment general-position hypotheses occur. +-/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory + +variable {I : Type*} [Fintype I] [DecidableEq I] + +abbrev Grid (K : ℕ) := I → Set.Icc (0 : ℤ) ((K : ℤ) - 1) + +def corner {K : ℕ} (a : Grid (I := I) K) : I → ℤ := fun j => (a j).val + +def mixGrid {K : ℕ} (a b : Grid (I := I) K) (S : Finset I) : Grid (I := I) K := + fun j => if j ∈ S then b j else a j + +omit [Fintype I] in +private theorem corner_mix {K : ℕ} (a b : Grid (I := I) K) (S : Finset I) : + corner (mixGrid a b S) = mixed (corner a) (corner b) S := by + ext j + by_cases hj : j ∈ S <;> simp [corner, mixGrid, mixed, hj] + +def Cube (K : ℕ) (x : I → ℝ) : Prop := ∀ j, 0 < x j ∧ x j < (K : ℝ) + +def selectedBins (K : ℕ) (P : (I → ℤ) → Prop) : Set (I → ℝ) := + {x | ∃ a : Grid K, P (corner a) ∧ OpenBin (corner a) x} + +def IsGridEdge {K : ℕ} (p : Grid (I := I) K × Grid (I := I) K × I) : Prop := + corner p.2.1 p.2.2 = corner p.1 p.2.2 + 1 ∧ + ∀ j, j ≠ p.2.2 → p.2.1 j = p.1 j + +abbrev CutEdge (K : ℕ) (P : (I → ℤ) → Prop) := + {p : Grid (I := I) K × Grid (I := I) K × I // + IsGridEdge p ∧ (P (corner p.1) ↔ ¬ P (corner p.2.1))} + +noncomputable instance (K : ℕ) (P : (I → ℤ) → Prop) : Fintype (CutEdge K P) := + Fintype.ofFinite _ + +def edgeTube {K : ℕ} {P : (I → ℤ) → Prop} (e : CutEdge K P) (r : ℝ) : Set (I → ℝ) := + faceTube (corner e.val.1) e.val.2.2 r + +omit [Fintype I] [DecidableEq I] in +theorem openBin_in_cube {K : ℕ} (a : Grid (I := I) K) (x : I → ℝ) + (hx : OpenBin (corner a) x) : Cube K x := by + intro j + have hl : (0 : ℝ) ≤ (corner a j : ℝ) := by exact_mod_cast (a j).property.1 + have hu : (corner a j : ℝ) ≤ (K : ℝ) - 1 := by exact_mod_cast (a j).property.2 + exact ⟨by linarith [(hx j).1], by linarith [(hx j).2]⟩ + +theorem near_finite_cut_tube {K : ℕ} (P : (I → ℤ) → Prop) + (a b : Grid (I := I) K) (x z : I → ℝ) (r : ℝ) + (ha : OpenBin (corner a) x) (hb : OpenBin (corner b) z) + (hd : ∀ j, |z j - x j| < r) (hr : r ≤ 1) + (hPa : P (corner a)) (hPb : ¬ P (corner b)) : + ∃ e : CutEdge K P, z ∈ edgeTube e r := by + classical + obtain ⟨S, i, w, hi, hS, hSi, hadj, hw, hw', hdw⟩ := + near_cut_face P (corner a) (corner b) x z r ha hb hd hr hPa hPb + let u := mixGrid a b S + let v := mixGrid a b (insert i S) + have hui : corner u i = corner a i := by simp [u, corner, mixGrid, hi] + have hvi : corner v i = corner b i := by simp [v, corner, mixGrid] + have hsame (j : I) (hj : j ≠ i) : v j = u j := by simp [v, u, mixGrid, hj] + have hPu : P (corner u) := by simpa [u, corner_mix] using hS + have hPv : ¬ P (corner v) := by simpa [v, corner_mix] using hSi + have hwu : ClosedBin (corner u) w := by simpa [u, corner_mix] using hw + have hwv : ClosedBin (corner v) w := by simpa [v, corner_mix] using hw' + rcases hadj with hab | hab + · have he : corner v i = corner u i + 1 := by rw [hui, hvi]; exact hab + let e : CutEdge K P := ⟨(u, v, i), ⟨he, hsame⟩, by simp [hPu, hPv]⟩ + refine ⟨e, mem_faceTube_of_near (corner u) i r z w hwu ?_ hdw⟩ + have he' : (corner v i : ℝ) = (corner u i : ℝ) + 1 := by exact_mod_cast he + exact le_antisymm (hwu i).2 (by linarith [(hwv i).1]) + · have he : corner u i = corner v i + 1 := by rw [hui, hvi]; exact hab + let e : CutEdge K P := ⟨(v, u, i), ⟨he, fun j hj => (hsame j hj).symm⟩, + by simp [hPu, hPv]⟩ + refine ⟨e, mem_faceTube_of_near (corner v) i r z w hwv ?_ hdw⟩ + have he' : (corner u i : ℝ) = (corner v i : ℝ) + 1 := by exact_mod_cast he + exact le_antisymm (hwv i).2 (by linarith [(hwu i).1]) + +omit [Fintype I] [DecidableEq I] in +private theorem floor_grid {K : ℕ} (z : I → ℝ) (hz : Cube K z) : + ∃ b : Grid (I := I) K, ∀ j, corner b j = ⌊z j⌋ := by + have h (j : I) : ⌊z j⌋ ∈ Set.Icc (0 : ℤ) ((K : ℤ) - 1) := by + refine ⟨Int.floor_nonneg.mpr (hz j).1.le, ?_⟩ + have hlt : ⌊z j⌋ < (K : ℤ) := Int.floor_lt.mpr (by simpa using (hz j).2) + omega + exact ⟨fun j => ⟨⌊z j⌋, h j⟩, fun _ => rfl⟩ + +omit [Fintype I] [DecidableEq I] in +private theorem interpolation_short {K : ℕ} (x y : I → ℝ) (t : ℝ) + (hx : Cube K x) (hy : Cube K y) (ht : 0 < t) (ht₁ : t < 1) : + Cube K (fun j => (1 - t) * x j + t * y j) ∧ + ∀ j, |((1 - t) * x j + t * y j) - x j| < t * K := by + constructor + · intro j + have hxt := mul_pos (sub_pos.mpr ht₁) (hx j).1 + have hyt := mul_pos ht (hy j).1 + have hxu := mul_lt_mul_of_pos_left (hx j).2 (sub_pos.mpr ht₁) + have hyu := mul_lt_mul_of_pos_left (hy j).2 ht + constructor <;> nlinarith + · intro j + have hdiff : |y j - x j| < (K : ℝ) := by + apply abs_lt.mpr + constructor <;> linarith [(hx j).1, (hx j).2, (hy j).1, (hy j).2] + have heq : (1 - t) * x j + t * y j - x j = t * (y j - x j) := by ring + rw [heq, abs_mul, abs_of_pos ht] + exact mul_lt_mul_of_pos_left hdiff ht + +/-- Every shell point off the grid hyperplanes belongs to an interior +cut-face tube. This is the actual cover used by the manuscript. -/ +theorem interpolation_shell_cover {q K : ℕ} (P : (Fin q → ℤ) → Prop) + (t : ℝ) (ht : 0 < t) (ht₁ : t < 1) (hr : t * K ≤ 1) + (z : Fin q → ℝ) + (hz : z ∈ PublishedInputs.interpolate t (selectedBins K P) {y | Cube K y} \ + selectedBins K P) + (hoff : ∀ j (k : ℤ), z j ≠ (k : ℝ)) : + ∃ e : CutEdge K P, z ∈ edgeTube e (t * K) := by + obtain ⟨⟨x, ⟨a, hPa, hax⟩, y, hy, rfl⟩, hnot⟩ := hz + have hx := openBin_in_cube a x hax + obtain ⟨hzCube, hd⟩ := interpolation_short x y t hx hy ht ht₁ + obtain ⟨b, hb⟩ := floor_grid _ hzCube + have hzb : OpenBin (corner b) (fun j => (1 - t) * x j + t * y j) := by + intro j + rw [hb j] + refine ⟨?_, Int.lt_floor_add_one _⟩ + exact lt_of_le_of_ne (Int.floor_le _) (Ne.symm (hoff j _)) + have hPb : ¬ P (corner b) := by + intro hPb + exact hnot ⟨b, hPb, hzb⟩ + exact near_finite_cut_tube P a b x _ (t * K) hax hzb hd hr hPa hPb + +omit [DecidableEq I] in +/-- The only excluded points lie on countably many null hyperplanes. -/ +theorem ae_off_grid : ∀ᵐ z : I → ℝ ∂volume, ∀ j (k : ℤ), z j ≠ (k : ℝ) := by + apply ae_all_iff.mpr + intro j + apply ae_all_iff.mpr + intro k + simpa only [MeasureTheory.volume_pi] using + (MeasureTheory.Measure.ae_eval_ne (fun _ : I => (volume : Measure ℝ)) j (k : ℝ)) + +theorem interpolation_shell_cover_ae {q K : ℕ} (P : (Fin q → ℤ) → Prop) + (t : ℝ) (ht : 0 < t) (ht₁ : t < 1) (hr : t * K ≤ 1) : + ∀ᵐ z ∂volume, z ∈ PublishedInputs.interpolate t (selectedBins K P) {y | Cube K y} \ + selectedBins K P → ∃ e : CutEdge K P, z ∈ edgeTube e (t * K) := by + filter_upwards [ae_off_grid (I := Fin q)] with z hz + exact fun h => interpolation_shell_cover P t ht ht₁ hr z h hz + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridCutFlow.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridCutFlow.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd6b126d6471a2e9c0e7bf2684ab719d3b92a392 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridCutFlow.lean @@ -0,0 +1,122 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridAdjacency +import OAI.Combinatorics.ContingencyTables.Dense.GridMass + +namespace OAI + +/-! # From geometric cut faces to Metropolis cut flow -/ + +namespace ContingencyTables.GridBoundary + +open scoped BigOperators Classical + +noncomputable section + +variable {q K : ℕ} + +private theorem edge_not_reverse (a b : Grid (I := Fin q) K) (i j : Fin q) + (hi : IsGridEdge (a, b, i)) (hj : IsGridEdge (b, a, j)) : False := by + by_cases h : i = j + · subst j + have ha : corner b i = corner a i + 1 := hi.1 + have hb : corner a i = corner b i + 1 := hj.1 + omega + · have heq : corner a i = corner b i := congrArg Subtype.val (hj.2 i h) + have hplus : corner b i = corner a i + 1 := hi.1 + omega + +private theorem cutEdge_eq {Q : (Fin q → ℤ) → Prop} (e f : CutEdge K Q) + (ha : e.val.1 = f.val.1) (hb : e.val.2.1 = f.val.2.1) : e = f := by + have hi : e.val.2.2 = f.val.2.2 := by + apply edge_axis_unique e.val.1 e.val.2.1 _ _ e.property.1 + rw [ha, hb] + exact f.property.1 + apply Subtype.ext + exact Prod.ext ha (Prod.ext hb hi) + +def cutPair (Q : (Fin q → ℤ) → Prop) (e : CutEdge K Q) : + Selected K Q × Selected K (fun a => ¬ Q a) := + if h : Q (corner e.val.1) then + (⟨e.val.1, h⟩, ⟨e.val.2.1, e.property.2.mp h⟩) + else + (⟨e.val.2.1, by + by_contra hn + exact h (e.property.2.mpr hn)⟩, ⟨e.val.1, h⟩) + +theorem cutPair_neighbor (Q : (Fin q → ℤ) → Prop) (e : CutEdge K Q) : + Neighbor (cutPair Q e).1.val (cutPair Q e).2.val := by + unfold cutPair + split_ifs + · exact ⟨e.val.2.2, true, e.property.1⟩ + · exact ⟨e.val.2.2, false, e.property.1⟩ + +theorem cutPair_weight (Q : (Fin q → ℤ) → Prop) (w : Grid (I := Fin q) K → ℝ) + (e : CutEdge K Q) : + min (w (cutPair Q e).1.val) (w (cutPair Q e).2.val) = + min (w e.val.1) (w e.val.2.1) := by + unfold cutPair + split_ifs <;> simp only [min_comm] + +theorem cutPair_injective (Q : (Fin q → ℤ) → Prop) : Function.Injective (cutPair (K := K) Q) := by + intro e f h + have hp := congrArg (fun p : Selected K Q × Selected K (fun a => ¬ Q a) => p.1.val) h + have hn := congrArg (fun p : Selected K Q × Selected K (fun a => ¬ Q a) => p.2.val) h + by_cases he : Q (corner e.val.1) <;> by_cases hf : Q (corner f.val.1) + · simp only [cutPair, dite_eq_left he, dite_eq_left hf] at hp hn + exact cutEdge_eq e f hp hn + · simp only [cutPair, dite_eq_left he, dite_eq_right hf] at hp hn + exfalso + apply edge_not_reverse e.val.1 e.val.2.1 e.val.2.2 f.val.2.2 e.property.1 + rw [hp, hn] + exact f.property.1 + · simp only [cutPair, dite_eq_right he, dite_eq_left hf] at hp hn + exfalso + apply edge_not_reverse e.val.1 e.val.2.1 e.val.2.2 f.val.2.2 e.property.1 + rw [hp, hn] + exact f.property.1 + · simp only [cutPair, dite_eq_right he, dite_eq_right hf] at hp hn + exact cutEdge_eq e f hn hp + +theorem selected_sum_eq_filter (Q : (Fin q → ℤ) → Prop) (f : Grid (I := Fin q) K → ℝ) : + (∑ a : Selected K Q, f a.val) = ∑ a ∈ Finset.univ.filter (fun a => Q (corner a)), f a := by + exact (Finset.sum_subtype (p := fun a : Grid (I := Fin q) K => Q (corner a)) + (F := instFintypeSelected Q) (Finset.univ.filter (fun a => Q (corner a))) + (fun a => by simp) f).symm + +/-- Every geometric cut face contributes its weight once to the actual +ordered cut flow. An injection suffices; no exterior or duplicate face is +counted in the conductance lower bound. -/ +theorem cut_faces_le_neighbor_flow (Q : (Fin q → ℤ) → Prop) + (w : Grid (I := Fin q) K → ℝ) (hw : ∀ a, 0 ≤ w a) : + (∑ e : CutEdge K Q, min (w e.val.1) (w e.val.2.1)) ≤ + ∑ a ∈ Finset.univ.filter (fun a : Grid (I := Fin q) K => Q (corner a)), + ∑ b ∈ Finset.univ.filter (fun b : Grid (I := Fin q) K => ¬ Q (corner b)), + if Neighbor a b then min (w a) (w b) else 0 := by + calc + _ ≤ ∑ p : Selected K Q × Selected K (fun a => ¬ Q a), + if Neighbor p.1.val p.2.val then min (w p.1.val) (w p.2.val) else 0 := by + apply Finset.sum_le_sum_of_injOn (cutPair Q) (cutPair_injective Q).injOn (Finset.subset_univ _) + · intro e _ + rw [ite_eq_left (cutPair_neighbor Q e), cutPair_weight] + · intro p _ _ + split_ifs + · exact le_min (hw _) (hw _) + · exact le_rfl + _ = _ := by + rw [Fintype.sum_prod_type] + change (∑ a : Selected K Q, ∑ b : Selected K (fun a => ¬ Q a), + if Neighbor a.val b.val then min (w a.val) (w b.val) else 0) = _ + rw [selected_sum_eq_filter Q (fun a => ∑ b : Selected K (fun a => ¬ Q a), + if Neighbor a b.val then min (w a) (w b.val) else 0)] + apply Finset.sum_congr rfl + intro a _ + convert selected_sum_eq_filter (fun a => ¬ Q a) + (fun b => if Neighbor a b then min (w a) (w b) else 0) using 1 + congr 1 + ext b + simp + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridIndexProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridIndexProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..03205f714c5d07b30b3020c5c4903dae9840bb7a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridIndexProgram.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGridWords +import OAI.Combinatorics.ContingencyTables.Transport.AxisProposalTest + +namespace OAI + +/-! # Binary indexing into the explicitly enumerated grid -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary +open scoped BigOperators + +abbrev GridIndexData := List ℕ×ℕ + +def gridIndexPowerInput (z : GridIndexData×ℕ) : GridEnumerationData×ℕ := + (((z.1.1.map (fun _ => false)),z.1.2),z.2) + +def gridIndexPowerInputRealizer : Realizer gridIndexPowerInput := + pair (pair (composition (composition first first) (map (constant false))) + (composition first second)) second + +lemma polynomial_gridIndexPowerInput : PolynomialTime gridIndexPowerInputRealizer := + polynomial_pair (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) + (polynomial_map (polynomial_constant false))) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second + +def gridIndexTerm (z : GridIndexData×ℕ) : ℕ := + z.1.1.getD z.2 0*clippedGridPower (gridIndexPowerInput z) + +def gridIndexTermRealizer : Realizer gridIndexTerm := by + let val : Realizer (fun z : GridIndexData×ℕ => z.1.1.getD z.2 0) := + composition (pair (composition first first) second) (getDFast 0) + let power := composition gridIndexPowerInputRealizer clippedGridPowerRealizer + let result := composition (pair val power) multiply + exact result + +lemma polynomial_gridIndexTerm : PolynomialTime gridIndexTermRealizer := by + unfold gridIndexTermRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast 0)) + (polynomial_composition polynomial_gridIndexPowerInput polynomial_clippedGridPower)) + polynomial_multiply + +def gridIndexIndices (z : GridIndexData) : List ℕ := List.range z.1.length + +def gridIndexIndicesRealizer : Realizer gridIndexIndices := + composition (composition first listLength) range + +lemma polynomial_gridIndexIndices : PolynomialTime gridIndexIndicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) + Polynomial.X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.1).trans (weight_fst z) + +def gridIndex (z : GridIndexData) : ℕ := + ((gridIndexIndices z).map (fun i => gridIndexTerm (z,i))).sum + +def gridIndexRealizer : Realizer gridIndex := + composition (composition (pair identity gridIndexIndicesRealizer) + (mapWith gridIndexTermRealizer)) listSum + +/-- Index computation is polynomial in the binary grid coordinates and +base; the exponent loops are bounded by the coordinate list length. -/ +theorem polynomial_gridIndex : PolynomialTime gridIndexRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_identity polynomial_gridIndexIndices) + (polynomial_mapWith polynomial_gridIndexTerm)) polynomial_listSum + +private lemma range_sum (f : ℕ → ℕ) (q : ℕ) : + ((List.range q).map f).sum=∑ j : Fin q,f j.val := by + induction q with + | zero => simp + | succ q ih => + rw [List.sum_range_succ,Fin.sum_univ_castSucc,ih] + rfl + +lemma gridIndex_ofFn {q K : ℕ} (f : Fin q → Fin K) : + gridIndex (List.ofFn (fun i => (f i).val),K)=(finFunctionFinEquiv f).val := by + unfold gridIndex gridIndexIndices + rw [List.length_ofFn,range_sum,finFunctionFinEquiv_apply] + apply Finset.sum_congr rfl + intro i _ + unfold gridIndexTerm gridIndexPowerInput clippedGridPower clippedGridPowerInput + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,List.length_map, + List.length_ofFn,BinaryPowerPrograms.power_eq,dite_true,Option.getD_some] + rw [min_eq_left (Nat.le_of_lt i.isLt)] + +/-- The computed integer is exactly the position used by the state list. -/ +theorem gridIndex_code {q K : ℕ} (a : Grid (I := Fin q) K) : + gridIndex (gridNatCode a,K)=((gridEnumeration q K).symm a).val := by + let f : Fin q → Fin K := fun i => (gridDigitEquiv K).symm (a i) + have hcode : gridNatCode a=List.ofFn (fun i => (f i).val) := rfl + rw [hcode,gridIndex_ofFn] + rfl + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMass.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMass.lean new file mode 100644 index 0000000000000000000000000000000000000000..a612a1051f5c6f6a365f4a3e8b40239c2fffbe30 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMass.lean @@ -0,0 +1,155 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridCover + +namespace OAI + +/-! +# Continuous mass and weighted grid cuts + +Unit bins have disjoint interiors and exact volume one. Their continuous +mass is compared with the discrete weights, and the finite shell cover +converts interpolation gain into a weighted cut-face sum. +-/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators + +variable {q K : ℕ} + +def binSet (a : Grid (I := Fin q) K) : Set (Fin q → ℝ) := + {x | OpenBin (corner a) x} + +def ambientBox (q K : ℕ) : Set (Fin q → ℝ) := + Set.Icc (fun _ => 0) (fun _ => (K : ℝ)) + +abbrev Selected (K : ℕ) (P : (Fin q → ℤ) → Prop) := + {a : Grid (I := Fin q) K // P (corner a)} + +noncomputable instance (P : (Fin q → ℤ) → Prop) : Fintype (Selected K P) := + Fintype.ofFinite _ + +private theorem binSet_pi (a : Grid (I := Fin q) K) : + binSet a = Set.pi Set.univ (fun j => Set.Ioo (corner a j : ℝ) ((corner a j : ℝ) + 1)) := by + ext x + simp [binSet, OpenBin] + +theorem binSet_measurable (a : Grid (I := Fin q) K) : MeasurableSet (binSet a) := by + rw [binSet_pi] + exact MeasurableSet.univ_pi fun _ => measurableSet_Ioo + +theorem binSet_volume (a : Grid (I := Fin q) K) : volume (binSet a) = 1 := by + rw [binSet_pi, Real.volume_pi_Ioo] + simp + +theorem binSet_disjoint (a b : Grid (I := Fin q) K) (hab : a ≠ b) : + Disjoint (binSet a) (binSet b) := by + apply Set.disjoint_left.mpr + intro x hax hbx + apply hab + funext j + apply Subtype.ext + have ha : ⌊x j⌋ = corner a j := Int.floor_eq_iff.mpr ⟨(hax j).1.le, (hax j).2⟩ + have hb : ⌊x j⌋ = corner b j := Int.floor_eq_iff.mpr ⟨(hbx j).1.le, (hbx j).2⟩ + exact ha.symm.trans hb + +theorem binSet_subset_ambient (a : Grid (I := Fin q) K) : binSet a ⊆ ambientBox q K := by + intro x hx + have h := openBin_in_cube a x hx + exact ⟨fun j => (h j).1.le, fun j => (h j).2.le⟩ + +theorem selectedBins_finiteBox (P : (Fin q → ℤ) → Prop) : + PublishedInputs.IsFiniteBoxUnion (selectedBins K P) := by + classical + let e := (Fintype.equivFin (Selected K P)).symm + refine ⟨Fintype.card (Selected K P), (fun k j => (corner (e k).val j : ℝ)), + (fun k j => (corner (e k).val j : ℝ) + 1), ?_⟩ + ext x + constructor + · rintro ⟨a, ha, hx⟩ + exact ⟨e.symm ⟨a, ha⟩, by simpa [OpenBin] using hx⟩ + · rintro ⟨k, hk⟩ + exact ⟨(e k).val, (e k).property, hk⟩ + +theorem cube_finiteBox : PublishedInputs.IsFiniteBoxUnion {x : Fin q → ℝ | Cube K x} := by + refine ⟨1, (fun _ _ => 0), (fun _ _ => (K : ℝ)), ?_⟩ + ext x + simp [Cube] + +theorem selectedBins_closure (P : (Fin q → ℤ) → Prop) : + closure (selectedBins K P) ⊆ ambientBox q K := by + apply isClosed_Icc.closure_subset_iff.mpr + rintro x ⟨a, _, hx⟩ + exact binSet_subset_ambient a hx + +theorem cube_closure : closure {x : Fin q → ℝ | Cube K x} ⊆ ambientBox q K := by + apply isClosed_Icc.closure_subset_iff.mpr + intro x hx + exact ⟨fun j => (hx j).1.le, fun j => (hx j).2.le⟩ + +theorem selectedBins_integral (P : (Fin q → ℤ) → Prop) (ρ : (Fin q → ℝ) → ℝ) + (hi : IntegrableOn ρ (ambientBox q K)) : + (∫ x in selectedBins K P, ρ x) = ∑ a : Selected K P, ∫ x in binSet a.val, ρ x := by + have heq : selectedBins K P = ⋃ a : Selected K P, binSet a.val := by + ext x + simp only [selectedBins, binSet, Set.mem_ofPred_eq, Set.mem_iUnion] + constructor + · rintro ⟨a, ha, hx⟩ + exact ⟨⟨a, ha⟩, hx⟩ + · rintro ⟨a, hx⟩ + exact ⟨a.val, a.property, hx⟩ + rw [heq] + apply integral_iUnion_fintype + · exact fun a => binSet_measurable a.val + · intro a b hab + exact binSet_disjoint a.val b.val (fun h => hab (Subtype.ext h)) + · exact fun a => hi.mono_set (binSet_subset_ambient a.val) + +/-- The selected side has at least one quarter of its own discrete mass; +it need not be the smaller side for the discrete weights. -/ +theorem selectedBins_mass_lower (P : (Fin q → ℤ) → Prop) (ρ : (Fin q → ℝ) → ℝ) + (w : Grid (I := Fin q) K → ℝ) (hi : IntegrableOn ρ (ambientBox q K)) + (hbin : ∀ a x, x ∈ binSet a → w a / 4 ≤ ρ x) : + (∑ a : Selected K P, w a.val) / 4 ≤ ∫ x in selectedBins K P, ρ x := by + rw [selectedBins_integral P ρ hi, Finset.sum_div] + apply Finset.sum_le_sum + intro a _ + have h := setIntegral_ge_of_const_le_real (binSet_measurable a.val) + (show volume (binSet a.val) ≠ ⊤ by rw [binSet_volume]; simp) + (hbin a.val) (hi.mono_set (binSet_subset_ambient a.val)) + simpa [Measure.real, binSet_volume] using h + +theorem edgeTube_mass_upper (P : (Fin q → ℤ) → Prop) (e : CutEdge K P) + (r : ℝ) (hr : 0 ≤ r) (hr₁ : r ≤ 1 / 4) + (hsize : (q - 1 : ℕ) * (2 * r) ≤ (1 / 2 : ℝ)) + (ρ : (Fin q → ℝ) → ℝ) (w : Grid (I := Fin q) K → ℝ) + (hw : ∀ a, 0 ≤ w a) (hi : IntegrableOn ρ (ambientBox q K)) + (hbound : ∀ x, x ∈ edgeTube e r ∩ {x | Cube K x} → + ρ x ≤ 4 * min (w e.val.1) (w e.val.2.1)) : + (∫ x in edgeTube e r ∩ {x | Cube K x}, ρ x) ≤ + 4 * min (w e.val.1) (w e.val.2.1) := by + let E := edgeTube e r ∩ {x | Cube K x} + have hE : MeasurableSet E := (faceTube_measurable _ _ _).inter + (cube_finiteBox (q := q) (K := K)).isOpen.measurableSet + have hsub : E ⊆ ambientBox q K := fun x hx => + ⟨fun j => (hx.2 j).1.le, fun j => (hx.2 j).2.le⟩ + have hfin : volume (edgeTube e r) ≠ ⊤ := by + rw [edgeTube, faceTube_volume _ _ _ hr] + exact ENNReal.ofReal_ne_top + have hfinE : volume E ≠ ⊤ := ne_top_of_le_ne_top hfin (measure_mono Set.inter_subset_left) + have hvol : (volume E).toReal ≤ 1 := by + calc + _ ≤ (volume (edgeTube e r)).toReal := ENNReal.toReal_mono hfin + (measure_mono Set.inter_subset_left) + _ ≤ 1 := by + exact faceTube_volume_le_one (corner e.val.1) e.val.2.2 r hr hr₁ (by simpa using hsize) + have hb := setIntegral_mono_on (hi.mono_set hsub) + (integrableOn_const hfinE) hE hbound + rw [setIntegral_const, smul_eq_mul] at hb + have hw' : 0 ≤ 4 * min (w e.val.1) (w e.val.2.1) := + mul_nonneg (by norm_num) (le_min (hw _) (hw _)) + exact hb.trans (by simpa [Measure.real] using mul_le_mul_of_nonneg_right hvol hw') + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMeasure.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMeasure.lean new file mode 100644 index 0000000000000000000000000000000000000000..953930815274a87b485c792853577236152b8381 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMeasure.lean @@ -0,0 +1,148 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridBoundary +import Mathlib.MeasureTheory.Measure.Lebesgue.Basic +import Mathlib.MeasureTheory.Integral.Bochner.Set +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +namespace OAI + +/-! +# Volume and mass of grid face neighbourhoods + +The exact tube volume and a finite integral-cover bound used to turn the +interpolation shell gain into a weighted cut estimate. +-/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators + +variable {I : Type*} [Fintype I] [DecidableEq I] + +def tubeLower (a : I → ℤ) (i : I) (r : ℝ) : I → ℝ := + fun j => if j = i then (a j : ℝ) + 1 - r else (a j : ℝ) - r + +def tubeUpper (a : I → ℤ) (_i : I) (r : ℝ) : I → ℝ := + fun j => (a j : ℝ) + 1 + r + +/-- An open rectangular neighbourhood of the positive `i`-face of a bin. -/ +def faceTube (a : I → ℤ) (i : I) (r : ℝ) : Set (I → ℝ) := + Set.pi Set.univ fun j => Set.Ioo (tubeLower a i r j) (tubeUpper a i r j) + +theorem faceTube_measurable (a : I → ℤ) (i : I) (r : ℝ) : + MeasurableSet (faceTube a i r) := by + exact MeasurableSet.univ_pi fun _ => measurableSet_Ioo + +omit [Fintype I] in +private theorem tube_width (a : I → ℤ) (i j : I) (r : ℝ) : + tubeUpper a i r j - tubeLower a i r j = if j = i then 2 * r else 1 + 2 * r := by + by_cases h : j = i <;> simp [tubeUpper, tubeLower, h] <;> ring + +private theorem product_one_exception (u v : ℝ) (i : I) : + (∏ j : I, if j = i then u else v) = u * v ^ (Fintype.card I - 1) := by + have heq : (fun j : I => if j = i then u else v) = Function.update (fun _ => v) i u := by + ext j + by_cases hj : j = i <;> simp [hj] + rw [heq, Finset.prod_update_of_mem (Finset.mem_univ i)] + simp [Finset.sdiff_singleton_eq_erase] + +theorem faceTube_volume (a : I → ℤ) (i : I) (r : ℝ) (hr : 0 ≤ r) : + volume (faceTube a i r) = + ENNReal.ofReal (2 * r * (1 + 2 * r) ^ (Fintype.card I - 1)) := by + rw [faceTube, Real.volume_pi_Ioo] + simp_rw [tube_width] + rw [← ENNReal.ofReal_prod_of_nonneg] + · rw [product_one_exception] + · intro j _ + split_ifs <;> positivity + +theorem faceTube_volume_toReal (a : I → ℤ) (i : I) (r : ℝ) (hr : 0 ≤ r) : + (volume (faceTube a i r)).toReal = + 2 * r * (1 + 2 * r) ^ (Fintype.card I - 1) := by + rw [faceTube_volume a i r hr, ENNReal.toReal_ofReal (by positivity)] + +private theorem reverse_bernoulli (u : ℝ) (hu : 0 ≤ u) (n : ℕ) : + (1 + u) ^ n * (1 - (n : ℝ) * u) ≤ 1 := by + induction n with + | zero => simp + | succ n ih => + have haux : (1 + u) * (1 - ((n : ℝ) + 1) * u) ≤ 1 - (n : ℝ) * u := by + have h := mul_nonneg (show 0 ≤ (n : ℝ) + 1 by positivity) (sq_nonneg u) + nlinarith + calc + (1 + u) ^ (n + 1) * (1 - ((n + 1 : ℕ) : ℝ) * u) = + (1 + u) ^ n * ((1 + u) * (1 - ((n : ℝ) + 1) * u)) := by + rw [pow_succ, Nat.cast_add, Nat.cast_one] + ring + _ ≤ (1 + u) ^ n * (1 - (n : ℝ) * u) := + mul_le_mul_of_nonneg_left haux (pow_nonneg (by linarith) _) + _ ≤ 1 := ih + +/-- The manuscript's tube-volume bound follows without an exponential +estimate: the relevant power is at most two by reverse Bernoulli. -/ +theorem faceTube_volume_le_one (a : I → ℤ) (i : I) (r : ℝ) + (hr : 0 ≤ r) (hr₁ : r ≤ 1 / 4) + (hsize : (Fintype.card I - 1 : ℕ) * (2 * r) ≤ (1 / 2 : ℝ)) : + (volume (faceTube a i r)).toReal ≤ 1 := by + rw [faceTube_volume_toReal a i r hr] + have hpow := pow_nonneg (show 0 ≤ 1 + 2 * r by linarith) (Fintype.card I - 1) + have hbern := reverse_bernoulli (2 * r) (by linarith) (Fintype.card I - 1) + have htwo : (1 + 2 * r) ^ (Fintype.card I - 1) ≤ 2 := by nlinarith + nlinarith + +omit [Fintype I] in +/-- A point near the positive face belongs to its rectangular tube. -/ +theorem mem_faceTube_of_near (a : I → ℤ) (i : I) (r : ℝ) (z w : I → ℝ) + (hw : ClosedBin a w) (hwi : w i = (a i : ℝ) + 1) + (hd : ∀ j, |z j - w j| < r) : z ∈ faceTube a i r := by + intro j _ + have h := abs_lt.mp (hd j) + by_cases hj : j = i + · subst j + simp only [tubeLower, tubeUpper, ite_true] + rw [hwi] at h + constructor <;> linarith + · simp only [tubeLower, tubeUpper, hj, ite_false] + have hwj := hw j + constructor <;> linarith + +end ContingencyTables.GridBoundary + +namespace ContingencyTables + +open MeasureTheory +open scoped BigOperators + +/-- Integrating a finite cover, allowing overlap and a null exceptional set. +This applies to the face tubes after removing grid hyperplanes. -/ +theorem integral_finite_cover {X K : Type*} [MeasurableSpace X] [Fintype K] + {μ : Measure X} (S : Set X) (E : K → Set X) (ρ : X → ℝ) + (hS : MeasurableSet S) (hE : ∀ k, MeasurableSet (E k)) + (hiS : IntegrableOn ρ S μ) (hiE : ∀ k, IntegrableOn ρ (E k) μ) + (hpos : ∀ k x, x ∈ E k → 0 ≤ ρ x) + (hcover : ∀ᵐ x ∂μ, x ∈ S → ∃ k, x ∈ E k) : + (∫ x in S, ρ x ∂μ) ≤ ∑ k, ∫ x in E k, ρ x ∂μ := by + classical + have hterm (k : K) (x : X) : 0 ≤ (E k).indicator ρ x := by + by_cases hx : x ∈ E k + · simpa [hx] using hpos k x hx + · simp [hx] + have hmono : S.indicator ρ ≤ᵐ[μ] fun x => ∑ k, (E k).indicator ρ x := by + filter_upwards [hcover] with x hx + by_cases hxS : x ∈ S + · obtain ⟨k, hk⟩ := hx hxS + simpa [hxS, hk] using + (Finset.single_le_sum (fun j _ => hterm j x) (Finset.mem_univ k)) + · simpa [hxS] using Finset.sum_nonneg (fun k _ => hterm k x) + have hint (k : K) : Integrable ((E k).indicator ρ) μ := + (hiE k).integrable_indicator (hE k) + have hbound := integral_mono_ae (hiS.integrable_indicator hS) + (integrable_finsetSum Finset.univ fun k _ => hint k) hmono + rw [integral_indicator hS, integral_finsetSum Finset.univ (fun k _ => hint k)] at hbound + simpa only [integral_indicator (hE _)] using hbound + +end ContingencyTables + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMetropolis.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMetropolis.lean new file mode 100644 index 0000000000000000000000000000000000000000..916f28332481e647df8daaef24af45594102d590 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMetropolis.lean @@ -0,0 +1,65 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridAdjacency +import OAI.Combinatorics.ContingencyTables.Transport.MetropolisChain +import Mathlib.Data.Nat.Log + +namespace OAI + +/-! # The actual dyadic axis-proposal chain -/ + +namespace ContingencyTables.GridBoundary + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +def binProposal (d : ℕ) : ℝ := 1 / (2 : ℝ) ^ Nat.clog 2 (8 * d) + +theorem binProposal_bounds (d : ℕ) (hd : 14 ≤ d) : + 0 < binProposal d ∧ 1 / (16 * (d : ℝ)) ≤ binProposal d ∧ + binProposal d ≤ 1 / (8 * (d : ℝ)) := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hn : 1 < 8 * d := by omega + have hlow := Nat.le_pow_clog (by decide : 1 < 2) (8 * d) + have hpred := Nat.pow_pred_clog_lt_self (by decide : 1 < 2) hn + have hpos := Nat.clog_pos (by decide : 1 < 2) hn + have hupp : 2 ^ Nat.clog 2 (8 * d) ≤ 16 * d := by + have heq : 2 ^ Nat.clog 2 (8 * d) = 2 ^ (Nat.clog 2 (8 * d)).pred * 2 := by + conv_lhs => rw [← Nat.succ_pred_eq_of_pos hpos] + exact pow_succ _ _ + rw [heq] + omega + have hlow' : 8 * (d : ℝ) ≤ (2 : ℝ) ^ Nat.clog 2 (8 * d) := by exact_mod_cast hlow + have hupp' : (2 : ℝ) ^ Nat.clog 2 (8 * d) ≤ 16 * (d : ℝ) := by exact_mod_cast hupp + refine ⟨by unfold binProposal; positivity, ?_, ?_⟩ + · exact one_div_le_one_div_of_le (by positivity) hupp' + · exact one_div_le_one_div_of_le (by positivity) hlow' + +theorem binProposal_degree (q d : ℕ) (hd : 14 ≤ d) (hq : q ≤ d) : + ((2 * q : ℕ) : ℝ) * binProposal d ≤ 1 / 4 := by + have hd₀ : (0 : ℝ) < d := by exact_mod_cast (show 0 < d by omega) + have hqd : (q : ℝ) ≤ d := by exact_mod_cast hq + have hb := binProposal_bounds d hd + calc + _ ≤ (2 * (q : ℝ)) * (1 / (8 * (d : ℝ))) := by + push_cast + exact mul_le_mul_of_nonneg_left hb.2.2 (by positivity) + _ ≤ (2 * (d : ℝ)) * (1 / (8 * (d : ℝ))) := by gcongr + _ = 1 / 4 := by field_simp; ring + +def gridChain {q K : ℕ} (d : ℕ) (hd : 14 ≤ d) (hq : q ≤ d) (hK : 1 ≤ K) + (w : Grid (I := Fin q) K → ℝ) (hw : ∀ a, 0 < w a) : FiniteChain (Grid (I := Fin q) K) := by + letI : Nonempty (Grid (I := Fin q) K) := ⟨fun _ => ⟨0, by constructor <;> omega⟩⟩ + exact MetropolisChain.chain w hw Neighbor neighbor_symm (binProposal d) + (binProposal_bounds d hd).1.le (2 * q) (fun a => by simpa using neighbor_degree a) + ((binProposal_degree q d hd hq).trans (by norm_num)) + +theorem gridChain_pi {q K : ℕ} (d : ℕ) (hd : 14 ≤ d) (hq : q ≤ d) (hK : 1 ≤ K) + (w : Grid (I := Fin q) K → ℝ) (hw : ∀ a, 0 < w a) (a : Grid (I := Fin q) K) : + (gridChain d hd hq hK w hw).π a = w a / (∑ b, w b) := rfl + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMinCut.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMinCut.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a015f065c4e3fcc199c8d64b729c0a88ca443bc --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridMinCut.lean @@ -0,0 +1,139 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridConductance +import OAI.Combinatorics.ContingencyTables.Dense.GridPartition +import OAI.Combinatorics.ContingencyTables.Dense.DenseGrid +import OAI.Combinatorics.ContingencyTables.Dense.DenseCutParameters + +namespace OAI + +/-! +# Every nontrivial cut of the actual dense grid + +Choosing the smaller continuous side and then comparing its own discrete +mass gives a lower bound using the smaller discrete side. No assumption +identifying those two choices is made. +-/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators Classical + +noncomputable section + +variable {q K : ℕ} + +def cutComplementEquiv (Q : (Fin q → ℤ) → Prop) : + CutEdge K Q ≃ CutEdge K (fun a => ¬ Q a) where + toFun e := ⟨e.val, e.property.1, not_congr e.property.2⟩ + invFun e := ⟨e.val, e.property.1, by simpa only [not_not] using not_congr e.property.2⟩ + left_inv e := Subtype.ext rfl + right_inv e := Subtype.ext rfl + +theorem cut_complement_sum (Q : (Fin q → ℤ) → Prop) (w : Grid (I := Fin q) K → ℝ) : + (∑ e : CutEdge K Q, min (w e.val.1) (w e.val.2.1)) = + ∑ e : CutEdge K (fun a => ¬ Q a), min (w e.val.1) (w e.val.2.1) := by + exact Fintype.sum_equiv (cutComplementEquiv Q) _ _ (fun _ => rfl) + +theorem weighted_min_cut (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) + (Q : (Fin q → ℤ) → Prop) (t : ℝ) (ht : 0 < t) (ht₁ : t < 1) + (hr : t * K ≤ 1 / 4) (hsize : (q - 1 : ℕ) * (2 * (t * K)) ≤ (1 / 2 : ℝ)) + (ρ : (Fin q → ℝ) → ℝ) (w : Grid (I := Fin q) K → ℝ) + (hw : ∀ a, 0 < w a) (hρ : ContinuousOn ρ (ambientBox q K)) + (hpos : ∀ x ∈ ambientBox q K, 0 < ρ x) + (hlc : PublishedInputs.LogConcaveOn ρ (ambientBox q K)) + (hbin : ∀ a x, x ∈ binSet a → w a / 4 ≤ ρ x) + (htube : ∀ (edge : CutEdge K Q) x, + x ∈ edgeTube edge (t * K) ∩ {x | Cube K x} → + ρ x ≤ 4 * min (w edge.val.1) (w edge.val.2.1)) + (hne : Nonempty (Selected K Q)) (hne' : Nonempty (Selected K (fun a => ¬ Q a))) : + (((2 : ℝ) ^ t - 1) / 16) * + min (∑ a : Selected K Q, w a.val) (∑ a : Selected K (fun b => ¬ Q b), w a.val) ≤ + ∑ edge : CutEdge K Q, min (w edge.val.1) (w edge.val.2.1) := by + have hi : IntegrableOn ρ (ambientBox q K) := hρ.integrableOn_Icc + have hsum := selected_complement_integral Q ρ hi + have hc : 0 ≤ ((2 : ℝ) ^ t - 1) / 16 := by + have hg := two_rpow_gain t ht.le + exact div_nonneg ((show (0 : ℝ) ≤ t / 2 by positivity).trans hg) (by norm_num) + by_cases hcut : 2 * (∫ x in selectedBins K Q, ρ x) ≤ ∫ x in {x | Cube K x}, ρ x + · calc + _ ≤ (((2 : ℝ) ^ t - 1) / 16) * (∑ a : Selected K Q, w a.val) := + mul_le_mul_of_nonneg_left (min_le_left _ _) hc + _ ≤ _ := weighted_cut_of_interpolation hPL Q t ht ht₁ hr hsize ρ w + (fun a => (hw a).le) hρ hpos hlc hbin htube + (selected_mass_positive Q ρ w hw hi hbin hne) hcut + · have hcut' : 2 * (∫ x in selectedBins K (fun a => ¬ Q a), ρ x) ≤ + ∫ x in {x | Cube K x}, ρ x := by linarith + have htube' (edge : CutEdge K (fun a => ¬ Q a)) (x : Fin q → ℝ) + (hx : x ∈ edgeTube edge (t * K) ∩ {x | Cube K x}) : + ρ x ≤ 4 * min (w edge.val.1) (w edge.val.2.1) := + htube ((cutComplementEquiv Q).symm edge) x hx + calc + _ ≤ (((2 : ℝ) ^ t - 1) / 16) * (∑ a : Selected K (fun b => ¬ Q b), w a.val) := + mul_le_mul_of_nonneg_left (min_le_right _ _) hc + _ ≤ ∑ edge : CutEdge K (fun a => ¬ Q a), min (w edge.val.1) (w edge.val.2.1) := + weighted_cut_of_interpolation hPL (fun a => ¬ Q a) t ht ht₁ hr hsize ρ w + (fun a => (hw a).le) hρ hpos hlc hbin htube' + (selected_mass_positive (fun a => ¬ Q a) ρ w hw hi hbin hne') hcut' + _ = _ := (cut_complement_sum Q w).symm + +variable {I J : Type*} [Fintype I] [Fintype J] [DecidableEq I] [DecidableEq J] + +/-- The actual dense sampler's dyadic weights satisfy every nontrivial +cut bound, with the manuscript interpolation parameter. -/ +theorem denseGrid_min_cut (R : Option I → ℕ) (P : Option J → ℕ) + (d : ℕ) (hd : 14 ≤ d) (hR : ∀ i, d ^ 12 ≤ R i) (hP : ∀ j, d ^ 12 ≤ P j) + (hRmax : ∀ i, R (some i) ≤ R none) (hPmax : ∀ j, P (some j) ≤ P none) + (hfree : Fintype.card (I × J) ≤ d) (e : I × J ≃ Fin q) + (hPL : PublishedInputs.FiniteBoxPrekopaLeindler q) (hK : 1 ≤ K) + (Q : (Fin q → ℤ) → Prop) + (hne : Nonempty (Selected K Q)) (hne' : Nonempty (Selected K (fun a => ¬ Q a))) : + (1 / (128 * (d : ℝ) * K)) * min + (∑ a : Selected K Q, DenseWeights.binWeight ((d : ℝ) ^ 4) + (denseGridPenalty R P d e) (realCorner a.val)) + (∑ a : Selected K (fun b => ¬ Q b), DenseWeights.binWeight ((d : ℝ) ^ 4) + (denseGridPenalty R P d e) (realCorner a.val)) ≤ + ∑ edge : CutEdge K Q, min + (DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner edge.val.1)) + (DenseWeights.binWeight ((d : ℝ) ^ 4) (denseGridPenalty R P d e) (realCorner edge.val.2.1)) := by + let p := denseGridPenalty R P d e + let w := fun a : Grid (I := Fin q) K => DenseWeights.binWeight ((d : ℝ) ^ 4) p (realCorner a) + let ρ := DenseWeights.density ((d : ℝ) ^ 4) p + have hq : q ≤ d := by + have hc := Fintype.card_congr e + rw [Fintype.card_fin] at hc + omega + obtain ⟨ht, ht₁, hr, hsize⟩ := denseInterpolation_bounds d K q hd hK hq + have hbound := weighted_min_cut hPL Q (denseInterpolation d K) ht ht₁ hr hsize ρ w + (fun a => DenseWeights.binWeight_pos _ _ _) + ((DenseWeights.density_continuous _ _ (denseGridPenalty_continuous R P d e)).continuousOn) + (fun x _ => DenseWeights.density_pos _ _ _) (fun x _ y _ t ht ht₁ => + DenseWeights.density_logConcave _ (by positivity) _ Set.univ + (denseGridPenalty_convex R P d e) x (Set.mem_univ _) y (Set.mem_univ _) t ht ht₁) + (fun a x hx => (denseGrid_bin_comparison R P d hd hR hP hRmax hPmax hfree e a x + (fun j => ⟨(hx j).1.le, (hx j).2.le⟩)).1) + (fun edge x hx => denseGrid_tube_comparison R P d hd hR hP hRmax hPmax hfree e edge + (denseInterpolation d K * K) (mul_nonneg ht.le (Nat.cast_nonneg _)) (by linarith) x hx.1) + hne hne' + have hs : 0 ≤ min (∑ a : Selected K Q, w a.val) + (∑ a : Selected K (fun b => ¬ Q b), w a.val) := by + apply le_min <;> exact Finset.sum_nonneg (fun a _ => (DenseWeights.binWeight_pos _ _ _).le) + have hgain := two_rpow_gain (denseInterpolation d K) ht.le + have hd₀ : (d : ℝ) ≠ 0 := by exact_mod_cast (show d ≠ 0 by omega) + have hK₀ : (K : ℝ) ≠ 0 := by exact_mod_cast (show K ≠ 0 by omega) + calc + _ = (denseInterpolation d K / 32) * min + (∑ a : Selected K Q, w a.val) (∑ a : Selected K (fun b => ¬ Q b), w a.val) := by + unfold denseInterpolation + congr 1 + field_simp [hd₀, hK₀] + norm_num + _ ≤ (((2 : ℝ) ^ denseInterpolation d K - 1) / 16) * min + (∑ a : Selected K Q, w a.val) (∑ a : Selected K (fun b => ¬ Q b), w a.val) := + mul_le_mul_of_nonneg_right (by linarith) hs + _ ≤ _ := hbound + +end + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/GridPartition.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridPartition.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8f51468517a31d33d3252d74f72f7a1ca9df15b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/GridPartition.lean @@ -0,0 +1,82 @@ +import OAI.Combinatorics.ContingencyTables.Dense.GridMass + +namespace OAI + +/-! +# Partition of cube mass by the finite bins + +The union misses only grid hyperplanes. Thus a predicate and its complement +have continuous masses summing to the cube mass, which lets the conductance +argument select the smaller continuous side. +-/ + +namespace ContingencyTables.GridBoundary + +open MeasureTheory +open scoped BigOperators + +variable {q K : ℕ} + +theorem cube_ae_all_bins : + {x : Fin q → ℝ | Cube K x} =ᵐ[volume] selectedBins K (fun _ => True) := by + filter_upwards [ae_off_grid (I := Fin q)] with x hoff + apply propext + constructor + · intro hx + have hb (j : Fin q) : ⌊x j⌋ ∈ Set.Icc (0 : ℤ) ((K : ℤ) - 1) := by + refine ⟨Int.floor_nonneg.mpr (hx j).1.le, ?_⟩ + have hlt : ⌊x j⌋ < (K : ℤ) := Int.floor_lt.mpr (by simpa using (hx j).2) + omega + refine ⟨(fun j => ⟨⌊x j⌋, hb j⟩), trivial, ?_⟩ + intro j + exact ⟨lt_of_le_of_ne (Int.floor_le _) (Ne.symm (hoff j _)), Int.lt_floor_add_one _⟩ + · rintro ⟨a, _, ha⟩ + exact openBin_in_cube a x ha + +theorem cube_integral_bins (ρ : (Fin q → ℝ) → ℝ) + (hi : IntegrableOn ρ (ambientBox q K)) : + (∫ x in {x | Cube K x}, ρ x) = + ∑ a : Grid (I := Fin q) K, ∫ x in binSet a, ρ x := by + rw [setIntegral_congr_set cube_ae_all_bins, selectedBins_integral _ ρ hi] + simpa only using + (Finset.sum_subtype Finset.univ (fun _ => by simp) + (fun a : Grid (I := Fin q) K => ∫ x in binSet a, ρ x)).symm + +theorem selected_complement_integral (Q : (Fin q → ℤ) → Prop) + (ρ : (Fin q → ℝ) → ℝ) (hi : IntegrableOn ρ (ambientBox q K)) : + (∫ x in selectedBins K Q, ρ x) + + (∫ x in selectedBins K (fun a => ¬ Q a), ρ x) = + ∫ x in {x | Cube K x}, ρ x := by + classical + rw [selectedBins_integral Q ρ hi, selectedBins_integral (fun a => ¬ Q a) ρ hi, + cube_integral_bins ρ hi] + have hQ (Q : (Fin q → ℤ) → Prop) : + (∑ a : Selected K Q, ∫ x in binSet a.val, ρ x) = + ∑ a ∈ Finset.univ.filter (fun a : Grid (I := Fin q) K => Q (corner a)), + ∫ x in binSet a, ρ x := by + exact (Finset.sum_subtype (p := fun a : Grid (I := Fin q) K => Q (corner a)) + (F := instFintypeSelected Q) + (Finset.univ.filter (fun a : Grid (I := Fin q) K => Q (corner a))) + (fun a => by simp) (fun a => ∫ x in binSet a, ρ x)).symm + rw [hQ Q, hQ (fun a => ¬ Q a)] + rw [Finset.sum_filter, Finset.sum_filter, ← Finset.sum_add_distrib] + apply Finset.sum_congr rfl + intro a _ + by_cases h : Q (corner a) <;> simp [h] + +theorem selected_mass_positive (Q : (Fin q → ℤ) → Prop) + (ρ : (Fin q → ℝ) → ℝ) (w : Grid (I := Fin q) K → ℝ) + (hw : ∀ a, 0 < w a) (hi : IntegrableOn ρ (ambientBox q K)) + (hbin : ∀ a x, x ∈ binSet a → w a / 4 ≤ ρ x) + (hne : Nonempty (Selected K Q)) : 0 < ∫ x in selectedBins K Q, ρ x := by + have hs : 0 < ∑ a : Selected K Q, w a.val := by + obtain ⟨a⟩ := hne + apply Finset.sum_pos' + · intro b _ + exact (hw b.val).le + · exact ⟨a, Finset.mem_univ _, hw a.val⟩ + exact (div_pos hs (by norm_num)).trans_le (selectedBins_mass_lower Q ρ w hi hbin) + +end ContingencyTables.GridBoundary + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Dense/PublishedCheeger.lean b/lean/OAI/Combinatorics/ContingencyTables/Dense/PublishedCheeger.lean new file mode 100644 index 0000000000000000000000000000000000000000..56709c3e76502b649ab87530216b415a65a4e8eb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Dense/PublishedCheeger.lean @@ -0,0 +1,41 @@ +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! +# The published finite-chain Cheeger input + +Levin and Peres, *Markov Chains and Mixing Times*, second edition (2017), +Theorem 13.10, equation (13.6), lower bound, together with the variational +characterization in Lemma 13.7. The theorem is attributed there to Sinclair +and Jerrum (1989) and Lawler and Sokal (1988). +Source: https://pages.uoregon.edu/dlevin/MARKOV/markovmixing.pdf + +The finite reversible lazy-chain Poincaré consequence is expressed using +stationary cut flow and the symmetric Dirichlet energy. +-/ + +namespace ContingencyTables.PublishedInputs + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +variable (X : Type*) [Fintype X] + +/-- The smallest Cheeger consequence needed here. The cut inequality uses +unnormalized stationary flow across each cut once; `energy` includes the +usual factor one half in its symmetric pair-sum formula. -/ +def FiniteCheeger : Prop := + ∀ (C : FiniteChain X) (κ : ℝ), 0 < κ → + (∀ S : Finset X, + κ * min (∑ x ∈ S, C.π x) (∑ x ∈ Sᶜ, C.π x) ≤ + ∑ x ∈ S, ∑ y ∈ Sᶜ, C.π x * C.P x y) → + ∀ f : X → ℝ, C.variance f ≤ (2 / κ ^ 2) * C.energy f + +end + +end ContingencyTables.PublishedInputs + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/FactorialLift.lean b/lean/OAI/Combinatorics/ContingencyTables/FactorialLift.lean new file mode 100644 index 0000000000000000000000000000000000000000..c82e7ef13670eb099380accfbbaf21e7a4dd5866 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/FactorialLift.lean @@ -0,0 +1,141 @@ +import Mathlib.LinearAlgebra.Eigenspace.Basic +import Mathlib.LinearAlgebra.Matrix.ToLin +import Mathlib.LinearAlgebra.Matrix.Symmetric +import Mathlib.Analysis.Real.Sqrt +import Mathlib.Tactic.FinCases +import Mathlib.Tactic.NormNum +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity +import Mathlib.Tactic.Ring + +namespace OAI +/-! +# A finite factorial-lift counterexample + +The ten labels are the first cell's rows 0, 1, 2 and columns 3, 4, 5, +and the second cell's rows 6, 7 and columns 8, 9. Conditioning on the +first three rows gives a symmetric addition matrix with two distinct +positive eigenvalues. This finite counterexample does not formalize a +randomized approximation algorithm for contingency tables. +-/ +noncomputable section + +namespace DistinctLifts + +abbrev Label := Fin 10 +abbrev Remaining := Fin 7 + +def count (S : Finset Label) (lo hi : ℕ) : ℕ := + (S.filter fun i => lo ≤ i.val ∧ i.val < hi).card +/-- The factorial lift for capacities 3 and 2, with constant weight one. +It is defined on all sets here and subsequently restricted to 5-subsets. -/ +def factorialLift (S : Finset Label) : ℝ := + ((count S 0 3).factorial : ℝ) * (count S 3 6).factorial / (3 : ℕ).factorial * + (((count S 6 8).factorial : ℝ) * (count S 8 10).factorial / (2 : ℕ).factorial) + +def fixed : Finset Label := {0, 1, 2} +def remaining (i : Remaining) : Label := ⟨i.val + 3, by exact Nat.add_lt_add_right i.isLt 3⟩ +def conditioned (i j : Remaining) : Finset Label := fixed ∪ {remaining i, remaining j} + +theorem conditioned_card (i j : Remaining) (h : i ≠ j) : + (conditioned i j).card = 5 := by + exact (by decide : ∀ i j : Remaining, i ≠ j → (conditioned i j).card = 5) i j h + +/-- Actual row-conditioned addition matrix, with the required zero diagonal. -/ +def additionMatrix : Matrix Remaining Remaining ℝ := + fun i j => if i = j then 0 else factorialLift (conditioned i j) +/-- First block: three first-cell columns. Second block: two rows and two +columns of the second cell; same-kind and mixed-kind entries differ. -/ +def explicitMatrix : Matrix Remaining Remaining ℝ := fun i j => + if i = j then 0 else + if (i.val < 3 ∧ j.val < 3) ∨ + (3 ≤ i.val ∧ i.val < 5 ∧ 3 ≤ j.val ∧ j.val < 5) ∨ + (5 ≤ i.val ∧ 5 ≤ j.val) then 1 else 1 / 2 + +theorem additionMatrix_eq : additionMatrix = explicitMatrix := by + have hcard : ({0, 1, 2} : Finset Label).card = 3 := by decide + ext i j + fin_cases i <;> fin_cases j <;> + norm_num [additionMatrix, explicitMatrix, factorialLift, count, + conditioned, fixed, remaining, Finset.filter_insert, Finset.filter_singleton, + Finset.card_insert_of_notMem, Nat.factorial_succ, hcard] + +theorem additionMatrix_symmetric : Matrix.IsSymm additionMatrix := by + rw [additionMatrix_eq] + ext i j + fin_cases i <;> fin_cases j <;> norm_num [explicitMatrix, Matrix.transpose_apply] + +/-- Both signs use the same three nonzero first coordinates. -/ +def eigenvector (s : ℝ) : Remaining → ℝ := fun i => if i.val < 3 then 2 else s + +theorem eigenvector_nonzero (s : ℝ) : eigenvector s ≠ 0 := by + intro h + have := congrFun h (0 : Remaining) + norm_num [eigenvector] at this + +/-- The calculation retains all four second-block entries separately. -/ +theorem eigenvector_equation (s : ℝ) (hs : s ^ 2 = 3) : + additionMatrix.mulVecLin (eigenvector s) = (2 + s) • eigenvector s := by + rw [additionMatrix_eq] + ext i + fin_cases i <;> + simp [Matrix.mulVec, dotProduct, Fin.sum_univ_succ, + explicitMatrix, eigenvector] <;> nlinarith + +theorem eigenvalue_of_square (s : ℝ) (hs : s ^ 2 = 3) : + Module.End.HasEigenvalue additionMatrix.mulVecLin (2 + s) := by + apply Module.End.hasEigenvalue_of_hasEigenvector + rw [Module.End.hasEigenvector_iff, Module.End.mem_eigenspace_iff] + exact ⟨eigenvector_equation s hs, eigenvector_nonzero s⟩ +/-- A necessary condition for having at most one positive eigenvalue, even +when multiplicities are counted. Two distinct positive native eigenvalues +already contradict this condition, so no inertia convention is required. -/ +def PositiveEigenvaluesUnique (A : Matrix Remaining Remaining ℝ) : Prop := + ∀ a b : ℝ, 0 < a → 0 < b → + Module.End.HasEigenvalue A.mulVecLin a → Module.End.HasEigenvalue A.mulVecLin b → a = b + +theorem two_distinct_positive_eigenvalues : + 0 < 2 + Real.sqrt 3 ∧ 0 < 2 - Real.sqrt 3 ∧ + 2 + Real.sqrt 3 ≠ 2 - Real.sqrt 3 ∧ + Module.End.HasEigenvalue additionMatrix.mulVecLin (2 + Real.sqrt 3) ∧ + Module.End.HasEigenvalue additionMatrix.mulVecLin (2 - Real.sqrt 3) := by + have hs : Real.sqrt 3 ^ 2 = 3 := Real.sq_sqrt (by norm_num) + have hn := Real.sqrt_nonneg (3 : ℝ) + have hp : 0 < Real.sqrt (3 : ℝ) := Real.sqrt_pos.2 (by norm_num) + refine ⟨by positivity, by nlinarith, by nlinarith, eigenvalue_of_square _ hs, ?_⟩ + have hm : (-Real.sqrt (3 : ℝ)) ^ 2 = 3 := by nlinarith + simpa only [sub_eq_add_neg] using eigenvalue_of_square _ hm +/-- The actual conditioned factorial lift fails the necessary spectral +condition in the addition property. No claim about the other lift is made. -/ +theorem factorial_lift_fails_addition_signature : + ¬ PositiveEigenvaluesUnique additionMatrix := by + obtain ⟨hp, hm, hne, hep, hem⟩ := two_distinct_positive_eigenvalues + intro h + exact hne (h _ _ hp hm hep hem) + +/-- Vectors constant on the groups of three and four remaining labels. -/ +def blockVector (a b : ℝ) : Remaining → ℝ := fun i => if i.val < 3 then a else b + +theorem restricted_quadratic (a b : ℝ) : + dotProduct (blockVector a b) (additionMatrix.mulVec (blockVector a b)) = + 6 * a ^ 2 + 12 * a * b + 8 * b ^ 2 := by + rw [additionMatrix_eq] + simp [Matrix.mulVec, dotProduct, Fin.sum_univ_succ, explicitMatrix, blockVector] + ring +/-- Full finite counterexample: the conditioned sets have the required size, +the actual factorial-lift matrix is symmetric, and it has two distinct +positive eigenvalues in the native linear-map API. -/ +theorem factorial_lift_counterexample : + (∀ i j : Remaining, i ≠ j → (conditioned i j).card = 5) ∧ + Matrix.IsSymm additionMatrix ∧ + 0 < 2 + Real.sqrt 3 ∧ 0 < 2 - Real.sqrt 3 ∧ + 2 + Real.sqrt 3 ≠ 2 - Real.sqrt 3 ∧ + Module.End.HasEigenvalue additionMatrix.mulVecLin (2 + Real.sqrt 3) ∧ + Module.End.HasEigenvalue additionMatrix.mulVecLin (2 - Real.sqrt 3) := by + exact ⟨conditioned_card, additionMatrix_symmetric, two_distinct_positive_eigenvalues⟩ + +end DistinctLifts + +end + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/BinIntervalProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinIntervalProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ef6d87891b305f2f8b8551fa796e1602ff564b8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinIntervalProgram.lean @@ -0,0 +1,119 @@ +import OAI.Combinatorics.ContingencyTables.Machines.SignedFloorProgram +import OAI.Combinatorics.ContingencyTables.Machines.ScaledWordProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionBinIntervals + +namespace OAI + +/-! # Binary evaluation of a bin interval and its bounded quotient draw + +The lower endpoint is computed as the negative floor of a negative +rational. Thus the executed arithmetic uses natural quotient/remainder, +without enumerating any of the integers in the interval. +-/ + +namespace ContingencyTables.BinIntervalProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped SignedPairProgram ProfilePrograms + +/-- `(number of bins, range size, bin index)`. -/ +abbrev Input := (ℕ×ℕ)×ℕ + +def negativeInput (z : Input) : SignedFloorProgram.Input := + ((0,z.2*z.1.2),z.1.1) +def negativeInputRealizer : Realizer negativeInput := + pair (pair (constant 0) + (composition (f := fun z : Input => (z.2,z.1.2)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair second (composition first second)) multiply)) (composition first first) +lemma polynomial_negativeInput : PolynomialTime negativeInputRealizer := + polynomial_pair (polynomial_pair (polynomial_constant 0) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_second)) polynomial_multiply)) + (polynomial_composition polynomial_first polynomial_first) + +def endpoint (z : Input) : ℕ := + (SignedPairProgram.normalize (SignedFloorProgram.floorCode (negativeInput z))).2 +def endpointRealizer : Realizer endpoint := + composition (f := fun z : Input => SignedPairProgram.normalize + (SignedFloorProgram.floorCode (negativeInput z))) (g := Prod.snd) + (composition (f := fun z : Input => SignedFloorProgram.floorCode (negativeInput z)) + (g := SignedPairProgram.normalize) + (composition negativeInputRealizer SignedFloorProgram.floorCodeRealizer) + SignedPairProgram.normalizeRealizer) second +theorem polynomial_endpoint : PolynomialTime endpointRealizer := + polynomial_composition (polynomial_composition + (polynomial_composition polynomial_negativeInput SignedFloorProgram.polynomial_floorCode) + SignedPairProgram.polynomial_normalize) polynomial_second + +theorem endpoint_eq (K N beta : ℕ) : endpoint ((K,N),beta)=FairBits.endpoint K N beta := by + unfold endpoint negativeInput + rw [SignedPairProgram.normalize_eq,SignedFloorProgram.floorCode_value] + change (-⌊((0:ℚ)-((beta*N:ℕ):ℚ))/K⌋).toNat=FairBits.endpoint K N beta + have he : ((0:ℚ)-((beta*N:ℕ):ℚ))/K= -((beta:ℚ)*N/K) := by + push_cast + ring + rw [he,Int.floor_neg,neg_neg,Int.ceil_toNat] + rfl + +def next (z : Input) : Input := (z.1,z.2+1) +def nextRealizer : Realizer next := pair first (composition second successor) +lemma polynomial_next : PolynomialTime nextRealizer := + polynomial_pair polynomial_first (polynomial_composition polynomial_second polynomial_successor) + +def intervalSize (z : Input) : ℕ := endpoint (next z)-endpoint z +def intervalSizeRealizer : Realizer intervalSize := + composition (f := fun z : Input => (endpoint (next z),endpoint z)) + (g := fun p : ℕ×ℕ => p.1-p.2) + (pair (composition (f := next) (g := endpoint) nextRealizer endpointRealizer) + endpointRealizer) subtract +theorem polynomial_intervalSize : PolynomialTime intervalSizeRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_next polynomial_endpoint) polynomial_endpoint) + polynomial_subtract + +theorem intervalSize_eq (K N beta : ℕ) : + intervalSize ((K,N),beta)=CompanionOracleDensity.intervalSize K N beta := by + unfold intervalSize next + rw [endpoint_eq,endpoint_eq] + rfl + +def draw (z : Input×List Bool) : ℕ := + endpoint z.1+scaledWordValue (intervalSize z.1,z.2) +def drawRealizer : Realizer draw := + composition (f := fun z : Input×List Bool => + (endpoint z.1,scaledWordValue (intervalSize z.1,z.2))) + (g := fun p : ℕ×ℕ => p.1+p.2) + (pair (composition (f := fun z : Input×List Bool => z.1) (g := endpoint) + first endpointRealizer) + (composition (f := fun z : Input×List Bool => (intervalSize z.1,z.2)) + (g := scaledWordValue) + (pair (composition (f := fun z : Input×List Bool => z.1) (g := intervalSize) + first intervalSizeRealizer) second) scaledWordRealizer)) add +theorem polynomial_draw : PolynomialTime drawRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_endpoint) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_intervalSize) polynomial_second) + polynomial_scaledWord)) polynomial_add + +theorem draw_mem (K N beta : ℕ) (hK : 0 + (z.1.1,BinIntervalProgram.intervalSize z)) (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition first first) BinIntervalProgram.intervalSizeRealizer) multiply +lemma polynomial_factorNumerator : PolynomialTime factorNumeratorRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + BinIntervalProgram.polynomial_intervalSize) polynomial_multiply + +def numerator (zs : List BinIntervalProgram.Input) : ℕ := (zs.map factorNumerator).prod +def numeratorRealizer : Realizer numerator := composition (map factorNumeratorRealizer) listProd +lemma polynomial_numerator : PolynomialTime numeratorRealizer := + polynomial_composition (polynomial_map polynomial_factorNumerator) polynomial_listProd + +def denominator (zs : List BinIntervalProgram.Input) : ℕ := (zs.map (fun z => z.1.2)).prod +def denominatorRealizer : Realizer denominator := + composition (map (composition first second)) listProd +lemma polynomial_denominator : PolynomialTime denominatorRealizer := + polynomial_composition (polynomial_map + (polynomial_composition polynomial_first polynomial_second)) polynomial_listProd + +def output (zs : List BinIntervalProgram.Input) : TreeFraction.Fraction := + TreeFraction.normalize (numerator zs,denominator zs) +def outputRealizer : Realizer output := + composition (pair numeratorRealizer denominatorRealizer) TreeFraction.normalizeRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair polynomial_numerator polynomial_denominator) + TreeFraction.polynomial_normalize + +lemma output_ofFn {q : ℕ} (K : ℕ) (N beta : Fin q → ℕ) : + TreeFraction.val (output (List.ofFn (fun i => ((K,N i),beta i))))= + (K:ℚ)^q*(∏ i : Fin q,(CompanionOracleDensity.intervalSize K (N i) (beta i):ℚ))/ + ∏ i : Fin q,(N i:ℚ) := by + rw [output,TreeFraction.normalize_val] + simp only [numerator,denominator,List.map_ofFn,Function.comp_apply,List.prod_ofFn, + factorNumerator,BinIntervalProgram.intervalSize_eq,TreeFraction.val, + Nat.cast_prod,Nat.cast_mul,Nat.cast_pow,Finset.prod_mul_distrib,Finset.prod_const,Finset.card_univ, + Fintype.card_fin] + +open CompanionFactorialApplication ForestAssignmentSplit GridBoundary + +noncomputable section +variable {m n : ℕ} + +def data (A : Instance (Fin m) (Fin n)) (K : ℕ) + (v : Grid (I := Fin (CompanionOracleDensity.dimension A)) K) : List BinIntervalProgram.Input := + List.ofFn (fun i : Fin (RootedCatalogGrid.freeCount A) => + ((K,CompanionOracleDensity.freeRange A (RootedForestCatalog.freeEquiv A i)), + CompanionOracleDensity.naturalBin A v (RootedForestCatalog.freeEquiv A i))) + +theorem output_data (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 rfl) + rw [hp,hd,hc] + +theorem output_integerBin (A : Instance (Fin m) (Fin n)) (K : ℕ) (hK : 0 z.1.1.2) := + composition (composition first first) second + let binary := composition (composition rangeR successor) ceilLogTwoRealizer + let accuracy := composition (f := fun z : Frame => (4,z.2.1+z.2.2)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 4) (composition second add)) multiply + exact composition (f := fun z : Frame => + (Nat.clog 2 (z.1.1.2+1),4*(z.2.1+z.2.2))) + (g := fun p : ℕ×ℕ => p.1+p.2) (pair binary accuracy) add +lemma polynomial_reservedWidth : PolynomialTime reservedWidthRealizer := by + unfold reservedWidthRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_successor) polynomial_ceilLogTwo) + (polynomial_composition (polynomial_pair (polynomial_constant 4) + (polynomial_composition polynomial_second polynomial_add)) polynomial_multiply)) polynomial_add + +def activeWidth (z : Frame) : ℕ := + Nat.clog 2 (BinIntervalProgram.intervalSize z.1+1)+4*(z.2.1+z.2.2) +def activeWidthRealizer : Realizer activeWidth := by + let sizeR : Realizer (fun z : Frame => BinIntervalProgram.intervalSize z.1) := + composition (f := fun z : Frame => z.1) (g := BinIntervalProgram.intervalSize) + first BinIntervalProgram.intervalSizeRealizer + let binary : Realizer (fun z : Frame => Nat.clog 2 (BinIntervalProgram.intervalSize z.1+1)) := + composition (composition sizeR successor) ceilLogTwoRealizer + let accuracy := composition (f := fun z : Frame => (4,z.2.1+z.2.2)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 4) (composition second add)) multiply + exact composition (f := fun z : Frame => + (Nat.clog 2 (BinIntervalProgram.intervalSize z.1+1),4*(z.2.1+z.2.2))) + (g := fun p : ℕ×ℕ => p.1+p.2) (pair binary accuracy) add +lemma polynomial_activeWidth : PolynomialTime activeWidthRealizer := by + unfold activeWidthRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first BinIntervalProgram.polynomial_intervalSize) + polynomial_successor) polynomial_ceilLogTwo) + (polynomial_composition (polynomial_pair (polynomial_constant 4) + (polynomial_composition polynomial_second polynomial_add)) polynomial_multiply)) polynomial_add + +def coordinate (z : Frame×List Bool) : ℕ := + BinIntervalProgram.draw (z.1.1,z.2.take (activeWidth z.1)) +def coordinateRealizer : Realizer coordinate := + composition (f := fun z : Frame×List Bool => (z.1.1,z.2.take (activeWidth z.1))) + (g := BinIntervalProgram.draw) + (pair (composition first first) + (composition (pair second (composition first activeWidthRealizer)) takeFast)) + BinIntervalProgram.drawRealizer +lemma polynomial_coordinate : PolynomialTime coordinateRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_activeWidth)) polynomial_takeFast)) + BinIntervalProgram.polynomial_draw + +lemma intervalSize_le (K N beta : ℕ) (hK : 0 + (z.1.1.getD z.2 (((0,0),0),(0,0)),dependentChunk ((widths z.1,z.1.2),z.2))) + (g := coordinate) + (pair (composition (pair (composition first first) second) + (getDFast (((0,0),0),(0,0)))) + (composition (pair (pair (composition first widthsRealizer) + (composition first second)) second) dependentChunkRealizer)) coordinateRealizer +lemma polynomial_item : PolynomialTime itemRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_first) + polynomial_second) (polynomial_getDFast (((0,0),0),(0,0)))) + (polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition polynomial_first polynomial_widths) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second) + polynomial_dependentChunk)) polynomial_coordinate + +def indices (z : Input) : List ℕ := List.range z.1.length +def indicesRealizer : Realizer indices := composition (composition first listLength) range +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) + Polynomial.X + intro z + simpa only [Function.comp_apply,Polynomial.eval_X] using + (list_length_le_weight z.1).trans (weight_fst z) + +def output (z : Input) : List ℕ := (indices z).map (fun i => item (z,i)) +def outputRealizer : Realizer output := + composition (pair identity indicesRealizer) (mapWith itemRealizer) +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_item) + +theorem output_ofFn {q : ℕ} (frames : Fin q → Frame) + (bits : Fin (∑ i,reservedWidth (frames i)) → Bool) : + output (List.ofFn frames,List.ofFn bits)= + List.ofFn (fun i => coordinate (frames i,List.ofFn (fun j : Fin (reservedWidth (frames i)) => + bits (finSigmaFinEquiv ⟨i,j⟩)))) := by + have hw : widths (List.ofFn frames,List.ofFn bits)= + List.ofFn (fun i => reservedWidth (frames i)) := by + simp only [widths,List.map_ofFn,Function.comp_def] + apply List.ext_getElem + · simp only [output,indices,List.length_map,List.length_range,List.length_ofFn] + · intro i hi hj + have hiq : i reservedWidth (frames i)) bits (⟨i,hiq⟩ : Fin q) + simp only [output,indices,List.length_ofFn,List.getElem_map,List.getElem_range, + List.getElem_ofFn,item,List.getD_eq_getElem?_getD,List.getElem?_ofFn,hiq,dite_true, + Option.getD_some,hw] + exact congrArg (fun b => coordinate (frames ⟨i,hiq⟩,b)) hd + +end ContingencyTables.BinVectorProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryContraction.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryContraction.lean new file mode 100644 index 0000000000000000000000000000000000000000..43d6a9e4dff93d09d826ede6b6903cf0c185fcaf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryContraction.lean @@ -0,0 +1,557 @@ +import OAI.Combinatorics.ContingencyTables.Transport.QuadraticTransport +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! +# Fixed-degree binary cubic contraction + +The full-matrix cubic contraction in paper 200-02, +Lemma `lem:binary-contraction`, follows from the generic spectral theorem +`CommonBasesFPRAS.cubic_signature` and its closed-limit lemma. A symmetric +cubic tensor is positive on distinct triples and zero on repetitions; +its coordinate slices have the quadratic signature; contraction by an +arbitrary nonnegative vector, in particular a pair indicator, preserves +that signature on the full remaining index set. + +There is no assumption of positivity on unrelated subset cardinalities. +-/ + +namespace ContingencyTables.BinaryContraction + +open scoped BigOperators Topology Classical +open LinearMap (BilinForm) +open CommonBasesFPRAS + +variable {I : Type*} [Fintype I] [DecidableEq I] + +omit [Fintype I] [DecidableEq I] in +/-- Our signature convention and the existing library convention agree +for symmetric forms; only the orthogonality argument order differs. -/ +lemma signature_iff (B : BilinForm ℝ (I → ℝ)) (hsymm : B.IsSymm) : + OnePositiveDirection B ↔ CommonBasesFPRAS.OnePositive B := by + constructor + · intro h e he v hv + exact h e he v (by rw [hsymm.eq e v]; exact hv) + · intro h e he v hv + exact h e he v (by rw [hsymm.eq v e]; exact hv) + +lemma exists_third (hcard : 3 ≤ Fintype.card I) (j k : I) : + ∃ i : I, i ≠ j ∧ i ≠ k := by + by_contra hn + have hsub : (Finset.univ : Finset I) ⊆ {j, k} := by + intro i _ + by_cases hij : i = j + · simp [hij] + · have hik : i = k := by + by_contra hik + exact hn ⟨i, hij, hik⟩ + simp [hik] + have hc := Finset.card_le_card hsub + have hpair : ({j, k} : Finset I).card ≤ 2 := by + by_cases h : j = k <;> simp [h] + simp only [Finset.card_univ] at hc + omega + +omit [Fintype I] in +/-- Every tensor entry is nonnegative on the actual cubic domain. -/ +lemma tensor_nonnegative (C : I → Matrix I I ℝ) + (hzero : ∀ i j k, i = j ∨ i = k ∨ j = k → C i j k = 0) + (hpos : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → 0 < C i j k) + (i j k : I) : 0 ≤ C i j k := by + by_cases hr : i = j ∨ i = k ∨ j = k + · rw [hzero i j k hr] + · exact (hpos i j k (fun h => hr (Or.inl h)) + (fun h => hr (Or.inr (Or.inl h))) (fun h => hr (Or.inr (Or.inr h)))).le + +/-- Strictly positive directions give positive slice squares, including +when the ground set has exactly three elements. -/ +lemma slice_square_positive (C : I → Matrix I I ℝ) (hcard : 3 ≤ Fintype.card I) + (hzero : ∀ i j k, i = j ∨ i = k ∨ j = k → C i j k = 0) + (hpos : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → 0 < C i j k) + (x : I → ℝ) (hx : ∀ i, 0 < x i) (i : I) : + 0 < (C i).toBilin' x x := by + obtain ⟨j, hji⟩ := Fintype.exists_ne_of_one_lt_card (by omega) i + obtain ⟨k, hki, hkj⟩ := exists_third hcard i j + rw [Matrix.toBilin'_apply] + apply Finset.sum_pos' + · intro a _ + apply Finset.sum_nonneg + intro b _ + exact mul_nonneg (mul_nonneg (hx a).le (tensor_nonnegative C hzero hpos i a b)) (hx b).le + · refine ⟨j, Finset.mem_univ _, ?_⟩ + apply Finset.sum_pos' + · intro b _ + exact mul_nonneg (mul_nonneg (hx j).le (tensor_nonnegative C hzero hpos i j b)) (hx b).le + · exact ⟨k, Finset.mem_univ _, + mul_pos (mul_pos (hx j) (hpos i j k (Ne.symm hji) (Ne.symm hki) (Ne.symm hkj))) (hx k)⟩ + +/-- Strict-direction specialization of the existing generic spectral +argument, with every positivity condition proved from distinct triples. -/ +theorem positive_cubic_contraction (C : I → Matrix I I ℝ) + (hcard : 3 ≤ Fintype.card I) + (hCs : ∀ i j k, C i j k = C i k j) + (hCt : ∀ i j k, C i j k = C j i k) + (hzero : ∀ i j k, i = j ∨ i = k ∨ j = k → C i j k = 0) + (hpos : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → 0 < C i j k) + (hsig : ∀ i, OnePositiveDirection (C i).toBilin') + (x : I → ℝ) (hx : ∀ i, 0 < x i) : + CommonBasesFPRAS.OnePositive (cubicContraction C x).toBilin' := by + have : Nonempty I := Fintype.card_pos_iff.mp (by omega) + apply cubic_signature C hCs hCt + (fun i => (signature_iff _ (matrix_bilin_symm _ (hCs i))).mp (hsig i)) x hx + · exact slice_square_positive C hcard hzero hpos x hx + · intro j k + apply Finset.sum_nonneg + intro i _ + exact mul_nonneg (hx i).le (tensor_nonnegative C hzero hpos i j k) + · intro j k hjk + obtain ⟨i, hij, hik⟩ := exists_third hcard j k + apply Finset.sum_pos' + · intro a _ + exact mul_nonneg (hx a).le (tensor_nonnegative C hzero hpos a j k) + · exact ⟨i, Finset.mem_univ _, mul_pos (hx i) (hpos i j k hij hik hjk)⟩ + +/-- Nonnegative contractions follow by the actual positive perturbation +and closed matrix limit from the paper. The contracted indices are retained. -/ +theorem nonnegative_cubic_contraction (C : I → Matrix I I ℝ) + (hcard : 3 ≤ Fintype.card I) + (hCs : ∀ i j k, C i j k = C i k j) + (hCt : ∀ i j k, C i j k = C j i k) + (hzero : ∀ i j k, i = j ∨ i = k ∨ j = k → C i j k = 0) + (hpos : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → 0 < C i j k) + (hsig : ∀ i, OnePositiveDirection (C i).toBilin') + (x : I → ℝ) (hx : ∀ i, 0 ≤ x i) : + OnePositiveDirection (cubicContraction C x).toBilin' := by + let F : ℝ → Matrix I I ℝ := fun t => cubicContraction C (fun i => x i + t) + let l := nhdsWithin (0 : ℝ) (Set.Ioi 0) + have : l.NeBot := nhdsWithin_Ioi_neBot (le_refl (0 : ℝ)) + have hF : CommonBasesFPRAS.OnePositive (F 0).toBilin' := by + apply onePositive_of_tendsto (l := l) F (F 0) + · intro i j + have hc : Continuous (fun t => F t i j) := by + dsimp [F, cubicContraction] + apply continuous_finsetSum + intro k _ + exact (continuous_const.add continuous_id).mul continuous_const + exact hc.continuousAt.tendsto.mono_left nhdsWithin_le_nhds + · intro t + exact cubicContraction_symm C hCs _ + · have ht : ∀ᶠ t in l, 0 < t := self_mem_nhdsWithin + filter_upwards [ht] with t ht + exact positive_cubic_contraction C hcard hCs hCt hzero hpos hsig _ + (fun i => add_pos_of_nonneg_of_pos (hx i) ht) + apply (signature_iff _ (matrix_bilin_symm _ (cubicContraction_symm C hCs x))).mpr + simpa only [F, add_zero] using hF + +/-- The pair-indicator contraction in Lemma binary-contraction is the sum +of the two coordinate slices on the full ground set. No principal restriction +has been taken yet. -/ +theorem pair_cubic_contraction (C : I → Matrix I I ℝ) + (hcard : 3 ≤ Fintype.card I) + (hCs : ∀ i j k, C i j k = C i k j) + (hCt : ∀ i j k, C i j k = C j i k) + (hzero : ∀ i j k, i = j ∨ i = k ∨ j = k → C i j k = 0) + (hpos : ∀ i j k, i ≠ j → i ≠ k → j ≠ k → 0 < C i j k) + (hsig : ∀ i, OnePositiveDirection (C i).toBilin') (p q : I) : + OnePositiveDirection (C p + C q).toBilin' := by + let x : I → ℝ := fun i => (if i = p then 1 else 0) + (if i = q then 1 else 0) + have hx : ∀ i, 0 ≤ x i := by + intro i + dsimp [x] + split_ifs <;> norm_num + have heq : cubicContraction C x = C p + C q := by + ext i j + simp only [cubicContraction, x, add_mul, Finset.sum_add_distrib, + ite_mul, one_mul, zero_mul, Finset.sum_ite_eq', Finset.mem_univ, ite_true, + Matrix.add_apply] + rw [← heq] + exact nonnegative_cubic_contraction C hcard hCs hCt hzero hpos hsig x hx + + +/-- Positivity is required only on the paper's valid subset degree. -/ +def DegreePositive (f : Set I → ℝ) (k : ℕ) : Prop := + ∀ A, A.ncard = k → 0 < f A + +/-- The paper's addition property: fix precisely `k-2` elements and test +only the remaining quadratic matrix. -/ +def AdditionProperty (f : Set I → ℝ) (k : ℕ) : Prop := + ∀ A, A.ncard + 2 = k → CommonBasesFPRAS.OnePositive (faceHessian f A).toBilin' + +/-- A coordinate slice of a valid-degree cubic tensor is a padded addition +matrix of the original weight. -/ +lemma fixedDegree_slice (f : Set I → ℝ) (k : ℕ) + (hsig : AdditionProperty f k) (A : Set I) (hA : A.ncard + 3 = k) + (i : {i // i ∉ A}) : CommonBasesFPRAS.OnePositive (faceCubic f A i).toBilin' := by + classical + rw [faceCubic_pad] + apply onePositive_padMatrix + apply onePositive_reindex + have hi : (insert i.val A).ncard + 2 = k := by + rw [ncard_insert_eq A i.val i.property] + omega + convert hsig (insert i.val A) hi using 1 + congr 2 <;> exact Subsingleton.elim _ _ + +/-- The full-ground pair contraction for a weight positive only at its +specified subset degree. This is the actual cubic tensor used by the paper. -/ +theorem fixedDegree_pair_contraction (f : Set I → ℝ) (k : ℕ) + (hk : k ≤ Fintype.card I) (hpos : DegreePositive f k) + (hsig : AdditionProperty f k) (A : Set I) (hA : A.ncard + 3 = k) + (p q : {i // i ∉ A}) : + OnePositiveDirection (faceCubic f A p + faceCubic f A q).toBilin' := by + classical + have hcard : 3 ≤ Fintype.card {i // i ∉ A} := by + have := card_outside A + omega + apply pair_cubic_contraction (faceCubic f A) hcard + (faceCubic_symm f A) (faceCubic_transpose f A) + · intro i j l hr + simp only [faceCubic, hr, ite_true] + · intro i j l hij hil hjl + simp only [faceCubic, hij, hil, hjl, false_or, ite_false] + apply hpos + rw [ncard_insert_union_pair A i j l hij hil hjl] + exact hA + · intro i + apply (signature_iff _ (matrix_bilin_symm _ (faceCubic_symm f A i))).mpr + exact fixedDegree_slice f k hsig A hA i + +abbrev PairRest (p q : I) := {i : I // i ≠ p ∧ i ≠ q} + +/-- Summing a labeled pair at occupancy one, on its actual remaining ground set. -/ +noncomputable def pairSum (f : Set I → ℝ) (p q : I) (U : Set (PairRest p q)) : ℝ := + f (insert p (Subtype.val '' U)) + f (insert q (Subtype.val '' U)) + +/-- Every valid residual weight is the sum of two strictly positive weights. -/ +lemma pairSum_positive (f : Set I → ℝ) (k : ℕ) (hpos : DegreePositive f k) + (p q : I) (U : Set (PairRest p q)) (hU : U.ncard + 1 = k) : + 0 < pairSum f p q U := by + classical + have hp : p ∉ Subtype.val '' U := by + rintro ⟨i, _, hi⟩ + exact i.property.1 hi + have hq : q ∉ Subtype.val '' U := by + rintro ⟨i, _, hi⟩ + exact i.property.2 hi + have hc : (Subtype.val '' U).ncard = U.ncard := + Set.ncard_image_of_injective U Subtype.val_injective + apply add_pos + · apply hpos + rw [ncard_insert_eq _ p hp, hc] + exact hU + · apply hpos + rw [ncard_insert_eq _ q hq, hc] + exact hU + +/-- Occupancy-one pair summation preserves the valid-degree addition property. +The proof contracts on the full index set first and then takes the exact +principal submatrix after removing the pair. -/ +theorem pairSum_addition (f : Set I → ℝ) (k : ℕ) + (hk : k ≤ Fintype.card I) (hpos : DegreePositive f k) + (hsig : AdditionProperty f k) (p q : I) : + AdditionProperty (pairSum f p q) (k - 1) := by + classical + intro A hA + let B : Set I := Subtype.val '' A + have hB : B.ncard = A.ncard := Set.ncard_image_of_injective A Subtype.val_injective + have hp : p ∉ B := by + rintro ⟨i, _, hi⟩ + exact i.property.1 hi + have hq : q ∉ B := by + rintro ⟨i, _, hi⟩ + exact i.property.2 hi + let p' : {i // i ∉ B} := ⟨p, hp⟩ + let q' : {i // i ∉ B} := ⟨q, hq⟩ + have hBdeg : B.ncard + 3 = k := by omega + have hpair := fixedDegree_pair_contraction f k hk hpos hsig B hBdeg p' q' + have hsymm : ∀ i j, + (faceCubic f B p' + faceCubic f B q') i j = + (faceCubic f B p' + faceCubic f B q') j i := by + intro i j + simp only [Matrix.add_apply, faceCubic_symm] + have hpair' := (signature_iff _ (matrix_bilin_symm _ hsymm)).mp hpair + let e : {i : PairRest p q // i ∉ A} → {i : I // i ∉ B} := + fun i => ⟨i.val.val, by + rintro ⟨j, hj, hji⟩ + exact i.property ((Subtype.val_injective hji) ▸ hj)⟩ + have he : Function.Injective e := by + intro i j hij + have h : i.val.val = j.val.val := congrArg (fun z : {i : I // i ∉ B} => z.val) hij + exact Subtype.ext (Subtype.ext h) + have heq : (faceCubic f B p' + faceCubic f B q').submatrix e e = + faceHessian (pairSum f p q) A := by + ext i j + by_cases hij : i = j + · subst j + simp [Matrix.submatrix_apply, faceCubic, faceHessian] + have hije : e i ≠ e j := fun h => hij (he h) + have hpi : p' ≠ e i := fun h => i.val.property.1 (congrArg Subtype.val h).symm + have hpj : p' ≠ e j := fun h => j.val.property.1 (congrArg Subtype.val h).symm + have hqi : q' ≠ e i := fun h => i.val.property.2 (congrArg Subtype.val h).symm + have hqj : q' ≠ e j := fun h => j.val.property.2 (congrArg Subtype.val h).symm + simp only [Matrix.submatrix_apply, Matrix.add_apply, faceCubic, + hpi, hpj, hqi, hqj, hije, false_or, ite_false, faceHessian, hij, + pairSum, Set.image_union, Set.image_pair] + rfl + rw [← heq] + exact onePositive_submatrix _ hpair' e + + +/-- The output positivity statement in its fixed-degree form. -/ +theorem pairSum_degreePositive (f : Set I → ℝ) (k : ℕ) (hk : 1 ≤ k) + (hpos : DegreePositive f k) (p q : I) : DegreePositive (pairSum f p q) (k - 1) := by + intro U hU + apply pairSum_positive f k hpos p q U + omega + +abbrev FixedRest (p : I) := {i : I // i ≠ p} + +noncomputable def fixIncluded (f : Set I → ℝ) (p : I) (U : Set (FixedRest p)) : ℝ := + f (insert p (Subtype.val '' U)) + +noncomputable def fixExcluded (f : Set I → ℝ) (p : I) (U : Set (FixedRest p)) : ℝ := + f (Subtype.val '' U) + +lemma fixIncluded_degreePositive (f : Set I → ℝ) (k : ℕ) (hk : 1 ≤ k) + (hpos : DegreePositive f k) (p : I) : DegreePositive (fixIncluded f p) (k - 1) := by + classical + intro U hU + apply hpos + have hp : p ∉ Subtype.val '' U := by + rintro ⟨i, _, hi⟩ + exact i.property hi + rw [ncard_insert_eq _ p hp, Set.ncard_image_of_injective U Subtype.val_injective] + omega + +omit [Fintype I] [DecidableEq I] in +lemma fixExcluded_degreePositive (f : Set I → ℝ) (k : ℕ) + (hpos : DegreePositive f k) (p : I) : DegreePositive (fixExcluded f p) k := by + classical + intro U hU + apply hpos + rw [Set.ncard_image_of_injective U Subtype.val_injective] + exact hU + +/-- Fixing an exclusion restricts each quadratic test to a principal submatrix. -/ +theorem fixExcluded_addition (f : Set I → ℝ) (k : ℕ) + (hsig : AdditionProperty f k) (p : I) : AdditionProperty (fixExcluded f p) k := by + classical + intro A hA + let B : Set I := Subtype.val '' A + have hB : B.ncard + 2 = k := by + rw [Set.ncard_image_of_injective A Subtype.val_injective] + exact hA + let e : {i : FixedRest p // i ∉ A} → {i : I // i ∉ B} := + fun i => ⟨i.val.val, by + rintro ⟨j, hj, hji⟩ + exact i.property ((Subtype.val_injective hji) ▸ hj)⟩ + have he : Function.Injective e := by + intro i j hij + have h : i.val.val = j.val.val := congrArg (fun z : {i : I // i ∉ B} => z.val) hij + exact Subtype.ext (Subtype.ext h) + have heq : (faceHessian f B).submatrix e e = faceHessian (fixExcluded f p) A := by + ext i j + by_cases hij : i = j + · subst j + simp [Matrix.submatrix_apply, faceHessian] + have hije : e i ≠ e j := fun h => hij (he h) + simp only [Matrix.submatrix_apply, faceHessian, hij, hije, ite_false, + fixExcluded, Set.image_union, Set.image_pair] + rfl + rw [← heq] + exact onePositive_submatrix _ (hsig B hB) e + +/-- Fixing an inclusion enlarges the fixed set in each quadratic test. -/ +theorem fixIncluded_addition (f : Set I → ℝ) (k : ℕ) + (hsig : AdditionProperty f k) (p : I) : AdditionProperty (fixIncluded f p) (k - 1) := by + classical + intro A hA + let B : Set I := Subtype.val '' A + have hp : p ∉ B := by + rintro ⟨i, _, hi⟩ + exact i.property hi + have hBcard : B.ncard = A.ncard := Set.ncard_image_of_injective A Subtype.val_injective + have hB : (insert p B).ncard + 2 = k := by + rw [ncard_insert_eq B p hp, hBcard] + omega + let e : {i : FixedRest p // i ∉ A} → {i : I // i ∉ insert p B} := + fun i => ⟨i.val.val, by + rintro (hip | ⟨j, hj, hji⟩) + · exact i.val.property hip + · exact i.property ((Subtype.val_injective hji) ▸ hj)⟩ + have he : Function.Injective e := by + intro i j hij + have h : i.val.val = j.val.val := + congrArg (fun z : {i : I // i ∉ insert p B} => z.val) hij + exact Subtype.ext (Subtype.ext h) + have heq : (faceHessian f (insert p B)).submatrix e e = + faceHessian (fixIncluded f p) A := by + ext i j + by_cases hij : i = j + · subst j + simp [Matrix.submatrix_apply, faceHessian] + have hije : e i ≠ e j := fun h => hij (he h) + simp only [Matrix.submatrix_apply, faceHessian, hij, hije, ite_false, + fixIncluded, Set.image_union, Set.image_pair] + congr 1 + ext x + simp [B, e] + tauto + rw [← heq] + apply onePositive_submatrix _ ?_ e + convert hsig (insert p B) hB using 1 + congr 2 + exact Subsingleton.elim _ _ + + +noncomputable def complementWeight (f : Set I → ℝ) (U : Set I) : ℝ := f Uᶜ + +def OmissionProperty (f : Set I → ℝ) (k : ℕ) : Prop := + AdditionProperty (complementWeight f) (Fintype.card I - k) + +omit [DecidableEq I] in +lemma complement_degreePositive (f : Set I → ℝ) (k : ℕ) (hk : k ≤ Fintype.card I) + (hpos : DegreePositive f k) : DegreePositive (complementWeight f) (Fintype.card I - k) := by + classical + intro U hU + apply hpos + have hc := U.ncard_add_ncard_compl + simp only [Nat.card_eq_fintype_card] at hc + omega + +omit [Fintype I] [DecidableEq I] in +lemma pairRest_image_avoids (p q : I) (U : Set (PairRest p q)) : + p ∉ Subtype.val '' U ∧ q ∉ Subtype.val '' U := by + constructor + · rintro ⟨i, _, hi⟩ + exact i.property.1 hi + · rintro ⟨i, _, hi⟩ + exact i.property.2 hi + +omit [Fintype I] in +/-- Complementation swaps which member of the pair is included. -/ +lemma pair_complement_set (p q : I) (hpq : p ≠ q) (U : Set (PairRest p q)) : + insert p (Subtype.val '' Uᶜ) = (insert q (Subtype.val '' U))ᶜ := by + classical + obtain ⟨hpU, hqU⟩ := pairRest_image_avoids p q U + obtain ⟨hpUc, hqUc⟩ := pairRest_image_avoids p q Uᶜ + ext x + by_cases hxp : x = p + · subst x + simp [hpq, hpU] + by_cases hxq : x = q + · subst x + simp [Ne.symm hpq, hqUc] + let xi : PairRest p q := ⟨x, hxp, hxq⟩ + have hmem (V : Set (PairRest p q)) : x ∈ Subtype.val '' V ↔ xi ∈ V := by + constructor + · rintro ⟨y, hy, hyx⟩ + have hyi : y = xi := Subtype.ext hyx + exact hyi ▸ hy + · intro hx + exact ⟨xi, hx, rfl⟩ + simp only [Set.mem_insert_iff, Set.mem_compl_iff, hxp, hxq, false_or, hmem] + +omit [Fintype I] in +lemma pairSum_complement (f : Set I → ℝ) (p q : I) (hpq : p ≠ q) : + complementWeight (pairSum f p q) = pairSum (complementWeight f) p q := by + classical + funext U + have hq := congrArg (fun V : Set I => Vᶜ) (pair_complement_set p q hpq Uᶜ) + simp only [compl_compl] at hq + simp only [complementWeight, pairSum] + rw [pair_complement_set p q hpq U, hq.symm, add_comm] + +lemma card_pairRest (p q : I) (hpq : p ≠ q) : + Fintype.card (PairRest p q) + 2 = Fintype.card I := by + classical + have hc := card_outside ({p, q} : Set I) + simpa [PairRest, Set.ncard_pair hpq, not_or] using hc + +/-- Complementation preserves occupancy one, so the proved addition closure +gives omission closure on every valid residual degree. -/ +theorem pairSum_omission (f : Set I → ℝ) (k : ℕ) + (hk : 1 ≤ k) (hkupper : k + 1 ≤ Fintype.card I) + (hpos : DegreePositive f k) (hsig : OmissionProperty f k) + (p q : I) (hpq : p ≠ q) : OmissionProperty (pairSum f p q) (k - 1) := by + classical + have hc := card_pairRest p q hpq + have hp := complement_degreePositive f k (by omega) hpos + have ha := pairSum_addition (complementWeight f) (Fintype.card I - k) + (Nat.sub_le _ _) hp hsig p q + change AdditionProperty (complementWeight (pairSum f p q)) + (Fintype.card (PairRest p q) - (k - 1)) + rw [pairSum_complement f p q hpq] + convert ha using 1 + omega + + +omit [Fintype I] [DecidableEq I] in +lemma fixed_complement_set (p : I) (U : Set (FixedRest p)) : + insert p (Subtype.val '' Uᶜ) = (Subtype.val '' U)ᶜ := by + classical + have hpU : p ∉ Subtype.val '' U := by + rintro ⟨i, _, hi⟩ + exact i.property hi + ext x + by_cases hxp : x = p + · subst x + simp [hpU] + let xi : FixedRest p := ⟨x, hxp⟩ + have hmem (V : Set (FixedRest p)) : x ∈ Subtype.val '' V ↔ xi ∈ V := by + constructor + · rintro ⟨y, hy, hyx⟩ + have hyi : y = xi := Subtype.ext hyx + exact hyi ▸ hy + · intro hx + exact ⟨xi, hx, rfl⟩ + simp only [Set.mem_insert_iff, Set.mem_compl_iff, hxp, false_or, hmem] + +omit [Fintype I] [DecidableEq I] in +lemma fixIncluded_complement (f : Set I → ℝ) (p : I) : + complementWeight (fixIncluded f p) = fixExcluded (complementWeight f) p := by + funext U + exact congrArg f (fixed_complement_set p U) + +omit [Fintype I] [DecidableEq I] in +lemma fixExcluded_complement (f : Set I → ℝ) (p : I) : + complementWeight (fixExcluded f p) = fixIncluded (complementWeight f) p := by + classical + funext U + have h := congrArg (fun V : Set I => Vᶜ) (fixed_complement_set p Uᶜ) + simp only [compl_compl] at h + exact congrArg f h.symm + +lemma card_fixedRest (p : I) : Fintype.card (FixedRest p) + 1 = Fintype.card I := by + classical + have hc := card_outside ({p} : Set I) + simpa [FixedRest] using hc + +/-- Complementation swaps a fixed inclusion with a fixed exclusion. -/ +theorem fixIncluded_omission (f : Set I → ℝ) (k : ℕ) (hk : 1 ≤ k) + (hsig : OmissionProperty f k) (p : I) : OmissionProperty (fixIncluded f p) (k - 1) := by + classical + have hc := card_fixedRest p + have ha := fixExcluded_addition (complementWeight f) (Fintype.card I - k) hsig p + change AdditionProperty (complementWeight (fixIncluded f p)) + (Fintype.card (FixedRest p) - (k - 1)) + rw [fixIncluded_complement] + convert ha using 1 + omega + +/-- Complementation swaps a fixed exclusion with a fixed inclusion. -/ +theorem fixExcluded_omission (f : Set I → ℝ) (k : ℕ) + (hsig : OmissionProperty f k) (p : I) : OmissionProperty (fixExcluded f p) k := by + classical + have hc := card_fixedRest p + have ha := fixIncluded_addition (complementWeight f) (Fintype.card I - k) hsig p + change AdditionProperty (complementWeight (fixExcluded f p)) + (Fintype.card (FixedRest p) - k) + rw [fixExcluded_complement] + convert ha using 1 + omega + +end ContingencyTables.BinaryContraction + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryExchangeProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryExchangeProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..087b0759c18d154c59abcec2e29aec80164e5c40 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryExchangeProgram.lean @@ -0,0 +1,196 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.SmallCellCatalogProgram +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeCandidates + +namespace OAI + +/-! # Polynomial enumeration of exchanges of a binary profile + +The program scans at most the square of the list length. It retains only +an absent receiving coordinate and a present donating coordinate, so every +retained natural-number update is again a binary profile. +-/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS.TreeTyped Polynomial +open scoped BigOperators Classical + +def binaryExchangeTest (z : List ℕ×(ℕ×ℕ)) : Bool := + decide (z.1.getD z.2.1 0=0 ∧ z.1.getD z.2.2 0=1) + +def binaryExchangeTestRealizer : Realizer binaryExchangeTest := by + let V : Realizer (fun z : List ℕ×(ℕ×ℕ) => z.1) := first + let I : Realizer (fun z : List ℕ×(ℕ×ℕ) => z.2.1) := composition second first + let J : Realizer (fun z : List ℕ×(ℕ×ℕ) => z.2.2) := composition second second + let absent := composition (pair (composition (pair V I) (getDFast 0)) (constant 0)) natEqual + let present := composition (pair (composition (pair V J) (getDFast 0)) (constant 1)) natEqual + exact (choose absent present (constant false)).congr (by + intro z + apply Bool.eq_iff_iff.mpr + simp only [Function.comp_apply,binaryExchangeTest,decide_eq_true_eq] + split_ifs <;> simp_all) + +theorem polynomial_binaryExchangeTest : PolynomialTime binaryExchangeTestRealizer := by + unfold binaryExchangeTestRealizer + apply polynomial_congr + apply polynomial_choose + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) (polynomial_getDFast 0)) + (polynomial_constant 0)) polynomial_natEqual + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_second)) (polynomial_getDFast 0)) + (polynomial_constant 1)) polynomial_natEqual + · exact polynomial_constant false + +def binaryExchangeIndices (xs : List ℕ) : List (ℕ×ℕ) := + (cellPairs (xs,xs)).filter (fun ij => binaryExchangeTest (xs,ij)) + +def binaryExchangeIndicesRealizer : Realizer binaryExchangeIndices := + composition (pair identity (composition (pair identity identity) cellPairsRealizer)) + (filterWith binaryExchangeTestRealizer) + +theorem polynomial_binaryExchangeIndices : PolynomialTime binaryExchangeIndicesRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_pair polynomial_identity polynomial_identity) + polynomial_cellPairs)) (polynomial_filterWith polynomial_binaryExchangeTest) + +theorem mem_binaryExchangeIndices (xs : List ℕ) (i j : ℕ) : + (i,j)∈binaryExchangeIndices xs ↔ + i listExchange (xs,ij)) + +def binaryExchangesRealizer : Realizer binaryExchanges := + composition (pair identity binaryExchangeIndicesRealizer) (mapWith listExchangeRealizer) + +theorem polynomial_binaryExchanges : PolynomialTime binaryExchangesRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_binaryExchangeIndices) + (polynomial_mapWith polynomial_listExchange) + +noncomputable def setProfile {n : ℕ} (S : Set (Fin n)) : Fin n → ℕ := + fun i => if i∈S then 1 else 0 + +lemma setProfile_injective {n : ℕ} : Function.Injective (setProfile (n := n)) := by + intro S T he + ext i + have hi := congrFun he i + by_cases hs : i∈S <;> by_cases ht : i∈T <;> simp_all [setProfile] + +/-- On an absent/present coordinate pair, the natural update is exactly +set removal followed by set insertion. -/ +theorem exchange_setProfile {n : ℕ} (S : Set (Fin n)) (i j : Fin n) + (hi : i∉S) (hj : j∈S) : + IntegerWeightedTransport.exchangeTarget (setProfile S) i j= + setProfile (insert i (S\{j})) := by + have hij : i≠j := fun he => hi (he ▸ hj) + funext a + by_cases hai : a=i + · subst a + simp [IntegerWeightedTransport.exchangeTarget,setProfile,hi,hij] + · by_cases haj : a=j + · subst a + simp [IntegerWeightedTransport.exchangeTarget,setProfile,hj,hai] + · by_cases ha : a∈S <;> + simp [IntegerWeightedTransport.exchangeTarget,setProfile,hai,haj,ha] + +/-- Every program output is a genuine binary exchange, and all such +exchanges are listed. No enumeration of the set of states is involved. -/ +theorem mem_binaryExchanges_setProfile {n : ℕ} (S : Set (Fin n)) (ys : List ℕ) : + ys∈binaryExchanges (List.ofFn (setProfile S)) ↔ + ∃ i j : Fin n,i∉S ∧ j∈S ∧ ys=List.ofFn (setProfile (insert i (S\{j}))) := by + simp only [binaryExchanges,List.mem_map] + constructor + · rintro ⟨⟨i,j⟩,hij,rfl⟩ + have h := (mem_binaryExchangeIndices _ i j).mp hij + have hi : i + simp [List.getD_eq_getElem?_getD,setProfile,hi,hj] + · exact ((listExchange_ofFn (setProfile S) i j).trans + (congrArg List.ofFn (exchange_setProfile S i j hi hj))) + +lemma getD_setProfile {n : ℕ} (S : Set (Fin n)) (i : Fin n) : + (List.ofFn (setProfile S)).getD i.val 0=setProfile S i := by + rw [List.getD_eq_getElem?_getD,List.getElem?_eq_getElem (by simp)] + simp only [Option.getD_some,List.getElem_ofFn] + +lemma binaryIndex_specs {n : ℕ} (S : Set (Fin n)) (ij : ℕ×ℕ) + (h : ij∈binaryExchangeIndices (List.ofFn (setProfile S))) : + ∃ i j : Fin n,ij=(i.val,j.val) ∧ i∉S ∧ j∈S := by + have hh := (mem_binaryExchangeIndices _ ij.1 ij.2).mp h + have hi : ij.1 a.2.val) hp + have h2 : j=v := congrArg (fun a : CommonBasesFPRAS.ExchangeChoice S => a.1.val) hp + subst u + subst v + rfl + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryPowerProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryPowerProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9f57afe8a57a58aa5b5cd61c53661dd5d020c76 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinaryPowerProgram.lean @@ -0,0 +1,69 @@ +import OAI.Combinatorics.ContingencyTables.Machines.IntegerMatrixProgram + +namespace OAI + +/-! # Binary powers with a polynomial bound in the exponent and input bits -/ + +namespace ContingencyTables.BinaryPowerPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped +open scoped BigOperators + +def setup (z : ℕ×ℕ) : ℕ×(List (List ℕ)×List ℕ) := (z.2,([[z.1]],[1])) + +def singleton {A : Type} [Codec A] : Realizer (fun a : A => [a]) := + composition (pair identity (constant [])) listCons + +lemma polynomial_singleton {A : Type} [Codec A] : PolynomialTime (singleton (A := A)) := + polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant [])) + polynomial_listCons + +def setupRealizer : Realizer setup := + pair second (pair (composition (composition first singleton) singleton) (constant [1])) + +lemma polynomial_setup : PolynomialTime setupRealizer := + polynomial_pair polynomial_second (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_singleton) + polynomial_singleton) (polynomial_constant [1])) + +def power (z : ℕ×ℕ) : ℕ := (IntegerMatrixPrograms.iterate (setup z)).headD 0 + +def powerRealizer : Realizer power := + composition (composition setupRealizer IntegerMatrixPrograms.iterateRealizer) (head 0) + +theorem power_eq (a N : ℕ) : power (a,N)=a^N := by + have hnum (n : ℕ) : + IntegerPropagation.numerators (fun _ _ : Fin 1 => a) 0 n 0=a^n := by + induction n with + | zero => simp [IntegerPropagation.numerators] + | succ n ih => simp [IntegerPropagation.numerators,ih,pow_succ] + have hi:=IntegerMatrixPrograms.iterate_ofFn (fun _ _ : Fin 1 => a) 0 N + have hs : (List.ofFn fun _ : Fin 1 => List.ofFn fun _ : Fin 1 => a)=[[a]] := by simp + have hv : (List.ofFn fun x : Fin 1 => if x=0 then (1:ℕ) else 0)=[1] := by simp + rw [hs,hv] at hi + unfold power setup + rw [hi] + simpa using hnum N + +/-- Multiplication uses binary operands; only the exponent controls the +number of iterations. This is sufficient for the dyadic tabulation. -/ +theorem work_power : WorkBound powerRealizer (fun z => z.2+weight z.1) := by + unfold powerRealizer + apply work_then_polynomial _ (polynomial_head 0) + apply work_composition + (work_of_polynomial polynomial_setup (5*Polynomial.X+3) (by + intro z + have hn:=weight_nat_numeric z.2 + rw [←Prod.eta z,weight_prod] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat, + Polynomial.eval_X] + omega)) IntegerMatrixPrograms.work_iterate (Polynomial.X+12) + intro z + simp only [setup,weight_prod,weight_cons,weight_nil,Polynomial.eval_add, + Polynomial.eval_X,Polynomial.eval_ofNat] + have hw:=weight_nat_le (1:ℕ) + norm_num at hw + omega + +end ContingencyTables.BinaryPowerPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/BinarySearchProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinarySearchProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..91f57ff49a7733614401283fbf3e65bead58ec2a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/BinarySearchProgram.lean @@ -0,0 +1,192 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BoundedBinarySearch +import OAI.Combinatorics.ContingencyTables.Machines.NetworkFeasibilityProgram + +namespace OAI + +/-! # A polynomial binary program for monotone endpoint search + +The supplied test is a realized binary predicate. The loop +performs one midpoint test per bit of the upper bound and keeps the +unchanged test data throughout. +-/ + +namespace ContingencyTables.BinarySearchProgram + +open MatchingFPRAS.TreeTyped Polynomial BoundedBinarySearch + +def midpointRealizer : Realizer midpoint := + composition (pair first (composition (pair + (composition (composition (pair second first) subtract) successor) (constant 2)) quotient)) add + +lemma polynomial_midpoint : PolynomialTime midpointRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair + (polynomial_composition + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + polynomial_subtract) polynomial_successor) (polynomial_constant 2)) + polynomial_quotient)) polynomial_add + +variable {A : Type} [Codec A] +variable (test : A×ℕ→Bool) (T : Realizer test) + +abbrev State (A : Type) := A×Window + +def advance (z : ℕ×State A) : State A := + (z.2.1,step (fun t=>test (z.2.1,t)) z.2.2) + +def advanceRealizer : Realizer (advance test) := by + let M : Realizer (fun z : ℕ×State A=>midpoint z.2.2) := + composition (composition second second) midpointRealizer + let P : Realizer (fun z : ℕ×State A=>test (z.2.1,midpoint z.2.2)) := + composition (f := fun z : ℕ×State A=>(z.2.1,midpoint z.2.2)) (g := test) + (pair (composition second first) M) T + let yes : Realizer (fun z : ℕ×State A=>(midpoint z.2.2,z.2.2.2)) := + pair M (composition (composition second second) second) + let no : Realizer (fun z : ℕ×State A=>(z.2.2.1,midpoint z.2.2-1)) := + pair (composition (composition second second) first) (composition M predecessor) + exact pair (composition second first) (choose P yes no) + +lemma polynomial_advance (hT : PolynomialTime T) : PolynomialTime (advanceRealizer test T) := by + unfold advanceRealizer + apply polynomial_pair + · exact polynomial_composition polynomial_second polynomial_first + · apply polynomial_choose + · exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_midpoint)) hT + · exact polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_midpoint) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_second) + · exact polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_first) + (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_midpoint) polynomial_predecessor) + +lemma midpoint_le_max (p : Window) : midpoint p≤ max p.1 p.2 := by + rcases p with ⟨lo,hi⟩ + unfold BoundedBinarySearch.midpoint + omega + +lemma step_le_max (f : ℕ→Bool) (p : Window) : + (step f p).1≤ max p.1 p.2 ∧ (step f p).2≤ max p.1 p.2 := by + have h := midpoint_le_max p + unfold step + split_ifs <;> dsimp only <;> constructor <;> omega + +omit [Codec A] in +lemma fold_context (xs : List ℕ) (s : State A) : + (xs.foldl (fun s i=>advance test (i,s)) s).1=s.1 := by + induction xs generalizing s with + | nil => rfl + | cons i xs ih => exact ih (advance test (i,s)) + +omit [Codec A] in +lemma fold_bounds (xs : List ℕ) (s : State A) (M : ℕ) + (h1 : s.2.1≤M) (h2 : s.2.2≤M) : + (xs.foldl (fun s i=>advance test (i,s)) s).2.1≤M ∧ + (xs.foldl (fun s i=>advance test (i,s)) s).2.2≤M := by + induction xs generalizing s with + | nil => exact ⟨h1,h2⟩ + | cons i xs ih => + have h := step_le_max (fun t=>test (s.1,t)) s.2 + have hm : max s.2.1 s.2.2≤M := max_le h1 h2 + exact ih (advance test (i,s)) (h.1.trans hm) (h.2.trans hm) + +lemma polynomial_loop (hT : PolynomialTime T) : + PolynomialTime (fold (advanceRealizer test T)) := by + apply polynomial_fold (polynomial_advance test T hT) (20*(X+1)) + intro xs s pre _post _he + let S := weight (xs,s) + let out := pre.foldl (fun s i=>advance test (i,s)) s + have hs : weight s≤S := weight_snd (xs,s) + have ha : weight s.1≤S := (weight_fst s).trans hs + have hp : weight s.2≤S := (weight_snd s).trans hs + have hM : weight (max s.2.1 s.2.2)≤S := by + rcases le_total s.2.1 s.2.2 with h | h + · rw [max_eq_right h] + exact (weight_snd s.2).trans hp + · rw [max_eq_left h] + exact (weight_fst s.2).trans hp + have hb := fold_bounds test pre s (max s.2.1 s.2.2) (le_max_left _ _) (le_max_right _ _) + have h1 := weight_nat_small hb.1 + have h2 := weight_nat_small hb.2 + change weight out.2.1≤4*weight (max s.2.1 s.2.2)+1 at h1 + change weight out.2.2≤4*weight (max s.2.1 s.2.2)+1 at h2 + have hc : out.1=s.1 := fold_context test pre s + have ho : weight out=weight out.1+weight out.2.1+weight out.2.2+2 := by + change weight (out.1,(out.2.1,out.2.2))=_ + simp only [weight_prod] + omega + simp only [eval_mul,eval_ofNat,eval_add,eval_X,eval_one] + change weight out≤20*(S+1) + rw [ho,hc] + omega + +def steps (z : A×ℕ) : List ℕ := List.range z.2.size + +def stepsRealizer : Realizer (steps (A := A)) := + composition (composition second bitSize) range + +lemma polynomial_steps : PolynomialTime (stepsRealizer (A := A)) := by + apply polynomial_boundedRange (polynomial_composition polynomial_second polynomial_bitSize) X + intro z + simp only [Function.comp_apply,eval_X] + exact (size_le_weight z.2).trans (weight_snd z) + +def prepare (z : A×ℕ) : List ℕ×State A := (steps z,(z.1,(0,z.2))) + +def prepareRealizer : Realizer (prepare (A := A)) := + pair stepsRealizer (pair first (pair (constant 0) second)) + +lemma polynomial_prepare : PolynomialTime (prepareRealizer (A := A)) := + polynomial_pair polynomial_steps + (polynomial_pair polynomial_first (polynomial_pair (polynomial_constant 0) polynomial_second)) + +def execute (z : A×ℕ) : State A := + (steps z).foldl (fun s i=>advance test (i,s)) (z.1,(0,z.2)) + +def executeRealizer : Realizer (execute test) := + composition (f := prepare (A := A)) + (g := fun z : List ℕ×State A=>z.1.foldl (fun s i=>advance test (i,s)) z.2) + prepareRealizer (fold (advanceRealizer test T)) + +lemma polynomial_execute (hT : PolynomialTime T) : PolynomialTime (executeRealizer test T) := + polynomial_composition polynomial_prepare (polynomial_loop test T hT) + +def search (z : A×ℕ) : ℕ := (execute test z).2.1 + +def searchRealizer : Realizer (search test) := + composition (f := execute test) (g := fun s : State A=>s.2.1) + (executeRealizer test T) (composition second first) + +lemma polynomial_search (hT : PolynomialTime T) : PolynomialTime (searchRealizer test T) := + polynomial_composition (polynomial_execute test T hT) + (polynomial_composition polynomial_second polynomial_first) + +omit [Codec A] in +lemma fold_code (xs : List ℕ) (a : A) (p : Window) : + xs.foldl (fun s i=>advance test (i,s)) (a,p)= + (a,run (fun t=>test (a,t)) xs.length p) := by + induction xs generalizing p with + | nil => rfl + | cons i xs ih => + change xs.foldl (fun s i=>advance test (i,s)) + (a,step (fun t=>test (a,t)) p)=(a,run (fun t=>test (a,t)) (xs.length+1) p) + exact ih _ + +omit [Codec A] in +theorem search_eq (a : A) (K U : ℕ) + (ht : ∀ t,test (a,t)=true ↔ t≤K) (hK : K≤U) : search test (a,U)=K := by + unfold search execute + rw [fold_code] + simp only [steps,List.length_range] + exact congrArg Prod.fst (run_eq_cutoff _ K U U.size ht hK (Nat.lt_size_self U)) + +end ContingencyTables.BinarySearchProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/BooleanChunkProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/BooleanChunkProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..9190542125a79361ec417b055218add24829dba2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/BooleanChunkProgram.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram + +namespace OAI + +/-! # Polynomial partition of a supplied Boolean word into fixed-width rows -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped Polynomial + +def wordChunk (z : (ℕ×List Bool)×ℕ) : List Bool := + (z.1.2.drop (z.2*z.1.1)).take z.1.1 + +def wordChunkRealizer : Realizer wordChunk := + composition (pair + (composition (pair (composition first second) + (composition (pair second (composition first first)) multiply)) dropFast) + (composition first first)) takeFast + +theorem polynomial_wordChunk : PolynomialTime wordChunkRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_first)) polynomial_multiply)) + polynomial_dropFast) + (polynomial_composition polynomial_first polynomial_first)) polynomial_takeFast + +def completeWordRows (z : ℕ×List Bool) : List ℕ := List.range (z.2.length/z.1) + +def completeWordRowsRealizer : Realizer completeWordRows := + composition (composition (pair (composition second listLength) first) quotient) range + +theorem polynomial_completeWordRows : PolynomialTime completeWordRowsRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_listLength) polynomial_first) + polynomial_quotient) X + intro z + simp only [eval_X,Function.comp_apply] + exact (Nat.div_le_self _ _).trans ((list_length_le_weight _).trans (weight_snd z)) + +def wordChunks (z : ℕ×List Bool) : List (List Bool) := + (completeWordRows z).map (fun i => wordChunk (z,i)) + +def wordChunksRealizer : Realizer wordChunks := + composition (pair identity completeWordRowsRealizer) (mapWith wordChunkRealizer) + +theorem polynomial_wordChunks : PolynomialTime wordChunksRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_completeWordRows) + (polynomial_mapWith polynomial_wordChunk) + +lemma wordChunk_ofFn {n k : ℕ} (bits : Fin (n*k) → Bool) (i : Fin n) : + wordChunk ((k,List.ofFn bits),i.val)= + List.ofFn (fun j : Fin k => bits (finProdFinEquiv (i,j))) := by + have hbound : k ≤ n*k-i.val*k := by + apply Nat.le_sub_of_add_le + simpa only [Nat.succ_mul,Nat.add_comm] using + Nat.mul_le_mul_right k (Nat.succ_le_of_lt i.isLt) + apply List.ext_getElem + · simp only [wordChunk,List.length_take,List.length_drop,List.length_ofFn,min_eq_left hbound] + · intro j _ _ + simp only [wordChunk,List.getElem_take,List.getElem_drop,List.getElem_ofFn] + apply congrArg bits + apply Fin.ext + change i.val*k+j=j+k*i.val + ac_rfl + +theorem wordChunks_ofFn {n k : ℕ} (hk : 0 List.ofFn (fun j : Fin k => bits (finProdFinEquiv (i,j)))) := by + have hrows : completeWordRows (k,List.ofFn bits)=List.range n := by + simp only [completeWordRows,List.length_ofFn,Nat.mul_div_cancel _ hk] + unfold wordChunks + rw [hrows] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have hin : i p + | k+1,p => run test k (step test p) + +lemma step_width (test : ℕ→Bool) (p : Window) : + 2*((step test p).2-(step test p).1)≤p.2-p.1 := by + rcases p with ⟨lo,hi⟩ + unfold step midpoint + split_ifs <;> dsimp only <;> omega + +lemma run_width (test : ℕ→Bool) (k : ℕ) (p : Window) : + ((run test k p).2-(run test k p).1)*2^k≤p.2-p.1 := by + induction k generalizing p with + | zero => simp [run] + | succ k ih => + have h := ih (step test p) + have hs := step_width test p + change ((run test k (step test p)).2-(run test k (step test p)).1)*2^(k+1)≤_ + calc + _ = (((run test k (step test p)).2-(run test k (step test p)).1)*2^k)*2 := by + rw [pow_succ] + ring + _ ≤ ((step test p).2-(step test p).1)*2 := Nat.mul_le_mul_right 2 h + _ ≤ p.2-p.1 := by simpa only [Nat.mul_comm] using hs + +lemma step_contains (test : ℕ→Bool) (K : ℕ) + (ht : ∀ t,test t=true ↔ t≤K) (p : Window) + (hlo : p.1≤K) (hhi : K≤p.2) : + (step test p).1≤K ∧ K≤(step test p).2 := by + unfold step + split_ifs with h + · exact ⟨(ht _).mp h,hhi⟩ + · have hm : K exact ⟨hlo,hhi⟩ + | succ k ih => + have hs := step_contains test K ht p hlo hhi + exact ih (step test p) hs.1 hs.2 + +theorem run_eq_cutoff (test : ℕ→Bool) (K U k : ℕ) + (ht : ∀ t,test t=true ↔ t≤K) (hK : K≤U) (hk : U<2^k) : + run test k (0,U)=(K,K) := by + have hb := run_contains test K ht k (0,U) (Nat.zero_le _) hK + have hw := run_width test k (0,U) + have hz : (run test k (0,U)).2-(run test k (0,U)).1=0 := by + simp only [Nat.sub_zero] at hw + by_contra hn + have hp : 1≤(run test k (0,U)).2-(run test k (0,U)).1 := by omega + have hm := Nat.mul_le_mul_right (2^k) hp + nlinarith + apply Prod.ext <;> dsimp only <;> omega + +def find (test : ℕ→Bool) (U : ℕ) : ℕ := + (run test (Nat.clog 2 (U+1)) (0,U)).1 + +theorem find_eq_cutoff (test : ℕ→Bool) (K U : ℕ) + (ht : ∀ t,test t=true ↔ t≤K) (hK : K≤U) : find test U=K := by + have hp : U<2^(Nat.clog 2 (U+1)) := + lt_of_lt_of_le (Nat.lt_succ_self U) (Nat.le_pow_clog (by decide) (U+1)) + exact congrArg Prod.fst (run_eq_cutoff test K U (Nat.clog 2 (U+1)) ht hK hp) + +end ContingencyTables.BoundedBinarySearch + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/BoundedComplementProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/BoundedComplementProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..c72b8125426adfc4f9d9eb8338141442b4031d0f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/BoundedComplementProgram.lean @@ -0,0 +1,131 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BoundedTableComplement +import OAI.Combinatorics.ContingencyTables.Machines.NetworkFeasibilityProgram + +namespace OAI + +/-! # Computing complementary bounded-table margins in binary -/ + +namespace ContingencyTables.BoundedComplementProgram + +open MatchingFPRAS.TreeTyped Polynomial NetworkVertexCode + +abbrev EntryInput := Input×ℕ + +def rowValue (z : EntryInput) : ℕ := + (z.1.2.getD z.2 []).sum-z.1.1.1.getD z.2 0 + +def rowValueRealizer : Realizer rowValue := + composition (pair + (composition (composition (pair (composition first second) second) (getDFast [])) listSum) + (composition (pair (composition (composition first first) first) second) (getDFast 0))) subtract + +lemma polynomial_rowValue : PolynomialTime rowValueRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_getDFast [])) polynomial_listSum) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) (polynomial_getDFast 0))) polynomial_subtract + +def columnValues (z : EntryInput) : List ℕ := z.1.2.map (fun row=>row.getD z.2 0) + +def columnValuesRealizer : Realizer columnValues := + composition (pair second (composition first second)) + (mapWith (composition (pair second first) (getDFast 0))) + +lemma polynomial_columnValues : PolynomialTime columnValuesRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_second)) + (polynomial_mapWith (polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_getDFast 0))) + +def columnValue (z : EntryInput) : ℕ := + (columnValues z).sum-z.1.1.2.getD z.2 0 + +def columnValueRealizer : Realizer columnValue := + composition (pair (composition columnValuesRealizer listSum) + (composition (pair (composition (composition first first) second) second) (getDFast 0))) subtract + +lemma polynomial_columnValue : PolynomialTime columnValueRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_columnValues polynomial_listSum) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_second) (polynomial_getDFast 0))) polynomial_subtract + +def rowIndices (z : Input) : List ℕ := List.range z.1.1.length +def columnIndices (z : Input) : List ℕ := List.range z.1.2.length + +def rowIndicesRealizer : Realizer rowIndices := + composition (composition (composition first first) listLength) range + +def columnIndicesRealizer : Realizer columnIndices := + composition (composition (composition first second) listLength) range + +lemma polynomial_rowIndices : PolynomialTime rowIndicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +lemma polynomial_columnIndices : PolynomialTime columnIndicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.2).trans ((weight_snd z.1).trans (weight_fst z)) + +def complement (z : Input) : Input := + (((rowIndices z).map (fun i=>rowValue (z,i)), + (columnIndices z).map (fun j=>columnValue (z,j))),z.2) + +def complementRealizer : Realizer complement := + pair (pair + (composition (pair identity rowIndicesRealizer) (mapWith rowValueRealizer)) + (composition (pair identity columnIndicesRealizer) (mapWith columnValueRealizer))) second + +lemma polynomial_complement : PolynomialTime complementRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_identity polynomial_rowIndices) + (polynomial_mapWith polynomial_rowValue)) + (polynomial_composition (polynomial_pair polynomial_identity polynomial_columnIndices) + (polynomial_mapWith polynomial_columnValue))) polynomial_second + +lemma rowValue_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (i : Fin m) : + rowValue (data r c b,i.val)=BoundedTableComplement.rows b r i := by + simp only [rowValue,data,ResidualGraphProgram.natCode,List.getD_eq_getElem?_getD, + List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some,Fin.eta,List.sum_ofFn, + BoundedTableComplement.rows,BoundedTableComplement.rowTotal] + +lemma columnValue_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) (j : Fin n) : + columnValue (data r c b,j.val)=BoundedTableComplement.columns b c j := by + simp only [columnValue,columnValues,data,ResidualGraphProgram.natCode,List.map_ofFn, + Function.comp_def,List.getD_eq_getElem?_getD,List.getElem?_ofFn,j.isLt, + dite_true,Option.getD_some,Fin.eta,List.sum_ofFn, + BoundedTableComplement.columns,BoundedTableComplement.columnTotal] + +lemma complement_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + complement (data r c b)=data (BoundedTableComplement.rows b r) + (BoundedTableComplement.columns b c) b := by + unfold complement + apply Prod.ext + · apply Prod.ext + · simp only [rowIndices,data,List.length_ofFn,DirectedBFSCode.range_eq_map,←List.ofFn_eq_map, + List.map_ofFn] + apply congrArg List.ofFn + funext i + exact rowValue_code r c b i + · simp only [columnIndices,data,List.length_ofFn,DirectedBFSCode.range_eq_map,←List.ofFn_eq_map, + List.map_ofFn] + apply congrArg List.ofFn + funext j + exact columnValue_code r c b j + · rfl + +end ContingencyTables.BoundedComplementProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/BoundedPowerProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/BoundedPowerProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee70b4ca066b5352054fbaff553d2a5cc7ed1719 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/BoundedPowerProgram.lean @@ -0,0 +1,40 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BinaryPowerProgram + +namespace OAI + +/-! # Reusing a unary allowance across a binary transition table -/ + +namespace ContingencyTables.BoundedPowerPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped + +def powerInput (z : List Bool×ℕ) : ℕ×ℕ := (2,z.1.length-z.2) + +def powerInputRealizer : Realizer powerInput := + pair (constant 2) (composition (pair (composition first listLength) second) subtract) + +lemma polynomial_powerInput : PolynomialTime powerInputRealizer := + polynomial_pair (polynomial_constant 2) (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_listLength) polynomial_second) + polynomial_subtract) + +def power (z : List Bool×ℕ) : ℕ := BinaryPowerPrograms.power (powerInput z) + +def powerRealizer : Realizer power := + composition powerInputRealizer BinaryPowerPrograms.powerRealizer + +/-- A single allowance list can be shared by all entries in the finite +matrix. Each binary power then has polynomial cost in the supplied data. -/ +theorem polynomial_power : PolynomialTime powerRealizer := by + apply work_composition polynomial_powerInput BinaryPowerPrograms.work_power (Polynomial.X+9) + intro z + have hl: z.1.length ≤ weight z := (list_length_le_weight z.1).trans (weight_fst z) + have hw : weight (2:ℕ)≤9 := by decide + simp only [powerInput,Polynomial.eval_add,Polynomial.eval_X,Polynomial.eval_ofNat] + omega + +theorem power_eq (xs : List Bool) (gap : ℕ) : power (xs,gap)=2^(xs.length-gap) := + BinaryPowerPrograms.power_eq 2 (xs.length-gap) + +end ContingencyTables.BoundedPowerPrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedCompletionWeights.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedCompletionWeights.lean new file mode 100644 index 0000000000000000000000000000000000000000..6772d5575f049ac62c420f2816c61fcf0b7dddc7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedCompletionWeights.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Transport.CanonicalIntegerLaw + +namespace OAI + +/-! # Explicit table weights from the computed dense-law cache -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped GridBoundary +open scoped BigOperators Classical + +abbrev CompletionCache := CanonicalParameters×List ℕ + +def cachedCompletionWeight (z : CompletionCache×Option MatrixCode) : ℕ := + z.2.elim 0 (fun X => z.1.2.getD (canonicalTableIndex (z.1.1,X)) 0) + +def cachedCompletionWeightRealizer : Realizer cachedCompletionWeight := by + let context : Realizer (fun z : CompletionCache×MatrixCode => z.1.1) := + composition first first + let cache : Realizer (fun z : CompletionCache×MatrixCode => z.1.2) := + composition first second + let index := composition (pair context second) canonicalTableIndexRealizer + let entry := composition (pair cache index) (getDFast 0) + exact optionCases (constant 0) entry + +lemma polynomial_cachedCompletionWeight : PolynomialTime cachedCompletionWeightRealizer := by + unfold cachedCompletionWeightRealizer + exact polynomial_optionCases (polynomial_constant 0) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_canonicalTableIndex)) (polynomial_getDFast 0)) + +def completionWeightEntry (z : CompletionCache×Option MatrixCode) : Option MatrixCode×ℕ := + (z.2,cachedCompletionWeight z) + +def completionWeightEntryRealizer : Realizer completionWeightEntry := + pair second cachedCompletionWeightRealizer + +lemma polynomial_completionWeightEntry : PolynomialTime completionWeightEntryRealizer := + polynomial_pair polynomial_second polynomial_cachedCompletionWeight + +def completionWeightInput (z : CanonicalParameters) : CompletionCache×List (Option MatrixCode) := + ((z,canonicalDrawCounts z),completionCandidates z.1) + +def completionWeightInputRealizer : Realizer completionWeightInput := + pair (pair identity canonicalDrawCountsRealizer) + (composition first completionCandidatesRealizer) + +def completionWeightMeasure (z : CanonicalParameters) : ℕ := + canonicalTabulationMeasure z+completionEnumerationMeasure z.1 + +private lemma weight_le_completionMeasure (z : CanonicalParameters) : + weight z≤completionWeightMeasure z := by + unfold completionWeightMeasure canonicalTabulationMeasure + omega + +lemma work_completionWeightInput : + WorkBound completionWeightInputRealizer completionWeightMeasure := by + have hw : WorkBound canonicalDrawCountsRealizer completionWeightMeasure := + work_remeasure work_canonicalDrawCounts Polynomial.X (fun z => by + simp only [Polynomial.eval_X,completionWeightMeasure]; omega) + have he : WorkBound (composition first completionCandidatesRealizer) completionWeightMeasure := by + apply work_composition (work_of_polynomial polynomial_first Polynomial.X + (fun z => by simpa using weight_le_completionMeasure z)) work_completionCandidates Polynomial.X + intro z + simp only [Polynomial.eval_X,completionWeightMeasure] + omega + have hi : WorkBound (identity (A := CanonicalParameters)) completionWeightMeasure := + work_of_polynomial polynomial_identity Polynomial.X + (fun z => by simpa using weight_le_completionMeasure z) + unfold completionWeightInputRealizer + apply work_pair _ he Polynomial.X (fun z => by simpa using weight_le_completionMeasure z) + exact work_pair hi hw Polynomial.X (fun z => by simpa using weight_le_completionMeasure z) + +def completionWeights (z : CanonicalParameters) : List (Option MatrixCode×ℕ) := + (completionCandidates z.1).map + (fun o => (o,cachedCompletionWeight ((z,canonicalDrawCounts z),o))) + +def completionWeightsRealizer : Realizer completionWeights := + composition completionWeightInputRealizer (mapWith completionWeightEntryRealizer) + +section +attribute [local irreducible] completionWeightInputRealizer + +theorem work_completionWeights : WorkBound completionWeightsRealizer completionWeightMeasure := by + unfold completionWeightsRealizer + exact work_then_polynomial work_completionWeightInput + (polynomial_mapWith polynomial_completionWeightEntry) +end + +attribute [local irreducible] canonicalDrawCounts canonicalCounts + +lemma cachedCompletionWeight_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (o : Option (Table R P)) : + cachedCompletionWeight ((((marginCode R,marginCode P),(d,h)), + canonicalDrawCounts ((marginCode R,marginCode P),(d,h))),o.map tableOutput)= + o.elim 0 (fun X => (canonicalCounts R P hd hR hP htotal h).count X) := by + cases o with + | none => rfl + | some X => exact canonicalCounts_computed R P hd hR hP htotal h hq X + +/-- The explicit list contains every feasible table once. Each rejected +free vector has zero weight; the surviving weights are the actual draw counts. -/ +theorem completionWeights_actual {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) (h : ℕ) : + completionWeights ((marginCode R,marginCode P),(d,h))= + List.ofFn (fun k : Fin (((∑ i,R i)+1)^(m*n)) => + let o := BoxCompletion.decode R P htotal (∑ i,R i) (finFunctionFinEquiv.symm k) + (o.map tableOutput,o.elim 0 (fun X => (canonicalCounts R P hd hR hP htotal h).count X))) := by + unfold completionWeights + rw [completionCandidates_code R P htotal,List.map_ofFn] + apply congrArg List.ofFn + funext k + dsimp only [Function.comp_apply] + congr 1 + exact cachedCompletionWeight_actual R P hd hq hR hP htotal h _ + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedDecisionSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedDecisionSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..2c3ee9161e74ef7d9e04a9e128502991c4f0ca98 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedDecisionSemantics.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CachedProfileDecision + +namespace OAI + +/-! # Cached completions implement the same outer-profile transition -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts CompletionTranslation +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +def encodedShortStep (h : ℕ) (x : PaperStates r c) (word : Fin s → Bool) : ShortStep := + (((stateCodeData r c e x,d^12),(d,h)),List.ofFn word) + +/-- This identity holds for every feasible cached completion, including +those not selected by a particular finite random word. -/ +theorem cachedDecision_encoded (htotal : ∑ i,r i=∑ j,c j) (h : ℕ) + (x : PaperStates r c) (word : Fin s → Bool) (A : Table (R x) (P x)) : + cachedDecision (encodedShortStep r c e h x word,tableOutput A)= + stateCode r c e (completionDecision R P x (decodedCodeProposal r c e x word) A) := by + have hp := codeProposal_encoded r c e htotal x word + cases hd : decodedCodeProposal r c e x word with + | none => + rw [hd,Option.map_none] at hp + have hviews : stepCandidateViews (shortStepInput (encodedShortStep r c e h x word))= + stateCode r c e x := by + simp only [stepCandidateViews,stepProposal,shortStepInput,encodedShortStep,hp, + Option.getD_none] + rfl + unfold cachedDecision + rw [hviews] + split_ifs <;> rfl + | some y => + rw [hd,Option.map_some] at hp + have hparams : stepCandidateParameters (shortStepInput (encodedShortStep r c e h x word))= + ((stateCodeData r c e y,d^12),(d,h)) := by + simp only [stepCandidateParameters,stepCandidate,stepCandidateViews,stepProposal, + shortStepInput,encodedShortStep,hp,Option.getD_some] + rfl + have hdata : cachedDecisionInput (encodedShortStep r c e h x word,tableOutput A)= + (((marginCode (R x),marginCode (P x)),(marginCode (R y),marginCode (P y))), + tableOutput A) := by + unfold cachedDecisionInput stepOldMargins stepNewMargins + rw [hparams] + dsimp only [shortStepInput,encodedShortStep] + rw [residualParameters_code,residualParameters_code] + have hviews : stepCandidateViews (shortStepInput (encodedShortStep r c e h x word))= + stateCode r c e y := by + simp only [stepCandidateViews,stepProposal,shortStepInput,encodedShortStep,hp, + Option.getD_some] + have hv := translationValid_code (R x) (R y) (P x) (P y) A + unfold cachedDecision + rw [hdata,hviews] + change (if translationValid _ then stateCode r c e y else stateCode r c e x)= + stateCode r c e (if ∀ i j,0 ≤ (A.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j + then y else x) + by_cases ht : ∀ i j,0 ≤ (A.val i j:ℤ)+between (R x) (R y) (P x) (P y) i j + · rw [ite_eq_left ht,ite_eq_left (hv.mpr ht)] + · rw [ite_eq_right ht,ite_eq_right (fun hv' => ht (hv.mp hv'))] + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedProfileDecision.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedProfileDecision.lean new file mode 100644 index 0000000000000000000000000000000000000000..483cf52d1b33d323806225eced0dc147485887ef --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedProfileDecision.lean @@ -0,0 +1,70 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionSemantics + +namespace OAI + +/-! # Reusing the outer transition test on an enumerated completion -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev ShortStep := ResidualParameters×List Bool + +def shortStepInput (z : ShortStep) : ProfileStepInput := (z.1,(z.2,[])) + +def shortStepInputRealizer : Realizer shortStepInput := + pair first (pair second (constant [])) + +lemma polynomial_shortStepInput : PolynomialTime shortStepInputRealizer := + polynomial_pair polynomial_first (polynomial_pair polynomial_second (polynomial_constant [])) + +def cachedDecisionInput (z : ShortStep×DensePrograms.MatrixCode) : DensePrograms.TranslationData := + ((stepOldMargins (shortStepInput z.1),stepNewMargins (shortStepInput z.1)),z.2) + +def cachedDecisionInputRealizer : Realizer cachedDecisionInput := by + let input := composition (first (A := ShortStep) (B := DensePrograms.MatrixCode)) + shortStepInputRealizer + let old := composition input stepOldMarginsRealizer + let next := composition input stepNewMarginsRealizer + exact pair (pair old next) second + +lemma polynomial_cachedDecisionInput : PolynomialTime cachedDecisionInputRealizer := by + unfold cachedDecisionInputRealizer + exact polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_shortStepInput) + polynomial_stepOldMargins) + (polynomial_composition (polynomial_composition polynomial_first polynomial_shortStepInput) + polynomial_stepNewMargins)) polynomial_second + +def cachedDecision (z : ShortStep×DensePrograms.MatrixCode) : List ℕ×List ℕ := + if DensePrograms.translationValid (cachedDecisionInput z) + then stepCandidateViews (shortStepInput z.1) else z.1.1.1.1.1.1.2 + +def cachedDecisionRealizer : Realizer cachedDecision := by + let input := composition (first (A := ShortStep) (B := DensePrograms.MatrixCode)) + shortStepInputRealizer + let yes := composition input stepCandidateViewsRealizer + let no := composition input stepViews + exact (choose (composition cachedDecisionInputRealizer DensePrograms.translationValidRealizer) + yes no).congr (by intro z; rfl) + +lemma polynomial_cachedDecision : PolynomialTime cachedDecisionRealizer := by + unfold cachedDecisionRealizer + exact polynomial_congr _ (polynomial_choose + (polynomial_composition polynomial_cachedDecisionInput DensePrograms.polynomial_translationValid) + (polynomial_composition (polynomial_composition polynomial_first polynomial_shortStepInput) + polynomial_stepCandidateViews) + (polynomial_composition (polynomial_composition polynomial_first polynomial_shortStepInput) + polynomial_stepViews)) + +/-- Changing only the completion bits cannot change the selected proposal. -/ +lemma shortStep_candidate (z : ProfileStepInput) : + stepCandidateViews (shortStepInput (z.1,z.2.1))=stepCandidateViews z := rfl + +/-- The exact test applied to a cached completion agrees with the +implemented transition when that completion was actually drawn. -/ +lemma cachedDecision_actual (z : ProfileStepInput) : + cachedDecision ((z.1,z.2.1),stepCompletion z)=profileStep z := rfl + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedStepCount.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedStepCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ffe9c32ba42072d95cbb386b3d936693e3fa48b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedStepCount.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CachedCompletionWeights +import OAI.Combinatorics.ContingencyTables.Machines.CachedDecisionSemantics +import OAI.Combinatorics.ContingencyTables.Transport.BooleanEnumeration +import OAI.Combinatorics.ContingencyTables.Transport.ListedIntegerLaw + +namespace OAI + +/-! # Weighted transitions from the cached completion list -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms +open scoped BigOperators Classical + +attribute [local irreducible] cachedDecisionRealizer cachedDecision + +abbrev DecisionQuery := ShortStep×(List ℕ×List ℕ) + +/-- A rejected box entry contributes zero. A valid completion contributes +its cached integer multiplicity precisely when it reaches the target. -/ +def decisionWeight (z : DecisionQuery×(Option MatrixCode×ℕ)) : ℕ := + z.2.1.elim 0 (fun X => if cachedDecision (z.1.1,X)=z.1.2 then z.2.2 else 0) + +def decisionWeightRealizer : Realizer decisionWeight := by + let input : Realizer (fun z : DecisionQuery×(Option MatrixCode×ℕ) => + ((z.1,z.2.2),z.2.1)) := pair (pair first (composition second second)) + (composition second first) + let step : Realizer (fun z : (DecisionQuery×ℕ)×MatrixCode => + (z.1.1.1,z.2)) := pair (composition (composition first first) first) second + let target : Realizer (fun z : (DecisionQuery×ℕ)×MatrixCode => z.1.1.2) := + composition (composition first first) second + let test := composition (pair (composition step cachedDecisionRealizer) target) profileCodeEqual + let entry := choose test (composition first second) (constant 0) + exact (composition input (optionCases (constant 0) entry)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq] + rfl) + +lemma polynomial_decisionWeight : PolynomialTime decisionWeightRealizer := by + unfold decisionWeightRealizer + apply polynomial_congr + exact polynomial_composition + (polynomial_pair (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_second)) + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_optionCases (polynomial_constant 0) (polynomial_choose + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) polynomial_cachedDecision) + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second)) polynomial_profileCodeEqual) + (polynomial_composition polynomial_first polynomial_second) (polynomial_constant 0))) + +def decisionWeightSum (z : DecisionQuery×List (Option MatrixCode×ℕ)) : ℕ := + (z.2.map (fun a => decisionWeight (z.1,a))).sum + +def decisionWeightSumRealizer : Realizer decisionWeightSum := + composition (mapWith decisionWeightRealizer) listSum + +lemma polynomial_decisionWeightSum : PolynomialTime decisionWeightSumRealizer := + polynomial_composition (polynomial_mapWith polynomial_decisionWeight) polynomial_listSum + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.DensePrograms +open scoped BigOperators Classical +noncomputable section + +/-- Free-box enumeration sums each feasible table's weight once. -/ +lemma sum_completionWeights {m n d : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (hd : 14≤d) (hq : m*n≤d) + (hR : ∀ i,d^12≤R i) (hP : ∀ j,d^12≤P j) (htotal : ∑ i,R i=∑ j,P j) + (h : ℕ) (w : MatrixCode → ℕ) : + ((completionWeights ((marginCode R,marginCode P),(d,h))).map + (fun z => z.1.elim 0 (fun X => z.2*w X))).sum= + ∑ X : Table R P,(canonicalCounts R P hd hR hP htotal h).count X*w (tableOutput X) := by + rw [completionWeights_actual R P hd hq hR hP htotal h,List.map_ofFn,List.sum_ofFn] + let f : BoxCompletion.Box m n (∑ i,R i) → ℕ := fun z => + (BoxCompletion.decode R P htotal (∑ i,R i) z).elim 0 + (fun X => (canonicalCounts R P hd hR hP htotal h).count X*w (tableOutput X)) + have hs := finFunctionFinEquiv.symm.sum_comp f + have hi : (∑ k : Fin (((∑ i,R i)+1)^(m*n)), + let o := BoxCompletion.decode R P htotal (∑ i,R i) (finFunctionFinEquiv.symm k) + (o.map tableOutput).elim 0 (fun X => + o.elim 0 (fun T => (canonicalCounts R P hd hR hP htotal h).count T)*w X))= + ∑ z : BoxCompletion.Box m n (∑ i,R i),f z := by + rw [←hs] + apply Finset.sum_congr rfl + intro k _ + dsimp only [f] + cases BoxCompletion.decode R P htotal (∑ i,R i) (finFunctionFinEquiv.symm k) <;> rfl + exact hi.trans (BoxCompletion.sum_decode R P htotal le_rfl _) + +end +end ContingencyTables.DensePrograms + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts CompletionTranslation +open scoped BigOperators Classical +noncomputable section + +attribute [local irreducible] canonicalCounts completionWeights decisionWeightSum + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc +local notation "s" => smallProposalBits (I := Fin m) (J := Fin n) + +lemma decisionWeightSum_actual (htotal : ∑ i,r i=∑ j,c j) (h : ℕ) + (x y : PaperStates r c) (word : Fin s → Bool) : + decisionWeightSum ((encodedShortStep r c e h x word,stateCode r c e y), + completionWeights ((marginCode (R x),marginCode (P x)),(d,h)))= + ∑ A : Table (R x) (P x),if completionDecision R P x (decodedCodeProposal r c e x word) A=y + then (canonicalCounts (R x) (P x) (listed_dimension_fourteen r c hr hc) + (listed_row_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_column_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_paper_totals r c hr hc x) h).count A else 0 := by + let w : MatrixCode → ℕ := fun X => + if cachedDecision (encodedShortStep r c e h x word,X)=stateCode r c e y then 1 else 0 + have he : decisionWeightSum ((encodedShortStep r c e h x word,stateCode r c e y), + completionWeights ((marginCode (R x),marginCode (P x)),(d,h)))= + ((completionWeights ((marginCode (R x),marginCode (P x)),(d,h))).map + (fun z => z.1.elim 0 (fun X => z.2*w X))).sum := by + unfold decisionWeightSum + congr 1 + apply List.map_congr_left + intro z _ + rcases z with ⟨o,a⟩ + cases o with + | none => rfl + | some X => + simp only [decisionWeight,Option.elim_some,w] + split_ifs <;> simp + rw [he,sum_completionWeights (R x) (P x) (listed_dimension_fourteen r c hr hc) + (by simpa only [Fintype.card_prod,Fintype.card_fin] using (listed_dimensions r c hr hc).2.2) + (listed_row_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_column_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_paper_totals r c hr hc x) h w] + apply Finset.sum_congr rfl + intro A _ + simp only [w,cachedDecision_encoded r c e hr hc htotal h x word A, + (stateCode_injective r c e).eq_iff] + split_ifs <;> simp + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedTerminalCount.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedTerminalCount.lean new file mode 100644 index 0000000000000000000000000000000000000000..902dcc67a14dd6ca5c497241596db4474f8bf570 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedTerminalCount.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PreparedTransitionCache +import OAI.Combinatorics.ContingencyTables.Machines.MatrixCodeEquality +import OAI.Combinatorics.ContingencyTables.Sampling.OuterTrialProgram + +namespace OAI + +/-! # Exact terminal counts from the retained dense-completion cache -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms + +abbrev TerminalOutputInput := (ProfileCheckData×ℕ)×(Option MatrixCode×ℕ) + +def terminalOutputEntry (z : TerminalOutputInput) : Option MatrixCode×ℕ := + (z.2.1.bind (fun X => outerTrial (z.1,X)),z.2.2) + +def terminalOutputEntryRealizer : Realizer terminalOutputEntry := + (pair (composition (pair first (composition second first)) + (optionCases (constant none) outerTrialRealizer)) (composition second second)).congr (by + rintro ⟨p,⟨o,n⟩⟩ + cases o <;> rfl) + +lemma polynomial_terminalOutputEntry : PolynomialTime terminalOutputEntryRealizer := by + unfold terminalOutputEntryRealizer + apply polynomial_congr + exact polynomial_pair (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_optionCases (polynomial_constant none) polynomial_outerTrial)) + (polynomial_composition polynomial_second polynomial_second) + +def terminalOutputs (z : TransitionCache) : List (Option MatrixCode×ℕ) := + z.2.2.map (fun entry => terminalOutputEntry (z.1.1,entry)) + +def terminalOutputsRealizer : Realizer terminalOutputs := + composition (pair (composition first first) (composition second second)) + (mapWith terminalOutputEntryRealizer) + +lemma polynomial_terminalOutputs : PolynomialTime terminalOutputsRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_second)) + (polynomial_mapWith polynomial_terminalOutputEntry) + +def successfulWeight (z : MatrixCode×(Option MatrixCode×ℕ)) : ℕ := + z.2.1.elim 0 (fun X => if X=z.1 then z.2.2 else 0) + +def successfulWeightRealizer : Realizer successfulWeight := by + let input : Realizer (fun z : MatrixCode×(Option MatrixCode×ℕ) => + ((z.1,z.2.2),z.2.1)) := pair (pair first (composition second second)) + (composition second first) + let test : Realizer (fun z : (MatrixCode×ℕ)×MatrixCode => decide (z.2=z.1.1)) := + composition (pair second (composition first first)) matrixEqual + let result := choose test (composition first second) (constant 0) + exact (composition input (optionCases (constant 0) result)).congr (by + intro z + simp only [Function.comp_apply,decide_eq_true_eq] + rfl) + +lemma polynomial_successfulWeight : PolynomialTime successfulWeightRealizer := by + unfold successfulWeightRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_second)) + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_optionCases (polynomial_constant 0) (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_first)) polynomial_matrixEqual) + (polynomial_composition polynomial_first polynomial_second) (polynomial_constant 0))) + +def successfulWeightSum (z : MatrixCode×List (Option MatrixCode×ℕ)) : ℕ := + (z.2.map (fun entry => successfulWeight (z.1,entry))).sum + +def successfulWeightSumRealizer : Realizer successfulWeightSum := + composition (mapWith successfulWeightRealizer) listSum + +lemma polynomial_successfulWeightSum : PolynomialTime successfulWeightSumRealizer := + polynomial_composition (polynomial_mapWith polynomial_successfulWeight) polynomial_listSum + +def terminalCount (z : TransitionCache×MatrixCode) : ℕ := + z.1.2.1*successfulWeightSum (z.2,terminalOutputs z.1) + +def terminalCountRealizer : Realizer terminalCount := + composition (pair (composition (composition first second) first) + (composition (pair second (composition first terminalOutputsRealizer)) + successfulWeightSumRealizer)) multiply + +lemma polynomial_terminalCount : PolynomialTime terminalCountRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first) + (polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_terminalOutputs)) polynomial_successfulWeightSum)) + polynomial_multiply + +end ContingencyTables.ProfilePrograms + +namespace ContingencyTables.ProfilePrograms +open DensePrograms + +lemma terminalCount_eq (p : ResidualParameters) (M : ℕ) + (entries : List (Option MatrixCode×ℕ)) (target : MatrixCode) : + terminalCount ((p,(M,entries)),target)= + M*(entries.map (fun entry => entry.1.elim 0 + (fun X => if outerTrial (p.1,X)=some target then entry.2 else 0))).sum := by + unfold terminalCount terminalOutputs successfulWeightSum + rw [List.map_map] + congr 2 + apply List.map_congr_left + rintro ⟨o,n⟩ _ + cases o with + | none => rfl + | some X => + simp only [Function.comp_apply,terminalOutputEntry,Option.bind_some,successfulWeight, + Option.elim_some] + cases outerTrial (p.1,X) with + | none => rfl + | some Y => simp only [Option.elim_some,Option.some.injEq] + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedTerminalSemantics.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedTerminalSemantics.lean new file mode 100644 index 0000000000000000000000000000000000000000..711c284f0e1676b7642f4ae507f79fc6c4a21bd1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CachedTerminalSemantics.lean @@ -0,0 +1,112 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CachedTerminalCount +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionCountSemantics +import OAI.Combinatorics.ContingencyTables.Transport.IntegerPushTransport +import OAI.Combinatorics.ContingencyTables.Transport.ListedOutputSemantics + +namespace OAI + +/-! # Cached terminal success counts equal the actual completion law -/ + +namespace ContingencyTables.SmallGraphProfiles +open ProfilePrograms DensePrograms PhysicalCompletionFibres FirstPaperPhysicalMarginal +open SmallContextCoordinates CompletionCounts CompletionTranslation +open scoped BigOperators Classical +noncomputable section + +variable {m n q : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) +variable (e : Fin q ≃ Cells (paperSmall r c)) +variable (hr : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn r)).length) +variable (hc : 0<(largeIndices ((dimensionAllowance (I := Fin m) (J := Fin n))^20,List.ofFn c)).length) +variable (b h : ℕ) (hb : Nat.clog 2 (stateBound r c+2)≤b) +local notation "d" => dimensionAllowance (I := Fin m) (J := Fin n) +local notation "R" => listedRows r c (d^20) (d^12) (stateCapacity r c) hr +local notation "P" => listedColumns r c (d^20) (d^12) (stateCapacity r c) hc +local notation "f" => 25*(d+b+h+1)^62 + +attribute [local irreducible] canonicalCounts listedCompletionCounts listedUnpaddedCounts + listedCompletionFactor stateCode stateCodeData completionWeights prepareTransitionCache + terminalCount listedRows listedColumns + +lemma tableCode_option_eq (o : Option (Table r c)) (T : Table r c) : + o.map (fun X => matrixCode X.val)=some (matrixCode T.val) ↔ o=some T := by + cases o with + | none => simp + | some X => + simp only [Option.map_some,Option.some.injEq] + constructor + · intro he + exact Subtype.ext (matrixCode_injective he) + · rintro rfl + rfl + +def listedTerminalDecision (x : PaperStates r c) (A : Table (R x) (P x)) : + Option (Table r c) := stateTrial r c ⟨x,(paperListedEquiv r c hr hc x).symm A⟩ + +attribute [local irreducible] listedTerminalDecision + +lemma terminal_completion_sum (x : PaperStates r c) (T : Table r c) : + ((listedCompletionCounts r c hr hc b h hb x).push + (fun A => stateTrial r c ⟨x,A⟩)).count (some T)= + ∑ A : Table (R x) (P x),if listedTerminalDecision r c hr hc x A=some T + then (listedUnpaddedCounts r c hr hc h x).count A* + listedCompletionFactor r c hr hc b h x else 0 := by + have he := IntegerLaw.push_equiv_count + (listedCompletionCounts r c hr hc b h hb x) (listedUnpaddedCounts r c hr hc h x) + (paperListedEquiv r c hr hc x) (listedCompletionFactor r c hr hc b h x) + (listedTerminalDecision r c hr hc x) + (listedCompletionCounts_count r c hr hc b h hb x) (some T) + simpa only [listedTerminalDecision,Equiv.symm_apply_apply] using he + +lemma terminal_cache_sum (x : PaperStates r c) (T : Table r c) : + ((completionWeights ((marginCode (R x),marginCode (P x)),(d,h))).map + (fun entry => entry.1.elim 0 (fun X => + if outerTrial ((stateCodeData r c e x,d^12),X)=some (matrixCode T.val) + then entry.2 else 0))).sum= + ∑ A : Table (R x) (P x),if listedTerminalDecision r c hr hc x A=some T + then (listedUnpaddedCounts r c hr hc h x).count A else 0 := by + let w : MatrixCode → ℕ := fun X => + if outerTrial ((stateCodeData r c e x,d^12),X)=some (matrixCode T.val) then 1 else 0 + have he : ((completionWeights ((marginCode (R x),marginCode (P x)),(d,h))).map + (fun entry => entry.1.elim 0 (fun X => + if outerTrial ((stateCodeData r c e x,d^12),X)=some (matrixCode T.val) + then entry.2 else 0))).sum= + ((completionWeights ((marginCode (R x),marginCode (P x)),(d,h))).map + (fun entry => entry.1.elim 0 (fun X => entry.2*w X))).sum := by + congr 1 + apply List.map_congr_left + rintro ⟨o,n⟩ _ + cases o with + | none => rfl + | some X => simp only [Option.elim_some,w]; split_ifs <;> simp + rw [he,sum_completionWeights (R x) (P x) (listed_dimension_fourteen r c hr hc) + (by simpa only [Fintype.card_prod,Fintype.card_fin] using (listed_dimensions r c hr hc).2.2) + (listed_row_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_column_padding r c (d^20) (d^12) (stateCapacity r c) hr hc x) + (listed_paper_totals r c hr hc x) h w] + apply Finset.sum_congr rfl + intro A _ + have ho := actualOuterTrial r c e hr hc x ((paperListedEquiv r c hr hc x).symm A) + rw [Equiv.apply_symm_apply] at ho + simp only [w,ho,tableCode_option_eq] + unfold listedTerminalDecision listedUnpaddedCounts + split_ifs <;> simp + +lemma terminalCount_actual (x : PaperStates r c) (T : Table r c) : + terminalCount (prepareTransitionCache + ((((stateCodeData r c e x,d^12),(d,h)),f)),matrixCode T.val)= + ((listedCompletionCounts r c hr hc b h hb x).push + (fun A => stateTrial r c ⟨x,A⟩)).count (some T) := by + rw [prepareTransitionCache_encoded r c e hr hc,terminalCount_eq, + terminal_cache_sum r c e hr hc h x T,terminal_completion_sum r c hr hc b h hb x T, + Finset.mul_sum] + apply Finset.sum_congr rfl + intro A _ + unfold listedCompletionFactor + split_ifs + · exact Nat.mul_comm _ _ + · exact Nat.mul_zero _ + +end +end ContingencyTables.SmallGraphProfiles + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CanonicalInitialEncoding.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CanonicalInitialEncoding.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8e483714e9f62556374acc0c19cda4748008b42 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CanonicalInitialEncoding.lean @@ -0,0 +1,117 @@ +import OAI.Combinatorics.ContingencyTables.Machines.InitialChoiceProgram +import OAI.Combinatorics.ContingencyTables.Counting.CompanionArithmeticProposal +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteCollections +import Mathlib.Data.List.NodupEquivFin + +namespace OAI + +/-! # Canonical paired-label order for the initial binary program + +The order is the explicit list of cells, then their copies, then the +two sides of each pair. The code is obtained directly from the sampled +Boolean rows, so no enumeration of the set-valued state space occurs. +-/ + +namespace ContingencyTables.CanonicalInitialEncoding + +open MatchingFPRAS MatchingFPRAS.TreeTyped +open CommonBasesFPRAS InitialTransversals FixedCardinalityMixture InitialFactorialBits +open scoped BigOperators Classical + +def pairValue (b : Bool) : List ℕ := [if b then 1 else 0,if b then 0 else 1] + +def pairValueRealizer : Realizer pairValue := + composition (pair (choose identity (constant 1) (constant 0)) + (composition (pair (choose identity (constant 0) (constant 1)) (constant [])) listCons)) listCons + +theorem polynomial_pairValue : PolynomialTime pairValueRealizer := + polynomial_composition (polynomial_pair + (polynomial_choose polynomial_identity (polynomial_constant 1) (polynomial_constant 0)) + (polynomial_composition (polynomial_pair + (polynomial_choose polynomial_identity (polynomial_constant 0) (polynomial_constant 1)) + (polynomial_constant [])) polynomial_listCons)) polynomial_listCons + +def pairedCode (rows : List (List Bool)) : List ℕ := rows.flatten.flatMap pairValue + +def pairedCodeRealizer : Realizer pairedCode := composition flatten (flatMapPoly pairValueRealizer) + +theorem polynomial_pairedCode : PolynomialTime pairedCodeRealizer := + polynomial_composition polynomial_flatten (polynomial_flatMapPoly polynomial_pairValue) + +def initialCode (z : InitialChoiceProgram.Input) : List ℕ := pairedCode (InitialChoiceProgram.choiceCode z) + +def initialCodeRealizer : Realizer initialCode := + composition InitialChoiceProgram.choiceCodeRealizer pairedCodeRealizer + +theorem polynomial_initialCode : PolynomialTime initialCodeRealizer := + polynomial_composition InitialChoiceProgram.polynomial_choiceCode polynomial_pairedCode + +noncomputable section +variable {q : ℕ} (b : Fin q → ℕ) + +def copyOrder : List (Copy b) := (List.finRange q).sigma (fun i => List.finRange (b i)) + +def pairOrder : List (Copy b×Bool) := (copyOrder b).product [false,true] + +lemma copyOrder_nodup : (copyOrder b).Nodup := + (List.nodup_finRange q).sigma (fun i => List.nodup_finRange (b i)) + +lemma copyOrder_mem (p : Copy b) : p∈copyOrder b := by + rcases p with ⟨i,k⟩ + simp [copyOrder] + +lemma pairOrder_nodup : (pairOrder b).Nodup := + (copyOrder_nodup b).product (by decide) + +lemma pairOrder_mem (p : Copy b×Bool) : p∈pairOrder b := by + rcases p with ⟨p,t⟩ + have hp := copyOrder_mem b p + cases t <;> simp [pairOrder,hp] + +def coordinateEquiv : (Copy b×Bool) ≃ Fin (pairOrder b).length := + (List.Nodup.getEquivOfForallMemList (pairOrder b) (pairOrder_nodup b) (pairOrder_mem b)).symm + +lemma coordinateOrder : List.ofFn (coordinateEquiv b).symm=pairOrder b := by + change List.ofFn (pairOrder b).get=pairOrder b + exact List.ofFn_get (pairOrder b) + +lemma encodeSet_eq_map (S : Set (Copy b×Bool)) : + CompanionArithmeticProposal.encodeSet (coordinateEquiv b) S= + (pairOrder b).map (fun p => if p∈S then 1 else 0) := by + have h := congrArg (List.map (fun p => if p∈S then (1:ℕ) else 0)) (coordinateOrder b) + rw [List.map_ofFn] at h + exact h + +lemma pairedCode_eq_map (v : ∀ i,Fin (b i) → Bool) : + pairedCode (List.ofFn (fun i => List.ofFn (v i)))= + (pairOrder b).map (fun p => if p∈encode b (fun i => subsetEquiv (b i) (v i)) then 1 else 0) := by + simp only [pairedCode,pairOrder,copyOrder,List.sigma,List.product,List.ofFn_eq_map, + List.flatten_eq_flatMap,List.flatMap_map,List.flatMap_assoc,List.map_flatMap,List.map_map] + apply List.flatMap_congr + intro i _ + simp only [id_eq,List.flatMap_map,Function.comp_def] + apply List.flatMap_congr + intro k _ + cases hv : v i k <;> + simp [pairValue,subsetEquiv,hv] + +/-- The explicit paired list order gives the same encoded set as the +semantic local choices, including cells of capacity zero. -/ +theorem pairedCode_encode (v : ∀ i,Fin (b i) → Bool) : + pairedCode (List.ofFn (fun i => List.ofFn (v i)))= + CompanionArithmeticProposal.encodeSet (coordinateEquiv b) + (encode b (fun i => subsetEquiv (b i) (v i))) := by + rw [encodeSet_eq_map] + exact pairedCode_eq_map b v + +theorem initialCode_ofFn (B : ℕ) (hB : 0 FixedCardinalityMixture.vectorDraw B (b i) (wordEquiv b B bits i)) + +end +end ContingencyTables.CanonicalInitialEncoding + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CellLowerTestProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CellLowerTestProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c3a60d1dbcdfc555a82eedb2dcdeea46966e7fa --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CellLowerTestProgram.lean @@ -0,0 +1,144 @@ +import OAI.Combinatorics.ContingencyTables.Machines.LowerCapacityProgram +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteOps + +namespace OAI + +/-! # The executed feasibility test with one extra lower cell bound -/ + +namespace ContingencyTables.CellLowerTestProgram + +open MatchingFPRAS.TreeTyped Polynomial + +abbrev Context := NetworkVertexCode.Input×(ℕ×ℕ) +abbrev Input := Context×ℕ + +def shifted (z : Input) : NetworkVertexCode.Input := + ((ListSubtractProgram.subtractAt ((z.1.1.1.1,z.1.2.1),z.2), + ListSubtractProgram.subtractAt ((z.1.1.1.2,z.1.2.2),z.2)), + LowerCapacityProgram.matrix ((z.1.1.2,z.1.2),z.2)) + +def rowInputRealizer : Realizer (fun z : Input=>((z.1.1.1.1,z.1.2.1),z.2)) := + pair (pair (composition (composition (composition first first) first) first) + (composition (composition first second) first)) second + +def columnInputRealizer : Realizer (fun z : Input=>((z.1.1.1.2,z.1.2.2),z.2)) := + pair (pair (composition (composition (composition first first) first) second) + (composition (composition first second) second)) second + +def capacityInputRealizer : Realizer (fun z : Input=>((z.1.1.2,z.1.2),z.2)) := + pair (pair (composition (composition first first) second) (composition first second)) second + +lemma polynomial_rowInput : PolynomialTime rowInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_first)) + polynomial_second + +lemma polynomial_columnInput : PolynomialTime columnInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) polynomial_second)) + polynomial_second + +lemma polynomial_capacityInput : PolynomialTime capacityInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_second)) polynomial_second + +def shiftedRealizer : Realizer shifted := + pair (pair + (composition (f := fun z : Input=>((z.1.1.1.1,z.1.2.1),z.2)) + (g := ListSubtractProgram.subtractAt) rowInputRealizer ListSubtractProgram.subtractAtRealizer) + (composition (f := fun z : Input=>((z.1.1.1.2,z.1.2.2),z.2)) + (g := ListSubtractProgram.subtractAt) columnInputRealizer ListSubtractProgram.subtractAtRealizer)) + (composition (f := fun z : Input=>((z.1.1.2,z.1.2),z.2)) + (g := LowerCapacityProgram.matrix) capacityInputRealizer LowerCapacityProgram.matrixRealizer) + +lemma polynomial_shifted : PolynomialTime shiftedRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition polynomial_rowInput ListSubtractProgram.polynomial_subtractAt) + (polynomial_composition polynomial_columnInput ListSubtractProgram.polynomial_subtractAt)) + (polynomial_composition polynomial_capacityInput LowerCapacityProgram.polynomial_matrix) + +def guards (z : Input) : Bool := + decide (z.2≤z.1.1.1.1.getD z.1.2.1 0) && + (decide (z.2≤z.1.1.1.2.getD z.1.2.2 0) && + decide (z.2≤ResidualGraphProgram.capacityEntry (z.1.1.2,z.1.2))) + +def guardsRealizer : Realizer guards := by + let rowBound : Realizer (fun z : Input=>z.1.1.1.1.getD z.1.2.1 0) := + composition (composition rowInputRealizer first) (getDFast 0) + let columnBound : Realizer (fun z : Input=>z.1.1.1.2.getD z.1.2.2 0) := + composition (composition columnInputRealizer first) (getDFast 0) + let capacityBound : Realizer (fun z : Input=>ResidualGraphProgram.capacityEntry (z.1.1.2,z.1.2)) := + composition (composition capacityInputRealizer first) ResidualGraphProgram.capacityEntryRealizer + exact composition (pair (composition (pair second rowBound) leNat) + (composition (pair (composition (pair second columnBound) leNat) + (composition (pair second capacityBound) leNat)) boolAnd)) boolAnd + +lemma polynomial_guards : PolynomialTime guardsRealizer := by + unfold guardsRealizer + apply polynomial_composition + · apply polynomial_pair + · exact polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_rowInput polynomial_first) + (polynomial_getDFast 0))) polynomial_leNat + · apply polynomial_composition + · apply polynomial_pair + · exact polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_columnInput polynomial_first) + (polynomial_getDFast 0))) polynomial_leNat + · exact polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_capacityInput polynomial_first) + ResidualGraphProgram.polynomial_capacityEntry)) polynomial_leNat + · exact polynomial_boolAnd + · exact polynomial_boolAnd + +def test (z : Input) : Bool := guards z && NetworkFeasibilityProgram.test (shifted z) + +def testRealizer : Realizer test := + composition (pair guardsRealizer + (composition (f := shifted) (g := NetworkFeasibilityProgram.test) + shiftedRealizer NetworkFeasibilityProgram.testRealizer)) boolAnd + +lemma polynomial_test : PolynomialTime testRealizer := + polynomial_composition (polynomial_pair polynomial_guards + (polynomial_composition polynomial_shifted NetworkFeasibilityProgram.polynomial_test)) + polynomial_boolAnd + +lemma shifted_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) (t : ℕ) : + shifted ((NetworkVertexCode.data r c b,(i.val,j.val)),t)= + NetworkVertexCode.data (BoundedCellShift.margin r i t) + (BoundedCellShift.margin c j t) (BoundedCellShift.lower b i j t) := by + unfold shifted NetworkVertexCode.data + rw [ListSubtractProgram.subtractAt_ofFn,ListSubtractProgram.subtractAt_ofFn, + LowerCapacityProgram.matrix_code] + +lemma guards_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) (t : ℕ) : + guards ((NetworkVertexCode.data r c b,(i.val,j.val)),t)=true ↔ + t≤r i ∧ t≤c j ∧ t≤b i j := by + dsimp only [guards, NetworkVertexCode.data] + rw [ResidualGraphProgram.capacityEntry_code] + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn, + i.isLt,j.isLt,dite_true,Option.getD_some,Fin.eta,Bool.and_eq_true] + constructor + · rintro ⟨hr,hc,hb⟩ + exact ⟨_root_.of_decide_eq_true hr,_root_.of_decide_eq_true hc,_root_.of_decide_eq_true hb⟩ + · rintro ⟨hr,hc,hb⟩ + exact ⟨_root_.decide_eq_true hr,_root_.decide_eq_true hc,_root_.decide_eq_true hb⟩ + +theorem test_correct {m n : ℕ} (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) (t : ℕ) : + test ((NetworkVertexCode.data r c b,(i.val,j.val)),t)=true ↔ + ∃ X,HasMargins X r c ∧ (∀ u v,X u v≤b u v) ∧ t≤X i j := by + rw [test,Bool.and_eq_true,guards_code,shifted_code,NetworkFeasibilityProgram.test_correct hEK] + simpa only [and_assoc] using (BoundedCellShift.feasible_lower_iff r c b i j t).symm + +end ContingencyTables.CellLowerTestProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CellMaximumProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CellMaximumProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..76cff30cd30c3874bb7dbc1c8ac620de879a36f1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CellMaximumProgram.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CellLowerTestProgram +import OAI.Combinatorics.ContingencyTables.Machines.BinarySearchProgram + +namespace OAI + +/-! # Computing an attained cell maximum by binary feasibility search + +A finite maximum is used only to prove the result of the executed binary +search. The program never enumerates feasible tables. +-/ + +namespace ContingencyTables.CellMaximumProgram + +open MatchingFPRAS.TreeTyped CellLowerTestProgram +open scoped Classical + +def bound (z : Context) : ℕ := ResidualGraphProgram.capacityEntry (z.1.2,z.2) + +def boundRealizer : Realizer bound := + composition (pair (composition first second) second) ResidualGraphProgram.capacityEntryRealizer + +lemma polynomial_bound : PolynomialTime boundRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + ResidualGraphProgram.polynomial_capacityEntry + +def maximum (z : Context) : ℕ := BinarySearchProgram.search test (z,bound z) + +def maximumRealizer : Realizer maximum := + composition (f := fun z : Context=>(z,bound z)) + (g := BinarySearchProgram.search test) + (pair identity boundRealizer) (BinarySearchProgram.searchRealizer test testRealizer) + +lemma polynomial_maximum : PolynomialTime maximumRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_bound) + (BinarySearchProgram.polynomial_search test testRealizer polynomial_test) + +lemma bound_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) : + bound (NetworkVertexCode.data r c b,(i.val,j.val))=b i j := + ResidualGraphProgram.capacityEntry_code b i j + +/-- For every feasible instance the computed value is attained, and it +bounds the same coordinate of every other feasible table. -/ +theorem maximum_correct {m n : ℕ} (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) + (hne : ∃ X,HasMargins X r c ∧ ∀ u v,X u v≤b u v) : + ∃ X,HasMargins X r c ∧ (∀ u v,X u v≤b u v) ∧ + X i j=maximum (NetworkVertexCode.data r c b,(i.val,j.val)) ∧ + ∀ Y,HasMargins Y r c → (∀ u v,Y u v≤b u v) → Y i j≤X i j := by + let S : Finset (BoundedTable r c b) := Finset.univ + have hS : S.Nonempty := by + obtain ⟨X,hm,hb⟩ := hne + exact ⟨⟨⟨X,hm⟩,hb⟩,Finset.mem_univ _⟩ + obtain ⟨M,hM,hmax⟩ := Finset.exists_max_image S + (fun X : BoundedTable r c b=>X.val.val i j) hS + have ht (t : ℕ) : + test ((NetworkVertexCode.data r c b,(i.val,j.val)),t)=true ↔ t≤M.val.val i j := by + rw [CellLowerTestProgram.test_correct hEK] + constructor + · rintro ⟨X,hm,hb,hx⟩ + exact hx.trans (hmax ⟨⟨X,hm⟩,hb⟩ (Finset.mem_univ _)) + · intro hx + exact ⟨M.val.val,M.val.property,M.property,hx⟩ + have he : maximum (NetworkVertexCode.data r c b,(i.val,j.val))=M.val.val i j := by + unfold maximum + rw [bound_code] + exact BinarySearchProgram.search_eq test _ _ _ ht (M.property i j) + exact ⟨M.val.val,M.val.property,M.property,he.symm, + fun Y hm hb=>hmax ⟨⟨Y,hm⟩,hb⟩ (Finset.mem_univ _)⟩ + +end ContingencyTables.CellMaximumProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CellMinimumProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CellMinimumProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..f56c504a43c6037113b3560df984e2ba49655c34 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CellMinimumProgram.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CellMaximumProgram +import OAI.Combinatorics.ContingencyTables.Machines.BoundedComplementProgram + +namespace OAI + +/-! # Computing an attained minimum through the complementary table + +Complementation changes the lower endpoint query to the +upper endpoint query and preserves every cell capacity. +-/ + +namespace ContingencyTables.CellMinimumProgram + +open MatchingFPRAS.TreeTyped CellLowerTestProgram + +def complemented (z : Context) : Context := (BoundedComplementProgram.complement z.1,z.2) + +def complementedRealizer : Realizer complemented := + pair (composition (f := fun z : Context=>z.1) + (g := BoundedComplementProgram.complement) first BoundedComplementProgram.complementRealizer) second + +lemma polynomial_complemented : PolynomialTime complementedRealizer := + polynomial_pair (polynomial_composition polynomial_first + BoundedComplementProgram.polynomial_complement) polynomial_second + +def minimum (z : Context) : ℕ := + CellMaximumProgram.bound z-CellMaximumProgram.maximum (complemented z) + +def minimumRealizer : Realizer minimum := + composition (f := fun z : Context=> + (CellMaximumProgram.bound z,CellMaximumProgram.maximum (complemented z))) + (g := fun z : ℕ×ℕ=>z.1-z.2) + (pair CellMaximumProgram.boundRealizer + (composition (f := complemented) (g := CellMaximumProgram.maximum) + complementedRealizer CellMaximumProgram.maximumRealizer)) subtract + +lemma polynomial_minimum : PolynomialTime minimumRealizer := + polynomial_composition (polynomial_pair CellMaximumProgram.polynomial_bound + (polynomial_composition polynomial_complemented CellMaximumProgram.polynomial_maximum)) + polynomial_subtract + +lemma complemented_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) : + complemented (NetworkVertexCode.data r c b,(i.val,j.val))= + (NetworkVertexCode.data (BoundedTableComplement.rows b r) + (BoundedTableComplement.columns b c) b,(i.val,j.val)) := by + unfold complemented + rw [BoundedComplementProgram.complement_code] + +/-- The returned lower endpoint is attained and is no larger than the +selected coordinate of any feasible bounded table. -/ +theorem minimum_correct {m n : ℕ} (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) + (i : Fin m) (j : Fin n) + (hne : ∃ X,HasMargins X r c ∧ ∀ u v,X u v≤b u v) : + ∃ X,HasMargins X r c ∧ (∀ u v,X u v≤b u v) ∧ + X i j=minimum (NetworkVertexCode.data r c b,(i.val,j.val)) ∧ + ∀ Y,HasMargins Y r c → (∀ u v,Y u v≤b u v) → X i j≤Y i j := by + obtain ⟨X₀,hx,hxb⟩ := hne + have hn : ∃ Y,HasMargins Y (BoundedTableComplement.rows b r) + (BoundedTableComplement.columns b c) ∧ ∀ u v,Y u v≤b u v := + ⟨BoundedTableComplement.complement b X₀, + BoundedTableComplement.complement_margins b X₀ r c hx hxb, + BoundedTableComplement.complement_bounds b X₀⟩ + obtain ⟨Y,hy,hyb,hvalue,hmax⟩ := CellMaximumProgram.maximum_correct hEK + (BoundedTableComplement.rows b r) (BoundedTableComplement.columns b c) b i j hn + refine ⟨BoundedTableComplement.complement b Y, + BoundedTableComplement.complement_reverse_margins b X₀ Y r c hx hxb hy hyb, + BoundedTableComplement.complement_bounds b Y,?_,?_⟩ + · unfold minimum + rw [CellMaximumProgram.bound_code,complemented_code,←hvalue] + rfl + · intro Z hz hzb + have hb := hmax (BoundedTableComplement.complement b Z) + (BoundedTableComplement.complement_margins b Z r c hz hzb) + (BoundedTableComplement.complement_bounds b Z) + change b i j-Y i j≤Z i j + change b i j-Z i j≤Y i j at hb + omega + +end ContingencyTables.CellMinimumProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CompletionEnumerationProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CompletionEnumerationProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..6bf79b4c19cc629915bd061ebc128fa20e3ca22b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CompletionEnumerationProgram.lean @@ -0,0 +1,101 @@ +import OAI.Combinatorics.ContingencyTables.Transport.BoxCompletion +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGridWords +import OAI.Combinatorics.ContingencyTables.Dense.DenseCanonicalProgram + +namespace OAI + +/-! # Explicit free-box enumeration with binary completion tests -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms +open scoped BigOperators Classical + +abbrev CompletionMargins := List ℕ×List ℕ + +def completionEnumerationData (z : CompletionMargins) : GridEnumerationData := + ((zeroGrid z).map (fun _ => false),z.1.sum+1) + +def completionEnumerationDataRealizer : Realizer completionEnumerationData := by + let dims := composition zeroGridRealizer (map (constant false)) + let base : Realizer (fun z : CompletionMargins => z.1.sum+1) := + composition (composition first listSum) successor + exact pair dims base + +lemma polynomial_completionEnumerationData : PolynomialTime completionEnumerationDataRealizer := by + unfold completionEnumerationDataRealizer + exact polynomial_pair (polynomial_composition polynomial_zeroGrid + (polynomial_map (polynomial_constant false))) + (polynomial_composition (polynomial_composition polynomial_first polynomial_listSum) + polynomial_successor) + +def completionCandidate (z : CompletionMargins×List ℕ) : Option MatrixCode := + acceptCompletion (z.1,unflattenGrid z) + +def completionCandidateRealizer : Realizer completionCandidate := + composition (pair first unflattenGridRealizer) acceptCompletionRealizer + +lemma polynomial_completionCandidate : PolynomialTime completionCandidateRealizer := + polynomial_composition (polynomial_pair polynomial_first polynomial_unflattenGrid) + polynomial_acceptCompletion + +/-- Rejected candidates remain as `none`, allowing later integer sums +to ignore them without adding a second enumeration or an ordering oracle. -/ +def completionCandidates (z : CompletionMargins) : List (Option MatrixCode) := + (gridWords (completionEnumerationData z)).map (fun v => completionCandidate (z,v)) + +def completionCandidatesRealizer : Realizer completionCandidates := + composition (pair identity (composition completionEnumerationDataRealizer gridWordsRealizer)) + (mapWith completionCandidateRealizer) + +def completionEnumerationMeasure (z : CompletionMargins) : ℕ := + gridStateCount (completionEnumerationData z)+weight z + +theorem work_completionCandidates : + WorkBound completionCandidatesRealizer completionEnumerationMeasure := by + have hp : WorkBound completionEnumerationDataRealizer completionEnumerationMeasure := + work_of_polynomial polynomial_completionEnumerationData Polynomial.X (fun z => by + simp only [completionEnumerationMeasure,Polynomial.eval_X]; omega) + obtain ⟨p,hp'⟩ := hp + have hg : WorkBound (composition completionEnumerationDataRealizer gridWordsRealizer) + completionEnumerationMeasure := by + apply work_composition ⟨p,hp'⟩ work_gridWords (Polynomial.X+p) + intro z + have hw := hp' z + simp only [completionEnumerationMeasure,Polynomial.eval_add,Polynomial.eval_X] + change gridStateCount (completionEnumerationData z)+weight (completionEnumerationData z)≤_ + change _≤p.eval (completionEnumerationMeasure z) at hw + unfold completionEnumerationMeasure at hw + omega + unfold completionCandidatesRealizer + apply work_then_polynomial _ (polynomial_mapWith polynomial_completionCandidate) + exact work_pair (work_of_polynomial polynomial_identity Polynomial.X (fun z => by + simp only [completionEnumerationMeasure,Polynomial.eval_X]; omega)) hg Polynomial.X + (fun z => by simp only [completionEnumerationMeasure,Polynomial.eval_X]; omega) + +lemma gridWords_finFunctions (xs : List Bool) (N q : ℕ) (hq : xs.length=q) : + gridWords (xs,N+1)=List.ofFn (fun k : Fin ((N+1)^q) => + List.ofFn (fun i : Fin q => ((finFunctionFinEquiv.symm k) i).val)) := by + rw [gridWords_eq_length xs (N+1) q hq] + rfl + +theorem completionCandidates_code {m n : ℕ} (R : Option (Fin m) → ℕ) + (P : Option (Fin n) → ℕ) (htotal : ∑ i,R i=∑ j,P j) : + completionCandidates (marginCode R,marginCode P)= + List.ofFn (fun k : Fin (((∑ i,R i)+1)^(m*n)) => + (BoxCompletion.decode R P htotal (∑ i,R i) (finFunctionFinEquiv.symm k)).map tableOutput) := by + have hsum : (marginCode R).sum=∑ i,R i := by + simp only [marginCode,List.sum_cons,List.sum_ofFn,Fintype.sum_option] + have hlen : ((zeroGrid (marginCode R,marginCode P)).map (fun _ => false)).length=m*n := by + simp only [zeroGrid,List.length_map,cellPairs,List.length_range,marginCode, + List.tail_cons,List.length_ofFn] + unfold completionCandidates completionEnumerationData + rw [hsum,gridWords_finFunctions _ (∑ i,R i) (m*n) hlen,List.map_ofFn] + apply congrArg List.ofFn + funext k + dsimp only [Function.comp_apply,completionCandidate] + rw [unflattenGrid_code] + exact BoxCompletion.acceptCompletion_eq R P htotal (finFunctionFinEquiv.symm k) + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/CorrectionValueProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/CorrectionValueProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..57338d508bd9b5843553acfecc81754e29e78acf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/CorrectionValueProgram.lean @@ -0,0 +1,110 @@ +import OAI.Combinatorics.ContingencyTables.Machines.PowerApproximationProgram + +namespace OAI + +/-! # Binary composition of the correction value + +The input contains the computed grid exponent, phase ratio, point +penalty, population factor and two precision marker lists. Normalized +fraction multiplication supplies a positive denominator for the signed +exponent passed to the executed power approximation. +-/ + +namespace ContingencyTables.CorrectionValueProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev Frame := (ℕ×TreeFraction.Fraction)×TreeFraction.Fraction + +def weighted (z : Frame) : TreeFraction.Fraction := TreeFraction.mul (z.1.2,z.2) +def weightedRealizer : Realizer weighted := + composition (f := fun z : Frame => (z.1.2,z.2)) (g := TreeFraction.mul) + (pair (composition first second) second) TreeFraction.mulRealizer +lemma polynomial_weighted : PolynomialTime weightedRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second) TreeFraction.polynomial_mul + +def exponentInput (z : Frame) : SignedFloorProgram.Input := + ((z.1.1*(weighted z).2,(weighted z).1),(weighted z).2) +def exponentInputRealizer : Realizer exponentInput := + pair (pair + (composition (f := fun z : Frame => (z.1.1,(weighted z).2)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (composition first first) (composition weightedRealizer second)) multiply) + (composition weightedRealizer first)) (composition weightedRealizer second) +lemma polynomial_exponentInput : PolynomialTime exponentInputRealizer := + polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_weighted polynomial_second)) polynomial_multiply) + (polynomial_composition polynomial_weighted polynomial_first)) + (polynomial_composition polynomial_weighted polynomial_second) + +lemma weighted_denominator_pos (z : Frame) : 0<(weighted z).2 := + TreeFraction.normalize_den_pos _ + +lemma exponentInput_value (z : Frame) : + ((exponentInput z).1.1-(exponentInput z).1.2:ℚ)/(exponentInput z).2= + (z.1.1:ℚ)-TreeFraction.val z.1.2*TreeFraction.val z.2 := by + have hd : ((weighted z).2:ℚ)≠0 := by exact_mod_cast (weighted_denominator_pos z).ne' + have hw : TreeFraction.val (weighted z)=TreeFraction.val z.1.2*TreeFraction.val z.2 := + TreeFraction.mul_val _ _ + rw [←hw] + simp only [exponentInput,Nat.cast_mul,TreeFraction.val] + field_simp [hd] + +abbrev Input := (Frame×TreeFraction.Fraction)×(List Bool×List Bool) + +def powerInput (z : Input) : PowerApproximationProgram.Input := + (exponentInput z.1.1,z.2) +def powerInputRealizer : Realizer powerInput := + pair (composition (composition first first) exponentInputRealizer) second +lemma polynomial_powerInput : PolynomialTime powerInputRealizer := + polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_exponentInput) + polynomial_second + +def power (z : Input) : TreeFraction.Fraction := PowerApproximationProgram.output (powerInput z) +def powerRealizer : Realizer power := + composition (f := powerInput) (g := PowerApproximationProgram.output) + powerInputRealizer PowerApproximationProgram.outputRealizer +lemma polynomial_power : PolynomialTime powerRealizer := + polynomial_composition polynomial_powerInput PowerApproximationProgram.polynomial_output + +def output (z : Input) : TreeFraction.Fraction := TreeFraction.mul (z.1.2,power z) +def outputRealizer : Realizer output := + composition (f := fun z : Input => (z.1.2,power z)) (g := TreeFraction.mul) + (pair (composition first second) powerRealizer) TreeFraction.mulRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_power) TreeFraction.polynomial_mul + +theorem output_value (z : Frame) (population : TreeFraction.Fraction) + (degree depth : List Bool) + (hlo : -2 ≤ (z.1.1:ℚ)-TreeFraction.val z.1.2*TreeFraction.val z.2) + (hhi : (z.1.1:ℚ)-TreeFraction.val z.1.2*TreeFraction.val z.2 ≤ 2) : + TreeFraction.val (output ((z,population),(degree,depth)))= + TreeFraction.val population*PowerOfTwoApproximation.approximation + ((z.1.1:ℚ)-TreeFraction.val z.1.2*TreeFraction.val z.2) degree.length depth.length := by + have hl := hlo + have hh := hhi + rw [←exponentInput_value z] at hl hh + rw [output,TreeFraction.mul_val] + unfold power powerInput + rw [PowerApproximationProgram.output_value _ _ _ degree depth hl hh,exponentInput_value] + +theorem output_approximate (z : Frame) (population : TreeFraction.Fraction) + (degree depth : List Bool) (sigma : ℚ) + (hdegree : degree.length=PowerOfTwoApproximation.rootDegree sigma) + (hdepth : depth.length=PowerOfTwoApproximation.depth sigma) + (hlo : -2 ≤ (z.1.1:ℚ)-TreeFraction.val z.1.2*TreeFraction.val z.2) + (hhi : (z.1.1:ℚ)-TreeFraction.val z.1.2*TreeFraction.val z.2 ≤ 2) : + TreeFraction.val (output ((z,population),(degree,depth)))= + TreeFraction.val population*PowerOfTwoApproximation.approximate + ((z.1.1:ℚ)-TreeFraction.val z.1.2*TreeFraction.val z.2) sigma := by + rw [output_value z population degree depth hlo hhi,hdegree,hdepth] + rfl + +end ContingencyTables.CorrectionValueProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/DependentWordProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/DependentWordProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecce75e6355c46fe12530c2d98a4d87624a119de --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/DependentWordProgram.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram +import OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanTrial + +namespace OAI + +/-! # Splitting a binary word at input-dependent coordinate widths -/ + +namespace ContingencyTables.DensePrograms +open MatchingFPRAS.TreeTyped Polynomial + +abbrev DependentChunkData := (List ℕ×List Bool)×ℕ + +def chunkStart (z : DependentChunkData) : ℕ := (z.1.1.take z.2).sum +def chunkStartRealizer : Realizer chunkStart := + composition (composition (pair (composition first first) second) takeFast) listSum + +theorem polynomial_chunkStart : PolynomialTime chunkStartRealizer := + polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_takeFast) polynomial_listSum + +def dependentChunk (z : DependentChunkData) : List Bool := + (z.1.2.drop (chunkStart z)).take (z.1.1.getD z.2 0) + +def dependentChunkRealizer : Realizer dependentChunk := + composition (pair + (composition (pair (composition first second) chunkStartRealizer) dropFast) + (composition (pair (composition first first) second) (getDFast 0))) takeFast + +theorem polynomial_dependentChunk : PolynomialTime dependentChunkRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_chunkStart) + polynomial_dropFast) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast 0))) polynomial_takeFast + +def chunkIndices (z : List ℕ×List Bool) : List ℕ := List.range z.1.length +def chunkIndicesRealizer : Realizer chunkIndices := composition (composition first listLength) range + +theorem polynomial_chunkIndices : PolynomialTime chunkIndicesRealizer := by + apply polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1).trans (weight_fst z) + +def dependentChunks (z : List ℕ×List Bool) : List (List Bool) := + (chunkIndices z).map (fun i => dependentChunk (z,i)) +def dependentChunksRealizer : Realizer dependentChunks := + composition (pair identity chunkIndicesRealizer) (mapWith dependentChunkRealizer) + +theorem polynomial_dependentChunks : PolynomialTime dependentChunksRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_chunkIndices) + (polynomial_mapWith polynomial_dependentChunk) + +open scoped BigOperators + +lemma take_ofFn_sum {q : ℕ} (width : Fin q → ℕ) (i : Fin q) : + ((List.ofFn width).take i.val).sum=∑ j : Fin i.val,width (Fin.castLE i.isLt.le j) := by + rw [←Fin.ofFn_take_eq_take_ofFn i.isLt.le,List.sum_ofFn] + rfl + +theorem dependentChunk_ofFn {q : ℕ} (width : Fin q → ℕ) + (bits : Fin (∑ i,width i) → Bool) (i : Fin q) : + dependentChunk ((List.ofFn width,List.ofFn bits),i.val)= + List.ofFn (fun j : Fin (width i) => bits (finSigmaFinEquiv ⟨i,j⟩)) := by + have hw : (List.ofFn width).getD i.val 0=width i := by + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn,i.isLt,dite_true,Option.getD_some,Fin.eta] + have hb : ((List.ofFn width).take i.val).sum+width i≤∑ j,width j := by + by_cases hi : width i=0 + · rw [hi,Nat.add_zero,←List.sum_ofFn] + exact (List.take_sublist i.val (List.ofFn width)).sum_le_sum (fun _ _ => Nat.zero_le _) + · have hh := (finSigmaFinEquiv (⟨i,⟨width i-1,by omega⟩⟩ : Sigma (fun i => Fin (width i)))).isLt + rw [finSigmaFinEquiv_apply,←take_ofFn_sum] at hh + dsimp only at hh + omega + have hlen : width i≤(∑ j,width j)-((List.ofFn width).take i.val).sum := + Nat.le_sub_of_add_le (by omega) + apply List.ext_getElem + · simp only [dependentChunk,chunkStart,List.length_take,List.length_drop,List.length_ofFn,hw, + min_eq_left hlen] + · intro j hj _ + simp only [dependentChunk,chunkStart,List.getElem_take,List.getElem_drop,List.getElem_ofFn] + apply congrArg bits + apply Fin.ext + simp only [finSigmaFinEquiv_apply,take_ofFn_sum] + +theorem dependentChunks_ofFn {q : ℕ} (width : Fin q → ℕ) + (bits : Fin (∑ i,width i) → Bool) : + dependentChunks (List.ofFn width,List.ofFn bits)= + List.ofFn (fun i => List.ofFn (fun j : Fin (width i) => bits (finSigmaFinEquiv ⟨i,j⟩))) := by + unfold dependentChunks chunkIndices + rw [List.length_ofFn] + apply List.ext_getElem + · simp only [List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have hiq : i < q := by simpa only [List.length_map,List.length_range] using hi + simp only [List.getElem_map,List.getElem_range,List.getElem_ofFn] + exact dependentChunk_ofFn width bits ⟨i,hiq⟩ + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/DirectedBFSProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/DirectedBFSProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..142d041612f7a5cfeb159975c00e88ab0d2140f8 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/DirectedBFSProgram.lean @@ -0,0 +1,177 @@ +import OAI.Combinatorics.ContingencyTables.Transport.DirectedBFSCode +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialCollections +import OAI.Combinatorics.MatchingCount.Machines.TreeSum +import OAI.Combinatorics.MatchingCount.Machines.TreeFastLookup +import OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure + +namespace OAI + +/-! # Polynomial binary programs for one stored BFS round -/ + +namespace ContingencyTables.DirectedBFSProgram + +open MatchingFPRAS.TreeTyped Polynomial DirectedBFSCode + +abbrev Context := Graph×Store +abbrev Query := Context×ℕ +abbrev Candidate := Query×ℕ + +def indices (g : Graph) : List ℕ := List.range g.length +def indicesRealizer : Realizer indices := composition listLength range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange polynomial_listLength X + intro g + simpa only [Function.comp_apply,eval_X] using list_length_le_weight g + +def pathSomeRealizer : Realizer (fun o : Option (List ℕ)=>o.isSome) := + (composition (pair (constant false) identity) + (optionCases (constant false) (constant true))).congr (by + intro o + cases o <;> rfl) + +lemma polynomial_pathSome : PolynomialTime pathSomeRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_pair (polynomial_constant false) polynomial_identity) + (polynomial_optionCases (polynomial_constant false) (polynomial_constant true))) + +def lookupPath (z : Store×ℕ) : Option (List ℕ) := lookup z.1 z.2 +def lookupRealizer : Realizer lookupPath := getDFast none +lemma polynomial_lookup : PolynomialTime lookupRealizer := polynomial_getDFast none + +def readEdge (z : (Graph×ℕ)×ℕ) : Bool := adjacent z.1.1 z.1.2 z.2 +def readEdgeRealizer : Realizer readEdge := + composition (pair (composition first (getDFast [])) second) (getDFast false) + +lemma polynomial_readEdge : PolynomialTime readEdgeRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first (polynomial_getDFast [])) polynomial_second) + (polynomial_getDFast false) + +def candidate (z : Candidate) : Bool := + (lookup z.1.1.2 z.2).isSome && adjacent z.1.1.1 z.2 z.1.2 + +def candidateRealizer : Realizer candidate := by + let G : Realizer (fun z : Candidate=>z.1.1.1) := composition (composition first first) first + let P : Realizer (fun z : Candidate=>z.1.1.2) := composition (composition first first) second + let V : Realizer (fun z : Candidate=>z.1.2) := composition first second + let U : Realizer (fun z : Candidate=>z.2) := second + let known : Realizer (fun z : Candidate=>(lookup z.1.1.2 z.2).isSome) := + composition (composition (pair P U) lookupRealizer) pathSomeRealizer + let edge : Realizer (fun z : Candidate=>adjacent z.1.1.1 z.2 z.1.2) := + composition (pair (pair G U) V) readEdgeRealizer + exact composition (pair known edge) boolAnd + +lemma polynomial_candidate : PolynomialTime candidateRealizer := by + unfold candidateRealizer + apply polynomial_composition + · apply polynomial_pair + · exact polynomial_composition + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_second) polynomial_lookup) polynomial_pathSome + · exact polynomial_composition (polynomial_pair + (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) + (polynomial_composition polynomial_first polynomial_second)) polynomial_readEdge + · exact polynomial_boolAnd + +def headOptionRealizer : Realizer (fun xs : List ℕ=>xs.head?) := + (listCase none (composition first some)).congr (by intro xs;cases xs <;> rfl) + +lemma polynomial_headOption : PolynomialTime headOptionRealizer := + polynomial_congr _ (polynomial_listCase none + (polynomial_composition polynomial_first polynomial_some)) + +def predecessorInput (z : Query) : Option ℕ := DirectedBFSCode.predecessor z.1.1 z.1.2 z.2 + +def predecessorRealizer : Realizer predecessorInput := + (composition (composition (pair identity + (composition (composition first first) indicesRealizer)) (filterWith candidateRealizer)) + headOptionRealizer).congr (by + intro z + simp only [Function.comp_apply,id_eq,predecessorInput,DirectedBFSCode.predecessor,indices, + List.head?_filter,candidate]) + +lemma polynomial_predecessor : PolynomialTime predecessorRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_indices)) (polynomial_filterWith polynomial_candidate)) polynomial_headOption) + +def appendPath (z : Query×List ℕ) : Option (List ℕ) := Option.some (z.2++[z.1.2]) + +def appendPathRealizer : Realizer appendPath := + composition (composition (pair second + (composition (pair (composition first second) (constant [])) listCons)) append) some + +lemma polynomial_appendPath : PolynomialTime appendPathRealizer := + polynomial_composition (polynomial_composition + (polynomial_pair polynomial_second (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_constant [])) polynomial_listCons)) polynomial_append) polynomial_some + +def fromPredecessor (z : Query×ℕ) : Option (List ℕ) := + (lookup z.1.1.2 z.2).map (fun xs=>xs++[z.1.2]) + +def fromPredecessorRealizer : Realizer fromPredecessor := + (composition (pair first + (composition (pair (composition (composition first first) second) second) lookupRealizer)) + (optionCases (constant none) appendPathRealizer)).congr (by + intro z + dsimp only [Function.comp_apply,lookupPath,fromPredecessor,appendPath] + cases h : lookup z.1.1.2 z.2 <;> rfl) + +lemma polynomial_fromPredecessor : PolynomialTime fromPredecessorRealizer := + polynomial_congr _ (polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_second) polynomial_lookup)) + (polynomial_optionCases (polynomial_constant none) polynomial_appendPath)) + +def missing (z : Query) : Option (List ℕ) := + (predecessorInput z).bind (fun u=>fromPredecessor (z,u)) + +def missingRealizer : Realizer missing := + (composition (pair identity predecessorRealizer) + (optionCases (constant none) fromPredecessorRealizer)).congr (by + intro z + dsimp only [Function.comp_apply,id_eq,missing] + cases h : predecessorInput z <;> rfl) + +lemma polynomial_missing : PolynomialTime missingRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_pair polynomial_identity polynomial_predecessor) + (polynomial_optionCases (polynomial_constant none) polynomial_fromPredecessor)) + +def rowInput (z : Query) : Option (List ℕ) := roundRow z.1.1 z.1.2 z.2 + +def rowRealizer : Realizer rowInput := + (composition (pair identity + (composition (pair (composition first second) second) lookupRealizer)) + (optionCases missingRealizer (composition second some))).congr (by + intro z + dsimp only [Function.comp_apply,id_eq,lookupPath,rowInput,roundRow] + cases h : lookup z.1.2 z.2 <;> rfl) + +lemma polynomial_row : PolynomialTime rowRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_pair polynomial_identity (polynomial_composition + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second) polynomial_lookup)) + (polynomial_optionCases polynomial_missing + (polynomial_composition polynomial_second polynomial_some))) + +def roundInput (z : Context) : Store := round z.1 z.2 +def roundRealizer : Realizer roundInput := + composition (pair identity (composition first indicesRealizer)) (mapWith rowRealizer) + +theorem polynomial_round : PolynomialTime roundRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_indices)) + (polynomial_mapWith polynomial_row) + +end ContingencyTables.DirectedBFSProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/DirectedBFSRuntime.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/DirectedBFSRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..815e93e569df82343744e8469df00ce2ec312c46 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/DirectedBFSRuntime.lean @@ -0,0 +1,120 @@ +import OAI.Combinatorics.ContingencyTables.Transport.DirectedBFSBounds +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid + +namespace OAI + +/-! # Polynomial binary execution of the entire materialized BFS -/ + +namespace ContingencyTables.DirectedBFSRuntime + +open MatchingFPRAS.TreeTyped Polynomial DirectedBFSCode DirectedBFSBounds DirectedBFSProgram + +def advance (z : ℕ×Context) : Context := (z.2.1,round z.2.1 z.2.2) +def advanceRealizer : Realizer advance := + pair (composition second first) (composition second roundRealizer) + +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition polynomial_second polynomial_round) + +lemma fold_eq (steps : List ℕ) (g : Graph) (P : Store) : + steps.foldl (fun s i=>advance (i,s)) (g,P)= + (g,steps.foldl (fun P _=>round g P) P) := by + induction steps generalizing P with + | nil => rfl + | cons i steps ih => exact ih (round g P) + +theorem polynomial_fold : PolynomialTime (MatchingFPRAS.TreeTyped.fold advanceRealizer) := by + apply MatchingFPRAS.TreeTyped.polynomial_fold polynomial_advance (20*(X+1)^3) + intro steps s pre post he + let S := weight (steps,s) + have hsw : weight s≤ S := weight_snd (steps,s) + have hgw : weight s.1≤ S := (weight_fst s).trans hsw + have hpw : weight s.2≤ S := (weight_snd s).trans hsw + have hn : s.1.length≤ S := (list_length_le_weight s.1).trans hgw + have hpn : s.2.length≤ S := (list_length_le_weight s.2).trans hpw + have hpre : pre.length≤ S := by + have hl : pre.length≤ steps.length := by rw [he,List.length_append]; omega + exact hl.trans ((list_length_le_weight steps).trans (weight_fst (steps,s))) + have hb : Bounded s.2 (S+5) := by + intro o ho + exact (weight_mem ho).trans (hpw.trans (by omega)) + let out := pre.foldl (fun P _=>round s.1 P) s.2 + have ho : Bounded out (S+5+pre.length*(4*s.1.length+2)) := + fold_bounded s.1 s.2 (S+5) (by omega) hb pre + have hol : out.length≤ S := (fold_length_le s.1 s.2 pre).trans + (max_le hpn hn) + have hob : S+5+pre.length*(4*s.1.length+2)≤4*S^2+3*S+5 := by + have hm := Nat.mul_le_mul hpre (show 4*s.1.length+2≤4*S+2 by omega) + nlinarith + have hwo := store_weight out _ ho + have hwm := Nat.mul_le_mul hol (Nat.add_le_add_right hob 1) + have hwout : weight out≤4*S^3+3*S^2+6*S+1 := by nlinarith + change weight (pre.foldl (fun s i=>advance (i,s)) s)≤_ + have hf := fold_eq pre s.1 s.2 + rw [Prod.eta] at hf + rw [hf,weight_prod] + simp only [eval_mul,eval_ofNat,eval_pow,eval_add,eval_X,eval_one] + change 1+weight s.1+weight out≤20*(S+1)^3 + nlinarith + +def initialRow (z : ℕ×ℕ) : Option (List ℕ) := + if z.2=z.1 then Option.some [z.1] else none + +def initialRowRealizer : Realizer initialRow := + (choose (composition (pair second first) natEqual) + (composition (composition (pair first (constant [])) listCons) some) + (constant none)).congr (by + intro z + simp only [Function.comp_apply,initialRow,decide_eq_true_eq]) + +lemma polynomial_initialRow : PolynomialTime initialRowRealizer := + polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair polynomial_second polynomial_first) polynomial_natEqual) + (polynomial_composition (polynomial_composition + (polynomial_pair polynomial_first (polynomial_constant [])) polynomial_listCons) polynomial_some) + (polynomial_constant none)) + +def initialInput (z : Graph×ℕ) : Store := initial z.1 z.2 +def initialRealizer : Realizer initialInput := + composition (pair second (composition first indicesRealizer)) (mapWith initialRowRealizer) + +lemma polynomial_initial : PolynomialTime initialRealizer := + polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition polynomial_first polynomial_indices)) + (polynomial_mapWith polynomial_initialRow) + +def prepare (z : Graph×ℕ) : List ℕ×Context := + (indices z.1,(z.1,initial z.1 z.2)) +def prepareRealizer : Realizer prepare := + pair (composition (f := fun z : Graph×ℕ=>z.1) (g := indices) first indicesRealizer) + (pair first initialRealizer) + +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_indices) + (polynomial_pair polynomial_first polynomial_initial) + +def runInput (z : Graph×ℕ) : Store := run z.1 z.2 +def runRealizer : Realizer runInput := + (composition (composition prepareRealizer (MatchingFPRAS.TreeTyped.fold advanceRealizer)) + second).congr (by + intro z + change ((indices z.1).foldl (fun s i=>advance (i,s)) (z.1,initial z.1 z.2)).2 = _ + rw [fold_eq] + rfl) + +theorem polynomial_run : PolynomialTime runRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_composition polynomial_prepare polynomial_fold) polynomial_second) + +def searchInput (z : (Graph×ℕ)×ℕ) : Option (List ℕ) := search z.1.1 z.1.2 z.2 +def searchRealizer : Realizer searchInput := + composition (pair (composition first runRealizer) second) lookupRealizer + +theorem polynomial_search : PolynomialTime searchRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_run) polynomial_second) polynomial_lookup + +end ContingencyTables.DirectedBFSRuntime + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/DyadicRootProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/DyadicRootProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8573b35f417cc1973b257ec2869c51003852c614 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/DyadicRootProgram.lean @@ -0,0 +1,272 @@ +import OAI.Combinatorics.ContingencyTables.Transport.DyadicRootBisection +import OAI.Combinatorics.ContingencyTables.Machines.BinaryPowerProgram +import OAI.Combinatorics.MatchingCount.Machines.TreeFiniteOps +import OAI.Combinatorics.MatchingCount.Complexity.TreePolyTactic + +namespace OAI + +/-! # Polynomial binary execution of the rational correction bisection + +The root degree is the length of a supplied allowance list. One fixed +depth list controls the outer loop. Thus both natural-power evaluation +and the bisection loop have polynomial cost in the supplied binary data +and the two explicit allowances. +-/ + +namespace ContingencyTables.DyadicRootProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped Polynomial + +def powerInput (z : ℕ×List Bool) : ℕ×ℕ := (z.1,z.2.length) +def powerInputRealizer : Realizer powerInput := pair first (composition second listLength) +lemma polynomial_powerInput : PolynomialTime powerInputRealizer := by + unfold powerInputRealizer + exact polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_listLength) + +def markedPower (z : ℕ×List Bool) : ℕ := BinaryPowerPrograms.power (powerInput z) +def markedPowerRealizer : Realizer markedPower := + composition powerInputRealizer BinaryPowerPrograms.powerRealizer + +lemma polynomial_markedPower : PolynomialTime markedPowerRealizer := by + apply work_composition polynomial_powerInput BinaryPowerPrograms.work_power X + intro z + have hl:=list_length_le_weight z.2 + simp only [powerInput,eval_X] + rw [←Prod.eta z,weight_prod] + dsimp only + omega + +lemma markedPower_eq (a : ℕ) (xs : List Bool) : markedPower (a,xs)=a^xs.length := + BinaryPowerPrograms.power_eq a xs.length + +abbrev Parameters := TreeFraction.Fraction×List Bool +abbrev State := Parameters×DyadicRootBisection.State + +private def lowRealizer : Realizer (fun z : State=>z.2.1.1) := + composition (composition second first) first +private def highRealizer : Realizer (fun z : State=>z.2.1.2) := + composition (composition second first) second +private def denominatorRealizer : Realizer (fun z : State=>z.2.2) := composition second second +private def numeratorRealizer : Realizer (fun z : State=>z.1.1.1) := + composition (composition first first) first +private def targetDenominatorRealizer : Realizer (fun z : State=>z.1.1.2) := + composition (composition first first) second +private def allowanceRealizer : Realizer (fun z : State=>z.1.2) := composition first second + +private lemma polynomial_low : PolynomialTime lowRealizer := by unfold lowRealizer; tree_poly +private lemma polynomial_high : PolynomialTime highRealizer := by unfold highRealizer; tree_poly +private lemma polynomial_denominator : PolynomialTime denominatorRealizer := by + unfold denominatorRealizer; tree_poly +private lemma polynomial_numerator : PolynomialTime numeratorRealizer := by + unfold numeratorRealizer; tree_poly +private lemma polynomial_targetDenominator : PolynomialTime targetDenominatorRealizer := by + unfold targetDenominatorRealizer; tree_poly +private lemma polynomial_allowance : PolynomialTime allowanceRealizer := by + unfold allowanceRealizer; tree_poly + +def mid (z : State) : ℕ := z.2.1.1+z.2.1.2 +def midRealizer : Realizer mid := composition (pair lowRealizer highRealizer) add +lemma polynomial_mid : PolynomialTime midRealizer := + polynomial_composition (polynomial_pair polynomial_low polynomial_high) polynomial_add + +def twiceDenominator (z : State) : ℕ := 2*z.2.2 +def twiceDenominatorRealizer : Realizer twiceDenominator := + composition (f:=fun z : State=>(2,z.2.2)) (g:=fun p : ℕ×ℕ=>p.1*p.2) + (pair (constant 2) denominatorRealizer) multiply +lemma polynomial_twiceDenominator : PolynomialTime twiceDenominatorRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_denominator) + polynomial_multiply + +def leftProduct (z : State) : ℕ := markedPower (mid z,z.1.2)*z.1.1.2 +def leftProductRealizer : Realizer leftProduct := + composition (pair + (composition (pair midRealizer allowanceRealizer) markedPowerRealizer) + targetDenominatorRealizer) multiply +lemma polynomial_leftProduct : PolynomialTime leftProductRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_mid polynomial_allowance) + polynomial_markedPower) polynomial_targetDenominator) polynomial_multiply + +def rightProduct (z : State) : ℕ := z.1.1.1*markedPower (twiceDenominator z,z.1.2) +def rightProductRealizer : Realizer rightProduct := + composition (pair numeratorRealizer + (composition (pair twiceDenominatorRealizer allowanceRealizer) markedPowerRealizer)) multiply +lemma polynomial_rightProduct : PolynomialTime rightProductRealizer := + polynomial_composition (polynomial_pair polynomial_numerator + (polynomial_composition (polynomial_pair polynomial_twiceDenominator polynomial_allowance) + polynomial_markedPower)) polynomial_multiply + +def test (z : State) : Bool := decide (leftProduct z≤rightProduct z) +def testRealizer : Realizer test := composition (pair leftProductRealizer rightProductRealizer) leNat +lemma polynomial_test : PolynomialTime testRealizer := + polynomial_composition (polynomial_pair polynomial_leftProduct polynomial_rightProduct) + polynomial_leNat + +private def lowerBranchRealizer : Realizer (fun z : State=> + ((mid z,2*z.2.1.2),twiceDenominator z)) := + pair (pair midRealizer (composition + (f:=fun z : State=>(2,z.2.1.2)) (g:=fun p : ℕ×ℕ=>p.1*p.2) + (pair (constant 2) highRealizer) multiply)) + twiceDenominatorRealizer +private def upperBranchRealizer : Realizer (fun z : State=> + ((2*z.2.1.1,mid z),twiceDenominator z)) := + pair (pair (composition + (f:=fun z : State=>(2,z.2.1.1)) (g:=fun p : ℕ×ℕ=>p.1*p.2) + (pair (constant 2) lowRealizer) multiply) midRealizer) + twiceDenominatorRealizer + +def next (z : State) : State := + (z.1,if test z then ((mid z,2*z.2.1.2),twiceDenominator z) + else ((2*z.2.1.1,mid z),twiceDenominator z)) +def nextRealizer : Realizer next := + pair first (choose testRealizer lowerBranchRealizer upperBranchRealizer) + +lemma polynomial_next : PolynomialTime nextRealizer := by + apply polynomial_pair polynomial_first + apply polynomial_choose polynomial_test + · exact polynomial_pair (polynomial_pair polynomial_mid + (polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_high) + polynomial_multiply)) polynomial_twiceDenominator + · exact polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_pair (polynomial_constant 2) polynomial_low) + polynomial_multiply) polynomial_mid) polynomial_twiceDenominator + +lemma next_eq (z : State) : + next z=(z.1,DyadicRootBisection.advance z.1.1 z.1.2.length z.2) := by + simp only [next,test,leftProduct,rightProduct,markedPower_eq,mid,twiceDenominator, + DyadicRootBisection.advance,decide_eq_true_eq] + +def height (z : DyadicRootBisection.State) : ℕ := max (max z.1.1.size z.1.2.size) z.2.size + +private lemma size_double (a : ℕ) : (2*a).size≤a.size+1 := by + simpa only [two_mul,max_self] using nat_size_add a a + +lemma height_advance (c : TreeFraction.Fraction) (s : ℕ) (z : DyadicRootBisection.State) : + height (DyadicRootBisection.advance c s z)≤height z+1 := by + have hm:=nat_size_add z.1.1 z.1.2 + have ha:=size_double z.1.1 + have hb:=size_double z.1.2 + have hd:=size_double z.2 + unfold DyadicRootBisection.advance height + split_ifs <;> dsimp only <;> omega + +def advance (z : Bool×State) : State := next z.2 +def advanceRealizer : Realizer advance := composition second nextRealizer +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_composition polynomial_second polynomial_next + +lemma fold_parameters (xs : List Bool) (z : State) : + (xs.foldl (fun z a=>advance (a,z)) z).1=z.1 := by + induction xs generalizing z with + | nil=>rfl + | cons a xs ih=>exact ih (next z) + +lemma fold_height (xs : List Bool) (z : State) : + height (xs.foldl (fun z a=>advance (a,z)) z).2≤height z.2+xs.length := by + induction xs generalizing z with + | nil=>simp only [List.foldl_nil,List.length_nil,Nat.add_zero,le_refl] + | cons a xs ih=> + have hh:=height_advance z.1.1 z.1.2.length z.2 + have ht:=ih (next z) + have hn: height (next z).2≤height z.2+1 := by + rw [next_eq] + exact hh + change height (xs.foldl (fun z a=>advance (a,z)) (next z)).2≤ + height z.2+(xs.length+1) + omega + +lemma height_le_weight (z : DyadicRootBisection.State) : height z≤weight z := by + have ha: z.1.1.size≤weight z := + (size_le_weight _).trans ((weight_fst z.1).trans (weight_fst z)) + have hb: z.1.2.size≤weight z := + (size_le_weight _).trans ((weight_snd z.1).trans (weight_fst z)) + have hd: z.2.size≤weight z := (size_le_weight _).trans (weight_snd z) + exact max_le (max_le ha hb) hd + +lemma polynomial_loop : PolynomialTime (fold advanceRealizer) := by + apply polynomial_fold polynomial_advance (30*(X+1)) + intro xs z pre post he + let S:=weight (xs,z) + let out:=pre.foldl (fun z a=>advance (a,z)) z + have hz: weight z≤S:=weight_snd (xs,z) + have hp: weight z.1≤S:=(weight_fst z).trans hz + have hs: height z.2≤S:=(height_le_weight z.2).trans ((weight_snd z).trans hz) + have hl: pre.length≤S:=(list_length_le_weight pre).trans + ((weight_prefix he).trans (weight_fst (xs,z))) + have hh:=fold_height pre z + change height out.2≤height z.2+pre.length at hh + have hctx: out.1=z.1:=fold_parameters pre z + have h1:=weight_nat_le out.2.1.1 + have h2:=weight_nat_le out.2.1.2 + have h3:=weight_nat_le out.2.2 + have hs1: out.2.1.1.size≤height out.2:= + (le_max_left _ _).trans (le_max_left _ _) + have hs2: out.2.1.2.size≤height out.2:= + (le_max_right _ _).trans (le_max_left _ _) + have hs3: out.2.2.size≤height out.2:=le_max_right _ _ + have hw: weight out=weight out.1+weight out.2.1.1+weight out.2.1.2+weight out.2.2+3 := by + change weight (out.1,((out.2.1.1,out.2.1.2),out.2.2))=_ + simp only [weight_prod] + omega + simp only [eval_mul,eval_ofNat,eval_add,eval_X,eval_one] + change weight out≤30*(S+1) + rw [hw,hctx] + omega + +abbrev Input := Parameters×List Bool +def prepare (z : Input) : List Bool×State := (z.2,(z.1,((0,8),1))) +def prepareRealizer : Realizer prepare := pair second (pair first (constant ((0,8),1))) +lemma polynomial_prepare : PolynomialTime prepareRealizer := by + unfold prepareRealizer + exact polynomial_pair polynomial_second + (polynomial_pair polynomial_first (polynomial_constant ((0,8),1))) + +def execute (z : Input) : State := z.2.foldl (fun s a=>advance (a,s)) (z.1,((0,8),1)) +def executeRealizer : Realizer execute := composition prepareRealizer (fold advanceRealizer) +lemma polynomial_execute : PolynomialTime executeRealizer := + polynomial_composition polynomial_prepare polynomial_loop + +def finish (z : State) : TreeFraction.Fraction := + TreeFraction.normalize (mid z,twiceDenominator z) +def finishRealizer : Realizer finish := + composition (pair midRealizer twiceDenominatorRealizer) TreeFraction.normalizeRealizer +lemma polynomial_finish : PolynomialTime finishRealizer := + polynomial_composition (polynomial_pair polynomial_mid polynomial_twiceDenominator) + TreeFraction.polynomial_normalize + +def output (z : Input) : TreeFraction.Fraction := finish (execute z) +def outputRealizer : Realizer output := composition executeRealizer finishRealizer +theorem polynomial_output : PolynomialTime outputRealizer := + polynomial_composition polynomial_execute polynomial_finish + +lemma fold_eq (xs : List Bool) (p : Parameters) (z : DyadicRootBisection.State) : + xs.foldl (fun z a=>advance (a,z)) (p,z)= + (p,(DyadicRootBisection.advance p.1 p.2.length)^[xs.length] z) := by + induction xs generalizing z with + | nil=>rfl + | cons a xs ih=> + rw [List.foldl_cons] + change xs.foldl (fun z a=>advance (a,z)) (next (p,z))=_ + rw [next_eq,ih] + simp only [List.length_cons,Function.iterate_succ_apply] + +theorem output_eq (c : TreeFraction.Fraction) (degree depth : List Bool) : + output ((c,degree),depth)=DyadicRootBisection.output c degree.length depth.length := by + have hr (k : ℕ) : + (DyadicRootBisection.advance c degree.length)^[k] ((0,8),1)= + DyadicRootBisection.run c degree.length k := by + induction k with + | zero=>rfl + | succ k ih=>rw [Function.iterate_succ_apply',ih,DyadicRootBisection.run] + simp only [output,execute,fold_eq,hr,finish,mid,twiceDenominator,DyadicRootBisection.output] + +theorem output_value (c : TreeFraction.Fraction) (hc : 0 z.1.length-z.2) := + composition (pair (composition first listLength) second) subtract + let B := composition (composition (pair first N) takeFast) bitDenominatorRealizer + exact (composition (pair (composition first bitValue) B) less).congr (by + intro z + simp only [Function.comp_apply,bitDenominator_eq,List.length_take,dyadicWordAccept] + rw [min_eq_left (Nat.sub_le _ _)]) + +theorem polynomial_dyadicWordAccept : PolynomialTime dyadicWordAcceptRealizer := by + have hn : PolynomialTime (composition + (pair (composition (first (A := List Bool) (B := ℕ)) listLength) second) subtract) := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_listLength) polynomial_second) + polynomial_subtract + have hb := polynomial_composition (polynomial_composition + (polynomial_pair polynomial_first hn) polynomial_takeFast) polynomial_bitDenominator + unfold dyadicWordAcceptRealizer + exact polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_bitValue) hb) polynomial_less) + +theorem dyadicWordAccept_ofFn (gap k : ℕ) (bits : Fin k → Bool) : + dyadicWordAccept (List.ofFn bits,gap)= + decide (FairBits.acceptDyadic gap k (FairBits.binaryWordEquiv k bits)) := by + simp only [dyadicWordAccept,List.length_ofFn,bitValue_eq_word,FairBits.acceptDyadic] + +end ContingencyTables.DensePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/EndpointMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/EndpointMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..64325de9ba52f81520db4e3a54419aa5d09e6468 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/EndpointMatrixProgram.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Machines.CellMinimumProgram + +namespace OAI + +/-! # Computing every attained cell endpoint + +Both scans use the dimensions of the stored margin lists. Each entry is +computed by the binary feasibility search; neither scan enumerates tables. +-/ + +namespace ContingencyTables.EndpointMatrixProgram + +open MatchingFPRAS.TreeTyped Polynomial ResidualGraphProgram + +abbrev Input := NetworkVertexCode.Input +abbrev RowInput := Input × ℕ +abbrev CellInput := RowInput × ℕ + +def context (z : CellInput) : CellLowerTestProgram.Context := (z.1.1,(z.1.2,z.2)) +def contextRealizer : Realizer context := pair (composition first first) + (pair (composition first second) second) +lemma polynomial_context : PolynomialTime contextRealizer := + polynomial_pair (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second) + +def lowerEntry (z : CellInput) : ℕ := CellMinimumProgram.minimum (context z) +def lowerEntryRealizer : Realizer lowerEntry := + composition (f := context) (g := CellMinimumProgram.minimum) + contextRealizer CellMinimumProgram.minimumRealizer +lemma polynomial_lowerEntry : PolynomialTime lowerEntryRealizer := + polynomial_composition polynomial_context CellMinimumProgram.polynomial_minimum + +def upperEntry (z : CellInput) : ℕ := CellMaximumProgram.maximum (context z) +def upperEntryRealizer : Realizer upperEntry := + composition (f := context) (g := CellMaximumProgram.maximum) + contextRealizer CellMaximumProgram.maximumRealizer +lemma polynomial_upperEntry : PolynomialTime upperEntryRealizer := + polynomial_composition polynomial_context CellMaximumProgram.polynomial_maximum + +def columns (z : RowInput) : List ℕ := List.range z.1.1.2.length +def columnsRealizer : Realizer columns := + composition (composition (composition (composition first first) second) listLength) range +lemma polynomial_columns : PolynomialTime columnsRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.1.2).trans + ((weight_snd z.1.1).trans ((weight_fst z.1).trans (weight_fst z))) + +def lowerRow (z : RowInput) : List ℕ := (columns z).map (fun j => lowerEntry (z,j)) +def lowerRowRealizer : Realizer lowerRow := + composition (pair identity columnsRealizer) (mapWith lowerEntryRealizer) +lemma polynomial_lowerRow : PolynomialTime lowerRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_columns) + (polynomial_mapWith polynomial_lowerEntry) + +def upperRow (z : RowInput) : List ℕ := (columns z).map (fun j => upperEntry (z,j)) +def upperRowRealizer : Realizer upperRow := + composition (pair identity columnsRealizer) (mapWith upperEntryRealizer) +lemma polynomial_upperRow : PolynomialTime upperRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_columns) + (polynomial_mapWith polynomial_upperEntry) + +def rows (z : Input) : List ℕ := List.range z.1.1.length +def rowsRealizer : Realizer rows := + composition (composition (composition first first) listLength) range +lemma polynomial_rows : PolynomialTime rowsRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +def lowerMatrix (z : Input) : NatMatrix := (rows z).map (fun i => lowerRow (z,i)) +def lowerMatrixRealizer : Realizer lowerMatrix := + composition (pair identity rowsRealizer) (mapWith lowerRowRealizer) +lemma polynomial_lowerMatrix : PolynomialTime lowerMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_rows) + (polynomial_mapWith polynomial_lowerRow) + +def upperMatrix (z : Input) : NatMatrix := (rows z).map (fun i => upperRow (z,i)) +def upperMatrixRealizer : Realizer upperMatrix := + composition (pair identity rowsRealizer) (mapWith upperRowRealizer) +lemma polynomial_upperMatrix : PolynomialTime upperMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_rows) + (polynomial_mapWith polynomial_upperRow) + +def endpoints (z : Input) : NatMatrix × NatMatrix := (lowerMatrix z,upperMatrix z) +def endpointsRealizer : Realizer endpoints := pair lowerMatrixRealizer upperMatrixRealizer +lemma polynomial_endpoints : PolynomialTime endpointsRealizer := + polynomial_pair polynomial_lowerMatrix polynomial_upperMatrix + +lemma lowerMatrix_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + lowerMatrix (NetworkVertexCode.data r c b) = natCode (fun (i : Fin m) (j : Fin n) => + CellMinimumProgram.minimum (NetworkVertexCode.data r c b,(i.val,j.val))) := by + simp only [lowerMatrix,rows,NetworkVertexCode.data,List.length_ofFn, + DirectedBFSCode.range_eq_map,←List.ofFn_eq_map,List.map_ofFn,natCode] + apply congrArg List.ofFn + funext i + dsimp only [Function.comp_apply] + simp only [lowerRow,columns,List.length_ofFn,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn] + rfl + +lemma upperMatrix_code {m n : ℕ} (r : Fin m→ℕ) (c : Fin n→ℕ) (b : Fin m→Fin n→ℕ) : + upperMatrix (NetworkVertexCode.data r c b) = natCode (fun (i : Fin m) (j : Fin n) => + CellMaximumProgram.maximum (NetworkVertexCode.data r c b,(i.val,j.val))) := by + simp only [upperMatrix,rows,NetworkVertexCode.data,List.length_ofFn, + DirectedBFSCode.range_eq_map,←List.ofFn_eq_map,List.map_ofFn,natCode] + apply congrArg List.ofFn + funext i + dsimp only [Function.comp_apply] + simp only [upperRow,columns,List.length_ofFn,DirectedBFSCode.range_eq_map, + ←List.ofFn_eq_map,List.map_ofFn] + rfl + +end ContingencyTables.EndpointMatrixProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/EnumerationPointBounds.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/EnumerationPointBounds.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ac4c79101abf3a49c5e94b3b358ae5f6798d3e7 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/EnumerationPointBounds.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Sampling.ExactPrintCost +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxEnumeration + +namespace OAI + +/-! # Individual enumeration points have polynomial binary size -/ + +namespace ContingencyTables.ProfilePrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped DensePrograms Polynomial + +lemma gridCoordinates_weight (z : GridEnumerationData) (hz : 0 < z.2) (i : ℕ) : + weight (gridCoordinates (z,i)) ≤ z.1.length*(4*weight z.2+2)+1 := by + rw [gridCoordinates_eq] + apply ExactPrintCost.weight_ofFn + intro j + exact weight_nat_small (Nat.le_of_lt (Nat.mod_lt _ hz)) + +lemma gridWords_point_weight (z : GridEnumerationData) (hz : 0 < z.2) + (w : List ℕ) (hw : w∈gridWords z) : + weight w ≤ z.1.length*(4*weight z.2+2)+1 := by + rw [gridWords] at hw + obtain ⟨i,_,rfl⟩ := List.mem_map.mp hw + exact gridCoordinates_weight z hz i + +lemma splitViews_weight (n : ℕ) (w : List ℕ) : weight (splitViews (n,w))=weight w+2 := by + have h := weight_append (w.take n) (w.drop n) + rw [List.take_append_drop] at h + simp only [splitViews,weight_prod] + omega + +lemma profileBoxViews_length (z : ProfileCheckData) : + (profileBoxViews z).length=gridStateCount (profileEnumerationData z) := by + simp only [profileBoxViews,List.length_map,gridWords,List.length_range] + +lemma profileBoxViews_point_weight (z : ProfileCheckData) (v : List ℕ×List ℕ) + (hv : v∈profileBoxViews z) : + weight v ≤ (2*z.1.1.1.length)*(4*weight (z.2+1)+2)+3 := by + rw [profileBoxViews] at hv + obtain ⟨w,hw,rfl⟩ := List.mem_map.mp hv + have hb := gridWords_point_weight (profileEnumerationData z) (by + change 0 < z.2+1 + omega) w hw + simp only [profileEnumerationData,List.length_map,List.length_append] at hb + rw [←two_mul] at hb + rw [splitViews_weight] + omega + +/-- Exponentially many enumerated points do not make any one point's +binary representation exponentially large. -/ +theorem profileBoxViews_point_polynomial : ∃ p : Polynomial ℕ, + ∀ z v,v∈profileBoxViews z → weight v ≤ p.eval (weight z) := by + obtain ⟨p,hp⟩ := polynomial_successor + refine ⟨2*X*(4*p+2)+3,?_⟩ + intro z v hv + have hw : weight z.2 ≤ weight z := weight_snd z + have hu : weight (z.2+1) ≤ p.eval (weight z) := + (Nat.le_add_left _ _).trans ((hp z.2).trans (polynomial_eval_monotone p hw)) + have hc : z.1.1.1.length ≤ weight z := + (list_length_le_weight _).trans ((weight_fst _).trans ((weight_fst _).trans (weight_fst z))) + have h := profileBoxViews_point_weight z v hv + simp only [eval_add,eval_mul,eval_ofNat,eval_X] + exact h.trans (Nat.add_le_add_right (Nat.mul_le_mul + (Nat.mul_le_mul_left 2 hc) (by omega)) 3) + +end ContingencyTables.ProfilePrograms + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FairBits.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FairBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..654edf01fbd33b96676e7b0c3b9cf68cfdf6a52a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FairBits.lean @@ -0,0 +1,182 @@ +import Mathlib.Data.Rat.Floor +import Mathlib.Algebra.Order.Floor.Semifield +import Mathlib.Order.Interval.Finset.Nat +import Mathlib.Algebra.BigOperators.Group.Finset.Basic +import Mathlib.Algebra.BigOperators.Field +import Mathlib.Tactic.Linarith +import Mathlib.Tactic.Positivity + +namespace OAI + +/-! +# Bounded fair-bit scaling + +Both papers for result 200 implement a bounded approximately uniform integer +choice by drawing `z` uniformly from `0,...,Q-1` and returning `⌊M*z/Q⌋`. +When `Q = 2^k`, the input choice uses exactly `k` fair bits. + +We prove the exact integer fiber formula in 200-01, equation +`eq:dense-offset-count`, and the pointwise and total-variation error estimates +used in 200-02, Lemma `lem:dyadic-integer-draw`. The arguments are direct +finite arithmetic and have no published-input hypotheses. +-/ + +open scoped BigOperators + +namespace ContingencyTables.FairBits + +/-- The bounded scaling map on integer proposals. -/ +def scale (M Q z : ℕ) : ℕ := ⌊(M : ℚ) * z / Q⌋₊ + +/-- The rational floor is exactly the implemented natural integer quotient. -/ +lemma scale_eq_div (M Q z : ℕ) : scale M Q z = M * z / Q := by + rw [scale, ← Nat.cast_mul, Nat.floor_div_eq_div] + +/-- The first integer whose scaled value can be at least `β`. -/ +def endpoint (M Q β : ℕ) : ℕ := ⌈(β : ℚ) * Q / M⌉₊ + +/-- The proposal integers that produce a given output. -/ +def fiber (M Q β : ℕ) : Finset ℕ := + (Finset.range Q).filter fun z => scale M Q z = β + +lemma scale_lt {M Q z : ℕ} (hM : 0 < M) (hQ : 0 < Q) (hz : z < Q) : + scale M Q z < M := by + have hMq : (0 : ℚ) < M := by exact_mod_cast hM + have hQq : (0 : ℚ) < Q := by exact_mod_cast hQ + have hzq : (z : ℚ) < Q := by exact_mod_cast hz + rw [scale, Nat.floor_lt (by positivity), div_lt_iff₀ hQq] + nlinarith + +lemma scale_eq_iff {M Q β z : ℕ} (hM : 0 < M) (hQ : 0 < Q) : + scale M Q z = β ↔ endpoint M Q β ≤ z ∧ z < endpoint M Q (β + 1) := by + have hMq : (0 : ℚ) < M := by exact_mod_cast hM + have hQq : (0 : ℚ) < Q := by exact_mod_cast hQ + rw [scale, Nat.floor_eq_iff (by positivity)] + simp only [endpoint, Nat.ceil_le, Nat.lt_ceil, Nat.cast_add, Nat.cast_one] + constructor + · rintro ⟨hlo, hhi⟩ + constructor + · apply (div_le_iff₀ hMq).mpr + have h := (le_div_iff₀ hQq).mp hlo + nlinarith + · apply (lt_div_iff₀ hMq).mpr + have h := (div_lt_iff₀ hQq).mp hhi + nlinarith + · rintro ⟨hlo, hhi⟩ + constructor + · apply (le_div_iff₀ hQq).mpr + have h := (div_le_iff₀ hMq).mp hlo + nlinarith + · apply (div_lt_iff₀ hQq).mpr + have h := (lt_div_iff₀ hMq).mp hhi + nlinarith + +lemma endpoint_le_proposal {M Q β : ℕ} (hM : 0 < M) (hβ : β < M) : + endpoint M Q (β + 1) ≤ Q := by + have hMq : (0 : ℚ) < M := by exact_mod_cast hM + have hβq : ((β + 1 : ℕ) : ℚ) ≤ M := by + exact_mod_cast Nat.succ_le_of_lt hβ + rw [endpoint, Nat.ceil_le, div_le_iff₀ hMq] + nlinarith [mul_le_mul_of_nonneg_right hβq (Nat.cast_nonneg Q : (0 : ℚ) ≤ Q)] + +/-- The exact preimage interval, including both endpoint conventions. -/ +theorem fiber_eq_interval {M Q β : ℕ} (hM : 0 < M) (hQ : 0 < Q) + (hβ : β < M) : + fiber M Q β = Finset.Ico (endpoint M Q β) (endpoint M Q (β + 1)) := by + ext z + simp only [fiber, Finset.mem_filter, Finset.mem_range, Finset.mem_Ico] + rw [scale_eq_iff hM hQ] + constructor + · exact fun h => h.2 + · intro h + exact ⟨lt_of_lt_of_le h.2 (endpoint_le_proposal hM hβ), h⟩ + +/-- This is the ceiling-difference formula used to tabulate the implemented +output law without enumerating all random bit strings. -/ +theorem fiber_card {M Q β : ℕ} (hM : 0 < M) (hQ : 0 < Q) (hβ : β < M) : + (fiber M Q β).card = endpoint M Q (β + 1) - endpoint M Q β := by + rw [fiber_eq_interval hM hQ hβ, Nat.card_Ico] + +lemma endpoint_mono (M Q β : ℕ) : + endpoint M Q β ≤ endpoint M Q (β + 1) := by + apply Nat.ceil_mono + simp only [Nat.cast_add, Nat.cast_one] + apply div_le_div_of_nonneg_right _ (Nat.cast_nonneg M) + nlinarith [(Nat.cast_nonneg Q : (0 : ℚ) ≤ Q)] + +/-- A scaled output has a number of preimages differing by less than one +from the ideal real-valued number `Q/M`. -/ +theorem fiber_card_error {M Q β : ℕ} (hM : 0 < M) (hQ : 0 < Q) (hβ : β < M) : + |((fiber M Q β).card : ℚ) - (Q : ℚ) / M| < 1 := by + have hMq : (0 : ℚ) < M := by exact_mod_cast hM + have hlo := Nat.le_ceil ((β : ℚ) * Q / M) + have hhi := Nat.ceil_lt_add_one (show (0 : ℚ) ≤ (β : ℚ) * Q / M by positivity) + have hlo' := Nat.le_ceil (((β + 1 : ℕ) : ℚ) * Q / M) + have hhi' := Nat.ceil_lt_add_one + (show (0 : ℚ) ≤ ((β + 1 : ℕ) : ℚ) * Q / M by positivity) + rw [fiber_card hM hQ hβ, Nat.cast_sub (endpoint_mono M Q β)] + simp only [endpoint, Nat.cast_add, Nat.cast_one] at * + rw [abs_lt] + have hdiff : ((β : ℚ) + 1) * Q / M = (β : ℚ) * Q / M + (Q : ℚ) / M := by ring + constructor <;> linarith + +/-- The exact mass assigned by the finite uniform proposal. -/ +def outputMass (M Q β : ℕ) : ℚ := (fiber M Q β).card / (Q : ℚ) + +lemma outputMass_nonnegative (M Q β : ℕ) : 0 ≤ outputMass M Q β := by + dsimp [outputMass] + positivity + +/-- The masses are normalized on the declared output range. -/ +theorem outputMass_total {M Q : ℕ} (hM : 0 < M) (hQ : 0 < Q) : + ∑ β ∈ Finset.range M, outputMass M Q β = 1 := by + have hc : ∑ β ∈ Finset.range M, (fiber M Q β).card = Q := by + symm + simpa only [fiber, Finset.card_range] using + (Finset.card_eq_sum_card_fiberwise (s := Finset.range Q) + (t := Finset.range M) (f := scale M Q) (by + intro z hz + exact Finset.mem_range.mpr (scale_lt hM hQ (Finset.mem_range.mp hz)))) + have hcq : ∑ β ∈ Finset.range M, ((fiber M Q β).card : ℚ) = Q := by + exact_mod_cast hc + simp only [outputMass, ← Finset.sum_div, hcq] + exact div_self (by exact_mod_cast ne_of_gt hQ) + +/-- Every point mass differs from uniform by at most `1/Q`. -/ +theorem outputMass_error {M Q β : ℕ} (hM : 0 < M) (hQ : 0 < Q) (hβ : β < M) : + |outputMass M Q β - 1 / (M : ℚ)| ≤ 1 / (Q : ℚ) := by + have hQq : (0 : ℚ) < Q := by exact_mod_cast hQ + have hQn : (Q : ℚ) ≠ 0 := ne_of_gt hQq + have herr := (fiber_card_error hM hQ hβ).le + have heq : outputMass M Q β - 1 / (M : ℚ) = + (((fiber M Q β).card : ℚ) - (Q : ℚ) / M) / Q := by + dsimp [outputMass] + field_simp + rw [heq, abs_div, abs_of_pos hQq] + exact (div_le_div_iff_of_pos_right hQq).mpr herr + +/-- Total variation with the manuscript's convention `½ ∑ |p-u|`. -/ +def variationFromUniform (M Q : ℕ) : ℚ := + (1 / 2) * ∑ β ∈ Finset.range M, |outputMass M Q β - 1 / (M : ℚ)| + +/-- The bounded integer draw has total-variation error at most `M/(2Q)`. +The papers use the weaker bound `M/Q`. -/ +theorem variation_bound {M Q : ℕ} (hM : 0 < M) (hQ : 0 < Q) : + variationFromUniform M Q ≤ (M : ℚ) / (2 * Q) := by + have hsum : (∑ β ∈ Finset.range M, |outputMass M Q β - 1 / (M : ℚ)|) ≤ + (M : ℚ) * (1 / (Q : ℚ)) := by + calc + _ ≤ ∑ _β ∈ Finset.range M, (1 / (Q : ℚ)) := by + apply Finset.sum_le_sum + intro β hβ + exact outputMass_error hM hQ (Finset.mem_range.mp hβ) + _ = _ := by simp + dsimp [variationFromUniform] + calc + _ ≤ (1 / 2 : ℚ) * ((M : ℚ) * (1 / (Q : ℚ))) := + mul_le_mul_of_nonneg_left hsum (by norm_num) + _ = _ := by ring + +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteEncodedBind.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteEncodedBind.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c487abc9a8ebe96125e31d8d8f136274a63ec36 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteEncodedBind.lean @@ -0,0 +1,44 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent + +namespace OAI + +/-! # Composing exact laws through a noninjective state encoding -/ +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS FairBits +open scoped Classical +noncomputable section + +theorem encoded_bind {A B U V C Z W : Type*} + [Fintype A] [Fintype B] [Fintype U] [Fintype V] + (f : A → C) (g : B → Z) (e : Z → C) (F : C → U → W) (G : Z → V → W) + (hinit : SameLaw f (fun b => e (g b))) (hstep : ∀ z,SameLaw (F (e z)) (G z)) : + SameLaw (fun p : A×U => F (f p.1) p.2) (fun p : B×V => G (g p.1) p.2) := by + intro phi + rw [uniformAverage_prod,uniformAverage_prod] + have hi := hinit (fun c => uniformAverage (fun u : U => phi (F c u))) + refine hi.trans ?_ + apply congrArg uniformAverage + funext b + exact hstep (g b) phi + +theorem flat_encoded_bind {C Z W : Type*} (a b c d : ℕ) + (f : (Fin a → Bool) → C) (g : (Fin c → Bool) → Z) (e : Z → C) + (F : C → (Fin b → Bool) → W) (G : Z → (Fin d → Bool) → W) + (hinit : SameLaw f (fun bits => e (g bits))) (hstep : ∀ z,SameLaw (F (e z)) (G z)) : + SameLaw (fun bits : Fin (a+b) → Bool => + F (f (splitWordEquiv a b bits).1) (splitWordEquiv a b bits).2) + (fun bits : Fin (c+d) → Bool => + G (g (splitWordEquiv c d bits).1) (splitWordEquiv c d bits).2) := by + have h := encoded_bind f g e F G hinit hstep + intro phi + have hl := uniformAverage_equiv (splitWordEquiv a b) + (fun p : (Fin a → Bool)×(Fin b → Bool) => phi (F (f p.1) p.2)) + have hr := uniformAverage_equiv (splitWordEquiv c d) + (fun p : (Fin c → Bool)×(Fin d → Bool) => phi (G (g p.1) p.2)) + exact hl.trans ((h phi).trans hr.symm) + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteEncodedHistory.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteEncodedHistory.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ec1bb962f28db0249c6a3167ff12e1a53619abf --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteEncodedHistory.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteAdaptiveObservable + +namespace OAI + +/-! # Complete histories under an encoded transition law -/ + +namespace ContingencyTables.FiniteObservableTransport + +open CommonBasesFPRAS +open scoped Classical + +def traceAfter {C U : Type*} (step : C → U → C) (c : C) : List U → List C + | [] => [] + | u::us => let d := step c u; d::traceAfter step d us + +def traceStates {C U : Type*} (step : C → U → C) (c : C) (us : List U) : List C := + c::traceAfter step c us + +lemma traceAfter_map {C U V : Type*} (F : C → U → C) (f : V → U) + (vs : List V) (c : C) : + traceAfter F c (vs.map f)=traceAfter (fun c v => F c (f v)) c vs := by + induction vs generalizing c with + | nil => rfl + | cons v vs ih => simp only [List.map_cons,traceAfter,ih] + +lemma traceStates_map {C U V : Type*} (F : C → U → C) (f : V → U) + (vs : List V) (c : C) : + traceStates F c (vs.map f)=traceStates (fun c v => F c (f v)) c vs := by + unfold traceStates + rw [traceAfter_map] + +noncomputable section +variable {C Z U V : Type*} [Fintype U] [Fintype V] + +/-- Equality of the encoded row laws transfers the whole finite history, +including observables depending on every visited state. -/ +theorem traceStates_sameLaw (F : C → U → C) (G : Z → V → Z) (e : Z → C) + (h : ∀ z,SameLaw (F (e z)) (fun v => e (G z v))) (z : Z) (N : ℕ) : + SameLaw (fun us : Fin N → U => traceStates F (e z) (List.ofFn us)) + (fun vs : Fin N → V => (traceStates G z (List.ofFn vs)).map e) := by + intro phi + induction N generalizing z phi with + | zero => simp only [List.ofFn_zero,traceStates,traceAfter,List.map_cons,List.map_nil, + uniformAverage_const] + | succ N ih => + rw [uniformAverage_fin_succ,uniformAverage_fin_succ] + simp only [List.ofFn_cons,traceStates,traceAfter,List.map_cons] + have he := h z (fun c => uniformAverage (fun us : Fin N → U => + phi (e z::traceStates F c (List.ofFn us)))) + refine he.trans ?_ + apply congrArg uniformAverage + funext v + exact ih (G z v) (fun cs => phi (e z::cs)) + +/-- The same encoding argument also transports a terminal state without +requiring a decoder or finiteness of the encoded state space. -/ +theorem foldl_sameLaw (F : C → U → C) (G : Z → V → Z) (e : Z → C) + (h : ∀ z,SameLaw (F (e z)) (fun v => e (G z v))) (z : Z) (N : ℕ) : + SameLaw (fun us : Fin N → U => (List.ofFn us).foldl F (e z)) + (fun vs : Fin N → V => e ((List.ofFn vs).foldl G z)) := by + intro phi + induction N generalizing z phi with + | zero => simp only [List.ofFn_zero,List.foldl_nil,uniformAverage_const] + | succ N ih => + rw [uniformAverage_fin_succ,uniformAverage_fin_succ] + simp only [List.ofFn_cons,List.foldl_cons] + have he := h z (fun c => uniformAverage (fun us : Fin N → U => + phi ((List.ofFn us).foldl F c))) + refine he.trans ?_ + apply congrArg uniformAverage + funext v + exact ih (G z v) phi + +omit [Fintype U] in +/-- The reverse accumulator used by a bounded fold has precisely the +chronological history after reversing its stored list. -/ +lemma traceAfter_fold (F : C → U → C) (us : List U) (c : C) (history : List C) : + (us.foldl (fun s u => let d := F s.1 u; (d,d::s.2)) (c,history)).2.reverse= + history.reverse++traceAfter F c us := by + induction us generalizing c history with + | nil => simp only [List.foldl_nil,traceAfter,List.append_nil] + | cons u us ih => + simp only [List.foldl_cons,traceAfter] + rw [ih,List.reverse_cons,List.append_assoc] + rfl + +omit [Fintype U] in +lemma traceStates_fold (F : C → U → C) (us : List U) (c : C) : + (us.foldl (fun s u => let d := F s.1 u; (d,d::s.2)) (c,[c])).2.reverse= + traceStates F c us := by + rw [traceAfter_fold] + rfl + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteFairBits.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteFairBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4cc398b442e6890d050da612d589202bcb86e98 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteFairBits.lean @@ -0,0 +1,60 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalReindex +import Mathlib.Logic.Equiv.Fin.Basic +import Mathlib.Algebra.BigOperators.Fin + +namespace OAI + +/-! # Finite binary words and their exact uniform experiment laws -/ + +namespace ContingencyTables.FairBits + +open scoped BigOperators Classical +open ResidualMixture FirstSuccess + +noncomputable section + +def binaryWordEquiv (k : ℕ) : (Fin k → Bool) ≃ Fin (2 ^ k) := + (Equiv.piCongrRight (fun _ : Fin k => finTwoEquiv.symm)).trans finFunctionFinEquiv + +def splitWordEquiv (k l : ℕ) : (Fin (k + l) → Bool) ≃ ((Fin k → Bool) × (Fin l → Bool)) := + (Equiv.arrowCongr finSumFinEquiv.symm (Equiv.refl Bool)).trans + (Equiv.sumArrowEquivProdArrow _ _ _) + +def pairWordEquiv (k l : ℕ) : (Fin (k + l) → Bool) ≃ (Fin (2 ^ k) × Fin (2 ^ l)) := + (splitWordEquiv k l).trans (Equiv.prodCongr (binaryWordEquiv k) (binaryWordEquiv l)) + +variable {α β : Type*} [Fintype α] [Fintype β] [Nonempty α] [Nonempty β] + +theorem uniform_equiv (e : α ≃ β) : + equivLaw e (uniformLaw (α := α)) = uniformLaw (α := β) := by + apply RationalLaw.ext + funext y + change 1 / (Fintype.card α : ℚ) = 1 / (Fintype.card β : ℚ) + rw [Fintype.card_congr e] + +theorem uniform_product : + productLaw (uniformLaw (α := α)) (uniformLaw (α := β)) = uniformLaw (α := α × β) := by + apply RationalLaw.ext + funext y + change (1 / (Fintype.card α : ℚ)) * (1 / (Fintype.card β : ℚ)) = 1 / (Fintype.card (α × β) : ℚ) + rw [Fintype.card_prod, Nat.cast_mul] + ring + +omit [Nonempty α] [Nonempty β] in +theorem map_equiv [DecidableEq β] {γ : Type*} [Fintype γ] [DecidableEq γ] + (e : α ≃ β) (p : RationalLaw α) (f : β → γ) : + mapLaw (equivLaw e p) f = mapLaw p (fun x => f (e x)) := by + apply RationalLaw.ext + funext z + symm + change (∑ x, if f (e x) = z then p.mass x else 0) = + ∑ y, if f y = z then p.mass (e.symm y) else 0 + apply Fintype.sum_equiv e + intro x + simp + +end + +end ContingencyTables.FairBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteGraphCutProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteGraphCutProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b54a99a5490a71fc53505b6cc578b92d47af69c --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteGraphCutProgram.lean @@ -0,0 +1,151 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphRootSemantics +import OAI.Combinatorics.ContingencyTables.Rooted.RootedCut + +namespace OAI + +/-! # Executing the selected root-away cut + +Deletion filters the stored adjacency rows. The endpoint and cut side +are then computed by the bounded reachability program. +-/ + +namespace ContingencyTables.FiniteGraphCutProgram + +open MatchingFPRAS.TreeTyped Polynomial FiniteGraphRootProgram + +abbrev EdgeInput := GraphCode×(ℕ×ℕ) +abbrev KeepInput := ((ℕ×ℕ)×ℕ)×ℕ + +def keep (z : KeepInput) : Bool := + if z.1.2=z.1.1.1 then decide (z.2≠z.1.1.2) + else if z.1.2=z.1.1.2 then decide (z.2≠z.1.1.1) else true + +def keepRealizer : Realizer keep := by + let I : Realizer (fun z : KeepInput => z.1.2) := composition first second + let U : Realizer (fun z : KeepInput => z.1.1.1) := composition (composition first first) first + let V : Realizer (fun z : KeepInput => z.1.1.2) := composition (composition first first) second + let neqU := composition (composition (pair second U) natEqual) boolNot + let neqV := composition (composition (pair second V) natEqual) boolNot + exact (choose (composition (pair I U) natEqual) neqV + (choose (composition (pair I V) natEqual) neqU (constant true))).congr (by + intro z + simp [keep]) + +lemma polynomial_keep : PolynomialTime keepRealizer := by + unfold keepRealizer + have hi : PolynomialTime (composition (first (A := (ℕ×ℕ)×ℕ) (B := ℕ)) second) := + polynomial_composition polynomial_first polynomial_second + have hu : PolynomialTime (composition + (composition (first (A := (ℕ×ℕ)×ℕ) (B := ℕ)) first) first) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_first + have hv : PolynomialTime (composition + (composition (first (A := (ℕ×ℕ)×ℕ) (B := ℕ)) first) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + exact polynomial_congr _ (polynomial_choose + (polynomial_composition (polynomial_pair hi hu) polynomial_natEqual) + (polynomial_composition (polynomial_composition (polynomial_pair polynomial_second hv) + polynomial_natEqual) polynomial_boolNot) + (polynomial_choose (polynomial_composition (polynomial_pair hi hv) polynomial_natEqual) + (polynomial_composition (polynomial_composition (polynomial_pair polynomial_second hu) + polynomial_natEqual) polynomial_boolNot) (polynomial_constant true))) + +def deleteRow (z : EdgeInput×ℕ) : List ℕ := + (z.1.1.getD z.2 []).filter (fun a => keep ((z.1.2,z.2),a)) + +def deleteRowRealizer : Realizer deleteRow := + composition (f := fun z : EdgeInput×ℕ => + ((z.1.2,z.2),z.1.1.getD z.2 [])) + (g := fun z : ((ℕ×ℕ)×ℕ)×List ℕ => z.2.filter (fun a => keep (z.1,a))) + (pair (pair (composition first second) second) + (composition (pair (composition first first) second) (getDFast []))) + (filterWith keepRealizer) + +lemma polynomial_deleteRow : PolynomialTime deleteRowRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast []))) (polynomial_filterWith polynomial_keep) + +def deleteGraph (z : EdgeInput) : GraphCode := + (indices z.1).map (fun i => deleteRow (z,i)) + +def deleteGraphRealizer : Realizer deleteGraph := + composition (pair identity (composition first indicesRealizer)) (mapWith deleteRowRealizer) + +theorem polynomial_deleteGraph : PolynomialTime deleteGraphRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_indices)) + (polynomial_mapWith polynomial_deleteRow) + +def reachableCode (z : Input×ℕ) : Bool := decide (z.2∈reached z.1) + +def reachableCodeRealizer : Realizer reachableCode := + composition (pair (composition first reachedRealizer) second) membership + +lemma polynomial_reachableCode : PolynomialTime reachableCodeRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_reached) polynomial_second) + polynomial_membership + +abbrev CutInput := EdgeInput×ℕ + +def awayCode (z : CutInput) : ℕ := + if reachableCode ((deleteGraph z.1,z.1.2.1),z.2) then z.1.2.2 else z.1.2.1 + +def awayTestRealizer : Realizer (fun z : CutInput => + reachableCode ((deleteGraph z.1,z.1.2.1),z.2)) := + composition (pair (pair (composition first deleteGraphRealizer) + (composition (composition first second) first)) second) reachableCodeRealizer + +lemma polynomial_awayTest : PolynomialTime awayTestRealizer := + polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_first polynomial_deleteGraph) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first)) polynomial_second) polynomial_reachableCode + +def awayCodeRealizer : Realizer awayCode := + choose awayTestRealizer (composition (composition first second) second) + (composition (composition first second) first) + +lemma polynomial_awayCode : PolynomialTime awayCodeRealizer := + polynomial_choose polynomial_awayTest + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first) + +def cutCode (z : CutInput×ℕ) : Bool := + reachableCode ((deleteGraph z.1.1,awayCode z.1),z.2) + +def cutCodeRealizer : Realizer cutCode := + composition (pair (pair + (composition (composition first first) deleteGraphRealizer) + (composition first awayCodeRealizer)) second) reachableCodeRealizer + +theorem polynomial_cutCode : PolynomialTime cutCodeRealizer := + polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_deleteGraph) + (polynomial_composition polynomial_first polynomial_awayCode)) polynomial_second) + polynomial_reachableCode + +def canonicalCutCode (z : EdgeInput×ℕ) : Bool := + cutCode ((z.1,rootCode (z.1.1,z.1.2.1)),z.2) + +def canonicalCutCodeRealizer : Realizer canonicalCutCode := + composition (pair (pair first + (composition (pair (composition first first) + (composition (composition first second) first)) rootCodeRealizer)) second) + cutCodeRealizer + +theorem polynomial_canonicalCutCode : PolynomialTime canonicalCutCodeRealizer := + polynomial_composition (polynomial_pair (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first)) polynomial_rootCode)) polynomial_second) polynomial_cutCode + +end ContingencyTables.FiniteGraphCutProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteGraphRootProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteGraphRootProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e0241fe29020214a9013917a6037ddddb2db167 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteGraphRootProgram.lean @@ -0,0 +1,201 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphRoots +import OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeProgram +import OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialCollections +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts +import OAI.Combinatorics.MatchingCount.Machines.TreeColex +import OAI.Combinatorics.MatchingCount.Sampling.TreeDPCounts + +namespace OAI + +/-! # A binary list program computing a component root + +The graph is supplied by adjacency lists. The program makes one growth +round per stored vertex, then minimizes the reached indices. No loop +depends on the numeric size of an index or of an edge capacity. +-/ + +namespace ContingencyTables.FiniteGraphRootProgram + +open MatchingFPRAS.TreeTyped Polynomial + +abbrev GraphCode := List (List ℕ) +abbrev SearchState := GraphCode×List ℕ +abbrev Input := GraphCode×ℕ + +def indices (rows : GraphCode) : List ℕ := List.range rows.length + +def indicesRealizer : Realizer indices := composition listLength range + +lemma polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange polynomial_listLength X + intro rows + simpa only [Function.comp_apply,eval_X] using list_length_le_weight rows + +def neighborHit (z : List ℕ×List ℕ) : Bool := + z.2.any (fun a => decide (a∈z.1)) + +def neighborHitRealizer : Realizer neighborHit := + (composition (mapWith membership) any).congr (by + intro z + simp only [Function.comp_apply,List.any_map,Function.comp_def,id_eq,neighborHit]) + +lemma polynomial_neighborHit : PolynomialTime neighborHitRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_mapWith polynomial_membership) polynomial_any) + +def growTest (z : SearchState×ℕ) : Bool := + decide (z.2∈z.1.2) || neighborHit (z.1.2,z.1.1.getD z.2 []) + +def growTestRealizer : Realizer growTest := + composition (f := fun z : SearchState×ℕ => + (decide (z.2∈z.1.2),neighborHit (z.1.2,z.1.1.getD z.2 []))) + (g := fun z : Bool×Bool => z.1 || z.2) + (pair (composition (pair (composition first second) second) membership) + (composition (pair (composition first second) + (composition (pair (composition first first) second) (getDFast []))) + neighborHitRealizer)) boolOr + +lemma polynomial_growTest : PolynomialTime growTestRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + polynomial_membership) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast []))) polynomial_neighborHit)) polynomial_boolOr + +def grow (z : SearchState) : List ℕ := + (indices z.1).filter (fun a => growTest (z,a)) + +def growRealizer : Realizer grow := + composition (pair identity (composition first indicesRealizer)) + (filterWith growTestRealizer) + +lemma polynomial_grow : PolynomialTime growRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition polynomial_first polynomial_indices)) + (polynomial_filterWith polynomial_growTest) + +def advance (z : List ℕ×SearchState) : SearchState := + (z.2.1,grow z.2) + +def advanceRealizer : Realizer advance := + pair (composition second first) + (composition (f := fun z : List ℕ×SearchState => z.2) (g := grow) second growRealizer) + +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition polynomial_second polynomial_grow) + +lemma fold_first (steps : List (List ℕ)) (s : SearchState) : + (steps.foldl (fun s row => advance (row,s)) s).1=s.1 := by + induction steps generalizing s with + | nil => rfl + | cons row steps ih => exact ih (advance (row,s)) + +lemma grow_weight (s : SearchState) : weight (grow s)≤weight (indices s.1) := + weight_sublist (List.filter_sublist (p := fun a => growTest (s,a)) (l := indices s.1)) + +lemma fold_weight (steps : List (List ℕ)) (s : SearchState) : + weight (steps.foldl (fun s row => advance (row,s)) s).2≤ + max (weight s.2) (weight (indices s.1)) := by + induction steps generalizing s with + | nil => exact le_max_left _ _ + | cons row steps ih => + have ht := ih (advance (row,s)) + have hs := grow_weight s + exact ht.trans (max_le (hs.trans (le_max_right _ _)) (le_max_right _ _)) + +lemma indices_weight (rows : GraphCode) : + weight (indices rows)≤rows.length*(4*rows.length+2)+1 := by + have h := weight_map_bound (as := List.range rows.length) (f := id) + (N := 4*rows.length+1) (by + intro a ha + exact (weight_nat_numeric a).trans (by + have := List.mem_range.mp ha + omega)) + simpa only [List.map_id,List.length_range,indices] using h + +lemma polynomial_searchFold : PolynomialTime (fold advanceRealizer) := by + apply polynomial_fold polynomial_advance (10*(X+1)^2) + intro steps s pre _post _he + let S := weight (steps,s) + let out := pre.foldl (fun s row => advance (row,s)) s + have hs : weight s≤S := weight_snd (steps,s) + have hr : weight s.1≤S := (weight_fst s).trans hs + have hv : weight s.2≤S := (weight_snd s).trans hs + have hn : s.1.length≤S := (list_length_le_weight s.1).trans hr + have hi := indices_weight s.1 + have hib : weight (indices s.1)≤4*S^2+2*S+1 := by + have hm := Nat.mul_le_mul hn (show 4*s.1.length+2≤4*S+2 by omega) + nlinarith + have ho : weight out.2 ≤ max (weight s.2) (weight (indices s.1)) := fold_weight pre s + have hot : weight out.2≤4*S^2+3*S+1 := ho.trans (max_le (by omega) (by omega)) + have hf : out.1=s.1 := fold_first pre s + have hw : weight out=weight out.1+weight out.2+1 := by + change weight (out.1,out.2)=_ + rw [weight_prod] + omega + simp only [eval_mul,eval_ofNat,eval_pow,eval_add,eval_X,eval_one] + change weight out≤10*(S+1)^2 + rw [hw,hf] + nlinarith + +def prepare (z : Input) : GraphCode×SearchState := (z.1,(z.1,[z.2])) + +def prepareRealizer : Realizer prepare := + pair first (pair first (composition (pair second (constant [])) listCons)) + +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair polynomial_first (polynomial_pair polynomial_first + (polynomial_composition (polynomial_pair polynomial_second (polynomial_constant [])) + polynomial_listCons)) + +def run (z : Input) : SearchState := + z.1.foldl (fun s row => advance (row,s)) (z.1,[z.2]) + +def runRealizer : Realizer run := composition prepareRealizer (fold advanceRealizer) + +lemma polynomial_run : PolynomialTime runRealizer := + polynomial_composition polynomial_prepare polynomial_searchFold + +def reached (z : Input) : List ℕ := (run z).2 + +def reachedRealizer : Realizer reached := + composition (f := run) (g := fun s : SearchState => s.2) runRealizer second + +theorem polynomial_reached : PolynomialTime reachedRealizer := + polynomial_composition polynomial_run polynomial_second + +lemma minimum_fold_le (xs : List ℕ) (b : ℕ) : + xs.foldl (fun b a => min a b) b≤b := by + induction xs generalizing b with + | nil => exact le_rfl + | cons a xs ih => exact (ih (min a b)).trans (min_le_right _ _) + +lemma polynomial_minimumFold : PolynomialTime (fold minimum) := by + apply polynomial_fold polynomial_minimum (4*X+1) + intro xs b pre _post _he + have hb : b.size≤weight (xs,b) := (size_le_weight b).trans (weight_snd (xs,b)) + have hs := Nat.size_le_size (minimum_fold_le pre b) + have hw := weight_nat_le (pre.foldl (fun b a => min a b) b) + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_one] + omega + +def rootCode (z : Input) : ℕ := + (reached z).foldl (fun b a => min a b) z.1.length + +def rootCodeRealizer : Realizer rootCode := + composition (f := fun z : Input => (reached z,z.1.length)) + (g := fun z : List ℕ×ℕ => z.1.foldl (fun b a => min a b) z.2) + (pair reachedRealizer (composition first listLength)) (fold minimum) + +theorem polynomial_rootCode : PolynomialTime rootCodeRealizer := + polynomial_composition (polynomial_pair polynomial_reached + (polynomial_composition polynomial_first polynomial_listLength)) polynomial_minimumFold + +end ContingencyTables.FiniteGraphRootProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FinitePlainLift.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FinitePlainLift.lean new file mode 100644 index 0000000000000000000000000000000000000000..96f25f7698b4c9cd703197ec874359a1f4252ac3 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FinitePlainLift.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RealKernelApproximation +import OAI.Combinatorics.MatroidCounting.CommonBases + +namespace OAI + +/-! # Exact moment and distance identities for the transversal embedding -/ + +namespace ContingencyTables.FinitePlainLift + +open CommonBasesFPRAS RealKernelApproximation +open scoped BigOperators Classical + +noncomputable section +variable {Γ : Type*} [Fintype Γ] + +lemma sum_mul (gs : List (Γ × Γ)) (p : PlainIndex gs → ℝ) + (g : ChainIndex gs → ℝ) : + (∑ S,plainLift gs p S*g S)=∑ S : PlainIndex gs,p S*g S.val := by + have h := Fintype.sum_subtype_add_sum_subtype (plainPredicate gs) + (fun S => plainLift gs p S*g S) + have ht (S : PlainIndex gs) : plainLift gs p S.val*g S.val=p S*g S.val := by + rw [plainLift,dite_eq_left S.property] + have hf (S : {S : ChainIndex gs // ¬plainPredicate gs S}) : + plainLift gs p S.val*g S.val=0 := by + rw [plainLift,dite_eq_right S.property,zero_mul] + simp_rw [ht,hf,Finset.sum_const_zero,add_zero] at h + exact h.symm + +lemma distance_lift (gs : List (Γ × Γ)) (p q : PlainIndex gs → ℝ) : + distance (plainLift gs p) (plainLift gs q)=distance p q := by + have h := Fintype.sum_subtype_add_sum_subtype (plainPredicate gs) + (fun S => |plainLift gs p S-plainLift gs q S|) + have ht (S : PlainIndex gs) : + |plainLift gs p S.val-plainLift gs q S.val|=|p S-q S| := by + rw [plainLift,dite_eq_left S.property,plainLift,dite_eq_left S.property] + have hf (S : {S : ChainIndex gs // ¬plainPredicate gs S}) : + |plainLift gs p S.val-plainLift gs q S.val|=0 := by + rw [plainLift,dite_eq_right S.property,plainLift,dite_eq_right S.property,sub_self,abs_zero] + simp_rw [ht,hf,Finset.sum_const_zero,add_zero] at h + unfold distance + rw [h] + +end +end ContingencyTables.FinitePlainLift + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteTraceSlowdown.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteTraceSlowdown.lean new file mode 100644 index 0000000000000000000000000000000000000000..b8fb530aa735b06d11e5863d7cc43dc4aa4806f0 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteTraceSlowdown.lean @@ -0,0 +1,190 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteChainSlowdown + +namespace OAI + +/-! # Trace transition matrices under an exact holding slowdown -/ + +namespace ContingencyTables.FiniteChainSlowdown + +open CommonBasesFPRAS +open scoped BigOperators Classical + +noncomputable section + +variable {Y : Type*} [Fintype Y] + +def slowKilled (Q : KilledKernel Y) (a : ℝ) (ha0 : 0 < a) (ha1 : a ≤ 1) : KilledKernel Y where + Q x y := a*Q.Q x y+if x=y then 1-a else 0 + r := a*Q.r+(1-a) + nonnegative x y := by + apply add_nonneg (mul_nonneg ha0.le (Q.nonnegative x y)) + split_ifs + · linarith + · rfl + rnonneg := add_nonneg (mul_nonneg ha0.le Q.rnonneg) (sub_nonneg.mpr ha1) + rlt := by nlinarith [mul_pos ha0 (sub_pos.mpr Q.rlt)] + rowbound x := by + simp only [Finset.sum_add_distrib,←Finset.mul_sum] + have hh := mul_le_mul_of_nonneg_left (Q.rowbound x) ha0.le + simpa using add_le_add_right hh (1-a) + +lemma slowKilled_apply (Q : KilledKernel Y) (a : ℝ) (ha0 : 0 < a) (ha1 : a ≤ 1) + (f : Y → ℝ) (x : Y) : + (slowKilled Q a ha0 ha1).apply f x=a*Q.apply f x+(1-a)*f x := by + unfold KilledKernel.apply + change (∑ y,(a*Q.Q x y+if x=y then 1-a else 0)*f y)=_ + simp only [add_mul,Finset.sum_add_distrib,ite_mul,zero_mul,mul_assoc] + rw [←Finset.mul_sum] + simp + +variable {X : Type*} [Fintype X] + +lemma inner (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) + (f g : X → ℝ) : (slow C a ha0 ha1).inner f g=C.inner f g := rfl + +/-- The observable dual estimate is also stable under the holding +factor. This is the estimate used by trajectory concentration; a full +spectral gap for unrelated observables is not needed. -/ +theorem dual_bound (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) + (ha : 1/2 ≤ a) (K : ℝ) (hK : 0 ≤ K) (g H : X → ℝ) + (h : (C.inner g H)^2 ≤ K*C.inner g g*C.energy H) : + ((slow C a ha0 ha1).inner g H)^2 ≤ + (2*K)*(slow C a ha0 ha1).inner g g*(slow C a ha0 ha1).energy H := by + have he : C.energy H ≤ 2*(slow C a ha0 ha1).energy H := by + rw [energy] + have hm := mul_le_mul_of_nonneg_right ha (C.energy_nonneg H) + linarith + rw [inner,inner] + calc + _ ≤ K*C.inner g g*C.energy H := h + _ ≤ K*C.inner g g*(2*(slow C a ha0 ha1).energy H) := + mul_le_mul_of_nonneg_left he (mul_nonneg hK (C.inner_nonneg g)) + _ = _ := by ring + +/-- Thus all accepted warm-start trajectory moment estimates transfer +to the implemented holding chain with a factor of at most two. -/ +theorem warm_moment_bound (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) + (ha : 1/2 ≤ a) (K U : ℝ) (hK : 0 ≤ K) (hU : 0 ≤ U) (g : X → ℝ) + (hdual : ∀ H,(C.inner g H)^2 ≤ K*C.inner g g*C.energy H) + (nu : X → ℝ) (hwarm : ∀ x,nu x ≤ U*C.π x) (N : ℕ) (hN : 0 < N) : + (∑ x,nu x*(slow C a ha0 ha1).squareMoment g N x)/(N:ℝ)^2 ≤ + 4*U*K*C.inner g g/N := by + have hh := (slow C a ha0 ha1).warm_squareMoment_bound g (2*K) U + (mul_nonneg (by norm_num) hK) hU + (fun H => dual_bound C a ha0 ha1 ha K hK g H (hdual H)) nu hwarm N hN + simpa only [inner,show 2*U*(2*K)=4*U*K by ring] using hh + +lemma slow_apply (C : FiniteChain X) (a : ℝ) (ha0 : 0 ≤ a) (ha1 : a ≤ 1) + (f : X → ℝ) (x : X) : + (slow C a ha0 ha1).apply f x=a*C.apply f x+(1-a)*f x := by + unfold FiniteChain.apply + change (∑ y,(a*C.P x y+if x=y then 1-a else 0)*f y)=_ + simp only [add_mul,Finset.sum_add_distrib,ite_mul,zero_mul,mul_assoc] + rw [←Finset.mul_sum] + simp + +lemma slowKilled_matches (C : FiniteChain X) (A : X → Prop) + (Q : KilledKernel (FiniteChain.Outside A)) + (hQ : ∀ x y : FiniteChain.Outside A,Q.Q x y=C.P x.val y.val) + (a : ℝ) (ha0 : 0 < a) (ha1 : a ≤ 1) : + ∀ x y : FiniteChain.Outside A,(slowKilled Q a ha0 ha1).Q x y= + (slow C a ha0.le ha1).P x.val y.val := by + intro x y + simp only [slowKilled,slow] + rw [hQ] + by_cases h : x=y + · subst y + simp + · have hv : x.val≠y.val := fun hv => h (Subtype.ext hv) + simp only [h,hv,ite_false] + +/-- A holding step changes when the chain hits the selected set, but +not where it first hits. The equality follows from the Green residual +identity, without manipulating an infinite series term by term. -/ +theorem hitKernel (C : FiniteChain X) (A : X → Prop) + (Q : KilledKernel (FiniteChain.Outside A)) + (a : ℝ) (ha0 : 0 < a) (ha1 : a ≤ 1) + (x : FiniteChain.Outside A) (y : FiniteChain.Inside A) : + (slow C a ha0.le ha1).hitKernel A (slowKilled Q a ha0 ha1) x y=C.hitKernel A Q x y := by + let h : FiniteChain.Outside A → ℝ := fun z => C.hitKernel A Q z y + have hh (z : FiniteChain.Outside A) : h z=C.P z.val y.val+Q.apply h z := by + exact Q.green_firstStep (fun z => C.P z.val y.val) z + have he (z : FiniteChain.Outside A) : + (slow C a ha0.le ha1).P z.val y.val=h z-(slowKilled Q a ha0 ha1).apply h z := by + have hzy : z.val≠y.val := fun he => z.property (he.symm ▸ y.property) + change a*C.P z.val y.val+(if z.val=y.val then 1-a else 0)=_ + rw [ite_eq_right hzy,add_zero,slowKilled_apply] + nlinarith [hh z] + unfold FiniteChain.hitKernel + simp_rw [he] + exact (slowKilled Q a ha0 ha1).green_residual h x + +/-- The trace itself acquires exactly the same holding factor. -/ +theorem traceMatrix (C : FiniteChain X) (A : X → Prop) + (Q : KilledKernel (FiniteChain.Outside A)) + (a : ℝ) (ha0 : 0 < a) (ha1 : a ≤ 1) + (x y : FiniteChain.Inside A) : + (slow C a ha0.le ha1).traceMatrix A (slowKilled Q a ha0 ha1) x y= + a*C.traceMatrix A Q x y+if x=y then 1-a else 0 := by + unfold FiniteChain.traceMatrix + simp_rw [hitKernel C A Q a ha0 ha1] + have he (z : FiniteChain.Outside A) : (slow C a ha0.le ha1).P x.val z.val=a*C.P x.val z.val := by + have hxz : x.val≠z.val := fun he => z.property (he ▸ x.property) + change a*C.P x.val z.val+(if x.val=z.val then 1-a else 0)=_ + rw [ite_eq_right hxz,add_zero] + simp_rw [he,mul_assoc,←Finset.mul_sum] + change (a*C.P x.val y.val+if x.val=y.val then 1-a else 0)+ + a*(∑ z : FiniteChain.Outside A,C.P x.val z.val*C.hitKernel A Q z y)=_ + have hiff : x.val=y.val ↔ x=y := ⟨Subtype.ext,congrArg Subtype.val⟩ + simp only [hiff] + ring + +theorem trace_energy (C : FiniteChain X) (A : X → Prop) + [Nonempty (FiniteChain.Inside A)] (Q : KilledKernel (FiniteChain.Outside A)) + (hQ : ∀ x y : FiniteChain.Outside A,Q.Q x y=C.P x.val y.val) + (a : ℝ) (ha0 : 0 < a) (ha1 : a ≤ 1) (f : FiniteChain.Inside A → ℝ) : + ((slow C a ha0.le ha1).traceChain A (slowKilled Q a ha0 ha1) + (slowKilled_matches C A Q hQ a ha0 ha1)).energy f= + a*(C.traceChain A Q hQ).energy f := by + rw [FiniteChain.energy_eq,FiniteChain.energy_eq,←mul_div_assoc] + congr 1 + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro x _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro y _ + change (C.π x.val/C.insideMass A)* + (slow C a ha0.le ha1).traceMatrix A (slowKilled Q a ha0 ha1) x y*(f x-f y)^2= + a*((C.π x.val/C.insideMass A)*C.traceMatrix A Q x y*(f x-f y)^2) + rw [traceMatrix C A Q a ha0 ha1] + by_cases h : x=y + · subst y + simp + · simp only [h,ite_false,add_zero] + ring + +/-- This transfers the accepted trace Poincaré estimate to the actual +dyadic holding chain, rather than merely to a separately defined trace. -/ +theorem trace_variance_bound (C : FiniteChain X) (A : X → Prop) + [Nonempty (FiniteChain.Inside A)] (Q : KilledKernel (FiniteChain.Outside A)) + (hQ : ∀ x y : FiniteChain.Outside A,Q.Q x y=C.P x.val y.val) + (a : ℝ) (ha0 : 0 < a) (ha1 : a ≤ 1) (ha : 1/2 ≤ a) + (K : ℝ) (hK : 0 ≤ K) (f : FiniteChain.Inside A → ℝ) + (h : (C.traceChain A Q hQ).variance f ≤ K*(C.traceChain A Q hQ).energy f) : + ((slow C a ha0.le ha1).traceChain A (slowKilled Q a ha0 ha1) + (slowKilled_matches C A Q hQ a ha0 ha1)).variance f ≤ + (2*K)*((slow C a ha0.le ha1).traceChain A (slowKilled Q a ha0 ha1) + (slowKilled_matches C A Q hQ a ha0 ha1)).energy f := by + have hv : ((slow C a ha0.le ha1).traceChain A (slowKilled Q a ha0 ha1) + (slowKilled_matches C A Q hQ a ha0 ha1)).variance f=(C.traceChain A Q hQ).variance f := rfl + rw [hv,trace_energy C A Q hQ a ha0 ha1] + have hm := mul_le_mul_of_nonneg_right ha ((C.traceChain A Q hQ).energy_nonneg f) + have hh := mul_le_mul_of_nonneg_left hm hK + nlinarith + +end + +end ContingencyTables.FiniteChainSlowdown + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteVaryingObservable.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteVaryingObservable.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d269a0daed4b4fc533cd47a84dd8ccf93d9b954 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteVaryingObservable.lean @@ -0,0 +1,67 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteVaryingWordWalk +import OAI.Combinatorics.ContingencyTables.Machines.FiniteEncodedHistory + +namespace OAI + +/-! # Observable transport for independent words of varying widths -/ +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS FirstSuccess +open scoped Classical + +noncomputable section + +lemma uniformAverage_pi_snoc {N : ℕ} {Y : Fin (N+1) → Type*} + [∀ i,Fintype (Y i)] (f : ((i : Fin (N+1)) → Y i) → ℝ) : + uniformAverage f=uniformAverage (fun xy : + ((i : Fin N) → Y i.castSucc) × Y (Fin.last N) => f (Fin.snoc xy.1 xy.2)) := by + let E : (((i : Fin N) → Y i.castSucc) × Y (Fin.last N)) ≃ + ((i : Fin (N+1)) → Y i) := + (Equiv.prodComm _ _).trans (Fin.snocEquiv Y) + exact (uniformAverage_equiv E f).symm + +/-- The encoded state type need not be finite. Equality of every actual +conditional call transfers the entire variable-width experiment. -/ +theorem varyingWalk_sameLaw {C Z : Type*} (u v : ℕ → ℕ) + (F : (i : ℕ) → C → (Fin (u i) → Bool) → C) + (G : (i : ℕ) → Z → (Fin (v i) → Bool) → Z) (e : Z → C) + (h : ∀ i z,SameLaw (F i (e z)) (fun bits => e (G i z bits))) + (z : Z) (N : ℕ) : + SameLaw (varyingWalk u F (e z) N) (fun bits => e (varyingWalk v G z N bits)) := by + intro phi + induction N generalizing phi with + | zero => simp only [varyingWalk,uniformAverage_const] + | succ N ih => + rw [uniformAverage_pi_snoc,uniformAverage_pi_snoc] + simp only [varyingWalk,Fin.init_snoc,Fin.snoc_last] + rw [uniformAverage_prod,uniformAverage_prod] + have hi := ih (fun c => uniformAverage (fun bits : Fin (u N) → Bool => phi (F N c bits))) + refine hi.trans ?_ + apply congrArg uniformAverage + funext pref + exact h N (varyingWalk v G z N pref) phi + +/-- Only stages actually visited need a conditional-law identification. -/ +theorem varyingWalk_sameLaw_prefix {C Z : Type*} (u v : ℕ → ℕ) + (F : (i : ℕ) → C → (Fin (u i) → Bool) → C) + (G : (i : ℕ) → Z → (Fin (v i) → Bool) → Z) (e : Z → C) + (z : Z) (N : ℕ) + (h : ∀ i,i < N → ∀ s,SameLaw (F i (e s)) (fun bits => e (G i s bits))) : + SameLaw (varyingWalk u F (e z) N) (fun bits => e (varyingWalk v G z N bits)) := by + intro phi + induction N generalizing phi with + | zero => simp only [varyingWalk,uniformAverage_const] + | succ N ih => + rw [uniformAverage_pi_snoc,uniformAverage_pi_snoc] + simp only [varyingWalk,Fin.init_snoc,Fin.snoc_last] + rw [uniformAverage_prod,uniformAverage_prod] + have hi := ih (fun i hi => h i (Nat.lt_trans hi (Nat.lt_succ_self N))) + (fun c => uniformAverage (fun bits : Fin (u N) → Bool => phi (F N c bits))) + refine hi.trans ?_ + apply congrArg uniformAverage + funext pref + exact h N (Nat.lt_succ_self N) (varyingWalk v G z N pref) phi + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteVaryingWordWalk.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteVaryingWordWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..eafb380d2e1b390dd9c05ab34fbe8cf2b6e6bb16 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteVaryingWordWalk.lean @@ -0,0 +1,109 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent + +namespace OAI + +/-! # Independent words for successive draws with varying widths -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture FairBits +noncomputable section + +variable {X : Type*} [Fintype X] [DecidableEq X] + +abbrev VaryingWords (width : ℕ → ℕ) (n : ℕ) := + (i : Fin n) → Fin (width i.val) → Bool + +def varyingWalk (width : ℕ → ℕ) + (step : (i : ℕ) → X → (Fin (width i) → Bool) → X) (x : X) : + (n : ℕ) → VaryingWords width n → X + | 0,_ => x + | n+1,bits => step n (varyingWalk width step x n (Fin.init bits)) (bits (Fin.last n)) + +def varyingLaw (width : ℕ → ℕ) + (step : (i : ℕ) → X → (Fin (width i) → Bool) → X) + (p : RationalLaw X) : ℕ → RationalLaw X + | 0 => p + | n+1 => bindLaw (varyingLaw width step p n) + (fun x => mapLaw (uniformLaw (α := Fin (width n) → Bool)) (step n x)) + +theorem varyingWalk_law (width : ℕ → ℕ) + (step : (i : ℕ) → X → (Fin (width i) → Bool) → X) (x : X) (n : ℕ) : + mapLaw (uniformLaw (α := VaryingWords width n)) (varyingWalk width step x n)= + varyingLaw width step (pointLaw x) n := by + induction n with + | zero => + apply RationalLaw.ext + funext y + simp [varyingWalk,varyingLaw,pointLaw,mapLaw,uniformLaw,uniformMass,eq_comm] + | succ n ih => + let E : (VaryingWords width n × (Fin (width n) → Bool)) ≃ VaryingWords width (n+1) := + (Equiv.prodComm _ _).trans (Fin.snocEquiv (fun i : Fin (n+1) => Fin (width i.val) → Bool)) + have hc : varyingWalk width step x (n+1) ∘ E= + fun ab => step n (varyingWalk width step x n ab.1) ab.2 := by + funext ab + rcases ab with ⟨pref,last⟩ + change step n (varyingWalk width step x n (Fin.init + (Fin.snoc (α := fun i : Fin (n+1) => Fin (width i.val) → Bool) pref last))) + ((Fin.snoc (α := fun i : Fin (n+1) => Fin (width i.val) → Bool) pref last) + (Fin.last n))=_ + simp only [Fin.init_snoc,Fin.snoc_last] + apply RationalLaw.ext + funext y + change (mapLaw (uniformLaw (α := VaryingWords width (n+1))) + (varyingWalk width step x (n+1))).mass y= + (bindLaw (varyingLaw width step (pointLaw x) n) + (fun z => mapLaw (uniformLaw (α := Fin (width n) → Bool)) (step n z))).mass y + rw [←ih] + simp only [bindLaw,uniform_map_mass] + have he := uniformMapMass_equiv E (varyingWalk width step x (n+1)) y + rw [hc] at he + rw [←he] + exact uniformMapMass_prod (varyingWalk width step x n) (step n) y + +omit [DecidableEq X] in +private lemma bindLaw_associative (p : RationalLaw X) (q r : X → RationalLaw X) : + bindLaw (bindLaw p q) r=bindLaw p (fun x => bindLaw (q x) r) := by + apply RationalLaw.ext + funext z + simp only [bindLaw,Finset.sum_mul,Finset.mul_sum,mul_assoc] + exact Finset.sum_comm + +theorem varyingLaw_start (width : ℕ → ℕ) + (step : (i : ℕ) → X → (Fin (width i) → Bool) → X) + (p : RationalLaw X) (n : ℕ) : + bindLaw p (fun x => varyingLaw width step (pointLaw x) n)=varyingLaw width step p n := by + induction n with + | zero => + apply RationalLaw.ext + funext y + simp [varyingLaw,bindLaw,pointLaw] + | succ n ih => + change bindLaw p (fun x => bindLaw (varyingLaw width step (pointLaw x) n) + (fun z => mapLaw (uniformLaw (α := Fin (width n) → Bool)) (step n z)))= + bindLaw (varyingLaw width step p n) + (fun z => mapLaw (uniformLaw (α := Fin (width n) → Bool)) (step n z)) + rw [←ih,bindLaw_associative] + +def varyingWordEquiv (width : ℕ → ℕ) (n : ℕ) : + (Fin (∑ i : Fin n,width i.val) → Bool) ≃ VaryingWords width n := + (Equiv.arrowCongr finSigmaFinEquiv.symm (Equiv.refl Bool)).trans + (Equiv.piCurry (fun _ _ => Bool)) + +/-- The flattened word consumes exactly the sum of the successive +widths, including unused bits on any branch of the deterministic draws. -/ +theorem flatVaryingWalk_law (width : ℕ → ℕ) + (step : (i : ℕ) → X → (Fin (width i) → Bool) → X) (x : X) (n : ℕ) : + mapLaw (uniformLaw (α := Fin (∑ i : Fin n,width i.val) → Bool)) + (fun bits => varyingWalk width step x n (varyingWordEquiv width n bits))= + varyingLaw width step (pointLaw x) n := by + have he := map_equiv (varyingWordEquiv width n) + (uniformLaw (α := Fin (∑ i : Fin n,width i.val) → Bool)) (varyingWalk width step x n) + rw [uniform_equiv] at he + exact he.symm.trans (varyingWalk_law width step x n) + +end +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordDependent.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordDependent.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d7a66e7cf0ef3fba51c8b49131207cba555f75a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordDependent.lean @@ -0,0 +1,75 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentLaw +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordWalk + +namespace OAI + +/-! # Independent words with a state-dependent second output -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture FairBits + +noncomputable section + +variable {A B X Z : Type*} [Fintype A] [Fintype B] [Fintype X] [Fintype Z] + +lemma mapLaw_product_bind [DecidableEq Z] (p : RationalLaw A) (q : RationalLaw B) + (f : A → B → Z) : + mapLaw (productLaw p q) (fun ab => f ab.1 ab.2)= + bindLaw p (fun a => mapLaw q (f a)) := by + apply RationalLaw.ext + funext z + simp only [mapLaw,productLaw,bindLaw,Fintype.sum_prod_type,Finset.mul_sum,mul_ite,mul_zero] + +omit [Fintype Z] in +/-- Fresh terminal bits are independent of the bits used to obtain the +state, even though the completion space depends on that state. -/ +theorem mapLaw_dependent_product {Y : X → Type*} [∀ x,Fintype (Y x)] + [DecidableEq X] [∀ x,DecidableEq (Y x)] + (p : RationalLaw A) (q : RationalLaw B) (f : A → X) (g : (x : X) → B → Y x) : + mapLaw (productLaw p q) (fun ab => (⟨f ab.1,g (f ab.1) ab.2⟩ : Sigma Y))= + dependentJointLaw (mapLaw p f) (fun x => mapLaw q (g x)) := by + apply RationalLaw.ext + funext z + rcases z with ⟨x,y⟩ + simp only [mapLaw,productLaw,dependentJointLaw,Fintype.sum_prod_type,Finset.sum_mul] + apply Finset.sum_congr rfl + intro a _ + by_cases h : f a=x + · subst x + simp only [Sigma.mk.inj_iff,heq_eq_eq,true_and,ite_true,Finset.mul_sum,mul_ite,mul_zero] + · have hn (b : B) : (⟨f a,g (f a) b⟩ : Sigma Y)≠⟨x,y⟩ := + fun hh => h (congrArg Sigma.fst hh) + simp only [hn,ite_false,h,Finset.sum_const_zero,zero_mul] + + +/-- First drawing a state and then applying a fresh common word to that +state gives the corresponding composition of output laws. -/ +theorem mapLaw_product_finish [DecidableEq X] [DecidableEq Z] + (p : RationalLaw A) (q : RationalLaw B) (f : A → X) (finish : X → B → Z) : + mapLaw (productLaw p q) (fun ab => finish (f ab.1) ab.2)= + bindLaw (mapLaw p f) (fun x => mapLaw q (finish x)) := by + apply RationalLaw.ext + funext z + simp only [mapLaw,productLaw,bindLaw,Fintype.sum_prod_type] + symm + calc + _ = ∑ a,p.mass a*(∑ b,if finish (f a) b=z then q.mass b else 0) := by + simp_rw [Finset.sum_mul,ite_mul,zero_mul] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro a _ + simp + _ = _ := by + apply Finset.sum_congr rfl + intro a _ + rw [Finset.mul_sum] + apply Finset.sum_congr rfl + intro b _ + split_ifs <;> simp + +end +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordExecution.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordExecution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5de0b6ac51d8f74ca550b21f98b654aea4df9ac --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordExecution.lean @@ -0,0 +1,84 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FairBits +import OAI.Combinatorics.MatchingCount.Complexity.OnlineWordCost + +namespace OAI + +/-! # Executing a computed finite Boolean sampler + +The program reads a fresh word on the physical online machine, preserves +the input, and runs the deterministic binary sampler on that word. +-/ + +namespace ContingencyTables.FiniteWordExecution +open MatchingFPRAS MatchingFPRAS.PhysicalStream Polynomial + +variable {A B : Type} [TreeTyped.Codec A] [TreeTyped.Codec B] + +def source (n : A → ℕ) (a : A) : Experiment (List Bool) := OnlineWord.prepend (n a) [] + +noncomputable def sourceRealizer {n : A → ℕ} (N : TreeTyped.Realizer n) : + OnlineTree.Realizer (source n) := + (OnlineTree.composition (OnlineTree.deterministic N) OnlineWord.naturalRealizer).congr + (by intro a g; rfl) + +def wordMeasure (n : A → ℕ) (a : A) : ℕ := TreeTyped.weight a+n a + +theorem work_source {n : A → ℕ} {N : TreeTyped.Realizer n} + (hN : TreeTyped.PolynomialTime N) : + OnlineTree.WorkBound (sourceRealizer N) (wordMeasure n) := by + unfold sourceRealizer + apply OnlineTree.work_congr + have hN' : OnlineTree.WorkBound (OnlineTree.deterministic N) (wordMeasure n) := + OnlineTree.work_of_polynomial (OnlineTree.polynomial_deterministic hN) X (by + intro a + simp only [eval_X,wordMeasure] + omega) + apply OnlineTree.work_composition hN' OnlineWord.work_natural (5*X+1) + intro a + change n a+TreeTyped.weight (n a)≤(5*X+1).eval (wordMeasure n a) + have hw := TreeTyped.weight_nat_numeric (n a) + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_one,wordMeasure] + omega + +def experiment (n : A → ℕ) (f : A×List Bool → B) (a : A) : Experiment B := + (source n a).map (fun bs => f (a,bs)) + +noncomputable def realizer {n : A → ℕ} {f : A×List Bool → B} + (N : TreeTyped.Realizer n) (F : TreeTyped.Realizer f) : OnlineTree.Realizer (experiment n f) := + (OnlineTree.composition + (OnlineTree.pair (OnlineTree.deterministic TreeTyped.identity) (sourceRealizer N)) + (OnlineTree.deterministic F)).congr (by + intro a g + simp only [Experiment.mean_bind,Experiment.mean,Experiment.mean_map,experiment,id_eq]) + +/-- Runtime is polynomial in the input's encoded size plus the number of +fresh bits. -/ +theorem work_realizer {n : A → ℕ} {f : A×List Bool → B} + {N : TreeTyped.Realizer n} {F : TreeTyped.Realizer f} + (hN : TreeTyped.PolynomialTime N) (hF : TreeTyped.PolynomialTime F) : + OnlineTree.WorkBound (realizer N F) (wordMeasure n) := by + unfold realizer + apply OnlineTree.work_congr + apply OnlineTree.work_then_polynomial _ (OnlineTree.polynomial_deterministic hF) + have hid : OnlineTree.WorkBound (OnlineTree.deterministic (TreeTyped.identity (A := A))) + (wordMeasure n) := + OnlineTree.work_of_polynomial (OnlineTree.polynomial_deterministic TreeTyped.polynomial_identity) X (by + intro a + simp only [eval_X,wordMeasure] + omega) + apply OnlineTree.work_pair hid (work_source hN) X + intro a + simp only [eval_X,wordMeasure] + omega + +omit [TreeTyped.Codec A] [TreeTyped.Codec B] in + +theorem experiment_mean (n : A → ℕ) (f : A×List Bool → B) (a : A) (g : B → ℚ) : + (experiment n f a).mean g= + average (fun bits : Bits (n a) => g (f (a,List.ofFn bits))) := by + unfold experiment source + rw [Experiment.mean_map,OnlineWord.mean_prepend_nil] + +end ContingencyTables.FiniteWordExecution + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordJointPadding.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordJointPadding.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac4d4e59b5e883b69ff906ef3fdce5988b51384b --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordJointPadding.lean @@ -0,0 +1,83 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartPadding + +namespace OAI + +/-! # Padding preserves the joint law with every unused suffix bit -/ +namespace ContingencyTables.FiniteObservableTransport +open CommonBasesFPRAS FairBits +open scoped BigOperators Classical +noncomputable section + +theorem SameLaw.append_joint {Z : Type*} {n q : ℕ} + {f : (Fin n → Bool) → Z} {g : (Fin q → Bool) → Z} + (h : SameLaw f g) (t : ℕ) : + SameLaw (fun bits : Fin (n+t) → Bool => + (f (splitWordEquiv n t bits).1,(splitWordEquiv n t bits).2)) + (fun bits : Fin (q+t) → Bool => + (g (splitWordEquiv q t bits).1,(splitWordEquiv q t bits).2)) := by + have hp := h.prod (show SameLaw (fun bits : Fin t → Bool => bits) (fun bits : Fin t → Bool => bits) + from fun _ => rfl) + intro phi + have hl := uniformAverage_equiv (splitWordEquiv n t) + (fun p : (Fin n → Bool)×(Fin t → Bool) => phi (f p.1,p.2)) + have hr := uniformAverage_equiv (splitWordEquiv q t) + (fun p : (Fin q → Bool)×(Fin t → Bool) => phi (g p.1,p.2)) + exact hl.trans ((hp phi).trans hr.symm) + +theorem restart_append_joint_sameLaw + (base : List CompanionRestartProgram.Stage×List ℕ) (n q : ℕ) + (hn : (∑ i : Fin base.1.length,CompanionRestartProgram.widthAt base i.val)=n) + (g : (Fin q → Bool) → List ℕ) + (h : SameLaw (fun bits : Fin n → Bool => + CompanionRestartProgram.output (base,List.ofFn bits)) g) (t : ℕ) : + SameLaw (fun bits : Fin (n+t) → Bool => + (CompanionRestartProgram.output (base,List.ofFn bits),(splitWordEquiv n t bits).2)) + (fun bits : Fin (q+t) → Bool => + (g (splitWordEquiv q t bits).1,(splitWordEquiv q t bits).2)) := by + have hp := h.append_joint t + have he (bits : Fin (n+t) → Bool) : + CompanionRestartProgram.output (base,List.ofFn bits)= + CompanionRestartProgram.output (base,List.ofFn (splitWordEquiv n t bits).1) := by + have hs := (CompanionRestartProgram.output_take_sum base (List.ofFn bits)).symm + rw [hn,DensePrograms.ofFn_split_take] at hs + exact hs + intro phi + simp_rw [he] + exact hp phi + +/-- Flattening the first two independent blocks preserves their joint +law with the untouched third block. -/ +theorem nested_word_joint {Z : Type*} (a b t : ℕ) + (f : (Fin a → Bool) → (Fin b → Bool) → Z) : + SameLaw (fun bits : Fin (a+(b+t)) → Bool => + (f (splitWordEquiv a (b+t) bits).1 + (splitWordEquiv b t (splitWordEquiv a (b+t) bits).2).1, + (splitWordEquiv b t (splitWordEquiv a (b+t) bits).2).2)) + (fun bits : (Fin (a+b) → Bool)×(Fin t → Bool) => + (f (splitWordEquiv a b bits.1).1 (splitWordEquiv a b bits.1).2,bits.2)) := by + intro phi + have houter := uniformAverage_equiv (splitWordEquiv a (b+t)) + (fun p : (Fin a → Bool)×(Fin (b+t) → Bool) => + phi (f p.1 (splitWordEquiv b t p.2).1,(splitWordEquiv b t p.2).2)) + have hinner (u : Fin a → Bool) := uniformAverage_equiv (splitWordEquiv b t) + (fun p : (Fin b → Bool)×(Fin t → Bool) => phi (f u p.1,p.2)) + have hfirst := uniformAverage_equiv (splitWordEquiv a b) + (fun p : (Fin a → Bool)×(Fin b → Bool) => + uniformAverage (fun tail : Fin t → Bool => phi (f p.1 p.2,tail))) + rw [uniformAverage_prod] at hfirst + rw [uniformAverage_prod] + refine houter.trans ?_ + rw [uniformAverage_prod] + calc + _ = uniformAverage (fun u : Fin a → Bool => + uniformAverage (fun v : Fin b → Bool => + uniformAverage (fun tail : Fin t → Bool => phi (f u v,tail)))) := by + apply congrArg uniformAverage + funext u + exact (hinner u).trans (uniformAverage_prod _) + _ = _ := hfirst.symm + +end +end ContingencyTables.FiniteObservableTransport + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordMachine.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordMachine.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b677a1dceff26cd863702c20765ed6b6aa7b937 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordMachine.lean @@ -0,0 +1,92 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordExecution +import OAI.Combinatorics.ContingencyTables.Machines.LiteralProgram + +namespace OAI + +/-! # A single physical machine for a computed finite-word algorithm -/ + +namespace ContingencyTables.FiniteWordExecution +open MatchingFPRAS MatchingFPRAS.PhysicalStream Turing +open TreeTyped Polynomial + +variable {n : List Symbol → ℕ} {f : List Symbol×List Bool → List Symbol} + +noncomputable def machine (N : TreeTyped.Realizer n) (F : TreeTyped.Realizer f) : RandomMachine := + (LiteralProgram.wrap (realizer N F)).machine + +noncomputable def machineTime (N : TreeTyped.Realizer n) (F : TreeTyped.Realizer f) + (as : List Symbol) : ℕ := LiteralProgram.wrapTime (realizer N F) as + +private lemma output_alphabet (as : List Symbol) + (hout : ∀ bs,∀ b∈f (as,bs),b≠6 ∧ b≠7) : + (experiment n f as).All (fun bs => ∀ b∈bs,b≠6 ∧ b≠7) := by + unfold experiment + rw [Experiment.all_map] + exact (Experiment.all_true _).mono (fun bs _ => hout bs) + +/-- Every run halts within the physical execution bound. Its output law +is exactly the law obtained by feeding an independent uniform word to f. -/ +theorem machine_law (N : TreeTyped.Realizer n) (F : TreeTyped.Realizer f) + (as : List Symbol) (ha : ∀ a∈as,a≠0) + (hout : ∀ bs,∀ b∈f (as,bs),b≠6 ∧ b≠7) + (t : ℕ) (ht : machineTime N F as≤t) : + (∀ bits : Bits t,(run (machine N F) as bits).state=none) ∧ + ∀ g : Tape Symbol → ℚ, + average (fun bits : Bits t => g (run (machine N F) as bits).tape)= + average (fun bits : Bits (n as) => g (Tape.mk₁ (f (as,List.ofFn bits)))) := by + have hr := LiteralProgram.wrap_realizes (realizer N F) as ha (output_alphabet as hout) + constructor + · intro bits + exact (hr.run_all (fun _ => True) (Experiment.all_true _) t ht bits).1 + · intro g + have hm := hr.run_mean g t ht + rw [Experiment.mean_map] at hm + exact hm.trans (experiment_mean n f as (fun bs => g (Tape.mk₁ bs))) + +/-- Packing, coin reads, deterministic execution and public output all +have a polynomial bound in encoded input size plus the declared word. -/ +theorem machineTime_polynomial {N : TreeTyped.Realizer n} {F : TreeTyped.Realizer f} + (hN : TreeTyped.PolynomialTime N) (hF : TreeTyped.PolynomialTime F) : + ∃ q : Polynomial ℕ,∀ as,machineTime N F as≤q.eval (wordMeasure n as) := by + obtain ⟨p,hp⟩ := work_realizer hN hF + let G := realizer N F + let a := OnlineStack.accesses G.program.code + let o := OnlineStack.overhead G.program.code + let pk : Polynomial ℕ := (1+LiteralProgram.budgetPolynomial 1 (18*LiteralPacked.width) X 0)* + C (MachineCost.programCost LiteralPacked.packCode) + let out : Polynomial ℕ := C (MachineCost.programCost (LiteralTape.eraseCode LiteralPacked.header.length))+ + (1+LiteralProgram.budgetPolynomial (18*LiteralPacked.width) 1 p 0)* + C (MachineCost.programCost LiteralPacked.unpackCode) + let fac : Polynomial ℕ := C o*(1+2*C a*(X+p*C a+1))+1 + refine ⟨pk+p*fac+out,fun as => ?_⟩ + let M := wordMeasure n as + have hw : weight as≤M := Nat.le_add_right _ _ + have hn : as.length≤M := (list_length_le_weight as).trans hw + have hc : G.cost as≤p.eval M := (Nat.le_add_right _ _).trans (hp as) + have hout : (experiment n f as).worst weight≤p.eval M := + (Nat.le_add_left _ _).trans (hp as) + have hl : (experiment n f as).worst List.length≤p.eval M := + Experiment.worst_le _ _ _ ((Experiment.all_worst _ weight).mono + (fun bs hbs => (list_length_le_weight bs).trans (hbs.trans hout))) + have hf : OnlineStack.Executes.factor G.program.code (weight as) (G.cost as)≤fac.eval M := by + have he : fac.eval M=OnlineStack.Executes.factor G.program.code M (p.eval M) := by + simp only [fac,eval_add,eval_mul,eval_C,eval_ofNat,eval_X,eval_one, + OnlineStack.Executes.factor,a,o] + rw [he] + exact OnlineStack.Executes.factor_mono _ _ _ _ hw hc + have hpk : pk.eval M=LiteralProgram.packTime M := by + simp only [pk,eval_mul,eval_add,eval_one,eval_C,LiteralProgram.eval_budgetPolynomial, + eval_X,eval_zero,LiteralProgram.packTime] + have hpout : out.eval M=LiteralProgram.postTime (p.eval M) := by + simp only [out,eval_add,eval_mul,eval_one,eval_C,LiteralProgram.eval_budgetPolynomial, + eval_zero,LiteralProgram.postTime] + change LiteralProgram.wrapTime G as≤(pk+p*fac+out).eval M + simp only [eval_add,eval_mul,hpk,hpout] + unfold LiteralProgram.wrapTime OnlineTree.physicalCost + exact Nat.add_le_add + (Nat.add_le_add (LiteralProgram.packTime_mono hn) (Nat.mul_le_mul hc hf)) + (LiteralProgram.postTime_mono hl) + +end ContingencyTables.FiniteWordExecution + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordOutput.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordOutput.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd80db6b14041f429acde4857fe6f80d9cdddccb --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordOutput.lean @@ -0,0 +1,46 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordMachine + +namespace OAI + +/-! # Every-path output properties of the finite-word machine -/ + +namespace ContingencyTables.FiniteWordExecution +open MatchingFPRAS MatchingFPRAS.PhysicalStream Turing +open scoped BigOperators Classical + +variable {n : List Symbol → ℕ} {f : List Symbol×List Bool → List Symbol} + +/-- A property verified for every finite source word holds on every actual +machine tape once the fixed execution bound has elapsed. -/ +theorem machine_all (N : TreeTyped.Realizer n) (F : TreeTyped.Realizer f) + (as : List Symbol) (ha : ∀ a∈as,a≠0) + (hout : ∀ bs,∀ a∈f (as,bs),a≠6 ∧ a≠7) + (P : Tape Symbol → Prop) + (hf : ∀ bits : Bits (n as),P (Tape.mk₁ (f (as,List.ofFn bits)))) + (t : ℕ) (ht : machineTime N F as≤t) : + ∀ bits : Bits t,P (run (machine N F) as bits).tape := by + let g : Tape Symbol → ℚ := fun tape => if P tape then 0 else 1 + have hm := (machine_law N F as ha hout t ht).2 g + have hz : average (fun bits : Bits t => g (run (machine N F) as bits).tape)=0 := by + rw [hm] + have he : (fun bits : Bits (n as) => g (Tape.mk₁ (f (as,List.ofFn bits))))= + (fun _ => (0:ℚ)) := by + funext bits + exact ite_eq_left (hf bits) + rw [he,average_const] + have hpow : (2:ℚ)^t≠0 := pow_ne_zero _ (by norm_num) + have hs : ∑ bits : Bits t,g (run (machine N F) as bits).tape=0 := by + have h := congrArg (fun a : ℚ => a*(2:ℚ)^t) hz + simpa only [average,div_mul_cancel₀ _ hpow,zero_mul] using h + have hnonneg (bits : Bits t) : 0≤g (run (machine N F) as bits).tape := by + dsimp only [g] + split_ifs <;> norm_num + intro bits + have hb := (Finset.sum_eq_zero_iff_of_nonneg (fun b _ => hnonneg b)).mp hs bits (Finset.mem_univ bits) + by_contra hn + have hbad : (1:ℚ)=0 := by simpa only [g,ite_eq_right hn] using hb + norm_num at hbad + +end ContingencyTables.FiniteWordExecution + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordPadding.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordPadding.lean new file mode 100644 index 0000000000000000000000000000000000000000..268d94e52ff429a4ba6aed28afceb4a38abfdb93 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordPadding.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts + +namespace OAI + +/-! # Reserving a common word length for adaptive bounded draws -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture FairBits + +noncomputable section + +variable {A B : Type*} [Fintype A] [Fintype B] [DecidableEq A] + +lemma mapLaw_product_fst (p : RationalLaw A) (q : RationalLaw B) : + mapLaw (productLaw p q) Prod.fst=p := by + apply RationalLaw.ext + funext x + simp only [mapLaw, productLaw, Fintype.sum_prod_type] + change (∑ a,∑ b,if a=x then p.mass a*q.mass b else 0)=p.mass x + have hs (a : A) : (∑ b,if a=x then p.mass a*q.mass b else 0)=if a=x then p.mass a else 0 := by + by_cases ha : a=x + · simp only [ha,ite_true,←Finset.mul_sum,q.total,mul_one] + · simp only [ha,ite_false,Finset.sum_const_zero] + simp_rw [hs] + simp + +def prefixWord {k N : ℕ} (hk : k ≤ N) (bits : Fin N → Bool) : Fin k → Bool := + fun i => bits (Fin.castLE hk i) + +def paddingWordEquiv {k N : ℕ} (hk : k ≤ N) : + (Fin N → Bool) ≃ ((Fin k → Bool) × (Fin (N-k) → Bool)) := + (Equiv.arrowCongr (finCongr (Nat.add_sub_of_le hk)).symm (Equiv.refl Bool)).trans + (splitWordEquiv k (N-k)) + +lemma paddingWordEquiv_fst {k N : ℕ} (hk : k ≤ N) (bits : Fin N → Bool) : + (paddingWordEquiv hk bits).1=prefixWord hk bits := by + funext i + change bits _=bits _ + apply congrArg bits + apply Fin.ext + rfl + +/-- Taking the needed prefix of a larger uniform word preserves the exact +law, so unused bits can be reserved even after the current state is known. -/ +theorem prefixWord_uniform {k N : ℕ} (hk : k ≤ N) : + mapLaw (uniformLaw (α := Fin N → Bool)) (prefixWord hk)=uniformLaw (α := Fin k → Bool) := by + have hf : prefixWord hk=fun bits => (paddingWordEquiv hk bits).1 := by + funext bits + exact (paddingWordEquiv_fst hk bits).symm + rw [hf,←map_equiv (paddingWordEquiv hk),uniform_equiv,←uniform_product,mapLaw_product_fst] + +variable {Y : Type*} [Fintype Y] [DecidableEq Y] + +/-- An arbitrary finite draw keeps its law when padded to the common +bound; this applies separately at every state of an adaptive walk. -/ +theorem padded_draw_law {k N : ℕ} (hk : k ≤ N) (draw : (Fin k → Bool) → Y) : + mapLaw (uniformLaw (α := Fin N → Bool)) (fun bits => draw (prefixWord hk bits))= + mapLaw (uniformLaw (α := Fin k → Bool)) draw := by + rw [←mapLaw_comp,prefixWord_uniform] + +end +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordRationalLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordRationalLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6107aaf5e571e0e190e7527665414310fc482d2 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordRationalLaw.lean @@ -0,0 +1,66 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordOutput + +namespace OAI + +/-! # Transferring rational-output events to the fixed public machine -/ + +namespace ContingencyTables.FiniteWordExecution +open MatchingFPRAS MatchingFPRAS.PhysicalStream Turing +open scoped BigOperators Classical +noncomputable section +variable {n : List Symbol → ℕ} {f : List Symbol×List Bool → List Symbol} + +/-- An event verified on the rational value survives literal output and +finite-word compilation, without requiring a decoding oracle. -/ +theorem machine_rational_event (N : TreeTyped.Realizer n) (F : TreeTyped.Realizer f) + (as : List Symbol) (ha : ∀ a∈as,a≠0) + (hout : ∀ bs,∀ a∈f (as,bs),a≠6 ∧ a≠7) + (draw : Bits (n as) → ℚ) (hf : ∀ bits,f (as,List.ofFn bits)=encodeRat (draw bits)) + (P : ℚ → Prop) (t : ℕ) (ht : machineTime N F as≤t) : + average (fun bits : Bits (n as) => if P (draw bits) then 1 else 0) ≤ + ((Finset.univ.filter (fun bits : Bits t => + ∃ q : ℚ,Outputs (machine N F) as bits q ∧ P q)).card:ℚ)/(2:ℚ)^t := by + let g : Tape Symbol → ℚ := fun tape => + if ∃ q : ℚ,tape.right₀=ListBlank.mk (encodeRat q) ∧ P q then 1 else 0 + obtain ⟨hh,hm⟩ := machine_law N F as ha hout t ht + have hsource : average (fun bits : Bits (n as) => if P (draw bits) then 1 else 0) ≤ + average (fun bits : Bits (n as) => g (Tape.mk₁ (f (as,List.ofFn bits)))) := by + unfold average + apply div_le_div_of_nonneg_right _ (by positivity) + apply Finset.sum_le_sum + intro bits _ + by_cases hp : P (draw bits) + · have hg : ∃ q : ℚ,(Tape.mk₁ (f (as,List.ofFn bits))).right₀= + ListBlank.mk (encodeRat q) ∧ P q := by + refine ⟨draw bits,?_,hp⟩ + simp only [hf,Tape.mk₁,Tape.mk₂,Tape.mk'_right₀] + simp only [hp,ite_true,g,hg] + exact le_rfl + · simp only [hp,ite_false] + dsimp only [g] + split_ifs <;> norm_num + rw [←hm g] at hsource + simpa only [average,g,Outputs,hh,true_and,Finset.sum_boole] using hsource + +/-- All finite source words have a rational output satisfying P, so the +compiled machine has that property on every random tape. -/ +theorem machine_rational_all (N : TreeTyped.Realizer n) (F : TreeTyped.Realizer f) + (as : List Symbol) (ha : ∀ a∈as,a≠0) + (hout : ∀ bs,∀ a∈f (as,bs),a≠6 ∧ a≠7) + (draw : Bits (n as) → ℚ) (hf : ∀ bits,f (as,List.ofFn bits)=encodeRat (draw bits)) + (P : ℚ → Prop) (hP : ∀ bits,P (draw bits)) + (t : ℕ) (ht : machineTime N F as≤t) : + ∀ bits : Bits t,∃ q : ℚ,Outputs (machine N F) as bits q ∧ P q := by + have hp := machine_all N F as ha hout (fun tape => + ∃ q : ℚ,tape.right₀=ListBlank.mk (encodeRat q) ∧ P q) (fun bits => by + refine ⟨draw bits,?_,hP bits⟩ + simp only [hf,Tape.mk₁,Tape.mk₂,Tape.mk'_right₀]) t ht + have hh := (machine_law N F as ha hout t ht).1 + intro bits + obtain ⟨q,hq,hPq⟩ := hp bits + exact ⟨q,⟨hh bits,hq⟩,hPq⟩ + +end +end ContingencyTables.FiniteWordExecution + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordRejection.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordRejection.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfe6f4e82423e53e8a4e6405c2d3a821a902deff --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordRejection.lean @@ -0,0 +1,77 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts +import OAI.Combinatorics.ContingencyTables.Transport.RejectionLaw + +namespace OAI + +/-! # Repeated rejection implemented by one finite independent Boolean array -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture FairBits + +noncomputable section + +theorem retryLaw_map {A B C : Type*} [Fintype A] [Fintype B] [Fintype C] + [DecidableEq B] [DecidableEq C] + (p : RationalLaw A) (draw : A → B) (f : B → Option C) (fallback : C) (n : ℕ) : + retryLaw (mapLaw p draw) f fallback n = retryLaw p (fun x => f (draw x)) fallback n := by + have hm := mapLaw_comp p draw f + have hg : successMass (mapLaw p draw) f = successMass p (fun x => f (draw x)) := by + funext z + exact congrArg (fun q : RationalLaw (Option C) => q.mass (some z)) hm + have hf : failureMass (mapLaw p draw) f = failureMass p (fun x => f (draw x)) := + congrArg (fun q : RationalLaw (Option C) => q.mass none) hm + apply RationalLaw.ext + funext z + simp only [retryLaw_mass, hg, hf] + +variable {α : Type*} [Fintype α] [DecidableEq α] + +def wordRetry {k : ℕ} (f : (Fin k → Bool) → Option α) (fallback : α) : + (n : ℕ) → (Fin n → Fin k → Bool) → α + | 0, _ => fallback + | n + 1, bits => (f (bits 0)).getD (wordRetry f fallback n (Fin.tail bits)) + +def wordRetryLaw {k : ℕ} (f : (Fin k → Bool) → Option α) (fallback : α) (n : ℕ) : RationalLaw α := + mapLaw (uniformLaw (α := Fin n → Fin k → Bool)) (wordRetry f fallback n) + +/-- The first successful output is computed from an actual fixed Boolean +array; unused suffix words do not change its distribution. -/ +theorem wordRetryLaw_eq {k : ℕ} (f : (Fin k → Bool) → Option α) (fallback : α) (n : ℕ) : + wordRetryLaw f fallback n = retryLaw (uniformLaw (α := Fin k → Bool)) f fallback n := by + induction n with + | zero => + apply RationalLaw.ext + funext z + simp [wordRetryLaw, wordRetry, retryLaw, pointLaw, mapLaw, uniformLaw, uniformMass, eq_comm] + | succ n ih => + let E : ((Fin k → Bool) × (Fin n → Fin k → Bool)) ≃ (Fin (n + 1) → Fin k → Bool) := + Fin.consEquiv (fun _ => Fin k → Bool) + have hc : (fun z => wordRetry f fallback (n + 1) (E z)) = + fun z => (f z.1).getD (wordRetry f fallback n z.2) := by + funext z + rcases z with ⟨head, tail⟩ + change (f ((Fin.cons (α := fun _ : Fin (n+1) => Fin k → Bool) head tail) 0)).getD + (wordRetry f fallback n (Fin.tail (Fin.cons (α := fun _ : Fin (n+1) => Fin k → Bool) head tail))) = _ + simp only [Fin.cons_zero, Fin.tail_cons] + unfold wordRetryLaw + rw [← uniform_equiv E, map_equiv E, hc, ← uniform_product] + have hcomp := mapLaw_comp + (productLaw (uniformLaw (α := Fin k → Bool)) (uniformLaw (α := Fin n → Fin k → Bool))) + (fun z => (id z.1, wordRetry f fallback n z.2)) (fun z => (f z.1).getD z.2) + dsimp only [id_eq, Prod.fst, Prod.snd] at hcomp + rw [← hcomp] + have hp := mapLaw_product (uniformLaw (α := Fin k → Bool)) + (uniformLaw (α := Fin n → Fin k → Bool)) id (wordRetry f fallback n) + dsimp only [id_eq] at hp + rw [hp, mapLaw_id] + change retryStep (uniformLaw (α := Fin k → Bool)) f (wordRetryLaw f fallback n) = _ + rw [ih] + rfl + +end + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordSlices.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordSlices.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fdb2a81764a9be3db36f1cb412efa2d1f4e5602 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordSlices.lean @@ -0,0 +1,74 @@ +import OAI.Combinatorics.ContingencyTables.Dense.DenseMetropolisSemantics + +namespace OAI + +/-! # Exact bounded list slices of a finite Boolean word -/ + +namespace ContingencyTables.FiniteWordSlices + +open FairBits + +lemma slice_ofFn {N : ℕ} (bits : Fin N → Bool) (start count : ℕ) + (h : start+count ≤ N) : + ((List.ofFn bits).drop start).take count= + List.ofFn (fun i : Fin count => bits ⟨start+i.val,by omega⟩) := by + apply List.ext_getElem + · simp only [List.length_take,List.length_drop,List.length_ofFn] + omega + · intro i hi hj + simp only [List.getElem_take,List.getElem_drop,List.getElem_ofFn] + +abbrev Fields (p q k : ℕ) := + (Fin 1 → Bool) × ((Fin p → Bool) × (((Fin q → Bool) × (Fin q → Bool)) × (Fin k → Bool))) + +def split (p q k : ℕ) : (Fin (1+(p+((q+q)+k))) → Bool) ≃ Fields p q k := + (splitWordEquiv _ _).trans (Equiv.prodCongr (Equiv.refl _) + ((splitWordEquiv _ _).trans (Equiv.prodCongr (Equiv.refl _) + ((splitWordEquiv _ _).trans (Equiv.prodCongr (splitWordEquiv _ _) (Equiv.refl _)))))) + +lemma first_slice (p q k : ℕ) (bits : Fin (1+(p+((q+q)+k))) → Bool) : + ((List.ofFn bits).drop 1).take p=List.ofFn (split p q k bits).2.1 := by + rw [slice_ofFn bits 1 p (by omega)] + apply congrArg List.ofFn + funext i + rfl + +lemma current_slice (p q k : ℕ) (bits : Fin (1+(p+((q+q)+k))) → Bool) : + ((List.ofFn bits).drop (1+p)).take q=List.ofFn (split p q k bits).2.2.1.1 := by + rw [slice_ofFn bits (1+p) q (by omega)] + apply congrArg List.ofFn + funext i + apply congrArg bits + apply Fin.ext + change 1+p+i.val=1+(p+i.val) + omega + +lemma target_slice (p q k : ℕ) (bits : Fin (1+(p+((q+q)+k))) → Bool) : + ((List.ofFn bits).drop (1+p+q)).take q=List.ofFn (split p q k bits).2.2.1.2 := by + rw [slice_ofFn bits (1+p+q) q (by omega)] + apply congrArg List.ofFn + funext i + apply congrArg bits + apply Fin.ext + change 1+p+q+i.val=1+(p+(q+i.val)) + omega + +lemma coin_slice (p q k : ℕ) (bits : Fin (1+(p+((q+q)+k))) → Bool) : + ((List.ofFn bits).drop (1+p+q+q)).take k=List.ofFn (split p q k bits).2.2.2 := by + rw [slice_ofFn bits (1+p+q+q) k (by omega)] + apply congrArg List.ofFn + funext i + apply congrArg bits + apply Fin.ext + change 1+p+q+q+i.val=1+(p+((q+q)+i.val)) + omega + +lemma holding_bit (p q k : ℕ) (bits : Fin (1+(p+((q+q)+k))) → Bool) : + (List.ofFn bits).getD 0 false=(split p q k bits).1 0 := by + simp only [List.getD_eq_getElem?_getD,List.getElem?_ofFn] + simp only [show 0 < 1+(p+((q+q)+k)) by omega,dite_true,Option.getD_some] + rfl + +end ContingencyTables.FiniteWordSlices + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordTableLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordTableLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..83190ac3d37ad8e38034e9326adbc6d8edde6ca6 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordTableLaw.lean @@ -0,0 +1,59 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordOutput +import OAI.Combinatorics.ContingencyTables.Machines.MatrixEncoding +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits + +namespace OAI + +/-! # Identifying public table probabilities with finite-word masses -/ + +namespace ContingencyTables.FiniteWordExecution +open MatchingFPRAS MatchingFPRAS.PhysicalStream Turing Algorithms +open ResidualMixture FirstSuccess +open scoped BigOperators Classical + +variable {n : List MatchingFPRAS.Symbol → ℕ} {f : List MatchingFPRAS.Symbol×List Bool → List MatchingFPRAS.Symbol} + +/-- Exact finite-word compilation preserves each table's probability, +including the quotient of the public output tape by trailing blanks. -/ +theorem machine_tableMass (N : TreeTyped.Realizer n) (F : TreeTyped.Realizer f) + (as : List MatchingFPRAS.Symbol) (ha : ∀ a∈as,a≠0) + (hout : ∀ bs,∀ a∈f (as,bs),a≠6 ∧ a≠7) + {m j L : ℕ} {r : Fin m → ℕ} {c : Fin j → ℕ} + (hL : n as=L) (draw : Bits L → Table r c) + (hf : ∀ bits,f (as,List.ofFn bits)=encodeMatrix (draw bits).val) + (t : ℕ) (ht : machineTime N F as≤t) (X : Table r c) : + tableMass (machine N F) as t X.val= + ((mapLaw (uniformLaw (α := Bits L)) draw).mass X:ℝ) := by + let g : Tape MatchingFPRAS.Symbol → ℚ := fun tape => if tape.right₀=ListBlank.mk (encodeMatrix X.val) then 1 else 0 + obtain ⟨hhalt,hm⟩ := machine_law N F as ha hout t ht + have he := hm g + rw [hL] at he + have hl : average (fun bits : Bits t => g (run (machine N F) as bits).tape)= + ((Finset.univ.filter (fun bits : Bits t => OutputsTable (machine N F) as bits X.val)).card:ℚ)/(2:ℚ)^t := by + simp only [average,g,OutputsTable,hhalt,true_and,Finset.sum_boole] + have hg (bits : Bits L) : g (Tape.mk₁ (f (as,List.ofFn bits)))= + if draw bits=X then (1:ℚ) else 0 := by + simp only [g,hf,Tape.mk₁,Tape.mk₂,Tape.mk'_right₀] + have hi : ListBlank.mk (encodeMatrix (draw bits).val)=ListBlank.mk (encodeMatrix X.val) ↔ + draw bits=X := by + constructor + · intro h + exact Subtype.ext (blankMatrix_injective _ _ h) + · rintro h + rw [h] + rw [hi] + have hr : average (fun bits : Bits L => g (Tape.mk₁ (f (as,List.ofFn bits))))= + (mapLaw (uniformLaw (α := Bits L)) draw).mass X := by + simp_rw [hg] + simp only [average,mapLaw,uniformLaw,uniformMass,Fintype.card_fun,Fintype.card_bool, + Fintype.card_fin,Finset.sum_div] + apply Finset.sum_congr rfl + intro bits _ + split_ifs <;> simp + rw [hl,hr] at he + have heR := congrArg (fun z : ℚ => (z:ℝ)) he + simpa only [Rat.cast_div,Rat.cast_natCast,Rat.cast_pow,Rat.cast_ofNat,tableMass] using heR + +end ContingencyTables.FiniteWordExecution + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordWalk.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordWalk.lean new file mode 100644 index 0000000000000000000000000000000000000000..55f775a781c5c8d26601b7792506058b4485d740 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FiniteWordWalk.lean @@ -0,0 +1,94 @@ +import OAI.Combinatorics.ContingencyTables.Transport.RationalWalks +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits + +namespace OAI + +/-! # Exact laws of a walk driven by independent fixed-length Boolean words -/ + +namespace ContingencyTables.FirstSuccess + +open scoped BigOperators Classical +open ResidualMixture + +noncomputable section + +variable {α : Type*} [Fintype α] [DecidableEq α] + +def uniformMapMass {A : Type*} [Fintype A] (f : A → α) (y : α) : ℚ := + (∑ x, if f x = y then (1 : ℚ) else 0) / Fintype.card A + +omit [Fintype α] in +theorem uniformMapMass_equiv {A B : Type*} [Fintype A] [Fintype B] + (e : A ≃ B) (f : B → α) (y : α) : uniformMapMass (f ∘ e) y = uniformMapMass f y := by + unfold uniformMapMass + rw [Fintype.card_congr e] + congr 1 + exact e.sum_comp (fun x => if f x = y then (1 : ℚ) else 0) + +theorem finite_fiber_sum {A : Type*} [Fintype A] (f : A → α) (g : α → ℚ) : + (∑ y, (∑ x, if f x = y then (1 : ℚ) else 0) * g y) = ∑ x, g (f x) := by + simp_rw [Finset.sum_mul, ite_mul, one_mul, zero_mul] + rw [Finset.sum_comm] + simp only [Finset.sum_ite_eq, Finset.mem_univ, ite_true] + +theorem uniformMapMass_prod {A B : Type*} [Fintype A] [Fintype B] + (f : A → α) (g : α → B → α) (y : α) : + uniformMapMass (fun z : A × B => g (f z.1) z.2) y = + ∑ s, uniformMapMass f s * uniformMapMass (g s) y := by + unfold uniformMapMass + simp only [Fintype.card_prod, Nat.cast_mul, div_mul_div_comm, ← Finset.sum_div, + Fintype.sum_prod_type] + rw [finite_fiber_sum] + +theorem uniform_map_mass {A : Type*} [Fintype A] [Nonempty A] (f : A → α) (y : α) : + (mapLaw (uniformLaw (α := A)) f).mass y = uniformMapMass f y := by + change (∑ x, if f x = y then 1 / (Fintype.card A : ℚ) else 0) = + (∑ x, if f x = y then (1 : ℚ) else 0) / Fintype.card A + rw [Finset.sum_div] + simp only [ite_div, zero_div] + +def wordWalk {k : ℕ} (step : α → (Fin k → Bool) → α) (a : α) : + (n : ℕ) → (Fin n → Fin k → Bool) → α + | 0, _ => a + | n + 1, bits => step (wordWalk step a n (Fin.init bits)) (bits (Fin.last n)) + +def wordWalkLaw {k : ℕ} (step : α → (Fin k → Bool) → α) (a : α) (n : ℕ) : RationalLaw α := + mapLaw (uniformLaw (α := Fin n → Fin k → Bool)) (wordWalk step a n) + +/-- A uniform finite Boolean array realizes the independent transition-law +composition, with no random-length source or conditioning. -/ +theorem wordWalkLaw_eq {k : ℕ} (step : α → (Fin k → Bool) → α) (a : α) (n : ℕ) : + wordWalkLaw step a n = walkLaw (fun s => mapLaw (uniformLaw (α := Fin k → Bool)) (step s)) a n := by + induction n with + | zero => + apply RationalLaw.ext + funext b + simp [wordWalkLaw, wordWalk, walkLaw, pointLaw, mapLaw, uniformLaw, uniformMass, eq_comm] + | succ n ih => + let E : ((Fin n → Fin k → Bool) × (Fin k → Bool)) ≃ (Fin (n + 1) → Fin k → Bool) := + (Equiv.prodComm _ _).trans (Fin.snocEquiv (fun _ => Fin k → Bool)) + have hc : (wordWalk step a (n + 1)) ∘ E = + fun ab => step (wordWalk step a n ab.1) ab.2 := by + funext ab + rcases ab with ⟨pref, last⟩ + change step (wordWalk step a n (Fin.init + (Fin.snoc (α := fun _ : Fin (n + 1) => Fin k → Bool) pref last))) + ((Fin.snoc (α := fun _ : Fin (n + 1) => Fin k → Bool) pref last) (Fin.last n)) = _ + simp only [Fin.init_snoc, Fin.snoc_last] + apply RationalLaw.ext + funext b + change (wordWalkLaw step a (n + 1)).mass b = + (bindLaw (walkLaw (fun s => mapLaw (uniformLaw (α := Fin k → Bool)) (step s)) a n) + (fun s => mapLaw (uniformLaw (α := Fin k → Bool)) (step s))).mass b + rw [← ih] + simp only [wordWalkLaw, bindLaw, uniform_map_mass] + have he := uniformMapMass_equiv E (wordWalk step a (n + 1)) b + rw [hc] at he + rw [← he] + exact uniformMapMass_prod (wordWalk step a n) step b + +end + +end ContingencyTables.FirstSuccess + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FirstSuccessProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FirstSuccessProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b2291e994e5842c4131017110f0e534901196d1 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FirstSuccessProgram.lean @@ -0,0 +1,104 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ListWordProgram +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordRejection + +namespace OAI + +/-! # Polynomial first-success selection for a supplied list of trial words -/ + +namespace ContingencyTables.FirstSuccessProgram +open MatchingFPRAS.TreeTyped + +variable {A B W : Type} [Codec A] [Codec B] [Codec W] [Inhabited B] + +def firstSome : List (Option B) → Option B + | [] => none + | none::xs => firstSome xs + | Option.some x::_ => Option.some x + +def isSomeRealizer : Realizer (Option.isSome : Option B → Bool) := + (composition (pair (constant false) identity) + (optionCases (constant false) (constant true))).congr (by intro o; cases o <;> rfl) + +theorem polynomial_isSome : PolynomialTime (isSomeRealizer (B := B)) := by + unfold isSomeRealizer + apply polynomial_congr + exact polynomial_composition (polynomial_pair (polynomial_constant false) polynomial_identity) + (polynomial_optionCases (polynomial_constant false) (polynomial_constant true)) + +omit [Codec B] [Inhabited B] in +lemma firstSome_filter (xs : List (Option B)) : + (xs.filter Option.isSome).headD none=firstSome xs := by + induction xs with + | nil => rfl + | cons x xs ih => + cases x with + | none => exact ih + | some b => rfl + +def firstSomeRealizer : Realizer (firstSome (B := B)) := + (composition (filter isSomeRealizer) (head none)).congr firstSome_filter + +theorem polynomial_firstSome : PolynomialTime (firstSomeRealizer (B := B)) := + polynomial_congr _ (polynomial_composition (polynomial_filter polynomial_isSome) (polynomial_head none)) + +def defaultRealizer : Realizer (fun z : B×Option B => z.2.getD z.1) := + (optionCases identity second).recode id (fun z : B×Option B => z.2.getD z.1) + (fun _ => rfl) (by rintro ⟨b,o⟩; cases o <;> rfl) + +theorem polynomial_default : PolynomialTime (defaultRealizer (B := B)) := by + unfold defaultRealizer + apply polynomial_recode + exact polynomial_optionCases polynomial_identity polynomial_second + +def retry (f : A×W → Option B) (z : (A×B)×List W) : B := + (firstSome (z.2.map (fun w => f (z.1.1,w)))).getD z.1.2 + +def retryRealizer {f : A×W → Option B} (F : Realizer f) : Realizer (retry f) := by + let inputs : Realizer (fun z : (A×B)×List W => (z.1.1,z.2)) := + pair (composition first first) second + let results := composition inputs (mapWith F) + exact composition (pair (composition first second) (composition results firstSomeRealizer)) defaultRealizer + +theorem polynomial_retry {f : A×W → Option B} {F : Realizer f} (hF : PolynomialTime F) : + PolynomialTime (retryRealizer F) := by + unfold retryRealizer + exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_mapWith hF)) polynomial_firstSome)) polynomial_default + +noncomputable section +open scoped Classical + +omit [Codec A] [Codec B] [Inhabited B] in +theorem retry_ofFn {k n : ℕ} (f : A×List Bool → Option B) + (a : A) (fallback : B) (bits : Fin n → Fin k → Bool) : + retry f ((a,fallback),List.ofFn (fun i => List.ofFn (bits i)))= + FirstSuccess.wordRetry (fun word => f (a,List.ofFn word)) fallback n bits := by + induction n with + | zero => rfl + | succ n ih => + simp only [retry,List.ofFn_succ,List.map_cons,FirstSuccess.wordRetry] + cases h : f (a,List.ofFn (bits 0)) with + | none => + simp only [firstSome,Option.getD_none] + exact ih (Fin.tail bits) + | some b => simp only [firstSome,Option.getD_some] + +theorem wordRetry_map {α β : Type*} {k : ℕ} (f : (Fin k → Bool) → Option α) + (g : α → β) (fallback : α) (n : ℕ) (bits : Fin n → Fin k → Bool) : + FirstSuccess.wordRetry (fun word => (f word).map g) (g fallback) n bits= + g (FirstSuccess.wordRetry f fallback n bits) := by + induction n with + | zero => rfl + | succ n ih => + simp only [FirstSuccess.wordRetry] + cases f (bits 0) with + | none => simpa only [Option.map_none,Option.getD_none] using ih (Fin.tail bits) + | some x => rfl + +end +end ContingencyTables.FirstSuccessProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityBits.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..17e95d56d551dd3b143b87fd0520a5cdbed42c19 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityBits.lean @@ -0,0 +1,153 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityLaw +import OAI.Combinatorics.ContingencyTables.Transport.FiniteRationalThreshold +import OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments +import OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent +import OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts + +namespace OAI + +/-! # Bounded Boolean implementation of fixed-cardinality subset draws -/ + +namespace ContingencyTables.FixedCardinalityBits + +open CommonBasesFPRAS ResidualMixture FirstSuccess FairBits FixedCardinalityLaw +open scoped BigOperators Classical +noncomputable section + +def headDraw (B n k : ℕ) (bits : Fin B → Bool) : Bool := + decide (rationalThresholdAccept B (headProbability n k) bits) + +def roundedHeadLaw (B n k : ℕ) : RationalLaw Bool := + mapLaw (uniformLaw (α := Fin B → Bool)) (headDraw B n k) + +lemma roundedHead_true (B n k : ℕ) : + (roundedHeadLaw B n k).mass true=rationalThresholdMass B (headProbability n k) := by + have hword := FiniteLawMoments.word_expectation (headDraw B n k) + (fun b => if b then (1:ℝ) else 0) + have hfun : (fun bits : Fin B → Bool => if headDraw B n k bits then (1:ℝ) else 0)= + (fun bits => if rationalThresholdAccept B (headProbability n k) bits then (1:ℝ) else 0) := by + funext bits + simp [headDraw] + rw [hfun] at hword + have ht := rationalThreshold_expectation B (headProbability n k) + (headProbability_bounds n k).1 (headProbability_bounds n k).2 + have he := hword.symm.trans ht + have hc : ((roundedHeadLaw B n k).mass true:ℝ)= + (rationalThresholdMass B (headProbability n k):ℝ) := by + simpa [FiniteLawMoments.expectation,Fintype.sum_bool,roundedHeadLaw] using he + exact_mod_cast hc + +private lemma bool_variation (p q : RationalLaw Bool) : + variation p q=|p.mass true-q.mass true| := by + have hp := p.total + have hq := q.total + rw [Fintype.sum_bool] at hp hq + have hf : p.mass false-q.mass false= -(p.mass true-q.mass true) := by linarith + unfold variation + rw [Fintype.sum_bool,hf,abs_neg] + ring + +theorem roundedHead_error (B n k : ℕ) : + variation (roundedHeadLaw B n k) (headLaw n k)≤1/(2:ℚ)^B := by + rw [bool_variation,roundedHead_true] + change |rationalThresholdMass B (headProbability n k)-headProbability n k|≤_ + have he := rationalThreshold_error B (headProbability n k) (headProbability_bounds n k).1 + rw [abs_of_nonpos (sub_nonpos.mpr he.2.1)] + linarith [he.2.2] + +def roundedFixedLaw (B : ℕ) : (n k : ℕ) → RationalLaw (Fin n → Bool) + | 0, _ => pointLaw (fun i => Fin.elim0 i) + | n+1, k => consLaw (roundedHeadLaw B n k) + (fun b => roundedFixedLaw B n (remaining n k b)) + +theorem roundedFixed_error (B n k : ℕ) : + variation (roundedFixedLaw B n k) (fixedLaw n k)≤(n:ℚ)/(2:ℚ)^B := by + induction n generalizing k with + | zero => simp [roundedFixedLaw,fixedLaw,variation] + | succ n ih => + change variation (consLaw (roundedHeadLaw B n k) _) + (consLaw (headLaw n k) _)≤_ + have hh := consLaw_variation (roundedHeadLaw B n k) (headLaw n k) + (fun b => roundedFixedLaw B n (remaining n k b)) + (fun b => fixedLaw n (remaining n k b)) ((n:ℚ)/(2:ℚ)^B) + (fun b => ih (remaining n k b)) + calc + _ ≤ variation (roundedHeadLaw B n k) (headLaw n k)+(n:ℚ)/(2:ℚ)^B := hh + _ ≤ 1/(2:ℚ)^B+(n:ℚ)/(2:ℚ)^B := + _root_.add_le_add (roundedHead_error B n k) le_rfl + _ = _ := by push_cast; ring + +def draw (B : ℕ) : (n k : ℕ) → (Fin n → Fin B → Bool) → (Fin n → Bool) + | 0, _, _ => fun i => Fin.elim0 i + | n+1, k, words => + let b := headDraw B n k (words 0) + Fin.cons b (draw B n (remaining n k b) (Fin.tail words)) + +private theorem consWordLaw {W V : Type*} [Fintype W] [Fintype V] + [Nonempty W] [Nonempty V] {n : ℕ} (f : W → Bool) + (g : Bool → V → (Fin n → Bool)) : + mapLaw (productLaw (uniformLaw (α := W)) (uniformLaw (α := V))) + (fun ab => Fin.cons (f ab.1) (g (f ab.1) ab.2))= + consLaw (mapLaw (uniformLaw (α := W)) f) + (fun b => mapLaw (uniformLaw (α := V)) (g b)) := by + change mapLaw _ (fun ab : W×V => consEquiv n (⟨f ab.1,g (f ab.1) ab.2⟩ : + (_b : Bool) × (Fin n → Bool)))=_ + rw [mapLaw_equiv_output,mapLaw_dependent_product] + rfl + +theorem draw_law (B n k : ℕ) : + mapLaw (uniformLaw (α := Fin n → Fin B → Bool)) (draw B n k)= + roundedFixedLaw B n k := by + induction n generalizing k with + | zero => + apply RationalLaw.ext + funext v + simp [draw,roundedFixedLaw,mapLaw,uniformLaw,uniformMass,pointLaw,eq_comm] + | succ n ih => + let E := Fin.consEquiv (fun _ : Fin (n+1) => Fin B → Bool) + have he := map_equiv E + (uniformLaw (α := (Fin B → Bool)×(Fin n → Fin B → Bool))) (draw B (n+1) k) + rw [uniform_equiv,←uniform_product] at he + have hf : (fun ab => draw B (n+1) k (E ab))= + (fun ab => Fin.cons (headDraw B n k ab.1) + (draw B n (remaining n k (headDraw B n k ab.1)) ab.2)) := by + funext ab + simp only [draw,E,Fin.consEquiv,Equiv.coe_fn_mk,Fin.cons_zero,Fin.tail_cons] + rw [hf] at he + have hc := consWordLaw (headDraw B n k) + (fun b => draw B n (remaining n k b)) + have htail : + (fun b => mapLaw (uniformLaw (α := Fin n → Fin B → Bool)) + (draw B n (remaining n k b)))= + (fun b => roundedFixedLaw B n (remaining n k b)) := by + funext b + exact ih (remaining n k b) + rw [htail] at hc + exact he.trans hc + +def blockWords (n B : ℕ) : (Fin (n*B) → Bool) ≃ (Fin n → Fin B → Bool) := + (Equiv.arrowCongr finProdFinEquiv.symm (Equiv.refl Bool)).trans (Equiv.curry _ _ _) + +def bitDraw (B n k : ℕ) (bits : Fin (n*B) → Bool) : Fin n → Bool := + draw B n k (blockWords n B bits) + +theorem bitDraw_law (B n k : ℕ) : + mapLaw (uniformLaw (α := Fin (n*B) → Bool)) (bitDraw B n k)= + roundedFixedLaw B n k := by + have he := map_equiv (blockWords n B) + (uniformLaw (α := Fin (n*B) → Bool)) (draw B n k) + rw [uniform_equiv] at he + exact he.symm.trans (draw_law B n k) + +/-- Exactly nB fair bits implement the sequential subset draw with +total variation error at most n/2^B, uniformly in the requested size. -/ +theorem bitDraw_error (B n k : ℕ) : + variation (mapLaw (uniformLaw (α := Fin (n*B) → Bool)) (bitDraw B n k)) + (fixedLaw n k)≤(n:ℚ)/(2:ℚ)^B := by + rw [bitDraw_law] + exact roundedFixed_error B n k + +end +end ContingencyTables.FixedCardinalityBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityFlat.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityFlat.lean new file mode 100644 index 0000000000000000000000000000000000000000..7945e39d33d9de1be8c3170236112520f0c2d586 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityFlat.lean @@ -0,0 +1,97 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityFold +import OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityMixture +import OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram + +namespace OAI + +/-! # A flat-word program for a local initial subset + +The first B bits select the size. The remaining word is partitioned +into B-bit inclusion rows, so the input list bounds the number of loop +iterations even on malformed inputs. +-/ + +namespace ContingencyTables.FixedCardinalityProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms DensePrograms + +abbrev SubsetInput := (ℕ×ℕ)×List Bool + +def subsetCode (z : SubsetInput) : List Bool := + drawWords ((z.1.1,scaledWordValue (z.1.1+1,z.2.take z.1.2)), + wordChunks (z.1.2,z.2.drop z.1.2)) + +def subsetCodeRealizer : Realizer subsetCode := by + let N : Realizer (fun z : SubsetInput => z.1.1) := composition first first + let B : Realizer (fun z : SubsetInput => z.1.2) := composition first second + let head := composition (pair second B) takeFast + let size := composition (pair (composition N successor) head) scaledWordRealizer + let rest := composition (pair second B) dropFast + let chunks := composition (pair B rest) wordChunksRealizer + exact composition (pair (pair N size) chunks) drawWordsRealizer + +theorem polynomial_subsetCode : PolynomialTime subsetCodeRealizer := by + unfold subsetCodeRealizer + have hn : PolynomialTime (composition + (first (A := ℕ×ℕ) (B := List Bool)) first) := + polynomial_composition polynomial_first polynomial_first + have hb : PolynomialTime (composition + (first (A := ℕ×ℕ) (B := List Bool)) second) := + polynomial_composition polynomial_first polynomial_second + exact polynomial_composition (polynomial_pair + (polynomial_pair hn (polynomial_composition + (polynomial_pair (polynomial_composition hn polynomial_successor) + (polynomial_composition (polynomial_pair polynomial_second hb) polynomial_takeFast)) + polynomial_scaledWord)) + (polynomial_composition (polynomial_pair hb + (polynomial_composition (polynomial_pair polynomial_second hb) polynomial_dropFast)) + polynomial_wordChunks)) polynomial_drawWords + +noncomputable section +open FairBits FixedCardinalityBits FixedCardinalityMixture + +lemma splitWord_append (B L : ℕ) (bits : Fin (B+L) → Bool) : + List.ofFn bits=List.ofFn (splitWordEquiv B L bits).1++List.ofFn (splitWordEquiv B L bits).2 := by + have hfirst : (splitWordEquiv B L bits).1=fun i => bits (Fin.castAdd L i) := by + funext i + apply congrArg bits + apply Fin.ext + rfl + have hsecond : (splitWordEquiv B L bits).2=fun i => bits (Fin.natAdd B i) := by + funext i + apply congrArg bits + apply Fin.ext + rfl + rw [hfirst,hsecond] + exact List.ofFn_add (f := bits) + +lemma splitWord_take (B L : ℕ) (bits : Fin (B+L) → Bool) : + (List.ofFn bits).take B=List.ofFn (splitWordEquiv B L bits).1 := by + rw [splitWord_append] + simp + +lemma splitWord_drop (B L : ℕ) (bits : Fin (B+L) → Bool) : + (List.ofFn bits).drop B=List.ofFn (splitWordEquiv B L bits).2 := by + rw [splitWord_append] + simp + +private theorem subsetCode_ofFn_raw (B n : ℕ) (hB : 0 z.2.1.1) := + composition (composition second first) first + let K : Realizer (fun z : List Bool×DrawState => z.2.1.2) := + composition (composition second first) second + let B : Realizer (fun z : List Bool×DrawState => includeCode (z.2.1,z.1)) := + composition (pair (composition second first) first) includeRealizer + let R := composition (pair N (constant 1)) subtract + let T := choose B (composition (pair K (constant 1)) subtract) + (composition (pair K R) minimum) + exact pair (pair R T) (composition (pair B (composition second second)) listCons) + +theorem polynomial_advance : PolynomialTime advanceRealizer := by + unfold advanceRealizer + have hn : PolynomialTime (composition + (composition (second (A := List Bool) (B := DrawState)) first) first) := + polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_first + have hk : PolynomialTime (composition + (composition (second (A := List Bool) (B := DrawState)) first) second) := + polynomial_composition (polynomial_composition polynomial_second polynomial_first) polynomial_second + have hb : PolynomialTime (composition + (pair (composition (second (A := List Bool) (B := DrawState)) first) first) + includeRealizer) := polynomial_composition + (polynomial_pair (polynomial_composition polynomial_second polynomial_first) polynomial_first) + polynomial_include + have hr := polynomial_composition (polynomial_pair hn (polynomial_constant 1)) polynomial_subtract + exact polynomial_pair + (polynomial_pair hr (polynomial_choose hb + (polynomial_composition (polynomial_pair hk (polynomial_constant 1)) polynomial_subtract) + (polynomial_composition (polynomial_pair hk hr) polynomial_minimum))) + (polynomial_composition (polynomial_pair hb + (polynomial_composition polynomial_second polynomial_second)) polynomial_listCons) + +lemma advance_bounds (word : List Bool) (s : DrawState) : + (advance (word,s)).1.1 ≤ s.1.1 ∧ (advance (word,s)).1.2 ≤ s.1.2 ∧ + weight (advance (word,s)).2 ≤ weight s.2+4 := by + refine ⟨Nat.sub_le _ _,?_,?_⟩ + · change (if includeCode (s.1,word) then s.1.2-1 else min s.1.2 (s.1.1-1)) ≤ s.1.2 + split_ifs + · exact Nat.sub_le _ _ + · exact min_le_left _ _ + · change weight (includeCode (s.1,word)::s.2)≤_ + rw [weight_cons] + have h := weight_bool (includeCode (s.1,word)) + omega + +lemma fold_bounds (words : List (List Bool)) (s : DrawState) : + let out := words.foldl (fun s word => advance (word,s)) s + out.1.1 ≤ s.1.1 ∧ out.1.2 ≤ s.1.2 ∧ weight out.2 ≤ weight s.2+4*words.length := by + induction words generalizing s with + | nil => exact ⟨le_rfl,le_rfl,by simp⟩ + | cons w ws ih => + have hs := advance_bounds w s + have ht := ih (advance (w,s)) + refine ⟨ht.1.trans hs.1,ht.2.1.trans hs.2.1,?_⟩ + simp only [List.foldl_cons,List.length_cons] + omega + +def drawWords (z : (ℕ×ℕ)×List (List Bool)) : List Bool := + (z.2.foldl (fun s word => advance (word,s)) (z.1,[])).2.reverse + +def prepareWords (z : (ℕ×ℕ)×List (List Bool)) : List (List Bool)×DrawState := (z.2,(z.1,[])) + +def prepareWordsRealizer : Realizer prepareWords := pair second (pair first (constant [])) + +def runWords (z : (ℕ×ℕ)×List (List Bool)) : DrawState := + z.2.foldl (fun s word => advance (word,s)) (z.1,[]) + +def runWordsRealizer : Realizer runWords := composition prepareWordsRealizer (fold advanceRealizer) + +def outputRealizer : Realizer (fun s : DrawState => s.2.reverse) := composition second reverse + +def drawWordsRealizer : Realizer drawWords := + composition (f := runWords) (g := fun s : DrawState => s.2.reverse) + runWordsRealizer outputRealizer + +theorem polynomial_drawWords : PolynomialTime drawWordsRealizer := by + have hf : PolynomialTime (fold advanceRealizer) := by + apply polynomial_fold polynomial_advance (20*(X+1)) + intro words s pre post he + let S := weight (words,s) + let out := pre.foldl (fun s word => advance (word,s)) s + have hs : weight s≤S := weight_snd (words,s) + have hn : s.1.1.size≤S := + (size_le_weight _).trans ((weight_fst s.1).trans ((weight_fst s).trans hs)) + have hk : s.1.2.size≤S := + (size_le_weight _).trans ((weight_snd s.1).trans ((weight_fst s).trans hs)) + have hb : weight s.2≤S := (weight_snd s).trans hs + have hp : pre.length≤S := (list_length_le_weight pre).trans + ((weight_prefix he).trans (weight_fst (words,s))) + have ht := fold_bounds pre s + have hon : weight out.1.1≤4*out.1.1.size+1 := weight_nat_le out.1.1 + have hok : weight out.1.2≤4*out.1.2.size+1 := weight_nat_le out.1.2 + have hsn : out.1.1.size≤S := (Nat.size_le_size ht.1).trans hn + have hsk : out.1.2.size≤S := (Nat.size_le_size ht.2.1).trans hk + have hlist : weight out.2≤weight s.2+4*pre.length := ht.2.2 + have hnweight : weight out.1.1≤4*S+1 := hon.trans (by omega) + have hkweight : weight out.1.2≤4*S+1 := hok.trans (by omega) + have hlweight : weight out.2≤5*S := by omega + have hw : weight out=weight out.1.1+weight out.1.2+weight out.2+2 := by + change weight ((out.1.1,out.1.2),out.2)=_ + simp only [weight_prod] + omega + simp only [eval_mul,eval_ofNat,eval_add,eval_X,eval_one] + change weight out≤20*(S+1) + rw [hw] + omega + unfold drawWordsRealizer runWordsRealizer prepareWordsRealizer outputRealizer + exact polynomial_composition (polynomial_composition + (polynomial_pair polynomial_second (polynomial_pair polynomial_first (polynomial_constant []))) hf) + (polynomial_composition polynomial_second polynomial_reverse) + +def sampleWords (n k : ℕ) : List (List Bool) → List Bool + | [] => [] + | w::ws => + let b := includeCode ((n,k),w) + b::sampleWords (n-1) (if b then k-1 else min k (n-1)) ws + +lemma fold_output (words : List (List Bool)) (n k : ℕ) (acc : List Bool) : + (words.foldl (fun s word => advance (word,s)) ((n,k),acc)).2= + (sampleWords n k words).reverse++acc := by + induction words generalizing n k acc with + | nil => simp [sampleWords] + | cons w ws ih => + rw [List.foldl_cons] + change (ws.foldl (fun s word => advance (word,s)) + ((n-1,if includeCode ((n,k),w) then k-1 else min k (n-1)), + includeCode ((n,k),w)::acc)).2=_ + rw [ih] + simp only [sampleWords,List.reverse_cons,List.append_assoc,List.singleton_append] + +lemma drawWords_eq (n k : ℕ) (words : List (List Bool)) : + drawWords ((n,k),words)=sampleWords n k words := by + unfold drawWords + rw [fold_output] + simp + +noncomputable section + +theorem sampleWords_ofFn (B n k : ℕ) (words : Fin n → Fin B → Bool) : + sampleWords n k (List.ofFn (fun i => List.ofFn (words i)))= + List.ofFn (FixedCardinalityBits.draw B n k words) := by + induction n generalizing k with + | zero => simp [sampleWords,FixedCardinalityBits.draw] + | succ n ih => + rw [List.ofFn_succ] + simp only [sampleWords,includeCode_ofFn,Nat.add_sub_cancel] + rw [ih] + simp only [FixedCardinalityBits.draw,FixedCardinalityLaw.remaining,List.ofFn_succ, + Fin.cons_zero,Fin.cons_succ] + rfl + +/-- The polynomial list program has exactly the proved sequential +finite-word semantics, including empty populations. -/ +theorem drawWords_ofFn (B n k : ℕ) (words : Fin n → Fin B → Bool) : + drawWords ((n,k),List.ofFn (fun i => List.ofFn (words i)))= + List.ofFn (FixedCardinalityBits.draw B n k words) := by + rw [drawWords_eq] + exact sampleWords_ofFn B n k words + +end +end ContingencyTables.FixedCardinalityProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityLaw.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityLaw.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1cc791c3c48ef8230266abe3dc935d00d4d067e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityLaw.lean @@ -0,0 +1,150 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentApproximation +import OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits +import Mathlib.Data.Nat.Factorial.Basic +import Mathlib.Algebra.Order.Field.Basic + +namespace OAI + +/-! # Sequential uniform sampling of a subset of prescribed size + +The head is included with probability k/n; conditional on that choice, +the same rule is applied to the remaining coordinates. The exact mass +is k!(n-k)!/n!, matching the factorial factor in the companion lift. +-/ + +namespace ContingencyTables.FixedCardinalityLaw + +open ResidualMixture FirstSuccess +open scoped BigOperators Classical +noncomputable section + +def count {n : ℕ} (v : Fin n → Bool) : ℕ := ∑ i,if v i then 1 else 0 + +lemma count_le {n : ℕ} (v : Fin n → Bool) : count v≤n := by + calc + _ ≤ ∑ _i : Fin n,1 := Finset.sum_le_sum (fun i _ => by cases v i <;> simp) + _ = n := by simp + +lemma count_decompose {n : ℕ} (v : Fin (n+1) → Bool) : + count v=(if v 0 then 1 else 0)+count (Fin.tail v) := by + simp only [count,Fin.sum_univ_succ,Fin.tail] + rfl + +def consEquiv (n : ℕ) : ((_b : Bool) × (Fin n → Bool)) ≃ (Fin (n+1) → Bool) where + toFun x := Fin.cons x.1 x.2 + invFun v := ⟨v 0,Fin.tail v⟩ + left_inv x := by cases x; simp + right_inv v := Fin.cons_self_tail v + +def consLaw {n : ℕ} (p : RationalLaw Bool) (Q : Bool → RationalLaw (Fin n → Bool)) : + RationalLaw (Fin (n+1) → Bool) := + equivLaw (consEquiv n) (dependentJointLaw p Q) + +lemma consLaw_mass {n : ℕ} (p : RationalLaw Bool) (Q : Bool → RationalLaw (Fin n → Bool)) + (v : Fin (n+1) → Bool) : + (consLaw p Q).mass v=p.mass (v 0)*(Q (v 0)).mass (Fin.tail v) := rfl + +lemma consLaw_variation {n : ℕ} (p q : RationalLaw Bool) + (Q R : Bool → RationalLaw (Fin n → Bool)) (e : ℚ) + (he : ∀ b,variation (Q b) (R b)≤e) : + variation (consLaw p Q) (consLaw q R)≤variation p q+e := by + rw [consLaw,consLaw,variation_equiv] + exact variation_dependentJoint_uniform p q Q R e he + +def bernoulli (q : ℚ) (hq0 : 0≤q) (hq1 : q≤1) : RationalLaw Bool where + mass b := if b then q else 1-q + nonnegative b := by cases b <;> simp [hq0,sub_nonneg.mpr hq1] + total := by simp + +def headProbability (n k : ℕ) : ℚ := ((min k (n+1):ℕ):ℚ)/(n+1) + +lemma headProbability_bounds (n k : ℕ) : 0≤headProbability n k ∧ headProbability n k≤1 := by + constructor + · exact div_nonneg (Nat.cast_nonneg _) (by positivity) + · apply (div_le_one (by positivity : (0:ℚ) pointLaw (fun i => Fin.elim0 i) + | n+1, k => consLaw (headLaw n k) (fun b => fixedLaw n (remaining n k b)) + +def factorialMass (n k : ℕ) : ℚ := (k.factorial:ℚ)*((n-k).factorial:ℚ)/(n.factorial:ℚ) + +private lemma factorialMass_true (n k : ℕ) (hk0 : 0 + have hk0 : k=0 := by omega + subst k + have hv : v=(fun i => Fin.elim0 i) := by funext i; exact Fin.elim0 i + subst v + simp [fixedLaw,pointLaw,count,factorialMass] + | succ n ih => + rw [fixedLaw,consLaw_mass] + have hcount := count_decompose v + cases hb : v 0 with + | false => + simp only [hb,Bool.false_eq_true,ite_false,zero_add] at hcount + by_cases hkn : k≤n + · rw [show remaining n k false=k by simp [remaining,min_eq_left hkn],ih k hkn] + have hp : (headLaw n k).mass false=1-(k:ℚ)/(n+1) := by + simp [headLaw,bernoulli,headProbability,min_eq_left hk] + rw [hp] + by_cases hc : count (Fin.tail v)=k + · simp only [hcount,hc,ite_true] + exact factorialMass_false n k hkn + · simp only [hc,ite_false,mul_zero,hcount] + · have hke : k=n+1 := by omega + subst k + have hp : (headLaw n (n+1)).mass false=0 := by + simp [headLaw,bernoulli,headProbability,show (n:ℚ)+1≠0 by positivity] + rw [hp,zero_mul] + have hc : count v≠n+1 := by rw [hcount]; have := count_le (Fin.tail v); omega + simp [hc] + | true => + simp only [hb,ite_true] at hcount + by_cases hk0 : k=0 + · subst k + have hp : (headLaw n 0).mass true=0 := by simp [headLaw,bernoulli,headProbability] + rw [hp,zero_mul] + have hc : count v≠0 := by omega + simp [hc] + · have hkpos : 0 fixedLaw n k.val) + +theorem sizeMixture_mass (n : ℕ) (v : Fin n → Bool) : + (sizeMixture n).mass v=factorialMass n (count v)/(n+1) := by + let k₀ : Fin (n+1) := ⟨count v,Nat.lt_succ_of_le (count_le v)⟩ + have hiff (k : Fin (n+1)) : count v=k.val ↔ k=k₀ := by + constructor + · intro h; apply Fin.ext; exact h.symm + · intro h; subst k; rfl + change (∑ k : Fin (n+1),(uniformLaw (α := Fin (n+1))).mass k* + (fixedLaw n k.val).mass v)=_ + simp_rw [fixedLaw_mass n _ (Nat.le_of_lt_succ (Fin.isLt _)) v,hiff] + simp [uniformLaw,uniformMass,k₀,mul_comm,div_eq_mul_inv] + +def subsetEquiv (n : ℕ) : (Fin n → Bool) ≃ Finset (Fin n) where + toFun v := Finset.univ.filter (fun i => v i=true) + invFun S i := decide (i∈S) + left_inv v := by + funext i + cases h : v i <;> simp [h] + right_inv S := by ext i; simp + +lemma count_subset_inverse (n : ℕ) (S : Finset (Fin n)) : + count ((subsetEquiv n).symm S)=S.card := by + change (∑ i : Fin n,if decide (i∈S) then 1 else 0)=S.card + simp only [decide_eq_true_eq] + rw [←Finset.sum_filter] + simp + +def localLaw (n : ℕ) : RationalLaw (Finset (Fin n)) := + equivLaw (subsetEquiv n) (sizeMixture n) + +theorem localLaw_mass (n : ℕ) (S : Finset (Fin n)) : + (localLaw n).mass S=factorialMass n S.card/(n+1) := by + change (sizeMixture n).mass ((subsetEquiv n).symm S)=_ + rw [sizeMixture_mass,count_subset_inverse] + +theorem localLaw_mass_cast (n : ℕ) (S : Finset (Fin n)) : + ((localLaw n).mass S:ℝ)=InitialLocalChoices.localWeight n 0 0 S/(n+1) := by + rw [localLaw_mass] + simp [factorialMass,InitialLocalChoices.localWeight,Rat.cast_div,Rat.cast_mul] + +def roundedSizeMixture (B n : ℕ) : RationalLaw (Fin n → Bool) := + bindLaw (scaledLaw (n+1) B (Nat.succ_pos n)) + (fun k => roundedFixedLaw B n k.val) + +lemma uniformInt_eq (n : ℕ) : + uniformIntLaw (n+1) (Nat.succ_pos n)=uniformLaw (α := Fin (n+1)) := by + apply RationalLaw.ext + funext k + simp [uniformIntLaw,uniformLaw,uniformMass] + +theorem roundedSizeMixture_error (B n : ℕ) : + variation (roundedSizeMixture B n) (sizeMixture n)≤ + (n+1:ℚ)/(2*(2:ℚ)^B)+(n:ℚ)/(2:ℚ)^B := by + have h := variation_bind_uniform + (scaledLaw (n+1) B (Nat.succ_pos n)) (uniformLaw (α := Fin (n+1))) + (fun k => roundedFixedLaw B n k.val) (fun k => fixedLaw n k.val) + ((n:ℚ)/(2:ℚ)^B) (fun k => roundedFixed_error B n k.val) + have hs := scaledLaw_variation (n+1) B (Nat.succ_pos n) + rw [uniformInt_eq] at hs + have hs' : variation (scaledLaw (n+1) B (Nat.succ_pos n)) (uniformLaw (α := Fin (n+1)))≤ + (n+1:ℚ)/(2*(2:ℚ)^B) := by + simpa only [Nat.cast_add,Nat.cast_one] using hs + exact h.trans (_root_.add_le_add hs' le_rfl) + +def drawBits (B n : ℕ) := B+n*B + +def vectorDraw (B n : ℕ) (bits : Fin (drawBits B n) → Bool) : Fin n → Bool := + let words := splitWordEquiv B (n*B) bits + bitDraw B n (scaledBitInteger (n+1) B (Nat.succ_pos n) words.1).val words.2 + +theorem vectorDraw_law (B n : ℕ) : + mapLaw (uniformLaw (α := Fin (drawBits B n) → Bool)) (vectorDraw B n)= + roundedSizeMixture B n := by + let drawSize := scaledBitInteger (n+1) B (Nat.succ_pos n) + let finish (k : Fin (n+1)) := bitDraw B n k.val + have he := map_equiv (splitWordEquiv B (n*B)) + (uniformLaw (α := Fin (B+n*B) → Bool)) + (fun words => finish (drawSize words.1) words.2) + rw [uniform_equiv,←uniform_product] at he + have hb := mapLaw_product_finish (uniformLaw (α := Fin B → Bool)) + (uniformLaw (α := Fin (n*B) → Bool)) drawSize finish + have hsize : mapLaw (uniformLaw (α := Fin B → Bool)) drawSize= + scaledLaw (n+1) B (Nat.succ_pos n) := scaledBitIntegerLaw_eq _ _ _ + have hfinish : (fun k => mapLaw (uniformLaw (α := Fin (n*B) → Bool)) (finish k))= + (fun k : Fin (n+1) => roundedFixedLaw B n k.val) := by + funext k + exact bitDraw_law B n k.val + rw [hsize,hfinish] at hb + exact he.symm.trans hb + +def subsetDraw (B n : ℕ) (bits : Fin (drawBits B n) → Bool) : Finset (Fin n) := + subsetEquiv n (vectorDraw B n bits) + +theorem subsetDraw_error (B n : ℕ) : + variation (mapLaw (uniformLaw (α := Fin (drawBits B n) → Bool)) (subsetDraw B n)) + (localLaw n)≤(n+1:ℚ)/(2*(2:ℚ)^B)+(n:ℚ)/(2:ℚ)^B := by + have he := mapLaw_equiv_output (subsetEquiv n) + (uniformLaw (α := Fin (drawBits B n) → Bool)) (vectorDraw B n) + change variation (mapLaw _ (fun bits => subsetEquiv n (vectorDraw B n bits))) _≤_ + rw [he,vectorDraw_law,localLaw,variation_equiv] + exact roundedSizeMixture_error B n + +end +end ContingencyTables.FixedCardinalityMixture + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b36ae87fcc706dc8fd8c004ff129ea5d7fb88f4 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FixedCardinalityProgram.lean @@ -0,0 +1,76 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityBits +import OAI.Combinatorics.ContingencyTables.Machines.ScaledWordProgram + +namespace OAI + +/-! # Polynomial binary arithmetic for sequential subset inclusion + +The rational inclusion threshold is computed by an integer product and +quotient. In particular the denominator is never expanded into a +unary loop; the only exponential integer has the supplied word length +as its binary length. +-/ + +namespace ContingencyTables.FixedCardinalityProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms + +abbrev HeadInput := (ℕ×ℕ)×List Bool + +def includeCode (z : HeadInput) : Bool := + decide (StackAddition.value z.2<2^z.2.length*min z.1.2 z.1.1/z.1.1) + +def includeRealizer : Realizer includeCode := by + let N : Realizer (fun z : HeadInput => z.1.1) := composition first first + let K : Realizer (fun z : HeadInput => z.1.2) := composition first second + let M := composition (pair K N) minimum + let D : Realizer (fun z : HeadInput => TreeTyped.bitDenominator z.2) := + composition second bitDenominatorRealizer + let T := composition (pair (composition (pair D M) multiply) N) quotient + exact (composition (pair (composition second bitValue) T) less).congr (by + intro z + simp only [Function.comp_apply,bitDenominator_eq,includeCode]) + +theorem polynomial_include : PolynomialTime includeRealizer := by + unfold includeRealizer + exact polynomial_congr _ (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_bitValue) + (polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_bitDenominator) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_first polynomial_first)) polynomial_minimum)) + polynomial_multiply) + (polynomial_composition polynomial_first polynomial_first)) polynomial_quotient)) + polynomial_less) + +noncomputable section + +theorem inclusion_threshold (B n k : ℕ) : + FairBits.rationalThreshold B (FixedCardinalityLaw.headProbability n k)= + 2^B*min k (n+1)/(n+1) := by + let M := 2^B*min k (n+1) + have hd : ((n+1:ℕ):ℚ)≠0 := by positivity + have he : (2:ℚ)^B*FixedCardinalityLaw.headProbability n k= + (M:ℚ)/(n+1:ℕ) := by + simp only [FixedCardinalityLaw.headProbability,M,Nat.cast_mul,Nat.cast_pow,Nat.cast_ofNat, + Nat.cast_add,Nat.cast_one] + ring + change ⌊(2:ℚ)^B*FixedCardinalityLaw.headProbability n k⌋₊=_ + rw [he] + have hh := Nat.mul_cast_floor_div_cancel (R := ℚ) (n := n+1) (by omega) + ((M:ℚ)/(n+1:ℕ)) + simpa only [div_mul_cancel₀ _ hd,Nat.floor_natCast] using hh.symm + +/-- The executable natural-number comparison is exactly the inclusion +decision in the finite Boolean law. -/ +theorem includeCode_ofFn (B n k : ℕ) (bits : Fin B → Bool) : + includeCode ((n+1,k),List.ofFn bits)=FixedCardinalityBits.headDraw B n k bits := by + simp only [includeCode,List.length_ofFn,bitValue_eq_word,FixedCardinalityBits.headDraw, + FairBits.rationalThresholdAccept,inclusion_threshold] + +end +end ContingencyTables.FixedCardinalityProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowEntryProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowEntryProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b4be85d61005af9765c234ae0060fdfdecddf14 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowEntryProgram.lean @@ -0,0 +1,152 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FlowPathProgram + +namespace OAI + +/-! # Binary signed augmentation of one matrix entry -/ + +namespace ContingencyTables.FlowEntryProgram + +open MatchingFPRAS.TreeTyped ResidualGraphProgram SignedPairProgram FlowPathProgram + +abbrev UpdateData := Data×(List (ℕ×ℕ)×ℕ) +abbrev EntryInput := UpdateData×(ℕ×ℕ) +abbrev RawInput := Signed×(ℕ×(ℕ×ℕ)) + +def rawUpdate (z : RawInput) : Signed := + (z.1.1+z.2.1*z.2.2.1,z.1.2+z.2.1*z.2.2.2) + +def rawUpdateRealizer : Realizer rawUpdate := by + let old : Realizer (fun z : RawInput=>z.1) := first + let a : Realizer (fun z : RawInput=>z.2.1) := composition second first + let f : Realizer (fun z : RawInput=>z.2.2.1) := composition (composition second second) first + let b : Realizer (fun z : RawInput=>z.2.2.2) := composition (composition second second) second + exact composition (pair old (pair (composition (pair a f) multiply) + (composition (pair a b) multiply))) plusRealizer + +lemma polynomial_rawUpdate : PolynomialTime rawUpdateRealizer := by + unfold rawUpdateRealizer + apply polynomial_composition + · apply polynomial_pair polynomial_first + apply polynomial_pair + · exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_first)) polynomial_multiply + · exact polynomial_composition (polynomial_pair + (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_composition polynomial_second polynomial_second) + polynomial_second)) polynomial_multiply + · exact polynomial_plus + +lemma rawUpdate_value (old : Signed) (a f b : ℕ) : + SignedPairProgram.value (rawUpdate (old,(a,(f,b))))= + SignedPairProgram.value old+(a:ℤ)*((f:ℤ)-b) := by + simp only [rawUpdate,SignedPairProgram.value,Nat.cast_add,Nat.cast_mul] + ring + +def limits (z : EntryInput) : ℕ×ℕ := + (capacityEntry (z.1.1.1,z.2),capacityEntry (z.1.1.1,(z.2.2,z.2.1))) + +def limitsRealizer : Realizer limits := by + let C : Realizer (fun z : EntryInput=>z.1.1.1) := composition (composition first first) first + let uv : Realizer (fun z : EntryInput=>z.2) := second + let vu : Realizer (fun z : EntryInput=>(z.2.2,z.2.1)) := + pair (composition second second) (composition second first) + exact pair (composition (pair C uv) capacityEntryRealizer) + (composition (pair C vu) capacityEntryRealizer) + +lemma polynomial_limits : PolynomialTime limitsRealizer := by + unfold limitsRealizer + apply polynomial_pair + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_second) polynomial_capacityEntry + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) + (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition polynomial_second polynomial_first))) polynomial_capacityEntry + +def rawInput (z : EntryInput) : RawInput := + (flowEntry (z.1.1.2,z.2),(z.1.2.2, + (arcCount (z.2,z.1.2.1),arcCount ((z.2.2,z.2.1),z.1.2.1)))) + +def rawInputRealizer : Realizer rawInput := by + let F : Realizer (fun z : EntryInput=>z.1.1.2) := + composition (composition first first) second + let as : Realizer (fun z : EntryInput=>z.1.2.1) := + composition (composition first second) first + let a : Realizer (fun z : EntryInput=>z.1.2.2) := + composition (composition first second) second + let uv : Realizer (fun z : EntryInput=>z.2) := second + let vu : Realizer (fun z : EntryInput=>(z.2.2,z.2.1)) := + pair (composition second second) (composition second first) + let forward : Realizer (fun z : EntryInput => arcCount (z.2,z.1.2.1)) := + composition (f := fun z : EntryInput => (z.2,z.1.2.1)) + (g := FlowPathProgram.arcCount) (pair uv as) arcCountRealizer + let backward : Realizer (fun z : EntryInput => arcCount ((z.2.2,z.2.1),z.1.2.1)) := + composition (f := fun z : EntryInput => ((z.2.2,z.2.1),z.1.2.1)) + (g := FlowPathProgram.arcCount) (pair vu as) arcCountRealizer + exact pair (composition (pair F uv) flowEntryRealizer) + (pair a (pair forward backward)) + +lemma polynomial_rawInput : PolynomialTime rawInputRealizer := by + unfold rawInputRealizer + apply polynomial_pair + · exact polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_second) polynomial_second) polynomial_flowEntry + · apply polynomial_pair + · exact polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_second + · apply polynomial_pair + · exact polynomial_composition (polynomial_pair polynomial_second + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first)) polynomial_arcCount + · exact polynomial_composition (polynomial_pair + (polynomial_pair (polynomial_composition polynomial_second polynomial_second) + (polynomial_composition polynomial_second polynomial_first)) + (polynomial_composition (polynomial_composition polynomial_first polynomial_second) + polynomial_first)) polynomial_arcCount + +def updateCell (z : EntryInput) : Signed := + FlowClamp.clamp (limits z,rawUpdate (rawInput z)) + +def updateCellRealizer : Realizer updateCell := + composition (pair limitsRealizer (composition rawInputRealizer rawUpdateRealizer)) + FlowClamp.clampRealizer + +lemma polynomial_updateCell : PolynomialTime updateCellRealizer := + polynomial_composition (polynomial_pair polynomial_limits + (polynomial_composition polynomial_rawInput polynomial_rawUpdate)) FlowClamp.polynomial_clamp + +lemma updateCell_bounds (z : EntryInput) : + (updateCell z).1≤(limits z).1 ∧ (updateCell z).2≤(limits z).2 := + FlowClamp.clamp_bounds _ _ + +lemma arcCount_map {n : ℕ} (u v : Fin n) (xs : List (Fin n×Fin n)) : + (arcCount ((u.val,v.val),xs.map (fun xy=>(xy.1.val,xy.2.val))):ℤ)= + (xs.map (fun xy=>if xy=(u,v) then (1:ℤ) else 0)).sum := by + rw [arcCount_cast,List.map_map] + congr 1 + apply List.map_congr_left + intro xy _ + simp only [Function.comp_apply,Fin.val_inj,Prod.ext_iff] + +lemma updateCell_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (s t : Fin n) (f : PublishedEdmondsKarp.Flow n) (xs : List (Fin n)) (a : ℕ) + (hnew : PublishedEdmondsKarp.Feasible c s t + (ResidualAugmentation.listUpdate f xs (a:ℤ))) (u v : Fin n) : + updateCell (((natCode c,flowCode f), + ((ResidualAugmentation.arcs xs).map (fun uv=>(uv.1.val,uv.2.val)),a)),(u.val,v.val))= + ForestAffineProgram.signedParts (ResidualAugmentation.listUpdate f xs (a:ℤ) u v) := by + unfold updateCell limits rawInput + rw [capacityEntry_code,capacityEntry_code,flowEntry_code] + apply FlowClamp.clamp_feasible c s t _ hnew u v + rw [rawUpdate_value,arcCount_map,arcCount_map] + simp only [SignedPairProgram.value,ForestAffineProgram.signedParts_sub, + ResidualAugmentation.listUpdate] + +end ContingencyTables.FlowEntryProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowLoopProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowLoopProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..a68de47002bfd09355a9e2aac89667a74a623c23 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowLoopProgram.lean @@ -0,0 +1,179 @@ +import OAI.Combinatorics.ContingencyTables.Transport.FlowMatrixBounds + +namespace OAI + +/-! # Polynomial binary execution of the bounded residual-flow loop -/ + +namespace ContingencyTables.FlowLoopProgram + +open MatchingFPRAS.TreeTyped Polynomial ResidualGraphProgram FlowMatrixBounds + +abbrev Context := NatMatrix×(ℕ×ℕ) +abbrev State := Context×FlowMatrix + +def step (z : ℕ×State) : State := + (z.2.1,FlowMatrixProgram.advance ((z.2.1.1,z.2.2),z.2.1.2)) + +def stepRealizer : Realizer step := + pair (composition second first) + (composition (pair (pair (composition (composition second first) first) + (composition second second)) (composition (composition second first) second)) + FlowMatrixProgram.advanceRealizer) + +lemma polynomial_step : PolynomialTime stepRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition (polynomial_pair (polynomial_pair + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_first) (polynomial_composition polynomial_second polynomial_second)) + (polynomial_composition (polynomial_composition polynomial_second polynomial_first) + polynomial_second)) FlowMatrixProgram.polynomial_advance) + +lemma fold_context (steps : List ℕ) (s : State) : + (steps.foldl (fun s i=>step (i,s)) s).1=s.1 := by + induction steps generalizing s with + | nil => rfl + | cons i steps ih => exact ih (step (i,s)) + +lemma fold_weight (steps : List ℕ) (s : State) : + weight (steps.foldl (fun s i=>step (i,s)) s).2≤ + max (weight s.2) (matrixBound s.1.1) := by + induction steps generalizing s with + | nil => exact le_max_left _ _ + | cons i steps ih => + have ht := ih (step (i,s)) + have hs := advance_weight ((s.1.1,s.2),s.1.2) + exact ht.trans (max_le hs (le_max_right _ _)) + +theorem polynomial_loop : PolynomialTime (MatchingFPRAS.TreeTyped.fold stepRealizer) := by + apply polynomial_fold polynomial_step (20*(X+1)^3) + intro steps s pre _post _he + let S := weight (steps,s) + let out := pre.foldl (fun s i=>step (i,s)) s + have hs : weight s≤ S := weight_snd (steps,s) + have hc : weight s.1≤ S := (weight_fst s).trans hs + have hC : weight s.1.1≤ S := (weight_fst s.1).trans hc + have hF : weight s.2≤ S := (weight_snd s).trans hs + have hb := matrixBound_le s.1.1 hC + have hfo := fold_weight pre s + have hout : weight out.2≤8*S^3+4*S^2+3*S+1 := + hfo.trans (max_le (by omega) (by omega)) + have hctx : out.1=s.1 := fold_context pre s + have he : weight out=1+weight out.1+weight out.2 := by + change weight (out.1,out.2)=_ + exact weight_prod _ _ + simp only [eval_mul,eval_ofNat,eval_pow,eval_add,eval_X,eval_one] + change weight out≤20*(S+1)^3 + rw [he,hctx] + nlinarith + +def zeroMatrix (C : NatMatrix) : FlowMatrix := + C.map (fun row=>row.map (fun _=>(0,0))) + +def zeroMatrixRealizer : Realizer zeroMatrix := map (map (constant (0,0))) + +lemma polynomial_zeroMatrix : PolynomialTime zeroMatrixRealizer := + polynomial_map (polynomial_map (polynomial_constant (0,0))) + +lemma zeroMatrix_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) : + zeroMatrix (natCode c)=flowCode (0 : PublishedEdmondsKarp.Flow n) := by + simp only [zeroMatrix,natCode,flowCode,List.map_ofFn,Function.comp_def] + rfl + +def cube (n : ℕ) : ℕ := n*n*n + +def cubeRealizer : Realizer cube := + composition (pair (composition (pair identity identity) multiply) identity) multiply + +lemma polynomial_cube : PolynomialTime cubeRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair polynomial_identity polynomial_identity) + polynomial_multiply) polynomial_identity) polynomial_multiply + +def iterationCount (C : NatMatrix) : ℕ := cube C.length+1 + +def iterationCountRealizer : Realizer iterationCount := + composition (composition listLength cubeRealizer) successor + +lemma polynomial_iterationCount : PolynomialTime iterationCountRealizer := + polynomial_composition (polynomial_composition polynomial_listLength polynomial_cube) + polynomial_successor + +def steps (C : NatMatrix) : List ℕ := List.range (iterationCount C) + +def stepsRealizer : Realizer steps := composition iterationCountRealizer range + +lemma polynomial_steps : PolynomialTime stepsRealizer := by + apply polynomial_boundedRange polynomial_iterationCount (X^3+1) + intro C + have h := Nat.pow_le_pow_left (list_length_le_weight C) 3 + simpa only [Function.comp_apply,iterationCount,cube,pow_succ,pow_zero,one_mul, + eval_add,eval_pow,eval_mul,eval_X,eval_one] using Nat.add_le_add_right h 1 + +def prepare (z : Context) : List ℕ×State := (steps z.1,(z,zeroMatrix z.1)) + +def prepareRealizer : Realizer prepare := + pair (composition (f := fun z : Context=>z.1) (g := steps) first stepsRealizer) + (pair identity (composition (f := fun z : Context=>z.1) + (g := zeroMatrix) first zeroMatrixRealizer)) + +lemma polynomial_prepare : PolynomialTime prepareRealizer := + polynomial_pair + (polynomial_composition (f := fun z : Context=>z.1) (g := steps) + polynomial_first polynomial_steps) + (polynomial_pair polynomial_identity + (polynomial_composition (f := fun z : Context=>z.1) (g := zeroMatrix) + polynomial_first polynomial_zeroMatrix)) + +def run (z : Context) : FlowMatrix := + ((steps z.1).foldl (fun s i=>step (i,s)) (z,zeroMatrix z.1)).2 + +def runRealizer : Realizer run := + composition (composition prepareRealizer (MatchingFPRAS.TreeTyped.fold stepRealizer)) second + +theorem polynomial_run : PolynomialTime runRealizer := + polynomial_composition (polynomial_composition polynomial_prepare polynomial_loop) + polynomial_second + +lemma step_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (s t : Fin n) (hst : s≠t) (k i : ℕ) : + step (i,((natCode c,(s.val,t.val)),flowCode (EdmondsKarpAlgorithm.run c s t k)))= + ((natCode c,(s.val,t.val)),flowCode (EdmondsKarpAlgorithm.run c s t (k+1))) := by + change ((natCode c,(s.val,t.val)), + FlowMatrixProgram.advance ((natCode c,flowCode (EdmondsKarpAlgorithm.run c s t k)), + (s.val,t.val)))=_ + apply congrArg (fun F : FlowMatrix=>((natCode c,(s.val,t.val)),F)) + exact FlowMatrixProgram.advance_code c s t hst _ (EdmondsKarpAlgorithm.run_feasible c s t hst k) + +lemma fold_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (s t : Fin n) (hst : s≠t) (steps : List ℕ) (k : ℕ) : + steps.foldl (fun s i=>step (i,s)) + ((natCode c,(s.val,t.val)),flowCode (EdmondsKarpAlgorithm.run c s t k))= + ((natCode c,(s.val,t.val)),flowCode (EdmondsKarpAlgorithm.run c s t (k+steps.length))) := by + induction steps generalizing k with + | nil => simp only [List.foldl_nil,List.length_nil,Nat.add_zero] + | cons i steps ih => + rw [List.foldl_cons,step_code c s t hst k i,ih] + simp only [List.length_cons,Nat.add_comm,Nat.add_left_comm] + +theorem run_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (s t : Fin n) (hst : s≠t) : + run (natCode c,(s.val,t.val))=flowCode (EdmondsKarpAlgorithm.maxFlow c s t) := by + unfold run + rw [zeroMatrix_code] + change (List.foldl _ ((natCode c,(s.val,t.val)), + flowCode (EdmondsKarpAlgorithm.run c s t 0)) (steps (natCode c))).2=_ + rw [fold_code c s t hst] + simp only [steps,List.length_range,iterationCount,cube,natCode,List.length_ofFn, + Nat.zero_add,EdmondsKarpAlgorithm.maxFlow,pow_succ,pow_zero,one_mul] + +theorem run_maximum (hEK : PublishedEdmondsKarp.EdmondsKarp1972Theorem1) + {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) (hc : ∀ u,c u u=0) + (s t : Fin n) (hst : s≠t) : + ∃ f,run (natCode c,(s.val,t.val))=flowCode f ∧ + PublishedEdmondsKarp.IsMaximum c s t f := by + exact ⟨EdmondsKarpAlgorithm.maxFlow c s t,run_code c s t hst, + EdmondsKarpAlgorithm.maxFlow_correct hEK c hc s t hst⟩ + +end ContingencyTables.FlowLoopProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..def8bf581be63e20a1533dd590473246fb9796dd --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowMatrixProgram.lean @@ -0,0 +1,146 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FlowEntryProgram +import OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpAlgorithm + +namespace OAI + +/-! # Materialized binary residual augmentation + +The path and bottleneck are computed once, then every matrix entry is +updated from the preceding matrix. Missing paths leave that matrix +unchanged. +-/ + +namespace ContingencyTables.FlowMatrixProgram + +open MatchingFPRAS.TreeTyped DirectedBFSProgram ResidualGraphProgram FlowPathProgram + FlowEntryProgram + +def updateRow (z : UpdateData×ℕ) : List SignedPairProgram.Signed := + (List.range z.1.1.1.length).map (fun v=>updateCell (z.1,(z.2,v))) + +def updateRowRealizer : Realizer updateRow := + composition + (f := fun z : UpdateData×ℕ=>(z,List.range z.1.1.1.length)) + (g := fun z : (UpdateData×ℕ)×List ℕ=> + z.2.map (fun v=>updateCell (z.1.1,(z.1.2,v)))) + (pair identity (composition (f := fun z : UpdateData×ℕ=>z.1.1.1) + (g := matrixIndices) (composition (composition first first) first) matrixIndicesRealizer)) + (mapWith (composition + (f := fun z : (UpdateData×ℕ)×ℕ=>(z.1.1,(z.1.2,z.2))) (g := updateCell) + (pair (composition first first) (pair (composition first second) second)) updateCellRealizer)) + +lemma polynomial_updateRow : PolynomialTime updateRowRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_first) polynomial_matrixIndices)) + (polynomial_mapWith (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + polynomial_second)) polynomial_updateCell)) + +def updateMatrix (z : UpdateData) : FlowMatrix := + (List.range z.1.1.length).map (fun u=>updateRow (z,u)) + +def updateMatrixRealizer : Realizer updateMatrix := + composition + (f := fun z : UpdateData=>(z,List.range z.1.1.length)) + (g := fun z : UpdateData×List ℕ=>z.2.map (fun u=>updateRow (z.1,u))) + (pair identity (composition (f := fun z : UpdateData=>z.1.1) (g := matrixIndices) + (composition first first) matrixIndicesRealizer)) (mapWith updateRowRealizer) + +lemma polynomial_updateMatrix : PolynomialTime updateMatrixRealizer := + polynomial_composition (polynomial_pair polynomial_identity + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) + polynomial_matrixIndices)) (polynomial_mapWith polynomial_updateRow) + +lemma updateMatrix_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (s t : Fin n) (f : PublishedEdmondsKarp.Flow n) (xs : List (Fin n)) (a : ℕ) + (hnew : PublishedEdmondsKarp.Feasible c s t + (ResidualAugmentation.listUpdate f xs (a:ℤ))) : + updateMatrix ((natCode c,flowCode f), + ((ResidualAugmentation.arcs xs).map (fun uv=>(uv.1.val,uv.2.val)),a))= + flowCode (ResidualAugmentation.listUpdate f xs (a:ℤ)) := by + simp only [updateMatrix,updateRow,natCode,List.length_ofFn,DirectedBFSCode.range_eq_map, + List.map_ofFn,←List.ofFn_eq_map,flowCode] + apply congrArg List.ofFn + funext u + apply congrArg List.ofFn + funext v + exact updateCell_code c s t f xs a hnew u v + +def prepareAugment (z : Data×List ℕ) : UpdateData := + (z.1,(arcPairs z.2,bottleneck z)) + +def prepareAugmentRealizer : Realizer prepareAugment := + pair first (pair (composition second arcPairsRealizer) bottleneckRealizer) + +lemma polynomial_prepareAugment : PolynomialTime prepareAugmentRealizer := + polynomial_pair polynomial_first (polynomial_pair + (polynomial_composition polynomial_second polynomial_arcPairs) polynomial_bottleneck) + +def augment (z : Data×List ℕ) : FlowMatrix := updateMatrix (prepareAugment z) + +def augmentRealizer : Realizer augment := + composition prepareAugmentRealizer updateMatrixRealizer + +lemma polynomial_augment : PolynomialTime augmentRealizer := + polynomial_composition polynomial_prepareAugment polynomial_updateMatrix + +def advance (z : Data×(ℕ×ℕ)) : FlowMatrix := + match ResidualGraphProgram.search z with + | none => z.1.2 + | Option.some xs => augment (z.1,xs) + +def advanceRealizer : Realizer advance := + (composition (pair identity ResidualGraphProgram.searchRealizer) + (optionCases (composition first second) + (composition (pair (composition first first) second) augmentRealizer))).congr (by + intro z + dsimp only [Function.comp_apply,id_eq,advance] + cases h : ResidualGraphProgram.search z <;> rfl) + +lemma polynomial_advance : PolynomialTime advanceRealizer := + polynomial_congr _ (polynomial_composition + (polynomial_pair polynomial_identity ResidualGraphProgram.polynomial_search) + (polynomial_optionCases (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + polynomial_augment))) + +lemma search_residual_nonnegative {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (f : PublishedEdmondsKarp.Flow n) (s t : Fin n) (xs : List (Fin n)) + (h : ResidualSearch.search c f s t=some xs) : + ∀ uv∈ResidualAugmentation.arcs xs,0≤(c uv.1 uv.2:ℤ)-f uv.1 uv.2 := by + obtain ⟨k,p,rfl,hp,_⟩ := ResidualSearch.search_shortest c f s t xs h + intro uv huv + rw [ResidualAugmentation.arcs_ofFn] at huv + obtain ⟨i,rfl⟩ := List.mem_ofFn.mp huv + exact (hp.2.2.2 i).le + +theorem advance_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (s t : Fin n) (hst : s≠t) (f : PublishedEdmondsKarp.Flow n) + (hf : PublishedEdmondsKarp.Feasible c s t f) : + advance ((natCode c,flowCode f),(s.val,t.val))= + flowCode (EdmondsKarpAlgorithm.advance c s t f) := by + cases hs : ResidualSearch.search c f s t with + | none => + simp only [advance,ResidualGraphProgram.search_code,hs,Option.map_none, + EdmondsKarpAlgorithm.advance,ResidualAugmentation.step,Option.getD_none] + | some xs => + have hn := search_residual_nonnegative c f s t xs hs + let a := bottleneck ((natCode c,flowCode f),xs.map Fin.val) + have ha : (a:ℤ)=ResidualAugmentation.bottleneck c f xs := bottleneck_code c f xs hn + have hstep : ResidualAugmentation.step c s t f= + Option.some (ResidualAugmentation.listUpdate f xs (a:ℤ)) := by + simp only [ResidualAugmentation.step,hs,Option.map_some,ha] + have hnew := ResidualAugmentation.step_feasible c s t hst f _ hf hstep + simp only [advance,ResidualGraphProgram.search_code,hs,Option.map_some] + change updateMatrix ((natCode c,flowCode f), + (arcPairs (xs.map Fin.val),a))=_ + rw [arcPairs_map,updateMatrix_code c s t f xs a hnew] + simp only [EdmondsKarpAlgorithm.advance,hstep,Option.getD_some] + +end ContingencyTables.FlowMatrixProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowPathProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowPathProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..87c731854ee8882094af068313d37b9b67b2b198 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FlowPathProgram.lean @@ -0,0 +1,190 @@ +import OAI.Combinatorics.ContingencyTables.Machines.ResidualGraphProgram +import OAI.Combinatorics.ContingencyTables.Transport.ResidualAugmentation +import OAI.Combinatorics.ContingencyTables.Machines.FiniteGraphRootProgram +import OAI.Combinatorics.ContingencyTables.Transport.FlowClamp + +namespace OAI + +/-! # Binary path bottlenecks and one integral flow-entry update -/ + +namespace ContingencyTables.FlowPathProgram + +open MatchingFPRAS.TreeTyped DirectedBFSProgram ResidualGraphProgram SignedPairProgram + +/-- Adjacent path entries, using only indices below the stored path length. -/ +def arcPairs (xs : List ℕ) : List (ℕ×ℕ) := + (List.range (xs.length-1)).map (fun i=>(xs.getD i 0,xs.getD (i+1) 0)) + +def pairAt (z : List ℕ×ℕ) : ℕ×ℕ := (z.1.getD z.2 0,z.1.getD (z.2+1) 0) + +def pairAtRealizer : Realizer pairAt := + pair (getDFast 0) (composition + (pair first (composition second successor)) (getDFast 0)) + +lemma polynomial_pairAt : PolynomialTime pairAtRealizer := + polynomial_pair (polynomial_getDFast 0) (polynomial_composition + (polynomial_pair polynomial_first (polynomial_composition polynomial_second + polynomial_successor)) (polynomial_getDFast 0)) + +def arcIndices (xs : List ℕ) : List ℕ := List.range (xs.length-1) + +def arcIndicesRealizer : Realizer arcIndices := + composition (composition listLength predecessor) range + +lemma polynomial_arcIndices : PolynomialTime arcIndicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition polynomial_listLength polynomial_predecessor) Polynomial.X + intro xs + have h := list_length_le_weight xs + simpa only [Function.comp_apply,Polynomial.eval_X] using (Nat.sub_le xs.length 1).trans h + +def arcPairsRealizer : Realizer arcPairs := + composition (pair identity arcIndicesRealizer) (mapWith pairAtRealizer) + +lemma polynomial_arcPairs : PolynomialTime arcPairsRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_arcIndices) + (polynomial_mapWith polynomial_pairAt) + +lemma arcPairs_nil : arcPairs []=[] := rfl +lemma arcPairs_singleton (u : ℕ) : arcPairs [u]=[] := rfl + +lemma arcPairs_cons_cons (u v : ℕ) (xs : List ℕ) : + arcPairs (u::v::xs)=(u,v)::arcPairs (v::xs) := by + simp [arcPairs,List.range_succ_eq_map,Function.comp_def] + +lemma arcPairs_map {n : ℕ} (xs : List (Fin n)) : + arcPairs (xs.map Fin.val)= + (ResidualAugmentation.arcs xs).map (fun uv=>(uv.1.val,uv.2.val)) := by + induction xs with + | nil => rfl + | cons u xs ih => + cases xs with + | nil => rfl + | cons v xs => + simpa only [List.map_cons,arcPairs_cons_cons,ResidualAugmentation.arcs] using + congrArg (List.cons (u.val,v.val)) ih + +def minimumScan (xs : List ℕ) : ℕ := + match xs with + | [] => 0 + | a::as => as.foldl (fun b a=>min a b) a + +def minimumScanRealizer : Realizer minimumScan := + (listCase 0 (composition (pair second first) (fold minimum))).congr (by + intro xs + cases xs <;> rfl) + +lemma polynomial_minimumScan : PolynomialTime minimumScanRealizer := + polynomial_congr _ (polynomial_listCase 0 (polynomial_composition + (polynomial_pair polynomial_second polynomial_first) + FiniteGraphRootProgram.polynomial_minimumFold)) + +lemma minimumScan_eq (xs : List ℕ) : minimumScan xs=xs.min?.getD 0 := by + cases xs with + | nil => rfl + | cons a xs => + simp only [minimumScan,List.min?_cons',Option.getD_some] + have he : (fun b a : ℕ=>min a b)=min := by + funext b c + exact min_comm c b + rw [he] + +lemma minimumFold_cast (xs : List ℕ) (a : ℕ) : + ((xs.foldl (fun b a : ℕ=>min a b) a:ℕ):ℤ)= + (xs.map (fun a : ℕ=>(a:ℤ))).foldl min (a:ℤ) := by + induction xs generalizing a with + | nil => rfl + | cons b xs ih => + simp only [List.foldl_cons,List.map_cons] + rw [ih,Nat.cast_min,min_comm (b:ℤ) (a:ℤ)] + +lemma minimumScan_cast (xs : List ℕ) : + (minimumScan xs:ℤ)=(xs.map (fun a : ℕ=>(a:ℤ))).min?.getD 0 := by + cases xs with + | nil => rfl + | cons a xs => + simp only [minimumScan,List.map_cons,List.min?_cons',Option.getD_some] + exact minimumFold_cast xs a + +def residuals (z : Data×List ℕ) : List ℕ := + (arcPairs z.2).map (fun uv=>residualValue (arcData (z.1,uv))) + +def residualsRealizer : Realizer residuals := + composition (pair first (composition second arcPairsRealizer)) + (mapWith (composition arcDataRealizer residualValueRealizer)) + +lemma polynomial_residuals : PolynomialTime residualsRealizer := + polynomial_composition (polynomial_pair polynomial_first + (polynomial_composition polynomial_second polynomial_arcPairs)) + (polynomial_mapWith (polynomial_composition polynomial_arcData polynomial_residualValue)) + +def bottleneck (z : Data×List ℕ) : ℕ := minimumScan (residuals z) +def bottleneckRealizer : Realizer bottleneck := composition residualsRealizer minimumScanRealizer +lemma polynomial_bottleneck : PolynomialTime bottleneckRealizer := + polynomial_composition polynomial_residuals polynomial_minimumScan + +lemma bottleneck_code {n : ℕ} (c : PublishedEdmondsKarp.Capacity n) + (f : PublishedEdmondsKarp.Flow n) (xs : List (Fin n)) + (hres : ∀ uv∈ResidualAugmentation.arcs xs,0≤(c uv.1 uv.2:ℤ)-f uv.1 uv.2) : + (bottleneck ((natCode c,flowCode f),xs.map Fin.val):ℤ)= + ResidualAugmentation.bottleneck c f xs := by + rw [bottleneck,minimumScan_cast] + apply congrArg (fun zs : List ℤ=>zs.min?.getD 0) + simp only [residuals,arcPairs_map,List.map_map] + change (ResidualAugmentation.arcs xs).map (fun uv=> + (residualValue (arcData ((natCode c,flowCode f),(uv.1.val,uv.2.val))):ℤ))= + (ResidualAugmentation.arcs xs).map (fun uv=>(c uv.1 uv.2:ℤ)-f uv.1 uv.2) + apply List.map_congr_left + intro uv huv + simp only [arcData,capacityEntry_code,flowEntry_code, + residualValue_correct,SignedPairProgram.value,ForestAffineProgram.signedParts_sub] + exact Int.toNat_of_nonneg (hres uv huv) + +def pairEqual (z : (ℕ×ℕ)×(ℕ×ℕ)) : Bool := + decide (z.1.1=z.2.1) && decide (z.1.2=z.2.2) + +def pairEqualRealizer : Realizer pairEqual := + composition (pair + (composition (pair (composition first first) (composition second first)) natEqual) + (composition (pair (composition first second) (composition second second)) natEqual)) boolAnd + +lemma polynomial_pairEqual : PolynomialTime pairEqualRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_first)) polynomial_natEqual) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_second polynomial_second)) polynomial_natEqual)) + polynomial_boolAnd + +def arcCount (z : (ℕ×ℕ)×List (ℕ×ℕ)) : ℕ := + (z.2.filter (fun uv=>pairEqual (z.1,uv))).length + +def arcCountRealizer : Realizer arcCount := + composition (filterWith pairEqualRealizer) listLength + +lemma polynomial_arcCount : PolynomialTime arcCountRealizer := + polynomial_composition (polynomial_filterWith polynomial_pairEqual) polynomial_listLength + +lemma arcCount_cast (uv : ℕ×ℕ) (xs : List (ℕ×ℕ)) : + (arcCount (uv,xs):ℤ)=(xs.map (fun xy=>if xy=uv then (1:ℤ) else 0)).sum := by + induction xs with + | nil => rfl + | cons a xs ih => + by_cases h : a=uv + · subst a + simpa [arcCount,pairEqual,add_comm] using congrArg (fun z : ℤ=>1+z) ih + · have he : pairEqual (uv,a)=false := by + by_cases h1 : uv.1=a.1 + · by_cases h2 : uv.2=a.2 + · exact False.elim (h (Prod.ext h1.symm h2.symm)) + · simp [pairEqual,h1,h2] + · simp [pairEqual,h1] + simp only [arcCount,List.filter_cons,he,Bool.false_eq_true,ite_false, + List.map_cons,h,ite_false,List.sum_cons,zero_add] + exact ih + +end ContingencyTables.FlowPathProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionAcceptanceProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionAcceptanceProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..170496ad1a982dc7bd030bf69c41a123078ddc6a --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionAcceptanceProgram.lean @@ -0,0 +1,81 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityProgram +import OAI.Combinatorics.MatchingCount.Complexity.TreeFractionCosts + +namespace OAI + +/-! # Binary execution of the rational acceptance coin + +The integer quotient computes the exact floor threshold used by the +finite-word acceptance law. The word length controls all powering and +word traversal, even for malformed fraction inputs. +-/ + +namespace ContingencyTables.FractionAcceptanceProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped ProfilePrograms + +abbrev Input := TreeFraction.Fraction×List Bool + +def scaledNumerator (z : Input) : ℕ := z.1.1*bitDenominator z.2 + +def scaledNumeratorRealizer : Realizer scaledNumerator := + composition (f := fun z : Input => (z.1.1,bitDenominator z.2)) + (g := fun x : ℕ×ℕ => x.1*x.2) + (pair (composition first first) (composition second bitDenominatorRealizer)) multiply + +lemma polynomial_scaledNumerator : PolynomialTime scaledNumeratorRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) + (polynomial_composition polynomial_second polynomial_bitDenominator)) polynomial_multiply + +def threshold (z : Input) : ℕ := scaledNumerator z/z.1.2 + +def thresholdRealizer : Realizer threshold := + composition (f := fun z : Input => (scaledNumerator z,z.1.2)) + (g := fun x : ℕ×ℕ => x.1/x.2) + (pair scaledNumeratorRealizer (composition first second)) quotient + +lemma polynomial_threshold : PolynomialTime thresholdRealizer := + polynomial_composition (polynomial_pair polynomial_scaledNumerator + (polynomial_composition polynomial_first polynomial_second)) polynomial_quotient + +def acceptCode (z : Input) : Bool := decide (StackAddition.value z.2 (StackAddition.value z.2,threshold z)) + (g := fun x : ℕ×ℕ => decide (x.1 + (TreeFraction.sum (xs.map TreeFraction.normalize),(xs.length,1))) (g := TreeFraction.div) + (pair (composition (map TreeFraction.normalizeRealizer) TreeFraction.sumRealizer) + (pair listLength (constant 1))) TreeFraction.divRealizer +lemma polynomial_average : PolynomialTime averageRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_map TreeFraction.polynomial_normalize) + TreeFraction.polynomial_sum) + (polynomial_pair polynomial_listLength (polynomial_constant 1))) TreeFraction.polynomial_div + +lemma average_value (xs : List TreeFraction.Fraction) : + TreeFraction.val (average xs)=(xs.map TreeFraction.val).sum/(xs.length:ℚ) := by + rw [average,TreeFraction.div_val,TreeFraction.sum_val] + · rw [show TreeFraction.val (xs.length,1)=(xs.length:ℚ) by + simp only [TreeFraction.val,Nat.cast_one,div_one]] + simp only [List.map_map,Function.comp_def,TreeFraction.normalize_val] + · intro b hb + obtain ⟨a,ha,rfl⟩ := List.mem_map.mp hb + exact TreeFraction.normalize_den_pos a + +lemma average_ofFn {X : Type*} (g : X → TreeFraction.Fraction) (N : ℕ) + (draws : Fin N → X) : + TreeFraction.val (average (List.ofFn (fun i => g (draws i))))= + (∑ i : Fin N, TreeFraction.val (g (draws i)))/(N:ℚ) := by + rw [average_value] + simp only [List.map_ofFn,List.length_ofFn,List.sum_ofFn,Function.comp_apply] + +private lemma height_mul (a b : TreeFraction.Fraction) : + TreeFraction.height (TreeFraction.mul (a,b)) ≤ + TreeFraction.height a+TreeFraction.height b+1 := by + have hn := TreeFraction.normalize_size_num (a.1*b.1,a.2*b.2) + have hd := TreeFraction.normalize_size_den (a.1*b.1,a.2*b.2) + have hnum := nat_size_mul a.1 b.1 + have hden := nat_size_mul a.2 b.2 + have ha := le_max_left a.1.size a.2.size + have ha' := le_max_right a.1.size a.2.size + have hb := le_max_left b.1.size b.2.size + have hb' := le_max_right b.1.size b.2.size + dsimp only at hn hd + change (TreeFraction.mul (a,b)).1.size ≤ _ at hn + change (TreeFraction.mul (a,b)).2.size ≤ _ at hd + unfold TreeFraction.height + apply max_le <;> omega + +private lemma fold_height (xs : List TreeFraction.Fraction) (a : TreeFraction.Fraction) + (M : ℕ) (hx : ∀ b∈xs,TreeFraction.height b ≤ M) : + TreeFraction.height (xs.foldl (fun a b => TreeFraction.mul (b,a)) a) ≤ + TreeFraction.height a+xs.length*(M+1) := by + induction xs generalizing a with + | nil => simp + | cons b bs ih => + have hb := hx b (by simp) + have ht := ih (TreeFraction.mul (b,a)) (fun c hc => hx c (by simp [hc])) + have hm := height_mul b a + simp only [List.foldl_cons,List.length_cons] + nlinarith + +private lemma polynomial_productFold : PolynomialTime (fold TreeFraction.mulRealizer) := by + apply polynomial_fold TreeFraction.polynomial_mul (8*X+8*X*(X+1)+3) + intro xs a pre post he + let S := weight (xs,a) + have hp : pre.length ≤ S := + (list_length_le_weight pre).trans ((weight_prefix he).trans (weight_fst (xs,a))) + have hb : ∀ b∈pre,TreeFraction.height b ≤ S := by + intro b hb + exact (TreeFraction.height_le_weight b).trans + ((weight_mem (as := xs) (by simp [he,hb])).trans (weight_fst (xs,a))) + have ha : TreeFraction.height a ≤ S := + (TreeFraction.height_le_weight a).trans (weight_snd (xs,a)) + have hh := fold_height pre a S hb + have hw := TreeFraction.weight_le_height (pre.foldl (fun a b => TreeFraction.mul (b,a)) a) + have hm := Nat.mul_le_mul_right (S+1) hp + simp only [eval_add,eval_mul,eval_ofNat,eval_X,eval_one] + change _ ≤ 8*S+8*S*(S+1)+3 + nlinarith + +def product (xs : List TreeFraction.Fraction) : TreeFraction.Fraction := + xs.foldl (fun a b => TreeFraction.mul (b,a)) (1,1) +def productRealizer : Realizer product := + composition (f := fun xs : List TreeFraction.Fraction => (xs,(1,1))) + (g := fun z : List TreeFraction.Fraction×TreeFraction.Fraction => + z.1.foldl (fun a b => TreeFraction.mul (b,a)) z.2) + (pair identity (constant (1,1))) (fold TreeFraction.mulRealizer) +lemma polynomial_product : PolynomialTime productRealizer := + polynomial_composition (polynomial_pair polynomial_identity (polynomial_constant (1,1))) + polynomial_productFold + +private lemma fold_value (xs : List TreeFraction.Fraction) (a : TreeFraction.Fraction) : + TreeFraction.val (xs.foldl (fun a b => TreeFraction.mul (b,a)) a)= + TreeFraction.val a*(xs.map TreeFraction.val).prod := by + induction xs generalizing a with + | nil => simp + | cons b bs ih => + simp only [List.foldl_cons,ih,TreeFraction.mul_val,List.map_cons,List.prod_cons] + ring + +lemma product_value (xs : List TreeFraction.Fraction) : + TreeFraction.val (product xs)=(xs.map TreeFraction.val).prod := by + rw [product,fold_value] + simp only [TreeFraction.val,Nat.cast_one,div_self (by norm_num : (1:ℚ)≠0),one_mul] + +end ContingencyTables.FractionAggregateProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionMetropolisProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionMetropolisProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ebc1aa4544e2c70eb7113a874fec05ed2665b83 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionMetropolisProgram.lean @@ -0,0 +1,90 @@ +import OAI.Combinatorics.ContingencyTables.Machines.FractionAcceptanceProgram +import OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport + +namespace OAI + +/-! # Clipped rational Metropolis acceptance as a binary program -/ + +namespace ContingencyTables.FractionMetropolisProgram + +open MatchingFPRAS MatchingFPRAS.TreeTyped + +abbrev Input := (TreeFraction.Fraction × TreeFraction.Fraction) × List Bool + +def ratio (z : Input) : TreeFraction.Fraction := TreeFraction.div (z.1.2,z.1.1) +def ratioRealizer : Realizer ratio := + composition (f := fun z : Input => (z.1.2,z.1.1)) (g := TreeFraction.div) + (pair (composition first second) (composition first first)) TreeFraction.divRealizer +lemma polynomial_ratio : PolynomialTime ratioRealizer := + polynomial_composition (polynomial_pair (polynomial_composition polynomial_first polynomial_second) + (polynomial_composition polynomial_first polynomial_first)) TreeFraction.polynomial_div + +def belowOne (z : Input) : Bool := TreeFraction.less (ratio z,(1,1)) +def belowOneRealizer : Realizer belowOne := + composition (f := fun z : Input => (ratio z,(1,1))) (g := TreeFraction.less) + (pair ratioRealizer (constant (1,1))) TreeFraction.lessRealizer +lemma polynomial_belowOne : PolynomialTime belowOneRealizer := + polynomial_composition (polynomial_pair polynomial_ratio (polynomial_constant _)) TreeFraction.polynomial_less + +def probability (z : Input) : TreeFraction.Fraction := if belowOne z then ratio z else (1,1) +def probabilityRealizer : Realizer probability := choose belowOneRealizer ratioRealizer (constant (1,1)) +lemma polynomial_probability : PolynomialTime probabilityRealizer := + polynomial_choose polynomial_belowOne polynomial_ratio (polynomial_constant _) + +attribute [local irreducible] probability + +def accept (z : Input) : Bool := FractionAcceptanceProgram.acceptCode (probability z,z.2) +def acceptRealizer : Realizer accept := + composition (f := fun z : Input => (probability z,z.2)) (g := FractionAcceptanceProgram.acceptCode) + (pair probabilityRealizer second) FractionAcceptanceProgram.acceptCodeRealizer +lemma polynomial_accept : PolynomialTime acceptRealizer := + polynomial_composition (polynomial_pair polynomial_probability polynomial_second) + FractionAcceptanceProgram.polynomial_acceptCode + +lemma probability_value (x y : TreeFraction.Fraction) (bits : List Bool) : + TreeFraction.val (probability ((x,y),bits))=min 1 (TreeFraction.val y/TreeFraction.val x) := by + have hd : 0 < (ratio ((x,y),bits)).2 := TreeFraction.normalize_den_pos _ + have hr : TreeFraction.val (ratio ((x,y),bits))=TreeFraction.val y/TreeFraction.val x := + TreeFraction.div_val y x + unfold probability belowOne + rw [TreeFraction.less_val _ _ hd (by decide)] + have hone : TreeFraction.val (1,1)=(1:ℚ) := by norm_num [TreeFraction.val] + rw [hone] + by_cases h : TreeFraction.val (ratio ((x,y),bits)) < 1 + · simp only [h,decide_true,ite_true] + rw [hr] + exact (min_eq_right (by simpa only [hr] using h.le)).symm + · simp only [h,decide_false,Bool.false_eq_true,ite_false,hone] + exact (min_eq_left (by simpa only [hr] using le_of_not_gt h)).symm + +lemma accept_ofFn (x y : TreeFraction.Fraction) (B : ℕ) (bits : Fin B → Bool) : + accept ((x,y),List.ofFn bits)= + decide (FairBits.rationalThresholdAccept B (min 1 (TreeFraction.val y/TreeFraction.val x)) bits) := by + rw [accept,FractionAcceptanceProgram.acceptCode_ofFn,probability_value] + +noncomputable section +open FiniteObservableTransport +open scoped Classical + +/-- Independent exact observable laws suffice for the implemented coin; +no finite type of rational weight values is required. -/ +theorem sameLaw_accept {X Y U V : Type*} [Fintype X] [Fintype Y] [Fintype U] [Fintype V] + (current : X → TreeFraction.Fraction) (target : U → TreeFraction.Fraction) + (f : Y → ℚ) (g : V → ℚ) + (hf : SameLaw (fun x => TreeFraction.val (current x)) f) + (hg : SameLaw (fun u => TreeFraction.val (target u)) g) (B : ℕ) : + SameLaw (fun z : (X × U) × (Fin B → Bool) => + accept ((current z.1.1,target z.1.2),List.ofFn z.2)) + (fun z : (Y × V) × (Fin B → Bool) => + decide (FairBits.rationalThresholdAccept B (min 1 (g z.1.2/f z.1.1)) z.2)) := by + have hid : SameLaw (fun x : Fin B → Bool => x) (fun x : Fin B → Bool => x) := fun _ => rfl + have hs := (hf.prod hg).prod hid + intro phi + simp_rw [accept_ofFn] + exact hs (fun z => phi (decide (FairBits.rationalThresholdAccept B (min 1 (z.1.2/z.1.1)) z.2))) + +end + +end ContingencyTables.FractionMetropolisProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionOutputProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionOutputProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7389f7e5ed533ecbdca6387c46588c2bc2c0824e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionOutputProgram.lean @@ -0,0 +1,37 @@ +import OAI.Combinatorics.MatchingCount.Complexity.TreeFractionCosts +import OAI.Combinatorics.MatchingCount.Tapes.Codec + +namespace OAI + +/-! # Canonical nonnegative rational output on the public tape -/ + +namespace ContingencyTables.FractionOutputProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped MatchingFPRAS.LiteralCodec + +def output (x : TreeFraction.Fraction) : List Symbol := ratWord (TreeFraction.normalize x) +def outputRealizer : Realizer output := + composition (f := TreeFraction.normalize) (g := ratWord) + TreeFraction.normalizeRealizer ratWordRealizer +lemma polynomial_output : PolynomialTime outputRealizer := + polynomial_composition TreeFraction.polynomial_normalize polynomial_ratWord + +lemma output_eq (x : TreeFraction.Fraction) : output x=encodeRat (TreeFraction.val x) := by + rw [output,TreeFraction.normalize_repr,ratWord_repr _ (TreeFraction.val_nonneg x)] + +lemma natWord_symbols (n : ℕ) (a : Symbol) (ha : a∈natWord n) : a≠0 ∧ a≠6 ∧ a≠7 := by + simp only [natWord,List.mem_append,List.mem_map,List.mem_singleton] at ha + rcases ha with ⟨b,_,rfl⟩ | rfl + · cases b <;> decide + · decide + +lemma output_symbols (x : TreeFraction.Fraction) (a : Symbol) (ha : a∈output x) : + a≠0 ∧ a≠6 ∧ a≠7 := by + simp only [output,ratWord,List.mem_cons,List.mem_append] at ha + rcases ha with (rfl | ha) | ha + · decide + · exact natWord_symbols _ a ha + · exact natWord_symbols _ a ha + +end ContingencyTables.FractionOutputProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionRepetitionProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionRepetitionProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..7904e6fe14938362d71654870f0e29af5936b68d --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/FractionRepetitionProgram.lean @@ -0,0 +1,26 @@ +import OAI.Combinatorics.ContingencyTables.Counting.CountingOracleScheduleProgram +import OAI.Combinatorics.ContingencyTables.Transport.FiniteMedianConfidence + +namespace OAI + +/-! # Executing the confidence repetition count on a rational input -/ +namespace ContingencyTables.FractionRepetitionProgram +open MatchingFPRAS MatchingFPRAS.TreeTyped + +def count (x : TreeFraction.Fraction) : ℕ := 64*((TreeFraction.normalize x).2.bits.length+1) +def countRealizer : Realizer count := + composition (f := fun x : TreeFraction.Fraction => (64,(TreeFraction.normalize x).2.bits.length+1)) + (g := fun p : ℕ×ℕ => p.1*p.2) + (pair (constant 64) (composition + (composition (composition (composition TreeFraction.normalizeRealizer second) toBits) listLength) + successor)) multiply +lemma polynomial_count : PolynomialTime countRealizer := + polynomial_composition (polynomial_pair (polynomial_constant 64) + (polynomial_composition (polynomial_composition (polynomial_composition + (polynomial_composition TreeFraction.polynomial_normalize polynomial_second) polynomial_toBits) + polynomial_listLength) polynomial_successor)) polynomial_multiply +lemma count_val (x : TreeFraction.Fraction) : count x=CommonBasesFPRAS.repetitionCount (TreeFraction.val x) := by + simp only [count,TreeFraction.normalize_repr,TreeFraction.repr,CommonBasesFPRAS.repetitionCount] +end ContingencyTables.FractionRepetitionProgram + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/GeometricRuntime.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/GeometricRuntime.lean new file mode 100644 index 0000000000000000000000000000000000000000..e15c5c8ecdc629cae3b0870ce1321701bb90cb47 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/GeometricRuntime.lean @@ -0,0 +1,57 @@ +import Mathlib.Analysis.SpecificLimits.Basic +import Mathlib.Logic.Equiv.Fin.Basic + +namespace OAI + +/-! # From per-attempt geometric failure to physical expected runtime -/ + +namespace ContingencyTables.GeometricRuntime +open scoped BigOperators + +lemma block_geometric (T : ℕ) (hT : 0 ρ^(t/T)) ∧ + (∑' t : ℕ,ρ^(t/T))=(T:ℝ)/(1-ρ) := by + let : NeZero T:=⟨hT.ne'⟩ + have hgeo:=summable_geometric_of_lt_one hρ hρ1 + have hprod : Summable (fun p : ℕ×Fin T => ρ^p.1) := by + apply (summable_prod_of_nonneg (fun p => pow_nonneg hρ p.1)).mpr + refine ⟨fun _ => Summable.of_finite,?_⟩ + simpa only [tsum_fintype,Finset.sum_const,Finset.card_univ,Fintype.card_fin, + nsmul_eq_mul] using hgeo.mul_left (T:ℝ) + have hs : Summable (fun t : ℕ => ρ^(t/T)) := + (Nat.divModEquiv T).summable_iff.mpr hprod + refine ⟨hs,?_⟩ + calc + (∑' t : ℕ,ρ^(t/T)) = ∑' p : ℕ×Fin T,ρ^p.1 := + (Nat.divModEquiv T).tsum_eq (fun p => ρ^p.1) + _ = ∑' n : ℕ,∑' _j : Fin T,ρ^n := hprod.tsum_prod + _ = ∑' n : ℕ,(T:ℝ)*ρ^n := by simp only [tsum_fintype,Finset.sum_const, + Finset.card_univ,Fintype.card_fin,nsmul_eq_mul] + _ = (T:ℝ)*(∑' n : ℕ,ρ^n) := tsum_mul_left + _ = (T:ℝ)/(1-ρ) := by rw [tsum_geometric_of_lt_one hρ hρ1]; rfl + +/-- A real tail is required to be summable, rather than assigning a +default value to a divergent infinite sum. -/ +theorem expected_time_bound (tail : ℕ → ℝ) (T : ℕ) (hT : 0 cellWidth (z.2,n)) + +def widthsRealizer : Realizer widths := + composition (pair second first) (mapWith cellWidthRealizer) + +theorem polynomial_widths : PolynomialTime widthsRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_cellWidth) + +abbrev Input := (List ℕ×ℕ)×List Bool + +def cellCode (z : Input×ℕ) : List Bool := + subsetCode ((z.1.1.1.getD z.2 0,z.1.1.2), + dependentChunk ((widths z.1.1,z.1.2),z.2)) + +def cellCodeRealizer : Realizer cellCode := by + let cap : Realizer (fun z : Input×ℕ => z.1.1.1.getD z.2 0) := + composition (pair (composition (composition first first) first) second) (getDFast 0) + let B : Realizer (fun z : Input×ℕ => z.1.1.2) := + composition (composition first first) second + let sizes : Realizer (fun z : Input×ℕ => widths z.1.1) := + composition (composition first first) widthsRealizer + let bits : Realizer (fun z : Input×ℕ => z.1.2) := composition first second + let block := composition (pair (pair sizes bits) second) dependentChunkRealizer + exact composition (pair (pair cap B) block) subsetCodeRealizer + +theorem polynomial_cellCode : PolynomialTime cellCodeRealizer := by + unfold cellCodeRealizer + have hc : PolynomialTime (composition + (pair (composition (composition (first (A := Input) (B := ℕ)) first) first) second) + (getDFast 0)) := polynomial_composition + (polynomial_pair (polynomial_composition + (polynomial_composition polynomial_first polynomial_first) polynomial_first) polynomial_second) + (polynomial_getDFast 0) + have hb : PolynomialTime (composition + (composition (first (A := Input) (B := ℕ)) first) second) := + polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_second + have hs := polynomial_composition + (polynomial_composition (polynomial_first (A := Input) (B := ℕ)) polynomial_first) polynomial_widths + exact polynomial_composition (polynomial_pair (polynomial_pair hc hb) + (polynomial_composition (polynomial_pair (polynomial_pair hs + (polynomial_composition polynomial_first polynomial_second)) polynomial_second) + polynomial_dependentChunk)) polynomial_subsetCode + +def indices (z : Input) : List ℕ := List.range z.1.1.length + +def indicesRealizer : Realizer indices := + composition (composition (composition first first) listLength) range + +theorem polynomial_indices : PolynomialTime indicesRealizer := by + apply polynomial_boundedRange + (polynomial_composition (polynomial_composition polynomial_first polynomial_first) polynomial_listLength) X + intro z + simpa only [Function.comp_apply,eval_X] using + (list_length_le_weight z.1.1).trans ((weight_fst z.1).trans (weight_fst z)) + +def choiceCode (z : Input) : List (List Bool) := (indices z).map (fun i => cellCode (z,i)) + +def choiceCodeRealizer : Realizer choiceCode := + composition (pair identity indicesRealizer) (mapWith cellCodeRealizer) + +theorem polynomial_choiceCode : PolynomialTime choiceCodeRealizer := + polynomial_composition (polynomial_pair polynomial_identity polynomial_indices) + (polynomial_mapWith polynomial_cellCode) + +noncomputable section +open FixedCardinalityMixture InitialFactorialBits +open scoped BigOperators + +lemma widths_ofFn {q : ℕ} (b : Fin q → ℕ) (B : ℕ) : + widths (List.ofFn b,B)=List.ofFn (fun i => drawBits B (b i)) := by + unfold widths + rw [List.map_ofFn] + rfl + +theorem cellCode_ofFn {q : ℕ} (b : Fin q → ℕ) (B : ℕ) (hB : 0 drawBits B (b i)) bits i + have he := congrArg (fun block : List Bool => subsetCode ((b i,B),block)) hd + exact he.trans (subsetCode_ofFn B (b i) hB (wordEquiv b B bits i)) + +/-- The executable product of cell programs gives exactly the Boolean +rows whose support is the initial independent choice vector. -/ +theorem choiceCode_ofFn {q : ℕ} (b : Fin q → ℕ) (B : ℕ) (hB : 0 List.ofFn (vectorDraw B (b i) (wordEquiv b B bits i))) := by + apply List.ext_getElem + · simp only [choiceCode,indices,List.length_map,List.length_range,List.length_ofFn] + · intro i hi _ + have hiq : i (mapLaw + (uniformLaw (α := Fin (drawBits B (b c)) → Bool)) (subsetDraw B (b c))).nonnegative (S c)) + total := by + rw [←Fintype.prod_sum] + simp only [RationalLaw.total,Finset.prod_const_one] + +/-- Reordering the independent cell words changes no finite initializer +law, including its finite-precision bias. -/ +theorem transversalDraw_law (b : C → ℕ) (e : C ≃ Fin q) (B : ℕ) : + mapLaw (uniformLaw (α := Fin (bitCount (fun i => b (e.symm i)) B) → Bool)) + (transversalDraw b e B)= + equivLaw (plainEquivChoices b).symm (finiteChoiceLaw b B) := by + let E := (choiceEquiv b e).trans (plainEquivChoices b).symm + have he := mapLaw_equiv_output E + (uniformLaw (α := Fin (bitCount (fun i => b (e.symm i)) B) → Bool)) + (drawChoices (fun i => b (e.symm i)) B) + rw [drawChoices_law] at he + change mapLaw _ (fun bits => E (drawChoices _ B bits))=_ + refine he.trans ?_ + apply RationalLaw.ext + funext S + change (∏ i : Fin q, + (mapLaw (uniformLaw (α := Fin (drawBits B (b (e.symm i))) → Bool)) + (subsetDraw B (b (e.symm i)))).mass ((plainEquivChoices b S) (e.symm i)))= + ∏ c,(mapLaw (uniformLaw (α := Fin (drawBits B (b c)) → Bool)) + (subsetDraw B (b c))).mass ((plainEquivChoices b S) c) + symm + apply Fintype.prod_equiv e + intro c + exact congrArg (fun c => + (mapLaw (uniformLaw (α := Fin (drawBits B (b c)) → Bool)) + (subsetDraw B (b c))).mass ((plainEquivChoices b S) c)) (e.symm_apply_apply c).symm + +end +end ContingencyTables.InitialFactorialBits + +namespace ContingencyTables.CompanionComputedInitial + +open CommonBasesFPRAS ResidualMixture FirstSuccess CompanionFactorialApplication +open InitialFactorialBits FiniteObservableTransport +open scoped Classical +noncomputable section +variable {m n : ℕ} + +theorem initialDraw_law (A : Instance (Fin m) (Fin n)) (B : ℕ) : + mapLaw (uniformLaw (α := Fin (wordLength A B) → Bool)) (initialDraw A B)= + mapLaw (uniformLaw (α := Fin (CompanionInitialDraw.initialBits A B) → Bool)) + (CompanionInitialDraw.draw A B) := by + let b := fun s : SmallCell A => A.b s.val.1 s.val.2 + let E := CompanionInitialDraw.indexEquiv A + have h₁ := mapLaw_equiv_output E + (uniformLaw (α := Fin (bitCount (fun i => b ((cellOrder A).symm i)) B) → Bool)) + (transversalDraw b (cellOrder A) B) + have h₂ := mapLaw_equiv_output E + (uniformLaw (α := Fin (bitCount (fun i => b ((CompanionInitialDraw.cellEnum A).symm i)) B) → Bool)) + (transversalDraw b (CompanionInitialDraw.cellEnum A) B) + have ht : mapLaw (uniformLaw (α := Fin (bitCount (fun i => b ((cellOrder A).symm i)) B) → Bool)) + (transversalDraw b (cellOrder A) B)= + mapLaw (uniformLaw (α := Fin (bitCount (fun i => b ((CompanionInitialDraw.cellEnum A).symm i)) B) → Bool)) + (transversalDraw b (CompanionInitialDraw.cellEnum A) B) := + (transversalDraw_law b (cellOrder A) B).trans + (transversalDraw_law b (CompanionInitialDraw.cellEnum A) B).symm + exact h₁.trans ((congrArg (equivLaw E) ht).trans h₂.symm) + +theorem initialProgram_sameLaw (A : Instance (Fin m) (Fin n)) (B : ℕ) (hB : 0 < B) : + SameLaw (fun bits : Fin (wordLength A B) → Bool => + initialProgram ((CompanionCellCatalog.input A,B),List.ofFn bits)) + (fun bits : Fin (CompanionInitialDraw.initialBits A B) → Bool => + CompanionArithmeticProposal.encodeSet (coordinateOrder A) + (CompanionInitialDraw.draw A B bits).val.val) := by + have h := (SameLaw.of_mapLaw_eq (initialDraw A B) (CompanionInitialDraw.draw A B) + (initialDraw_law A B)).map (fun S => CompanionArithmeticProposal.encodeSet (coordinateOrder A) S.val.val) + intro phi + simpa only [initialProgram_eq A B hB] using h phi + +end +end ContingencyTables.CompanionComputedInitial + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/InitialFactorialBits.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/InitialFactorialBits.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8bb81f5845bebc32f70700f9128bd8d33b4960f --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/InitialFactorialBits.lean @@ -0,0 +1,124 @@ +import OAI.Combinatorics.ContingencyTables.Transport.InitialFactorialLaw + +namespace OAI + +/-! # One finite Boolean word for the actual initial transversal + +The word is split into disjoint cell blocks; each block chooses a size +and then a subset of that size. The total variation errors add before +the exact paired-transversal encoding is applied. +-/ + +namespace ContingencyTables.InitialFactorialBits + +open CommonBasesFPRAS ResidualMixture FirstSuccess FairBits TwoLiftStates +open FixedCardinalityMixture InitialFactorialLaw InitialTransversals +open CompanionFactorialApplication +open scoped BigOperators Classical +noncomputable section + +variable {q : ℕ} + +def bitCount (b : Fin q → ℕ) (B : ℕ) : ℕ := ∑ i,drawBits B (b i) + +def wordEquiv (b : Fin q → ℕ) (B : ℕ) : + (Fin (bitCount b B) → Bool) ≃ (∀ i,Fin (drawBits B (b i)) → Bool) := + (Equiv.arrowCongr finSigmaFinEquiv.symm (Equiv.refl Bool)).trans + (Equiv.piCurry (fun _ _ => Bool)) + +def drawChoices (b : Fin q → ℕ) (B : ℕ) (bits : Fin (bitCount b B) → Bool) : + ∀ i,Finset (Fin (b i)) := + fun i => subsetDraw B (b i) (wordEquiv b B bits i) + +theorem drawChoices_law (b : Fin q → ℕ) (B : ℕ) : + mapLaw (uniformLaw (α := Fin (bitCount b B) → Bool)) (drawChoices b B)= + piLaw (fun i => mapLaw (uniformLaw (α := Fin (drawBits B (b i)) → Bool)) + (subsetDraw B (b i))) := by + have he := map_equiv (wordEquiv b B) + (uniformLaw (α := Fin (bitCount b B) → Bool)) + (fun words i => subsetDraw B (b i) (words i)) + rw [uniform_equiv,←pi_uniformLaw,pi_mapLaw] at he + exact he.symm + +theorem drawChoices_error (b : Fin q → ℕ) (B : ℕ) : + variation (mapLaw (uniformLaw (α := Fin (bitCount b B) → Bool)) (drawChoices b B)) + (piLaw (fun i => localLaw (b i)))≤ + ∑ i,((b i+1:ℚ)/(2*(2:ℚ)^B)+(b i:ℚ)/(2:ℚ)^B) := by + rw [drawChoices_law] + exact (variation_pi _ _ _).trans (Finset.sum_le_sum (fun i _ => subsetDraw_error B (b i))) + +theorem bitCount_eq (b : Fin q → ℕ) (B : ℕ) : + bitCount b B=(q+∑ i,b i)*B := by + simp only [bitCount,drawBits,Finset.sum_add_distrib,Finset.sum_const, + Finset.card_univ,Fintype.card_fin,nsmul_eq_mul,←Finset.sum_mul] + simp only [Nat.cast_id] + ring + +theorem bitCount_bound (b : Fin q → ℕ) (B W : ℕ) (hb : ∀ i,b i≤W) : + bitCount b B≤q*(W+1)*B := by + rw [bitCount_eq] + apply Nat.mul_le_mul_right + have hs : (∑ i,b i)≤q*W := by + calc + _ ≤ ∑ _i : Fin q,W := Finset.sum_le_sum (fun i _ => hb i) + _ = q*W := by simp + nlinarith + +theorem drawChoices_error_bound (b : Fin q → ℕ) (B W : ℕ) (hb : ∀ i,b i≤W) : + variation (mapLaw (uniformLaw (α := Fin (bitCount b B) → Bool)) (drawChoices b B)) + (piLaw (fun i => localLaw (b i)))≤(q:ℚ)*(3*W+1)/(2*(2:ℚ)^B) := by + apply (drawChoices_error b B).trans + calc + _ ≤ ∑ _i : Fin q,((W+1:ℚ)/(2*(2:ℚ)^B)+(W:ℚ)/(2:ℚ)^B) := by + apply Finset.sum_le_sum + intro i _ + have hi : (b i:ℚ)≤W := by exact_mod_cast hb i + exact _root_.add_le_add + (div_le_div_of_nonneg_right (by linarith) (by positivity)) + (div_le_div_of_nonneg_right hi (by positivity)) + _ = _ := by simp; ring + +variable {C : Type*} [Fintype C] + +def choiceEquiv (b : C → ℕ) (e : C ≃ Fin q) : + (∀ i : Fin q,Finset (Fin (b (e.symm i)))) ≃ (∀ c,Finset (Fin (b c))) := + (Equiv.piCongrLeft' (fun c => Finset (Fin (b c))) e).symm + +theorem choiceEquiv_law (b : C → ℕ) (e : C ≃ Fin q) : + equivLaw (choiceEquiv b e) (piLaw (fun i => localLaw (b (e.symm i))))=choiceLaw b := by + apply RationalLaw.ext + funext S + change (∏ i : Fin q,(localLaw (b (e.symm i))).mass (S (e.symm i)))= + ∏ c,(localLaw (b c)).mass (S c) + symm + apply Fintype.prod_equiv e + intro c + exact congrArg (fun x => (localLaw (b x)).mass (S x)) (e.symm_apply_apply c).symm + +def transversalDraw (b : C → ℕ) (e : C ≃ Fin q) (B : ℕ) + (bits : Fin (bitCount (fun i => b (e.symm i)) B) → Bool) : + {S : Set (Copy b×Bool) // PlainState pairs S} := + (plainEquivChoices b).symm + (choiceEquiv b e (drawChoices (fun i => b (e.symm i)) B bits)) + +theorem transversalDraw_error (b : C → ℕ) (e : C ≃ Fin q) (B W : ℕ) + (hb : ∀ c,b c≤W) : + variation (mapLaw (uniformLaw (α := Fin (bitCount (fun i => b (e.symm i)) B) → Bool)) + (transversalDraw b e B)) (plainLaw b)≤(q:ℚ)*(3*W+1)/(2*(2:ℚ)^B) := by + let E := (choiceEquiv b e).trans (plainEquivChoices b).symm + have he := mapLaw_equiv_output E + (uniformLaw (α := Fin (bitCount (fun i => b (e.symm i)) B) → Bool)) + (drawChoices (fun i => b (e.symm i)) B) + have ht : equivLaw E (piLaw (fun i => localLaw (b (e.symm i))))=plainLaw b := by + have hh := choiceEquiv_law b e + apply RationalLaw.ext + funext S + exact congrArg (fun p => p.mass ((plainEquivChoices b) S)) hh + change variation (mapLaw _ (fun bits => E (drawChoices _ B bits))) _≤_ + rw [he,←ht,variation_equiv] + exact drawChoices_error_bound _ B W (fun i => hb (e.symm i)) + +end +end ContingencyTables.InitialFactorialBits + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/InitialLocalChoices.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/InitialLocalChoices.lean new file mode 100644 index 0000000000000000000000000000000000000000..682d08584480f44002dbf3d502e3d40741d60f8e --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/InitialLocalChoices.lean @@ -0,0 +1,36 @@ +import OAI.Combinatorics.ContingencyTables.Counting.InitializationBrackets + +namespace OAI + +/-! # The initialization brackets are actual sums over remaining row labels -/ + +namespace ContingencyTables.InitialLocalChoices + +open scoped BigOperators Classical +open Nat +open InitializationBrackets + +noncomputable def localWeight (b u v : ℕ) (S : Finset (Fin (b-u-v))) : ℝ := + ((S.card+v)!:ℝ)*((b-u-v-S.card+v)!:ℝ)/(b !:ℝ) + +/-- Enumerating all choices of the remaining row labels gives exactly +the binomial/factorial bracket, including empty local spaces. -/ +theorem sum_localWeight (b u v : ℕ) : + (∑ S : Finset (Fin (b-u-v)), localWeight b u v S)=bracket b u v := by + have h := Finset.sum_powerset_apply_card + (fun k => ((k+v)!:ℝ)*((b-u-v-k+v)!:ℝ)/(b !:ℝ)) + (x := (Finset.univ : Finset (Fin (b-u-v)))) + simpa [localWeight,bracket,nsmul_eq_mul,Finset.sum_div,mul_div_assoc,mul_assoc] using h + +/-- Independent choices in the cells factor exactly; the expression is +a finite combinatorial sum before evaluating its four bracket cases. -/ +theorem sum_independent_choices {C : Type*} [Fintype C] (b u v : C → ℕ) : + (∑ S : ((c : C) → Finset (Fin (b c-u c-v c))), + ∏ c, localWeight (b c) (u c) (v c) (S c))= + ∏ c, bracket (b c) (u c) (v c) := by + rw [← Fintype.prod_sum] + simp_rw [sum_localWeight] + +end ContingencyTables.InitialLocalChoices + +end OAI diff --git a/lean/OAI/Combinatorics/ContingencyTables/Machines/IntegerMatrixProgram.lean b/lean/OAI/Combinatorics/ContingencyTables/Machines/IntegerMatrixProgram.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d10c3535e922bd34bc89dfbd33928f4af189441 --- /dev/null +++ b/lean/OAI/Combinatorics/ContingencyTables/Machines/IntegerMatrixProgram.lean @@ -0,0 +1,278 @@ +import OAI.Combinatorics.ContingencyTables.Transport.IntegerPropagation +import OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts + +namespace OAI + +/-! # Binary integer matrix propagation for exact law tabulation -/ + +namespace ContingencyTables.IntegerMatrixPrograms +open MatchingFPRAS MatchingFPRAS.TreeTyped +open scoped BigOperators + +/-- Missing coordinates are zero. The loop runs over the vector's length. -/ +def dot (z : List ℕ×List ℕ) : ℕ := + ((List.range z.1.length).map (fun i => z.1.getD i 0*z.2.getD i 0)).sum + +def entryRealizer : Realizer + (fun z : (List ℕ×List ℕ)×ℕ => z.1.1.getD z.2 0*z.1.2.getD z.2 0) := + composition (pair + (composition (pair (composition first first) second) (getDFast 0)) + (composition (pair (composition first second) second) (getDFast 0))) multiply + +lemma polynomial_entry : PolynomialTime entryRealizer := + polynomial_composition (polynomial_pair + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_first) polynomial_second) + (polynomial_getDFast 0)) + (polynomial_composition (polynomial_pair + (polynomial_composition polynomial_first polynomial_second) polynomial_second) + (polynomial_getDFast 0))) polynomial_multiply + +def dotRealizer : Realizer dot := + composition (f := fun z : List ℕ×List ℕ => (z,List.range z.1.length)) + (g := fun z : (List ℕ×List ℕ)×List ℕ => + (z.2.map (fun i => z.1.1.getD i 0*z.1.2.getD i 0)).sum) + (pair identity (composition (composition first listLength) range)) + (composition (mapWith entryRealizer) listSum) + +lemma polynomial_dot : PolynomialTime dotRealizer := by + unfold dotRealizer + apply polynomial_composition + · apply polynomial_pair polynomial_identity + exact polynomial_boundedRange (polynomial_composition polynomial_first polynomial_listLength) + Polynomial.X (fun z => by + simpa using (list_length_le_weight z.1).trans (weight_fst z)) + · exact polynomial_composition (polynomial_mapWith polynomial_entry) polynomial_listSum + +/-- A matrix is stored by columns, so each new coordinate is one dot product. -/ +def propagate (z : List (List ℕ)×List ℕ) : List ℕ := + z.1.map (fun column => dot (z.2,column)) + +def propagateRealizer : Realizer propagate := + composition (pair second first) (mapWith dotRealizer) + +lemma polynomial_propagate : PolynomialTime propagateRealizer := + polynomial_composition (polynomial_pair polynomial_second polynomial_first) + (polynomial_mapWith polynomial_dot) + +private lemma range_sum (f : ℕ → ℕ) (n : ℕ) : + ((List.range n).map f).sum=∑ i : Fin n,f i := by + induction n with + | zero => simp + | succ n ih => + rw [List.sum_range_succ,Fin.sum_univ_castSucc,ih] + rfl + +lemma dot_ofFn {n : ℕ} (v b : Fin n → ℕ) : + dot (List.ofFn v,List.ofFn b)=∑ i,v i*b i := by + unfold dot + rw [List.length_ofFn,range_sum] + apply Finset.sum_congr rfl + intro i _ + simp [List.getD_eq_getElem?_getD,i.isLt] + +lemma propagate_ofFn {n : ℕ} (B : Fin n → Fin n → ℕ) (v : Fin n → ℕ) : + propagate (List.ofFn (fun y => List.ofFn (fun x => B x y)),List.ofFn v)= + List.ofFn (fun y => ∑ x,v x*B x y) := by + simp only [propagate,List.map_ofFn,Function.comp_def,dot_ofFn] + +/-- One iteration retains the transition table unchanged. -/ +def step (z : ℕ×(List (List ℕ)×List ℕ)) : List (List ℕ)×List ℕ := + (z.2.1,propagate z.2) + +def stepRealizer : Realizer step := + pair (composition second first) (composition second propagateRealizer) + +lemma polynomial_step : PolynomialTime stepRealizer := + polynomial_pair (polynomial_composition polynomial_second polynomial_first) + (polynomial_composition polynomial_second polynomial_propagate) + +def iterate (z : ℕ×(List (List ℕ)×List ℕ)) : List ℕ := + (countDown step z.1 z.2).2 + +def iterateRealizer : Realizer iterate := + composition (composition identity (iterateDown stepRealizer)) second + +private lemma countDown_table (N : ℕ) (B : List (List ℕ)) (v : List ℕ) : + (countDown step N (B,v)).1=B := by + induction N generalizing v with + | zero => rfl + | succ N ih => exact ih _ + +lemma iterate_succ (N : ℕ) (B : List (List ℕ)) (v : List ℕ) : + iterate (N+1,(B,v))=iterate (N,(B,propagate (B,v))) := rfl + +lemma iterate_ofFn {n : ℕ} (B : Fin n → Fin n → ℕ) (start : Fin n) (N : ℕ) : + iterate (N,(List.ofFn (fun y => List.ofFn (fun x => B x y)), + List.ofFn (fun x => if x=start then 1 else 0)))= + List.ofFn (IntegerPropagation.numerators B start N) := by + have hi (N : ℕ) (v : Fin n → ℕ) : + countDown step N (List.ofFn (fun y => List.ofFn (fun x => B x y)),List.ofFn v)= + (List.ofFn (fun y => List.ofFn (fun x => B x y)), + List.ofFn ((fun v y => ∑ x,v x*B x y)^[N] v)) := by + induction N generalizing v with + | zero => rfl + | succ N ih => + rw [countDown] + change countDown step N (_,propagate (_,List.ofFn v))=_ + rw [propagate_ofFn,ih,Function.iterate_succ_apply] + have hn (N : ℕ) : ((fun v y => ∑ x,v x*B x y)^[N] + (fun x => if x=start then 1 else 0))=IntegerPropagation.numerators B start N := by + induction N with + | zero => rfl + | succ N ih => + rw [Function.iterate_succ_apply',ih] + rfl + unfold iterate + rw [hi,hn] + +lemma dot_nil (b : List ℕ) : dot ([],b)=0 := by simp [dot] + +lemma dot_cons (a : ℕ) (v b : List ℕ) : + dot (a::v,b)=a*b.headD 0+dot (v,b.tail) := by + have hzero : b.getD 0 0=b.headD 0 := by cases b <;> rfl + simp only [dot,List.length_cons,List.sum_range_succ',List.getD_cons_zero] + rw [hzero] + congr 1 + congr 1 + apply List.map_congr_left + intro i _ + cases b <;> simp + +lemma dot_le (v b : List ℕ) : dot (v,b) ≤ v.sum*b.sum := by + induction v generalizing b with + | nil => simp [dot_nil] + | cons a v ih => + rw [dot_cons] + cases b with + | nil => simpa using ih [] + | cons b bs => + have hb:=ih bs + simp only [List.headD_cons,List.tail_cons,List.sum_cons] + nlinarith [Nat.zero_le (a*bs.sum),Nat.zero_le (v.sum*b)] + +def matrixTotal (B : List (List ℕ)) : ℕ := (B.map List.sum).sum + +lemma propagate_sum_le (B : List (List ℕ)) (v : List ℕ) : + (propagate (B,v)).sum ≤ v.sum*matrixTotal B := by + induction B with + | nil => simp [propagate,matrixTotal] + | cons b B ih => + have hb:=dot_le v b + simp only [propagate,List.map_cons,List.sum_cons,matrixTotal] at * + nlinarith + +lemma sum_size_le_weight (v : List ℕ) : v.sum.size ≤ weight v := by + induction v with + | nil => simp + | cons a v ih => + have ha:=size_le_weight a + have hs:=nat_size_add a v.sum + rw [List.sum_cons,weight_cons] + have hm : max a.size v.sum.size ≤ weight a+weight v := max_le (by omega) (by omega) + omega + +lemma matrixTotal_size_le_weight (B : List (List ℕ)) : (matrixTotal B).size ≤ weight B := by + induction B with + | nil => simp [matrixTotal] + | cons b B ih => + have hb:=sum_size_le_weight b + have hs:=nat_size_add b.sum (matrixTotal B) + change (b.sum+matrixTotal B).size ≤ weight (b::B) + rw [weight_cons] + have hm : max b.sum.size (matrixTotal B).size ≤ weight b+weight B := + max_le (by omega) (by omega) + omega + +lemma pow_size_le (a N : ℕ) : (a^N).size ≤ 1+N*a.size := by + induction N with + | zero => simp + | succ N ih => + have hs:=nat_size_mul (a^N) a + rw [pow_succ] + nlinarith + +lemma weight_of_entry_bound (v : List ℕ) (M : ℕ) (h : ∀ a∈v,a.size ≤ M) : + weight v ≤ v.length*(4*M+2)+1 := by + have hw:=weight_map_bound (as := v) (f := id) (N := 4*M+1) (by + intro a ha + have hs:=h a ha + have hw:=weight_nat_le a + simpa using (show weight a ≤ 4*M+1 by omega)) + simpa using hw + +/-- The iteration bound uses the number of steps and the binary input size. +The numerical values of the matrix entries never control a loop. -/ +theorem work_iterate : WorkBound iterateRealizer + (fun z => z.1+weight z.2) := by + unfold iterateRealizer + apply work_then_polynomial _ polynomial_second + apply work_boundedRepeat + (work_of_polynomial polynomial_identity (5*Polynomial.X+3) (by + intro z + have hn:=weight_nat_numeric z.1 + rw [←Prod.eta z,weight_prod] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat, + Polynomial.eval_X] + omega)) polynomial_step Polynomial.X + (2+Polynomial.X+Polynomial.X*(4*(Polynomial.X+1+Polynomial.X*(Polynomial.X+2))+2)) + (fun z k state => state.1=z.2.1 ∧ state.2.length ≤ z.1+weight z.2 ∧ + state.2.sum ≤ z.2.2.sum*(matrixTotal z.2.1+1)^(z.1-k)) + · intro z + simp + · intro z + refine ⟨rfl,?_,?_⟩ + · have hv:=weight_snd z.2 + exact (list_length_le_weight z.2.2).trans (by omega) + · simp + · intro z k hk state hs + change k Nat.zero_le _) _ ha)).trans hsbit + have hw:=weight_of_entry_bound state.2 (S+1+S*(S+2)) ha + have hm:=Nat.mul_le_mul_right (4*(S+1+S*(S+2))+2) hlen + change weight state ≤ _ + rw [←Prod.eta state,weight_prod,hB] + simp only [Polynomial.eval_add,Polynomial.eval_mul,Polynomial.eval_ofNat, + Polynomial.eval_X,Polynomial.eval_one] + change 1+weight z.2.1+weight state.2 ≤ 2+S+S*(4*(S+1+S*(S+2))+2) + omega + +end ContingencyTables.IntegerMatrixPrograms + +end OAI