Datasets:
AI4M
/

text
stringlengths
0
3.34M
-- Andreas, 2018-05-28, issue #3095, fail on attempt to make hidden parent variable visible data Nat : Set where suc : {n : Nat} → Nat data IsSuc : Nat → Set where isSuc : ∀{n} → IsSuc (suc {n}) test : ∀{m} → IsSuc m → Set test p = aux p where aux : ∀{n} → IsSuc n → Set aux isSuc = {!.m!} -- Split on .m here -- Context: -- p : IsSuc .m -- .m : Nat -- .n : Nat -- Expected error: -- Cannot split on module parameter .m -- when checking that the expression ? has type Set
import pseudo_normed_group.CLC /-! # V-hat((M_c)^n)^{T⁻¹} This file defines a fundamental construction defined just above Definition 9.3 in `analytic.pdf`: the subspac of V-hat(M_c^n) where the two actions of T⁻¹ coincide. ## Main definition Here `M` is a profinitely filtered pseudo-normed group with `T⁻¹` scaling things by `r'`, `V` is a seminormed group with `T⁻¹` scaling norms by `r`, `c` is a real (a filtration coefficient) and `n` is a natural. - `CLCFPTinv r V r' c n M`: the seminormed group defined as the subgroup of `V-hat(M_c^n)` where the two actions of `T⁻¹` (one coming from the action on M, the other coming from the action on V) coincide. -/ open_locale classical nnreal noncomputable theory local attribute [instance] type_pow namespace category_theory theorem comm_sq₂ {C} [category C] {A₁ A₂ A₃ B₁ B₂ B₃ : C} {f₁ : A₁ ⟶ B₁} {f₂ : A₂ ⟶ B₂} {f₃ : A₃ ⟶ B₃} {a : A₁ ⟶ A₂} {a' : A₂ ⟶ A₃} {b : B₁ ⟶ B₂} {b' : B₂ ⟶ B₃} (h₁ : a ≫ f₂ = f₁ ≫ b) (h₂ : a' ≫ f₃ = f₂ ≫ b') : (a ≫ a') ≫ f₃ = f₁ ≫ b ≫ b' := by rw [category.assoc, h₂, ← category.assoc, h₁, ← category.assoc] end category_theory open SemiNormedGroup opposite Profinite pseudo_normed_group category_theory breen_deligne open profinitely_filtered_pseudo_normed_group category_theory.limits open normed_add_group_hom namespace SemiNormedGroup def equalizer {V W : SemiNormedGroup} (f g : V ⟶ W) := of (f.equalizer g) namespace equalizer def ι {V W : SemiNormedGroup} (f g : V ⟶ W) : equalizer f g ⟶ V := normed_add_group_hom.equalizer.ι _ _ @[reassoc] lemma condition {V W : SemiNormedGroup} (f g : V ⟶ W) : ι f g ≫ f = ι f g ≫ g := normed_add_group_hom.equalizer.comp_ι_eq _ _ lemma ι_range {V W : SemiNormedGroup} (f g : V ⟶ W) : (ι f g).range = (f - g).ker := begin ext, rw [normed_add_group_hom.mem_range, normed_add_group_hom.mem_ker], split, { rintro ⟨x, rfl⟩, rw [normed_add_group_hom.sub_apply], exact x.2 }, { intro h, refine ⟨⟨x, h⟩, rfl⟩, } end lemma ι_range' {V W : SemiNormedGroup} (f g : V ⟶ W) : (ι f g).range = (g - f).ker := begin rw ι_range, ext x, simp only [normed_add_group_hom.mem_ker, normed_add_group_hom.sub_apply, sub_eq_zero], rw eq_comm end def map {V₁ V₂ W₁ W₂ : SemiNormedGroup} {f₁ f₂ g₁ g₂} (φ : V₁ ⟶ V₂) (ψ : W₁ ⟶ W₂) (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) : equalizer f₁ g₁ ⟶ equalizer f₂ g₂ := normed_add_group_hom.equalizer.map _ _ hf.symm hg.symm lemma map_comp_ι {V₁ V₂ W₁ W₂ : SemiNormedGroup} {f₁ f₂ g₁ g₂} (φ : V₁ ⟶ V₂) (ψ : W₁ ⟶ W₂) (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) : map φ ψ hf hg ≫ ι _ _ = ι _ _ ≫ φ := rfl theorem map_congr {V₁ V₂ W₁ W₂ : SemiNormedGroup} {f₁ f₂ g₁ g₂} {φ : V₁ ⟶ V₂} {ψ : W₁ ⟶ W₂} {V₁' V₂' W₁' W₂' : SemiNormedGroup} {f₁' f₂' g₁' g₂'} {φ' : V₁' ⟶ V₂'} {ψ' : W₁' ⟶ W₂'} {hf : φ ≫ f₂ = f₁ ≫ ψ} {hg : φ ≫ g₂ = g₁ ≫ ψ} {hf' : φ' ≫ f₂' = f₁' ≫ ψ'} {hg' : φ' ≫ g₂' = g₁' ≫ ψ'} (Hφ : arrow.mk φ = arrow.mk φ') (Hψ : arrow.mk ψ = arrow.mk ψ') (Hf₁ : arrow.mk f₁ = arrow.mk f₁') (Hf₂ : arrow.mk f₂ = arrow.mk f₂') (Hg₁ : arrow.mk g₁ = arrow.mk g₁') (Hg₂ : arrow.mk g₂ = arrow.mk g₂') : arrow.mk (map φ ψ hf hg) = arrow.mk (map φ' ψ' hf' hg') := by { cases Hφ, cases Hψ, cases Hf₁, cases Hf₂, cases Hg₁, cases Hg₂, refl } lemma map_comp_map {V₁ V₂ V₃ W₁ W₂ W₃ : SemiNormedGroup} {f₁ f₂ f₃ g₁ g₂ g₃} {φ : V₁ ⟶ V₂} {ψ : W₁ ⟶ W₂} {φ' : V₂ ⟶ V₃} {ψ' : W₂ ⟶ W₃} (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) (hf' : φ' ≫ f₃ = f₂ ≫ ψ') (hg' : φ' ≫ g₃ = g₂ ≫ ψ') : map φ ψ hf hg ≫ map φ' ψ' hf' hg' = map (φ ≫ φ') (ψ ≫ ψ') (comm_sq₂ hf hf') (comm_sq₂ hg hg') := by { ext, refl } lemma map_id {J} [category J] {V W : SemiNormedGroup} (f g : V ⟶ W) : map (𝟙 V) (𝟙 W) (show 𝟙 V ≫ f = f ≫ 𝟙 W, by simp) (show 𝟙 V ≫ g = g ≫ 𝟙 W, by simp) = 𝟙 _ := by { ext, refl } lemma norm_map_le {V₁ V₂ W₁ W₂ : SemiNormedGroup} {f₁ f₂ g₁ g₂} {φ : V₁ ⟶ V₂} {ψ : W₁ ⟶ W₂} (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) (C : ℝ) (hφ : ∥ι f₁ g₁ ≫ φ∥ ≤ C) : ∥map φ ψ hf hg∥ ≤ C := normed_add_group_hom.equalizer.norm_map_le _ _ C hφ @[simps obj map] protected def F {J} [category J] {V W : J ⥤ SemiNormedGroup} (f g : V ⟶ W) : J ⥤ SemiNormedGroup := { obj := λ X, of ((f.app X).equalizer (g.app X)), map := λ X Y φ, equalizer.map (V.map φ) (W.map φ) (f.naturality _) (g.naturality _), map_id' := λ X, by simp only [category_theory.functor.map_id]; exact normed_add_group_hom.equalizer.map_id, map_comp' := λ X Y Z φ ψ, begin simp only [functor.map_comp], exact (map_comp_map _ _ _ _).symm end } @[simps] def map_nat {J} [category J] {V₁ V₂ W₁ W₂ : J ⥤ SemiNormedGroup} {f₁ f₂ g₁ g₂} (φ : V₁ ⟶ V₂) (ψ : W₁ ⟶ W₂) (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) : equalizer.F f₁ g₁ ⟶ equalizer.F f₂ g₂ := { app := λ X, equalizer.map (φ.app X) (ψ.app X) (by rw [← nat_trans.comp_app, ← nat_trans.comp_app, hf]) (by rw [← nat_trans.comp_app, ← nat_trans.comp_app, hg]), naturality' := λ X Y α, by simp only [equalizer.F_map, map_comp_map, nat_trans.naturality] } lemma map_nat_comp_map_nat {J} [category J] {V₁ V₂ V₃ W₁ W₂ W₃ : J ⥤ SemiNormedGroup} {f₁ f₂ f₃ g₁ g₂ g₃} {φ : V₁ ⟶ V₂} {ψ : W₁ ⟶ W₂} {φ' : V₂ ⟶ V₃} {ψ' : W₂ ⟶ W₃} (hf : φ ≫ f₂ = f₁ ≫ ψ) (hg : φ ≫ g₂ = g₁ ≫ ψ) (hf' : φ' ≫ f₃ = f₂ ≫ ψ') (hg' : φ' ≫ g₃ = g₂ ≫ ψ') : map_nat φ ψ hf hg ≫ map_nat φ' ψ' hf' hg' = map_nat (φ ≫ φ') (ψ ≫ ψ') (comm_sq₂ hf hf') (comm_sq₂ hg hg') := by { ext, refl } lemma map_nat_id {J} [category J] {V W : J ⥤ SemiNormedGroup} (f g : V ⟶ W) : map_nat (𝟙 V) (𝟙 W) (show 𝟙 V ≫ f = f ≫ 𝟙 W, by simp) (show 𝟙 V ≫ g = g ≫ 𝟙 W, by simp) = 𝟙 _ := by { ext, refl } end equalizer end SemiNormedGroup universe variable u variables (r : ℝ≥0) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)] variables (r' : ℝ≥0) [fact (0 < r')] [fact (r' ≤ 1)] variables (M M₁ M₂ M₃ : ProFiltPseuNormGrpWithTinv.{u} r') variables (c c₁ c₂ c₃ c₄ c₅ c₆ c₇ c₈ : ℝ≥0) (l m n : ℕ) variables (f : M₁ ⟶ M₂) (g : M₂ ⟶ M₃) def CLCTinv (r : ℝ≥0) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)] {A B : Profiniteᵒᵖ} (f g : A ⟶ B) : SemiNormedGroup := SemiNormedGroup.of $ normed_add_group_hom.equalizer ((CLC V).map f) ((CLC V).map g ≫ (CLC.T_inv r V).app B) namespace CLCTinv def ι (r : ℝ≥0) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)] {A B : Profiniteᵒᵖ} (f g : A ⟶ B) : CLCTinv r V f g ⟶ (CLC V).obj A := SemiNormedGroup.equalizer.ι _ _ lemma ι_range (r : ℝ≥0) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)] {A B : Profiniteᵒᵖ} (f g : A ⟶ B) : (ι r V f g).range = normed_add_group_hom.ker ((CLC V).map f - ((CLC V).map g ≫ (CLC.T_inv r V).app B)) := SemiNormedGroup.equalizer.ι_range _ _ lemma ι_range' (r : ℝ≥0) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)] {A B : Profiniteᵒᵖ} (f g : A ⟶ B) : (ι r V f g).range = normed_add_group_hom.ker (((CLC V).map g ≫ (CLC.T_inv r V).app B) - (CLC V).map f) := SemiNormedGroup.equalizer.ι_range' _ _ def map {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ : ϕ ≫ f₂ = f₁ ≫ ψ) (h₂ : ϕ ≫ g₂ = g₁ ≫ ψ) : CLCTinv r V f₁ g₁ ⟶ CLCTinv r V f₂ g₂ := SemiNormedGroup.equalizer.map ((CLC V).map ϕ) ((CLC V).map ψ) (by rw [← functor.map_comp, ← functor.map_comp, h₁]) $ by rw [← category.assoc, ← functor.map_comp, h₂, functor.map_comp, category.assoc, (CLC.T_inv _ _).naturality, category.assoc] lemma map_comp_ι {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ : ϕ ≫ f₂ = f₁ ≫ ψ) (h₂ : ϕ ≫ g₂ = g₁ ≫ ψ) : map r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂ ≫ ι r V _ _ = ι _ _ _ _ ≫ (CLC V).map ϕ := normed_add_group_hom.equalizer.ι_comp_map _ _ lemma map_norm_noninc {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ h₂) : (CLCTinv.map r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂).norm_noninc := equalizer.map_norm_noninc _ _ $ CLC.map_norm_noninc _ _ lemma norm_map_le {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ h₂) (C : ℝ≥0) (H : ∥SemiNormedGroup.equalizer.ι ((CLC V).map f₁) ((CLC V).map g₁ ≫ (CLC.T_inv r V).app B₁) ≫ (CLC V).map ϕ∥ ≤ C) : ∥CLCTinv.map r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂∥ ≤ C := SemiNormedGroup.equalizer.norm_map_le _ _ C H @[simp] lemma map_id {A B : Profiniteᵒᵖ} (f g : A ⟶ B) : map r V f g f g (𝟙 A) (𝟙 B) rfl rfl = 𝟙 _ := begin simp only [map, SemiNormedGroup.equalizer.map, category_theory.functor.map_id], exact equalizer.map_id, end lemma map_comp {A₁ A₂ A₃ B₁ B₂ B₃ : Profiniteᵒᵖ} {f₁ g₁ : A₁ ⟶ B₁} {f₂ g₂ : A₂ ⟶ B₂} {f₃ g₃ : A₃ ⟶ B₃} (ϕ₁ : A₁ ⟶ A₂) (ϕ₂ : A₂ ⟶ A₃) (ψ₁ : B₁ ⟶ B₂) (ψ₂ : B₂ ⟶ B₃) (h1 h2 h3 h4 h5 h6) : CLCTinv.map r V f₁ g₁ f₃ g₃ (ϕ₁ ≫ ϕ₂) (ψ₁ ≫ ψ₂) h1 h2 = CLCTinv.map r V f₁ g₁ f₂ g₂ ϕ₁ ψ₁ h3 h4 ≫ CLCTinv.map r V f₂ g₂ f₃ g₃ ϕ₂ ψ₂ h5 h6 := begin simp only [map, SemiNormedGroup.equalizer.map, category_theory.functor.map_comp], exact (equalizer.map_comp_map _ _ _ _).symm, end lemma map_comp_map {A₁ A₂ A₃ B₁ B₂ B₃ : Profiniteᵒᵖ} {f₁ g₁ : A₁ ⟶ B₁} {f₂ g₂ : A₂ ⟶ B₂} {f₃ g₃ : A₃ ⟶ B₃} (ϕ₁ : A₁ ⟶ A₂) (ϕ₂ : A₂ ⟶ A₃) (ψ₁ : B₁ ⟶ B₂) (ψ₂ : B₂ ⟶ B₃) (h₁ h₂ h₃ h₄) : CLCTinv.map r V f₁ g₁ f₂ g₂ ϕ₁ ψ₁ h₁ h₂ ≫ CLCTinv.map r V f₂ g₂ f₃ g₃ ϕ₂ ψ₂ h₃ h₄ = CLCTinv.map r V f₁ g₁ f₃ g₃ (ϕ₁ ≫ ϕ₂) (ψ₁ ≫ ψ₂) (comm_sq₂ h₁ h₃) (comm_sq₂ h₂ h₄) := (map_comp _ _ _ _ _ _ _ _ _ _ _ _).symm @[simps] def map_iso {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ≅ A₂) (ψ : B₁ ≅ B₂) (h₁ : ϕ.hom ≫ f₂ = f₁ ≫ ψ.hom) (h₂ : ϕ.hom ≫ g₂ = g₁ ≫ ψ.hom) : CLCTinv r V f₁ g₁ ≅ CLCTinv r V f₂ g₂ := { hom := map r V f₁ g₁ f₂ g₂ ϕ.hom ψ.hom h₁ h₂, inv := map r V f₂ g₂ f₁ g₁ ϕ.inv ψ.inv (by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, h₁]) (by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, h₂]), hom_inv_id' := by { simp only [map_comp_map, iso.hom_inv_id], apply map_id }, inv_hom_id' := by { simp only [map_comp_map, iso.inv_hom_id], apply map_id } } lemma map_iso_isometry {A₁ B₁ A₂ B₂ : Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ≅ A₂) (ψ : B₁ ≅ B₂) (h₁ : ϕ.hom ≫ f₂ = f₁ ≫ ψ.hom) (h₂ : ϕ.hom ≫ g₂ = g₁ ≫ ψ.hom) : isometry (map_iso r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂).hom := begin apply SemiNormedGroup.iso_isometry_of_norm_noninc; apply map_norm_noninc end @[simps] protected def F {J} [category J] (r : ℝ≥0) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)] {A B : J ⥤ Profiniteᵒᵖ} (f g : A ⟶ B) : J ⥤ SemiNormedGroup := { obj := λ X, CLCTinv r V (f.app X) (g.app X), map := λ X Y φ, map _ _ _ _ _ _ (A.map φ) (B.map φ) (f.naturality _) (g.naturality _), map_id' := λ X, by simp only [category_theory.functor.map_id]; apply map_id, map_comp' := λ X Y Z φ ψ, by simp only [functor.map_comp]; apply map_comp } theorem F_def {J} [category J] (r : ℝ≥0) (V : SemiNormedGroup) [normed_with_aut r V] [fact (0 < r)] {A B : J ⥤ Profiniteᵒᵖ} (f g : A ⟶ B) : CLCTinv.F r V f g = SemiNormedGroup.equalizer.F (whisker_right f (CLC V)) (whisker_right g (CLC V) ≫ whisker_left B (CLC.T_inv r V)) := rfl @[simps] def map_nat {J} [category J] {A₁ B₁ A₂ B₂ : J ⥤ Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ : ϕ ≫ f₂ = f₁ ≫ ψ) (h₂ : ϕ ≫ g₂ = g₁ ≫ ψ) : CLCTinv.F r V f₁ g₁ ⟶ CLCTinv.F r V f₂ g₂ := { app := λ X, map _ _ _ _ _ _ (ϕ.app X) (ψ.app X) (by rw [← nat_trans.comp_app, h₁, nat_trans.comp_app]) (by rw [← nat_trans.comp_app, h₂, nat_trans.comp_app]), naturality' := λ X Y α, by simp only [CLCTinv.F_map, map_comp_map, ϕ.naturality, ψ.naturality] } theorem map_nat_def {J} [category J] {A₁ B₁ A₂ B₂ : J ⥤ Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ⟶ A₂) (ψ : B₁ ⟶ B₂) (h₁ : ϕ ≫ f₂ = f₁ ≫ ψ) (h₂ : ϕ ≫ g₂ = g₁ ≫ ψ) : map_nat r V f₁ g₁ f₂ g₂ ϕ ψ h₁ h₂ = begin dsimp only [F_def], refine SemiNormedGroup.equalizer.map_nat (whisker_right ϕ (CLC V)) (whisker_right ψ (CLC V)) (by rw [← whisker_right_comp, ← whisker_right_comp, h₁]) (comm_sq₂ _ _).symm, { exact whisker_right ψ _ }, { rw [← whisker_right_comp, ← whisker_right_comp, h₂] }, ext x : 2, simp only [nat_trans.comp_app, whisker_left_app, whisker_right_app, (CLC.T_inv _ _).naturality], end := rfl . -- @[simps] def map_nat_iso {J} [category J] {A₁ B₁ A₂ B₂ : J ⥤ Profiniteᵒᵖ} (f₁ g₁ : A₁ ⟶ B₁) (f₂ g₂ : A₂ ⟶ B₂) (ϕ : A₁ ≅ A₂) (ψ : B₁ ≅ B₂) (h₁ : ϕ.hom ≫ f₂ = f₁ ≫ ψ.hom) (h₂ : ϕ.hom ≫ g₂ = g₁ ≫ ψ.hom) : CLCTinv.F r V f₁ g₁ ≅ CLCTinv.F r V f₂ g₂ := { hom := map_nat r V f₁ g₁ f₂ g₂ ϕ.hom ψ.hom h₁ h₂, inv := map_nat r V f₂ g₂ f₁ g₁ ϕ.inv ψ.inv (by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, h₁]) (by rw [iso.inv_comp_eq, ← category.assoc, iso.eq_comp_inv, h₂]), hom_inv_id' := begin simp only [map_nat_def, _root_.id, SemiNormedGroup.equalizer.map_nat_comp_map_nat, ← whisker_right_comp, iso.hom_inv_id, whisker_right_id', SemiNormedGroup.equalizer.map_nat_id], refl end, inv_hom_id' := begin simp only [map_nat_def, _root_.id, SemiNormedGroup.equalizer.map_nat_comp_map_nat, ← whisker_right_comp, iso.inv_hom_id, whisker_right_id', SemiNormedGroup.equalizer.map_nat_id], refl end, } end CLCTinv lemma aux (r' c c₂ : ℝ≥0) [r1 : fact (r' ≤ 1)] [h : fact (c₂ ≤ r' * c)] : fact (c₂ ≤ c) := ⟨h.1.trans $ (mul_le_mul' r1.1 le_rfl).trans (by simp)⟩ @[simps obj] def CLCFPTinv₂ (r : ℝ≥0) (V : SemiNormedGroup) (r' : ℝ≥0) [fact (0 < r)] [fact (0 < r')] [r1 : fact (r' ≤ 1)] [normed_with_aut r V] (c c₂ : ℝ≥0) [fact (c₂ ≤ r' * c)] (n : ℕ) : (ProFiltPseuNormGrpWithTinv r')ᵒᵖ ⥤ SemiNormedGroup := by haveI : fact (c₂ ≤ c) := aux r' c c₂; exact CLCTinv.F r V (nat_trans.op (FiltrationPow.Tinv r' c₂ c n)) (nat_trans.op (FiltrationPow.cast_le r' c₂ c n)) theorem CLCFPTinv₂_def (r : ℝ≥0) (V : SemiNormedGroup) (r' : ℝ≥0) [fact (0 < r)] [fact (0 < r')] [r1 : fact (r' ≤ 1)] [normed_with_aut r V] (c c₂ : ℝ≥0) [fact (c₂ ≤ r' * c)] (n : ℕ) : CLCFPTinv₂ r V r' c c₂ n = SemiNormedGroup.equalizer.F (CLCFP.Tinv V r' c c₂ n) (@CLCFP.res V r' c c₂ n (aux r' c c₂) ≫ CLCFP.T_inv r V r' c₂ n) := rfl instance CLCFPTinv₂.separated_space [fact (c₂ ≤ r' * c₁)] (M) : separated_space ((CLCFPTinv₂ r V r' c₁ c₂ n).obj M) := begin rw separated_iff_t2, refine @subtype.t2_space _ _ (id _) (id _), rw ← separated_iff_t2, apply uniform_space.completion.separated_space end instance CLCFPTinv₂.complete_space [fact (c₂ ≤ r' * c₁)] (M) : complete_space ((CLCFPTinv₂ r V r' c₁ c₂ n).obj M) := begin refine @is_closed.complete_space_coe _ (id _) (id _) _ _, { apply uniform_space.completion.complete_space }, { refine is_closed_eq _ continuous_const, apply normed_add_group_hom.continuous } end /-- The functor that sends `M` and `c` to `V-hat((filtration M c)^n)^{T⁻¹}`, defined by taking `T⁻¹`-invariants for two different actions by `T⁻¹`: * The first comes from the action of `T⁻¹` on `M`. * The second comes from the action of `T⁻¹` on `V`. We take the equalizer of those two actions. See the lines just above Definition 9.3 of [Analytic]. -/ def CLCFPTinv (r : ℝ≥0) (V : SemiNormedGroup) (r' : ℝ≥0) (c : ℝ≥0) (n : ℕ) [normed_with_aut r V] [fact (0 < r)] [fact (0 < r')] [fact (r' ≤ 1)] : (ProFiltPseuNormGrpWithTinv r')ᵒᵖ ⥤ SemiNormedGroup := CLCFPTinv₂ r V r' c (r' * c) n namespace CLCFPTinv₂ lemma map_norm_noninc [fact (c₂ ≤ r' * c)] [fact (c₂ ≤ c)] {M₁ M₂} (f : M₁ ⟶ M₂) : ((CLCFPTinv₂ r V r' c c₂ n).map f).norm_noninc := CLCTinv.map_norm_noninc _ _ _ _ _ _ _ _ _ _ def res [fact (c₂ ≤ r' * c₁)] [fact (c₂ ≤ c₁)] [fact (c₄ ≤ r' * c₃)] [fact (c₄ ≤ c₃)] [fact (c₃ ≤ c₁)] [fact (c₄ ≤ c₂)] : CLCFPTinv₂ r V r' c₁ c₂ n ⟶ CLCFPTinv₂ r V r' c₃ c₄ n := CLCTinv.map_nat r V _ _ _ _ (nat_trans.op (FiltrationPow.cast_le _ c₃ c₁ n)) (nat_trans.op (FiltrationPow.cast_le _ c₄ c₂ n)) rfl rfl @[simp] lemma res_refl [fact (c₂ ≤ r' * c₁)] [fact (c₂ ≤ c₁)] : res r V r' c₁ c₂ c₁ c₂ n = 𝟙 _ := by { simp only [res, FiltrationPow.cast_le_refl, nat_trans.op_id], ext x : 2, apply CLCTinv.map_id } lemma res_comp_res [fact (c₂ ≤ r' * c₁)] [fact (c₂ ≤ c₁)] [fact (c₄ ≤ r' * c₃)] [fact (c₄ ≤ c₃)] [fact (c₆ ≤ r' * c₅)] [fact (c₆ ≤ c₅)] [fact (c₃ ≤ c₁)] [fact (c₄ ≤ c₂)] [fact (c₅ ≤ c₃)] [fact (c₆ ≤ c₄)] [fact (c₅ ≤ c₁)] [fact (c₆ ≤ c₂)] : res r V r' c₁ c₂ c₃ c₄ n ≫ res r V r' c₃ c₄ c₅ c₆ n = res r V r' c₁ c₂ c₅ c₆ n := begin ext x : 2, simp only [res, nat_trans.comp_app], exact (CLCTinv.map_comp _ _ _ _ _ _ _ _ _ _ _ _).symm end lemma res_norm_noninc {_ : fact (c₂ ≤ r' * c₁)} {_ : fact (c₂ ≤ c₁)} {_ : fact (c₄ ≤ r' * c₃)} {_ : fact (c₄ ≤ c₃)} {_ : fact (c₃ ≤ c₁)} {_ : fact (c₄ ≤ c₂)} (M) : ((res r V r' c₁ c₂ c₃ c₄ n).app M).norm_noninc := CLCTinv.map_norm_noninc _ _ _ _ _ _ _ _ _ _ lemma norm_res_le [fact (c₂ ≤ r' * c₁)] [fact (c₂ ≤ c₁)] [fact (c₄ ≤ r' * c₃)] [fact (c₄ ≤ c₃)] [fact (c₃ ≤ c₁)] [fact (c₄ ≤ c₂)] (h₂₃ : c₂ = c₃) (M) : ∥(res r V r' c₁ c₂ c₃ c₄ n).app M∥ ≤ r := begin apply CLCTinv.norm_map_le, rw [← category.comp_id ((CLC V).map ((nat_trans.op (FiltrationPow.cast_le r' c₃ c₁ n)).app M))], have := nat_trans.congr_app (CLC.T r V).inv_hom_id ((FiltrationPow r' c₃ n).op.obj M), dsimp only [nat_trans.id_app] at this, rw [← this, CLC.T_inv_eq, nat_trans.comp_app, ← category.assoc ((CLC V).map _)], unfreezingI { subst c₃ }, rw [← SemiNormedGroup.equalizer.condition_assoc, ← category.assoc], refine normed_add_group_hom.norm_comp_le_of_le' 1 r r (mul_one ↑r).symm _ _, { apply CLC.norm_T_le }, { apply norm_noninc.norm_noninc_iff_norm_le_one.1, exact (CLC.map_norm_noninc V _).comp equalizer.ι_norm_noninc } end end CLCFPTinv₂ namespace CLCFPTinv lemma map_norm_noninc {M₁ M₂} (f : M₁ ⟶ M₂) : ((CLCFPTinv r V r' c n).map f).norm_noninc := CLCFPTinv₂.map_norm_noninc _ _ _ _ _ _ _ def res [fact (c₂ ≤ c₁)] : CLCFPTinv r V r' c₁ n ⟶ CLCFPTinv r V r' c₂ n := CLCFPTinv₂.res r V r' c₁ _ c₂ _ n @[simp] lemma res_refl : res r V r' c₁ c₁ n = 𝟙 _ := CLCFPTinv₂.res_refl _ _ _ _ _ _ lemma res_comp_res [fact (c₃ ≤ c₁)] [fact (c₅ ≤ c₃)] [fact (c₅ ≤ c₁)] : res r V r' c₁ c₃ n ≫ res r V r' c₃ c₅ n = res r V r' c₁ c₅ n := CLCFPTinv₂.res_comp_res _ _ _ _ _ _ _ _ _ _ lemma res_norm_noninc {_ : fact (c₂ ≤ c₁)} (M) : ((res r V r' c₁ c₂ n).app M).norm_noninc := CLCFPTinv₂.res_norm_noninc r V r' _ _ _ _ _ _ lemma norm_res_le [fact (c₂ ≤ c₁)] [fact (c₂ ≤ r' * c₁)] (M) : ∥(res r V r' c₁ c₂ n).app M∥ ≤ r := begin rw ← res_comp_res r V r' c₁ (r' * c₁) c₂, refine norm_comp_le_of_le' _ _ _ (one_mul ↑r).symm _ (CLCFPTinv₂.norm_res_le r V r' _ _ _ _ n rfl M), apply norm_noninc.norm_noninc_iff_norm_le_one.1, exact CLCTinv.map_norm_noninc r V _ _ _ _ _ _ _ _ end lemma norm_res_le_pow (N : ℕ) [fact (c₂ ≤ c₁)] [h : fact (c₂ ≤ r' ^ N * c₁)] (M) : ∥(res r V r' c₁ c₂ n).app M∥ ≤ (r ^ N) := begin unfreezingI { induction N with N ih generalizing c₁ c₂ }, { rw pow_zero, apply norm_noninc.norm_noninc_iff_norm_le_one.1, exact CLCTinv.map_norm_noninc r V _ _ _ _ _ _ _ _ }, haveI : fact (c₂ ≤ r' ^ N * c₁) := nnreal.fact_le_pow_mul_of_le_pow_succ_mul _ _ _, rw [pow_succ, mul_assoc] at h, resetI, rw [← res_comp_res r V r' c₁ (r' ^ N * c₁) c₂], exact norm_comp_le_of_le' _ _ _ (pow_succ _ _) (norm_res_le r V r' _ _ n M) (ih _ _) end end CLCFPTinv namespace breen_deligne open CLCFPTinv variables (M) {l m n} namespace universal_map variables (ϕ ψ : universal_map m n) def eval_CLCFPTinv₂ [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂] : CLCFPTinv₂ r V r' c₁ c₂ n ⟶ CLCFPTinv₂ r V r' c₃ c₄ m := begin dsimp only [CLCFPTinv₂_def], refine SemiNormedGroup.equalizer.map_nat (ϕ.eval_CLCFP _ _ _ _) (ϕ.eval_CLCFP _ _ _ _) (Tinv_comp_eval_CLCFP V r' c₁ c₂ c₃ c₄ ϕ).symm _, haveI : fact (c₂ ≤ c₁) := aux r' _ _, haveI : fact (c₄ ≤ c₃) := aux r' _ _, have h₁ := res_comp_eval_CLCFP V r' c₁ c₂ c₃ c₄ ϕ, have h₂ := T_inv_comp_eval_CLCFP r V r' c₂ c₄ ϕ, have := comm_sq₂ h₁ h₂, exact this.symm end @[simp] lemma eval_CLCFPTinv₂_zero [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] : (0 : universal_map m n).eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ = 0 := by { simp only [eval_CLCFPTinv₂, eval_CLCFP_zero], ext, refl } @[simp] lemma eval_CLCFPTinv₂_add [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂] [ψ.suitable c₃ c₁] [ψ.suitable c₄ c₂] : (ϕ + ψ : universal_map m n).eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ = ϕ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ + ψ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ := by { simp only [eval_CLCFPTinv₂, eval_CLCFP_add], ext, refl } @[simp] lemma eval_CLCFPTinv₂_sub [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂] [ψ.suitable c₃ c₁] [ψ.suitable c₄ c₂] : (ϕ - ψ : universal_map m n).eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ = ϕ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ - ψ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ := by { simp only [eval_CLCFPTinv₂, eval_CLCFP_sub], ext, refl } lemma eval_CLCFPTinv₂_comp {l m n : FreeMat} (f : l ⟶ m) (g : m ⟶ n) [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] [fact (c₆ ≤ r' * c₅)] [f.suitable c₅ c₃] [f.suitable c₆ c₄] [g.suitable c₃ c₁] [g.suitable c₄ c₂] : @eval_CLCFPTinv₂ r V _ _ r' _ _ c₁ c₂ c₅ c₆ _ _ (f ≫ g) _ _ (suitable.comp c₃) (suitable.comp c₄) = g.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄ ≫ f.eval_CLCFPTinv₂ r V r' c₃ c₄ c₅ c₆ := begin dsimp only [eval_CLCFPTinv₂, CLCFPTinv₂_def], delta id, simp only [SemiNormedGroup.equalizer.map_nat_comp_map_nat], generalize_proofs h1 h2 h3 h4 h5 h6 h7 h8, revert h5 h6 h7 h8, resetI, have H1 : eval_CLCFP V r' c₁ c₅ (f ≫ g) = eval_CLCFP V r' c₁ c₃ g ≫ eval_CLCFP V r' c₃ c₅ f := eval_CLCFP_comp V r' c₁ c₃ c₅ g f, have H2 : eval_CLCFP V r' c₂ c₆ (f ≫ g) = eval_CLCFP V r' c₂ c₄ g ≫ eval_CLCFP V r' c₄ c₆ f := eval_CLCFP_comp V r' c₂ c₄ c₆ g f, rw [H1, H2], intros, refl, end lemma res_comp_eval_CLCFPTinv₂ [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] [fact (c₆ ≤ r' * c₅)] [fact (c₈ ≤ r' * c₇)] [fact (c₂ ≤ c₁)] [fact (c₃ ≤ c₁)] [fact (c₄ ≤ c₂)] [fact (c₄ ≤ c₃)] [fact (c₆ ≤ c₅)] [fact (c₇ ≤ c₅)] [fact (c₈ ≤ c₆)] [fact (c₈ ≤ c₇)] [ϕ.suitable c₅ c₁] [ϕ.suitable c₆ c₂] [ϕ.suitable c₇ c₃] [ϕ.suitable c₈ c₄] : CLCFPTinv₂.res r V r' c₁ c₂ c₃ c₄ n ≫ ϕ.eval_CLCFPTinv₂ r V r' c₃ c₄ c₇ c₈ = ϕ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₅ c₆ ≫ CLCFPTinv₂.res r V r' c₅ c₆ c₇ c₈ m := begin dsimp only [CLCFPTinv₂.res, eval_CLCFPTinv₂, CLCFPTinv₂_def, CLCTinv.map_nat_def], delta id, simp only [SemiNormedGroup.equalizer.map_nat_comp_map_nat], congr' 1; { simp only [← CLCFP.res_def], apply res_comp_eval_CLCFP }, end lemma norm_eval_CLCFPTinv₂_le [fact (c₂ ≤ r' * c₁)] [fact (c₄ ≤ r' * c₃)] [ϕ.suitable c₃ c₁] [ϕ.suitable c₄ c₂] (N : ℕ) (h : ϕ.bound_by N) (M) : ∥(ϕ.eval_CLCFPTinv₂ r V r' c₁ c₂ c₃ c₄).app M∥ ≤ N := begin apply SemiNormedGroup.equalizer.norm_map_le, refine normed_add_group_hom.norm_comp_le_of_le' _ _ _ (mul_one _).symm _ _, { apply norm_eval_CLCFP_le, exact h }, { apply norm_noninc.norm_noninc_iff_norm_le_one.1, exact equalizer.ι_norm_noninc } end def eval_CLCFPTinv [ϕ.suitable c₂ c₁] : CLCFPTinv r V r' c₁ n ⟶ CLCFPTinv r V r' c₂ m := ϕ.eval_CLCFPTinv₂ r V r' c₁ _ c₂ _ lemma eval_CLCFPTinv_def [ϕ.suitable c₂ c₁] : ϕ.eval_CLCFPTinv r V r' c₁ c₂ = ϕ.eval_CLCFPTinv₂ r V r' c₁ _ c₂ _ := rfl @[simp] lemma eval_CLCFPTinv_zero : (0 : universal_map m n).eval_CLCFPTinv r V r' c₁ c₂ = 0 := by apply eval_CLCFPTinv₂_zero @[simp] lemma eval_CLCFPTinv_add [ϕ.suitable c₂ c₁] [ψ.suitable c₂ c₁] : (ϕ + ψ : universal_map m n).eval_CLCFPTinv r V r' c₁ c₂ = ϕ.eval_CLCFPTinv r V r' c₁ c₂ + ψ.eval_CLCFPTinv r V r' c₁ c₂ := eval_CLCFPTinv₂_add _ _ _ _ _ _ _ _ _ @[simp] lemma eval_CLCFPTinv_sub [ϕ.suitable c₂ c₁] [ψ.suitable c₂ c₁] : (ϕ - ψ : universal_map m n).eval_CLCFPTinv r V r' c₁ c₂ = ϕ.eval_CLCFPTinv r V r' c₁ c₂ - ψ.eval_CLCFPTinv r V r' c₁ c₂ := eval_CLCFPTinv₂_sub _ _ _ _ _ _ _ _ _ lemma eval_CLCFPTinv_comp {l m n : FreeMat} (f : l ⟶ m) (g : m ⟶ n) [hg : g.suitable c₂ c₁] [hf : f.suitable c₃ c₂] : @eval_CLCFPTinv r V _ _ r' _ _ c₁ c₃ _ _ (f ≫ g) (suitable.comp c₂) = g.eval_CLCFPTinv r V r' c₁ c₂ ≫ f.eval_CLCFPTinv r V r' c₂ c₃ := by apply eval_CLCFPTinv₂_comp lemma res_comp_eval_CLCFPTinv [fact (c₂ ≤ c₁)] [ϕ.suitable c₄ c₂] [ϕ.suitable c₃ c₁] [fact (c₄ ≤ c₃)] : res r V r' c₁ c₂ n ≫ ϕ.eval_CLCFPTinv r V r' c₂ c₄ = ϕ.eval_CLCFPTinv r V r' c₁ c₃ ≫ res r V r' c₃ c₄ m := by apply res_comp_eval_CLCFPTinv₂ lemma res_comp_eval_CLCFPTinv_absorb [fact (c₂ ≤ c₁)] [hϕ : ϕ.suitable c₃ c₂] : res r V r' c₁ c₂ n ≫ ϕ.eval_CLCFPTinv r V r' c₂ c₃ = @eval_CLCFPTinv r V _ _ r' _ _ c₁ c₃ _ _ ϕ (hϕ.le _ _ _ _ le_rfl (fact.out _)) := by rw [@res_comp_eval_CLCFPTinv r V _ _ r' _ _ c₁ c₂ c₃ c₃ _ _ ϕ (_root_.id _) (_root_.id _) (_root_.id _) (_root_.id _), res_refl, category.comp_id] lemma eval_CLCFPTinv_comp_res_absorb {_: fact (c₃ ≤ c₂)} [hϕ : ϕ.suitable c₂ c₁] : ϕ.eval_CLCFPTinv r V r' c₁ c₂ ≫ res r V r' c₂ c₃ m = @eval_CLCFPTinv r V _ _ r' _ _ c₁ c₃ _ _ ϕ (hϕ.le _ _ _ _ (fact.out _) le_rfl) := by rw [← @res_comp_eval_CLCFPTinv r V _ _ r' _ _ c₁ c₁ c₂ c₃ _ _ ϕ (_root_.id _) (_root_.id _) (_root_.id _) (_root_.id _), res_refl, category.id_comp] lemma norm_eval_CLCFPTinv_le [normed_with_aut r V] [fact (0 < r)] [ϕ.suitable c₂ c₁] (N : ℕ) (h : ϕ.bound_by N) (M) : ∥(ϕ.eval_CLCFPTinv r V r' c₁ c₂).app M∥ ≤ N := norm_eval_CLCFPTinv₂_le r V r' _ _ _ _ _ N h M lemma eval_CLCFPTinv_norm_noninc [normed_with_aut r V] [fact (0 < r)] [h : ϕ.very_suitable r r' c₂ c₁] (M) : ((ϕ.eval_CLCFPTinv r V r' c₁ c₂).app M).norm_noninc := begin apply norm_noninc.norm_noninc_iff_norm_le_one.2, have h' := h, unfreezingI { rcases h with ⟨N, k, c', hN, hϕ, hr, H⟩ }, haveI : fact (c' ≤ c₁) := ⟨H.trans $ fact.out _⟩, have aux := res_comp_eval_CLCFPTinv r V r' c₁ c' c₂ c₂ ϕ, rw [res_refl, category.comp_id] at aux, rw ← aux, refine le_trans _ hr, rw mul_comm, apply normed_add_group_hom.norm_comp_le_of_le, { apply_mod_cast norm_eval_CLCFPTinv_le, exact hN }, { haveI : fact (c' ≤ r' ^ k * c₁) := ⟨H⟩, rw nnreal.coe_pow, apply norm_res_le_pow }, end end universal_map end breen_deligne attribute [irreducible] CLCFPTinv₂ CLCFPTinv₂.res breen_deligne.universal_map.eval_CLCFPTinv₂
[STATEMENT] lemma supteq_not_supt_conv [simp]: "{\<unrhd>} - {\<rhd>} = Id" [PROOF STATE] proof (prove) goal (1 subgoal): 1. {\<unrhd>} - {\<rhd>} = Id [PROOF STEP] by auto
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import tidy.timing open tactic private lemma f : 1 = 1 := begin (time_tactic skip) >>= trace, simp end
{-# OPTIONS --safe --warning=error --without-K #-} open import LogicalFormulae module ClassicalLogic.ClassicalFive where em = {A : Set} → (A || (A → False)) dne = {A : Set} → ((A → False) → False) → A peirce = {A B : Set} → ((A → B) → A) → A iad = {A B : Set} → (A → B) → ((A → False) || B) dem = {A B : Set} → (((A → False) && (B → False)) → False) → A || B emToDne : em → dne emToDne em {A} pr with em {A} emToDne em {A} pr | inl x = x emToDne em {A} pr | inr x = exFalso (pr x) dneToPeirce : dne → peirce dneToPeirce dne {A} {B} aba = dne (λ z → z (aba (λ a → dne (λ _ → z a)))) peirceToIad : peirce → iad peirceToIad peirce {A} {B} aToB = peirce (λ z → inl (λ x → z (inr (aToB x)))) iadToDem : iad → dem iadToDem iad {A} {B} x with iad {A} {A} (λ i → i) iadToDem iad {A} {B} x | inl notA with iad {B} {B} (λ i → i) iadToDem iad {A} {B} x | inl notA | inl notB = exFalso (x (notA ,, notB)) iadToDem iad {A} {B} x | inl notA | inr b = inr b iadToDem iad {A} {B} x | inr a = inl a demToEm : dem → em demToEm dem {A} = dem (λ z → _&&_.snd z (_&&_.fst z))
From machine_program_logic.program_logic Require Import weakestpre. From HypVeri Require Import lifting rules.rules_base stdpp_extra. From HypVeri.algebra Require Import base reg mem pagetable trans mailbox base_extra. From HypVeri.lang Require Import lang_extra mem_extra reg_extra pagetable_extra trans_extra. Section mem_relinquish. Context `{hypparams: HypervisorParameters}. Context `{vmG: !gen_VMG Σ}. Lemma p_relinquish_inv_consist σ h i j ps tt: inv_trans_pgt_consistent σ -> inv_trans_ps_disj σ -> σ.2 !! h = Some (Some (j, i, ps, tt, true)) -> j ≠ i -> inv_trans_pgt_consistent (update_page_table_global revoke_access (update_transaction σ h (j, i, ps, tt, false)) i ps). Proof. intros Hinv_con Hinv_disj Hlk Hneq_i. rewrite /inv_trans_pgt_consistent /inv_trans_pgt_consistent' /=. rewrite map_Forall_lookup. intros h' meta Hlookup'. rewrite lookup_insert_Some in Hlookup'. destruct Hlookup' as [[<- <-]|[Hneq Hlookup']]. { intros p Hin. specialize (Hinv_con h _ Hlk p Hin). simpl in Hinv_con. generalize dependent σ.1.1.1.2. generalize dependent σ.2. induction ps using set_ind_L . - set_solver + Hin. - intros tran Htran pgt Hpgt. simpl. rewrite set_fold_disj_union_strong. { rewrite set_fold_singleton. destruct (decide (x = p)). { subst. destruct tt;first done. rewrite Hpgt. apply p_upd_pgt_pgt_not_elem. done. rewrite lookup_insert_Some. left. split;auto. assert (Hrw: {[j;i]} ∖ {[i]} = ({[j]} : gset _)). set_solver + Hneq_i. rewrite /revoke_access Hrw //. rewrite Hpgt. apply p_upd_pgt_pgt_not_elem. done. rewrite lookup_insert_Some. left. split;auto. assert (Hrw: {[i]} ∖ {[i]} = (∅ : gset _)). set_solver +. rewrite /revoke_access Hrw //. } { destruct (pgt !! x). { feed specialize IHps. set_solver + Hin n. apply (IHps (<[h := Some (j, i, X, tt, true)]>tran));eauto. rewrite lookup_insert //. rewrite lookup_insert_ne //. } { feed specialize IHps. set_solver + Hin n. apply (IHps (<[h := Some (j, i, X, tt, true)]>tran));eauto. rewrite lookup_insert //. } } } apply upd_is_strong_assoc_comm. set_solver + H0. } { rewrite /inv_trans_pgt_consistent /inv_trans_pgt_consistent' /= in Hinv_con. specialize (Hinv_con h' meta Hlookup'). simpl in Hinv_con. destruct meta as [[[[[sv rv] ps'] tt'] b]|];last done. simpl in *. intros p Hin. specialize (Hinv_con p Hin). assert (p ∉ ps). { intro. specialize (Hinv_disj h' _ Hlookup'). simpl in Hinv_disj. pose proof (elem_of_pages_in_trans' p (delete h' σ.2)) as [_ Hin']. feed specialize Hin'. exists h. eexists. split. rewrite lookup_delete_ne //. done. set_solver + Hin H0 Hin' Hinv_disj. } destruct tt',b;auto;try apply p_upd_pgt_pgt_not_elem;auto. } Qed. Lemma mem_relinquish {tt wi sacc i j q p_tx} {ps: gset PID} ai r0 wh: (* has access to the page which the instruction is in *) tpa ai ≠ p_tx -> tpa ai ∈ sacc -> (* current instruction is hvc *) decode_instruction wi = Some(Hvc) -> (* the hvc call to invoke is relinquish *) decode_hvc_func r0 = Some(Relinquish) -> {SS{{(* the encoding of instruction wi is stored in location ai *) ▷(PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗ ▷ (R0 @@ i ->r r0) ∗ ▷ (R1 @@ i ->r wh) ∗ (* the pagetable, the owership ra is not required *) ▷ i -@A> sacc ∗ (* the descriptor is ready in the tx page *) ▷ TX@ i := p_tx ∗ (* is the receiver and the transaction has been retrieved *) ▷ wh -{q}>t (j, i, ps, tt) ∗ ▷ wh ->re true }}} ExecI @ i {{{ RET (false, ExecI) ; (* PC is incremented *) PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗ (* donesn't have access to psd anymore *) i -@A> (sacc ∖ ps) ∗ (* return Succ to R0 *) R0 @@ i ->r (encode_hvc_ret_code Succ) ∗ R1 @@ i ->r wh ∗ (* the same tx *) TX@ i := p_tx ∗ (* the transaction is marked as unretrieved *) wh -{q}>t(j, i, ps, tt) ∗ wh ->re false }}}. Proof. iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Φ) "(>PC & >mem_ins & >R0 & >R1 & >acc & >tx & >tran & >re) HΦ". iApply (sswp_lift_atomic_step ExecI);[done|]. iIntros (n σ1) "%Hsche state". rewrite /scheduled /= /scheduler in Hsche. assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. } clear Hsche. iModIntro. iDestruct "state" as "(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl & trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)". (* valid regs *) iDestruct ((gen_reg_valid3 i PC ai R0 r0 R1 wh Heq_cur) with "regs PC R0 R1") as "(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1)";eauto. (* valid pt *) iDestruct (access_agree_check_true (tpa ai) i with "pgt_acc acc") as %Hcheckpg_ai;eauto. (* valid mem *) iDestruct (gen_mem_valid ai wi with "mem mem_ins") as %Hlookup_ai. (* valid tx rx *) iDestruct (mb_valid_tx i p_tx with "mb tx") as %Heq_tx. (* valid trans *) iDestruct (trans_valid_Some with "trans tran") as %[re Hlookup_tran]. iDestruct (trans_valid_handle_Some with "tran") as %Hvalid_handle. iDestruct (retri_valid_Some with "retri re") as %[meta Hlookup_tran']. rewrite Hlookup_tran in Hlookup_tran'. inversion Hlookup_tran'. subst re. clear meta Hlookup_tran' H1. iSplit. - (* reducible *) iPureIntro. apply (reducible_normal i Hvc ai wi);eauto. rewrite Heq_tx //. - iModIntro. iIntros (m2 σ2) "vmprop_auth %HstepP". iFrame "vmprop_auth". apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto. 2: rewrite Heq_tx //. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /get_transaction /= Hlookup_tran Heq_cur /= in Heqc2. case_bool_decide;last done. clear H0. simpl in Heqc2. case_bool_decide;last done. clear H0. destruct HstepP;subst m2 σ2; subst c2; simpl. rewrite /gen_vm_interp. (* unchanged part *) rewrite (preserve_get_rx_gmap σ1). 2: rewrite p_upd_pc_mb //. rewrite (preserve_get_mb_gmap σ1). 2: rewrite p_upd_pc_mb //. rewrite p_upd_pc_mem p_upd_reg_mem p_rvk_acc_mem p_upd_tran_mem. iFrame "Hnum mem mb rx_state". (* upd regs *) rewrite (u_upd_pc_regs _ i ai). 2: done. 2: { rewrite u_upd_reg_regs p_rvk_acc_current_vm p_upd_tran_current_vm. rewrite (preserve_get_reg_gmap σ1). rewrite lookup_insert_ne. solve_reg_lookup. done. f_equal. } rewrite u_upd_reg_regs p_rvk_acc_current_vm p_upd_tran_current_vm Heq_cur. rewrite (preserve_get_reg_gmap σ1);last done. iDestruct ((gen_reg_update2_global PC i _ (ai ^+ 1)%f R0 i _ (encode_hvc_ret_code Succ)) with "regs PC R0") as ">[$ [PC R0]]";eauto. (* upd pgt *) rewrite (preserve_get_own_gmap (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, false)) i ps) (update_incr_PC _)). 2: rewrite p_upd_pc_pgt p_upd_reg_pgt //. rewrite p_rvk_acc_own. rewrite (preserve_get_own_gmap σ1);last done. iFrame "pgt_owned". rewrite (preserve_get_access_gmap (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, true)) i ps) (update_incr_PC _)). 2: rewrite p_upd_pc_pgt p_upd_reg_pgt //. iDestruct (access_agree with "pgt_acc acc") as %Hlookup_pgt_acc. rewrite (u_rvk_acc_acc _ _ _ sacc). 2: { rewrite p_upd_tran_pgt. intros p Hin_p. specialize (Hconsis wh _ Hlookup_tran p Hin_p). simpl in Hconsis. destruct tt. done. eexists;eauto. eexists;eauto. } 2: rewrite (preserve_get_access_gmap σ1);done. rewrite (preserve_get_access_gmap σ1);last done. iDestruct (access_update (sacc∖ ps) with "pgt_acc acc") as ">[$ acc]". done. rewrite (preserve_get_excl_gmap (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, false)) i ps) (update_incr_PC _)). 2: rewrite p_upd_pc_pgt p_upd_reg_pgt //. rewrite (p_rvk_acc_excl _ _ j tt). 2: { intros p Hin. specialize (Hconsis wh _ Hlookup_tran p Hin). destruct tt; simpl in Hconsis. done. rewrite p_upd_tran_pgt //. rewrite p_upd_tran_pgt //. } rewrite (preserve_get_excl_gmap σ1);last done. iFrame "pgt_excl". (* upd tran *) rewrite (preserve_get_trans_gmap (update_transaction σ1 wh (j, i, ps, tt, false)) (update_incr_PC _)). 2: rewrite p_upd_pc_trans p_upd_reg_trans //. rewrite u_upd_tran_trans. rewrite insert_id. 2: rewrite /get_trans_gmap /get_transactions_gmap lookup_fmap Hlookup_tran //=. iFrame "trans". (* upd hp *) rewrite (preserve_get_hpool_gset (update_transaction σ1 wh (j, i, ps, tt, false)) (update_incr_PC _)). 2: rewrite p_upd_pc_trans p_upd_reg_trans //. rewrite p_upd_tran_hp. iFrame "hpool". (* upd retri *) rewrite (preserve_get_retri_gmap (update_transaction σ1 wh (j, i, ps, tt, false)) (update_incr_PC _)). 2: rewrite p_upd_pc_trans p_upd_reg_trans //. 2: { exists (Some (j, i, ps, tt, true)). split;eauto. } rewrite u_upd_tran_retri. iDestruct (retri_update_flip with "retri re") as ">[$ re]". (* inv_trans_wellformed *) rewrite (preserve_inv_trans_wellformed (update_transaction σ1 wh (j, i, ps, tt, false))). 2: rewrite p_upd_pc_trans p_upd_reg_trans //. iAssert (⌜inv_trans_wellformed (update_transaction σ1 wh (j, i, ps, tt, false))⌝%I) as "$". iPureIntro. apply (p_upd_tran_inv_wf σ1 wh);eauto. (* inv_trans_pgt_consistent *) rewrite (preserve_inv_trans_pgt_consistent (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, false)) i ps) (update_incr_PC _)). 2: rewrite p_upd_pc_trans p_upd_reg_trans //. 2: rewrite p_upd_pc_pgt p_upd_reg_pgt //. iAssert (⌜inv_trans_pgt_consistent (update_page_table_global revoke_access (update_transaction σ1 wh (j, i, ps, tt, false)) i ps)⌝%I) as "$". iPureIntro. apply p_relinquish_inv_consist;auto. { destruct Hwf as [_ [Hwf _]]. specialize (Hwf wh _ Hlookup_tran). done. } (* inv_trans_ps_disj *) rewrite (preserve_inv_trans_ps_disj (update_transaction σ1 wh (j, i, ps, tt, false))). 2: rewrite p_upd_pc_trans p_upd_reg_trans //. iAssert (⌜inv_trans_ps_disj (update_transaction σ1 wh (j, i, ps, tt, false))⌝%I) as "$". iPureIntro. eapply p_upd_tran_inv_disj. apply Hdisj. exact Hlookup_tran. done. (* just_scheduled *) iModIntro. rewrite /just_scheduled_vms /just_scheduled. rewrite /scheduled /machine.scheduler /= /scheduler. rewrite p_upd_pc_current_vm p_upd_reg_current_vm p_rvk_acc_current_vm p_upd_tran_current_vm. rewrite Heq_cur. iSplitL "". set fl := (filter _ _). assert (fl = []) as ->. { rewrite /fl. induction n. - simpl. rewrite filter_nil //=. - rewrite seq_S. rewrite filter_app. rewrite IHn. simpl. rewrite filter_cons_False /=. rewrite filter_nil //. rewrite andb_negb_l //. } by iSimpl. (* Φ *) case_bool_decide;last contradiction. simpl. iApply "HΦ". rewrite /fresh_handles. iFrame. Qed. Lemma mem_relinquish_invalid_handle {E i wi sacc r0 r2 wh p_tx} ai: tpa ai ≠ p_tx -> (tpa ai) ∈ sacc -> (* the current instruction is hvc *) (* the decoding of wi is correct *) decode_instruction wi = Some(Hvc) -> (* the hvc call to invoke is retrieve *) decode_hvc_func r0 = Some(Relinquish) -> wh ∉ valid_handles -> {SS{{(* the encoding of instruction wi is stored in location ai *) ▷ (PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗ (* registers *) ▷ (R0 @@ i ->r r0) ∗ ▷ (R1 @@ i ->r wh) ∗ ▷ (R2 @@ i ->r r2) ∗ ▷ i -@A> sacc ∗ ▷ TX@ i := p_tx}}} ExecI @ i; E {{{ RET (false, ExecI) ; (* PC is incremented *) PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗ R0 @@ i ->r (encode_hvc_ret_code Error) ∗ R1 @@ i ->r wh ∗ R2 @@ i ->r (encode_hvc_error InvParam) ∗ i -@A> sacc ∗ TX@ i := p_tx }}}. Proof. iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Hnin_wh Φ) "(>PC & >mem_ins & >R0 & >R1 & >R2 & >acc & >tx) HΦ". iApply (sswp_lift_atomic_step ExecI);[done|]. iIntros (n σ1) "%Hsche state". rewrite /scheduled /= /scheduler in Hsche. assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. } clear Hsche. iModIntro. iDestruct "state" as "(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl & trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)". (* valid regs *) iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 wh R2 r2 Heq_cur) with "regs PC R0 R1 R2") as "(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)";eauto. (* valid pt *) iDestruct (access_agree_check_true (tpa ai) i with "pgt_acc acc") as %Hcheckpg_ai;eauto. (* valid mem *) iDestruct (gen_mem_valid ai wi with "mem mem_ins") as %Hlookup_ai. (* valid tx *) iDestruct (mb_valid_tx i p_tx with "mb tx") as %Heq_tx. (* valid tran *) iSplit. - (* reducible *) iPureIntro. apply (reducible_normal i Hvc ai wi);auto. rewrite Heq_tx //. - iModIntro. iIntros (m2 σ2) "vmprop_auth %HstepP". iFrame "vmprop_auth". apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto. 2: rewrite Heq_tx //. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /= in Heqc2. assert (Hwh_None: get_transaction σ1 wh = None). { destruct Hwf as [_ [_ Hwf]]. rewrite /inv_finite_handles in Hwf. rewrite Hwf in Hnin_wh. rewrite not_elem_of_dom in Hnin_wh. rewrite /get_transaction Hnin_wh //. case_bool_decide;done. } rewrite Hwh_None /= in Heqc2. destruct HstepP;subst m2 σ2; subst c2; simpl. iDestruct (hvc_error_update (E:= E) InvParam with "PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]") as ">[[$ $] ?]". 1-4: auto. iPureIntro. auto. rewrite /scheduled /machine.scheduler /= /scheduler. rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur. case_bool_decide;last contradiction. simpl. iApply "HΦ". iFrame. by iFrame. Qed. Lemma mem_relinquish_fresh_handle {E i wi sacc r0 r2 wh sh q p_tx} ai: tpa ai ≠ p_tx -> (tpa ai) ∈ sacc -> decode_instruction wi = Some(Hvc) -> decode_hvc_func r0 = Some(Relinquish) -> wh ∈ sh -> {SS{{▷ (PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗ ▷ (R0 @@ i ->r r0) ∗ ▷ (R1 @@ i ->r wh) ∗ ▷ (R2 @@ i ->r r2) ∗ ▷ i -@A> sacc ∗ ▷ TX@ i := p_tx ∗ ▷ fresh_handles q sh}}} ExecI @ i; E {{{ RET (false, ExecI) ; PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗ R0 @@ i ->r (encode_hvc_ret_code Error) ∗ R1 @@ i ->r wh ∗ R2 @@ i ->r (encode_hvc_error InvParam) ∗ i -@A> sacc ∗ TX@ i := p_tx ∗ fresh_handles q sh }}}. Proof. iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Hin_wh Φ) "(>PC & >mem_ins & >R0 & >R1 & >R2 & >acc & >tx & >[hp handles]) HΦ". iApply (sswp_lift_atomic_step ExecI);[done|]. iIntros (n σ1) "%Hsche state". rewrite /scheduled /= /scheduler in Hsche. assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. } clear Hsche. iModIntro. iDestruct "state" as "(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl & trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)". (* valid regs *) iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 wh R2 r2 Heq_cur) with "regs PC R0 R1 R2") as "(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)";eauto. (* valid pt *) iDestruct (access_agree_check_true (tpa ai) i with "pgt_acc acc") as %Hcheckpg_ai;eauto. (* valid mem *) iDestruct (gen_mem_valid ai wi with "mem mem_ins") as %Hlookup_ai. (* valid tx *) iDestruct (mb_valid_tx i p_tx with "mb tx") as %Heq_tx. (* valid hpool *) iDestruct (hpool_valid with "hpool hp") as %Heq_hp. (* valid tran *) iAssert (⌜get_transaction σ1 wh = None⌝%I) as %Hwh_None. { iDestruct (big_sepS_elem_of _ _ wh with "handles") as "[tran _]". done. iDestruct (trans_valid_None with "trans tran") as %Hlookup_tran. iPureIntro. rewrite /get_transaction Hlookup_tran //. case_bool_decide;done. } iSplit. - (* reducible *) iPureIntro. apply (reducible_normal i Hvc ai wi);auto. rewrite Heq_tx //. - iModIntro. iIntros (m2 σ2) "vmprop_auth %HstepP". iFrame "vmprop_auth". apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto. 2: rewrite Heq_tx //. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /= in Heqc2. rewrite Hwh_None /= in Heqc2. destruct HstepP;subst m2 σ2; subst c2; simpl. iDestruct (hvc_error_update (E:= E) InvParam with "PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]") as ">[[$ $] ?]". 1-4: auto. iPureIntro. auto. rewrite /scheduled /machine.scheduler /= /scheduler. rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur. case_bool_decide;last contradiction. simpl. iApply "HΦ". iFrame. by iFrame. Qed. Lemma mem_relinquish_invalid_trans {E i wi sacc r0 r2 wh meta q p_tx} ai: tpa ai ≠ p_tx -> (tpa ai) ∈ sacc -> decode_instruction wi = Some(Hvc) -> decode_hvc_func r0 = Some(Relinquish) -> meta.1.1.2 ≠ i -> {SS{{▷ (PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗ ▷ (R0 @@ i ->r r0) ∗ ▷ (R1 @@ i ->r wh) ∗ ▷ (R2 @@ i ->r r2) ∗ ▷ i -@A> sacc ∗ ▷ TX@ i := p_tx ∗ ▷ wh -{q}>t (meta) }}} ExecI @ i; E {{{ RET (false, ExecI) ; PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗ R0 @@ i ->r (encode_hvc_ret_code Error) ∗ R1 @@ i ->r wh ∗ R2 @@ i ->r (encode_hvc_error Denied) ∗ i -@A> sacc ∗ TX@ i := p_tx ∗ wh -{q}>t (meta) }}}. Proof. iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Hin_wh Φ) "(>PC & >mem_ins & >R0 & >R1 & >R2 & >acc & >tx & >tran) HΦ". iApply (sswp_lift_atomic_step ExecI);[done|]. iIntros (n σ1) "%Hsche state". rewrite /scheduled /= /scheduler in Hsche. assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. } clear Hsche. iModIntro. iDestruct "state" as "(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl & trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)". (* valid regs *) iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 wh R2 r2 Heq_cur) with "regs PC R0 R1 R2") as "(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)";eauto. (* valid pt *) iDestruct (access_agree_check_true (tpa ai) i with "pgt_acc acc") as %Hcheckpg_ai;eauto. (* valid mem *) iDestruct (gen_mem_valid ai wi with "mem mem_ins") as %Hlookup_ai. (* valid tx *) iDestruct (mb_valid_tx i p_tx with "mb tx") as %Heq_tx. (* valid tran *) iDestruct (trans_valid_Some with "trans tran") as %[? Hlookup_tran]. iDestruct (trans_valid_handle_Some with "tran") as %Hvalid_handle. iSplit. - (* reducible *) iPureIntro. apply (reducible_normal i Hvc ai wi);auto. rewrite Heq_tx //. - iModIntro. iIntros (m2 σ2) "vmprop_auth %HstepP". iFrame "vmprop_auth". apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto. 2: rewrite Heq_tx //. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /= in Heqc2. rewrite /get_transaction Hlookup_tran /= in Heqc2. destruct meta as [[[? ?] ?] ?]. case_bool_decide;last contradiction. clear H0. simpl in Heqc2. case_bool_decide;rewrite Heq_cur // in H0. rewrite andb_false_r /= in Heqc2. destruct HstepP;subst m2 σ2; subst c2; simpl. iDestruct (hvc_error_update (E:= E) Denied with "PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]") as ">[[$ $] ?]". 1-4: auto. iPureIntro. auto. rewrite /scheduled /machine.scheduler /= /scheduler. rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur. case_bool_decide;last contradiction. simpl. iApply "HΦ". iFrame. by iFrame. Qed. Lemma mem_relinquish_not_retrieved{E i wi sacc r0 r2 wh q p_tx} ai: tpa ai ≠ p_tx -> (tpa ai) ∈ sacc -> decode_instruction wi = Some(Hvc) -> decode_hvc_func r0 = Some(Relinquish) -> {SS{{▷ (PC @@ i ->r ai) ∗ ▷ ai ->a wi ∗ ▷ (R0 @@ i ->r r0) ∗ ▷ (R1 @@ i ->r wh) ∗ ▷ (R2 @@ i ->r r2) ∗ ▷ i -@A> sacc ∗ ▷ TX@ i := p_tx ∗ ▷ wh -{q}>re false }}} ExecI @ i; E {{{ RET (false, ExecI) ; PC @@ i ->r (ai ^+ 1)%f ∗ ai ->a wi ∗ R0 @@ i ->r (encode_hvc_ret_code Error) ∗ R1 @@ i ->r wh ∗ R2 @@ i ->r (encode_hvc_error Denied) ∗ i -@A> sacc ∗ TX@ i := p_tx ∗ wh -{q}>re false }}}. Proof. iIntros (Hneq_tx Hin_acc Hdecode_i Hdecode_f Φ) "(>PC & >mem_ins & >R0 & >R1 & >R2 & >acc & >tx & >re) HΦ". iApply (sswp_lift_atomic_step ExecI);[done|]. iIntros (n σ1) "%Hsche state". rewrite /scheduled /= /scheduler in Hsche. assert (σ1.1.1.2 = i) as Heq_cur. { case_bool_decide;last done. by apply fin_to_nat_inj. } clear Hsche. iModIntro. iDestruct "state" as "(Hnum & mem & regs & mb & rx_state & pgt_owned & pgt_acc & pgt_excl & trans & hpool & retri & %Hwf & %Hdisj & %Hconsis)". (* valid regs *) iDestruct ((gen_reg_valid4 i PC ai R0 r0 R1 wh R2 r2 Heq_cur) with "regs PC R0 R1 R2") as "(%Hlookup_PC & %Hlookup_R0 & %Hlookup_R1 & %Hlookup_R2)";eauto. (* valid pt *) iDestruct (access_agree_check_true (tpa ai) i with "pgt_acc acc") as %Hcheckpg_ai;eauto. (* valid mem *) iDestruct (gen_mem_valid ai wi with "mem mem_ins") as %Hlookup_ai. (* valid tx *) iDestruct (mb_valid_tx i p_tx with "mb tx") as %Heq_tx. (* valid tran *) iDestruct (retri_valid_Some with "retri re") as %[? Hlookup_re]. iDestruct (retri_valid_handle_Some with "re") as %Hvalid_handle. iSplit. - (* reducible *) iPureIntro. apply (reducible_normal i Hvc ai wi);auto. rewrite Heq_tx //. - iModIntro. iIntros (m2 σ2) "vmprop_auth %HstepP". iFrame "vmprop_auth". apply (step_ExecI_normal i Hvc ai wi) in HstepP;eauto. 2: rewrite Heq_tx //. remember (exec Hvc σ1) as c2 eqn:Heqc2. rewrite /exec /hvc Hlookup_R0 /= Hdecode_f /relinquish Hlookup_R1 /= in Heqc2. rewrite /get_transaction Hlookup_re /= in Heqc2. destruct x as [[[? ?] ?] ?]. assert (Heq_c2 : (m2,σ2) = (ExecI, update_incr_PC (update_reg (update_reg σ1 R0 (encode_hvc_ret_code Error)) R2 (encode_hvc_error Denied)))). { case_bool_decide;last contradiction. destruct HstepP;subst m2 σ2; subst c2; done. } inversion Heq_c2. clear H1 H2 Heq_c2 Heqc2. iDestruct (hvc_error_update (E:= E) Denied with "PC R0 R2 [$Hnum $mem $regs $mb $rx_state $pgt_owned $pgt_acc $pgt_excl $ trans $hpool $retri]") as ">[[$ $] ?]". 1-4: auto. iPureIntro. auto. rewrite /scheduled /machine.scheduler /= /scheduler. rewrite p_upd_pc_current_vm 2!p_upd_reg_current_vm Heq_cur. case_bool_decide;last contradiction. simpl. iApply "HΦ". iFrame. by iFrame. Qed. End mem_relinquish.
section \<open>Derived facts about quantum registers\<close> theory Quantum_Extra imports Laws_Quantum Quantum begin no_notation meet (infixl "\<sqinter>\<index>" 70) no_notation Group.mult (infixl "\<otimes>\<index>" 70) no_notation Order.top ("\<top>\<index>") unbundle lattice_syntax unbundle register_notation unbundle cblinfun_notation lemma zero_not_register[simp]: \<open>~ register (\<lambda>_. 0)\<close> unfolding register_def by simp lemma register_pair_is_register_converse: \<open>register (F;G) \<Longrightarrow> register F\<close> \<open>register (F;G) \<Longrightarrow> register G\<close> using [[simproc del: Laws_Quantum.compatibility_warn]] apply (cases \<open>register F\<close>) apply (auto simp: register_pair_def)[2] apply (cases \<open>register G\<close>) by (auto simp: register_pair_def)[2] lemma register_id'[simp]: \<open>register (\<lambda>x. x)\<close> using register_id by (simp add: id_def) lemma register_projector: assumes "register F" assumes "is_Proj a" shows "is_Proj (F a)" using assms unfolding register_def is_Proj_algebraic by metis lemma register_unitary: assumes "register F" assumes "unitary a" shows "unitary (F a)" using assms by (smt (verit, best) register_def unitary_def) lemma compatible_proj_intersect: (* I think this also holds without is_Proj premises, but my proof ideas use the Penrose-Moore pseudoinverse or simultaneous diagonalization and we do not have an existence theorem for either. *) assumes "compatible R S" and "is_Proj a" and "is_Proj b" shows "(R a *\<^sub>S \<top>) \<sqinter> (S b *\<^sub>S \<top>) = ((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>)" proof (rule antisym) have "((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>) \<le> (S b *\<^sub>S \<top>)" apply (subst swap_registers[OF assms(1)]) by (simp add: cblinfun_compose_image cblinfun_image_mono) moreover have "((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>) \<le> (R a *\<^sub>S \<top>)" by (simp add: cblinfun_compose_image cblinfun_image_mono) ultimately show \<open>((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>) \<le> (R a *\<^sub>S \<top>) \<sqinter> (S b *\<^sub>S \<top>)\<close> by auto have "is_Proj (R a)" using assms(1) assms(2) compatible_register1 register_projector by blast have "is_Proj (S b)" using assms(1) assms(3) compatible_register2 register_projector by blast show \<open>(R a *\<^sub>S \<top>) \<sqinter> (S b *\<^sub>S \<top>) \<le> (R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>\<close> proof (unfold less_eq_ccsubspace.rep_eq, rule) fix \<psi> assume asm: \<open>\<psi> \<in> space_as_set ((R a *\<^sub>S \<top>) \<sqinter> (S b *\<^sub>S \<top>))\<close> then have \<open>\<psi> \<in> space_as_set (R a *\<^sub>S \<top>)\<close> by auto then have R: \<open>R a *\<^sub>V \<psi> = \<psi>\<close> using \<open>is_Proj (R a)\<close> cblinfun_fixes_range is_Proj_algebraic by blast from asm have \<open>\<psi> \<in> space_as_set (S b *\<^sub>S \<top>)\<close> by auto then have S: \<open>S b *\<^sub>V \<psi> = \<psi>\<close> using \<open>is_Proj (S b)\<close> cblinfun_fixes_range is_Proj_algebraic by blast from R S have \<open>\<psi> = (R a o\<^sub>C\<^sub>L S b) *\<^sub>V \<psi>\<close> by (simp add: cblinfun_apply_cblinfun_compose) also have \<open>\<dots> \<in> space_as_set ((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>)\<close> apply simp by (metis R S calculation cblinfun_apply_in_image) finally show \<open>\<psi> \<in> space_as_set ((R a o\<^sub>C\<^sub>L S b) *\<^sub>S \<top>)\<close> by - qed qed lemma compatible_proj_mult: assumes "compatible R S" and "is_Proj a" and "is_Proj b" shows "is_Proj (R a o\<^sub>C\<^sub>L S b)" using [[simproc del: Laws_Quantum.compatibility_warn]] using assms unfolding is_Proj_algebraic compatible_def apply auto apply (metis (no_types, lifting) cblinfun_compose_assoc register_mult) by (simp add: assms(2) assms(3) is_proj_selfadj register_projector) lemma unitary_sandwich_register: \<open>unitary a \<Longrightarrow> register (sandwich a)\<close> unfolding register_def apply (auto simp: sandwich_def) apply (metis (no_types, lifting) cblinfun_assoc_left(1) cblinfun_compose_id_right unitaryD1) by (simp add: lift_cblinfun_comp(2)) lemma sandwich_tensor: fixes a :: \<open>'a::finite ell2 \<Rightarrow>\<^sub>C\<^sub>L 'a ell2\<close> and b :: \<open>'b::finite ell2 \<Rightarrow>\<^sub>C\<^sub>L 'b ell2\<close> assumes \<open>unitary a\<close> \<open>unitary b\<close> shows "sandwich (a \<otimes>\<^sub>o b) = sandwich a \<otimes>\<^sub>r sandwich b" apply (rule tensor_extensionality) by (auto simp: unitary_sandwich_register assms sandwich_def register_tensor_is_register comp_tensor_op tensor_op_adjoint) lemma sandwich_grow_left: fixes a :: \<open>'a::finite ell2 \<Rightarrow>\<^sub>C\<^sub>L 'a ell2\<close> assumes "unitary a" shows "sandwich a \<otimes>\<^sub>r id = sandwich (a \<otimes>\<^sub>o id_cblinfun)" by (simp add: unitary_sandwich_register assms sandwich_tensor sandwich_id) lemma register_sandwich: \<open>register F \<Longrightarrow> F (sandwich a b) = sandwich (F a) (F b)\<close> by (smt (verit, del_insts) register_def sandwich_def) lemma assoc_ell2_sandwich: \<open>assoc = sandwich assoc_ell2\<close> apply (rule tensor_extensionality3') apply (simp_all add: unitary_sandwich_register)[2] apply (rule equal_ket) apply (case_tac x) by (simp add: sandwich_def assoc_apply cblinfun_apply_cblinfun_compose tensor_op_ell2 assoc_ell2_tensor assoc_ell2'_tensor flip: tensor_ell2_ket) lemma assoc_ell2'_sandwich: \<open>assoc' = sandwich assoc_ell2'\<close> apply (rule tensor_extensionality3) apply (simp_all add: unitary_sandwich_register)[2] apply (rule equal_ket) apply (case_tac x) by (simp add: sandwich_def assoc'_apply cblinfun_apply_cblinfun_compose tensor_op_ell2 assoc_ell2_tensor assoc_ell2'_tensor flip: tensor_ell2_ket) lemma swap_sandwich: "swap = sandwich Uswap" apply (rule tensor_extensionality) apply (auto simp: sandwich_def)[2] apply (rule tensor_ell2_extensionality) by (simp add: sandwich_def cblinfun_apply_cblinfun_compose tensor_op_ell2) lemma id_tensor_sandwich: fixes a :: "'a::finite ell2 \<Rightarrow>\<^sub>C\<^sub>L 'b::finite ell2" assumes "unitary a" shows "id \<otimes>\<^sub>r sandwich a = sandwich (id_cblinfun \<otimes>\<^sub>o a)" apply (rule tensor_extensionality) using assms by (auto simp: register_tensor_is_register comp_tensor_op sandwich_def tensor_op_adjoint unitary_sandwich_register) lemma compatible_selfbutter_join: assumes [register]: "compatible R S" shows "R (selfbutter \<psi>) o\<^sub>C\<^sub>L S (selfbutter \<phi>) = (R; S) (selfbutter (\<psi> \<otimes>\<^sub>s \<phi>))" apply (subst register_pair_apply[symmetric, where F=R and G=S]) using assms by auto lemma register_mult': assumes \<open>register F\<close> shows \<open>F a *\<^sub>V F b *\<^sub>V c = F (a o\<^sub>C\<^sub>L b) *\<^sub>V c\<close> by (simp add: assms lift_cblinfun_comp(4) register_mult) lemma register_scaleC: assumes \<open>register F\<close> shows \<open>F (c *\<^sub>C a) = c *\<^sub>C F a\<close> by (simp add: assms complex_vector.linear_scale) lemma register_bounded_clinear: \<open>register F \<Longrightarrow> bounded_clinear F\<close> using bounded_clinear_finite_dim register_def by blast lemma register_adjoint: "F (a*) = (F a)*" if \<open>register F\<close> using register_def that by blast end
{- HLINT ignore "Evaluate" -} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NumericUnderscores #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} -- | -- Copyright: © 2021 IOHK -- License: Apache-2.0 -- -- Provides functions for selecting coins for use as collateral from a UTxO -- set. -- -- See the documentation for 'performSelection' for more details. -- module Cardano.Wallet.CoinSelection.Internal.Collateral ( -- * Public API performSelection , PerformSelection , PerformSelectionOf , SelectionConstraints (..) , SelectionParams , SelectionParamsOf (..) , SelectionResult , SelectionResultOf (..) , selectionResultEmpty , SelectionCollateralError , SelectionCollateralErrorOf (..) , SearchSpaceLimit (..) , searchSpaceLimitDefault -- * Internal API -- ** Selecting collateral by giving priority to smallest values first , selectCollateralSmallest -- ** Selecting collateral by giving priority to largest values first , selectCollateralLargest -- ** Guarding search space size , SearchSpaceRequirement (..) , guardSearchSpaceSize -- ** Generating submaps , submaps -- ** Generating subsequences , subsequencesOfSize , numberOfSubsequencesOfSize -- ** Control flow , firstRight , takeUntil ) where import Cardano.Wallet.Primitive.Types.Coin ( Coin ) import Cardano.Wallet.Primitive.Types.Tx ( TxIn ) import Data.Function ( (&) ) import Data.IntCast ( intCast, intCastMaybe ) import Data.List.NonEmpty ( NonEmpty ) import Data.Map.Strict ( Map ) import Data.Maybe ( listToMaybe, mapMaybe ) import Data.Ord ( Down (..) ) import Data.Semigroup ( sconcat ) import Data.Set ( Set ) import GHC.Generics ( Generic ) import Prelude import qualified Data.Foldable as F import qualified Data.List as L import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Math.Combinatorics.Exact.Binomial as MathExact import qualified Numeric.SpecFunctions as MathFast -------------------------------------------------------------------------------- -- Public API -------------------------------------------------------------------------------- -- | The type of all functions that perform selections. -- type PerformSelectionOf inputId = SelectionConstraints -> SelectionParamsOf inputId -> Either (SelectionCollateralErrorOf inputId) (SelectionResultOf inputId) -- | The default type for 'PerformSelectionOf'. -- type PerformSelection = PerformSelectionOf TxIn -- | Specifies all constraints required for collateral selection. -- -- Selection constraints: -- -- - are dependent on the current set of protocol parameters. -- -- - are not specific to a given selection. -- -- - place limits on the selection algorithm, enabling it to produce -- selections that are acceptable to the ledger. -- data SelectionConstraints = SelectionConstraints { maximumSelectionSize :: Int -- ^ An upper bound on the number of unique coins that can be selected -- as collateral. , searchSpaceLimit :: SearchSpaceLimit -- ^ An upper bound on the search space size, to protect the wallet -- against computations that use excessive amounts of time or space. } deriving (Eq, Generic, Show) -- | Specifies all parameters that are specific to a given selection. -- data SelectionParamsOf inputId = SelectionParams { coinsAvailable :: Map inputId Coin -- ^ The set of all coins available for selection as collateral. , minimumSelectionAmount :: Coin -- ^ A lower bound on the sum of coins to be selected as collateral. } deriving (Eq, Generic, Show) -- | The default type for 'SelectionParamsOf'. -- type SelectionParams = SelectionParamsOf TxIn -- | Specifies an upper bound on the search space size. -- data SearchSpaceLimit = SearchSpaceLimit Int -- ^ Specifies an upper bound on the number of coin combinations that can -- be considered in any single step. | UnsafeNoSearchSpaceLimit -- ^ Specifies that there is no search space limit. This should only be -- used for testing purposes. deriving (Eq, Show) -- | The default search space limit. -- -- This constant is used by the test suite, so we can be reasonably confident -- that performing selections with this limit will not use inordinate amounts -- of time and space. -- searchSpaceLimitDefault :: SearchSpaceLimit searchSpaceLimitDefault = SearchSpaceLimit 1_000_000 -- | Represents a successful selection of collateral. -- newtype SelectionResultOf inputId = SelectionResult { coinsSelected :: Map inputId Coin -- ^ The coins that were selected for collateral. } deriving (Eq, Generic, Show) -- | The default type for 'SelectionResultOf'. -- type SelectionResult = SelectionResultOf TxIn -- | A completely empty result, with no inputs selected. -- selectionResultEmpty :: SelectionResultOf inputId selectionResultEmpty = SelectionResult { coinsSelected = Map.empty } -- | Represents an unsuccessful attempt to select collateral. -- data SelectionCollateralErrorOf inputId = SelectionCollateralError { largestCombinationAvailable :: Map inputId Coin -- ^ The largest combination of coins available. , minimumSelectionAmount :: Coin -- ^ A lower bound on the sum of coins to be selected as collateral. } deriving (Eq, Generic, Show) -- | The default type for `SelectionCollateralErrorOf`. -- type SelectionCollateralError = SelectionCollateralErrorOf TxIn -- | Selects coins for collateral. -- -- This function tries two strategies in the following order, picking the first -- strategy that succeeds: -- -- 1. Attempt to select an amount of collateral that is as small as possible. -- 2. Attempt to select collateral from the largest coins available. -- -- The first strategy, given unlimited computation time, will always produce an -- optimal result: the smallest possible amount of collateral. However, if the -- required search space is large, and if the 'searchSpaceLimit' parameter is -- set to a value that's smaller than the required search space size, then this -- strategy will fail without computing a result. -- -- The second strategy sacrifices optimality and always produces a result if -- one is available, by looking only at the very largest coins available. This -- result can be computed very quickly, without using much search space. -- -- The combination of these two strategies means that we can satisfy the -- following properties: -- -- If the attempt to select collateral succeeds: -- -- >>> sum coinsSelected ≥ minimumSelectionAmount -- >>> size coinsSelected ≤ maximumSelectionSize -- >>> coinsSelected ⊆ coinsAvailable -- -- If the attempt to select collateral fails: -- -- >>> sum largestCombinationAvailable < minimumSelectionAmount -- >>> size largestCombinationAvailable ≤ maximumSelectionSize -- >>> largestCombinationAvailable ⊆ coinsAvailable -- performSelection :: forall inputId. Ord inputId => PerformSelectionOf inputId performSelection constraints = firstRight $ fmap ($ constraints) [ selectCollateralSmallest , selectCollateralLargest ] -------------------------------------------------------------------------------- -- Internal API -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Selecting collateral by giving priority to smallest values first -------------------------------------------------------------------------------- -- | Attempts to select an amount of collateral that is as small as possible. -- -- This function, given unlimited computation time, will always produce an -- optimal result: the smallest possible amount of collateral. However, if the -- required search space is large, and if the 'searchSpaceLimit' parameter is -- set to a value that's smaller than the required search space size, then this -- function will return without computing a result. -- selectCollateralSmallest :: forall inputId. Ord inputId => PerformSelectionOf inputId selectCollateralSmallest constraints params = case smallestValidCombination of Just coinsSelected -> Right SelectionResult {coinsSelected} Nothing -> Left SelectionCollateralError { largestCombinationAvailable = mempty , minimumSelectionAmount } where coinsToConsider :: [(inputId, Coin)] coinsToConsider = coinsAvailable & Map.toList & L.sortOn snd & takeUntil ((>= minimumSelectionAmount) . snd) numberOfCoinsToConsider :: Int numberOfCoinsToConsider = length coinsToConsider smallestValidCombination :: Maybe (Map inputId Coin) smallestValidCombination = listToMaybe $ L.sortOn F.fold validCombinations where validCombinations :: [Map inputId Coin] validCombinations = mapMaybe smallestValidCombinationOfSize [1 .. maximumSelectionSize] smallestValidCombinationOfSize :: Int -> Maybe (Map inputId Coin) smallestValidCombinationOfSize size = guardSearchSpaceSize searchSpaceRequirement searchSpaceLimit result where result :: Maybe (Map inputId Coin) result = coinsToConsider & (`subsequencesOfSize` size) & fmap (\ics -> (ics, F.foldMap snd ics)) & L.sortOn snd & L.dropWhile ((< minimumSelectionAmount) . snd) & listToMaybe & fmap (Map.fromList . fst) searchSpaceRequirement :: SearchSpaceRequirement searchSpaceRequirement = maybe SearchSpaceRequirementUnknown SearchSpaceRequirement (numberOfCoinsToConsider `numberOfSubsequencesOfSize` size) SelectionConstraints { maximumSelectionSize , searchSpaceLimit } = constraints SelectionParams { coinsAvailable , minimumSelectionAmount } = params -------------------------------------------------------------------------------- -- Selecting collateral by giving priority to largest values first -------------------------------------------------------------------------------- -- | Selects collateral from the largest coins available. -- -- This function sacrifices optimality and always produces a result if one is -- available, by looking only at the very largest coins available. -- -- This result can be computed very quickly, without using much search space. -- selectCollateralLargest :: forall inputId. Ord inputId => PerformSelectionOf inputId selectCollateralLargest constraints params = case smallestValidSubmapOfLargestCombinationAvailable of Just coinsSelected -> Right SelectionResult {coinsSelected} Nothing -> Left SelectionCollateralError { largestCombinationAvailable , minimumSelectionAmount } where largestCombinationAvailable :: Map inputId Coin largestCombinationAvailable = coinsAvailable & Map.toList & L.sortOn (Down . snd) & L.take maximumSelectionSize & Map.fromList smallestValidSubmapOfLargestCombinationAvailable :: Maybe (Map inputId Coin) smallestValidSubmapOfLargestCombinationAvailable = largestCombinationAvailable & submaps & Set.toList & fmap (\ics -> (ics, F.fold ics)) & L.sortOn snd & L.dropWhile ((< minimumSelectionAmount) . snd) & fmap fst & listToMaybe SelectionConstraints { maximumSelectionSize } = constraints SelectionParams { coinsAvailable , minimumSelectionAmount } = params -------------------------------------------------------------------------------- -- Generating submaps -------------------------------------------------------------------------------- -- | Generates all submaps of a given map. -- -- This function is analogous to 'Set.powerSet'. -- -- For a map 'm' of size 'n', this function will generate all possible submaps, -- including the empty map and the original map 'm'. -- submaps :: forall a b. (Ord a, Ord b) => Map a b -> Set (Map a b) submaps m = Set.map (Map.restrictKeys m) (Set.powerSet (Map.keysSet m)) -------------------------------------------------------------------------------- -- Guarding search space size -------------------------------------------------------------------------------- data SearchSpaceRequirement = SearchSpaceRequirement Int -- ^ Indicates a known search space requirement. | SearchSpaceRequirementUnknown -- ^ Indicates that the search space requirement is unknown. guardSearchSpaceSize :: SearchSpaceRequirement -- ^ The search space requirement -> SearchSpaceLimit -- ^ The search space limit -> Maybe a -- ^ A computation that potentially yields a value -> Maybe a -- ^ The guarded computation guardSearchSpaceSize requirement limit = case requirement of -- When the search space requirement is unknown, err on the side of -- caution and avoid evaluating the computation, unless the caller -- has explicitly specified that there is no limit: SearchSpaceRequirementUnknown -> case limit of SearchSpaceLimit _ -> const Nothing UnsafeNoSearchSpaceLimit -> id -- When the search space requirement is known, only evaluate the -- computation if the requirement is not greater than the limit: SearchSpaceRequirement r -> case limit of SearchSpaceLimit l | l < r -> const Nothing SearchSpaceLimit _ -> id UnsafeNoSearchSpaceLimit -> id -------------------------------------------------------------------------------- -- Generating subsequences -------------------------------------------------------------------------------- -- | Computes the number of subsequences generated by 'subsequencesOfSize'. -- -- This function can be used to determine whether calling 'subsequencesOfSize' -- would use an excessive amount of time and space, and if so, avoid calling -- it. -- -- Returns 'Nothing' if the result is larger than 'maxBound :: Int'. -- numberOfSubsequencesOfSize :: Int -- ^ Indicates the size of the sequence. -> Int -- ^ Indicates the size of subsequences. -> Maybe Int numberOfSubsequencesOfSize n k | k < 0 || n < 0 = Nothing | k == 0 || k == n = Just 1 | k == 1 || k == (n - 1) = Just n | resultOutOfBounds = Nothing | otherwise = intCastMaybe resultExact where resultExact :: Integer resultExact = MathExact.choose (intCast @Int @Integer n) (intCast @Int @Integer k) resultFast :: Integer resultFast = floor (MathFast.choose n k) resultOutOfBounds :: Bool resultOutOfBounds = False || resultFast < 0 || resultFast > intCast @Int @Integer (maxBound @Int) || resultExact < 0 || resultExact > intCast @Int @Integer (maxBound @Int) -- | Generates all subsequences of size 'k' from a particular sequence. -- -- Warning: this function can use an excessive amount of time and space. -- -- To check how many results would be returned without actually generating -- them, use the 'numberOfSubsequencesOfSize' function. -- -- Properties: -- -- >>> all (== k) (length <$> xs `subsequencesOfSize` k) -- -- >>> length (xs `subsequencesOfSize` k) == -- >>> length xs `numberOfSubsequencesOfSize` k -- subsequencesOfSize :: [a] -- ^ The sequence from which to generate subsequences. -> Int -- ^ The size 'k' of subsequences to generate. -> [[a]] -- ^ All subsequences of size 'k'. subsequencesOfSize xs k | k <= 0 = [] | k > length xs = [] | otherwise = case drop k (subsequencesBySize xs) of result : _ -> result [] -> [] where subsequencesBySize [] = [[[]]] subsequencesBySize (y : ys) = zipWith (++) ([] : map (map (y :)) next) (next ++ [[]]) where next = subsequencesBySize ys -------------------------------------------------------------------------------- -- Control flow -------------------------------------------------------------------------------- -- | Applies a sequence of functions to an argument until one succeeds. -- -- This function iterates through the specified sequence from left to right, -- applying each function to the given argument, and returning the very first -- 'Right' result encountered, without evaluating the subsequent functions. -- -- If none of the given functions produces a 'Right' result, then this function -- returns the 'Left' result produced by the last function in the sequence. -- firstRight :: NonEmpty (a -> Either e r) -> (a -> Either e r) firstRight = sconcat -- | Takes items from a list until a predicate becomes true. -- -- The returned list is a prefix of the original list, and includes the very -- first item that satisfies the predicate. -- takeUntil :: (a -> Bool) -> [a] -> [a] takeUntil p = foldr (\x ys -> x : if p x then [] else ys) []
[STATEMENT] lemma ltln_weak_strong_stable_words_1: "w \<Turnstile>\<^sub>n (\<phi> W\<^sub>n \<psi>) \<longleftrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n (G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1))" (is "?lhs \<longleftrightarrow> ?rhs") [PROOF STATE] proof (prove) goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> = w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) [PROOF STEP] proof [PROOF STATE] proof (state) goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] assume ?lhs [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] moreover [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] { [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] assume assm: "w \<Turnstile>\<^sub>n G\<^sub>n \<phi>" [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n G\<^sub>n \<phi> goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] moreover [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n G\<^sub>n \<phi> goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] obtain i where "\<And>j. \<F> \<phi> (suffix i w) \<subseteq> \<G>\<F> \<phi> w" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>i. (\<And>j. \<F> \<phi> (suffix i w) \<subseteq> \<G>\<F> \<phi> w) \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (metis MOST_nat_le \<G>\<F>_suffix \<mu>_stable_def order_refl suffix_\<mu>_stable) [PROOF STATE] proof (state) this: \<F> \<phi> (suffix i w) \<subseteq> \<G>\<F> \<phi> w goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] hence "\<And>j. \<F> \<phi> (suffix i (suffix j w)) \<subseteq> \<G>\<F> \<phi> w" [PROOF STATE] proof (prove) using this: \<F> \<phi> (suffix i w) \<subseteq> \<G>\<F> \<phi> w goal (1 subgoal): 1. \<And>j. \<F> \<phi> (suffix i (suffix j w)) \<subseteq> \<G>\<F> \<phi> w [PROOF STEP] by (metis \<F>_suffix \<G>\<F>_\<F>_subset \<G>\<F>_suffix semiring_normalization_rules(24) subset_Un_eq suffix_suffix sup.orderE) [PROOF STATE] proof (state) this: \<F> \<phi> (suffix i (suffix ?j2 w)) \<subseteq> \<G>\<F> \<phi> w goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: w \<Turnstile>\<^sub>n G\<^sub>n \<phi> \<F> \<phi> (suffix i (suffix ?j2 w)) \<subseteq> \<G>\<F> \<phi> w [PROOF STEP] have "suffix i w \<Turnstile>\<^sub>n G\<^sub>n (\<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1)" [PROOF STATE] proof (prove) using this: w \<Turnstile>\<^sub>n G\<^sub>n \<phi> \<F> \<phi> (suffix i (suffix ?j2 w)) \<subseteq> \<G>\<F> \<phi> w goal (1 subgoal): 1. suffix i w \<Turnstile>\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1 [PROOF STEP] using GF_advice_a1[OF \<open>\<And>j. \<F> \<phi> (suffix i (suffix j w)) \<subseteq> \<G>\<F> \<phi> w\<close>] [PROOF STATE] proof (prove) using this: w \<Turnstile>\<^sub>n G\<^sub>n \<phi> \<F> \<phi> (suffix i (suffix ?j2 w)) \<subseteq> \<G>\<F> \<phi> w suffix i (suffix ?j1 w) \<Turnstile>\<^sub>n \<phi> \<Longrightarrow> suffix i (suffix ?j1 w) \<Turnstile>\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1 goal (1 subgoal): 1. suffix i w \<Turnstile>\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1 [PROOF STEP] by (simp add: add.commute) [PROOF STATE] proof (state) this: suffix i w \<Turnstile>\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1 goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] hence "?rhs" [PROOF STATE] proof (prove) using this: suffix i w \<Turnstile>\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1 goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) [PROOF STEP] using assm [PROOF STATE] proof (prove) using this: suffix i w \<Turnstile>\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1 w \<Turnstile>\<^sub>n G\<^sub>n \<phi> goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) [PROOF STEP] by auto [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] } [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n G\<^sub>n \<phi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] moreover [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n G\<^sub>n \<phi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] have "w \<Turnstile>\<^sub>n \<phi> U\<^sub>n \<psi> \<Longrightarrow> ?rhs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) [PROOF STEP] by auto [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n \<phi> U\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (2 subgoals): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) 2. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> w \<Turnstile>\<^sub>n G\<^sub>n \<phi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) w \<Turnstile>\<^sub>n \<phi> U\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) [PROOF STEP] show ?rhs [PROOF STATE] proof (prove) using this: w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> w \<Turnstile>\<^sub>n G\<^sub>n \<phi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) w \<Turnstile>\<^sub>n \<phi> U\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) [PROOF STEP] using ltln_weak_to_strong(1) [PROOF STATE] proof (prove) using this: w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> w \<Turnstile>\<^sub>n G\<^sub>n \<phi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) w \<Turnstile>\<^sub>n \<phi> U\<^sub>n \<psi> \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<lbrakk>?w \<Turnstile>\<^sub>n ?\<phi> W\<^sub>n ?\<psi>; \<not> ?w \<Turnstile>\<^sub>n G\<^sub>n ?\<phi>\<rbrakk> \<Longrightarrow> ?w \<Turnstile>\<^sub>n ?\<phi> U\<^sub>n ?\<psi> goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) [PROOF STEP] by blast [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] assume ?rhs [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) \<Longrightarrow> w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] thus ?lhs [PROOF STATE] proof (prove) using this: w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> [PROOF STEP] unfolding ltln_weak_strong_2 [PROOF STATE] proof (prove) using this: w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1) goal (1 subgoal): 1. w \<Turnstile>\<^sub>n \<phi> U\<^sub>n (\<psi> or\<^sub>n G\<^sub>n \<phi>) [PROOF STEP] unfolding semantics_ltln.simps [PROOF STATE] proof (prove) using this: \<exists>i. (suffix i w \<Turnstile>\<^sub>n \<psi> \<or> (\<forall>ia. suffix ia (suffix i w) \<Turnstile>\<^sub>n \<phi>[\<G>\<F> \<phi> w]\<^sub>\<Pi>\<^sub>1 \<or> (\<exists>j<ia. False))) \<and> (\<forall>j<i. suffix j w \<Turnstile>\<^sub>n \<phi>) goal (1 subgoal): 1. \<exists>i. (suffix i w \<Turnstile>\<^sub>n \<psi> \<or> (\<forall>ia. suffix ia (suffix i w) \<Turnstile>\<^sub>n \<phi> \<or> (\<exists>j<ia. False))) \<and> (\<forall>j<i. suffix j w \<Turnstile>\<^sub>n \<phi>) [PROOF STEP] by (metis \<G>\<F>_suffix order_refl GF_advice_a2) [PROOF STATE] proof (state) this: w \<Turnstile>\<^sub>n \<phi> W\<^sub>n \<psi> goal: No subgoals! [PROOF STEP] qed
import challenge_notations import challenge_prerequisites /-! # Liquid Tensor Experiment ## The main challenge The main challenge of the liquid tensor experiment is a formalisation of the first theorem in Peter Scholze's blogpost https://xenaproject.wordpress.com/2020/12/05/liquid-tensor-experiment/ Theorem 1.1 (Clausen--Scholze) Let `0 < p' < p ≤ 1` be real numbers, let `S` be a profinite set, and let `V` be a `p`-Banach space. Let `ℳ p' S` be the space of `p'`-measures on `S`. Then $$ Ext^i (ℳ p' S, V) = 0 $$ for `i ≥ 1`. -/ noncomputable theory open_locale liquid_tensor_experiment nnreal zero_object open liquid_tensor_experiment category_theory category_theory.limits variables (p' p : ℝ≥0) [fact (0 < p')] [fact (p' < p)] [fact (p ≤ 1)] theorem liquid_tensor_experiment (S : Profinite.{0}) (V : pBanach.{0} p) : ∀ i > 0, Ext i (ℳ_{p'} S) V ≅ 0 := begin intros i hi, apply is_zero.iso_zero, revert i, haveI : fact (0 < (p:ℝ)) := ⟨lt_trans (fact.out _ : 0 < p') (fact.out _)⟩, haveI : fact (p' < 1) := ⟨lt_of_lt_of_le (fact.out _ : p' < p) (fact.out _)⟩, erw is_zero_iff_epi_and_is_iso _ _ (V : Condensed.{0 1 2} Ab) (laurent_measures.short_exact p' S), let := pBanach.choose_seminormed_add_comm_group V, let := pBanach.choose_normed_with_aut V 2⁻¹, haveI : fact (0 < (2⁻¹ : ℝ≥0) ^ (p : ℝ)) := r_pos', convert laurent_measures.epi_and_is_iso p' p S ⟨V⟩ _ using 1, intro v, rw [pBanach.choose_normed_with_aut_T_inv, inv_inv, two_smul, two_nsmul], end
-- This test case is aimed at checking that one can give RTS options -- (as well as other options) using the Emacs mode. It does not test -- backend options.
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} ----------------------------------------------------------------------------- -- | -- Module : Diagrams.TwoD.Apollonian -- Copyright : (c) 2011, 2016 Brent Yorgey -- License : BSD-style (see LICENSE) -- Maintainer : [email protected] -- -- Generation of Apollonian gaskets. Any three mutually tangent -- circles uniquely determine exactly two others which are mutually -- tangent to all three. This process can be repeated, generating a -- fractal circle packing. -- -- See J. Lagarias, C. Mallows, and A. Wilks, \"Beyond the Descartes -- circle theorem\", /Amer. Math. Monthly/ 109 (2002), 338--361. -- <http://arxiv.org/abs/math/0101066>. -- -- A few examples: -- -- > import Diagrams.TwoD.Apollonian -- > apollonian1 = apollonianGasket 0.01 2 2 2 -- -- <<diagrams/src_Diagrams_TwoD_Apollonian_apollonian1.svg#diagram=apollonian1&width=400>> -- -- > import Diagrams.TwoD.Apollonian -- > apollonian2 = apollonianGasket 0.01 2 3 3 -- -- <<diagrams/src_Diagrams_TwoD_Apollonian_apollonian2.svg#diagram=apollonian2&width=400>> -- -- > import Diagrams.TwoD.Apollonian -- > apollonian3 = apollonianGasket 0.01 2 4 7 -- -- <<diagrams/src_Diagrams_TwoD_Apollonian_apollonian3.svg#diagram=apollonian3&width=400>> -- ----------------------------------------------------------------------------- module Diagrams.TwoD.Apollonian ( -- * Circles Circle(..), mkCircle, center, radius -- * Descartes' Theorem , descartes, other, initialConfig -- * Apollonian gasket generation , apollonian -- ** Kissing sets , KissingSet(..), kissingSets, flipSelected, selectOthers -- ** Apollonian trees , apollonianTrees, apollonianTree -- * Diagram generation , drawCircle , drawGasket , apollonianGasket ) where import Data.Complex import qualified Data.Foldable as F import Data.Maybe (catMaybes) import Data.Tree import Diagrams.Prelude hiding (center, radius) import Control.Arrow (second, (&&&)) ------------------------------------------------------------ -- Circles ------------------------------------------------------------ -- | Representation for circles that lets us quickly compute an -- Apollonian gasket. data Circle n = Circle { bend :: n -- ^ The bend is the reciprocal of signed -- radius: a negative radius means the -- outside and inside of the circle are -- switched. The bends of any four mutually -- tangent circles satisfy Descartes' -- Theorem. , cb :: Complex n -- ^ /Product/ of bend and center represented -- as a complex number. Amazingly, these -- products also satisfy the equation of -- Descartes' Theorem. } deriving (Eq, Show) -- | Create a @Circle@ given a signed radius and a location for its center. mkCircle :: Fractional n => n -- ^ signed radius -> P2 n -- ^ center -> Circle n mkCircle r (unp2 -> (x,y)) = Circle (1/r) (b*x :+ b*y) where b = 1/r -- | Get the center of a circle. center :: Fractional n => Circle n -> P2 n center (Circle b (cbx :+ cby)) = p2 (cbx / b, cby / b) -- | Get the (unsigned) radius of a circle. radius :: Fractional n => Circle n -> n radius = abs . recip . bend liftF :: RealFloat n => (forall a. Floating a => a -> a) -> Circle n -> Circle n liftF f (Circle b c) = Circle (f b) (f c) liftF2 :: RealFloat n => (forall a. Floating a => a -> a -> a) -> Circle n -> Circle n -> Circle n liftF2 f (Circle b1 cb1) (Circle b2 cb2) = Circle (f b1 b2) (f cb1 cb2) instance RealFloat n => Num (Circle n) where (+) = liftF2 (+) (-) = liftF2 (-) (*) = liftF2 (*) negate = liftF negate abs = liftF abs fromInteger n = Circle (fromInteger n) (fromInteger n) instance RealFloat n => Fractional (Circle n) where (/) = liftF2 (/) recip = liftF recip -- | The @Num@, @Fractional@, and @Floating@ instances for @Circle@ -- (all simply lifted elementwise over @Circle@'s fields) let us use -- Descartes' Theorem directly on circles. instance RealFloat n => Floating (Circle n) where sqrt = liftF sqrt ------------------------------------------------------------ -- Descartes' Theorem ------------------------------------------------------------ -- XXX generalize these for higher dimensions? -- | Descartes' Theorem states that if @b1@, @b2@, @b3@ and @b4@ are -- the bends of four mutually tangent circles, then -- -- @ -- b1^2 + b2^2 + b3^2 + b4^2 = 1/2 * (b1 + b2 + b3 + b4)^2. -- @ -- -- Surprisingly, if we replace each of the @bi@ with the /product/ -- of @bi@ and the center of the corresponding circle (represented -- as a complex number), the equation continues to hold! (See the -- paper referenced at the top of the module.) -- -- @descartes [b1,b2,b3]@ solves for @b4@, returning both solutions. -- Notably, @descartes@ works for any instance of @Floating@, which -- includes both @Double@ (for bends), @Complex Double@ (for -- bend/center product), and @Circle@ (for both at once). descartes :: Floating n => [n] -> [n] descartes [b1,b2,b3] = [r + s, -r + s] where r = 2 * sqrt (b1*b2 + b1*b3 + b2*b3) s = b1+b2+b3 descartes _ = error "descartes must be called on a list of length 3" -- | If we have /four/ mutually tangent circles we can choose one of -- them to replace; the remaining three determine exactly one other -- circle which is mutually tangent. However, in this situation -- there is no need to apply 'descartes' again, since the two -- solutions @b4@ and @b4'@ satisfy -- -- @ -- b4 + b4' = 2 * (b1 + b2 + b3) -- @ -- -- Hence, to replace @b4@ with its dual, we need only sum the other -- three, multiply by two, and subtract @b4@. Again, this works for -- bends as well as bend/center products. other :: Num n => [n] -> n -> n other xs x = 2 * sum xs - x -- | Generate an initial configuration of four mutually tangent -- circles, given just the signed bends of three of them. initialConfig :: RealFloat n => n -> n -> n -> [Circle n] initialConfig b1 b2 b3 = cs ++ [c4] where cs = [Circle b1 0, Circle b2 ((b2/b1 + 1) :+ 0), Circle b3 cb3] a = 1/b1 + 1/b2 b = 1/b1 + 1/b3 c = 1/b2 + 1/b3 x = (b*b + a*a - c*c)/(2*a) y = sqrt (b*b - x*x) cb3 = b3*x :+ b3*y [c4,_] = descartes cs ------------------------------------------------------------ -- Gasket generation ------------------------------------------------------------ select :: [a] -> [(a, [a])] select [] = [] select (x:xs) = (x,xs) : (map . second) (x:) (select xs) -- | The basic idea of a kissing set is supposed to represent a set of -- four mutually tangent circles with one selected, though in fact -- it is more general than that: it represents any set of objects -- with one distinguished object selected. data KissingSet n = KS { selected :: n, others :: [n] } deriving (Show) -- | Generate all possible kissing sets from a set of objects by -- selecting each object in turn. kissingSets :: [n] -> [KissingSet n] kissingSets = map (uncurry KS) . select -- | \"Flip\" the selected circle to the 'other' circle mutually tangent -- to the other three. The new circle remains selected. flipSelected :: Num n => KissingSet n -> KissingSet n flipSelected (KS c cs) = KS (other cs c) cs -- | Make the selected circle unselected, and select each of the -- others, generating a new kissing set for each. selectOthers :: KissingSet n -> [KissingSet n] selectOthers (KS c cs) = [ KS c' (c:cs') | (c',cs') <- select cs ] -- | Given a threshold radius and a list of /four/ mutually tangent -- circles, generate the Apollonian gasket containing those circles. -- Stop the recursion when encountering a circle with an (unsigned) -- radius smaller than the threshold. apollonian :: RealFloat n => n -> [Circle n] -> [Circle n] apollonian thresh cs = (cs++) . concat . map (maybe [] flatten . prune p . fmap selected) . apollonianTrees $ cs where p c = radius c >= thresh -- | Given a set of /four/ mutually tangent circles, generate the -- infinite Apollonian tree rooted at the given set, represented as -- a list of four subtrees. Each node in the tree is a kissing set -- with one circle selected which has just been flipped. The three -- children of a node represent the kissing sets obtained by -- selecting each of the other three circles and flipping them. The -- initial roots of the four trees are chosen by selecting and -- flipping each of the circles in the starting set. This -- representation has the property that each circle in the -- Apollonian gasket is the selected circle in exactly one node -- (except that the initial four circles never appear as the -- selected circle in any node). apollonianTrees :: RealFloat n => [Circle n] -> [Tree (KissingSet (Circle n))] apollonianTrees = map (apollonianTree . flipSelected) . kissingSets -- | Generate a single Apollonian tree from a root kissing set. See -- the documentation for 'apollonianTrees' for an explanation. apollonianTree :: RealFloat n => KissingSet (Circle n) -> Tree (KissingSet (Circle n)) apollonianTree = unfoldTree (id &&& (map flipSelected . selectOthers)) -- | Prune a tree at the shallowest points where the predicate is not -- satisfied. prune :: (a -> Bool) -> Tree a -> Maybe (Tree a) prune p (Node a ts) | not (p a) = Nothing | otherwise = Just $ Node a (catMaybes (map (prune p) ts)) ------------------------------------------------------------ -- Diagram generation ------------------------------------------------------------ -- | Draw a circle. drawCircle :: (Renderable (Path V2 n) b, TypeableFloat n) => Circle n -> QDiagram b V2 n Any drawCircle c = circle (radius c) # moveTo (center c) # fcA transparent -- | Draw a generated gasket, using a line width 0.003 times the -- radius of the largest circle. drawGasket :: (Renderable (Path V2 n) b, TypeableFloat n) => [Circle n] -> QDiagram b V2 n Any drawGasket cs = F.foldMap drawCircle cs -- | Draw an Apollonian gasket: the first argument is the threshold; -- the recursion will stop upon reaching circles with radii less than -- it. The next three arguments are bends of three circles. apollonianGasket :: (Renderable (Path V2 n) b, TypeableFloat n) => n -> n -> n -> n -> QDiagram b V2 n Any apollonianGasket thresh b1 b2 b3 = drawGasket . apollonian thresh $ (initialConfig b1 b2 b3) ------------------------------------------------------------ -- Some notes on floating-point error -- (only for the intrepid) ------------------------------------------------------------ {- -- code from Gerald Gutierrez, personal communication module Main where import Data.Complex import Diagrams.Backend.SVG.CmdLine import Diagrams.Prelude -- ------^---------^---------^---------^---------^---------^---------^-------- data Circle = Circle Double (Complex Double) deriving (Show) descartes a b c = (s + r, s - r) where s = a + b + c r = 2 * sqrt ((a * b) + (b * c) + (c * a)) descartesDual a b c d = 2 * (a + b + c) - d soddies (Circle k1 b1) (Circle k2 b2) (Circle k3 b3) = ( Circle k4 b4 , Circle k5 b5 ) where (k4, k5) = descartes k1 k2 k3 (b4, b5) = descartes b1 b2 b3 soddiesDual (Circle k1 b1) (Circle k2 b2) (Circle k3 b3) (Circle k4 b4) = Circle (descartesDual k1 k2 k3 k4) (descartesDual b1 b2 b3 b4) mutuallyTangentCirclesFromTriangle z1 z2 z3 = ( Circle k1 (z1 * (k1 :+ 0)) , Circle k2 (z2 * (k2 :+ 0)) , Circle k3 (z3 * (k3 :+ 0)) ) where a = magnitude (z2 - z3) b = magnitude (z3 - z1) c = magnitude (z1 - z2) s = (a + b + c) / 2 k1 = 1 / (s - a) k2 = 1 / (s - b) k3 = 1 / (s - c) main :: IO () main = mainWith picture pic = mainWith picture mkCircle :: Circle -> Diagram B mkCircle (Circle k b) = circle (1 / k) # moveTo (p2 (realPart z, imagPart z)) where z = b / (k :+ 0) picture :: Diagram B picture = mkCircle c1 <> mkCircle c2 <> mkCircle c3 <> mkCircle c4 <> mkCircle c5 where (c1, c2, c3) = mutuallyTangentCirclesFromTriangle z1 z2 z3 (c4, c5) = soddies c1 c2 c3 -- z1 = 0 :+ 0 -- z2 = 3 :+ 0 -- z3 = 0 :+ 4 -- z1 = (-0.546) :+ (-0.755) -- z2 = ( 0.341) :+ (-0.755) -- z3 = (-0.250) :+ ( 0.428) ofsBad = 0.15397 -- doesn't work ofsGood = 0.15398 -- works ofs = ofsGood z1 = ofs + ((-0.546) :+ (-0.755)) z2 = ofs + (( 0.341) :+ (-0.755)) z3 = ofs + ((-0.250) :+ ( 0.428)) ------------------------------------------------------------ Email to Gerald Gutierrez, 30 Sep 2016: I got a chance to sit down and think hard about your code today, and I think I have figured out what the problem is. If you look at the outputs of 'soddies c1 c2 c3' using the two different values for 'ofs', you will see that they are *almost* the same, except that the complex numbers have been switched (though in fact their real components are almost the same so you only notice the difference in the imaginary components). This clearly causes incorrect results since the y-coordinates represented by the imaginary components are now getting scaled by different bend values. So the resulting circles are of the right size and have (close to) the correct x-coordinates, but their y-coordinates are wrong. The problem is that in the 'soddies' function, you make independent calls to 'descartes k1 k2 k3' (to solve for the bends) and 'descartes b1 b2 b3' (to solve for the bend-center products), and then *assume* that they return their solutions *in the same order*, so that you can match up the first values to make one circle and the second values to make another circle. I would guess that this is *usually* true but apparently not when certain values are hovering right around a branch cut of sqrt, or something like that. I think my code in Diagrams.TwoD.Apollonian suffers from the same problem. Ultimately I think it is due to the inherent inaccuracy of floating-point numbers; there is nothing wrong with the formula itself. It would be nice to figure out how to correct for this, but I am not sure how off the top of my head. The interesting thing is that switching the bend-center products does not seem to violate the generalized Descartes' Theorem at all --- so it would seem that it does not actually completely characterize mutually tangent circles, that is, there exist sets of circles satisfying the theorem which are not in fact mutually tangent. -}
import data.finsupp.basic section /-- An inductive type from which to index the variables of the mv_polynomials the proof manages -/ @[derive decidable_eq] inductive vars : Type | α : vars | β : vars lemma finsupp_vars_eq_ext (f g : vars →₀ ℕ) : f = g ↔ f vars.α = g vars.α ∧ f vars.β = g vars.β := begin rw finsupp.ext_iff, split, { intro h, split, exact h vars.α, exact h vars.β, }, { intro h, intro a, induction a, finish, finish, }, -- induction, end end
#julia -L rollingHarness.jl test_Rolling.jl outPathStub d datastub #passed arguments #ARGS[1] is partial path for output. #ARGS[2] is d must be one of 20, 50, 1000 #ARGS[3] specifies the data stub: AdjSales_NoWeekends_ShuffleWithinCol using Distributed const spath = ARGS[1] const param_path = ARGS[3] # e.g. "AdjSales_NoWeekends" const d = parse(Int, ARGS[2]) const s = .95 @assert d in [20, 50, 1000] "Only bins of size 20, 50, 1000 currently supported" K_grid = vcat(round.(Int, 2 .^(3:.25:10)), 1115) N_grid = [10, 20, 40] outPath = "$(spath)_RossRolling_$(s)__$(d)_$(param_path)" #First read in the data and parse it appropriately ps_full = readdlm("../RossmanKaggleData/CleanedData/ps_full$(d).csv", ',') supp_full = readdlm("../RossmanKaggleData/CleanedData/support$(d).csv", ',') @assert minimum(ps_full) >=0 "ps_full has negative entries" #Load shuffled data tdata = readdlm("../RossmanKaggleData/CleanedData/$(param_path)_Binned$(d).csv", ',') binned_data = tdata[2:end, 2:end] #drop column header = stores, drop row header = dates dates= tdata[2:end, 1] #keep track of dates for fun #currently run single-threaded for ease @time rollingTest(K_grid, supp_full, ps_full, binned_data, dates, outPath, N_grid, s, onlySAA=false, numTestDays=10)
""" Create top banner """ import random import math import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches import itertools random.seed(23) np.random.seed(23) # Hexagon radius in mm RADIUS = 4 # Dimensions of the bounding box of the hexagons WIDTH = math.sqrt(3) * RADIUS HEIGHT = 2 * RADIUS # Banner dimensions in mm PAGEWIDTH = 300 PAGEHEIGHT = 70 mm_to_in = 0.03937008 # CMAP "cool" also looks, uh, cool cmap = plt.get_cmap("inferno") def draw_hexagon(ax, center, color): # because the dimensions of the axes have been set in mm, # the dimensions of thie hexagon are given in mm as well. ax.add_patch( mpatches.RegularPolygon( xy=center, numVertices=6, # Due to rounding errors I think, it is better to make the hexagons # a little larger than the RADIUS parameter radius=RADIUS + 0.2, facecolor=color, edgecolor="none", orientation=0, fill=True, ) ) figure, ax = plt.subplots( 1, 1, figsize=(PAGEWIDTH * mm_to_in, PAGEHEIGHT * mm_to_in), frameon=False ) # Dimensions of the page in mm ax.set_xlim([0, PAGEWIDTH]) ax.set_ylim([0, PAGEHEIGHT]) for offset_x, offset_y in [(0, 0), (WIDTH / 2, (3 / 2) * RADIUS)]: rows = np.arange(start=offset_x, stop=1.05 * PAGEWIDTH, step=WIDTH) columns = np.arange(start=offset_y, stop=1.05 * PAGEHEIGHT, step=3 * RADIUS) for x, y in itertools.product(rows, columns): color = cmap( math.hypot(x, y) / math.hypot(PAGEWIDTH, PAGEHEIGHT) + random.gauss(0, 0.01) ) draw_hexagon(ax, center=(x, y), color=color) ax.axis("off") plt.subplots_adjust(top=1, bottom=0, left=0, right=1) plt.savefig("images/banner.svg")
using Animations using GtkReactive using Gtk: get_gtk_property, visible using Images using Javis using LaTeXStrings using ReferenceTests using Test using VideoIO @testset "Unit" begin include("unit.jl") end @testset "SVG LaTeX tests" begin include("svg.jl") end @testset "Animations" begin include("animations.jl") end @testset "Javis Viewer" begin include("viewer.jl") end
Formal statement is: lemma i_times_eq_iff: "\<i> * w = z \<longleftrightarrow> w = - (\<i> * z)" Informal statement is: $\i * w = z$ if and only if $w = -\i * z$.
Initialize printing: ``` %pylab inline from sympy.interactive.printing import init_printing init_printing() ``` Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'. # Poisson Equation Radial Poisson equation is $$ \phi''(r)+{2\over r} \phi'(r) = -4\pi\rho(r). $$ Alternatively, this can also be written as: $$ {1\over r}(r \phi(r))'' = -4\pi\rho(r). $$ ### Example I Positive Gaussian charge density: ``` from sympy import var, exp, pi, sqrt, integrate, refine, Q, oo, Symbol, DiracDelta var("r alpha Z") alpha = Symbol("alpha", positive=True) rho = Z * (alpha / sqrt(pi))**3 * exp(-alpha**2 * r**2) rho ``` The total charge is $Z$: ``` integrate(4*pi*rho*r**2, (r, 0, oo)) ``` Solve for $\phi(r)$ from the Poisson equation: ``` phi = integrate(-4*pi*rho*r, r, r)/r phi ``` Tell SymPy that $\alpha$ is positive: ``` phi = refine(phi, Q.positive(alpha)) phi ``` Plot the charge: ``` from sympy import plot ``` ``` plot(rho.subs({Z: 1, alpha: 0.1}), (r, 0, 100)); ``` Plot the potential ``` plot(phi.subs({Z: 1, alpha: 0.1}), 1/r, (r, 0, 100), ylim=[0, 0.12]); ``` ``` ```
import pq_induction_principles universes u1 u2 section pq_hom_group_property variables {G : Type u1} [group G] {H : Type u2} [group H] theorem pq_hom_group_property (f : G → H) (hf : is_pq_morphism f) : (∀ x y : G, f (x * y) = (f x) * (f y)) ↔ (∀ x : pq_group G, counit (L_of_morph f hf x) = f (counit x)) := begin split, { intros hf1, apply pq_group_word_induction, { simp only [monoid_hom.map_one], specialize hf1 1 1, simp only [mul_one] at hf1, symmetry, apply eq_one_of_left_cancel_mul_self, assumption, }, { intros x y hx, simp only [monoid_hom.map_mul, hf1, counit_of, L_of_morph_of, hx], }, }, { intros hf1 x y, specialize hf1 ((of x) * (of y)), simp only [monoid_hom.map_mul, L_of_morph_of, counit_of] at hf1, symmetry, assumption, }, end end pq_hom_group_property /- section pq_hom_group_property_dual variables {Q1 : Type u1} [power_quandle Q1] {Q2 : Type u2} [power_quandle Q2] [inhabited Q2] lemma L_of_morph_of_eq_of_imp_eq_of (x : pq_group Q2) (hx : of x = L_of_morph of of_is_pq_morphism x) : ∃ y, x = of y := begin /- induction x, { rw quot_mk_helper at *, induction x, { rw incl_unit_eq_unit at *, use (arbitrary Q2) ^ (0 : ℤ), rw of_pow_eq_pow_of, simp only [gpow_zero], }, { rw ←of_def at *, use x, }, { rw ←mul_def at *, }, { rw ←inv_def at *, sorry, }, }, {refl,}, -/ revert x, refine pq_group_word_induction _ _, { intro hx, use (arbitrary Q2) ^ (0 : ℤ), rw of_pow_eq_pow_of, simp only [gpow_zero], }, { intros x y hx hxy, simp only [monoid_hom.map_mul, L_of_morph_of] at hxy, --have hxy1 := congr_arg counit hxy, --simp only [monoid_hom.map_mul, counit_of, mul_right_inj] at hxy1, }, end theorem pq_hom_group_property_dual' (f : pq_group Q1 →* pq_group Q2) : (∀ x : Q1, ∃ y : Q2, f (of x) = of y) ↔ (∀ x : pq_group Q1, (L_of_morph (of : Q2 → pq_group Q2) of_is_pq_morphism) (f x) = (L_of_morph f (functoriality_group_bundled_to_pq f)) ((L_of_morph (of : Q1 → pq_group Q1) of_is_pq_morphism) x)) := begin split, { intro hf, apply pq_group_word_induction, { simp only [monoid_hom.map_one], }, { intros x y hx, specialize hf y, cases hf with z hz, simp only [monoid_hom.map_mul, hx, L_of_morph_of, mul_left_inj], rw hz, refl, }, }, { intro hf, intro q, specialize hf (of q), simp only [monoid_hom.map_mul, L_of_morph_of] at hf, apply L_of_morph_of_eq_of_imp_eq_of, symmetry, assumption, }, end theorem pq_hom_group_property_dual (f : pq_group Q1 →* pq_group Q2) : (∃ g : Q1 → Q2, ∃ hg : is_pq_morphism g, f = L_of_morph g hg) ↔ (∀ x : pq_group Q1, (L_of_morph (of : Q2 → pq_group Q2) of_is_pq_morphism) (f x) = (L_of_morph f (functoriality_group_bundled_to_pq f)) ((L_of_morph (of : Q1 → pq_group Q1) of_is_pq_morphism) x)) := begin split, { intro hf, cases hf with g hg, cases hg with hgpq hg, rw hg, apply pq_group_word_induction, { simp only [monoid_hom.map_one], }, { intros x y hx, simp only [monoid_hom.map_mul, hx, L_of_morph_of], }, }, { intro hf, fconstructor, intro q, specialize hf (of q), simp only [monoid_hom.map_mul, L_of_morph_of] at hf, }, end end pq_hom_group_property_dual -/
! ! The Laboratory of Algorithms ! ! The MIT License ! ! Copyright 2011-2015 Andrey Pudov. ! ! Permission is hereby granted, free of charge, to any person obtaining a copy ! of this software and associated documentation files (the 'Software'), to deal ! in the Software without restriction, including without limitation the rights ! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ! copies of the Software, and to permit persons to whom the Software is ! furnished to do so, subject to the following conditions: ! ! The above copyright notice and this permission notice shall be included in ! all copies or substantial portions of the Software. ! ! THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ! THE SOFTWARE. ! module MUDepthFirstSearch use MDepthFirstSearch use MGraph use MUAsserts use MUReport implicit none private type, public :: TUDepthFirstSearch contains procedure, nopass :: present end type contains subroutine present() type(TDepthFirstSearch) dfs type(TGraph) graph integer, dimension(:), pointer :: sequence real :: start call graph%init() call graph%addVertex(1) call graph%addVertex(2) call graph%addVertex(3) call graph%addVertex(4) call graph%addVertex(5) call graph%addVertex(6) ! 2 - 3 - 6 ! / ! 1 ! \ ! 4 - 5 ! expected to have 1 - 2 - 3 - 6 - 4 - 5 call graph%addEdge(1, 2) call graph%addEdge(2, 3) call graph%addEdge(3, 6) call graph%addEdge(1, 4) call graph%addEdge(4, 5) call cpu_time(start) sequence => dfs%search(graph) call report('Graph', 'DepthFirstSearch', '', start) call assert_equals(sequence(1:6), (/ 1, 2, 3, 6, 4, 5 /)) call graph%destroy() deallocate(sequence) print *, '' end subroutine end module
||| The content of this module is based on the paper ||| Applications of Applicative Proof Search ||| by Liam O'Connor module Search.Properties import Data.Fuel import Data.List.Lazy import Data.List.Lazy.Quantifiers import Data.Nat import Data.So import Data.Stream import Data.Colist import Data.Colist1 import public Search.Negation import public Search.HDecidable import public Search.Generator import Decidable.Equality %default total ------------------------------------------------------------------------ -- Type ||| Take the product of a list of types public export Product : List Type -> Type Product = foldr Pair () ||| A property amenable to testing ||| @cs is the list of generators we need (inferrable) ||| @a is the type we hope is inhabited ||| NB: the longer the list of generators, the bigger the search space! public export record Prop (cs : List Type) (a : Type) where constructor MkProp ||| The function trying to find an `a` provided generators for `cs`. ||| Made total by consuming some fuel along the way. runProp : Colist1 (Product cs) -> Fuel -> HDec a ------------------------------------------------------------------------ -- Prop-like structure ||| A type constructor satisfying the AProp interface is morally a Prop ||| It may not make use of all of the powers granted by Prop, hence the ||| associated `Constraints` list of types. public export interface AProp (0 t : Type -> Type) where 0 Constraints : List Type toProp : t a -> Prop Constraints a ||| Props are trivially AProp public export AProp (Prop cs) where Constraints = cs toProp = id ||| Half deciders are AProps that do not need any constraints to be satisfied public export AProp HDec where Constraints = [] toProp = MkProp . const . const ||| Deciders are AProps that do not need any constraints to be satisfied public export AProp Dec where Constraints = [] toProp = MkProp . (const . const . toHDec) ||| We can run an AProp to try to generate a value of type a public export check : (gen : Generator (Product cs)) => (f : Fuel) -> (p : Prop cs a) -> {auto pr : So (isTrue (runProp p (generate @{gen}) f))} -> a check @{gen} f p @{pr} = evidence (runProp p (generate @{gen}) f) pr ||| Provided that we know how to generate candidates of type `a`, we can look ||| for a witness satisfying a given predicate over `a`. public export exists : {0 p : a -> Type} -> (aPropt : AProp t) => ((x : a) -> t (p x)) -> Prop (a :: Constraints @{aPropt}) (DPair a p) exists test = MkProp $ \ acs, fuel => let candidates : LazyList a = take fuel (map fst acs) in let cs = map snd acs in let find = any candidates (\ x => runProp (toProp (test x)) cs fuel) in map toDPair find ------------------------------------------------------------------------ -- Examples namespace GT11 example : Prop ? (DPair Nat (\ i => Not (i `LTE` 10))) example = exists (\ i => not (isLTE 11 i)) lemma : DPair Nat (\ i => Not (i `LTE` 10)) lemma = check (limit 1000) example namespace Pythagoras formula : Type formula = DPair Nat $ \ m => DPair Nat $ \ n => DPair Nat $ \ p => (0 `LT` m, 0 `LT` n, 0 `LT` p , (m * m + n * n) === (p * p)) search : Prop ? Pythagoras.formula search = exists $ \ m => exists $ \ n => exists $ \ p => (isLT 0 m && isLT 0 n && isLT 0 p && decEq (m * m + n * n) (p * p)) -- This one is quite a bit slower so it's better to run -- the compiled version instead lemma : HDec Pythagoras.formula lemma = runProp search generate (limit 10)
-- 2012-09-25 Andreas, reported by Nicolas Pouillard {-# OPTIONS --sized-types #-} module Issue700 where import Common.Level open import Common.Size postulate Size< : Size → Set {-# BUILTIN SIZELT Size< #-} postulate A : Set data T (i : Size) : Set where c : (j : Size< i) → T j → T _ bug : ∀ i → T i → A bug i (c j x) = bug j x {- WAS: de Bruijn index out of scope Issue700.bug is projection like in argument 1 for type Issue700.T Translated clause: delta = (j : Size< @0) (x : T j) perm = x0,x1 -> x0,x1 ps = [r(ConP Issue700.T.c Nothing [r(VarP "j"),r(VarP "x")])] body = Bind (Abs "h1" Bind (Abs "h2" Body (Def Issue700.bug [r(Var 1 []),r(Var 0 [])]))) body = [h1 h2] bug h1 h2 -}
[STATEMENT] lemma mem_multiset_single [rewrite]: "x \<in># {#y#} \<longleftrightarrow> x = y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<in># {#y#}) = (x = y) [PROOF STEP] by simp
(* File: ZF_aux.thy Time-stamp: <2016-01-06T17:35:18Z> Author: JRF Web: http://jrf.cocolog-nifty.com/software/2016/01/post.html Logic Image: ZF (of Isabelle2015) *) theory ZF_aux imports ZF Nat_ZF Arith begin lemma function_apply_eq: "a = b ==> f(a) = f(b)" by (erule subst_context) lemma singleton_iff2: "{A} = {B} <-> A = B" apply blast done lemma Pow_Un_0_simps: "Pow(A) Un {0} = Pow(A)" "{0} Un Pow(A) = Pow(A)" by blast+ lemmas succ_neq_self_simps = succ_neq_self succ_neq_self[THEN not_sym] (** disjoint **) lemma disjointI: "[| !!x. [| x: X; x: Y |] ==> False |] ==> X Int Y = 0" by blast lemma disjointE: "[| A Int B = 0; x: A; x: B |] ==> R" by blast lemma disjoint_sym: "A Int B = 0 ==> B Int A = 0" by blast lemma disjoint_subset: "[| A Int B = 0; C <= A; D <= B |] ==> C Int D = 0" by blast lemma disjoint_UnI: "[| A Int C = 0; B Int C = 0 |] ==> (A Un B) Int C = 0" by blast lemma disjoint_Un_iff: "(A Un B) Int C = 0 <-> A Int C = 0 & B Int C = 0" by blast lemma disjoint_Un_iff2: "A Int (B Un C) = 0 <-> A Int B = 0 & A Int C = 0" by blast lemma disjoint_cons_iff: "cons(a, A) Int B = 0 <-> a ~: B & A Int B = 0" by blast lemma disjoint_cons_iff2: "A Int cons(b, B) = 0 <-> A Int B = 0 & b ~: A" by blast (** continuous **) lemma domain_continuous: "domain(Union(X)) = (UN x: X. domain(x))" by blast lemma continuous_simps_1: "{f(x). x: {g(y). y: X}} = {f(g(y)). y: X}" "Union(X) * A = (UN x: X. x * A)" by blast+ lemmas continuous_simps = domain_continuous continuous_simps_1 (** Nat **) lemma mem_nat_in_nat: "[| a: b; b: nat |] ==> a: nat" apply (rule lt_nat_in_nat) apply (erule ltI) apply (erule nat_into_Ord) apply assumption done lemma lt_Un_eq_lemma: "A < B ==> A Un B = B" apply (frule leI [THEN le_imp_subset]) apply blast done lemma le_Un_eq_lemma: "A le B ==> A Un B = B" apply (frule le_imp_subset) apply blast done lemma nat_succ_Un: "[| A: nat; B: nat |] ==> succ(A) Un succ(B) = succ(A Un B)" apply (erule nat_into_Ord [THEN Ord_linear_lt]) apply (erule nat_into_Ord) prefer 2 apply hypsubst apply blast apply (rule lt_Un_eq_lemma [THEN ssubst], assumption) apply (drule succ_leI) apply (drule lt_Un_eq_lemma, assumption) apply (rule trans[OF Un_commute lt_Un_eq_lemma, THEN ssubst], assumption) apply (drule succ_leI) apply (drule trans[OF Un_commute lt_Un_eq_lemma], assumption) done lemma nat_UnI: "[| A: nat; B: nat |] ==> A Un B: nat" apply (rule_tac i="A" and j="B" in Ord_linear_lt) apply (erule nat_into_Ord) apply (erule nat_into_Ord) apply (drule_tac [3] lt_Un_eq_lemma) apply (drule lt_Un_eq_lemma) apply (simp_all add: Un_commute) done lemma gt_not_eq: "[| p < n; n:nat|]==> n~=p" by blast lemma lt_asym_if: "p < n ==> if (n < p, a, b) = b" by (blast elim: lt_asym intro: if_not_P) lemma le_asym_if: "p le n ==> if (n < p, a, b) = b" apply (simp only: le_iff) apply (blast elim: lt_asym intro: if_not_P) done lemma lt_irrefl_if: "if (n < n, a, b) = b" by (blast intro: if_not_P) (** Arith **) lemma succ_pred: "[|j:nat; i:nat|]==> i < j --> succ(j #- 1) = j" apply (erule nat_induct) apply blast apply simp done lemma lt_pred: "[|succ(x)<n; n:nat; x:nat|]==> x < n#-1 " apply (rule succ_leE) apply (frule nat_into_Ord [THEN le_refl, THEN lt_trans], assumption) apply (simp add: succ_pred) done lemma gt_pred: "[|n < succ(x); p<n; p:nat; n:nat; x:nat|]==> n#-1 < x " apply (rule succ_leE) apply (simp add: succ_pred) done lemma lt_imp_le_pred: "[| i < j; j: nat |] ==> i le j #- 1" apply (erule natE) apply simp_all done lemma diff_eq_0D: "[| m #- n = 0; m: nat; n: nat |] ==> m le n" apply (erule rev_mp) apply (rule_tac x="m" in bspec) prefer 2 apply assumption apply (erule_tac n="n" in nat_induct) apply (rule_tac [2] ballI) apply (rename_tac [2] v) apply (erule_tac [2] n="v" in natE) apply simp_all done lemma Un_diff [rule_format]: assumes prem: "m: nat" shows "ALL n:nat. ALL l:nat. (m Un n) #- l = (m #- l) Un (n #- l)" apply (rule prem [THEN nat_induct]) apply simp apply (intro ballI) apply (erule_tac n="n" in natE) apply (erule_tac [2] n="l" in natE) apply (simp_all add: nat_succ_Un) done lemma Un_least_ltE: "[| i Un j < k; Ord(i); Ord(j); [| i < k; j < k |] ==> R |] ==> R" apply (frule_tac i1="i" and j1="j" in Un_least_lt_iff [THEN iffD1]) apply assumption+ apply blast done lemma diff_le_mono1: assumes major: "i le j" and prem1: "i: nat" and prem2: "j: nat" and prem3: "k: nat" shows "i #- k le j #- k" apply (rule major [THEN rev_mp]) apply (rule prem2 [THEN [2] bspec]) apply (rule prem3 [THEN [2] bspec]) apply (rule prem1 [THEN nat_induct]) apply simp apply (intro ballI impI) apply (rename_tac u v) apply (erule_tac n="u" in natE) apply (erule_tac [2] n="v" in natE) apply simp_all done lemma diff_ltD: assumes major: "i #- j < k" and prem1: "i: nat" and prem2: "j: nat" shows "k: nat ==> i < j #+ k" apply (rule major [THEN rev_mp]) apply (rule prem1 [THEN [2] bspec]) apply (rule prem2 [THEN nat_induct]) apply simp apply (intro ballI impI) apply (rename_tac v) apply (erule_tac n="v" in natE) apply simp_all done lemma diff_leI: assumes major: "i le j #+ k" and prem1: "i: nat" and prem2: "j: nat" shows "k: nat ==> i #- j le k" apply (rule major [THEN rev_mp]) apply (rule prem1 [THEN [2] bspec]) apply (rule prem2 [THEN nat_induct]) apply simp apply (intro ballI impI) apply (rename_tac v) apply (erule_tac n="v" in natE) apply simp_all done lemma diff_le_iff: "[| i: nat; j: nat; k: nat |] ==> i #- j le k <-> i le j #+ k" apply (rule iffI) apply (rule_tac [2] diff_leI) apply (drule diff_ltD) apply simp_all done lemma lt_diffI: assumes major: "i #+ j < k" and prem1: "i: nat" and prem2: "j: nat" and prem3: "k: nat" shows "j < k #- i" apply (insert prem2) apply (rule major [THEN rev_mp]) apply (rule prem1 [THEN [2] bspec]) apply (rule prem3 [THEN nat_induct]) apply simp apply (intro ballI impI) apply (rename_tac v) apply (erule_tac n="v" in natE) apply simp_all done lemma lt_diffD: assumes major: "j < k #- i" and prem1: "i: nat" and prem2: "j: nat" and prem3: "k: nat" shows "i #+ j < k" apply (insert prem2) apply (rule major [THEN rev_mp]) apply (rule prem1 [THEN [2] bspec]) apply (rule prem3 [THEN nat_induct]) apply simp apply (intro ballI impI) apply (rename_tac v) apply (erule_tac n="v" in natE) apply simp_all done lemma lt_diff_iff: "[| i: nat; j: nat; k: nat |] ==> j < k #- i <-> i #+ j < k" apply (rule iffI) apply (erule_tac [2] lt_diffI) apply (erule lt_diffD) apply assumption+ done lemma diff_diff_eq_diff_add: assumes prem1: "i: nat" and prem2: "j: nat" and prem3: "k: nat" shows "i #- j #- k = i #- (k #+ j)" apply (rule prem1 [THEN [2] bspec]) apply (rule prem3 [THEN [2] bspec]) apply (rule prem2 [THEN nat_induct]) apply simp apply (intro ballI) apply (rename_tac u v) apply (erule_tac n="v" in natE) apply simp_all done (** Quantifiers Bounded by Natural Number **) lemmas nat_ltI = nat_into_Ord [THEN [2] ltI] lemma ball_mem_nat_in_nat: "n: nat ==> (ALL x:n. x:nat) <-> True" apply (blast intro: mem_nat_in_nat) done lemma nat_succ_mono: "[| n:m; m: nat |] ==> succ(n): succ(m)" apply (rule ltD) apply (simp add: nat_ltI) done lemma nat_ball_succ: "n: nat ==> (ALL x:succ(n). P(x)) <-> P(0) & (ALL x:n. P(succ(x)))" apply safe apply (erule bspec) apply (rule ltD) apply simp apply (drule nat_ltI, assumption) apply (erule bspec) apply (rule ltD) apply simp apply (erule natE) apply simp+ apply (frule_tac mem_nat_in_nat, assumption) apply (erule_tac n="x" in natE) apply simp apply (rename_tac v) apply (drule_tac x="v" in bspec) apply simp_all apply (rule ltD) apply (drule_tac i="succ(v)" in ltI) apply (erule nat_into_Ord) apply (simp add: succ_lt_iff) done lemma nat_bex_succ: "n: nat ==> (EX x:succ(n). P(x)) <-> P(0) | (EX x:n. P(succ(x)))" apply safe apply simp_all apply (erule natE) apply simp apply (drule_tac x="x" in bspec) apply simp apply simp apply (frule mem_nat_in_nat, assumption) apply (erule_tac n="x" in natE) apply simp apply (rename_tac v) apply (drule_tac x="v" in bspec) apply simp apply (rule ltD) apply (drule_tac i="succ(v)" in ltI) apply (erule nat_into_Ord) apply (simp add: succ_lt_iff) apply simp apply (erule natE) apply simp apply hypsubst apply (rule disjI2) apply (rule bexI, assumption) apply (rule ltD) apply (erule nat_0_le) apply (case_tac "n = succ(x)") apply simp apply (rule disjI2) apply (rule bexI, assumption) apply (frule_tac i="n" and j="succ(x)" in nat_into_Ord [THEN Ord_linear]) apply (rule nat_into_Ord) apply (frule mem_nat_in_nat, assumption) apply (erule nat_succI) apply simp apply (blast elim: mem_irrefl mem_asym) done lemma nat_ball_cong: assumes prem1: "A = A'" and prem2: "!!x. x < A' ==> P(x) <-> P'(x)" and prem3: "!!x. [| x: A'; A'~: nat |] ==> P(x) <-> P'(x)" shows "Ball(A, P) <-> Ball(A', P')" apply (rule prem1 [THEN ball_cong]) apply (case_tac "A' : nat") apply (rule prem2) apply (erule ltI) apply (erule nat_into_Ord) apply (erule prem3) apply assumption done lemma nat_bex_cong: assumes prem1: "A = A'" and prem2: "!!x. x < A' ==> P(x) <-> P'(x)" and prem3: "!!x. [| x: A'; A'~: nat |] ==> P(x) <-> P'(x)" shows "Bex(A, P) <-> Bex(A', P')" apply (rule prem1 [THEN bex_cong]) apply (case_tac "A' : nat") apply (rule prem2) apply (erule ltI) apply (erule nat_into_Ord) apply (erule prem3) apply assumption done lemmas nat_bquant_congs = nat_ball_cong nat_bex_cong lemma nat_bquant_succ1_1: "(ALL x:succ(i).P(x)) <-> P(i) & (ALL x:i. P(x))" by simp lemma nat_bquant_succ1_2: "(EX x:succ(i).P(x)) <-> P(i) | (EX x:i. P(x))" by simp lemmas nat_bquant_succ1 = nat_bquant_succ1_1 nat_bquant_succ1_2 lemmas nat_bquant_succ2 = nat_ball_succ nat_bex_succ (* declare nat_bquant_succ1 [simp del] declare nat_bquant_succ2 [simp] *) lemma complete_induct0: "[| i : nat; !! i. [| i : nat; (ALL j: i. P(j)) |] ==> P(i) |] ==> P(i)" apply (erule complete_induct) apply simp done end
clc; clear; close all; warning off; addpath(genpath(cd)); I=double(imread('E:\lichang\1.Image fusion total variation\img\tank\tank_IR.png'))/255; %V=double(imread('E:\lichang\1.Image fusion total variation\img\tank\tank_VIS.png'))/255; % I=histeq(I); % V=histeq(V); % figure; imshow(I); % figure; imshow(V); % imwrite(I,'new_4917_IR.png','png'); % imwrite(V,'new_4917_VIS.png','png'); % I=rgb2gray(I); % V=rgb2gray(V); %proposed nmpdef; pars_irn = irntvInputPars('l2tv'); pars_irn.adapt_epsR = 1; pars_irn.epsR_cutoff = 0.01; % This is the percentage cutoff pars_irn.adapt_epsF = 1; pars_irn.epsF_cutoff = 0.05; % This is the percentage cutoff pars_irn.pcgtol_ini = 1e-4; pars_irn.loops = 5; pars_irn.U0 = I; pars_irn.variant = NMP_TV_SUBSTITUTION; pars_irn.weight_scheme = NMP_WEIGHTS_THRESHOLD; pars_irn.pcgtol_ini = 1e-2; pars_irn.adaptPCGtol = 1; Final_Metric=zeros(6,1); tic; for i=[0.1:0.1:0.9]%[0.01:0.01:0.09 0.1:0.1:0.9 1:10 20:10:100] X = irntv(I, {}, i, pars_irn); X=im2gray(X); imwrite(X,strcat('Proposed_tank_',strcat(num2str(i),'.png')),'png'); %figure; %imshow(X); % Result = Metric(uint8(abs(I)*255),uint8(abs(V)*255),uint8(abs(X*255))); % temp=Result.Total; % Final_Metric=max(Final_Metric,temp); end
! { dg-do compile } ! { dg-options "-Wc-binding-type" } ! { dg-require-visibility "" } ! This should compile, though there is a warning about the type of len ! (return variable of strlen()) for being implicit. ! PR fortran/32797 ! MODULE ISO_C_UTILITIES USE ISO_C_BINDING implicit none CHARACTER(C_CHAR), DIMENSION(1), SAVE, TARGET, PRIVATE :: dummy_string="?" CONTAINS FUNCTION C_F_STRING(CPTR) RESULT(FPTR) use, intrinsic :: iso_c_binding TYPE(C_PTR), INTENT(IN) :: CPTR ! The C address CHARACTER(KIND=C_CHAR), DIMENSION(:), POINTER :: FPTR INTERFACE FUNCTION strlen(string) RESULT(len) BIND(C,NAME="strlen") ! { dg-warning "Implicitly declared" } USE ISO_C_BINDING TYPE(C_PTR), VALUE :: string ! A C pointer END FUNCTION END INTERFACE CALL C_F_POINTER(FPTR=FPTR, CPTR=CPTR, SHAPE=[strlen(CPTR)]) END FUNCTION END MODULE ISO_C_UTILITIES
-- -- An instance of this template must have a $Export section and the export_terminals option -- -- Macros that may be redefined in an instance of this template -- -- $eof_token -- $additional_interfaces -- $super_stream_class -- subclass com.ibm.lpg.Utf8LpgLexStream for getKind -- $prs_stream_class -- use /.PrsStream./ if not subclassing -- -- B E G I N N I N G O F T E M P L A T E LexerTemplateD -- %Options programming_language=rt_cpp,margin=4 %Options table %options action-block=("*.h", "/.", "./") %options ParseTable=ParseTable %Options prefix=Char_ -- -- This template requires that the name of the EOF token be set -- to EOF and that the prefix be "Char_" to be consistent with -- KeywordTemplateD. -- %Eof EOF %End -- -- This template also requires that the name of the parser EOF -- Token to be exported be set to EOF_TOKEN -- %Export EOF_TOKEN %End %Define -- -- Macros that are be needed in an instance of this template -- $eof_token /.$_EOF_TOKEN./ $additional_interfaces /../ $super_stream_class /.$file_prefix$Utf8LpgLexStream./ $prs_stream_class /.IPrsStream./ $super_class /.Object./ -- -- Macros useful for specifying actions -- $Header /. // // Rule $rule_number: $rule_text // ./ $DefaultAction /.$Header$case $rule_number: { ./ $BeginAction /.$DefaultAction./ $EndAction /. break; }./ $BeginJava /.$BeginAction $symbol_declarations./ $EndJava /.$EndAction./ $NoAction /.$Header$case $rule_number: break; ./ $BeginActions /. void ruleAction( int ruleNumber) { switch(ruleNumber) {./ $SplitActions /. default: ruleAction$rule_number(ruleNumber); break; } return; } void ruleAction$rule_number(int ruleNumber) { switch (ruleNumber) {./ $EndActions /. default: break; } return; }./ %End %Globals /. ./ %End %Headers /. #pragma once #include <iostream> #include "IPrsStream.h" #include "Object.h" #include "ParseTable.h" #include "RuleAction.h" #include "stringex.h" #include "Token.h" #include "$sym_type.h" #include "$prs_type.h" #include "$kw_lexer_class.h" #include "LexParser.h" #include "Utf8LpgLexStream.h" struct $action_type :public $super_class, public RuleAction$additional_interfaces { struct $super_stream_class; $super_stream_class *lexStream= nullptr; ~$action_type(){ delete lexStream; delete lexParser; } inline static ParseTable* prs = new $prs_type(); ParseTable* getParseTable() { return prs; } LexParser* lexParser = new LexParser(); LexParser* getParser() { return lexParser; } int getToken(int i) { return lexParser->getToken(i); } int getRhsFirstTokenIndex(int i) { return lexParser->getFirstToken(i); } int getRhsLastTokenIndex(int i) { return lexParser->getLastToken(i); } int getLeftSpan() { return lexParser->getToken(1); } int getRightSpan() { return lexParser->getLastToken(); } void resetKeywordLexer() { if (kwLexer == nullptr) this->kwLexer = new $kw_lexer_class(lexStream->getInputBytes(), $_IDENTIFIER); else this->kwLexer->setInput(lexStream->getInputBytes()); } void reset(const std::wstring& filename, int tab) { delete lexStream; lexStream = new $super_stream_class(filename, tab); lexParser->reset((ILexStream*) lexStream, prs,this); resetKeywordLexer(); } void reset(shared_ptr_string input_bytes, const std::wstring& filename) { reset(input_bytes, filename, 1); } void reset(shared_ptr_string input_bytes, const std::wstring& filename, int tab) { lexStream = new $super_stream_class(input_bytes, filename, tab); lexParser->reset((ILexStream*) lexStream, prs, this); resetKeywordLexer(); } $action_type(const std::wstring& filename, int tab) { reset(filename, tab); } $action_type(shared_ptr_string input_bytes, const std::wstring& filename, int tab) { reset(input_bytes, filename, tab); } $action_type(shared_ptr_string input_bytes, const std::wstring& filename) { reset(input_bytes, filename, 1); } $action_type() {} ILexStream* getILexStream() { return lexStream; } /** * @deprecated replaced by {@link #getILexStream()} */ ILexStream* getLexStream() { return lexStream; } void initializeLexer($prs_stream_class * prsStream, int start_offset, int end_offset) { if (lexStream->getInputBytes().size() == 0) throw std::exception("LexStream was not initialized"); lexStream->setPrsStream(prsStream); prsStream->makeToken(start_offset, end_offset, 0); // Token list must start with a bad token } void lexer($prs_stream_class* prsStream) { lexer(nullptr, prsStream); } void lexer(Monitor* monitor, $prs_stream_class* prsStream) { if (lexStream->getInputBytes().size() == 0) throw std::exception("lexStream was not initialized"); lexStream->setPrsStream(prsStream); prsStream->makeToken(0, 0, 0); // Token list must start with a bad token lexParser->parseCharacters(monitor); // Lex the input characters int i = lexStream->getStreamIndex(); prsStream->makeToken(i, i, $eof_token); // and end with the end of file token prsStream->setStreamLength(prsStream->getSize()); return; } ./ %End %Rules /.$BeginActions./ %End %Trailers /. $EndActions }; ./ %End -- -- E N D O F T E M P L A T E --
\documentclass[../../main.tex]{subfiles} \begin{document} % START SKRIV HER \section{Inventory Pooling} Risk pooling is an important concept in supply chain management, as it can reduce the need for safety stock. Conceptionally, aggregated demand across locations will reduce demand variability since higher-than-expected demand in one location is likely to be offset by lower-than-expected demand in another location. Similarly, aggregated forecasts are more accurate than… hence reduce the risk and need for safety stock. A strategy for risk pooling could be to centralize inventory in one central warehouse. In our case, instead of one warehouse each in Bergen and Oslo, we could have one central warehouse in between, which would serve both Bergen and Oslo customers. Demand for Bergen/Oslo area would then be aggregated, and demand variability would be reduced. Since safety stock is the stock to cover demand variability, this would be reduced, hence the average needed inventory position needed will also reduce. The benefit of risk pooling increases as demand variability increases. An increase in the coefficient of variation translates to an increased need for safety stock. If two demand regions are aggregated, however, the coefficient of variation would reduce, hence reducing the need for safety stock and also the average inventory needed. This would drive down cost of storing inventory, or it can free up resources for new inventory, which will increase the selection for customers. The benefit of risk pooling comes from the fact that increased demand in one region is offset by decreased demand in another region. Consequently, the benefit is reduced when demand in different locations becomes more positively correlated. Due to the risk pooling effect, retailers might favor centralized over decentralized systems, i.e. a central warehouses over having one warehouse in each demand region. In terms of safety stock, service level and fixed costs, it will be beneficial. As demand variability decreases, safety stock can be reduced. When the central warehouse has the same inventory as the regional warehouses combined, and demand for the regions are not perfectly correlated, the service level will be higher for the centralized system. Finally, fixed costs is lower with one warehouse compared to multiple. Definition of service level. However, centralized systems are not always favorable over decentralized ones. First, since the distance to customers will be larger, customer lead times are likely to be much higher. Since transportation costs are a function of distance, these are also likely to be higher. In the online retail industry, customer lead time is a major competitive advantage (source). In our case, it is not possible to deliver same-day delivery using a centralized warehouse. Since this is a major concern for our company, a centralized system is not an option. • A table with centralized vs decentralized might be useful here Trade-off inventory levels * High safety stock costly * Low safety stock risky as it increases the chance of lost sales (especially in online retail) * First rule of inventory management: Forecast is always wrong * Second rule: Aggregate demand information is always more accurate than dis-aggregate data * => Combined: Risk pooling With complete pooling, a stock-out occurs if and only if (sum av D all warehouse > sum av S all warehoues) https://pubsonline.informs.org/doi/abs/10.1287/msom.4.1.12.284 % SLUTT SKRIV HER \end{document}
{- This example used to fail but after the point-free evaluation fix it seems to work #-} module Issue259c where postulate A : Set a : A b : ({x : A} → A) → A C : A → Set d : {x : A} → A d {x} = a e : A e = b (λ {x} → d {x}) F : C e → Set₁ F _ with Set F _ | _ = Set
Only within the last 16 months, the world has seen the emergence of the Sustainable Development Goals (SDG), the Paris agreement which has just recently come into force, and the so called New Urban Agenda (NUA). All three of them represent bold and (more or less) legally binding agreements by the Member States of the United Nations. The New Urban Agenda should be the most concrete and practical one since it addresses the smaller scale of government, i.e. cities – the place where we will win or lose our struggle for a more just, equitable and indeed sustainable world. November 8, 2016 Comments Off on The New Urban Agenda: More Power to Cities? Yes, but how? On September 22 2013, 50.9% of the Hamburg citizens voted in a referendum for the full remunicipalisation of the energy distribution grids in the city. The referendum was initiated by the citizen’s initiative ‘Our Hamburg – Our Grid’ (OHOG) and constituted the climax of an intense political controversy that lasted for more than three years. Through this vote Hamburg has received international attention and became a flagship example for remarkable civil engagement. In the international best-seller “This Changes Everything” (2014), Naomi Klein sees the driving motive in the people’s ‘desire for local power’. Indeed it is true that under the constitution of the City of Hamburg, a successful referendum has a binding effect, which left the City government no other option than to announce the implementation of the referendum decision and to start the remunicipalisation process immediately after the vote. Now, three years after the referendum, it is time to evaluate what has been achieved so far. A series of interviews with key actors that were and, for the most part, still are involved in the remunicipalisation process shed some light on the remunicipalisation process and recent developments. It is almost time. One of the most important international summits is on our doorstep. Next week the UN General Assembly will be gathering in Quito, Ecuador to (hopefully) agree and sign the so called New Urban Agenda, the international urban “constitution” supposed to be guiding sustainable urban development in the next 20 years. Almost 40,000 participants from all around the world have registered. After the successful adoption of the Sustainable Development Goals (SDG) and the Paris agreement, expectations on the next UN cities summit are high. The question however is: will it deliver? Will delegates agree on a meaningful outcome that ultimately provides guidance for national and local governments? Will it keep up to the promise to be the “SDG implementation summit”? In fact, the goals and principles of the SDGs and the Paris agreement will be confronted with a reality check – since first and foremost much of their substance will have to be implemented by the cities of this world. October 13, 2016 Comments Off on Habitat III. The upcoming UN cities summit is as important as the Paris Climate Conference – but will it deliver?
[STATEMENT] lemma image_set [code]: "image f (set xs) = set (map f xs)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. f ` set xs = set (map f xs) [PROOF STEP] by simp
lemma reflect_poly_const [simp]: "reflect_poly [:a:] = [:a:]"
import Lean import Lean.Meta import Lean.Elab import Lean.Parser import Lean.Parser.Extension import LeanCodePrompts.Utils open Lean Meta Elab Parser Tactic def depsPrompt : IO (Array String) := do let file ← reroutePath <| System.mkFilePath ["data/types.txt"] IO.FS.lines file declare_syntax_cat typed_ident syntax "(" ident ":" term ")" : typed_ident syntax "{" ident ":" term "}" : typed_ident #check Array.foldrM #check TSyntaxArray.rawImpl #check TSyntax.mk instance : Coe (Syntax) (TSyntax n) where coe := TSyntax.mk instance : Coe (Array Syntax) (Array (TSyntax n)) where coe := Array.map Coe.coe /-- check whether a string parses as a term -/ def checkTerm (s : String) : MetaM Bool := do let env ← getEnv let chk := Lean.Parser.runParserCategory env `term s match chk with | Except.ok _ => pure true | Except.error _ => pure false /-- split prompts into those that parse -/ def promptsSplit : MetaM ((Array String) × (Array String)) := do let deps ← depsPrompt let mut succ: Array String := Array.empty let mut fail: Array String := Array.empty for type in deps do let chk ← checkTerm type if chk then succ := succ.push type else fail := fail.push type return (succ, fail) declare_syntax_cat argument syntax "(" ident+ " : " term ")" : argument syntax "{" ident+ " : " term "}" : argument syntax "[" ident " : " term "]" : argument syntax "[" term "]" : argument declare_syntax_cat thmStat syntax argument* docComment "theorem" argument* ":" term : thmStat syntax "theorem" (ident)? argument* ":" term : thmStat syntax "def" ident argument* ":" term : thmStat syntax argument* ":" term : thmStat def thmsPrompt : IO (Array String) := do let file ← reroutePath <| System.mkFilePath ["data/thms.txt"] IO.FS.lines file /-- check whether a string parses as a theorem -/ def checkThm (s : String) : MetaM Bool := do let env ← getEnv let chk := Lean.Parser.runParserCategory env `thmStat s match chk with | Except.ok stx => IO.println stx pure true | Except.error _ => pure false #check Syntax partial def tokens (s : Syntax) : Array String := match s with | .missing => Array.empty | .node _ _ args => args.foldl (fun acc x => acc ++ tokens x) Array.empty | .atom _ val => #[val] | .ident _ val .. => #[val.toString] def getTokens (s: String) : MetaM <| Array String := do let env ← getEnv let chk := Lean.Parser.runParserCategory env `thmStat s match chk with | Except.ok stx => pure <| tokens stx | Except.error _ => pure Array.empty -- #eval getTokens "{α : Type u} [group α] [has_lt α] [covariant_class α α (function.swap has_mul.mul) has_lt.lt] {a : α} : 1 < a⁻¹ ↔ a < 1" /-- split prompts into those that parse -/ def promptsThmSplit : MetaM ((Array String) × (Array String)) := do let deps ← thmsPrompt let mut succ: Array String := Array.empty let mut fail: Array String := Array.empty for type in deps do let chk ← checkThm type if chk then succ := succ.push type else fail := fail.push type return (succ, fail) def promptsThmSplitCore : CoreM ((Array String) × (Array String)) := promptsThmSplit.run' def levelNames := [`u, `v, `u_1, `u_2, `u_3, `u_4, `u_5, `u_6, `u_7, `u_8, `u_9, `u_10, `u_11, `u₁, `u₂, `W₁, `W₂, `w₁, `w₂, `u', `v', `uu, `w, `wE] partial def idents : Syntax → List String | Syntax.ident _ s .. => [s.toString] | Syntax.node _ _ ss => ss.toList.bind idents | _ => [] def elabThm (s : String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : TermElabM <| Except String Expr := do let env ← getEnv let chk := Lean.Parser.runParserCategory env `thmStat s match chk with | Except.ok stx => match stx with | `(thmStat| $_:docComment theorem $args:argument* : $type:term) => elabAux type args | `(thmStat|theorem $_ $args:argument* : $type:term) => elabAux type args | `(thmStat|theorem $args:argument* : $type:term) => elabAux type args | `(thmStat|$vars:argument* $_:docComment theorem $args:argument* : $type:term ) => elabAux type (vars ++ args) | `(thmStat|def $_ $args:argument* : $type:term) => elabAux type args | `(thmStat|$args:argument* : $type:term) => elabAux type args | _ => return Except.error s!"parsed incorrectly to {stx}" | Except.error e => return Except.error e where elabAux (type: Syntax)(args: Array Syntax) : TermElabM <| Except String Expr := do let header := if opens.isEmpty then "" else (opens.foldl (fun acc s => acc ++ " " ++ s) "open ") ++ " in " let mut argS := "" for arg in args do argS := argS ++ (showSyntax arg) ++ " -> " let funStx := s!"{header}{argS}{showSyntax type}" match Lean.Parser.runParserCategory (← getEnv) `term funStx with | Except.ok termStx => Term.withLevelNames levelNames <| try let expr ← Term.withoutErrToSorry <| Term.elabTerm termStx none return Except.ok expr catch e => return Except.error s!"{← e.toMessageData.toString} ; identifiers {idents termStx} (during elaboration)" | Except.error e => return Except.error s!"parsed to {funStx}; error while parsing as theorem: {e}" def elabThmCore (s : String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : CoreM <| Except String Expr := (elabThm s opens levelNames).run'.run' theorem true_true_iff_True : true = true ↔ True := by apply Iff.intro intros exact True.intro intros rfl theorem true_false_iff_false : false = true ↔ False := by apply Iff.intro intro hyp simp at hyp intro hyp contradiction syntax "lynx" ("at" ident)? : tactic syntax "lynx" "at" "*" : tactic macro_rules | `(tactic| lynx) => `(tactic|try(repeat rw [true_true_iff_True]);try (repeat (rw [true_false_iff_false]))) | `(tactic| lynx at $t:ident) => `(tactic| try(repeat rw [true_true_iff_True] at $t:ident);try (repeat (rw [true_false_iff_false] at $t:ident))) | `(tactic| lynx at *) => `(tactic|try(repeat rw [true_true_iff_True] at *);try (repeat (rw [true_false_iff_false] at *))) def provedEqual (e₁ e₂ : Expr) : TermElabM Bool := do let type ← mkEq e₁ e₂ let mvar ← mkFreshExprMVar <| some type let mvarId := mvar.mvarId! let stx ← `(tactic| lynx; try (rfl)) let res ← runTactic mvarId stx let (remaining, _) := res return remaining.isEmpty def provedEquiv (e₁ e₂ : Expr) : TermElabM Bool := do try let type ← mkAppM ``Iff #[e₁, e₂] let mvar ← mkFreshExprMVar <| some type let mvarId := mvar.mvarId! let stx ← `(tactic| intros; lynx at *<;> apply Iff.intro <;> intro hyp <;> (lynx at *) <;> (try assumption) <;> try (intros; apply Eq.symm; apply hyp)) let res ← runTactic mvarId stx let (remaining, _) := res return remaining.isEmpty catch _ => pure false def compareThms(s₁ s₂ : String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : TermElabM <| Except String Bool := do let e₁ ← elabThm s₁ opens levelNames let e₂ ← elabThm s₂ opens levelNames match e₁ with | Except.ok e₁ => match e₂ with | Except.ok e₂ => let p := (← provedEqual e₁ e₂) || (← provedEquiv e₁ e₂) return Except.ok p | Except.error e₂ => return Except.error e₂ | Except.error e₁ => return Except.error e₁ def compareThmsCore(s₁ s₂ : String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : CoreM <| Except String Bool := (compareThms s₁ s₂ opens levelNames).run'.run' def compareThmExps(e₁ e₂: Expr) : TermElabM <| Except String Bool := do let p := (← provedEqual e₁ e₂) || (← provedEquiv e₁ e₂) return Except.ok p def compareThmExpsCore(e₁ e₂: Expr) : CoreM <| Except String Bool := do (compareThmExps e₁ e₂).run'.run' def equalThms(s₁ s₂ : String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : TermElabM Bool := do match ← compareThms s₁ s₂ opens levelNames with | Except.ok p => return p | Except.error _ => return false def groupThms(ss: Array String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : TermElabM (Array (Array String)) := do let mut groups: Array (Array String) := Array.empty for s in ss do match ← groups.findIdxM? (fun g => equalThms s g[0]! opens levelNames) with |none => groups := groups.push #[s] | some j => groups := groups.set! j (groups[j]!.push s) return groups def groupTheoremsCore(ss: Array String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : CoreM (Array (Array String)) := (groupThms ss opens levelNames).run'.run' def groupThmsSort(ss: Array String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : TermElabM (Array (Array String)) := do let gps ← groupThms ss opens levelNames return gps.qsort (fun xs ys => xs.size > ys.size) def groupThmsSortCore(ss: Array String)(opens: List String := []) (levelNames : List Lean.Name := levelNames) : CoreM (Array (Array String)) := (groupThmsSort ss opens levelNames).run'.run' -- Tests -- #eval checkTerm "(fun x : Nat => x + 1)" -- #eval checkTerm "a • s" -- #eval checkTerm "λ x : Nat, x + 1" -- #eval checkTerm "a - t = 0" def checkStatements : MetaM (List (String × Bool)) := do let prompts ← depsPrompt (prompts.toList.take 50).mapM fun s => do return (s, ← checkTerm s) def tryParseThm (s : String) : MetaM String := do let env ← getEnv let chk := Lean.Parser.runParserCategory env `thmStat s match chk with | Except.ok stx => match stx with | `(thmStat|theorem $_ $args:argument* : $type:term) => let mut argS := "" for arg in args do argS := argS ++ (showSyntax arg) ++ " -> " let funStx := s!"{argS}{showSyntax type}" pure s!"match: {funStx}" | `(thmStat|$args:argument* : $type:term) => let mut argS := "" for arg in args do argS := argS ++ (showSyntax arg) ++ " -> " let funStx := s!"{argS}{showSyntax type}" pure s!"match: {funStx}" | _ => pure s!"parsed to mysterious {stx}" | Except.error e => pure s!"error: {e}" -- #eval tryParseThm "theorem blah (n : Nat) {m: Type} : n = n" -- #eval elabThm "(p: Nat)/-- blah test -/ theorem (n : Nat) {m: Type} : n = p" def eg := "section variable (α : Type) {n : Nat} /-- A doc that should be ignored -/ theorem blah (m: Nat) : n = m " -- #eval checkThm eg -- #eval checkThm "(n : Nat) {m: Type} : n = n" -- #eval tryParseThm "theorem subfield.list_sum_mem {K : Type u} [field K] (s : subfield K) {l : list K} : (∀ (x : K), x ∈ l → x ∈ s) → l.sum ∈ s" def checkElabThm (s : String) : TermElabM String := do let env ← getEnv let chk := Lean.Parser.runParserCategory env `thmStat s match chk with | Except.ok stx => match stx with | `(thmStat|theorem $_ $args:argument* : $type:term) => let mut argS := "" for arg in args do argS := argS ++ (showSyntax arg) ++ " -> " let funStx := s!"{argS}{showSyntax type}" match Lean.Parser.runParserCategory env `term funStx with | Except.ok termStx => Term.withLevelNames levelNames <| try let expr ← Term.withoutErrToSorry <| Term.elabTerm termStx none pure s!"elaborated: {← expr.view} from {funStx}" catch e => pure s!"{← e.toMessageData.toString} during elaboration" | Except.error e => pure s!"parsed to {funStx}; error while parsing: {e}" | `(thmStat|$vars:argument* $_:docComment theorem $args:argument* : $type:term ) => let mut argS := "" for arg in vars ++ args do argS := argS ++ (showSyntax arg) ++ " -> " let funStx := s!"{argS}{showSyntax type}" match Lean.Parser.runParserCategory env `term funStx with | Except.ok termStx => Term.withLevelNames levelNames <| try let expr ← Term.withoutErrToSorry <| Term.elabTerm termStx none pure s!"elaborated: {← expr.view} from {funStx}" catch e => pure s!"{← e.toMessageData.toString} during elaboration" | Except.error e => pure s!"parsed to {funStx}; error while parsing: {e}" | `(thmStat|$args:argument* : $type:term) => let mut argS := "" for arg in args do argS := argS ++ (showSyntax arg) ++ " -> " let funStx := s!"{argS}{showSyntax type}" match Lean.Parser.runParserCategory env `term funStx with | Except.ok termStx => Term.withLevelNames levelNames <| try let expr ← Term.withoutErrToSorry <| Term.elabTerm termStx none pure s!"elaborated: {← expr.view} from {funStx}" catch e => pure s!"{← e.toMessageData.toString} during elaboration" | Except.error e => pure s!"parsed to {funStx}; error while parsing: {e}" | _ => pure s!"parsed to mysterious {stx}" | Except.error e => pure s!"error: {e}" -- #eval checkElabThm "theorem blah (n : Nat) {m : Nat} : n = m" -- #eval checkElabThm eg -- #eval checkElabThm "theorem subfield.list_sum_mem {K : Type u} [field K] (s : subfield K) {l : list K} : (∀ (x : K), x ∈ l → x ∈ s) → l.sum ∈ s" -- #eval elabThm "theorem blah (n : Nat) {m : Nat} : n = m" -- #eval elabThm "theorem (n : Nat) {m : Nat} : n = m" -- #eval elabThm "theorem blah (n : Nat) {m : Nat} : n = succ n" ["Nat"] -- #eval elabThm "theorem blah (n : Nat) {m : Nat} : n = succ n" ["Nat"] -- #eval elabThm "(n : Nat) {m : Nat} : n = succ n" ["Nat"] -- #eval elabThmCore "(n : Nat) {m : Nat} : n = succ n" ["Nat"] -- #eval elabThm "theorem subfield.list_sum_mem {K : Type u} [field K] (s : subfield K) {l : list K} : (∀ (x : K), x ∈ l → x ∈ s) → l.sum ∈ s" -- #eval compareThms "theorem nonsense(n : Nat) (m : Nat) : n = m" "(p : Nat)(q: Nat) : p = q" -- #eval compareThms ": True" ": true = true" -- #eval compareThms "{A: Type} : A → True" "{A: Type}: A → true" -- #eval compareThms ": False" ": false = true" -- #eval compareThms "{A: Sort} : False → A" "{A: Sort} : false = true → A" example : (∀ {A: Sort}, False → A) ↔ (∀ {A: Sort}, false = true → A) := by intros; lynx at *<;> apply Iff.intro <;> intro hyp <;> (lynx at *) <;> (try assumption) <;> try (intros; apply Eq.symm; apply hyp) example : (∀ (a b c: Nat), a + (b + c) = (a + b) + c) ↔ (∀ (a b c: Nat), (a + b) + c = a + (b + c)) := by intros; apply Iff.intro <;> intro hyp <;> (try assumption) <;> try (intros; apply Eq.symm; apply hyp) -- #eval compareThms "(a b c: Nat): a + (b + c) = (a + b) + c" "(a b c: Nat): (a + b) + c = a + (b + c)"
lemma uniformity_trans': "eventually E uniformity \<Longrightarrow> eventually (\<lambda>((x, y), (y', z)). y = y' \<longrightarrow> E (x, z)) (uniformity \<times>\<^sub>F uniformity)"
[STATEMENT] lemma signed_div_arith: "sint ((a::('a::len) word) sdiv b) = signed_take_bit (LENGTH('a) - 1) (sint a sdiv sint b)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. sint (a sdiv b) = signed_take_bit (LENGTH('a) - 1) (sint a sdiv sint b) [PROOF STEP] apply transfer [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>a b. signed_take_bit (LENGTH('a) - Suc 0) (signed_take_bit (LENGTH('a) - Suc 0) a sdiv signed_take_bit (LENGTH('a) - Suc 0) b) = signed_take_bit (LENGTH('a) - 1) (signed_take_bit (LENGTH('a) - Suc 0) a sdiv signed_take_bit (LENGTH('a) - Suc 0) b) [PROOF STEP] apply simp [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
pascalTriangle <- function(h) { for(i in 0:(h-1)) { s <- "" for(k in 0:(h-i)) s <- paste(s, " ", sep="") for(j in 0:i) { s <- paste(s, sprintf("%3d ", choose(i, j)), sep="") } print(s) } }
function centroid = polygon_centroid_2 ( n, v ) %*****************************************************************************80 % %% POLYGON_CENTROID_2 computes the centroid of a polygon. % % Discussion: % % The centroid is the area-weighted sum of the centroids of % disjoint triangles that make up the polygon. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 17 October 2005 % % Author: % % John Burkardt % % Reference: % % Adrian Bowyer and John Woodwark, % A Programmer's Geometry, % Butterworths, 1983. % % Parameters: % % Input, integer N, the number of vertices of the polygon. % % Input, real V(2,N), the coordinates of the vertices. % % Output, real CENTROID(2,1), the coordinates of the centroid. % area = 0.0; centroid(1:2,1) = 0.0; for i = 1 : n - 2 area_triangle = triangle_area ( ... v(1,i), v(2,i), ... v(1,i+1), v(2,i+1), ... v(1,n), v(2,n) ); area = area + area_triangle; centroid(1:2,1) = centroid(1:2,1) + area_triangle ... * ( v(1:2,i) + v(1:2,i+1) + v(1:2,n) ) / 3.0; end if ( area == 0.0 ) centroid(1:2,1) = v(1:2,1); else centroid(1:2,1) = centroid(1:2,1) / area; end return end
import sys import math import numpy as np light_x, light_y, initial_tx, initial_ty = [int(i) for i in input().split()] # 현재 위치를 기준으로 light의 사분면 파악하기 remain_x = light_x - initial_tx remain_y = light_y - initial_ty dir_arr = ['N','S','E','W',''] val_arr = [[0,1], [0,-1], [1,0], [-1,0], [0,0]] # game loop while True: remaining_turns = int(input()) # The remaining amount of turns Thor can move. Do not remove this line. condition_arr = [(remain_y < 0), (remain_y > 0), \ (remain_x > 0), (remain_x < 0), \ (remain_x == 0 or remain_y == 0)] ch_dir = '' # True인 값만 찾아 index 가져오기 for cond_idx in np.where(condition_arr)[0]: ch_dir += str(dir_arr[cond_idx]) remain_x += -1 * val_arr[cond_idx][0] remain_y += val_arr[cond_idx][1] print(ch_dir)
import Hw5 import Lean.Elab.Print import Lean.Elab.Command theorem desiredType (A B : Prop) : ¬ (A ∨ B) ↔ ¬ A ∧ ¬ B := sorry open Lean open Lean.Meta open Lean.Elab.Command def collectAxiomsOf (constName : Name) : MetaM (List String) := do let env ← getEnv let (_, s) := ((CollectAxioms.collect constName).run env).run {} let a := s.axioms.toList.map toString return a #eval isDefEq (Expr.const ``desiredType []) (Expr.const ``problem2 []) #eval collectAxiomsOf ``problem2
Require Import Coq.ZArith.ZArith Coq.micromega.Lia. Require Import Crypto.Util.ZUtil.Hints.Core. Require Import Crypto.Util.ZUtil.Sgn. Require Import Crypto.Util.ZUtil.Modulo. Require Import Crypto.Util.ZUtil.Div. Require Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos. Local Open Scope Z_scope. Module Z. Lemma quot_div_full a b : Z.quot a b = Z.sgn a * Z.sgn b * (Z.abs a / Z.abs b). Proof. destruct (Z_zerop b); [ subst | apply Z.quot_div; assumption ]. destruct a; simpl; reflexivity. Qed. Local Arguments Z.mul !_ !_. Lemma quot_sgn_nonneg a b : 0 <= Z.sgn (Z.quot a b) * Z.sgn a * Z.sgn b. Proof. rewrite quot_div_full, !Z.sgn_mul, !Z.sgn_sgn. set (d := Z.abs a / Z.abs b). destruct a, b; simpl; try (subst d; simpl; lia); try rewrite (Z.mul_opp_l 1); do 2 try rewrite (Z.mul_opp_r _ 1); rewrite ?Z.mul_1_l, ?Z.mul_1_r, ?Z.opp_involutive; apply Z.div_abs_sgn_nonneg. Qed. Lemma quot_nonneg_same_sgn a b : Z.sgn a = Z.sgn b -> 0 <= Z.quot a b. Proof. intro H. generalize (quot_sgn_nonneg a b); rewrite H. rewrite <- Z.mul_assoc, <- Z.sgn_mul. destruct (Z_zerop b); [ subst; destruct a; unfold Z.quot; simpl in *; congruence | ]. rewrite (Z.sgn_pos (_ * _)) by nia. intro; apply Z.sgn_nonneg; lia. Qed. Lemma mul_quot_eq_full a m : m <> 0 -> m * (Z.quot a m) = a - a mod (Z.abs m * Z.sgn a). Proof. intro Hm. assert (0 <> m * m) by (intro; apply Hm; nia). assert (0 < m * m) by nia. assert (0 <> Z.abs m) by (destruct m; simpl in *; try congruence). rewrite quot_div_full. rewrite <- (Z.abs_sgn m) at 1. transitivity ((Z.sgn m * Z.sgn m) * Z.sgn a * (Z.abs m * (Z.abs a / Z.abs m))); [ nia | ]. rewrite <- Z.sgn_mul, Z.sgn_pos, Z.mul_1_l, Z.mul_div_eq_full by lia. rewrite Z.mul_sub_distr_l. rewrite Z.mul_comm, Z.abs_sgn. destruct a; simpl Z.sgn; simpl Z.abs; autorewrite with zsimplify_const; [ reflexivity | reflexivity | ]. repeat match goal with |- context[-1 * ?x] => replace (-1 * x) with (-x) by lia end. repeat match goal with |- context[?x * -1] => replace (x * -1) with (-x) by lia end. rewrite <- Zmod_opp_opp; simpl Z.opp. reflexivity. Qed. Lemma quot_sub_sgn a : Z.quot (a - Z.sgn a) a = 0. Proof. rewrite quot_div_full. destruct (Z_zerop a); subst; [ lia | ]. rewrite Z.div_small; lia. Qed. Lemma quot_small_abs a b : 0 <= Z.abs a < Z.abs b -> Z.quot a b = 0. Proof. intros; rewrite Z.quot_small_iff by lia; lia. Qed. Lemma quot_add_sub_sgn_small a b : b <> 0 -> Z.sgn a = Z.sgn b -> Z.quot (a + b - Z.sgn b) b = Z.quot (a - Z.sgn b) b + 1. Proof. destruct (Z_zerop a), (Z_zerop b), (Z_lt_le_dec a 0), (Z_lt_le_dec b 0), (Z_lt_le_dec 1 (Z.abs a)); subst; try lia; rewrite !Z.quot_div_full; try rewrite (Z.sgn_neg a) by lia; try rewrite (Z.sgn_neg b) by lia; repeat first [ reflexivity | rewrite Z.sgn_neg by lia | rewrite Z.sgn_pos by lia | rewrite Z.abs_eq by lia | rewrite Z.abs_neq by lia | rewrite !Z.mul_opp_l | rewrite Z.abs_opp in * | rewrite Z.abs_eq in * by lia | match goal with | [ |- context[-1 * ?x] ] => replace (-1 * x) with (-x) by lia | [ |- context[?x * -1] ] => replace (x * -1) with (-x) by lia | [ |- context[-?x - ?y] ] => replace (-x - y) with (-(x + y)) by lia | [ |- context[-?x + - ?y] ] => replace (-x + - y) with (-(x + y)) by lia | [ |- context[(?a + ?b + ?c) / ?b] ] => replace (a + b + c) with (((a + c) + b * 1)) by lia; rewrite Z.div_add' by lia | [ |- context[(?a + ?b - ?c) / ?b] ] => replace (a + b - c) with (((a - c) + b * 1)) by lia; rewrite Z.div_add' by lia end | progress intros | progress Z.replace_all_neg_with_pos | progress autorewrite with zsimplify ]. Qed. End Z.
[STATEMENT] theorem inorder_del: "\<lbrakk> avl t; sorted(inorder t) \<rbrakk> \<Longrightarrow> inorder (tree(del x t)) = del_list x (inorder t)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>avl t; Sorted_Less.sorted (Tree2.inorder t)\<rbrakk> \<Longrightarrow> Tree2.inorder (tree (del x t)) = del_list x (Tree2.inorder t) [PROOF STEP] apply(induction t rule: tree2_induct) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<lbrakk>avl \<langle>\<rangle>; Sorted_Less.sorted (Tree2.inorder \<langle>\<rangle>)\<rbrakk> \<Longrightarrow> Tree2.inorder (tree (del x \<langle>\<rangle>)) = del_list x (Tree2.inorder \<langle>\<rangle>) 2. \<And>x1 a b x3. \<lbrakk>\<lbrakk>avl x1; Sorted_Less.sorted (Tree2.inorder x1)\<rbrakk> \<Longrightarrow> Tree2.inorder (tree (del x x1)) = del_list x (Tree2.inorder x1); \<lbrakk>avl x3; Sorted_Less.sorted (Tree2.inorder x3)\<rbrakk> \<Longrightarrow> Tree2.inorder (tree (del x x3)) = del_list x (Tree2.inorder x3); avl \<langle>x1, (a, b), x3\<rangle>; Sorted_Less.sorted (Tree2.inorder \<langle>x1, (a, b), x3\<rangle>)\<rbrakk> \<Longrightarrow> Tree2.inorder (tree (del x \<langle>x1, (a, b), x3\<rangle>)) = del_list x (Tree2.inorder \<langle>x1, (a, b), x3\<rangle>) [PROOF STEP] apply(auto simp: del_list_simps inorder_baldL inorder_baldR avl_delete inorder_split_maxD simp del: baldR.simps baldL.simps split!: splits prod.splits) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
theory Chisholm_A imports SDL (*Christoph Benzmüller & Xavier Parent, 2018*) begin (* Chisholm Example *) consts go::\<sigma> tell::\<sigma> kill::\<sigma> axiomatization where D1: "\<lfloor>\<^bold>O\<^bold>\<langle>go\<^bold>\<rangle>\<rfloor>" (*It ought to be that Jones goes to assist his neighbors.*) and D2: "\<lfloor>\<^bold>O\<^bold>\<langle>go \<^bold>\<rightarrow> tell\<^bold>\<rangle>\<rfloor>" (*It ought to be that if Jones goes, then he tells them he is coming.*) and D3: "\<lfloor>\<^bold>O\<^bold>\<langle>\<^bold>\<not>go \<^bold>\<rightarrow> \<^bold>\<not>tell\<^bold>\<rangle>\<rfloor>" (*If Jones doesn't go, then he ought not tell them he is coming.*) and D4: "\<lfloor>\<^bold>\<not>go\<rfloor>\<^sub>c\<^sub>w" (*Jones doesn't go. (This is encoded as a locally valid statement.)*) (*Some Experiments*) sledgehammer_params [max_facts=20] (*Sets default parameters for the theorem provers*) nitpick_params [user_axioms,expect=genuine,show_all,format=2] (*... and for the model finder.*) lemma True nitpick [satisfy] oops (*Consistency-check: Is there a model?*) lemma False sledgehammer oops (*Inconsistency-check: Can Falsum be derived?*) lemma "\<lfloor>\<^bold>O\<^bold>\<langle>\<^bold>\<not>tell\<^bold>\<rangle>\<rfloor>" sledgehammer nitpick oops (*Should James not tell?*) lemma "\<lfloor>\<^bold>O\<^bold>\<langle>tell\<^bold>\<rangle>\<rfloor>" sledgehammer nitpick oops (*Should James tell?*) lemma "\<lfloor>\<^bold>O\<^bold>\<langle>kill\<^bold>\<rangle>\<rfloor>" sledgehammer nitpick oops (*Should James kill?*) (* The issue of Chisholm_A: D1 entails D3 (The requirement of logical independence is not met).*) lemma "(\<lfloor>\<^bold>O\<^bold>\<langle>go\<^bold>\<rangle>\<rfloor>) \<longrightarrow> (\<lfloor>\<^bold>O\<^bold>\<langle>\<^bold>\<not>go \<^bold>\<rightarrow> \<^bold>\<not>tell\<^bold>\<rangle>\<rfloor>)" unfolding obligationSDL_def by simp end (* D2: "\<lfloor>\<^bold>O\<^bold>\<langle>tell\<^bold>|go\<^bold>\<rangle>\<rfloor>" and D3: "\<lfloor>\<^bold>O\<^bold>\<langle>\<^bold>\<not>tell\<^bold>|\<^bold>\<not>go\<^bold>\<rangle>\<rfloor>" and *)
lemma emeasure_lborel_Ioo[simp]: assumes [simp]: "l \<le> u" shows "emeasure lborel {l <..< u} = ennreal (u - l)"
lemma imaginary_eq_real_iff [simp]: assumes "y \<in> Reals" "x \<in> Reals" shows "\<i> * y = x \<longleftrightarrow> x=0 \<and> y=0"
(* Title: HOL/ex/Transfer_Debug.thy Author: Ondřej Kunčar, TU München *) theory Transfer_Debug imports Main "~~/src/HOL/Library/FSet" begin (* This file demonstrates some of the typical scenarios when transfer or transfer_prover does not produce expected results and how the user might handle such cases. *) (* As an example, we use finite sets. The following command recreates the environment in which the type of finite sets was created and allows us to do transferring on this type. *) context includes fset.lifting begin subsection \<open>1. A missing transfer rule\<close> (* We will simulate the situation in which there is not any transfer rules for fmember. *) declare fmember.transfer[transfer_rule del] fmember_transfer[transfer_rule del] (* We want to prove the following theorem about |\<subseteq>| by transfer *) lemma "(A |\<subseteq>| B) = fBall A (\<lambda>x. x |\<in>| B)" apply transfer (* Transfer complains that it could not find a transfer rule for |\<subseteq>| with a matching transfer relation. An experienced user could notice that |\<in>| was transferred to |\<in>| by a a default reflexivity transfer rule (because there was not any genuine transfer rule for |\<in>|) and fBall was transferred to Ball using the transfer relation pcr_fset. Therefore transfer is looking for a transfer rule for |\<subseteq>| with a transfer relation that mixes op= and pcr_fset. This situation might be confusing because the real problem (a missing transfer rule) propagates during the transferring algorithm and manifests later in an obfuscated way. Fortunately, we could inspect the behavior of transfer in a more interactive way to pin down the real problem. *) oops lemma "(A |\<subseteq>| B) = fBall A (\<lambda>x. x |\<in>| B)" apply transfer_start (* Setups 6 goals for 6 transfer rules that have to be found and the result as the 7. goal, which gets synthesized to the final result of transferring when we find the 6 transfer rules. *) apply transfer_step (* We can see that the default reflexivity transfer rule was applied and |\<in>| was transferred to |\<in>| \<Longrightarrow> there is no genuine transfer rule for |\<in>|. *) oops (* We provide a transfer rule for |\<in>|. *) lemma "(A |\<subseteq>| B) = fBall A (\<lambda>x. x |\<in>| B)" apply transfer_start apply transfer_step (* The new transfer rule was selected and |\<in>| was transferred to \<in>. *) apply transfer_step+ apply transfer_end by blast (* Of course in the real life, we would use transfer instead of transfer_start, transfer_step+ and transfer_end. *) lemma "(A |\<subseteq>| B) = fBall A (\<lambda>x. x |\<in>| B)" by transfer blast subsection \<open>2. Unwanted instantiation of a transfer relation variable\<close> (* We want to prove the following fact. *) lemma "finite (UNIV :: 'a::finite fset set)" apply transfer (* Transfer does not do anything here. *) oops (* Let us inspect interactively what happened. *) lemma "finite (UNIV :: 'a::finite fset set)" apply transfer_start apply transfer_step (* Here we can realize that not an expected transfer rule was chosen. We stumbled upon a limitation of Transfer: the tool used the rule Lifting_Set.UNIV_transfer, which transfers UNIV to UNIV and assumes that the transfer relation has to be bi-total. The problem is that at this point the transfer relation is not known (it is represented by a schematic variable ?R) and therefore in order to discharge the assumption "bi_total ?R", ?R is instantiated to op=. If the relation had been known (we wish pcr_fset op=, which is not bi-total), the assumption bi_total pcr_fset op= could not have been discharged and the tool would have backtracked and chosen Lifting.right_total_UNIV_transfer, which assumes only right-totalness (and pcr_fset is right-total). *) back back (* We can force the tool to backtrack and choose the desired transfer rule. *) apply transfer_step apply transfer_end by auto (* Of course, to use "back" in proofs is not a desired style. But we can prioritize the rule Lifting.right_total_UNIV_transfer by redeclaring it LOCALLY as a transfer rule. *) lemma "finite (UNIV :: 'a::finite fset set)" proof - note right_total_UNIV_transfer[transfer_rule] show ?thesis by transfer auto qed end (* Let us close the environment of fset transferring and add the rule that we deleted. *) lifting_forget fset.lifting (* deletes the extra added transfer rule for |\<in>| *) declare fmember_transfer[transfer_rule] (* we want to keep parametricity of |\<in>| *) end
Require Import TestSuite.admit. Require Import Coq.Classes.Morphisms Coq.Classes.RelationClasses Coq.Program.Program Coq.Setoids.Setoid. Global Set Implicit Arguments. Hint Extern 0 => apply reflexivity : typeclass_instances. Inductive Comp : Type -> Type := | Pick : forall A, (A -> Prop) -> Comp A. Axiom computes_to : forall A, Comp A -> A -> Prop. Axiom refine : forall {A} (old : Comp A) (new : Comp A), Prop. Global Instance refine_PreOrder A : PreOrder (@refine A). Admitted. Add Parametric Morphism A : (@Pick A) with signature (pointwise_relation _ (flip impl)) ==> (@refine A) as refine_flip_impl_Pick. admit. Defined. Definition remove_forall_eq' A x B (P : A -> B -> Prop) : pointwise_relation _ impl (P x) (fun z => forall y : A, y = x -> P y z). admit. Defined. Goal forall A B (x : A) (P : _ -> _ -> Prop), refine (Pick (fun n : B => forall y, y = x -> P y n)) (Pick (fun n : B => P x n)). Proof. intros. setoid_rewrite (@remove_forall_eq' _ _ _ _). Undo. (* This failed with NotConvertible at some time *) setoid_rewrite (@remove_forall_eq' _ _ _).
{-# OPTIONS --cubical --safe #-} module Strict.Properties where open import Path open import Level open import Strict open import Agda.Builtin.Strict open import Function $!-≡ : {A : Type a} {B : A → Type b} → (f : ∀ x → B x) → ∀ x → (f $! x) ≡ f x $!-≡ f x = builtin-eq-to-path (primForceLemma x f) $!≡$ : {A : Type a} {B : A → Type b} → _$!_ {A = A} {B = B} ≡ _$_ {A = A} {B = B} $!≡$ i f x = $!-≡ f x i
From Hammer Require Import Hammer. Theorem injection_is_involution_in_Prop (f : Prop -> Prop) (inj : forall A B, (f A <-> f B) -> (A <-> B)) (ext : forall A B, A <-> B -> f A <-> f B) : forall A, f (f A) <-> A. Proof. hammer_hook "PropFacts" "PropFacts.injection_is_involution_in_Prop". intros. enough (f (f (f A)) <-> f A) by (apply inj; assumption). split; intro H. - now_show (f A). enough (f A <-> True) by firstorder. enough (f (f A) <-> f True) by (apply inj; assumption). split; intro H'. + now_show (f True). enough (f (f (f A)) <-> f True) by firstorder. apply ext; firstorder. + now_show (f (f A)). enough (f (f A) <-> True) by firstorder. apply inj; firstorder. - now_show (f (f (f A))). enough (f A <-> f (f (f A))) by firstorder. apply ext. split; intro H'. + now_show (f (f A)). enough (f A <-> f (f A)) by firstorder. apply ext; firstorder. + now_show A. enough (f A <-> A) by firstorder. apply inj; firstorder. Defined.
SUBROUTINE RDFDOR (XNAME,XMIN,XMAX,X,ILDEC,IVALS) IMPLICIT NONE * FORMAL_PARAMETERS: DOUBLE PRECISION X,XMIN,XMAX INTEGER ILDEC,IVALS CHARACTER*(*) XNAME DIMENSION X(ILDEC) ** local variables ; dummy set DOUBLE PRECISION DM REAL R(1),RM INTEGER I(1),IM CHARACTER*80 C(1),CM LOGICAL L(1),LM * include files INCLUDE 'rdstainf.inc' * other INTEGER IS,I1,ILX DOUBLE PRECISION XL CHARACTER Q*1, LXNAME*31 SAVE DATA Q /''''/ CALL RDDATA (7,'RDFDOR',0,0,' ',IS,XNAME,'D', $ X,R,I,C,L,ILDEC,1,1,1,1,IVALS, $ DM,RM,IM,CM,LM) LXNAME = XNAME ILX = LEN_TRIM (LXNAME) DO 10 I1=1,IVALS XL = X(I1) IF (XMAX.LT.XMIN) THEN IF (TOSCR) WRITE (*,'(1X,4A)') & 'ERROR in RDFDOR: Range not valid of identifier ', & Q,LXNAME(1:ILX),Q IF (TOLOG) WRITE (IULOG,'(1X,4A)') & 'ERROR in RDFDOR: Range not valid of identifier ', & Q,LXNAME(1:ILX),Q CALL FATALERR (' ',' ') ELSE IF ((XL.LT.XMIN.OR.XL.GT.XMAX).AND.XL.NE.DM) THEN IF (TOSCR) WRITE (*, & '(1X,4A,I3,3A,/,T19,A,G12.5,A,G12.5,A,G12.5,A)') & 'ERROR in RDFDOR: Range error of identifier ', & Q,LXNAME(1:ILX),'(',I1,')',Q,',', & 'value =',XL,', range = [',XMIN,',',XMAX,']' IF (TOLOG) WRITE (IULOG, & '(1X,4A,I3,3A,/,T19,A,G12.5,A,G12.5,A,G12.5,A)') & 'ERROR in RDFDOR: Range error of identifier ', & Q,LXNAME(1:ILX),'(',I1,')',Q,',', & 'value =',XL,', range = [',XMIN,',',XMAX,']' CALL FATALERR (' ',' ') END IF 10 CONTINUE RETURN END
Foliot had been one of three members of the cathedral chapter from Hereford sent to King Henry III 's court to secure permission for the chapter to hold an election in 1219 Foliot was elected to the see of Hereford in June 1219 and consecrated on 27 October 1219 along with William de <unk> , the Bishop of Llandaff , at Canterbury .
Formal statement is: lemma big_prod_in_1: assumes "\<And>x. x \<in> A \<Longrightarrow> f x \<in> L F (\<lambda>_. 1)" shows "(\<lambda>y. \<Prod>x\<in>A. f x y) \<in> L F (\<lambda>_. 1)" Informal statement is: If $f$ is a function from $A$ to $L^1$, then the product of the functions in $f$ is in $L^1$.
import Issue953 g : Set₁ g = Issue953.f
------------------------------------------------------------------------ -- The Agda standard library -- -- Coinductive "natural" numbers ------------------------------------------------------------------------ {-# OPTIONS --without-K --guardedness --sized-types #-} module Codata.Musical.Conat where open import Codata.Musical.Notation open import Data.Nat.Base using (ℕ; zero; suc) open import Function open import Relation.Binary open import Relation.Binary.PropositionalEquality as P using (_≡_) ------------------------------------------------------------------------ -- The type data Coℕ : Set where zero : Coℕ suc : (n : ∞ Coℕ) → Coℕ module Coℕ-injective where suc-injective : ∀ {m n} → (Coℕ ∋ suc m) ≡ suc n → m ≡ n suc-injective P.refl = P.refl ------------------------------------------------------------------------ -- Some operations pred : Coℕ → Coℕ pred zero = zero pred (suc n) = ♭ n fromℕ : ℕ → Coℕ fromℕ zero = zero fromℕ (suc n) = suc (♯ fromℕ n) fromℕ-injective : ∀ {m n} → fromℕ m ≡ fromℕ n → m ≡ n fromℕ-injective {zero} {zero} eq = P.refl fromℕ-injective {zero} {suc n} () fromℕ-injective {suc m} {zero} () fromℕ-injective {suc m} {suc n} eq = P.cong suc (fromℕ-injective (P.cong pred eq)) ∞ℕ : Coℕ ∞ℕ = suc (♯ ∞ℕ) infixl 6 _+_ _+_ : Coℕ → Coℕ → Coℕ zero + n = n suc m + n = suc (♯ (♭ m + n)) ------------------------------------------------------------------------ -- Equality data _≈_ : Coℕ → Coℕ → Set where zero : zero ≈ zero suc : ∀ {m n} (m≈n : ∞ (♭ m ≈ ♭ n)) → suc m ≈ suc n module ≈-injective where suc-injective : ∀ {m n p q} → (suc m ≈ suc n ∋ suc p) ≡ suc q → p ≡ q suc-injective P.refl = P.refl setoid : Setoid _ _ setoid = record { Carrier = Coℕ ; _≈_ = _≈_ ; isEquivalence = record { refl = refl ; sym = sym ; trans = trans } } where refl : Reflexive _≈_ refl {zero} = zero refl {suc n} = suc (♯ refl) sym : Symmetric _≈_ sym zero = zero sym (suc m≈n) = suc (♯ sym (♭ m≈n)) trans : Transitive _≈_ trans zero zero = zero trans (suc m≈n) (suc n≈k) = suc (♯ trans (♭ m≈n) (♭ n≈k)) ------------------------------------------------------------------------ -- Legacy import Codata.Conat as C open import Codata.Thunk import Size fromMusical : ∀ {i} → Coℕ → C.Conat i fromMusical zero = C.zero fromMusical (suc n) = C.suc λ where .force → fromMusical (♭ n) toMusical : C.Conat Size.∞ → Coℕ toMusical C.zero = zero toMusical (C.suc n) = suc (♯ toMusical (n .force))
{-# OPTIONS --cubical --no-import-sorts --safe #-} module Cubical.Data.Unit.Base where open import Cubical.Foundations.Prelude -- Obtain Unit open import Agda.Builtin.Unit public renaming ( ⊤ to Unit ) -- Universe polymorphic version Unit* : {ℓ : Level} → Type ℓ Unit* = Lift Unit pattern tt* = lift tt -- Universe polymorphic version without definitional equality -- Allows us to "lock" proofs. See "Locking, unlocking" in -- https://coq.inria.fr/refman/proof-engine/ssreflect-proof-language.html data lockUnit {ℓ} : Type ℓ where unlock : lockUnit
(* *********************************************************************) (* *) (* The CertiKOS Certified Kit Operating System *) (* *) (* The FLINT Group, Yale University *) (* *) (* Copyright The FLINT Group, Yale University. All rights reserved. *) (* This file is distributed under the terms of the Yale University *) (* Non-Commercial License Agreement. *) (* *) (* *********************************************************************) Require Import Coq.Program.Basics. Require Import Coq.Relations.Relations. Require Import Coq.Classes.RelationClasses. Require Import Coq.Classes.RelationPairs. Require Import Coq.Classes.Morphisms. Require Import ExtensionalityAxioms. Require Import Lens. Require Import Functor. Require Import PowersetMonad. (** * Lifting operations *) (** Because [Mem.MemoryModel] contains so many theorems, we need some systematic way to lift the memory operations along a lens, so that the lifting of the theorems is convenient to automate. The signature of most of the memory operations are variations on the theme [mem -> F mem], where [F] is a functor such as [option] or [- × Z]. Using the functor's [fmap] and the lens operations, we can define a generic lifting operator as in the following. *) Class Lift {S V} π `{πops: LensOps S V π} A B := { lift: A -> B }. Arguments lift {S V} π {πops A B Lift} _. Section LIFT. Context {S V} `{HSV: Lens S V} `{HF: Functor}. Global Instance lens_lift: Lift π (V -> F V) (S -> F S) := { lift f s := fmap (fun v => set π v s) (f (π s)) }. End LIFT. (** Typeclass resolution needs some help to figure out those functors by unification. *) Section LIFTINSTANCES. Context {S V} `{HSV: Lens S V}. Global Instance lift_const A: Lift π (V -> A) (S -> A) := lens_lift (F := (fun _ => A)). Global Instance lift_prod A: Lift π (V -> V * A) (S -> S * A) := lens_lift. Global Instance lift_powerset: Lift π (V -> V -> Prop) (S -> S -> Prop) := lens_lift (F := (fun X => X -> Prop)). End LIFTINSTANCES. (** ** The [lift_peel] tactic *) (** This is the main tactic we use: it lifts a theorem [Hf] of the underlying memory model by "peeling off" its structure recursively to prove the lifted goal. The leaf goals are handled with the caller-provided tactic [leaftac]. *) (* Premises are "translated" and used to specialize Hf *) Ltac lift_peel_intro π recurse Hf x := intro x; (specialize (Hf x) || specialize (Hf (π x)) || (match type of Hf with forall (H: ?T), _ => let H' := fresh H in assert (H': T) by recurse x; specialize (Hf H'); clear H' end)); recurse Hf. (* Existential: we must use [set] to augment any memory state provided by Hf, but we can otherwise just pass everything along *) Ltac lift_peel_exists π recurse Hf x := let Hf' := fresh Hf in destruct Hf as [x Hf']; (exists x || eexists (set _ x _)); recurse Hf'. (* Conjunction: split and peel each side independently *) Ltac lift_peel_conj π recurse Hf := let Hl := fresh Hf "l" in let Hr := fresh Hf "r" in destruct Hf as [Hl Hr]; split; [recurse Hl | recurse Hr]. Ltac lift_peel π Hf leaftac := let recurse Hf := lift_peel π Hf leaftac in try match goal with | |- forall (x: _), _ => let x := fresh x in lift_peel_intro π recurse Hf x | |- exists (x: _), _ => let x := fresh x in lift_peel_exists π recurse Hf x | |- { x: _ | _ } => let x := fresh x in lift_peel_exists π recurse Hf x | |- _ /\ _ => lift_peel_conj π recurse Hf | |- ?T => leaftac end. (** Now the goal is to come up with an appropriate leaf tactic which will be able to prove some theorems instanciated with the lifted operations using the original version. *) (** ** Expressing everything in terms of [lift] *) (** As a first step, in order to be able to apply general theorems about it, we will want to make sure the goal and premises are all stated in terms of [lift]. In order to do this, we use the rule below to make sure that the [simpl] tactic stops whenever [lift] is reached. Then [simpl] allows us to unfold typeclass methods which are defined in terms of lift (the most common case). *) Arguments lift _ _ _ _ _ _ _ _ : simpl never. (** There are also derived operations (such as [free_list] for instance), which are defined in terms of the typeclass methods. In such cases, we usually want to prove that lifting such operations is equivalent to applying them to a lifted typeclass instance. Then we can rewrite them in terms of [lift] as well. Such proofs are collected into the "lift" rewrite database. *) Ltac lift_norm := repeat progress (simpl in *; autorewrite with lift in *). (** Unfortunately there is no [Create HintDb] command for rewrite databases, so we have to create it by adding a fake entry. *) Hint Rewrite injective_projections using fail : lift. (** ** Simplifying occurences of [lift] *) (** Once everything is stated in terms of lift, futher rewriting rules from the [lift_simpl] database can be applied. In particular, the theorems below try to ensure that the goal and hypotheses are stated in terms of [get] and [same_context] rather than in terms of [lift]. *) Ltac lift_simpl := repeat progress (lift_norm; autorewrite with lift_simpl in *; lens_simpl). Section LIFTOPTION. Context {S V} `{HSV: Lens S V}. Lemma lift_option_eq_unlift (f: V -> option V) (s s': S): lift π f s = Some s' -> f (π s) = Some (π s'). Proof. unfold lift; simpl. intros. destruct (f (π s)); try discriminate. inversion H. autorewrite with lens. reflexivity. Qed. Theorem lift_option_eq_same_context (f: V -> option V) (s s': S): lift π f s = Some s' -> same_context π s s'. Proof. unfold lift; simpl. case (f (π s)). * intros ? H; inversion H; subst. symmetry. apply lens_set_same_context. * discriminate. Qed. Theorem lift_option_eq_intro (f: V -> option V) (s s': S): same_context π s s' -> f (π s) = Some (π s') -> lift π f s = Some s'. Proof. intros Hc Hv. unfold lift; simpl. rewrite Hv; clear Hv. f_equal. rewrite Hc. apply lens_set_get. Qed. Theorem lift_option_eq_iff f s s' `{!Lens π}: lift π f s = Some s' <-> f (π s) = Some (π s') /\ same_context π s s'. Proof. repeat split. - apply lift_option_eq_unlift. assumption. - eapply lift_option_eq_same_context. eassumption. - intros [Hf Hc]. eapply lift_option_eq_intro; assumption. Qed. End LIFTOPTION. Section LIFTPROD. Context {S V} `{Hgs: Lens S V} {A: Type}. Theorem lift_prod_eq_unlift (f: V -> V * A) (s s': S) (a: A): lift π f s = (s', a) -> f (π s) = (π s', a). Proof. unfold lift; simpl. destruct (f (π s)) as [v' a']. intros H. inversion H. autorewrite with lens. reflexivity. Qed. Theorem lift_prod_eq_same_context (f: V -> V * A) (s s': S) (a: A): lift π f s = (s', a) -> same_context π s s'. Proof. unfold lift; simpl. destruct (f (π s)). intro H; inversion H; subst. symmetry. apply lens_set_same_context. Qed. Theorem lift_prod_eq_intro (f: V -> V * A) (s s': S) (a: A): same_context π s s' -> f (π s) = (π s', a) -> lift π f s = (s', a). Proof. unfold lift; simpl. intros Hc Hv. destruct (f (π s)) as [v']. inversion Hv; subst; clear Hv. rewrite Hc; clear Hc. autorewrite with lens. reflexivity. Qed. Theorem lift_prod_eq_iff (f: V -> V * A) (s s': S) (a: A): lift π f s = (s', a) <-> f (π s) = (π s', a) /\ same_context π s s'. Proof. repeat split. - apply lift_prod_eq_unlift. assumption. - eapply lift_prod_eq_same_context. eassumption. - intros [Hf Hc]. apply lift_prod_eq_intro; assumption. Qed. End LIFTPROD. Section LIFTREL. Context {S V} `{Lens S V}. Global Instance lift_relation_unlift (R: relation V): subrelation (lift π R) (R @@ π)%signature. Proof. unfold lift, RelCompFun; simpl. intros s1 s2 Hs. inversion Hs. autorewrite with lens. assumption. Qed. Global Instance lift_relation_same_context (R: relation V): subrelation (lift π R) (same_context π). Proof. unfold lift; simpl. intros s1 s2 Hs. inversion Hs. autorewrite with lens. reflexivity. Qed. Lemma lift_relation_intro (R: V -> V -> Prop) (s1 s2: S): same_context π s1 s2 -> R (π s1) (π s2) -> lift (Lift := lift_powerset) π R s1 s2. Proof. intros Hc Hv. unfold lift; simpl. replace s2 with (set π (π s2) s1). * change (set π (π s2) s1) with ((fun v => set π v s1) (π s2)). eapply powerset_fmap_intro. assumption. * rewrite Hc. autorewrite with lens. reflexivity. Qed. Lemma lift_relation_iff (R: V -> V -> Prop) (s1 s2: S): lift π R s1 s2 <-> R (π s1) (π s2) /\ same_context π s1 s2. Proof. repeat split. - apply lift_relation_unlift. assumption. - eapply lift_relation_same_context. eassumption. - intros [Hv Hc]. apply lift_relation_intro; assumption. Qed. End LIFTREL. Hint Rewrite @lift_option_eq_iff @lift_prod_eq_iff @lift_relation_iff using typeclasses eauto : lift_simpl. (** ** Solving the residual goals *) (** The rewriting rules above likely leaves us with several conjunctions. We destruct them to make sure that the components are readily available. *) Ltac split_conjuncts := repeat match goal with | [ H: _ /\ _ |- _ ] => let Hl := fresh H "l" in let Hr := fresh H "r" in destruct H as [Hl Hr] end. (** Hopefully, the residual goal can then easily be solved with [eauto], given a few hints in the "lift" database which we use to solve corner cases. *) Hint Extern 10 (eq _ _) => congruence : lift. (* Use the minimal priority, because we want to use [same_context] as a side-condition for some immediate hints. *) Hint Extern 0 (same_context _ _ _) => congruence || reflexivity : lift. (** As a last resort, we unfold [lift] and try to normalize the result. Hopefully we'll get something easily solvable. *) Ltac lift_unfold := repeat progress (lift_simpl; unfold lift in *). (** We're now ready to define our leaf tactic, and use it in conjunction with [peel] to solve the goals automatically. *) Ltac lift_auto := lift_simpl; split_conjuncts; eauto 10 with lift typeclass_instances; lift_unfold; eauto 10 with lift typeclass_instances. (** The [lift_partial] variant allows for some unsolved leaves. *) Ltac lift_partial π f := pose proof f as Hf; lift_peel π Hf lift_auto. (** The [lift] variant demands 100% success *) Ltac lift π f := now lift_partial π f. (** ** Properties of lifted operations *) (** Lifting commutes with lens composition *) Section COMPOSE. Existing Instances lens_compose compose_lensops. Context {A B C} (π: A -> B) (ρ: B -> C) `{Hπ: Lens _ _ π} `{Hρ: Lens _ _ ρ}. Context `{HF: Functor}. Context (f: C -> F C). Lemma lift_compose: lift (compose ρ π) f = lift π (lift ρ f). Proof. unfold lift. simpl. apply functional_extensionality. intros a. unfold Basics.compose. reflexivity. Qed. End COMPOSE.
-- Dominio de discurso variable A : Type lemma Example1 (P Q : A → Prop) : (∀ x, P x → Q x) → (∀ x, P x) → (∀ x, Q x) := begin intros hpq hp, intro a, apply hpq, -- lines below can be replaced by apply ((hpq a) (hp a)) apply hp end lemma Example2 (P Q : A → Prop) : (∀ x, P x ∧ Q x) ↔ (∀ x, P x) ∧ (∀ x, Q x) := begin apply iff.intro, -- [-->] intro hpq, apply and.intro, intro x, apply and.left (hpq x), intro x, apply and.right (hpq x), -- [<--] intro hpq, intro x, apply and.intro, apply ((and.left hpq) x), apply ((and.right hpq) x) end lemma Example3 (P Q : A → Prop) : (∃ x, P x ∧ Q x) → (∃ x, P x) := begin intro hpq, apply (exists.elim hpq), intros a ha, apply exists.intro a, apply (and.left ha) end
[GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝¹ : Fintype α inst✝ : Fintype ↑(colorClasses C) ⊢ Fintype.card ↑(colorClasses C) ≤ Fintype.card α [PROOFSTEP] simp [colorClasses] -- porting note: brute force instance declaration `[Fintype (Setoid.classes (Setoid.ker C))]` [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝¹ : Fintype α inst✝ : Fintype ↑(colorClasses C) ⊢ Fintype.card ↑(Setoid.classes (Setoid.ker ↑C)) ≤ Fintype.card α [PROOFSTEP] haveI : Fintype (Setoid.classes (Setoid.ker C)) := by assumption [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝¹ : Fintype α inst✝ : Fintype ↑(colorClasses C) ⊢ Fintype ↑(Setoid.classes (Setoid.ker ↑C)) [PROOFSTEP] assumption [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝¹ : Fintype α inst✝ : Fintype ↑(colorClasses C) this : Fintype ↑(Setoid.classes (Setoid.ker ↑C)) ⊢ Fintype.card ↑(Setoid.classes (Setoid.ker ↑C)) ≤ Fintype.card α [PROOFSTEP] convert Setoid.card_classes_ker_le C [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝¹ : Fintype V inst✝ : Fintype α ⊢ Fintype (Coloring G α) [PROOFSTEP] classical change Fintype (RelHom G.Adj (⊤ : SimpleGraph α).Adj) apply Fintype.ofInjective _ RelHom.coe_fn_injective [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝¹ : Fintype V inst✝ : Fintype α ⊢ Fintype (Coloring G α) [PROOFSTEP] change Fintype (RelHom G.Adj (⊤ : SimpleGraph α).Adj) [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝¹ : Fintype V inst✝ : Fintype α ⊢ Fintype (G.Adj →r ⊤.Adj) [PROOFSTEP] apply Fintype.ofInjective _ RelHom.coe_fn_injective [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α h : Colorable G 0 ⊢ IsEmpty V [PROOFSTEP] constructor [GOAL] case false V : Type u G : SimpleGraph V α : Type v C : Coloring G α h : Colorable G 0 ⊢ V → False [PROOFSTEP] intro v [GOAL] case false V : Type u G : SimpleGraph V α : Type v C : Coloring G α h : Colorable G 0 v : V ⊢ False [PROOFSTEP] obtain ⟨i, hi⟩ := h.some v [GOAL] case false.mk V : Type u G : SimpleGraph V α : Type v C : Coloring G α h : Colorable G 0 v : V i : ℕ hi : i < 0 ⊢ False [PROOFSTEP] exact Nat.not_lt_zero _ hi [GOAL] V : Type u G : SimpleGraph V α✝ : Type v C : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ↪ β ⊢ Function.Injective fun C => Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C [PROOFSTEP] intro C C' h [GOAL] V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ↪ β C C' : Coloring G α h : (fun C => Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C) C = (fun C => Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C) C' ⊢ C = C' [PROOFSTEP] dsimp only at h [GOAL] V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ↪ β C C' : Coloring G α h : Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C = Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C' ⊢ C = C' [PROOFSTEP] ext v [GOAL] case h V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ↪ β C C' : Coloring G α h : Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C = Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C' v : V ⊢ ↑C v = ↑C' v [PROOFSTEP] apply (Embedding.completeGraph f).inj' [GOAL] case h.a V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ↪ β C C' : Coloring G α h : Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C = Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C' v : V ⊢ Function.Embedding.toFun (Embedding.completeGraph f).toEmbedding (↑C v) = Function.Embedding.toFun (Embedding.completeGraph f).toEmbedding (↑C' v) [PROOFSTEP] change ((Embedding.completeGraph f).toHom.comp C) v = _ [GOAL] case h.a V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ↪ β C C' : Coloring G α h : Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C = Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C' v : V ⊢ ↑(Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C) v = Function.Embedding.toFun (Embedding.completeGraph f).toEmbedding (↑C' v) [PROOFSTEP] rw [h] [GOAL] case h.a V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ↪ β C C' : Coloring G α h : Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C = Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C' v : V ⊢ ↑(Hom.comp (Embedding.toHom (Embedding.completeGraph f)) C') v = Function.Embedding.toFun (Embedding.completeGraph f).toEmbedding (↑C' v) [PROOFSTEP] rfl [GOAL] V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ≃ β C : Coloring G α ⊢ ↑(recolorOfEmbedding G (Equiv.toEmbedding f.symm)) (↑(recolorOfEmbedding G (Equiv.toEmbedding f)) C) = C [PROOFSTEP] ext v [GOAL] case h V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ≃ β C : Coloring G α v : V ⊢ ↑(↑(recolorOfEmbedding G (Equiv.toEmbedding f.symm)) (↑(recolorOfEmbedding G (Equiv.toEmbedding f)) C)) v = ↑C v [PROOFSTEP] apply Equiv.symm_apply_apply [GOAL] V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ≃ β C : Coloring G β ⊢ ↑(recolorOfEmbedding G (Equiv.toEmbedding f)) (↑(recolorOfEmbedding G (Equiv.toEmbedding f.symm)) C) = C [PROOFSTEP] ext v [GOAL] case h V : Type u G : SimpleGraph V α✝ : Type v C✝ : Coloring G α✝ α : Type u_1 β : Type u_2 f : α ≃ β C : Coloring G β v : V ⊢ ↑(↑(recolorOfEmbedding G (Equiv.toEmbedding f)) (↑(recolorOfEmbedding G (Equiv.toEmbedding f.symm)) C)) v = ↑C v [PROOFSTEP] apply Equiv.apply_symm_apply [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n m : ℕ h : n ≤ m hc : Colorable G n ⊢ Fintype.card (Fin n) ≤ Fintype.card (Fin m) [PROOFSTEP] simp [h] [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α ⊢ Fintype.card α ≤ Fintype.card (Fin (Fintype.card α)) [PROOFSTEP] simp [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Fintype α n : ℕ hc : Colorable G n hn : n ≤ Fintype.card α ⊢ Coloring G α [PROOFSTEP] rw [← Fintype.card_fin n] at hn [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Fintype α n : ℕ hc : Colorable G n hn : Fintype.card (Fin n) ≤ Fintype.card α ⊢ Coloring G α [PROOFSTEP] exact G.recolorOfCardLE hn hc.some [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α V' : Type u_1 G' : SimpleGraph V' f : G ↪g G' n : ℕ h : Colorable G' n ⊢ n ≤ Fintype.card (Fin n) [PROOFSTEP] simp [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ ⊢ Colorable G n ↔ ∃ C, ∀ (v : V), ↑C v < n [PROOFSTEP] constructor [GOAL] case mp V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ ⊢ Colorable G n → ∃ C, ∀ (v : V), ↑C v < n [PROOFSTEP] rintro hc [GOAL] case mp V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ hc : Colorable G n ⊢ ∃ C, ∀ (v : V), ↑C v < n [PROOFSTEP] have C : G.Coloring (Fin n) := hc.toColoring (by simp) [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ hc : Colorable G n ⊢ n ≤ Fintype.card (Fin n) [PROOFSTEP] simp [GOAL] case mp V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ hc : Colorable G n C : Coloring G (Fin n) ⊢ ∃ C, ∀ (v : V), ↑C v < n [PROOFSTEP] let f := Embedding.completeGraph (@Fin.valEmbedding n) [GOAL] case mp V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ hc : Colorable G n C : Coloring G (Fin n) f : ⊤ ↪g ⊤ := Embedding.completeGraph Fin.valEmbedding ⊢ ∃ C, ∀ (v : V), ↑C v < n [PROOFSTEP] use f.toHom.comp C [GOAL] case h V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ hc : Colorable G n C : Coloring G (Fin n) f : ⊤ ↪g ⊤ := Embedding.completeGraph Fin.valEmbedding ⊢ ∀ (v : V), ↑(Hom.comp (Embedding.toHom f) C) v < n [PROOFSTEP] intro v [GOAL] case h V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ hc : Colorable G n C : Coloring G (Fin n) f : ⊤ ↪g ⊤ := Embedding.completeGraph Fin.valEmbedding v : V ⊢ ↑(Hom.comp (Embedding.toHom f) C) v < n [PROOFSTEP] cases' C with color valid [GOAL] case h.mk V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ hc : Colorable G n f : ⊤ ↪g ⊤ := Embedding.completeGraph Fin.valEmbedding v : V color : V → Fin n valid : ∀ {a b : V}, Adj G a b → Adj ⊤ (color a) (color b) ⊢ ↑(Hom.comp (Embedding.toHom f) { toFun := color, map_rel' := valid }) v < n [PROOFSTEP] exact Fin.is_lt (color v) [GOAL] case mpr V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ ⊢ (∃ C, ∀ (v : V), ↑C v < n) → Colorable G n [PROOFSTEP] rintro ⟨C, Cf⟩ [GOAL] case mpr.intro V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ C : Coloring G ℕ Cf : ∀ (v : V), ↑C v < n ⊢ Colorable G n [PROOFSTEP] refine' ⟨Coloring.mk _ _⟩ [GOAL] case mpr.intro.refine'_1 V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ C : Coloring G ℕ Cf : ∀ (v : V), ↑C v < n ⊢ V → Fin n [PROOFSTEP] exact fun v => ⟨C v, Cf v⟩ [GOAL] case mpr.intro.refine'_2 V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ C : Coloring G ℕ Cf : ∀ (v : V), ↑C v < n ⊢ ∀ {v w : V}, Adj G v w → { val := ↑C v, isLt := (_ : ↑C v < n) } ≠ { val := ↑C w, isLt := (_ : ↑C w < n) } [PROOFSTEP] rintro v w hvw [GOAL] case mpr.intro.refine'_2 V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ C : Coloring G ℕ Cf : ∀ (v : V), ↑C v < n v w : V hvw : Adj G v w ⊢ { val := ↑C v, isLt := (_ : ↑C v < n) } ≠ { val := ↑C w, isLt := (_ : ↑C w < n) } [PROOFSTEP] simp only [Fin.mk_eq_mk, Ne.def] [GOAL] case mpr.intro.refine'_2 V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α n : ℕ C : Coloring G ℕ Cf : ∀ (v : V), ↑C v < n v w : V hvw : Adj G v w ⊢ ¬↑C v = ↑C w [PROOFSTEP] exact C.valid hvw [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ hc : Colorable G n ⊢ chromaticNumber G ≤ n [PROOFSTEP] rw [chromaticNumber] [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ hc : Colorable G n ⊢ sInf {n | Colorable G n} ≤ n [PROOFSTEP] apply csInf_le chromaticNumber_bddBelow [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ hc : Colorable G n ⊢ n ∈ {n | Colorable G n} [PROOFSTEP] constructor [GOAL] case val V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ hc : Colorable G n ⊢ Coloring G (Fin n) [PROOFSTEP] exact Classical.choice hc [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α m : ℕ hc : Colorable G m ⊢ Colorable G (chromaticNumber G) [PROOFSTEP] classical dsimp only [chromaticNumber] rw [Nat.sInf_def] apply Nat.find_spec exact colorable_set_nonempty_of_colorable hc [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α m : ℕ hc : Colorable G m ⊢ Colorable G (chromaticNumber G) [PROOFSTEP] dsimp only [chromaticNumber] [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α m : ℕ hc : Colorable G m ⊢ Colorable G (sInf {n | Colorable G n}) [PROOFSTEP] rw [Nat.sInf_def] [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α m : ℕ hc : Colorable G m ⊢ Colorable G (Nat.find ?m.140369) V : Type u G : SimpleGraph V α : Type v C : Coloring G α m : ℕ hc : Colorable G m ⊢ Set.Nonempty {n | Colorable G n} [PROOFSTEP] apply Nat.find_spec [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α m : ℕ hc : Colorable G m ⊢ Set.Nonempty {n | Colorable G n} [PROOFSTEP] exact colorable_set_nonempty_of_colorable hc [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Finite V ⊢ Colorable G (chromaticNumber G) [PROOFSTEP] cases nonempty_fintype V [GOAL] case intro V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Finite V val✝ : Fintype V ⊢ Colorable G (chromaticNumber G) [PROOFSTEP] exact colorable_chromaticNumber G.colorable_of_fintype [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Subsingleton V ⊢ chromaticNumber G ≤ 1 [PROOFSTEP] rw [chromaticNumber] [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Subsingleton V ⊢ sInf {n | Colorable G n} ≤ 1 [PROOFSTEP] apply csInf_le chromaticNumber_bddBelow [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Subsingleton V ⊢ 1 ∈ {n | Colorable G n} [PROOFSTEP] constructor [GOAL] case val V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Subsingleton V ⊢ Coloring G (Fin 1) [PROOFSTEP] refine' Coloring.mk (fun _ => 0) _ [GOAL] case val V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Subsingleton V ⊢ ∀ {v w : V}, Adj G v w → (fun x => 0) v ≠ (fun x => 0) w [PROOFSTEP] intro v w [GOAL] case val V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Subsingleton V v w : V ⊢ Adj G v w → (fun x => 0) v ≠ (fun x => 0) w [PROOFSTEP] rw [Subsingleton.elim v w] [GOAL] case val V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Subsingleton V v w : V ⊢ Adj G w w → (fun x => 0) w ≠ (fun x => 0) w [PROOFSTEP] simp [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : IsEmpty V ⊢ chromaticNumber G = 0 [PROOFSTEP] rw [← nonpos_iff_eq_zero] [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : IsEmpty V ⊢ chromaticNumber G ≤ 0 [PROOFSTEP] apply csInf_le chromaticNumber_bddBelow [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : IsEmpty V ⊢ 0 ∈ {n | Colorable G n} [PROOFSTEP] apply colorable_of_isEmpty [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Finite V h : chromaticNumber G = 0 ⊢ IsEmpty V [PROOFSTEP] have h' := G.colorable_chromaticNumber_of_fintype [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Finite V h : chromaticNumber G = 0 h' : Colorable G (chromaticNumber G) ⊢ IsEmpty V [PROOFSTEP] rw [h] at h' [GOAL] V : Type u G✝ : SimpleGraph V α : Type v C : Coloring G✝ α G : SimpleGraph V inst✝ : Finite V h : chromaticNumber G = 0 h' : Colorable G 0 ⊢ IsEmpty V [PROOFSTEP] exact G.isEmpty_of_colorable_zero h' [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Nonempty V n : ℕ hc : Colorable G n ⊢ 0 < chromaticNumber G [PROOFSTEP] apply le_csInf (colorable_set_nonempty_of_colorable hc) [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Nonempty V n : ℕ hc : Colorable G n ⊢ ∀ (b : ℕ), b ∈ {n | Colorable G n} → Nat.succ 0 ≤ b [PROOFSTEP] intro m hm [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Nonempty V n : ℕ hc : Colorable G n m : ℕ hm : m ∈ {n | Colorable G n} ⊢ Nat.succ 0 ≤ m [PROOFSTEP] by_contra h' [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Nonempty V n : ℕ hc : Colorable G n m : ℕ hm : m ∈ {n | Colorable G n} h' : ¬Nat.succ 0 ≤ m ⊢ False [PROOFSTEP] simp only [not_le] at h' [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Nonempty V n : ℕ hc : Colorable G n m : ℕ hm : m ∈ {n | Colorable G n} h' : m < Nat.succ 0 ⊢ False [PROOFSTEP] obtain ⟨i, hi⟩ := hm.some (Classical.arbitrary V) [GOAL] case mk V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Nonempty V n : ℕ hc : Colorable G n m : ℕ hm : m ∈ {n | Colorable G n} h' : m < Nat.succ 0 i : ℕ hi : i < m ⊢ False [PROOFSTEP] have h₁ : i < 0 := lt_of_lt_of_le hi (Nat.le_of_lt_succ h') [GOAL] case mk V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Nonempty V n : ℕ hc : Colorable G n m : ℕ hm : m ∈ {n | Colorable G n} h' : m < Nat.succ 0 i : ℕ hi : i < m h₁ : i < 0 ⊢ False [PROOFSTEP] exact Nat.not_lt_zero _ h₁ [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α h : 0 < chromaticNumber G ⊢ Colorable G (chromaticNumber G) [PROOFSTEP] obtain ⟨h, hn⟩ := Nat.nonempty_of_pos_sInf h [GOAL] case intro V : Type u G : SimpleGraph V α : Type v C : Coloring G α h✝ : 0 < chromaticNumber G h : ℕ hn : h ∈ {n | Colorable G n} ⊢ Colorable G (chromaticNumber G) [PROOFSTEP] exact colorable_chromaticNumber hn [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α V' : Type u_1 G' : SimpleGraph V' m : ℕ hc : Colorable G' m h : ∀ (n : ℕ), Colorable G' n → Colorable G n ⊢ chromaticNumber G ≤ chromaticNumber G' [PROOFSTEP] apply csInf_le chromaticNumber_bddBelow [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α V' : Type u_1 G' : SimpleGraph V' m : ℕ hc : Colorable G' m h : ∀ (n : ℕ), Colorable G' n → Colorable G n ⊢ chromaticNumber G' ∈ {n | Colorable G n} [PROOFSTEP] apply h [GOAL] case a V : Type u G : SimpleGraph V α : Type v C : Coloring G α V' : Type u_1 G' : SimpleGraph V' m : ℕ hc : Colorable G' m h : ∀ (n : ℕ), Colorable G' n → Colorable G n ⊢ Colorable G' (chromaticNumber G') [PROOFSTEP] apply colorable_chromaticNumber hc [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' ⊢ chromaticNumber G = Fintype.card α [PROOFSTEP] apply le_antisymm [GOAL] case a V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' ⊢ chromaticNumber G ≤ Fintype.card α [PROOFSTEP] apply chromaticNumber_le_card C [GOAL] case a V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' ⊢ Fintype.card α ≤ chromaticNumber G [PROOFSTEP] by_contra hc [GOAL] case a V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' hc : ¬Fintype.card α ≤ chromaticNumber G ⊢ False [PROOFSTEP] rw [not_le] at hc [GOAL] case a V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' hc : chromaticNumber G < Fintype.card α ⊢ False [PROOFSTEP] obtain ⟨n, cn, hc⟩ := exists_lt_of_csInf_lt (colorable_set_nonempty_of_colorable C.to_colorable) hc [GOAL] case a.intro.intro V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' hc✝ : chromaticNumber G < Fintype.card α n : ℕ cn : n ∈ {n | Colorable G n} hc : n < Fintype.card α ⊢ False [PROOFSTEP] rw [← Fintype.card_fin n] at hc [GOAL] case a.intro.intro V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' hc✝ : chromaticNumber G < Fintype.card α n : ℕ cn : n ∈ {n | Colorable G n} hc : Fintype.card (Fin n) < Fintype.card α ⊢ False [PROOFSTEP] have f := (Function.Embedding.nonempty_of_card_le (le_of_lt hc)).some [GOAL] case a.intro.intro V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' hc✝ : chromaticNumber G < Fintype.card α n : ℕ cn : n ∈ {n | Colorable G n} hc : Fintype.card (Fin n) < Fintype.card α f : Fin n ↪ α ⊢ False [PROOFSTEP] have C' := cn.some [GOAL] case a.intro.intro V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α h : ∀ (C' : Coloring G α), Function.Surjective ↑C' hc✝ : chromaticNumber G < Fintype.card α n : ℕ cn : n ∈ {n | Colorable G n} hc : Fintype.card (Fin n) < Fintype.card α f : Fin n ↪ α C' : Coloring G (Fin n) ⊢ False [PROOFSTEP] specialize h (G.recolorOfEmbedding f C') [GOAL] case a.intro.intro V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α hc✝ : chromaticNumber G < Fintype.card α n : ℕ cn : n ∈ {n | Colorable G n} hc : Fintype.card (Fin n) < Fintype.card α f : Fin n ↪ α C' : Coloring G (Fin n) h : Function.Surjective ↑(↑(recolorOfEmbedding G f) C') ⊢ False [PROOFSTEP] have h1 : Function.Surjective f := Function.Surjective.of_comp h [GOAL] case a.intro.intro V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α hc✝ : chromaticNumber G < Fintype.card α n : ℕ cn : n ∈ {n | Colorable G n} hc : Fintype.card (Fin n) < Fintype.card α f : Fin n ↪ α C' : Coloring G (Fin n) h : Function.Surjective ↑(↑(recolorOfEmbedding G f) C') h1 : Function.Surjective ↑f ⊢ False [PROOFSTEP] have h2 := Fintype.card_le_of_surjective _ h1 [GOAL] case a.intro.intro V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype α C : Coloring G α hc✝ : chromaticNumber G < Fintype.card α n : ℕ cn : n ∈ {n | Colorable G n} hc : Fintype.card (Fin n) < Fintype.card α f : Fin n ↪ α C' : Coloring G (Fin n) h : Function.Surjective ↑(↑(recolorOfEmbedding G f) C') h1 : Function.Surjective ↑f h2 : Fintype.card α ≤ Fintype.card (Fin n) ⊢ False [PROOFSTEP] exact Nat.lt_le_antisymm hc h2 [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Nonempty V ⊢ chromaticNumber ⊥ = 1 [PROOFSTEP] let C : (⊥ : SimpleGraph V).Coloring (Fin 1) := Coloring.mk (fun _ => 0) fun {v w} h => False.elim h [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Nonempty V C : Coloring ⊥ (Fin 1) := Coloring.mk (fun x => 0) (_ : ∀ {v w : V}, Adj ⊥ v w → (fun x => 0) v ≠ (fun x => 0) w) ⊢ chromaticNumber ⊥ = 1 [PROOFSTEP] apply le_antisymm [GOAL] case a V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Nonempty V C : Coloring ⊥ (Fin 1) := Coloring.mk (fun x => 0) (_ : ∀ {v w : V}, Adj ⊥ v w → (fun x => 0) v ≠ (fun x => 0) w) ⊢ chromaticNumber ⊥ ≤ 1 [PROOFSTEP] exact chromaticNumber_le_card C [GOAL] case a V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Nonempty V C : Coloring ⊥ (Fin 1) := Coloring.mk (fun x => 0) (_ : ∀ {v w : V}, Adj ⊥ v w → (fun x => 0) v ≠ (fun x => 0) w) ⊢ 1 ≤ chromaticNumber ⊥ [PROOFSTEP] exact chromaticNumber_pos C.to_colorable [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Fintype V ⊢ chromaticNumber ⊤ = Fintype.card V [PROOFSTEP] apply chromaticNumber_eq_card_of_forall_surj (selfColoring _) [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Fintype V ⊢ ∀ (C' : Coloring ⊤ V), Function.Surjective ↑C' [PROOFSTEP] intro C [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype V C : Coloring ⊤ V ⊢ Function.Surjective ↑C [PROOFSTEP] rw [← Finite.injective_iff_surjective] [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype V C : Coloring ⊤ V ⊢ Function.Injective ↑C [PROOFSTEP] intro v w [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype V C : Coloring ⊤ V v w : V ⊢ ↑C v = ↑C w → v = w [PROOFSTEP] contrapose [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype V C : Coloring ⊤ V v w : V ⊢ ¬v = w → ¬↑C v = ↑C w [PROOFSTEP] intro h [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α inst✝ : Fintype V C : Coloring ⊤ V v w : V h : ¬v = w ⊢ ¬↑C v = ↑C w [PROOFSTEP] exact C.valid h [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V ⊢ chromaticNumber ⊤ = 0 [PROOFSTEP] let n := (⊤ : SimpleGraph V).chromaticNumber [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V n : ℕ := chromaticNumber ⊤ ⊢ chromaticNumber ⊤ = 0 [PROOFSTEP] by_contra hc [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V n : ℕ := chromaticNumber ⊤ hc : ¬chromaticNumber ⊤ = 0 ⊢ False [PROOFSTEP] replace hc := pos_iff_ne_zero.mpr hc [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V n : ℕ := chromaticNumber ⊤ hc : 0 < chromaticNumber ⊤ ⊢ False [PROOFSTEP] apply Nat.not_succ_le_self n [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V n : ℕ := chromaticNumber ⊤ hc : 0 < chromaticNumber ⊤ ⊢ Nat.succ n ≤ n [PROOFSTEP] convert_to (⊤ : SimpleGraph {m | m < n + 1}).chromaticNumber ≤ _ [GOAL] case h.e'_3 V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V n : ℕ := chromaticNumber ⊤ hc : 0 < chromaticNumber ⊤ ⊢ Nat.succ n = chromaticNumber ⊤ [PROOFSTEP] rw [SimpleGraph.chromaticNumber_top, Fintype.card_ofFinset, Finset.card_range, Nat.succ_eq_add_one] [GOAL] case convert_2 V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V n : ℕ := chromaticNumber ⊤ hc : 0 < chromaticNumber ⊤ ⊢ chromaticNumber ⊤ ≤ n [PROOFSTEP] refine' (colorable_of_chromaticNumber_pos hc).chromaticNumber_mono_of_embedding _ [GOAL] case convert_2 V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V n : ℕ := chromaticNumber ⊤ hc : 0 < chromaticNumber ⊤ ⊢ ⊤ ↪g ⊤ [PROOFSTEP] apply Embedding.completeGraph [GOAL] case convert_2.f V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 inst✝ : Infinite V n : ℕ := chromaticNumber ⊤ hc : 0 < chromaticNumber ⊤ ⊢ ↑{m | m < n + 1} ↪ V [PROOFSTEP] exact (Function.Embedding.subtype _).trans (Infinite.natEmbedding V) [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 ⊢ ∀ {v w : V ⊕ W}, Adj (completeBipartiteGraph V W) v w → (fun v => Sum.isRight v) v ≠ (fun v => Sum.isRight v) w [PROOFSTEP] intro v w [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 v w : V ⊕ W ⊢ Adj (completeBipartiteGraph V W) v w → (fun v => Sum.isRight v) v ≠ (fun v => Sum.isRight v) w [PROOFSTEP] cases v [GOAL] case inl V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 w : V ⊕ W val✝ : V ⊢ Adj (completeBipartiteGraph V W) (Sum.inl val✝) w → (fun v => Sum.isRight v) (Sum.inl val✝) ≠ (fun v => Sum.isRight v) w [PROOFSTEP] cases w [GOAL] case inr V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 w : V ⊕ W val✝ : W ⊢ Adj (completeBipartiteGraph V W) (Sum.inr val✝) w → (fun v => Sum.isRight v) (Sum.inr val✝) ≠ (fun v => Sum.isRight v) w [PROOFSTEP] cases w [GOAL] case inl.inl V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 val✝¹ val✝ : V ⊢ Adj (completeBipartiteGraph V W) (Sum.inl val✝¹) (Sum.inl val✝) → (fun v => Sum.isRight v) (Sum.inl val✝¹) ≠ (fun v => Sum.isRight v) (Sum.inl val✝) [PROOFSTEP] simp [GOAL] case inl.inr V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 val✝¹ : V val✝ : W ⊢ Adj (completeBipartiteGraph V W) (Sum.inl val✝¹) (Sum.inr val✝) → (fun v => Sum.isRight v) (Sum.inl val✝¹) ≠ (fun v => Sum.isRight v) (Sum.inr val✝) [PROOFSTEP] simp [GOAL] case inr.inl V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 val✝¹ : W val✝ : V ⊢ Adj (completeBipartiteGraph V W) (Sum.inr val✝¹) (Sum.inl val✝) → (fun v => Sum.isRight v) (Sum.inr val✝¹) ≠ (fun v => Sum.isRight v) (Sum.inl val✝) [PROOFSTEP] simp [GOAL] case inr.inr V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 val✝¹ val✝ : W ⊢ Adj (completeBipartiteGraph V W) (Sum.inr val✝¹) (Sum.inr val✝) → (fun v => Sum.isRight v) (Sum.inr val✝¹) ≠ (fun v => Sum.isRight v) (Sum.inr val✝) [PROOFSTEP] simp [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W ⊢ SimpleGraph.chromaticNumber (completeBipartiteGraph V W) = 2 [PROOFSTEP] apply chromaticNumber_eq_card_of_forall_surj (CompleteBipartiteGraph.bicoloring V W) [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W ⊢ ∀ (C' : Coloring (completeBipartiteGraph V W) Bool), Function.Surjective ↑C' [PROOFSTEP] intro C b [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool ⊢ ∃ a, ↑C a = b [PROOFSTEP] have v := Classical.arbitrary V [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V ⊢ ∃ a, ↑C a = b [PROOFSTEP] have w := Classical.arbitrary W [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W ⊢ ∃ a, ↑C a = b [PROOFSTEP] have h : (completeBipartiteGraph V W).Adj (Sum.inl v) (Sum.inr w) := by simp [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W ⊢ Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) [PROOFSTEP] simp [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) ⊢ ∃ a, ↑C a = b [PROOFSTEP] have hn := C.valid h [GOAL] V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) ⊢ ∃ a, ↑C a = b [PROOFSTEP] by_cases he : C (Sum.inl v) = b [GOAL] case pos V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ↑C (Sum.inl v) = b ⊢ ∃ a, ↑C a = b [PROOFSTEP] exact ⟨_, he⟩ [GOAL] case neg V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ¬↑C (Sum.inl v) = b ⊢ ∃ a, ↑C a = b [PROOFSTEP] by_cases he' : C (Sum.inr w) = b [GOAL] case pos V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ¬↑C (Sum.inl v) = b he' : ↑C (Sum.inr w) = b ⊢ ∃ a, ↑C a = b [PROOFSTEP] exact ⟨_, he'⟩ [GOAL] case neg V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ¬↑C (Sum.inl v) = b he' : ¬↑C (Sum.inr w) = b ⊢ ∃ a, ↑C a = b [PROOFSTEP] exfalso [GOAL] case neg.h V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool b : Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ¬↑C (Sum.inl v) = b he' : ¬↑C (Sum.inr w) = b ⊢ False [PROOFSTEP] cases b [GOAL] case neg.h.false V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ¬↑C (Sum.inl v) = false he' : ¬↑C (Sum.inr w) = false ⊢ False [PROOFSTEP] simp only [Bool.eq_true_eq_not_eq_false, Bool.eq_false_eq_not_eq_true] at he he' [GOAL] case neg.h.true V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ¬↑C (Sum.inl v) = true he' : ¬↑C (Sum.inr w) = true ⊢ False [PROOFSTEP] simp only [Bool.eq_true_eq_not_eq_false, Bool.eq_false_eq_not_eq_true] at he he' [GOAL] case neg.h.false V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ↑C (Sum.inl v) = true he' : ↑C (Sum.inr w) = true ⊢ False [PROOFSTEP] rw [he, he'] at hn [GOAL] case neg.h.true V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : ↑C (Sum.inl v) ≠ ↑C (Sum.inr w) he : ↑C (Sum.inl v) = false he' : ↑C (Sum.inr w) = false ⊢ False [PROOFSTEP] rw [he, he'] at hn [GOAL] case neg.h.false V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : true ≠ true he : ↑C (Sum.inl v) = true he' : ↑C (Sum.inr w) = true ⊢ False [PROOFSTEP] contradiction [GOAL] case neg.h.true V✝ : Type u G : SimpleGraph V✝ α : Type v C✝ : Coloring G α V : Type u_1 W : Type u_2 inst✝¹ : Nonempty V inst✝ : Nonempty W C : Coloring (completeBipartiteGraph V W) Bool v : V w : W h : Adj (completeBipartiteGraph V W) (Sum.inl v) (Sum.inr w) hn : false ≠ false he : ↑C (Sum.inl v) = false he' : ↑C (Sum.inr w) = false ⊢ False [PROOFSTEP] contradiction [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α s : Finset V h : IsClique G ↑s inst✝ : Fintype α C : Coloring G α ⊢ Finset.card s ≤ Fintype.card α [PROOFSTEP] rw [isClique_iff_induce_eq] at h [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α s : Finset V h : induce (↑s) G = ⊤ inst✝ : Fintype α C : Coloring G α ⊢ Finset.card s ≤ Fintype.card α [PROOFSTEP] have f : G.induce ↑s ↪g G := Embedding.comap (Function.Embedding.subtype fun x => x ∈ ↑s) G [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α s : Finset V h : induce (↑s) G = ⊤ inst✝ : Fintype α C : Coloring G α f : induce (↑s) G ↪g G ⊢ Finset.card s ≤ Fintype.card α [PROOFSTEP] rw [h] at f [GOAL] V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α s : Finset V h : induce (↑s) G = ⊤ inst✝ : Fintype α C : Coloring G α f : ⊤ ↪g G ⊢ Finset.card s ≤ Fintype.card α [PROOFSTEP] convert Fintype.card_le_of_injective _ (C.comp f.toHom).injective_of_top_hom using 1 [GOAL] case h.e'_3 V : Type u G : SimpleGraph V α : Type v C✝ : Coloring G α s : Finset V h : induce (↑s) G = ⊤ inst✝ : Fintype α C : Coloring G α f : ⊤ ↪g G ⊢ Finset.card s = Fintype.card ↑↑s [PROOFSTEP] simp [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α s : Finset V h : IsClique G ↑s n : ℕ hc : Colorable G n ⊢ Finset.card s ≤ n [PROOFSTEP] convert h.card_le_of_coloring hc.some [GOAL] case h.e'_4 V : Type u G : SimpleGraph V α : Type v C : Coloring G α s : Finset V h : IsClique G ↑s n : ℕ hc : Colorable G n ⊢ n = Fintype.card (Fin n) [PROOFSTEP] simp [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Finite V s : Finset V h : IsClique G ↑s ⊢ Finset.card s ≤ chromaticNumber G [PROOFSTEP] cases nonempty_fintype V [GOAL] case intro V : Type u G : SimpleGraph V α : Type v C : Coloring G α inst✝ : Finite V s : Finset V h : IsClique G ↑s val✝ : Fintype V ⊢ Finset.card s ≤ chromaticNumber G [PROOFSTEP] exact h.card_le_of_colorable G.colorable_chromaticNumber_of_fintype [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n m : ℕ hc : Colorable G n hm : n < m ⊢ CliqueFree G m [PROOFSTEP] by_contra h [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n m : ℕ hc : Colorable G n hm : n < m h : ¬CliqueFree G m ⊢ False [PROOFSTEP] simp only [CliqueFree, isNClique_iff, not_forall, Classical.not_not] at h [GOAL] V : Type u G : SimpleGraph V α : Type v C : Coloring G α n m : ℕ hc : Colorable G n hm : n < m h : ∃ x, IsClique G ↑x ∧ Finset.card x = m ⊢ False [PROOFSTEP] obtain ⟨s, h, rfl⟩ := h [GOAL] case intro.intro V : Type u G : SimpleGraph V α : Type v C : Coloring G α n : ℕ hc : Colorable G n s : Finset V h : IsClique G ↑s hm : n < Finset.card s ⊢ False [PROOFSTEP] exact Nat.lt_le_antisymm hm (h.card_le_of_colorable hc)
import measure_theory.measurable_space import measure_theory.integration import measure_theory.borel_space namespace measure_theory section product universes u_1 u_2 variables (α:Type u_1) (β:Type u_2) (s:set α) open measure_theory measure_theory.simple_func lemma lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator {α} [M:measurable_space α] (μ:measure_theory.measure α) (Mf:measurable_space α) (hMf:Mf ≤ M) (c:ennreal) (T:set α) (h_meas_T:M.measurable_set' T) (h_ind:∀ (S:set α), Mf.measurable_set' S → (μ S * μ T = μ (S ∩ T))) (f:α → ennreal) (h_meas_f:@measurable α ennreal Mf _ f): @lintegral α M μ (λ a, (f * (T.indicator (λ (_x : α), c))) a) = @lintegral α M μ f * @lintegral α M μ (T.indicator (λ (_x : α), c)) := begin revert f, apply measurable.ennreal_induction, { intros c' s' h_meas_s', have h1:(λ a, (s'.indicator (λ (_x : α), c') * T.indicator (λ (_x : α), c)) a) = (λ a, (s' ∩ T).indicator (λ (_x :α), c * c') a), { ext1 a, cases classical.em (a ∈ s' ∩ T) with h1_1 h1_1, { rw set.indicator_of_mem h1_1, simp at h1_1, simp, rw if_pos, rw if_pos, rw mul_comm, apply h1_1.right, apply h1_1.left }, { rw set.indicator_of_not_mem h1_1, simp, simp at h1_1, intros h1_2 h1_3, exfalso, apply h1_1, apply h1_2, apply h1_3 } }, rw h1, rw measure_theory.lintegral_indicator, rw measure_theory.lintegral_indicator, rw measure_theory.lintegral_indicator, simp, rw ← h_ind, ring, apply h_meas_s', apply h_meas_T, apply hMf, apply h_meas_s', apply measurable_set.inter, apply hMf, apply h_meas_s', apply h_meas_T }, { intros f' g h_univ h_meas_f' h_meas_g h_ind_f' h_ind_g, have h_measM_f' := measurable.mono h_meas_f' hMf (le_refl _), have h_measM_g := measurable.mono h_meas_g hMf (le_refl _), have h_indicator:@measurable α ennreal M ennreal.measurable_space (λ (a : α), T.indicator (λ (_x : α), c) a), { apply measurable.indicator, apply measurable_const, apply h_meas_T, }, have h8:(f' + g) * T.indicator (λ (_x : α), c)= (λ a, (f' * (T.indicator (λ _, c))) a + (g * (T.indicator (λ _, c))) a), { ext1 a, simp [right_distrib] }, rw h8, have h_add:(f' + g) = (λ a, (f' a + g a)), { refl }, rw h_add, rw measure_theory.lintegral_add, rw measure_theory.lintegral_add, rw right_distrib, rw h_ind_f', rw h_ind_g, apply h_measM_f', apply h_measM_g, apply measurable.ennreal_mul, apply h_measM_f', apply h_indicator, apply measurable.ennreal_mul, apply h_measM_g, apply h_indicator, }, { intros f h_meas_f h_mono_f h_ind_f, have h_measM_f := (λ n, measurable.mono (h_meas_f n) hMf (le_refl _)), have h_mul: (λ a, ((λ (x : α), ⨆ (n : ℕ), f n x) * T.indicator (λ (_x : α), c)) a) = (λ (a : α), ⨆ (n : ℕ), (λ (x:α), f n x * (T.indicator (λ (_x : α), c) x)) a), { ext1 a, rw @pi.mul_apply, rw ennreal.supr_mul, }, rw h_mul, rw lintegral_supr, rw lintegral_supr, rw ennreal.supr_mul, have h_mul2:(λ (n:ℕ), (@lintegral α M μ (λ (x : α), f n x * T.indicator (λ (_x : α), c) x))) = (λ n, @lintegral α M μ (f n) * @lintegral α M μ (T.indicator (λ (_x : α), c))), { ext1 n, rw ← h_ind_f n, refl }, rw h_mul2, apply h_measM_f, apply h_mono_f, { intros n, apply measurable.ennreal_mul, apply h_measM_f, apply measurable.indicator, apply measurable_const, apply h_meas_T }, { intros m n h_le a, apply ennreal.mul_le_mul, apply h_mono_f, apply h_le, apply le_refl _ }, }, end lemma lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space {α} [M:measurable_space α] (μ:measure_theory.measure α) (Mf:measurable_space α) (Mg:measurable_space α) (hMf:Mf ≤ M) (hMg:Mg ≤ M) (h_ind:∀ (S T:set α), Mf.measurable_set' S → Mg.measurable_set' T → (μ S * μ T = μ (S ∩ T))) (f g:α → ennreal) (h_meas_f:@measurable α ennreal Mf _ f) (h_meas_g:@measurable α ennreal Mg _ g): @lintegral α M μ (λ a, (f * g) a) = @lintegral α M μ f * @lintegral α M μ g := begin revert g, have h_meas_Mf:∀ ⦃f:α → ennreal⦄, (@measurable α ennreal Mf _ f) → (@measurable α ennreal M _ f), { intros f' h_meas_f', apply measurable.mono h_meas_f' hMf, apply le_refl _ }, have h_meas_Mg:∀ ⦃f:α → ennreal⦄, (@measurable α ennreal Mg _ f) → (@measurable α ennreal M _ f), { intros f' h_meas_f', apply measurable.mono h_meas_f' hMg, apply le_refl _ }, have H1:= h_meas_Mf h_meas_f, apply measurable.ennreal_induction, intros c s h_s, { apply lintegral_mul_indicator_eq_lintegral_mul_lintegral_indicator, apply hMf, apply hMg, apply h_s, { intros S h_meas_S, apply h_ind, apply h_meas_S, apply h_s, }, apply h_meas_f, }, { intros f' g h_univ h_measMg_f' h_measMg_g h_ind_f' h_ind_g', have h_measM_f' := h_meas_Mg h_measMg_f', have h_measM_g := h_meas_Mg h_measMg_g, have h_add:(f' + g) = (λ a, (f' a + g a)), { refl }, rw h_add, rw measure_theory.lintegral_add, have h8:(λ a, (f * λ a', (f' a' + g a')) a ) = (λ a, (f a * f' a) + (f a * g a)), { ext1 a, simp [left_distrib], }, rw h8, rw measure_theory.lintegral_add, rw left_distrib, have h9:(λ a, (f * f') a) = (λ a, f a * f' a), { ext1 a, refl }, rw ← h9, rw h_ind_f', have h10:(λ a, (f * g) a) = (λ a, f a * g a), { ext1 a, refl }, rw ← h10, rw h_ind_g', apply measurable.ennreal_mul, apply H1, apply h_measM_f', apply measurable.ennreal_mul, apply H1, apply h_measM_g, apply h_measM_f', apply h_measM_g }, { intros f' h_meas_f' h_mono_f' h_ind_f', have h_measM_f' := (λ n, h_meas_Mg (h_meas_f' n)), have h_mul:(λ (a : α), (f * λ (x : α), ⨆ (n : ℕ), f' n x) a) = (λ (a : α), ⨆ (n : ℕ), (λ (x:α), (f x * f' n x)) a), { ext1 a, simp, rw ennreal.mul_supr }, rw h_mul, rw lintegral_supr, rw lintegral_supr, rw ennreal.mul_supr, have h_mul2:(λ (n:ℕ), (@lintegral α M μ (λ (x : α), f x * f' n x))) = (λ n, @lintegral α M μ f * @lintegral α M μ (f' n)), { ext1 n, rw ← h_ind_f' n, refl }, rw h_mul2, { apply h_measM_f', }, { apply h_mono_f', }, { intros n, apply measurable.ennreal_mul, apply H1, apply h_measM_f' }, { intros n m h_le a, apply ennreal.mul_le_mul, apply le_refl _, apply h_mono_f' h_le, }, }, end lemma lintegral_mul_eq_lintegral_mul_lintegral_of_independent_fn {α} [M:measurable_space α] (μ:measure_theory.measure α) (f g:α → ennreal) (h_meas_f:measurable f) (h_meas_g:measurable g) (h_ind:∀ (S T:set ennreal), measurable_set S → measurable_set T → (μ (f ⁻¹' S) * μ (g ⁻¹' T) = μ ((f ⁻¹' S) ∩ (g ⁻¹' T)))): ∫⁻ (a : α), (f * g) a ∂μ = (∫⁻ (a : α), f a ∂μ) * (∫⁻ (a : α), g a ∂μ) := begin let Mf := ennreal.measurable_space.comap f, let Mg := ennreal.measurable_space.comap g, begin apply lintegral_mul_eq_lintegral_mul_lintegral_of_independent_measurable_space μ Mf Mg, { rw measurable_iff_comap_le at h_meas_f, apply h_meas_f }, { rw measurable_iff_comap_le at h_meas_g, apply h_meas_g }, { intros S T h_S h_T, have h_S':∃ (A:set ennreal), (measurable_set A) ∧ (f ⁻¹' A = S), { apply h_S }, have h_T':∃ (B:set ennreal), (measurable_set B) ∧ (g ⁻¹' B = T), { apply h_T }, cases h_S' with A h_S', cases h_T' with B h_T', rw ← h_S'.right, rw ← h_T'.right, apply h_ind, apply h_S'.left, apply h_T'.left }, { rw measurable_iff_comap_le, apply le_refl _ }, { rw measurable_iff_comap_le, apply le_refl _ }, end end end product end measure_theory
function [spec, headerinfo] = read_caret_spec(specfile) % READ_CARET_SPEC reads in a caret .spec file. % % Use as % [spec, headerinfo] = read_caret_spec(specfile) % % Output arguments: % spec = structure containing per file type the files listed % headerinfo = structure containing the specfile header % % The file can be an xml-file or an ascii formatted file % Copyright (C) 2013, Jan-Mathijs Schoffelen try, % read xml-file that contains a description to a bunch of files % belonging together ft_hastoolbox('gifti', 1); g = xmltree(specfile); % convert into a structure s = convert(g); if isfield(s, 'FileHeader') headerinfo = s.FileHeader; spec = rmfield(s, 'FileHeader'); else headerinfo = []; spec = s; end % process the headerinfo if ~isempty(headerinfo) if isfield(headerinfo, 'Element') tmp = headerinfo.Element; tmp2 = struct([]); for k = 1:numel(headerinfo.Element) tmp2(1).(strrep(headerinfo.Element{k}.Name, '-', '_')) = headerinfo.Element{k}.Value; end headerinfo = tmp2; end end % further process the fields in spec f = fieldnames(spec); for k = 1:numel(f) if isempty(strfind(f{k}, 'study_metadata')) if iscell(spec.(f{k})) tmp = spec.(f{k}); tmp2 = {}; for m = 1:numel(tmp) tmpx = tmp{m}; if isstruct(tmpx) fn = fieldnames(tmpx) for i = 1:numel(fn) tmp2{end+1,1} = tmpx.(fn{i}); end end end spec.(f{k}) = tmp2; elseif isstruct(spec.(f{k})) tmp = spec.(f{k}); fn = fieldnames(tmp); tmp2 = {}; for m = 1:numel(fn) tmp2{end+1,1} = tmp.(fn{m}); end spec.(f{k}) = tmp2; else % don't know what to do with it spec = rmfield(spec, f{k}); end else % don't know what to do with it spec = rmfield(spec, f{k}); end end catch % process as ASCII-file fid = fopen_or_error(specfile); line = 'some text'; while isempty(strfind(line, 'EndHeader')) line = fgetl(fid); if isempty(strfind(line, 'BeginHeader')) && isempty(strfind(line, 'EndHeader')) tok = tokenize(line, ' '); headerinfo.(strrep(tok{1},'-','_')) = tok{2}; end end line = fgetl(fid); % empty line spec = struct([]); while 1 line = fgetl(fid); if ~ischar(line), break, end tok = tokenize(line, ' '); if ~isempty(tok{1}) if isfield(spec, tok{1}) spec(1).(tok{1}){end+1,1} = tok{2}; else spec(1).(tok{1}){1} = tok{2}; end end end fclose(fid); end
theory book imports Main begin lemma conj_swap1: "P \<and> Q \<Longrightarrow> Q \<and> P" apply (rule conjI) apply (erule conjE) apply assumption apply (erule conjE) apply assumption done lemma conj_swap2: "P \<and> Q \<Longrightarrow> Q \<and> P" apply (rule conjI) apply (drule conjunct2) apply assumption apply (drule conjunct1) apply assumption done lemma imp_uncurry1: "P \<longrightarrow> (Q \<longrightarrow> R) \<Longrightarrow> P \<and> Q \<longrightarrow> R" apply (rule impI) apply (erule impE) apply (erule conjE) apply assumption apply (erule impE) apply (erule conjE) apply assumption+ done lemma imp_uncurry2: "P \<longrightarrow> (Q \<longrightarrow> R) \<Longrightarrow> P \<and> Q \<longrightarrow> R" apply (rule impI) apply (erule conjE) apply (drule mp) apply assumption apply (drule mp) apply assumption+ done lemma imp_uncurry3: "P \<longrightarrow> (Q \<longrightarrow> R) \<Longrightarrow> P \<and> Q \<longrightarrow> R" apply (rule impI) apply (erule conjE) apply (drule mp) apply assumption by (drule mp) lemma "\<lbrakk> \<not>(P \<longrightarrow> Q); \<not>(R \<longrightarrow> Q) \<rbrakk> \<Longrightarrow> R" apply (erule_tac Q="R\<longrightarrow>Q" in contrapos_np) apply (intro impI) (* rule impI works too *) by (erule notE) lemma "(P \<and> Q) \<and> R \<Longrightarrow> P \<or> (Q \<and> R)" apply (rule disjCI) apply (elim conjE disjE) (* rule conjE, rule disjE *) by (erule contrapos_np, rule conjI) (* apply assumption *) end
\subsection{Offline Nesting Experiment} \label{subsec:nest_offline} %------------------------------------------------------ The following two limitations are imposed for the offline nesting experiment: \begin{itemize} \item The child domain is completely included in the parent domain. \item The integration time for the child domain is the same as or less than that for the parent domain. \end{itemize} Furthermore, the offline experiment is conducted in the following order: \begin{enumerate} \item The temporal integration of the parent domain is conducted. \item The initial and boundary conditions for the child domain are generated using the history or init/restart output of the parent domain. \item Using the generated initial and boundary data, the temporal integration of the child domain is conducted. \end{enumerate} An explanation is provided according to the above workflow. \subsubsection{Time Integration of Parent Domain} In order to prepare the data in parent domain which is used as the boundary data for the child domain, there are some necessary settings. The configuration files for the simulation in the parent domain can be generated by using ``the supporting tool for the preparation of configuration file'' (See \ref{sec:basic_makeconf}). Rename the sample files \\ \verb|${Tutorial_dir}/real/sample/USER.offline-nesting-parent.sh| to \verb|USER.sh|, and run \verb|make|. The time integration of the parent domain is carried out as a single-domain computation. However, the following five aspects need to be considered in the configuration. \begin{itemize} \item All variables required for the computation in the child domain have already been generated with the computation of the parent domain as history or restart output. \item The interval of the history or restart output is sufficiently short. \item The ``catalog file,'' which gives information pertaining to the parent’s calculation domain to the child domain, is output. \item The history in the parent domain is output at the model levels if the history file is used. \item In case the starting time of the computation in the child domain is the same as that in the parent domain, history output data at $t=0$ in the parent domain is required. \end{itemize} In order to output the ``catalog file'', configuration file for either the preprocess, initialization or simulation run should have setting like the following: \editboxtwo{ \verb|&PARAM_DOMAIN_CATALOGUE| & \\ \verb| DOMAIN_CATALOGUE_FNAME = "latlon_domain_catalogue_d01.txt",| & Name of catalog file\\ \textcolor{blue}{\verb| DOMAIN_CATALOGUE_OUTPUT = .true.,|} & Output the catalog file\\ \verb|/| \\ } If the output option of the catalog file is \verb|.true.|, the file \verb|latlon_domain_catalogue_d01.txt| (in the case of this example) is output. In the case ``the making tool for the complete settings of the experiment'' is used, the file with the same name is generated in the directory \verb|pp|. In this file, the latitudes and longitudes of the four corners of the regions where each MPI manages the parent domain calculation are described. If you want to use history file, setting like the following is required. \editboxtwo{ \verb|&PARAM_FILE_HISTORY| &\\ \verb| FILE_HISTORY_DEFAULT_BASENAME = "history",| & \\ \textcolor{blue}{\verb| FILE_HISTORY_DEFAULT_TINTERVAL = 900.D0,|} & Time interval of history data output\\ \verb| FILE_HISTORY_DEFAULT_TUNIT = "SEC",| & Unit of \verb|FILE_HISTORY_DEFAULT_TINTERVAL|\\ \verb| FILE_HISTORY_DEFAULT_TAVERAGE = .false.,| & \\ \verb| FILE_HISTORY_DEFAULT_DATATYPE = "REAL4",| & \\ \textcolor{blue}{\verb| FILE_HISTORY_DEFAULT_ZCOORD = "model",|} & Output the data at model surface\\ \textcolor{blue}{\verb| FILE_HISTORY_OUTPUT_STEP0 = .true.,|} & Include the output data at $t=0$ \\ \verb|/| \\ } \nmitem{FILE_HISTORY_DEFAULT_TINTERVAL} is the time interval of the history output, which is configured as the update time interval used in the calculation of the child domain. Take care of the free disk space if the time interval of the data output is relatively short. Refer to Section \ref{sec:output} for details of the items in \namelist{PARAM_FILE_HISTORY}. If you want to use restart files, the setting is like \editboxtwo{ \verb|&PARAM_RESTART| & \\ \textcolor{blue}{\verb| RESTART_OUTPUT = .true.|} & \\ \textcolor{blue}{\verb| RESTART_OUT_BASENAME = 'restart_d01',|} & \\ \verb|/|& \\ \verb|&PARAM_TIME| & \\ \textcolor{blue}{\verb| TIME_DT_ATMOS_RESTART = 900.D0,|} & Time interval of restart data output\\ \textcolor{blue}{\verb| TIME_DT_ATMOS_RESTART_UNIT = "SEC",|} & \\ \textcolor{blue}{\verb| TIME_DT_OCEAN_RESTART = 900.D0,|} & Time interval of restart data output\\ \textcolor{blue}{\verb| TIME_DT_OCEAN_RESTART_UNIT = "SEC",|} & \\ \textcolor{blue}{\verb| TIME_DT_LAND_RESTART = 900.D0,|} & Time interval of restart data output\\ \textcolor{blue}{\verb| TIME_DT_LAND_RESTART_UNIT = "SEC",|} & \\ \textcolor{blue}{\verb| TIME_DT_URBAN_RESTART = 900.D0,|} & Time interval of restart data output\\ \textcolor{blue}{\verb| TIME_DT_URBASN_RESTART_UNIT = "SEC",|} & \\ \verb|/|& \\ } For details of these parameters, see Section \ref{sec:restart}. All necessary variables for the generation of initial and boundary data for the child domain must be described in \namelist{FILE_HISTORY_ITEM} in the file \runconf. The necessary variables for offline nesting depends on the setting of the simulation in the child domain, the following is variables in standard real atmospheric simulations. \begin{alltt} T2, MSLP, DENS, MOMZ, MOMX, MOMY, RHOT, QV LAND_SFC_TEMP, URBAN_SFC_TEMP, OCEAN_SFC_TEMP OCEAN_SFC_ALB_IR_dir OCEAN_SFC_ALB_IR_dif, OCEAN_SFC_ALB_NIR_dir OCEAN_SFC_ALB_NIR_dif, OCEAN_SFC_ALB_VIS_dir OCEAN_SFC_ALB_VIS_dif, LAND_SFC_ALB_IR_dir, LAND_SFC_ALB_IR_dif, LAND_SFC_ALB_NIR_dir, LAND_SFC_ALB_NIR_dif, LAND_SFC_ALB_VIS_dir, LAND_SFC_ALB_VIS_dif, OCEAN_TEMP, OCEAN_SFC_Z0M, LAND_TEMP, LAND_WATER \end{alltt} (Output according to microphysics model used in the parent model) \begin{alltt} QC, QR, QI, QS, QG NC, NR, NI, NS, NG \end{alltt} Once this configuration is complete, conduct the time integration of the parent domain by \verb|scale-rm|. In general, the variables at the lower layer than the lowest layer in the parent simulation are calculated by extrapolation. Extrapolation may result unrealistic value, especially when the lowest layer in the parent simulation is much higher than that in the child simulation. In order to avoid this problem, the mean sea-level pressure and 2-m temperature are used to calculate these variables if you use the history file. On the other hand, if you use the restart file, such quantities are not contained in the file. Therefore, the variables at the layers lower than the parent lowest layer is just copy of the value at the lowest layer. %------------------------------------------------------------- \subsubsection{Generation of Initial and Boundary Data for Child Domain} To prepare the configuration files for simulations in the child domain can be generated by using ``the supporting tool for the preparation of configuration file'' (See \ref{sec:basic_makeconf}). Rename the sample files \\ \verb|${Tutorial_dir}/real/sample/USER.offline-nesting-child.sh| to USER.sh, and run \verb|make|. In the case that you generate the initial and boundary data using the history data from the simulation for the parent domain, \initconf is configured as follows: \editboxtwo{ \textcolor{blue}{\verb|&PARAM_COMM_CARTESC_NEST|} & \\ \textcolor{blue}{\verb| OFFLINE_PARENT_BASENAME = "history_d01",|} & file name of the parent domain \\ \textcolor{blue}{\verb| OFFLINE_PARENT_PRC_NUM_X = 2,|} & \verb|PRC_NUM_X| in the file \verb|run.d01.conf|\\ \textcolor{blue}{\verb| OFFLINE_PARENT_PRC_NUM_Y = 2,|} & \verb|PRC_NUM_Y| in the file \verb|run.d01.conf|\\ \textcolor{blue}{\verb| LATLON_CATALOGUE_FNAME =| \textbackslash} &\\ \textcolor{blue}{\hspace{1cm}\verb| "latlon_domain_catalogue_d01.txt",|} & catalog file generated at the parent domain process\\ \textcolor{blue}{\verb|/|} &\\ & \\ \verb|&PARAM_MKINIT_REAL_ATMOS| &\\ \textcolor{blue}{\verb| NUMBER_OF_TSTEPS = 25,|} & number of time steps in the history file\\ \verb| NUMBER_OF_FILES = 1,| & \\ \verb| BASENAME_ORG = "history_d01",| & \verb|FILE_HISTORY_DEFAULT_BASENAME| in the file \verb|run.d01.conf|\\ \verb| FILETYPE_ORG = "SCALE-RM",| & \\ \verb| BASENAME_BOUNDARY = "boundary_d01",| &\\ \textcolor{blue}{\verb| BOUNDARY_UPDATE_DT = 900.D0,|} & time interval of history output (unit:\verb|"SEC"|) \\ \verb|/| &\\ & \\ \verb|&PARAM_MKINIT_REAL_OCEAN| &\\ \textcolor{blue}{\verb| NUMBER_OF_TSTEPS = 25,|} & number of time steps in the history file\\ \verb| NUMBER_OF_FILES = 1,| & \\ \verb| BASENAME_ORG = "history_d01",| & \verb|FILE_HISTORY_DEFAULT_BASENAME| in the file \verb|run.d01.conf|\\ \verb| FILETYPE_ORG = "SCALE-RM",| & \\ \verb| BASENAME_BOUNDARY = "boundary_d01",| &\\ \textcolor{blue}{\verb| BOUNDARY_UPDATE_DT = 900.D0,|} & time interval of history output (unit:\verb|"SEC"|) \\ \verb|/| &\\ & \\ \verb|&PARAM_MKINIT_REAL_LAND| &\\ \textcolor{blue}{\verb| NUMBER_OF_TSTEPS = 25,|} & number of time steps in the history file\\ \verb| NUMBER_OF_FILES = 1,| & \\ \verb| BASENAME_ORG = "history_d01",| & \verb|FILE_HISTORY_DEFAULT_BASENAME| in the file \verb|run.d01.conf|\\ \verb| FILETYPE_ORG = "SCALE-RM",| & \\ \verb| BASENAME_BOUNDARY = "boundary_d01",| &\\ \textcolor{blue}{\verb| BOUNDARY_UPDATE_DT = 900.D0,|} & time interval of history output (unit:\verb|"SEC"|) \\ \verb|/| &\\ } In order to generate the initial and boundary data from the output of \scalerm format, \nmitem{FILETYPE_ORG} is specified as \verb|"SCALE-RM"|. \nmitem{BOUNDARY_UPDATE_DT} is set to the same value of \nmitem{FILE_HISTORY_DEFAULT_TINTERVAL} as in the configuration file in the parent domain (\verb|run.d01.conf|). The items in \namelist{PARAM_COMM_CARTESC_NEST} are prepared for the nesting experiment. In offline nesting, the file name of the data in the parent domain is specified as \nmitem{OFFLINE_PARENT_BASENAME} . The number of processes of the parent domain is also specified as \nmitem{OFFLINE_PARENT_PRC_NUM_*}. Configure them correctly by referring to the configuration file for the parent domain (\verb|run.d01.conf|). In the case that the restart files are used to generate the initial and boundary data, set \nmitem{NUMBER_OF_TSTEPS} = 1 and \nmitem{NUMBER_OF_FILES} to the number of the time steps. Additionally, the restart files must be renamed or symbolic links must be created to make file names have incremented number like \verb|restart_d01_00000.pe000000.nc| as described in Section \ref{sec:datainput_grads}. After editing the configuration file, form the initial and boundary data for the child domain by \verb|scale-rm_init|. If the execution is aborted with the message like the following, it means that the child domain is not completely contained in the parent domain: \msgbox{ \verb|ERROR [INTERP_domain_compatibility] REQUESTED DOMAIN IS TOO MUCH BROAD| \\ \verb| -- LONGITUDINAL direction over the limit| \\ } \subsubsection{Time Integration in Child Domain} Following the generation of the initial and boundary conditions, compute the time integration in the child domain by \verb|scale-rm|. This is same as in the usual atmospheric experiment. Before this, confirm that \nmitem{ATMOS_BOUNDARY_UPDATE_DT} of \namelist{PARAM_ATMOS_BOUNDARY} in the file \runconf is the same as the time interval of the output of history data for the parent domain. Note that the calculation continues without any message even if these time intervals are inconsistent in the current version. \editbox{ \verb|&PARAM_ATMOS_BOUNDARY| \\ \textcolor{blue}{\verb| ATMOS_BOUNDARY_UPDATE_DT = 900.D0,|} \\ \verb|/| \\ } If an experiment involving multiple offline nestings is performed, the above procedure is repeated; the results of the above time integration for the child domain are regarded as those for the parent domain, and the initial and boundary data are generated for further inner domain calculations.
function obj = iatgetDemoObject % IATGETDEMOOBJECT Returns the object used by the motion detection demo. % % IATGETDEMOOBJECT finds the VIDEOINPUT object used by the motion detection % demo and returns it. % % See also VIDEOINPUT. % DT 4/2004 % Copyright 2004 The MathWorks, Inc. % Look for existing objects created by the demo. obj = imaqfind('Tag', 'Motion Detection Object'); if isempty(obj) obj = localCreateObj; stop(obj) % Clear the callbacks. obj.TimerFcn = ''; obj.FramesAcquiredFcn = ''; obj.StartFcn = ''; obj.StopFcn = ''; obj.TriggerFcn = ''; % Configure the object for manual trigger so that GETSNAPSHOT returns % quicker. triggerconfig(obj, 'Manual'); % Configure the object to return YCbCr data which the demo requires. set(obj, 'ReturnedColorSpace', 'YCbCr'); % Save the video resolution in the base workspace. videoRes = obj.ROIPosition; assignin('base', 'videoRes', [videoRes(4) videoRes(3)]); else obj = obj{1}; % Save the video resolution in the base workspace. videoRes = obj.ROIPosition; assignin('base', 'videoRes', [videoRes(4) videoRes(3)]); end function obj = localCreateObj % localCreateObj searches for the first supported device with a % default format. Once found, it creates an object for that device and % returns the object to the calling function. Some devices do not have % default formats and can not be used since the demo doesn't provide a % method of specifying camera files. % Determine the available adaptors. info = imaqhwinfo; adaptorName = []; adaptorID = []; adaptorIndex = 1; % Search through all of the installed adaptors until an available adaptor % with hardware that has a default format is found. while (isempty(adaptorName) && isempty(adaptorID)) if (adaptorIndex > length(info.InstalledAdaptors)) error('imaq:motiondetection:nohardware', 'No hardware compatible with the motion detection demo was found.'); end % Get information on the current adaptor. curAdaptor = info.InstalledAdaptors{adaptorIndex}; adaptorInfo = imaqhwinfo(curAdaptor); % For the current adaptor, search through each installed device looking % for a device that has a default format. idIndex = 1; while (isempty(adaptorID) && (idIndex <= length(adaptorInfo.DeviceIDs))) curID = adaptorInfo.DeviceIDs{idIndex}; if ~isempty(adaptorInfo.DeviceInfo(idIndex).DefaultFormat) adaptorName = curAdaptor; adaptorID = curID; end % If the current device doesn't have a default format check the % next one. idIndex = idIndex + 1; end % Check the next adaptor. adaptorIndex = adaptorIndex + 1; end % Create the object. obj = videoinput(adaptorName, adaptorID); % Configure the object's tag so that it can be found later by using % IMAQFIND. set(obj, 'Tag', 'Motion Detection Object'); % End of localCreateObj
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fin.fin2 import data.pfun import data.vector3 import number_theory.pell /-! # Diophantine functions and Matiyasevic's theorem Hilbert's tenth problem asked whether there exists an algorithm which for a given integer polynomial determines whether this polynomial has integer solutions. It was answered in the negative in 1970, the final step being completed by Matiyasevic who showed that the power function is Diophantine. Here a function is called Diophantine if its graph is Diophantine as a set. A subset `S ⊆ ℕ ^ α` in turn is called Diophantine if there exists an integer polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. ## Main definitions * `is_poly`: a predicate stating that a function is a multivariate integer polynomial. * `poly`: the type of multivariate integer polynomial functions. * `dioph`: a predicate stating that a set is Diophantine, i.e. a set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. * `dioph_fn`: a predicate on a function stating that it is Diophantine in the sense that its graph is Diophantine as a set. ## Main statements * `pell_dioph` states that solutions to Pell's equation form a Diophantine set. * `pow_dioph` states that the power function is Diophantine, a version of Matiyasevic's theorem. ## References * [M. Carneiro, _A Lean formalization of Matiyasevic's theorem_][carneiro2018matiyasevic] * [M. Davis, _Hilbert's tenth problem is unsolvable_][MR317916] ## Tags Matiyasevic's theorem, Hilbert's tenth problem ## TODO * Finish the solution of Hilbert's tenth problem. * Connect `poly` to `mv_polynomial` -/ universe u open nat function namespace int lemma eq_nat_abs_iff_mul (x n) : nat_abs x = n ↔ (x - n) * (x + n) = 0 := begin refine iff.trans _ mul_eq_zero.symm, refine iff.trans _ (or_congr sub_eq_zero add_eq_zero_iff_eq_neg).symm, exact ⟨λe, by rw ← e; apply nat_abs_eq, λo, by cases o; subst x; simp [nat_abs_of_nat]⟩ end end int open fin2 /-- `list_all p l` is equivalent to `∀ a ∈ l, p a`, but unfolds directly to a conjunction, i.e. `list_all p [0, 1, 2] = p 0 ∧ p 1 ∧ p 2`. -/ @[simp] def list_all {α} (p : α → Prop) : list α → Prop | [] := true | (x :: []) := p x | (x :: l) := p x ∧ list_all l @[simp] theorem list_all_cons {α} (p : α → Prop) (x : α) : ∀ (l : list α), list_all p (x :: l) ↔ p x ∧ list_all p l | [] := (and_true _).symm | (x :: l) := iff.rfl theorem list_all_iff_forall {α} (p : α → Prop) : ∀ (l : list α), list_all p l ↔ ∀ x ∈ l, p x | [] := (iff_true_intro $ list.ball_nil _).symm | (x :: l) := by rw [list.ball_cons, ← list_all_iff_forall l]; simp theorem list_all.imp {α} {p q : α → Prop} (h : ∀ x, p x → q x) : ∀ {l : list α}, list_all p l → list_all q l | [] := id | (x :: l) := by simpa using and.imp (h x) list_all.imp @[simp] theorem list_all_map {α β} {p : β → Prop} (f : α → β) {l : list α} : list_all p (l.map f) ↔ list_all (p ∘ f) l := by induction l; simp * theorem list_all_congr {α} {p q : α → Prop} (h : ∀ x, p x ↔ q x) {l : list α} : list_all p l ↔ list_all q l := ⟨list_all.imp (λx, (h x).1), list_all.imp (λx, (h x).2)⟩ instance decidable_list_all {α} (p : α → Prop) [decidable_pred p] (l : list α) : decidable (list_all p l) := decidable_of_decidable_of_iff (by apply_instance) (list_all_iff_forall _ _).symm /- poly -/ /-- A predicate asserting that a function is a multivariate integer polynomial. (We are being a bit lazy here by allowing many representations for multiplication, rather than only allowing monomials and addition, but the definition is equivalent and this is easier to use.) -/ inductive is_poly {α} : ((α → ℕ) → ℤ) → Prop | proj : ∀ i, is_poly (λx : α → ℕ, x i) | const : Π (n : ℤ), is_poly (λx : α → ℕ, n) | sub : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x - g x) | mul : Π {f g : (α → ℕ) → ℤ}, is_poly f → is_poly g → is_poly (λx, f x * g x) /-- The type of multivariate integer polynomials -/ def poly (α : Type u) := {f : (α → ℕ) → ℤ // is_poly f} namespace poly section parameter {α : Type u} instance : has_coe_to_fun (poly α) (λ _, (α → ℕ) → ℤ) := ⟨λ f, f.1⟩ /-- The underlying function of a `poly` is a polynomial -/ lemma isp (f : poly α) : is_poly f := f.2 /-- Extensionality for `poly α` -/ lemma ext {f g : poly α} (e : ∀x, f x = g x) : f = g := subtype.eq (funext e) /-- Construct a `poly` given an extensionally equivalent `poly`. -/ def subst (f : poly α) (g : (α → ℕ) → ℤ) (e : ∀x, f x = g x) : poly α := ⟨g, by rw ← (funext e : coe_fn f = g); exact f.isp⟩ @[simp] theorem subst_eval (f g e x) : subst f g e x = g x := rfl /-- The `i`th projection function, `x_i`. -/ def proj (i) : poly α := ⟨_, is_poly.proj i⟩ @[simp] theorem proj_eval (i x) : proj i x = x i := rfl /-- The constant function with value `n : ℤ`. -/ def const (n) : poly α := ⟨_, is_poly.const n⟩ @[simp] theorem const_eval (n x) : const n x = n := rfl /-- The zero polynomial -/ def zero : poly α := const 0 instance : has_zero (poly α) := ⟨poly.zero⟩ @[simp] theorem zero_eval (x) : (0 : poly α) x = 0 := rfl /-- The zero polynomial -/ def one : poly α := const 1 instance : has_one (poly α) := ⟨poly.one⟩ @[simp] theorem one_eval (x) : (1 : poly α) x = 1 := rfl /-- Subtraction of polynomials -/ def sub : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.sub pf pg⟩ instance : has_sub (poly α) := ⟨poly.sub⟩ @[simp] theorem sub_eval : Π (f g x), (f - g : poly α) x = f x - g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Negation of a polynomial -/ def neg (f : poly α) : poly α := 0 - f instance : has_neg (poly α) := ⟨poly.neg⟩ @[simp] theorem neg_eval (f x) : (-f : poly α) x = -f x := show (0-f) x = _, by simp /-- Addition of polynomials -/ def add : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := subst (⟨f, pf⟩ - -⟨g, pg⟩) _ (λx, show f x - (0 - g x) = f x + g x, by simp) instance : has_add (poly α) := ⟨poly.add⟩ @[simp] theorem add_eval : Π (f g x), (f + g : poly α) x = f x + g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl /-- Multiplication of polynomials -/ def mul : poly α → poly α → poly α | ⟨f, pf⟩ ⟨g, pg⟩ := ⟨_, is_poly.mul pf pg⟩ instance : has_mul (poly α) := ⟨poly.mul⟩ @[simp] theorem mul_eval : Π (f g x), (f * g : poly α) x = f x * g x | ⟨f, pf⟩ ⟨g, pg⟩ x := rfl instance : comm_ring (poly α) := by refine_struct { add := ((+) : poly α → poly α → poly α), zero := 0, neg := (has_neg.neg : poly α → poly α), mul := ((*)), one := 1, sub := (has_sub.sub), npow := @npow_rec _ ⟨(1 : poly α)⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨(0 : poly α)⟩ ⟨(+)⟩, zsmul := @zsmul_rec _ ⟨(0 : poly α)⟩ ⟨(+)⟩ ⟨neg⟩ }; intros; try { refl }; refine ext (λ _, _); simp [sub_eq_add_neg, mul_add, mul_left_comm, mul_comm, add_comm, add_assoc] lemma induction {C : poly α → Prop} (H1 : ∀i, C (proj i)) (H2 : ∀n, C (const n)) (H3 : ∀f g, C f → C g → C (f - g)) (H4 : ∀f g, C f → C g → C (f * g)) (f : poly α) : C f := begin cases f with f pf, induction pf with i n f g pf pg ihf ihg f g pf pg ihf ihg, apply H1, apply H2, apply H3 _ _ ihf ihg, apply H4 _ _ ihf ihg end /-- The sum of squares of a list of polynomials. This is relevant for Diophantine equations, because it means that a list of equations can be encoded as a single equation: `x = 0 ∧ y = 0 ∧ z = 0` is equivalent to `x^2 + y^2 + z^2 = 0`. -/ def sumsq : list (poly α) → poly α | [] := 0 | (p::ps) := p*p + sumsq ps theorem sumsq_nonneg (x) : ∀ l, 0 ≤ sumsq l x | [] := le_refl 0 | (p::ps) := by rw sumsq; simp [-add_comm]; exact add_nonneg (mul_self_nonneg _) (sumsq_nonneg ps) theorem sumsq_eq_zero (x) : ∀ l, sumsq l x = 0 ↔ list_all (λa : poly α, a x = 0) l | [] := eq_self_iff_true _ | (p::ps) := by rw [list_all_cons, ← sumsq_eq_zero ps]; rw sumsq; simp [-add_comm]; exact ⟨λ(h : p x * p x + sumsq ps x = 0), have p x = 0, from eq_zero_of_mul_self_eq_zero $ le_antisymm (by rw ← h; have t := add_le_add_left (sumsq_nonneg x ps) (p x * p x); rwa [add_zero] at t) (mul_self_nonneg _), ⟨this, by simp [this] at h; exact h⟩, λ⟨h1, h2⟩, by rw [h1, h2]; refl⟩ end /-- Map the index set of variables, replacing `x_i` with `x_(f i)`. -/ def remap {α β} (f : α → β) (g : poly α) : poly β := ⟨λv, g $ v ∘ f, g.induction (λi, by simp; apply is_poly.proj) (λn, by simp; apply is_poly.const) (λf g pf pg, by simp; apply is_poly.sub pf pg) (λf g pf pg, by simp; apply is_poly.mul pf pg)⟩ @[simp] theorem remap_eval {α β} (f : α → β) (g : poly α) (v) : remap f g v = g (v ∘ f) := rfl end poly namespace sum /-- combine two functions into a function on the disjoint union -/ def join {α β γ} (f : α → γ) (g : β → γ) : α ⊕ β → γ := by {refine sum.rec _ _, exacts [f, g]} end sum local infixr ` ⊗ `:65 := sum.join open sum namespace option /-- Functions from `option` can be combined similarly to `vector.cons` -/ def cons {α β} (a : β) (v : α → β) : option α → β := by {refine option.rec _ _, exacts [a, v]} notation a :: b := cons a b @[simp] theorem cons_head_tail {α β} (v : option α → β) : v none :: v ∘ some = v := funext $ λo, by cases o; refl end option /- dioph -/ /-- A set `S ⊆ ℕ^α` is Diophantine if there exists a polynomial on `α ⊕ β` such that `v ∈ S` iff there exists `t : ℕ^β` with `p (v, t) = 0`. -/ def dioph {α : Type u} (S : set (α → ℕ)) : Prop := ∃ {β : Type u} (p : poly (α ⊕ β)), ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0 namespace dioph section variables {α β γ : Type u} theorem ext {S S' : set (α → ℕ)} (d : dioph S) (H : ∀v, S v ↔ S' v) : dioph S' := eq.rec d $ show S = S', from set.ext H theorem of_no_dummies (S : set (α → ℕ)) (p : poly α) (h : ∀ (v : α → ℕ), S v ↔ p v = 0) : dioph S := ⟨ulift empty, p.remap inl, λv, (h v).trans ⟨λh, ⟨λt, empty.rec _ t.down, by simp; rw [ show (v ⊗ λt:ulift empty, empty.rec _ t.down) ∘ inl = v, from rfl, h]⟩, λ⟨t, ht⟩, by simp at ht; rwa [show (v ⊗ t) ∘ inl = v, from rfl] at ht⟩⟩ lemma inject_dummies_lem (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (v : α → ℕ) : (∃t, p (v ⊗ t) = 0) ↔ (∃t, p.remap (inl ⊗ (inr ∘ f)) (v ⊗ t) = 0) := begin simp, refine ⟨λt, _, λt, _⟩; cases t with t ht, { have : (v ⊗ (0 :: t) ∘ g) ∘ (inl ⊗ inr ∘ f) = v ⊗ t := funext (λs, by cases s with a b; dsimp [join, (∘)]; try {rw inv}; refl), exact ⟨(0 :: t) ∘ g, by rwa this⟩ }, { have : v ⊗ t ∘ f = (v ⊗ t) ∘ (inl ⊗ inr ∘ f) := funext (λs, by cases s with a b; refl), exact ⟨t ∘ f, by rwa this⟩ } end theorem inject_dummies {S : set (α → ℕ)} (f : β → γ) (g : γ → option β) (inv : ∀ x, g (f x) = some x) (p : poly (α ⊕ β)) (h : ∀ (v : α → ℕ), S v ↔ ∃t, p (v ⊗ t) = 0) : ∃ q : poly (α ⊕ γ), ∀ (v : α → ℕ), S v ↔ ∃t, q (v ⊗ t) = 0 := ⟨p.remap (inl ⊗ (inr ∘ f)), λv, (h v).trans $ inject_dummies_lem f g inv _ _⟩ theorem reindex_dioph {S : set (α → ℕ)} : Π (d : dioph S) (f : α → β), dioph (λv, S (v ∘ f)) | ⟨γ, p, pe⟩ f := ⟨γ, p.remap ((inl ∘ f) ⊗ inr), λv, (pe _).trans $ exists_congr $ λt, suffices v ∘ f ⊗ t = (v ⊗ t) ∘ (inl ∘ f ⊗ inr), by simp [this], funext $ λs, by cases s with a b; refl⟩ theorem dioph_list_all (l) (d : list_all dioph l) : dioph (λv, list_all (λS : set (α → ℕ), S v) l) := suffices ∃ β (pl : list (poly (α ⊕ β))), ∀ v, list_all (λS : set _, S v) l ↔ ∃t, list_all (λp : poly (α ⊕ β), p (v ⊗ t) = 0) pl, from let ⟨β, pl, h⟩ := this in ⟨β, poly.sumsq pl, λv, (h v).trans $ exists_congr $ λt, (poly.sumsq_eq_zero _ _).symm⟩, begin induction l with S l IH, exact ⟨ulift empty, [], λv, by simp; exact ⟨λ⟨t⟩, empty.rec _ t, trivial⟩⟩, simp at d, exact let ⟨⟨β, p, pe⟩, dl⟩ := d, ⟨γ, pl, ple⟩ := IH dl in ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) :: pl.map (λq, q.remap (inl ⊗ (inr ∘ inr))), λv, by simp; exact iff.trans (and_congr (pe v) (ple v)) ⟨λ⟨⟨m, hm⟩, ⟨n, hn⟩⟩, ⟨m ⊗ n, by rw [ show (v ⊗ m ⊗ n) ∘ (inl ⊗ inr ∘ inl) = v ⊗ m, from funext $ λs, by cases s with a b; refl]; exact hm, by { refine list_all.imp (λq hq, _) hn, dsimp [(∘)], rw [show (λ (x : α ⊕ γ), (v ⊗ m ⊗ n) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ n, from funext $ λs, by cases s with a b; refl]; exact hq }⟩, λ⟨t, hl, hr⟩, ⟨⟨t ∘ inl, by rwa [ show (v ⊗ t) ∘ (inl ⊗ inr ∘ inl) = v ⊗ t ∘ inl, from funext $ λs, by cases s with a b; refl] at hl⟩, ⟨t ∘ inr, by { refine list_all.imp (λq hq, _) hr, dsimp [(∘)] at hq, rwa [show (λ (x : α ⊕ γ), (v ⊗ t) ((inl ⊗ λ (x : γ), inr (inr x)) x)) = v ⊗ t ∘ inr, from funext $ λs, by cases s with a b; refl] at hq }⟩⟩⟩⟩ end theorem and_dioph {S S' : set (α → ℕ)} (d : dioph S) (d' : dioph S') : dioph (λv, S v ∧ S' v) := dioph_list_all [S, S'] ⟨d, d'⟩ theorem or_dioph {S S' : set (α → ℕ)} : ∀ (d : dioph S) (d' : dioph S'), dioph (λv, S v ∨ S' v) | ⟨β, p, pe⟩ ⟨γ, q, qe⟩ := ⟨β ⊕ γ, p.remap (inl ⊗ inr ∘ inl) * q.remap (inl ⊗ inr ∘ inr), λv, begin refine iff.trans (or_congr ((pe v).trans _) ((qe v).trans _)) (exists_or_distrib.symm.trans (exists_congr $ λt, (@mul_eq_zero _ _ _ (p ((v ⊗ t) ∘ (inl ⊗ inr ∘ inl))) (q ((v ⊗ t) ∘ (inl ⊗ inr ∘ inr)))).symm)), exact inject_dummies_lem _ (some ⊗ (λ_, none)) (λx, rfl) _ _, exact inject_dummies_lem _ ((λ_, none) ⊗ some) (λx, rfl) _ _, end⟩ /-- A partial function is Diophantine if its graph is Diophantine. -/ def dioph_pfun (f : (α → ℕ) →. ℕ) := dioph (λv : option α → ℕ, f.graph (v ∘ some, v none)) /-- A function is Diophantine if its graph is Diophantine. -/ def dioph_fn (f : (α → ℕ) → ℕ) := dioph (λv : option α → ℕ, f (v ∘ some) = v none) theorem reindex_dioph_fn {f : (α → ℕ) → ℕ} (d : dioph_fn f) (g : α → β) : dioph_fn (λv, f (v ∘ g)) := reindex_dioph d (functor.map g) theorem ex_dioph {S : set (α ⊕ β → ℕ)} : dioph S → dioph (λv, ∃x, S (v ⊗ x)) | ⟨γ, p, pe⟩ := ⟨β ⊕ γ, p.remap ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x ⊗ t, by simp; rw [ show (v ⊗ x ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ x) ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t ∘ inl, (pe _).2 ⟨t ∘ inr, by simp at ht; rwa [ show (v ⊗ t) ∘ ((inl ⊗ inr ∘ inl) ⊗ inr ∘ inr) = (v ⊗ t ∘ inl) ⊗ t ∘ inr, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem ex1_dioph {S : set (option α → ℕ)} : dioph S → dioph (λv, ∃x, S (x :: v)) | ⟨β, p, pe⟩ := ⟨option β, p.remap (inr none :: inl ⊗ inr ∘ some), λv, ⟨λ⟨x, hx⟩, let ⟨t, ht⟩ := (pe _).1 hx in ⟨x :: t, by simp; rw [ show (v ⊗ x :: t) ∘ (inr none :: inl ⊗ inr ∘ some) = x :: v ⊗ t, from funext $ λs, by cases s with a b; try {cases a}; refl]; exact ht⟩, λ⟨t, ht⟩, ⟨t none, (pe _).2 ⟨t ∘ some, by simp at ht; rwa [ show (v ⊗ t) ∘ (inr none :: inl ⊗ inr ∘ some) = t none :: v ⊗ t ∘ some, from funext $ λs, by cases s with a b; try {cases a}; refl] at ht⟩⟩⟩⟩ theorem dom_dioph {f : (α → ℕ) →. ℕ} (d : dioph_pfun f) : dioph f.dom := cast (congr_arg dioph $ set.ext $ λv, (pfun.dom_iff_graph _ _).symm) (ex1_dioph d) theorem dioph_fn_iff_pfun (f : (α → ℕ) → ℕ) : dioph_fn f = @dioph_pfun α f := by refine congr_arg dioph (set.ext $ λv, _); exact pfun.lift_graph.symm theorem abs_poly_dioph (p : poly α) : dioph_fn (λv, (p v).nat_abs) := by refine of_no_dummies _ ((p.remap some - poly.proj none) * (p.remap some + poly.proj none)) (λv, _); apply int.eq_nat_abs_iff_mul theorem proj_dioph (i : α) : dioph_fn (λv, v i) := abs_poly_dioph (poly.proj i) theorem dioph_pfun_comp1 {S : set (option α → ℕ)} (d : dioph S) {f} (df : dioph_pfun f) : dioph (λv : α → ℕ, ∃ h : f.dom v, S (f.fn v h :: v)) := ext (ex1_dioph (and_dioph d df)) $ λv, ⟨λ⟨x, hS, (h: Exists _)⟩, by rw [show (x :: v) ∘ some = v, from funext $ λs, rfl] at h; cases h with hf h; refine ⟨hf, _⟩; rw [pfun.fn, h]; exact hS, λ⟨x, hS⟩, ⟨f.fn v x, hS, show Exists _, by rw [show (f.fn v x :: v) ∘ some = v, from funext $ λs, rfl]; exact ⟨x, rfl⟩⟩⟩ theorem dioph_fn_comp1 {S : set (option α → ℕ)} (d : dioph S) {f : (α → ℕ) → ℕ} (df : dioph_fn f) : dioph (λv : α → ℕ, S (f v :: v)) := ext (dioph_pfun_comp1 d (cast (dioph_fn_iff_pfun f) df)) $ λv, ⟨λ⟨_, h⟩, h, λh, ⟨trivial, h⟩⟩ end section variables {α β γ : Type} open vector3 open_locale vector3 theorem dioph_fn_vec_comp1 {n} {S : set (vector3 ℕ (succ n))} (d : dioph S) {f : (vector3 ℕ n) → ℕ} (df : dioph_fn f) : dioph (λv : vector3 ℕ n, S (cons (f v) v)) := ext (dioph_fn_comp1 (reindex_dioph d (none :: some)) df) $ λv, by rw [ show option.cons (f v) v ∘ (cons none some) = f v :: v, from funext $ λs, by cases s with a b; refl] theorem vec_ex1_dioph (n) {S : set (vector3 ℕ (succ n))} (d : dioph S) : dioph (λv : vector3 ℕ n, ∃x, S (x :: v)) := ext (ex1_dioph $ reindex_dioph d (none :: some)) $ λv, exists_congr $ λx, by rw [ show (option.cons x v) ∘ (cons none some) = x :: v, from funext $ λs, by cases s with a b; refl] theorem dioph_fn_vec {n} (f : vector3 ℕ n → ℕ) : dioph_fn f ↔ dioph (λv : vector3 ℕ (succ n), f (v ∘ fs) = v fz) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_pfun_vec {n} (f : vector3 ℕ n →. ℕ) : dioph_pfun f ↔ dioph (λv : vector3 ℕ (succ n), f.graph (v ∘ fs, v fz)) := ⟨λh, reindex_dioph h (fz :: fs), λh, reindex_dioph h (none :: some)⟩ theorem dioph_fn_compn {α : Type} : ∀ {n} {S : set (α ⊕ fin2 n → ℕ)} (d : dioph S) {f : vector3 ((α → ℕ) → ℕ) n} (df : vector_allp dioph_fn f), dioph (λv : α → ℕ, S (v ⊗ λi, f i v)) | 0 S d f := λdf, ext (reindex_dioph d (id ⊗ fin2.elim0)) $ λv, by refine eq.to_iff (congr_arg S $ funext $ λs, _); {cases s with a b, refl, cases b} | (succ n) S d f := f.cons_elim $ λf fl, by simp; exact λ df dfl, have dioph (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)), from ext (dioph_fn_comp1 (reindex_dioph d (some ∘ inl ⊗ none :: some ∘ inr)) (reindex_dioph_fn df inl)) $ λv, by {refine eq.to_iff (congr_arg S $ funext $ λs, _); cases s with a b, refl, cases b; refl}, have dioph (λv, S (v ⊗ f v :: λ (i : fin2 n), fl i v)), from @dioph_fn_compn n (λv, S (v ∘ inl ⊗ f (v ∘ inl) :: v ∘ inr)) this _ dfl, ext this $ λv, by rw [ show cons (f v) (λ (i : fin2 n), fl i v) = λ (i : fin2 (succ n)), (f :: fl) i v, from funext $ λs, by cases s with a b; refl] theorem dioph_comp {n} {S : set (vector3 ℕ n)} (d : dioph S) (f : vector3 ((α → ℕ) → ℕ) n) (df : vector_allp dioph_fn f) : dioph (λv, S (λi, f i v)) := dioph_fn_compn (reindex_dioph d inr) df theorem dioph_fn_comp {n} {f : vector3 ℕ n → ℕ} (df : dioph_fn f) (g : vector3 ((α → ℕ) → ℕ) n) (dg : vector_allp dioph_fn g) : dioph_fn (λv, f (λi, g i v)) := dioph_comp ((dioph_fn_vec _).1 df) ((λv, v none) :: λi v, g i (v ∘ some)) $ by simp; exact ⟨proj_dioph none, (vector_allp_iff_forall _ _).2 $ λi, reindex_dioph_fn ((vector_allp_iff_forall _ _).1 dg _) _⟩ localized "notation x ` D∧ `:35 y := dioph.and_dioph x y" in dioph localized "notation x ` D∨ `:35 y := dioph.or_dioph x y" in dioph localized "notation `D∃`:30 := dioph.vec_ex1_dioph" in dioph localized "prefix `&`:max := fin2.of_nat'" in dioph theorem proj_dioph_of_nat {n : ℕ} (m : ℕ) [is_lt m n] : dioph_fn (λv : vector3 ℕ n, v &m) := proj_dioph &m localized "prefix `D&`:100 := dioph.proj_dioph_of_nat" in dioph theorem const_dioph (n : ℕ) : dioph_fn (const (α → ℕ) n) := abs_poly_dioph (poly.const n) localized "prefix `D.`:100 := dioph.const_dioph" in dioph variables {f g : (α → ℕ) → ℕ} (df : dioph_fn f) (dg : dioph_fn g) include df dg theorem dioph_comp2 {S : ℕ → ℕ → Prop} (d : dioph (λv:vector3 ℕ 2, S (v &0) (v &1))) : dioph (λv, S (f v) (g v)) := dioph_comp d [f, g] (by exact ⟨df, dg⟩) theorem dioph_fn_comp2 {h : ℕ → ℕ → ℕ} (d : dioph_fn (λv:vector3 ℕ 2, h (v &0) (v &1))) : dioph_fn (λv, h (f v) (g v)) := dioph_fn_comp d [f, g] (by exact ⟨df, dg⟩) theorem eq_dioph : dioph (λv, f v = g v) := dioph_comp2 df dg $ of_no_dummies _ (poly.proj &0 - poly.proj &1) (λv, (int.coe_nat_eq_coe_nat_iff _ _).symm.trans ⟨@sub_eq_zero_of_eq ℤ _ (v &0) (v &1), eq_of_sub_eq_zero⟩) localized "infix ` D= `:50 := dioph.eq_dioph" in dioph theorem add_dioph : dioph_fn (λv, f v + g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 + poly.proj &1) localized "infix ` D+ `:80 := dioph.add_dioph" in dioph theorem mul_dioph : dioph_fn (λv, f v * g v) := dioph_fn_comp2 df dg $ abs_poly_dioph (poly.proj &0 * poly.proj &1) localized "infix ` D* `:90 := dioph.mul_dioph" in dioph theorem le_dioph : dioph (λv, f v ≤ g v) := dioph_comp2 df dg $ ext (D∃2 $ D&1 D+ D&0 D= D&2) (λv, ⟨λ⟨x, hx⟩, le.intro hx, le.dest⟩) localized "infix ` D≤ `:50 := dioph.le_dioph" in dioph theorem lt_dioph : dioph (λv, f v < g v) := df D+ (D. 1) D≤ dg localized "infix ` D< `:50 := dioph.lt_dioph" in dioph theorem ne_dioph : dioph (λv, f v ≠ g v) := ext (df D< dg D∨ dg D< df) $ λv, ne_iff_lt_or_gt.symm localized "infix ` D≠ `:50 := dioph.ne_dioph" in dioph theorem sub_dioph : dioph_fn (λv, f v - g v) := dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext (D&1 D= D&0 D+ D&2 D∨ D&1 D≤ D&2 D∧ D&0 D= D.0) $ (vector_all_iff_forall _).1 $ λx y z, show (y = x + z ∨ y ≤ z ∧ x = 0) ↔ y - z = x, from ⟨λo, begin rcases o with ae | ⟨yz, x0⟩, { rw [ae, add_tsub_cancel_right] }, { rw [x0, tsub_eq_zero_iff_le.mpr yz] } end, λh, begin subst x, cases le_total y z with yz zy, { exact or.inr ⟨yz, tsub_eq_zero_iff_le.mpr yz⟩ }, { exact or.inl (tsub_add_cancel_of_le zy).symm }, end⟩ localized "infix ` D- `:80 := dioph.sub_dioph" in dioph theorem dvd_dioph : dioph (λv, f v ∣ g v) := dioph_comp (D∃2 $ D&2 D= D&1 D* D&0) [f, g] (by exact ⟨df, dg⟩) localized "infix ` D∣ `:50 := dioph.dvd_dioph" in dioph theorem mod_dioph : dioph_fn (λv, f v % g v) := have dioph (λv : vector3 ℕ 3, (v &2 = 0 ∨ v &0 < v &2) ∧ ∃ (x : ℕ), v &0 + v &2 * x = v &1), from (D&2 D= D.0 D∨ D&0 D< D&2) D∧ (D∃3 $ D&1 D+ D&3 D* D&0 D= D&2), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show ((y = 0 ∨ z < y) ∧ ∃ c, z + y * c = x) ↔ x % y = z, from ⟨λ⟨h, c, hc⟩, begin rw ← hc; simp; cases h with x0 hl, rw [x0, mod_zero], exact mod_eq_of_lt hl end, λe, by rw ← e; exact ⟨or_iff_not_imp_left.2 $ λh, mod_lt _ (nat.pos_of_ne_zero h), x / y, mod_add_div _ _⟩⟩ localized "infix ` D% `:80 := dioph.mod_dioph" in dioph theorem modeq_dioph {h : (α → ℕ) → ℕ} (dh : dioph_fn h) : dioph (λv, f v ≡ g v [MOD h v]) := df D% dh D= dg D% dh localized "notation `D≡` := dioph.modeq_dioph" in dioph theorem div_dioph : dioph_fn (λv, f v / g v) := have dioph (λv : vector3 ℕ 3, v &2 = 0 ∧ v &0 = 0 ∨ v &0 * v &2 ≤ v &1 ∧ v &1 < (v &0 + 1) * v &2), from (D&2 D= D.0 D∧ D&0 D= D.0) D∨ D&0 D* D&2 D≤ D&1 D∧ D&1 D< (D&0 D+ D.1) D* D&2, dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ ext this $ (vector_all_iff_forall _).1 $ λz x y, show y = 0 ∧ z = 0 ∨ z * y ≤ x ∧ x < (z + 1) * y ↔ x / y = z, by refine iff.trans _ eq_comm; exact y.eq_zero_or_pos.elim (λy0, by rw [y0, nat.div_zero]; exact ⟨λo, (o.resolve_right $ λ⟨_, h2⟩, nat.not_lt_zero _ h2).right, λz0, or.inl ⟨rfl, z0⟩⟩) (λypos, iff.trans ⟨λo, o.resolve_left $ λ⟨h1, _⟩, ne_of_gt ypos h1, or.inr⟩ (le_antisymm_iff.trans $ and_congr (nat.le_div_iff_mul_le _ _ ypos) $ iff.trans ⟨lt_succ_of_le, le_of_lt_succ⟩ (div_lt_iff_lt_mul _ _ ypos)).symm) localized "infix ` D/ `:80 := dioph.div_dioph" in dioph omit df dg open pell theorem pell_dioph : dioph (λv:vector3 ℕ 4, ∃ h : 1 < v &0, xn h (v &1) = v &2 ∧ yn h (v &1) = v &3) := have dioph {v : vector3 ℕ 4 | 1 < v &0 ∧ v &1 ≤ v &3 ∧ (v &2 = 1 ∧ v &3 = 0 ∨ ∃ (u w s t b : ℕ), v &2 * v &2 - (v &0 * v &0 - 1) * v &3 * v &3 = 1 ∧ u * u - (v &0 * v &0 - 1) * w * w = 1 ∧ s * s - (b * b - 1) * t * t = 1 ∧ 1 < b ∧ (b ≡ 1 [MOD 4 * v &3]) ∧ (b ≡ v &0 [MOD u]) ∧ 0 < w ∧ v &3 * v &3 ∣ w ∧ (s ≡ v &2 [MOD u]) ∧ (t ≡ v &1 [MOD 4 * v &3]))}, from D.1 D< D&0 D∧ D&1 D≤ D&3 D∧ ((D&2 D= D.1 D∧ D&3 D= D.0) D∨ (D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D&7 D* D&7 D- (D&5 D* D&5 D- D.1) D* D&8 D* D&8 D= D.1 D∧ D&4 D* D&4 D- (D&5 D* D&5 D- D.1) D* D&3 D* D&3 D= D.1 D∧ D&2 D* D&2 D- (D&0 D* D&0 D- D.1) D* D&1 D* D&1 D= D.1 D∧ D.1 D< D&0 D∧ (D≡ (D&0) (D.1) (D.4 D* D&8)) D∧ (D≡ (D&0) (D&5) D&4) D∧ D.0 D< D&3 D∧ D&8 D* D&8 D∣ D&3 D∧ (D≡ (D&2) (D&7) D&4) D∧ (D≡ (D&1) (D&6) (D.4 D* D&8)))), dioph.ext this $ λv, matiyasevic.symm theorem xn_dioph : dioph_pfun (λv:vector3 ℕ 2, ⟨1 < v &0, λh, xn h (v &1)⟩) := have dioph (λv:vector3 ℕ 3, ∃ y, ∃ h : 1 < v &1, xn h (v &2) = v &0 ∧ yn h (v &2) = y), from let D_pell := @reindex_dioph _ (fin2 4) _ pell_dioph [&2, &3, &1, &0] in D∃3 D_pell, (dioph_pfun_vec _).2 $ dioph.ext this $ λv, ⟨λ⟨y, h, xe, ye⟩, ⟨h, xe⟩, λ⟨h, xe⟩, ⟨_, h, xe, rfl⟩⟩ include df dg /-- A version of **Matiyasevic's theorem** -/ theorem pow_dioph : dioph_fn (λv, f v ^ g v) := have dioph {v : vector3 ℕ 3 | v &2 = 0 ∧ v &0 = 1 ∨ 0 < v &2 ∧ (v &1 = 0 ∧ v &0 = 0 ∨ 0 < v &1 ∧ ∃ (w a t z x y : ℕ), (∃ (a1 : 1 < a), xn a1 (v &2) = x ∧ yn a1 (v &2) = y) ∧ (x ≡ y * (a - v &1) + v &0 [MOD t]) ∧ 2 * a * v &1 = t + (v &1 * v &1 + 1) ∧ v &0 < t ∧ v &1 ≤ w ∧ v &2 ≤ w ∧ a * a - ((w + 1) * (w + 1) - 1) * (w * z) * (w * z) = 1)}, from let D_pell := @reindex_dioph _ (fin2 9) _ pell_dioph [&4, &8, &1, &0] in (D&2 D= D.0 D∧ D&0 D= D.1) D∨ (D.0 D< D&2 D∧ ((D&1 D= D.0 D∧ D&0 D= D.0) D∨ (D.0 D< D&1 D∧ (D∃3 $ D∃4 $ D∃5 $ D∃6 $ D∃7 $ D∃8 $ D_pell D∧ (D≡ (D&1) (D&0 D* (D&4 D- D&7) D+ D&6) (D&3)) D∧ D.2 D* D&4 D* D&7 D= D&3 D+ (D&7 D* D&7 D+ D.1) D∧ D&6 D< D&3 D∧ D&7 D≤ D&5 D∧ D&8 D≤ D&5 D∧ D&4 D* D&4 D- ((D&5 D+ D.1) D* (D&5 D+ D.1) D- D.1) D* (D&5 D* D&2) D* (D&5 D* D&2) D= D.1)))), dioph_fn_comp2 df dg $ (dioph_fn_vec _).2 $ dioph.ext this $ λv, iff.symm $ eq_pow_of_pell.trans $ or_congr iff.rfl $ and_congr iff.rfl $ or_congr iff.rfl $ and_congr iff.rfl $ ⟨λ⟨w, a, t, z, a1, h⟩, ⟨w, a, t, z, _, _, ⟨a1, rfl, rfl⟩, h⟩, λ⟨w, a, t, z, ._, ._, ⟨a1, rfl, rfl⟩, h⟩, ⟨w, a, t, z, a1, h⟩⟩ end end dioph
program Write; begin ; writeln('It'
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.measure.giry_monad import dynamics.ergodic.measure_preserving import measure_theory.integral.set_integral /-! # The product measure In this file we define and prove properties about the binary product measure. If `α` and `β` have σ-finite measures `μ` resp. `ν` then `α × β` can be equipped with a σ-finite measure `μ.prod ν` that satisfies `(μ.prod ν) s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ`. We also have `(μ.prod ν) (s ×ˢ t) = μ s * ν t`, i.e. the measure of a rectangle is the product of the measures of the sides. We also prove Tonelli's theorem and Fubini's theorem. ## Main definition * `measure_theory.measure.prod`: The product of two measures. ## Main results * `measure_theory.measure.prod_apply` states `μ.prod ν s = ∫⁻ x, ν {y | (x, y) ∈ s} ∂μ` for measurable `s`. `measure_theory.measure.prod_apply_symm` is the reversed version. * `measure_theory.measure.prod_prod` states `μ.prod ν (s ×ˢ t) = μ s * ν t` for measurable sets `s` and `t`. * `measure_theory.lintegral_prod`: Tonelli's theorem. It states that for a measurable function `α × β → ℝ≥0∞` we have `∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ`. The version for functions `α → β → ℝ≥0∞` is reversed, and called `lintegral_lintegral`. Both versions have a variant with `_symm` appended, where the order of integration is reversed. The lemma `measurable.lintegral_prod_right'` states that the inner integral of the right-hand side is measurable. * `measure_theory.integrable_prod_iff` states that a binary function is integrable iff both * `y ↦ f (x, y)` is integrable for almost every `x`, and * the function `x ↦ ∫ ∥f (x, y)∥ dy` is integrable. * `measure_theory.integral_prod`: Fubini's theorem. It states that for a integrable function `α × β → E` (where `E` is a second countable Banach space) we have `∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ`. This theorem has the same variants as Tonelli's theorem. The lemma `measure_theory.integrable.integral_prod_right` states that the inner integral of the right-hand side is integrable. ## Implementation Notes Many results are proven twice, once for functions in curried form (`α → β → γ`) and one for functions in uncurried form (`α × β → γ`). The former often has an assumption `measurable (uncurry f)`, which could be inconvenient to discharge, but for the latter it is more common that the function has to be given explicitly, since Lean cannot synthesize the function by itself. We name the lemmas about the uncurried form with a prime. Tonelli's theorem and Fubini's theorem have a different naming scheme, since the version for the uncurried version is reversed. ## Tags product measure, Fubini's theorem, Tonelli's theorem, Fubini-Tonelli theorem -/ noncomputable theory open_locale classical topological_space ennreal measure_theory open set function real ennreal open measure_theory measurable_space measure_theory.measure open topological_space (hiding generate_from) open filter (hiding prod_eq map) variables {α α' β β' γ E : Type*} /-- Rectangles formed by π-systems form a π-system. -/ lemma is_pi_system.prod {C : set (set α)} {D : set (set β)} (hC : is_pi_system C) (hD : is_pi_system D) : is_pi_system (image2 (×ˢ) C D) := begin rintro _ ⟨s₁, t₁, hs₁, ht₁, rfl⟩ _ ⟨s₂, t₂, hs₂, ht₂, rfl⟩ hst, rw [prod_inter_prod] at hst ⊢, rw [prod_nonempty_iff] at hst, exact mem_image2_of_mem (hC _ hs₁ _ hs₂ hst.1) (hD _ ht₁ _ ht₂ hst.2) end /-- Rectangles of countably spanning sets are countably spanning. -/ lemma is_countably_spanning.prod {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : is_countably_spanning (image2 (×ˢ) C D) := begin rcases ⟨hC, hD⟩ with ⟨⟨s, h1s, h2s⟩, t, h1t, h2t⟩, refine ⟨λ n, (s n.unpair.1) ×ˢ (t n.unpair.2), λ n, mem_image2_of_mem (h1s _) (h1t _), _⟩, rw [Union_unpair_prod, h2s, h2t, univ_prod_univ] end variables [measurable_space α] [measurable_space α'] [measurable_space β] [measurable_space β'] variables [measurable_space γ] variables {μ : measure α} {ν : measure β} {τ : measure γ} variables [normed_group E] [measurable_space E] /-! ### Measurability Before we define the product measure, we can talk about the measurability of operations on binary functions. We show that if `f` is a binary measurable function, then the function that integrates along one of the variables (using either the Lebesgue or Bochner integral) is measurable. -/ /-- The product of generated σ-algebras is the one generated by rectangles, if both generating sets are countably spanning. -/ lemma generate_from_prod_eq {α β} {C : set (set α)} {D : set (set β)} (hC : is_countably_spanning C) (hD : is_countably_spanning D) : @prod.measurable_space _ _ (generate_from C) (generate_from D) = generate_from (image2 (×ˢ) C D) := begin apply le_antisymm, { refine sup_le _ _; rw [comap_generate_from]; apply generate_from_le; rintro _ ⟨s, hs, rfl⟩, { rcases hD with ⟨t, h1t, h2t⟩, rw [← prod_univ, ← h2t, prod_Union], apply measurable_set.Union, intro n, apply measurable_set_generate_from, exact ⟨s, t n, hs, h1t n, rfl⟩ }, { rcases hC with ⟨t, h1t, h2t⟩, rw [← univ_prod, ← h2t, Union_prod_const], apply measurable_set.Union, rintro n, apply measurable_set_generate_from, exact mem_image2_of_mem (h1t n) hs } }, { apply generate_from_le, rintro _ ⟨s, t, hs, ht, rfl⟩, rw [prod_eq], apply (measurable_fst _).inter (measurable_snd _), { exact measurable_set_generate_from hs }, { exact measurable_set_generate_from ht } } end /-- If `C` and `D` generate the σ-algebras on `α` resp. `β`, then rectangles formed by `C` and `D` generate the σ-algebra on `α × β`. -/ lemma generate_from_eq_prod {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_countably_spanning C) (h2D : is_countably_spanning D) : generate_from (image2 (×ˢ) C D) = prod.measurable_space := by rw [← hC, ← hD, generate_from_prod_eq h2C h2D] /-- The product σ-algebra is generated from boxes, i.e. `s ×ˢ t` for sets `s : set α` and `t : set β`. -/ lemma generate_from_prod : generate_from (image2 (×ˢ) {s : set α | measurable_set s} {t : set β | measurable_set t}) = prod.measurable_space := generate_from_eq_prod generate_from_measurable_set generate_from_measurable_set is_countably_spanning_measurable_set is_countably_spanning_measurable_set /-- Rectangles form a π-system. -/ lemma is_pi_system_prod : is_pi_system (image2 (×ˢ) {s : set α | measurable_set s} {t : set β | measurable_set t}) := is_pi_system_measurable_set.prod is_pi_system_measurable_set /-- If `ν` is a finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. `measurable_measure_prod_mk_left` is strictly more general. -/ lemma measurable_measure_prod_mk_left_finite [is_finite_measure ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin refine induction_on_inter generate_from_prod.symm is_pi_system_prod _ _ _ _ hs, { simp [measurable_zero, const_def] }, { rintro _ ⟨s, t, hs, ht, rfl⟩, simp only [mk_preimage_prod_right_eq_if, measure_if], exact measurable_const.indicator hs }, { intros t ht h2t, simp_rw [preimage_compl, measure_compl (measurable_prod_mk_left ht) (measure_ne_top ν _)], exact h2t.const_sub _ }, { intros f h1f h2f h3f, simp_rw [preimage_Union], have : ∀ b, ν (⋃ i, prod.mk b ⁻¹' f i) = ∑' i, ν (prod.mk b ⁻¹' f i) := λ b, measure_Union (λ i j hij, disjoint.preimage _ (h1f i j hij)) (λ i, measurable_prod_mk_left (h2f i)), simp_rw [this], apply measurable.ennreal_tsum h3f }, end /-- If `ν` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `x ↦ ν { y | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_left [sigma_finite ν] {s : set (α × β)} (hs : measurable_set s) : measurable (λ x, ν (prod.mk x ⁻¹' s)) := begin have : ∀ x, measurable_set (prod.mk x ⁻¹' s) := λ x, measurable_prod_mk_left hs, simp only [← @supr_restrict_spanning_sets _ _ ν, this], apply measurable_supr, intro i, haveI := fact.mk (measure_spanning_sets_lt_top ν i), exact measurable_measure_prod_mk_left_finite hs end /-- If `μ` is a σ-finite measure, and `s ⊆ α × β` is measurable, then `y ↦ μ { x | (x, y) ∈ s }` is a measurable function. -/ lemma measurable_measure_prod_mk_right {μ : measure α} [sigma_finite μ] {s : set (α × β)} (hs : measurable_set s) : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' s)) := measurable_measure_prod_mk_left (measurable_set_swap_iff.mpr hs) lemma measurable.map_prod_mk_left [sigma_finite ν] : measurable (λ x : α, map (prod.mk x) ν) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_left hs], exact measurable_measure_prod_mk_left hs end lemma measurable.map_prod_mk_right {μ : measure α} [sigma_finite μ] : measurable (λ y : β, map (λ x : α, (x, y)) μ) := begin apply measurable_of_measurable_coe, intros s hs, simp_rw [map_apply measurable_prod_mk_right hs], exact measurable_measure_prod_mk_right hs end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_right' [sigma_finite ν] : ∀ {f : α × β → ℝ≥0∞} (hf : measurable f), measurable (λ x, ∫⁻ y, f (x, y) ∂ν) := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], suffices : measurable (λ x, c * ν (prod.mk x ⁻¹' s)), { simpa [lintegral_indicator _ (m hs)] }, exact (measurable_measure_prod_mk_left hs).const_mul _ }, { rintro f g - hf hg h2f h2g, simp_rw [pi.add_apply, lintegral_add (hf.comp m) (hg.comp m)], exact h2f.add h2g }, { intros f hf h2f h3f, have := measurable_supr h3f, have : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), simpa [lintegral_supr (λ n, (hf n).comp m), this] } end /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_right [sigma_finite ν] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ x, ∫⁻ y, f x y ∂ν) := hf.lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. -/ lemma measurable.lintegral_prod_left' [sigma_finite μ] {f : α × β → ℝ≥0∞} (hf : measurable f) : measurable (λ y, ∫⁻ x, f (x, y) ∂μ) := (measurable_swap_iff.mpr hf).lintegral_prod_right' /-- The Lebesgue integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Tonelli's theorem is measurable. This version has the argument `f` in curried form. -/ lemma measurable.lintegral_prod_left [sigma_finite μ] {f : α → β → ℝ≥0∞} (hf : measurable (uncurry f)) : measurable (λ y, ∫⁻ x, f x y ∂μ) := hf.lintegral_prod_left' lemma measurable_set_integrable [sigma_finite ν] [opens_measurable_space E] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable_set { x | integrable (f x) ν } := begin simp_rw [integrable, hf.of_uncurry_left.ae_measurable, true_and], exact measurable_set_lt (measurable.lintegral_prod_right hf.ennnorm) measurable_const end section variables [second_countable_topology E] [normed_space ℝ E] [complete_space E] [borel_space E] /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measurable.integral_prod_right [sigma_finite ν] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable (λ x, ∫ y, f x y ∂ν) := begin let s : ℕ → simple_func (α × β) E := simple_func.approx_on _ hf univ _ (mem_univ 0), let s' : ℕ → α → simple_func β E := λ n x, (s n).comp (prod.mk x) measurable_prod_mk_left, let f' : ℕ → α → E := λ n, {x | integrable (f x) ν}.indicator (λ x, (s' n x).integral ν), have hf' : ∀ n, measurable (f' n), { intro n, refine measurable.indicator _ (measurable_set_integrable hf), have : ∀ x, (s' n x).range.filter (λ x, x ≠ 0) ⊆ (s n).range, { intros x, refine finset.subset.trans (finset.filter_subset _ _) _, intro y, simp_rw [simple_func.mem_range], rintro ⟨z, rfl⟩, exact ⟨(x, z), rfl⟩ }, simp only [simple_func.integral_eq_sum_of_subset (this _)], refine finset.measurable_sum _ (λ x _, _), refine (measurable.ennreal_to_real _).smul_const _, simp only [simple_func.coe_comp, preimage_comp] {single_pass := tt}, apply measurable_measure_prod_mk_left, exact (s n).measurable_set_fiber x }, have h2f' : tendsto f' at_top (𝓝 (λ (x : α), ∫ (y : β), f x y ∂ν)), { rw [tendsto_pi_nhds], intro x, by_cases hfx : integrable (f x) ν, { have : ∀ n, integrable (s' n x) ν, { intro n, apply (hfx.norm.add hfx.norm).mono' (s' n x).measurable.ae_measurable, apply eventually_of_forall, intro y, simp_rw [s', simple_func.coe_comp], exact simple_func.norm_approx_on_zero_le _ _ (x, y) n }, simp only [f', hfx, simple_func.integral_eq_integral _ (this _), indicator_of_mem, mem_set_of_eq], refine tendsto_integral_of_dominated_convergence (λ y, ∥f x y∥ + ∥f x y∥) (λ n, (s' n x).ae_measurable) (hfx.norm.add hfx.norm) _ _, { exact λ n, eventually_of_forall (λ y, simple_func.norm_approx_on_zero_le _ _ (x, y) n) }, { exact eventually_of_forall (λ y, simple_func.tendsto_approx_on _ _ (by simp)) } }, { simpa [f', hfx, integral_undef] using @tendsto_const_nhds _ _ _ (0 : E) _, } }, exact measurable_of_tendsto_metric hf' h2f' end /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is measurable. -/ lemma measurable.integral_prod_right' [sigma_finite ν] ⦃f : α × β → E⦄ (hf : measurable f) : measurable (λ x, ∫ y, f (x, y) ∂ν) := by { rw [← uncurry_curry f] at hf, exact hf.integral_prod_right } /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. This version has `f` in curried form. -/ lemma measurable.integral_prod_left [sigma_finite μ] ⦃f : α → β → E⦄ (hf : measurable (uncurry f)) : measurable (λ y, ∫ x, f x y ∂μ) := (hf.comp measurable_swap).integral_prod_right' /-- The Bochner integral is measurable. This shows that the integrand of (the right-hand-side of) the symmetric version of Fubini's theorem is measurable. -/ lemma measurable.integral_prod_left' [sigma_finite μ] ⦃f : α × β → E⦄ (hf : measurable f) : measurable (λ y, ∫ x, f (x, y) ∂μ) := (hf.comp measurable_swap).integral_prod_right' end /-! ### The product measure -/ namespace measure_theory namespace measure /-- The binary product of measures. They are defined for arbitrary measures, but we basically prove all properties under the assumption that at least one of them is σ-finite. -/ @[irreducible] protected def prod (μ : measure α) (ν : measure β) : measure (α × β) := bind μ $ λ x : α, map (prod.mk x) ν instance prod.measure_space {α β} [measure_space α] [measure_space β] : measure_space (α × β) := { volume := volume.prod volume } variables {μ ν} [sigma_finite ν] lemma volume_eq_prod (α β) [measure_space α] [measure_space β] : (volume : measure (α × β)) = (volume : measure α).prod (volume : measure β) := rfl lemma prod_apply {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ x, ν (prod.mk x ⁻¹' s) ∂μ := by simp_rw [measure.prod, bind_apply hs measurable.map_prod_mk_left, map_apply measurable_prod_mk_left hs] /-- The product measure of the product of two sets is the product of their measures. Note that we do not need the sets to be measurable. -/ @[simp] lemma prod_prod (s : set α) (t : set β) : μ.prod ν (s ×ˢ t) = μ s * ν t := begin apply le_antisymm, { set ST := (to_measurable μ s) ×ˢ (to_measurable ν t), have hSTm : measurable_set ST := (measurable_set_to_measurable _ _).prod (measurable_set_to_measurable _ _), calc μ.prod ν (s ×ˢ t) ≤ μ.prod ν ST : measure_mono $ set.prod_mono (subset_to_measurable _ _) (subset_to_measurable _ _) ... = μ (to_measurable μ s) * ν (to_measurable ν t) : by simp_rw [prod_apply hSTm, mk_preimage_prod_right_eq_if, measure_if, lintegral_indicator _ (measurable_set_to_measurable _ _), lintegral_const, restrict_apply_univ, mul_comm] ... = μ s * ν t : by rw [measure_to_measurable, measure_to_measurable] }, { /- Formalization is based on https://mathoverflow.net/a/254134/136589 -/ set ST := to_measurable (μ.prod ν) (s ×ˢ t), have hSTm : measurable_set ST := measurable_set_to_measurable _ _, have hST : s ×ˢ t ⊆ ST := subset_to_measurable _ _, set f : α → ℝ≥0∞ := λ x, ν (prod.mk x ⁻¹' ST), have hfm : measurable f := measurable_measure_prod_mk_left hSTm, set s' : set α := {x | ν t ≤ f x}, have hss' : s ⊆ s' := λ x hx, measure_mono (λ y hy, hST $ mk_mem_prod hx hy), calc μ s * ν t ≤ μ s' * ν t : mul_le_mul_right' (measure_mono hss') _ ... = ∫⁻ x in s', ν t ∂μ : by rw [set_lintegral_const, mul_comm] ... ≤ ∫⁻ x in s', f x ∂μ : set_lintegral_mono measurable_const hfm (λ x, id) ... ≤ ∫⁻ x, f x ∂μ : lintegral_mono' restrict_le_self le_rfl ... = μ.prod ν ST : (prod_apply hSTm).symm ... = μ.prod ν (s ×ˢ t) : measure_to_measurable _ } end lemma ae_measure_lt_top {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) : ∀ᵐ x ∂μ, ν (prod.mk x ⁻¹' s) < ∞ := by { simp_rw [prod_apply hs] at h2s, refine ae_lt_top (measurable_measure_prod_mk_left hs) h2s } lemma integrable_measure_prod_mk_left {s : set (α × β)} (hs : measurable_set s) (h2s : (μ.prod ν) s ≠ ∞) : integrable (λ x, (ν (prod.mk x ⁻¹' s)).to_real) μ := begin refine ⟨(measurable_measure_prod_mk_left hs).ennreal_to_real.ae_measurable, _⟩, simp_rw [has_finite_integral, ennnorm_eq_of_real to_real_nonneg], convert h2s.lt_top using 1, simp_rw [prod_apply hs], apply lintegral_congr_ae, refine (ae_measure_lt_top hs h2s).mp _, apply eventually_of_forall, intros x hx, rw [lt_top_iff_ne_top] at hx, simp [of_real_to_real, hx], end /-- Note: the assumption `hs` cannot be dropped. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_prod_null {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = 0 ↔ (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := by simp_rw [prod_apply hs, lintegral_eq_zero_iff (measurable_measure_prod_mk_left hs)] /-- Note: the converse is not true without assuming that `s` is measurable. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma measure_ae_null_of_prod_null {s : set (α × β)} (h : μ.prod ν s = 0) : (λ x, ν (prod.mk x ⁻¹' s)) =ᵐ[μ] 0 := begin obtain ⟨t, hst, mt, ht⟩ := exists_measurable_superset_of_null h, simp_rw [measure_prod_null mt] at ht, rw [eventually_le_antisymm_iff], exact ⟨eventually_le.trans_eq (eventually_of_forall $ λ x, (measure_mono (preimage_mono hst) : _)) ht, eventually_of_forall $ λ x, zero_le _⟩ end /-- Note: the converse is not true. For a counterexample, see Walter Rudin *Real and Complex Analysis*, example (c) in section 8.9. -/ lemma ae_ae_of_ae_prod {p : α × β → Prop} (h : ∀ᵐ z ∂μ.prod ν, p z) : ∀ᵐ x ∂ μ, ∀ᵐ y ∂ ν, p (x, y) := measure_ae_null_of_prod_null h /-- `μ.prod ν` has finite spanning sets in rectangles of finite spanning sets. -/ def finite_spanning_sets_in.prod {ν : measure β} {C : set (set α)} {D : set (set β)} (hμ : μ.finite_spanning_sets_in C) (hν : ν.finite_spanning_sets_in D) : (μ.prod ν).finite_spanning_sets_in (image2 (×ˢ) C D) := begin haveI := hν.sigma_finite, refine ⟨λ n, hμ.set n.unpair.1 ×ˢ hν.set n.unpair.2, λ n, mem_image2_of_mem (hμ.set_mem _) (hν.set_mem _), λ n, _, _⟩, { rw [prod_prod], exact mul_lt_top (hμ.finite _).ne (hν.finite _).ne }, { simp_rw [Union_unpair_prod, hμ.spanning, hν.spanning, univ_prod_univ] } end lemma prod_fst_absolutely_continuous : map prod.fst (μ.prod ν) ≪ μ := begin refine absolutely_continuous.mk (λ s hs h2s, _), rw [map_apply measurable_fst hs, ← prod_univ, prod_prod, h2s, zero_mul], end lemma prod_snd_absolutely_continuous : map prod.snd (μ.prod ν) ≪ ν := begin refine absolutely_continuous.mk (λ s hs h2s, _), rw [map_apply measurable_snd hs, ← univ_prod, prod_prod, h2s, mul_zero] end variables [sigma_finite μ] instance prod.sigma_finite : sigma_finite (μ.prod ν) := (μ.to_finite_spanning_sets_in.prod ν.to_finite_spanning_sets_in).sigma_finite /-- A measure on a product space equals the product measure if they are equal on rectangles with as sides sets that generate the corresponding σ-algebras. -/ lemma prod_eq_generate_from {μ : measure α} {ν : measure β} {C : set (set α)} {D : set (set β)} (hC : generate_from C = ‹_›) (hD : generate_from D = ‹_›) (h2C : is_pi_system C) (h2D : is_pi_system D) (h3C : μ.finite_spanning_sets_in C) (h3D : ν.finite_spanning_sets_in D) {μν : measure (α × β)} (h₁ : ∀ (s ∈ C) (t ∈ D), μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := begin refine (h3C.prod h3D).ext (generate_from_eq_prod hC hD h3C.is_countably_spanning h3D.is_countably_spanning).symm (h2C.prod h2D) _, { rintro _ ⟨s, t, hs, ht, rfl⟩, haveI := h3D.sigma_finite, rw [h₁ s hs t ht, prod_prod] } end /-- A measure on a product space equals the product measure if they are equal on rectangles. -/ lemma prod_eq {μν : measure (α × β)} (h : ∀ s t, measurable_set s → measurable_set t → μν (s ×ˢ t) = μ s * ν t) : μ.prod ν = μν := prod_eq_generate_from generate_from_measurable_set generate_from_measurable_set is_pi_system_measurable_set is_pi_system_measurable_set μ.to_finite_spanning_sets_in ν.to_finite_spanning_sets_in (λ s hs t ht, h s t hs ht) lemma prod_swap : map prod.swap (μ.prod ν) = ν.prod μ := begin refine (prod_eq _).symm, intros s t hs ht, simp_rw [map_apply measurable_swap (hs.prod ht), preimage_swap_prod, prod_prod, mul_comm] end lemma prod_apply_symm {s : set (α × β)} (hs : measurable_set s) : μ.prod ν s = ∫⁻ y, μ ((λ x, (x, y)) ⁻¹' s) ∂ν := by { rw [← prod_swap, map_apply measurable_swap hs], simp only [prod_apply (measurable_swap hs)], refl } lemma prod_assoc_prod [sigma_finite τ] : map measurable_equiv.prod_assoc ((μ.prod ν).prod τ) = μ.prod (ν.prod τ) := begin refine (prod_eq_generate_from generate_from_measurable_set generate_from_prod is_pi_system_measurable_set is_pi_system_prod μ.to_finite_spanning_sets_in (ν.to_finite_spanning_sets_in.prod τ.to_finite_spanning_sets_in) _).symm, rintro s hs _ ⟨t, u, ht, hu, rfl⟩, rw [mem_set_of_eq] at hs ht hu, simp_rw [map_apply (measurable_equiv.measurable _) (hs.prod (ht.prod hu)), measurable_equiv.prod_assoc, measurable_equiv.coe_mk, equiv.prod_assoc_preimage, prod_prod, mul_assoc] end /-! ### The product of specific measures -/ lemma prod_restrict (s : set α) (t : set β) : (μ.restrict s).prod (ν.restrict t) = (μ.prod ν).restrict (s ×ˢ t) := begin refine prod_eq (λ s' t' hs' ht', _), rw [restrict_apply (hs'.prod ht'), prod_inter_prod, prod_prod, restrict_apply hs', restrict_apply ht'] end lemma restrict_prod_eq_prod_univ (s : set α) : (μ.restrict s).prod ν = (μ.prod ν).restrict (s ×ˢ (univ : set β)) := begin have : ν = ν.restrict set.univ := measure.restrict_univ.symm, rwa [this, measure.prod_restrict, ← this], end lemma prod_dirac (y : β) : μ.prod (dirac y) = map (λ x, (x, y)) μ := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_right (hs.prod ht), mk_preimage_prod_left_eq_if, measure_if, dirac_apply' _ ht, ← indicator_mul_right _ (λ x, μ s), pi.one_apply, mul_one] end lemma dirac_prod (x : α) : (dirac x).prod ν = map (prod.mk x) ν := begin refine prod_eq (λ s t hs ht, _), simp_rw [map_apply measurable_prod_mk_left (hs.prod ht), mk_preimage_prod_right_eq_if, measure_if, dirac_apply' _ hs, ← indicator_mul_left _ _ (λ x, ν t), pi.one_apply, one_mul] end lemma dirac_prod_dirac {x : α} {y : β} : (dirac x).prod (dirac y) = dirac (x, y) := by rw [prod_dirac, map_dirac measurable_prod_mk_right] lemma prod_sum {ι : Type*} [fintype ι] (ν : ι → measure β) [∀ i, sigma_finite (ν i)] : μ.prod (sum ν) = sum (λ i, μ.prod (ν i)) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ ht, prod_prod, ennreal.tsum_mul_left] end lemma sum_prod {ι : Type*} [fintype ι] (μ : ι → measure α) [∀ i, sigma_finite (μ i)] : (sum μ).prod ν = sum (λ i, (μ i).prod ν) := begin refine prod_eq (λ s t hs ht, _), simp_rw [sum_apply _ (hs.prod ht), sum_apply _ hs, prod_prod, ennreal.tsum_mul_right] end lemma prod_add (ν' : measure β) [sigma_finite ν'] : μ.prod (ν + ν') = μ.prod ν + μ.prod ν' := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod, left_distrib] } lemma add_prod (μ' : measure α) [sigma_finite μ'] : (μ + μ').prod ν = μ.prod ν + μ'.prod ν := by { refine prod_eq (λ s t hs ht, _), simp_rw [add_apply, prod_prod, right_distrib] } @[simp] lemma zero_prod (ν : measure β) : (0 : measure α).prod ν = 0 := by { rw measure.prod, exact bind_zero_left _ } @[simp] lemma prod_zero (μ : measure α) : μ.prod (0 : measure β) = 0 := by simp [measure.prod] lemma map_prod_map {δ} [measurable_space δ] {f : α → β} {g : γ → δ} {μa : measure α} {μc : measure γ} (hfa : sigma_finite (map f μa)) (hgc : sigma_finite (map g μc)) (hf : measurable f) (hg : measurable g) : (map f μa).prod (map g μc) = map (prod.map f g) (μa.prod μc) := begin haveI := hgc.of_map μc hg, refine prod_eq (λ s t hs ht, _), rw [map_apply (hf.prod_map hg) (hs.prod ht), map_apply hf hs, map_apply hg ht], exact prod_prod (f ⁻¹' s) (g ⁻¹' t) end end measure namespace measure_preserving open measure variables {δ : Type*} [measurable_space δ] {μa : measure α} {μb : measure β} {μc : measure γ} {μd : measure δ} lemma skew_product [sigma_finite μb] [sigma_finite μd] {f : α → β} (hf : measure_preserving f μa μb) {g : α → γ → δ} (hgm : measurable (uncurry g)) (hg : ∀ᵐ x ∂μa, map (g x) μc = μd) : measure_preserving (λ p : α × γ, (f p.1, g p.1 p.2)) (μa.prod μc) (μb.prod μd) := begin classical, have : measurable (λ p : α × γ, (f p.1, g p.1 p.2)) := (hf.1.comp measurable_fst).prod_mk hgm, /- if `μa = 0`, then the lemma is trivial, otherwise we can use `hg` to deduce `sigma_finite μc`. -/ rcases eq_or_ne μa 0 with (rfl|ha), { rw [← hf.map_eq, zero_prod, (map f).map_zero, zero_prod], exact ⟨this, (map _).map_zero⟩ }, haveI : sigma_finite μc, { rcases (ae_ne_bot.2 ha).nonempty_of_mem hg with ⟨x, hx : map (g x) μc = μd⟩, exact sigma_finite.of_map _ hgm.of_uncurry_left (by rwa hx) }, -- Thus we can apply `measure.prod_eq` to prove equality of measures. refine ⟨this, (prod_eq $ λ s t hs ht, _).symm⟩, rw [map_apply this (hs.prod ht)], refine (prod_apply (this $ hs.prod ht)).trans _, have : ∀ᵐ x ∂μa, μc ((λ y, (f x, g x y)) ⁻¹' (s ×ˢ t)) = indicator (f ⁻¹' s) (λ y, μd t) x, { refine hg.mono (λ x hx, _), unfreezingI { subst hx }, simp only [mk_preimage_prod_right_fn_eq_if, indicator_apply, mem_preimage], split_ifs, exacts [(map_apply hgm.of_uncurry_left ht).symm, measure_empty] }, simp only [preimage_preimage], rw [lintegral_congr_ae this, lintegral_indicator _ (hf.1 hs), set_lintegral_const, hf.measure_preimage hs, mul_comm] end /-- If `f : α → β` sends the measure `μa` to `μb` and `g : γ → δ` sends the measure `μc` to `μd`, then `prod.map f g` sends `μa.prod μc` to `μb.prod μd`. -/ protected lemma prod [sigma_finite μb] [sigma_finite μd] {f : α → β} {g : γ → δ} (hf : measure_preserving f μa μb) (hg : measure_preserving g μc μd) : measure_preserving (prod.map f g) (μa.prod μc) (μb.prod μd) := have measurable (uncurry $ λ _ : α, g), from (hg.1.comp measurable_snd), hf.skew_product this $ filter.eventually_of_forall $ λ _, hg.map_eq end measure_preserving end measure_theory open measure_theory.measure section lemma ae_measurable.prod_swap [sigma_finite μ] [sigma_finite ν] {f : β × α → γ} (hf : ae_measurable f (ν.prod μ)) : ae_measurable (λ (z : α × β), f z.swap) (μ.prod ν) := by { rw ← prod_swap at hf, exact hf.comp_measurable measurable_swap } lemma ae_measurable.fst [sigma_finite ν] {f : α → γ} (hf : ae_measurable f μ) : ae_measurable (λ (z : α × β), f z.1) (μ.prod ν) := hf.comp_measurable' measurable_fst prod_fst_absolutely_continuous lemma ae_measurable.snd [sigma_finite ν] {f : β → γ} (hf : ae_measurable f ν) : ae_measurable (λ (z : α × β), f z.2) (μ.prod ν) := hf.comp_measurable' measurable_snd prod_snd_absolutely_continuous /-- The Bochner integral is a.e.-measurable. This shows that the integrand of (the right-hand-side of) Fubini's theorem is a.e.-measurable. -/ lemma ae_measurable.integral_prod_right' [sigma_finite ν] [second_countable_topology E] [normed_space ℝ E] [borel_space E] [complete_space E] ⦃f : α × β → E⦄ (hf : ae_measurable f (μ.prod ν)) : ae_measurable (λ x, ∫ y, f (x, y) ∂ν) μ := ⟨λ x, ∫ y, hf.mk f (x, y) ∂ν, hf.measurable_mk.integral_prod_right', by { filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ hx using integral_congr_ae hx }⟩ lemma ae_measurable.prod_mk_left [sigma_finite ν] {f : α × β → γ} (hf : ae_measurable f (μ.prod ν)) : ∀ᵐ x ∂μ, ae_measurable (λ y, f (x, y)) ν := by { filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with x hx using ⟨λ y, hf.mk f (x, y), hf.measurable_mk.comp measurable_prod_mk_left, hx⟩ } end namespace measure_theory /-! ### The Lebesgue integral on a product -/ variables [sigma_finite ν] lemma lintegral_prod_swap [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z.swap ∂(ν.prod μ) = ∫⁻ z, f z ∂(μ.prod ν) := by { rw ← prod_swap at hf, rw [← lintegral_map' hf measurable_swap, prod_swap] } /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod_of_measurable : ∀ (f : α × β → ℝ≥0∞) (hf : measurable f), ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have m := @measurable_prod_mk_left, refine measurable.ennreal_induction _ _ _, { intros c s hs, simp only [← indicator_comp_right], simp [lintegral_indicator, m hs, hs, lintegral_const_mul, measurable_measure_prod_mk_left hs, prod_apply] }, { rintro f g - hf hg h2f h2g, simp [lintegral_add, measurable.lintegral_prod_right', hf.comp m, hg.comp m, hf, hg, h2f, h2g] }, { intros f hf h2f h3f, have kf : ∀ x n, measurable (λ y, f n (x, y)) := λ x n, (hf n).comp m, have k2f : ∀ x, monotone (λ n y, f n (x, y)) := λ x i j hij y, h2f hij (x, y), have lf : ∀ n, measurable (λ x, ∫⁻ y, f n (x, y) ∂ν) := λ n, (hf n).lintegral_prod_right', have l2f : monotone (λ n x, ∫⁻ y, f n (x, y) ∂ν) := λ i j hij x, lintegral_mono (k2f x hij), simp only [lintegral_supr hf h2f, lintegral_supr (kf _), k2f, lintegral_supr lf l2f, h3f] }, end /-- **Tonelli's Theorem**: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral. -/ lemma lintegral_prod (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ := begin have A : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ z, hf.mk f z ∂(μ.prod ν) := lintegral_congr_ae hf.ae_eq_mk, have B : ∫⁻ x, ∫⁻ y, f (x, y) ∂ν ∂μ = ∫⁻ x, ∫⁻ y, hf.mk f (x, y) ∂ν ∂μ, { apply lintegral_congr_ae, filter_upwards [ae_ae_of_ae_prod hf.ae_eq_mk] with _ ha using lintegral_congr_ae ha, }, rw [A, B, lintegral_prod_of_measurable _ hf.measurable_mk], apply_instance end /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued almost everywhere measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : ae_measurable f (μ.prod ν)) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := by { simp_rw [← lintegral_prod_swap f hf], exact lintegral_prod _ hf.prod_swap } /-- The symmetric verion of Tonelli's Theorem: For `ℝ≥0∞`-valued measurable functions on `α × β`, the integral of `f` is equal to the iterated integral, in reverse order. -/ lemma lintegral_prod_symm' [sigma_finite μ] (f : α × β → ℝ≥0∞) (hf : measurable f) : ∫⁻ z, f z ∂(μ.prod ν) = ∫⁻ y, ∫⁻ x, f (x, y) ∂μ ∂ν := lintegral_prod_symm f hf.ae_measurable /-- The reversed version of **Tonelli's Theorem**. In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.1 z.2 ∂(μ.prod ν) := (lintegral_prod _ hf).symm /-- The reversed version of **Tonelli's Theorem** (symmetric version). In this version `f` is in curried form, which makes it easier for the elaborator to figure out `f` automatically. -/ lemma lintegral_lintegral_symm [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ z, f z.2 z.1 ∂(ν.prod μ) := (lintegral_prod_symm _ hf.prod_swap).symm /-- Change the order of Lebesgue integration. -/ lemma lintegral_lintegral_swap [sigma_finite μ] ⦃f : α → β → ℝ≥0∞⦄ (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ = ∫⁻ y, ∫⁻ x, f x y ∂μ ∂ν := (lintegral_lintegral hf).trans (lintegral_prod_symm _ hf) lemma lintegral_prod_mul {f : α → ℝ≥0∞} {g : β → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g ν) : ∫⁻ z, f z.1 * g z.2 ∂(μ.prod ν) = ∫⁻ x, f x ∂μ * ∫⁻ y, g y ∂ν := by simp [lintegral_prod _ (hf.fst.mul hg.snd), lintegral_lintegral_mul hf hg] /-! ### Integrability on a product -/ section variables [opens_measurable_space E] lemma integrable.swap [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (f ∘ prod.swap) (ν.prod μ) := ⟨hf.ae_measurable.prod_swap, (lintegral_prod_swap _ hf.ae_measurable.ennnorm : _).le.trans_lt hf.has_finite_integral⟩ lemma integrable_swap_iff [sigma_finite μ] ⦃f : α × β → E⦄ : integrable (f ∘ prod.swap) (ν.prod μ) ↔ integrable f (μ.prod ν) := ⟨λ hf, by { convert hf.swap, ext ⟨x, y⟩, refl }, λ hf, hf.swap⟩ lemma has_finite_integral_prod_iff ⦃f : α × β → E⦄ (h1f : measurable f) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := begin simp only [has_finite_integral, lintegral_prod_of_measurable _ h1f.ennnorm], have : ∀ x, ∀ᵐ y ∂ν, 0 ≤ ∥f (x, y)∥ := λ x, eventually_of_forall (λ y, norm_nonneg _), simp_rw [integral_eq_lintegral_of_nonneg_ae (this _) (h1f.norm.comp measurable_prod_mk_left).ae_measurable, ennnorm_eq_of_real to_real_nonneg, of_real_norm_eq_coe_nnnorm], -- this fact is probably too specialized to be its own lemma have : ∀ {p q r : Prop} (h1 : r → p), (r ↔ p ∧ q) ↔ (p → (r ↔ q)) := λ p q r h1, by rw [← and.congr_right_iff, and_iff_right_of_imp h1], rw [this], { intro h2f, rw lintegral_congr_ae, refine h2f.mp _, apply eventually_of_forall, intros x hx, dsimp only, rw [of_real_to_real], rw [← lt_top_iff_ne_top], exact hx }, { intro h2f, refine ae_lt_top _ h2f.ne, exact h1f.ennnorm.lintegral_prod_right' }, end lemma has_finite_integral_prod_iff' ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : has_finite_integral f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, has_finite_integral (λ y, f (x, y)) ν) ∧ has_finite_integral (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := begin rw [has_finite_integral_congr h1f.ae_eq_mk, has_finite_integral_prod_iff h1f.measurable_mk], apply and_congr, { apply eventually_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm], assume x hx, exact has_finite_integral_congr hx }, { apply has_finite_integral_congr, filter_upwards [ae_ae_of_ae_prod h1f.ae_eq_mk.symm] with _ hx using integral_congr_ae (eventually_eq.fun_comp hx _), }, { apply_instance, }, end /-- A binary function is integrable if the function `y ↦ f (x, y)` is integrable for almost every `x` and the function `x ↦ ∫ ∥f (x, y)∥ dy` is integrable. -/ lemma integrable_prod_iff ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν) ∧ integrable (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := by simp [integrable, h1f, has_finite_integral_prod_iff', h1f.norm.integral_prod_right', h1f.prod_mk_left] /-- A binary function is integrable if the function `x ↦ f (x, y)` is integrable for almost every `y` and the function `y ↦ ∫ ∥f (x, y)∥ dx` is integrable. -/ lemma integrable_prod_iff' [sigma_finite μ] ⦃f : α × β → E⦄ (h1f : ae_measurable f (μ.prod ν)) : integrable f (μ.prod ν) ↔ (∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ) ∧ integrable (λ y, ∫ x, ∥f (x, y)∥ ∂μ) ν := by { convert integrable_prod_iff (h1f.prod_swap) using 1, rw [integrable_swap_iff] } lemma integrable.prod_left_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ y ∂ ν, integrable (λ x, f (x, y)) μ := ((integrable_prod_iff' hf.ae_measurable).mp hf).1 lemma integrable.prod_right_ae [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : ∀ᵐ x ∂ μ, integrable (λ y, f (x, y)) ν := hf.swap.prod_left_ae lemma integrable.integral_norm_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, ∥f (x, y)∥ ∂ν) μ := ((integrable_prod_iff hf.ae_measurable).mp hf).2 lemma integrable.integral_norm_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, ∥f (x, y)∥ ∂μ) ν := hf.swap.integral_norm_prod_left end variables [second_countable_topology E] [normed_space ℝ E] [complete_space E] [borel_space E] lemma integrable.integral_prod_left ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ x, ∫ y, f (x, y) ∂ν) μ := integrable.mono hf.integral_norm_prod_left hf.ae_measurable.integral_prod_right' $ eventually_of_forall $ λ x, (norm_integral_le_integral_norm _).trans_eq $ (norm_of_nonneg $ integral_nonneg_of_ae $ eventually_of_forall $ λ y, (norm_nonneg (f (x, y)) : _)).symm lemma integrable.integral_prod_right [sigma_finite μ] ⦃f : α × β → E⦄ (hf : integrable f (μ.prod ν)) : integrable (λ y, ∫ x, f (x, y) ∂μ) ν := hf.swap.integral_prod_left /-! ### The Bochner integral on a product -/ variables [sigma_finite μ] lemma integral_prod_swap (f : α × β → E) (hf : ae_measurable f (μ.prod ν)) : ∫ z, f z.swap ∂(ν.prod μ) = ∫ z, f z ∂(μ.prod ν) := begin rw ← prod_swap at hf, rw [← integral_map measurable_swap hf, prod_swap] end variables {E' : Type*} [measurable_space E'] [normed_group E'] [borel_space E'] [complete_space E'] [normed_space ℝ E'] [second_countable_topology E'] /-! Some rules about the sum/difference of double integrals. They follow from `integral_add`, but we separate them out as separate lemmas, because they involve quite some steps. -/ /-- Integrals commute with addition inside another integral. `F` can be any function. -/ lemma integral_fn_integral_add ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) + g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν + ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_add h2f h2g], end /-- Integrals commute with subtraction inside another integral. `F` can be any measurable function. -/ lemma integral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → E') (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine integral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_sub h2f h2g], end /-- Integrals commute with subtraction inside a lower Lebesgue integral. `F` can be any function. -/ lemma lintegral_fn_integral_sub ⦃f g : α × β → E⦄ (F : E → ℝ≥0∞) (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫⁻ x, F (∫ y, f (x, y) - g (x, y) ∂ν) ∂μ = ∫⁻ x, F (∫ y, f (x, y) ∂ν - ∫ y, g (x, y) ∂ν) ∂μ := begin refine lintegral_congr_ae _, filter_upwards [hf.prod_right_ae, hg.prod_right_ae] with _ h2f h2g, simp [integral_sub h2f h2g], end /-- Double integrals commute with addition. -/ lemma integral_integral_add ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) + g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_add id hf hg).trans $ integral_add hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with addition. This is the version with `(f + g) (x, y)` (instead of `f (x, y) + g (x, y)`) in the LHS. -/ lemma integral_integral_add' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f + g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ + ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_add hf hg /-- Double integrals commute with subtraction. -/ lemma integral_integral_sub ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, f (x, y) - g (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := (integral_fn_integral_sub id hf hg).trans $ integral_sub hf.integral_prod_left hg.integral_prod_left /-- Double integrals commute with subtraction. This is the version with `(f - g) (x, y)` (instead of `f (x, y) - g (x, y)`) in the LHS. -/ lemma integral_integral_sub' ⦃f g : α × β → E⦄ (hf : integrable f (μ.prod ν)) (hg : integrable g (μ.prod ν)) : ∫ x, ∫ y, (f - g) (x, y) ∂ν ∂μ = ∫ x, ∫ y, f (x, y) ∂ν ∂μ - ∫ x, ∫ y, g (x, y) ∂ν ∂μ := integral_integral_sub hf hg /-- The map that sends an L¹-function `f : α × β → E` to `∫∫f` is continuous. -/ lemma continuous_integral_integral : continuous (λ (f : α × β →₁[μ.prod ν] E), ∫ x, ∫ y, f (x, y) ∂ν ∂μ) := begin rw [continuous_iff_continuous_at], intro g, refine tendsto_integral_of_L1 _ (L1.integrable_coe_fn g).integral_prod_left (eventually_of_forall $ λ h, (L1.integrable_coe_fn h).integral_prod_left) _, simp_rw [← lintegral_fn_integral_sub (λ x, (nnnorm x : ℝ≥0∞)) (L1.integrable_coe_fn _) (L1.integrable_coe_fn g)], refine tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds _ (λ i, zero_le _) _, { exact λ i, ∫⁻ x, ∫⁻ y, nnnorm (i (x, y) - g (x, y)) ∂ν ∂μ }, swap, { exact λ i, lintegral_mono (λ x, ennnorm_integral_le_lintegral_ennnorm _) }, show tendsto (λ (i : α × β →₁[μ.prod ν] E), ∫⁻ x, ∫⁻ (y : β), nnnorm (i (x, y) - g (x, y)) ∂ν ∂μ) (𝓝 g) (𝓝 0), have : ∀ (i : α × β →₁[μ.prod ν] E), measurable (λ z, (nnnorm (i z - g z) : ℝ≥0∞)) := λ i, ((Lp.measurable i).sub (Lp.measurable g)).ennnorm, simp_rw [← lintegral_prod_of_measurable _ (this _), ← L1.of_real_norm_sub_eq_lintegral, ← of_real_zero], refine (continuous_of_real.tendsto 0).comp _, rw [← tendsto_iff_norm_tendsto_zero], exact tendsto_id end /-- **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. `integrable_prod_iff` can be useful to show that the function in question in integrable. `measure_theory.integrable.integral_prod_right` is useful to show that the inner integral of the right-hand side is integrable. -/ lemma integral_prod : ∀ (f : α × β → E) (hf : integrable f (μ.prod ν)), ∫ z, f z ∂(μ.prod ν) = ∫ x, ∫ y, f (x, y) ∂ν ∂μ := begin apply integrable.induction, { intros c s hs h2s, simp_rw [integral_indicator hs, ← indicator_comp_right, function.comp, integral_indicator (measurable_prod_mk_left hs), set_integral_const, integral_smul_const, integral_to_real (measurable_measure_prod_mk_left hs).ae_measurable (ae_measure_lt_top hs h2s.ne), prod_apply hs] }, { intros f g hfg i_f i_g hf hg, simp_rw [integral_add' i_f i_g, integral_integral_add' i_f i_g, hf, hg] }, { exact is_closed_eq continuous_integral continuous_integral_integral }, { intros f g hfg i_f hf, convert hf using 1, { exact integral_congr_ae hfg.symm }, { refine integral_congr_ae _, refine (ae_ae_of_ae_prod hfg).mp _, apply eventually_of_forall, intros x hfgx, exact integral_congr_ae (ae_eq_symm hfgx) } } end /-- Symmetric version of **Fubini's Theorem**: For integrable functions on `α × β`, the Bochner integral of `f` is equal to the iterated Bochner integral. This version has the integrals on the right-hand side in the other order. -/ lemma integral_prod_symm (f : α × β → E) (hf : integrable f (μ.prod ν)) : ∫ z, f z ∂(μ.prod ν) = ∫ y, ∫ x, f (x, y) ∂μ ∂ν := by { simp_rw [← integral_prod_swap f hf.ae_measurable], exact integral_prod _ hf.swap } /-- Reversed version of **Fubini's Theorem**. -/ lemma integral_integral {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.1 z.2 ∂(μ.prod ν) := (integral_prod _ hf).symm /-- Reversed version of **Fubini's Theorem** (symmetric version). -/ lemma integral_integral_symm {f : α → β → E} (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ z, f z.2 z.1 ∂(ν.prod μ) := (integral_prod_symm _ hf.swap).symm /-- Change the order of Bochner integration. -/ lemma integral_integral_swap ⦃f : α → β → E⦄ (hf : integrable (uncurry f) (μ.prod ν)) : ∫ x, ∫ y, f x y ∂ν ∂μ = ∫ y, ∫ x, f x y ∂μ ∂ν := (integral_integral hf).trans (integral_prod_symm _ hf) /-- **Fubini's Theorem** for set integrals. -/ lemma set_integral_prod (f : α × β → E) {s : set α} {t : set β} (hf : integrable_on f (s ×ˢ t) (μ.prod ν)) : ∫ z in s ×ˢ t, f z ∂(μ.prod ν) = ∫ x in s, ∫ y in t, f (x, y) ∂ν ∂μ := begin simp only [← measure.prod_restrict s t, integrable_on] at hf ⊢, exact integral_prod f hf end end measure_theory
program example implicit none != unit (s) :: x != unit (m) :: y integer :: x, y integer :: z z = x + y end program example
isEven' : Nat -> Bool isEven' Z = True isEven' (S k) = not (isEven' k) mutual isEven : Nat -> Bool isEven Z = True isEven (S k) = isOdd k isOdd : Nat -> Bool isOdd Z = False isOdd (S k) = isEven k
-- Aplicacion_de_particiones_en_relaciones_de_equivalencia.lean -- Aplicación de particiones en relaciones de equivalencia -- José A. Alonso Jiménez -- Sevilla, 12 de octubre de 2021 -- --------------------------------------------------------------------- -- --------------------------------------------------------------------- -- Definir la función -- relacionP : particion A → {R : A → A → Prop // equivalence R} -- tal que (relacionP P) es la relación de equivalencia definida por la -- partición P. -- --------------------------------------------------------------------- import tactic @[ext] structure particion (A : Type) := (Bloques : set (set A)) (Hno_vacios : ∀ X ∈ Bloques, (X : set A).nonempty) (Hrecubren : ∀ a, ∃ X ∈ Bloques, a ∈ X) (Hdisjuntos : ∀ X Y ∈ Bloques, (X ∩ Y : set A).nonempty → X = Y) namespace particion variable {A : Type} variables {X Y : set A} variable {P : particion A} def relacion : (particion A) → (A → A → Prop) := λ P a b, ∀ X ∈ Bloques P, a ∈ X → b ∈ X lemma reflexiva (P : particion A) : reflexive (relacion P) := λ a X hXC haX, haX lemma iguales_si_comun (hX : X ∈ Bloques P) (hY : Y ∈ Bloques P) {a : A} (haX : a ∈ X) (haY : a ∈ Y) : X = Y := Hdisjuntos P X hX Y hY ⟨a, haX, haY⟩ lemma pertenece_si_pertenece (hX : X ∈ Bloques P) (hY : Y ∈ Bloques P) {a b : A} (haX : a ∈ X) (haY : a ∈ Y) (hbX : b ∈ X) : b ∈ Y := begin convert hbX, exact iguales_si_comun hY hX haY haX, end lemma simetrica (P : particion A) : symmetric (relacion P) := begin intros a b h X hX hbX, obtain ⟨Y, hY, haY⟩ := Hrecubren P a, specialize h Y hY haY, exact pertenece_si_pertenece hY hX h hbX haY, end lemma transitiva (P : particion A) : transitive (relacion P) := λ a b c hab hbc X hX haX, hbc X hX (hab X hX haX) def relacionP : particion A → {R : A → A → Prop // equivalence R} := λ P, ⟨λ a b, ∀ X ∈ Bloques P, a ∈ X → b ∈ X, ⟨reflexiva P, simetrica P, transitiva P⟩⟩ end particion
! Hauksson, E. and W. Yang, and P.M. Shearer, "Waveform Relocated Earthquake Catalog for Southern California (1981 to 2011)"; Bull. Seismol. Soc. Am., Vol. 102, No. 5, pp.2239-2244, October 2012, doi:10.1785/0120120010 ! ! The locatino methods and formats are similar to what was applied by: ! Lin, G., P. M. Shearer, and E. Hauksson (2007),Applying a three-dimensional velocity model, waveform cross ! correlation, and cluster analysis to locate southern California seismicity from 1981 to 2005, ! J. Geophys. Res., 112, B12309, doi:10.1029/2007JB004986. ! ! ONLY EARTHQUAKES are included in this file. Quarry blasts and other events have been removed. ! ! LOCATION FILE FORMAT DESCRIPTION ! The locations are in the following custom format with 146 character lines: ! ! 1981 01 01 04 13 55.710 3301565 33.25524 -115.96763 5.664 2.26 45 17 0.21 1 4 260 460 76 0.300 0.800 0.003 0.003 le ct Poly5 ! where ! 1981 = year ! 1 = month ! 1 = day ! 4 = hour ! 13 = minute ! 55.710 = second ! ! 3301565 = SCSN cuspid (up to 9 digits) ! ! 33.25524 = latitude ! -115.96763 = longitude ! 5.664 = depth (km) ! 2.26 = SCSN calculated preferred magnitude (0.0 if unassigned) ! ! 45 = number of P and S picks used for 1D SSST or 3D location (different from old format) ! 17 = to nearest statino in km (different from old format) ! 0.21 = rms residual (s) for 1D location; value of 99.0 indicates information not available ! ! 1 = local day/night flag (=0 for day, =1 for night in Calif.) ! ! 4 = location method flag (=1 for SCSN catalog or 1d hypoinverse relocation, ! =2 for 1D SSST, =3 for 3D, =4 for waveform cross-correlation) ! Superseeded by flag below ! 260 = similar event cluster identification number (0 if the event is not relocated with waveform cross-correlation data) ! ! 460 = number of events in similar event cluster (0 if the event is not in similar event clusters) ! ! 76 = number of differential times used to locate this event ! ! 0.300 = est. std. error (km) in absolute horz. position ! 0.800 = est. std. error (km) in absolute depth ! 0.003 = est. std. error (km) in horz. position relative to other events in cluster ! 0.003 = est. std. error (km) in depth relative to other events in cluster ! ! le = SCSN flag for event type (le=local, qb=quarry, re=regional) ! ct = for location method (ct=cross-correlation; 3d=3d velocity model; xx= not relocated, SCSN location used) ! Poly5= the polygon where the earthquake is located. We used 5 polygons to ! generate this catlog. ! ! This catalog is complete, so an attempt is made to include cluster relocated, 3D-model relocated, and not relocated earthquakes. ! If you only want cluster relocated events, you can 'grep ct ...' to get a list of events. ! ! VERSIONS ! ! 1.0) Preliminary version that still needs some quality checking. ! If you find issues with the catalog, please email: [email protected] ! ------------------------------------------------------------------------------------------------- ! hexdump -v -e '"%d %d %d %d %d %d %d %d %d %d %d %d %d\n"' ints | head ! hexdump -v -e '"%f %f %f %f %f %f %f %f %f %f\n"' reals | head ! hexdump -v -e '"%c%c %c%c %c%c%c%c%c\n"' chars | head program fung integer, parameter:: b8 = selected_real_kind(14) ! basic real types integer year,month,day,hour,minute real(b8) second integer cuspid real(b8) latitude,longitude,depth,SCSN integer PandS,statino real(b8) residual integer tod,method, ec,nen,dt real(b8) stdpos,stddepth,stdhorrel,stddeprel character(len=10)therest character(len=2)le,ct character(len=5)poly character(len=32)fname,fbase CALL get_command_argument(1,fname) open(11,file=fname,status="old") OPEN(UNIT=12, FILE="reals"//trim(fname), STATUS="NEW", ACCESS="STREAM") OPEN(UNIT=13, FILE="ints"//trim(fname), STATUS="NEW", ACCESS="STREAM") OPEN(UNIT=14, FILE="chars"//trim(fname), STATUS="NEW", ACCESS="STREAM") OPEN(UNIT=15, FILE="ascii"//trim(fname), STATUS="NEW") do read(11,1,end=2)year,month,day,hour,minute ,& second, & cuspid, & latitude,longitude,depth,SCSN, & PandS,statino, & residual, & tod,method, ec,nen,dt, & stdpos,stddepth,stdhorrel,stddeprel, & le,ct,poly ! if(depth .lt. 0.0 .or. SCSN .lt. 0.0)then write(*,1)year,month,day,hour,minute ,& second, & cuspid, & latitude,longitude,depth,SCSN, & PandS,statino, & residual, & tod,method, ec,nen,dt, & stdpos,stddepth,stdhorrel,stddeprel, & le,ct,poly ! endif ! 10 8 byte reals write(12)second,latitude,longitude,depth,SCSN, & residual,stdpos,stddepth,stdhorrel,stddeprel ! 13 4 byte integers write(13)year,month,day,hour,minute,cuspid, & PandS,statino,tod,method,ec,nen,dt write(14)le,ct,poly write(15,"(a2,',',a2,',',a5)")le,ct,poly 1 format(i4,4(1x,i2.2),1x,& f6.3,1x,i9,1x,f8.5,1x,f10.5,1x,f7.3,1x,f5.2, & 1x,i3,1x,i3,1x,f6.2,1x,i3,1x,i3,1x,i5,1x,i5, & 1x,i7,4(1x,f7.3),2x,a2,1x,a2,1x,a5) enddo 2 continue end program
foo : String foo = """a """
function preprocessing() cd matconvnet; complienn; cd .. end
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_PARAMETERS_HPP_2010127 #define BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_PARAMETERS_HPP_2010127 // Copyright 2010 Dean Michael Berris. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/network/protocol/http/parameters.hpp> namespace boost { namespace network { namespace http { BOOST_PARAMETER_NAME(follow_redirects) BOOST_PARAMETER_NAME(cache_resolved) BOOST_PARAMETER_NAME(openssl_certificate) BOOST_PARAMETER_NAME(openssl_verify_path) BOOST_PARAMETER_NAME(request) BOOST_PARAMETER_NAME(body) BOOST_PARAMETER_NAME(content_type) BOOST_PARAMETER_NAME(body_handler) BOOST_PARAMETER_NAME(connection_manager) BOOST_PARAMETER_NAME(connection_factory) } /* http */ } /* network */ } /* boost */ #endif /* BOOST_NETWORK_PROTOCOL_HTTP_CLIENT_PARAMETERS_HPP_2010127 */
lemma contour_integrable_on: "f contour_integrable_on g \<longleftrightarrow> (\<lambda>t. f(g t) * vector_derivative g (at t)) integrable_on {0..1}"
State Before: α : Type u β : Type v ι✝ : Sort w γ : Type x ι : Type u_1 s : Set ι hs : Set.Finite s t : (i : ι) → i ∈ s → Set α ht : ∀ (i : ι) (hi : i ∈ s), Set.Finite (t i hi) ⊢ Set.Finite (⋃ (i : ι) (h : i ∈ s), t i h) State After: case intro α : Type u β : Type v ι✝ : Sort w γ : Type x ι : Type u_1 s : Set ι t : (i : ι) → i ∈ s → Set α ht : ∀ (i : ι) (hi : i ∈ s), Set.Finite (t i hi) a✝ : Fintype ↑s ⊢ Set.Finite (⋃ (i : ι) (h : i ∈ s), t i h) Tactic: cases hs State Before: case intro α : Type u β : Type v ι✝ : Sort w γ : Type x ι : Type u_1 s : Set ι t : (i : ι) → i ∈ s → Set α ht : ∀ (i : ι) (hi : i ∈ s), Set.Finite (t i hi) a✝ : Fintype ↑s ⊢ Set.Finite (⋃ (i : ι) (h : i ∈ s), t i h) State After: case intro α : Type u β : Type v ι✝ : Sort w γ : Type x ι : Type u_1 s : Set ι t : (i : ι) → i ∈ s → Set α ht : ∀ (i : ι) (hi : i ∈ s), Set.Finite (t i hi) a✝ : Fintype ↑s ⊢ Set.Finite (⋃ (x : ↑s), t ↑x (_ : ↑x ∈ s)) Tactic: rw [biUnion_eq_iUnion] State Before: case intro α : Type u β : Type v ι✝ : Sort w γ : Type x ι : Type u_1 s : Set ι t : (i : ι) → i ∈ s → Set α ht : ∀ (i : ι) (hi : i ∈ s), Set.Finite (t i hi) a✝ : Fintype ↑s ⊢ Set.Finite (⋃ (x : ↑s), t ↑x (_ : ↑x ∈ s)) State After: no goals Tactic: apply finite_iUnion fun i : s => ht i.1 i.2
import Mathlib.Algebra.Ring.Basic import Mathlib.Algebra.Group.Defs /-! # Free modules We construct the free module over a ring `R` generated by a set `X`. It is assumed that both `R` and `X` have decidable equality. This is to obtain decidable equality for the elements of the module, which we do (`FreeModule.decEq`). We choose our definition to allow both such computations and to prove results. The definition is as a quotient of *Formal Sums* (`FormalSum`), which are simply lists of pairs `(a,x)` where `a` is a coefficient in `R` and `x` is a term in `X`. We associate to such a formal sum a coordinate function `X → R` (`FormalSum.coords`). We see that having the same coordinate functions gives an equivalence relation on the formal sums. The free module (`FreeModule`) is then defined as the corresponding quotient of such formal sums. We also give an alternative description via moves, which is more convenient for universal properties. -/ variable {R : Type _} [Ring R] [DecidableEq R] variable {X : Type _} [DecidableEq X] section FormalSumCoords /-! ## Formal sums -/ /-- A *formal sum* represents an `R`-linear combination of finitely many elements of `X`. This is implemented as a list `R × X`, which associates to each element `X` of the list a coefficient from `R`. -/ abbrev FormalSum (R X : Type _) [Ring R] := List (R × X) /-! ## Coordinate functions and Supports * We define coordinate functions X → R for formal sums. * We define (weak) support, relate non-zero coordinates. * We prove decidable equality on a list (easy fact). -/ /-! ### Coordinate functions The definition of coordinate functions is in two steps. We first define the coordinate for a pair `(a,x)`, and then define the coordinate function for a formal sum by summing over such terms. -/ /-- Coordinates for a formal sum with one term. -/ def monomCoeff (R X : Type _) [Ring R] [DecidableEq X](x₀ : X) (nx : R × X) : R := match (nx.2 == x₀) with | true => nx.1 | false => 0 /-- Homomorphism property for coordinates for a formal sum with one term. -/ theorem monom_coords_hom (x₀ x : X) (a b : R) : monomCoeff R X x₀ (a + b, x) = monomCoeff R X x₀ (a, x) + monomCoeff R X x₀ (b, x) := by repeat ( rw [monomCoeff]) cases x == x₀ <;> simp /-- Associativity of scalar multiplication coordinates for a formal sum with one term. -/ theorem monom_coords_mul (x₀ : X) (a b : R) : monomCoeff R X x₀ (a * b, x) = a * monomCoeff R X x₀ (b, x) := by repeat ( rw [monomCoeff]) cases x == x₀ <;> simp /-- Coordinates for a formal sum with one term with scalar `0`. -/ theorem monom_coords_at_zero (x₀ x : X) : monomCoeff R X x₀ (0, x) = 0 := by rw [monomCoeff] cases x == x₀ <;> rfl /-- The coordinates for a formal sum. -/ def FormalSum.coords : FormalSum R X → X → R | [], _ => 0 | h :: t, x₀ => monomCoeff R X x₀ h + coords t x₀ /-! ### Support of a formal sum We next define the support of a formal sum and prove the property that coordinates vanish outside the support. -/ /-- Support for a formal sum in a weak sense (coordinates may vanish on this). -/ def FormalSum.support (s : FormalSum R X) : List X := s.map <| fun (_, x) => x open FormalSum /-- Support contains elements `x : X` where the coordinate is not `0`. -/ theorem nonzero_coord_in_support (s : FormalSum R X) : ∀ x : X, 0 ≠ s.coords x → x ∈ s.support := match s with | [] => fun x hyp => by have d : coords [] x = (0 : R) := by rfl rw [d] at hyp contradiction | h :: t => by intro x hyp let (a₀, x₀) := h have d : support ((a₀, x₀) :: t) = x₀ :: (support t) := by rfl rw [d] match p : x₀ == x with | true => have eqn : x₀ = x := of_decide_eq_true p rw [eqn] apply List.mem_of_elem_eq_true simp [List.elem] | false => rw [coords, monomCoeff, p, zero_add] at hyp let step := nonzero_coord_in_support t x hyp apply List.mem_of_elem_eq_true simp [List.elem] have p' : (x == x₀) = false := by have eqn := of_decide_eq_false p have eqn' : ¬(x = x₀) := by intro contra let contra' := Eq.symm contra contradiction exact decide_eq_false eqn' rw [p'] apply List.elem_eq_true_of_mem exact step /-! ### Equality of coordinates on a list We define equality of coordinates on a list and prove that it is decidable and implied by equality of formal sums. -/ /-- The condition of being equal on all elements is a given list -/ def equalOnList (l : List X) (f g : X → R) : Prop := match l with | [] => true | h :: t => (f h = g h) ∧ (equalOnList t f g) /-- Equal functions are equal on arbitrary supports. -/ theorem equalOnList_of_equal (l : List X) (f g : X → R) : f = g → equalOnList l f g := by intro hyp induction l with | nil => rw [equalOnList] | cons h t step => rw [equalOnList] apply And.intro rw [hyp] exact step /-- Functions equal on support `l` are equal on each `x ∈ l`. -/ theorem eq_mem_of_equalOnList (l : List X) (f g : X → R) (x : X)(mhyp : x ∈ l) : equalOnList l f g → f x = g x := match l with | [] => by contradiction | h :: t => by intro hyp simp [equalOnList] at hyp cases mhyp exact hyp.left have inTail : x ∈ t := by assumption have step := eq_mem_of_equalOnList t f g x inTail hyp.right exact step /-- Decidability of equality on list. -/ @[instance] def decidableEqualOnList (l : List X) (f g : X → R) : Decidable (equalOnList l f g) := match l with | [] => Decidable.isTrue (by simp [equalOnList]) | h :: t => by simp [equalOnList] cases (decidableEqualOnList t f g)with | isTrue hs => exact (if c : f h = g h then (Decidable.isTrue ⟨c, hs⟩) else by apply Decidable.isFalse intro contra have contra' := contra.left contradiction) | isFalse hs => apply Decidable.isFalse intro contra have contra' := contra.right contradiction end FormalSumCoords /-! ## Quotient Free Module * We define relation by having equal coordinates * We show this is an equivalence relation and define the quotient -/ section QuotientFreeModule /-- Relation by equal coordinates. -/ def eqlCoords (R X : Type) [Ring R] [DecidableEq X](s₁ s₂ : FormalSum R X) : Prop := s₁.coords = s₂.coords namespace eqlCoords /-- Relation by equal coordinates is reflexive. -/ theorem refl (s : FormalSum R X) : eqlCoords R X s s := by rfl /-- Relation by equal coordinates is symmetric. -/ theorem symm {s₁ s₂ : FormalSum R X} : eqlCoords R X s₁ s₂ → eqlCoords R X s₂ s₁ := by intro hyp apply funext intro x apply Eq.symm exact congrFun hyp x /-- Relation by equal coordinates is transitive. -/ theorem trans {s₁ s₂ s₃ : FormalSum R X} : eqlCoords R X s₁ s₂ → eqlCoords R X s₂ s₃ → eqlCoords R X s₁ s₃ := by intro hyp₁ hyp₂ apply funext intro x have l₁ := congrFun hyp₁ x have l₂ := congrFun hyp₂ x exact Eq.trans l₁ l₂ /-- Relation by equal coordinates is an equivalence relation. -/ theorem is_equivalence : Equivalence (eqlCoords R X) := { refl := refl, symm := symm, trans := trans } end eqlCoords /-- Setoid based on equal coordinates. -/ instance formalSumSetoid (R X : Type) [Ring R] [DecidableEq X] : Setoid (FormalSum R X) := ⟨eqlCoords R X, eqlCoords.is_equivalence⟩ /-- Quotient free module. -/ abbrev FreeModule (R X : Type) [Ring R] [DecidableEq X] := Quotient (formalSumSetoid R X) notation R"["G"]" => FreeModule R G end QuotientFreeModule section DecidableEqQuotFreeModule /-! ## Decidable equality on quotient free modules We show that the free module `F[X]` has decidable equality. This has two steps: * show decidable equality for images of formal sums. * lift to quotient (by relating to formal sums). We also show that the coordinate functions are defined on the quotient. -/ namespace FreeModule /-- Decidable equality for quotient elements in the free module -/ @[instance] def decideEqualQuotient (s₁ s₂ : FormalSum R X) : Decidable (@Eq (R[X]) ⟦s₁⟧ ⟦s₂⟧) := if ch₁ : equalOnList s₁.support s₁.coords s₂.coords then if ch₂ : equalOnList s₂.support s₁.coords s₂.coords then Decidable.isTrue (by apply Quotient.sound apply funext intro x exact if h₁ : (0 = s₁.coords x) then if h₂ : (0 = s₂.coords x) then by rw [← h₁, h₂] else by have lem : x ∈ s₂.support := by apply nonzero_coord_in_support assumption let lem' := eq_mem_of_equalOnList s₂.support s₁.coords s₂.coords x lem ch₂ exact lem' else by have lem : x ∈ s₁.support := by apply nonzero_coord_in_support assumption let lem' := eq_mem_of_equalOnList s₁.support s₁.coords s₂.coords x lem ch₁ exact lem') else Decidable.isFalse (by intro contra let lem := equalOnList_of_equal s₂.support s₁.coords s₂.coords (Quotient.exact contra) contradiction) else Decidable.isFalse (by intro contra let lem := equalOnList_of_equal s₁.support s₁.coords s₂.coords (Quotient.exact contra) contradiction) /-! ### Lift to quotient -/ /-- Boolean equality on support. -/ def beqOnSupport (l : List X) (f g : X → R) :Bool := l.all <| fun x => decide (f x = g x) /-- Equality on support from boolean equality. -/ theorem eql_on_support_of_true {l : List X} {f g : X → R} : beqOnSupport l f g = true → equalOnList l f g := by intro hyp induction l with | nil => simp [equalOnList] | cons h t step => simp [equalOnList] simp [beqOnSupport, List.all] at hyp let p₂ := step hyp.right exact And.intro hyp.left p₂ /-- Boolean equality on support gives equal quotients. -/ theorem eqlquot_of_beq_support (s₁ s₂ : FormalSum R X) (c₁ : beqOnSupport s₁.support s₁.coords s₂.coords) (c₂ : beqOnSupport s₂.support s₁.coords s₂.coords) : @Eq (R[X]) ⟦s₁⟧ ⟦s₂⟧ := by let ch₁ := eql_on_support_of_true c₁ let ch₂ := eql_on_support_of_true c₂ apply Quotient.sound apply funext intro x exact if h₁ : (0 = s₁.coords x) then if h₂ : (0 = s₂.coords x) then by rw [← h₁, h₂] else by have lem : x ∈ s₂.support := by apply nonzero_coord_in_support assumption let lem' := eq_mem_of_equalOnList s₂.support s₁.coords s₂.coords x lem ch₂ exact lem' else by have lem : x ∈ s₁.support := by apply nonzero_coord_in_support assumption let lem' := eq_mem_of_equalOnList s₁.support s₁.coords s₂.coords x lem ch₁ exact lem' /-- Boolean equality for the quotient via lifting -/ def beq_quot : (x₁ x₂ : R[X]) → Bool := by apply Quotient.lift₂ (fun (s₁ s₂ : FormalSum R X) => decide (@Eq (R[X]) ⟦s₁⟧ ⟦s₂⟧)) intro a₁ b₁ a₂ b₂ eqv₁ eqv₂ let eq₁ : Eq (α := R[X]) ⟦a₁⟧ ⟦a₂⟧ := Quot.sound eqv₁ let eq₂ : Eq (α := R[X]) ⟦b₁⟧ ⟦b₂⟧ := Quot.sound eqv₂ conv => lhs; congr; rw [eq₁, eq₂] /-- Boolean equality for the quotient is equality. -/ lemma eq_of_beq_true : ∀ x₁ x₂ : R[X], x₁.beq_quot x₂ = true → x₁ = x₂ := by apply Quotient.ind₂ (motive := fun (x₁ x₂ : R[X]) => x₁.beq_quot x₂ = true → x₁ = x₂) intro s₁ s₂ eqv let eql := of_decide_eq_true eqv assumption /-- Boolean inequality for the quotient is inequality. -/ lemma neq_of_beq_false : ∀ x₁ x₂ : R[X], x₁.beq_quot x₂ = false → Not (x₁ = x₂) := by apply Quotient.ind₂ (motive := fun (x₁ x₂ : R[X]) => x₁.beq_quot x₂ = false → Not (x₁ = x₂)) intro s₁ s₂ neqv let neql := of_decide_eq_false neqv assumption /-- Decidable equality for the free module. -/ @[instance] def decEq (x₁ x₂ : R[X]) : Decidable (x₁ = x₂) := by match p : x₁.beq_quot x₂ with | true => apply Decidable.isTrue apply FreeModule.eq_of_beq_true assumption | false => apply Decidable.isFalse apply FreeModule.neq_of_beq_false assumption /-! ### Induced coordinates on the quotient. -/ /-- Coordinates are well defined on the quotient. -/ theorem equal_coords_of_approx (s₁ s₂ : FormalSum R X): s₁ ≈ s₂ → s₁.coords = s₂.coords := by intro hyp apply funext; intro x₀ exact congrFun hyp x₀ /-- coordinates for the quotient -/ def coordinates (x₀ : X) : R[X] → R := by apply Quotient.lift (fun s : FormalSum R X => s.coords x₀) intro a b intro hyp let l := equal_coords_of_approx _ _ hyp exact congrFun l x₀ end FreeModule end DecidableEqQuotFreeModule /-! ## Module structure We define the module structure on the quotient of the free module by the equivalence relation. * We define scalar multiplication and addition on formal sums. * We show that we have induced operations on the quotient. * We show that the induced operations give a module structure on the quotient. -/ section ModuleStruture open FormalSum namespace FormalSum /-! ### Scalar multiplication: on formal sums and on the quotient. -/ /-- Scalar multiplication on formal sums. -/ def scmul : R → FormalSum R X → FormalSum R X | _, [] => [] | r, (h :: t) => let (a₀, x₀) := h (r * a₀, x₀) :: (scmul r t) /-- Coordinates after scalar multiplication. -/ theorem scmul_coords (r : R) (s : FormalSum R X) (x₀ : X) : (r * s.coords x₀) = (s.scmul r).coords x₀ := by induction s with | nil => simp [coords] | cons h t ih => simp [scmul, coords, monom_coords_mul, left_distrib, ih] /-- Scalar multiplication on the Free Module. -/ def FreeModule.scmul : R → R[X] → R[X] := by intro r let f : FormalSum R X → R[X] := fun s => ⟦s.scmul r⟧ apply Quotient.lift f intro s₁ s₂ simp intro hypeq apply funext intro x₀ have l₁ := scmul_coords r s₁ x₀ have l₂ := scmul_coords r s₂ x₀ rw [← l₁, ← l₂] rw [hypeq] /-! ### Addition: on formal sums and on the quotient. -/ /-- Coordinates add when appending. -/ theorem append_coords (s₁ s₂ : FormalSum R X) (x₀ : X) : (s₁.coords x₀) + (s₂.coords x₀) = (s₁ ++ s₂).coords x₀ := by induction s₁ with | nil => simp [coords] | cons h t ih => simp [coords, ← ih, add_assoc] /-- Coordinates well-defined up to equivalence. -/ theorem append_equiv (s₁ s₂ t₁ t₂ : FormalSum R X) :(s₁ ≈ s₂) → (t₁ ≈ t₂) → s₁ ++ t₁ ≈ s₂ ++ t₂ := by intro eqv₁ eqv₂ apply funext intro x₀ rw [← append_coords] rw [← append_coords] have ls : coords s₁ x₀ = coords s₂ x₀ := by apply congrFun eqv₁ have lt : coords t₁ x₀ = coords t₂ x₀ := by apply congrFun eqv₂ rw [← ls, ← lt] end FormalSum /-- Addition of elements in the free module. -/ def FreeModule.add : R[X] → R[X] → R[X] := by let f : FormalSum R X → FormalSum R X → R[X] := fun s₁ s₂ => ⟦s₁ ++ s₂⟧ apply Quotient.lift₂ f intro a₁ b₁ a₂ b₂ simp intro eq₁ eq₂ apply funext intro x₀ have l₁ := append_coords a₁ b₁ x₀ have l₂ := append_coords a₂ b₂ x₀ rw [← l₁, ← l₂] rw [eq₁, eq₂] instance : Add (R[X]) := ⟨FreeModule.add⟩ instance : HSMul R (R[X]) (R[X]) := ⟨FreeModule.scmul⟩ namespace FormalSum /-! ### Properties of operations on formal sums. -/ /-- Associativity for scalar multiplication for formal sums. -/ theorem action (a b : R) (s : FormalSum R X) : (s.scmul b).scmul a = s.scmul (a * b) := by induction s with | nil => simp [scmul] | cons h t ih => simp [scmul, ih, mul_assoc] /-- Distributivity for the module operations. -/ theorem act_sum (a b : R) (s : FormalSum R X) : (s.scmul a) ++ (s.scmul b) ≈ s.scmul (a + b) := by induction s with | nil => simp [scmul] apply eqlCoords.refl | cons h t ih => apply funext; intro x₀ let il₁ := congrFun ih x₀ rw [← append_coords] simp [scmul, coords, right_distrib, monom_coords_hom] rw [← append_coords] at il₁ rw [← il₁] simp conv => lhs rw [add_assoc] arg 2 rw [← add_assoc] arg 1 rw [add_comm] conv => lhs rw [add_assoc] rw [← add_assoc] end FormalSum namespace FreeModule /-! ### Module properties for the free module. -/ /-- Associativity for scalar and ring products. -/ theorem module_action (a b : R) (x : R[X]) : a • (b • x) = (a * b) • x := by apply @Quotient.ind (motive := fun x : R[X] => a • (b • x) = (a * b) • x) intro s apply Quotient.sound rw [FormalSum.action] apply eqlCoords.refl /-- Commutativity of addition. -/ theorem addn_comm (x₁ x₂ : R[X]) : x₁ + x₂ = x₂ + x₁ := by apply @Quotient.ind₂ (motive := fun x₁ x₂ : R[X] => x₁ + x₂ = x₂ + x₁) intro s₁ s₂ apply Quotient.sound apply funext intro x₀ let lm₁ := append_coords s₁ s₂ x₀ let lm₂ := append_coords s₂ s₁ x₀ rw [← lm₁, ← lm₂] simp [add_comm] theorem add_assoc_aux (s₁ : FormalSum R X) (x₂ x₃ : R[X]) : (⟦s₁⟧ + x₂) + x₃ = ⟦s₁⟧ + (x₂ + x₃) := by apply @Quotient.ind₂ (motive := fun x₂ x₃ : R[X] => (⟦s₁⟧ + x₂) + x₃ = ⟦s₁⟧ + (x₂ + x₃)) intro x₂ x₃ apply Quotient.sound apply funext intro x₀ rw [← append_coords] rw [← append_coords] rw [← append_coords] rw [← append_coords] simp [add_assoc] /-- Associativity of addition. -/ theorem addn_assoc (x₁ x₂ x₃ : R[X]) : (x₁ + x₂) + x₃ = x₁ + (x₂ + x₃) := by apply @Quotient.ind (motive := fun x₁ : R[X] => (x₁ + x₂) + x₃ = x₁ + (x₂ + x₃)) intro x₁ apply add_assoc_aux /-- The zero element of the free module. -/ def zero : R[X] := ⟦[]⟧ /-- adding zero-/ theorem addn_zero (x: R[X]) : x + zero = x := by apply @Quotient.ind (motive := fun x : R[X] => x + zero = x) intro x apply Quotient.sound apply funext intro x₀ rw [← append_coords] simp [add_zero, coords] /-- adding zero-/ theorem zero_addn (x: R[X]) : zero + x = x := by apply @Quotient.ind (motive := fun x : R[X] => zero + x = x) intro x apply Quotient.sound apply funext intro x₀ rw [← append_coords] simp [add_zero, coords] /-- Distributivity for addition of module elements. -/ theorem elem_distrib (a : R) (x₁ x₂ : R[X]) : a • (x₁ + x₂) = a • x₁ + a • x₂ := by apply @Quotient.ind₂ (motive := fun x₁ x₂ : R[X] => a • (x₁ + x₂) = a • x₁ + a • x₂) intro s₁ s₂ apply Quotient.sound apply funext intro x₀ rw [← scmul_coords] rw [← append_coords] rw [← append_coords] rw [← scmul_coords] rw [← scmul_coords] simp [left_distrib] /-- Distributivity with respect to scalars. -/ theorem coeffs_distrib (a b: R)(x: R[X]) : a • x + b • x = (a + b) • x:= by apply @Quotient.ind (motive := fun x : R[X] => a • x + b • x = (a + b) • x) intro s apply Quotient.sound apply funext intro x₀ let l := act_sum a b s let l'' := congrFun l x₀ exact l'' /-- Multiplication by `1 : R`. -/ theorem unit_coeffs (x: R[X]) : (1 : R) • x = x:= by apply @Quotient.ind (motive := fun x : R[X] => (1 : R) • x = x) intro s apply Quotient.sound apply funext intro x₀ let l := scmul_coords 1 s x₀ rw [← l] simp /-- Multiplication by `0 : R`. -/ theorem zero_coeffs (x: R[X]) : (0 : R) • x = ⟦ [] ⟧:= by apply @Quotient.ind (motive := fun x : R[X] => (0 : R) • x = ⟦ [] ⟧) intro s apply Quotient.sound apply funext intro x₀ let l := scmul_coords 0 s x₀ rw [← l] simp [coords] /-- The module is an additive commutative group, mainly proved as a check -/ instance : AddCommGroup (R[X]) := { zero := ⟦ []⟧ add := FreeModule.add add_assoc := FreeModule.addn_assoc add_zero := FreeModule.addn_zero zero_add := FreeModule.zero_addn neg := fun x => (-1 : R) • x sub_eq_add_neg := by intros; rfl add_left_neg := by intro x let l := FreeModule.coeffs_distrib (-1 : R) (1 : R) x simp at l rw [FreeModule.unit_coeffs] at l rw [FreeModule.zero_coeffs] at l exact l add_comm := FreeModule.addn_comm } end FreeModule end ModuleStruture /-! ## Equivalent definition of the relation via moves For conceptual results such as the universal property (needed for the group ring structure) it is useful to define the relation on the free module in terms of moves. We do this, and show that this is the same as the relation defined by equality of coordinates. * We define elementary moves on formal sums * We show coordinates equal if and only if related by elementary moves * Hence can define map on Free Module when invariant under elementary moves -/ section ElementaryMoves open FormalSum /-- Elementary moves for formal sums. -/ inductive ElementaryMove (R X : Type) [Ring R] [DecidableEq R][DecidableEq X] : FormalSum R X → FormalSum R X → Prop where | zeroCoeff (tail : FormalSum R X) (x : X) (a : R) (h : a = 0) : ElementaryMove R X ((a, x) :: tail) tail | addCoeffs (a b : R) (x : X) (tail : FormalSum R X) : ElementaryMove R X ((a, x) :: (b, x) :: tail) ((a + b, x) :: tail) | cons (a : R) (x : X) (s₁ s₂ : FormalSum R X) : ElementaryMove R X s₁ s₂ → ElementaryMove R X ((a, x) :: s₁) ((a, x) :: s₂) | swap (a₁ a₂ : R) (x₁ x₂ : X) (tail : FormalSum R X) : ElementaryMove R X ((a₁, x₁) :: (a₂, x₂) :: tail) ((a₂, x₂) :: (a₁, x₁) :: tail) def FreeModuleAux (R X : Type) [Ring R] [DecidableEq R][DecidableEq X] := Quot (ElementaryMove R X) namespace FormalSum /-- Image in the quotient (i.e., actual, not formal, sum). -/ def sum (s : FormalSum R X) : FreeModuleAux R X := Quot.mk (ElementaryMove R X) s /-- Equivalence by having the same image. -/ def equiv (s₁ s₂ : FormalSum R X) : Prop := s₁.sum = s₂.sum infix:65 " ≃ " => FormalSum.equiv /-! ### Invariance of coordinates under elementary moves -/ /-- Coordinates are invariant under moves. -/ theorem coords_move_invariant (x₀ : X) (s₁ s₂ : FormalSum R X) (h : ElementaryMove R X s₁ s₂) : coords s₁ x₀ = coords s₂ x₀ := by induction h with | zeroCoeff tail x a hyp => simp [coords, hyp, monom_coords_at_zero] | addCoeffs a b x tail => simp [coords, monom_coords_at_zero, ← add_assoc, monom_coords_hom] | cons a x s₁ s₂ _ step => simp [coords, step] | swap a₁ a₂ x₁ x₂ tail => simp [coords, ← add_assoc, add_comm] end FormalSum /-- Coordinates on the quotients. -/ def FreeModuleAux.coeff (x₀ : X) : FreeModuleAux R X → R := Quot.lift (fun s => s.coords x₀) (coords_move_invariant x₀) namespace FormalSum /-- Commutative diagram for coordinates. -/ theorem coeff_factors (x : X) (s : FormalSum R X) : FreeModuleAux.coeff x (sum s) = s.coords x := by simp [FreeModuleAux.coeff] apply @Quot.liftBeta (r := ElementaryMove R X) (f := fun s => s.coords x) apply coords_move_invariant /-- Coordinates well-defined under the equivalence generated by moves. -/ theorem coords_well_defined (x : X) (s₁ s₂ : FormalSum R X) : s₁ ≃ s₂ → s₁.coords x = s₂.coords x := by intro hyp have l : FreeModuleAux.coeff x (sum s₂) = s₂.coords x := by simp [coeff_factors, hyp] rw [← l] rw [← coeff_factors] rw [hyp] /-! ### Equal coordinates implies related by elementary moves. -/ /-- Cons respects equivalence. -/ theorem cons_equiv_of_equiv (s₁ s₂ : FormalSum R X) (a : R) (x : X) : s₁ ≃ s₂ → (a, x) :: s₁ ≃ (a, x) :: s₂ := by intro h let f : FormalSum R X → FreeModuleAux R X := fun s => sum <| (a, x) :: s let wit : (s₁ s₂ : FormalSum R X) → (ElementaryMove R X s₁ s₂) → f s₁ = f s₂ := by intro s₁ s₂ hyp apply Quot.sound apply ElementaryMove.cons assumption let g := Quot.lift f wit let factorizes : (s : FormalSum R X) → g (s.sum) = sum ((a, x) :: s) := Quot.liftBeta f wit rw [equiv] rw [← factorizes] rw [← factorizes] rw [h] /-- If a coordinate `x` for a formal sum `s` is non-zero, `s` is related by moves to a formal sum with first term `x` with coefficient its coordinates, and the rest shorter than `s`. -/ theorem nonzero_coeff_has_complement (x₀ : X)(s : FormalSum R X) : 0 ≠ s.coords x₀ → (∃ ys : FormalSum R X, (((s.coords x₀, x₀) :: ys) ≃ s) ∧ (List.length ys < s.length)) := by induction s with | nil => intro contra contradiction | cons head tail hyp => let (a, x) := head intro pos cases c : x == x₀ with | true => let k := FormalSum.coords tail x₀ have lem : a + k = coords ((a, x) :: tail) x₀ := by rw [coords, monomCoeff, c] have c'' : x = x₀ := of_decide_eq_true c rw [c''] rw [c''] at lem exact if c' : (0 = k) then by have lIneq : tail.length < List.length ((a, x) :: tail) := by simp [List.length_cons] rw [← c', add_zero] at lem rw [← lem] exact ⟨tail, rfl, lIneq⟩ else by let ⟨ys, eqnStep, lIneqStep⟩ := hyp c' have eqn₁ : (a, x₀) :: (k, x₀) :: ys ≃ (a + k, x₀) :: ys := by apply Quot.sound apply ElementaryMove.addCoeffs have eqn₂ : (a, x₀) :: (k, x₀) :: ys ≃ (a, x₀) :: tail := by apply cons_equiv_of_equiv assumption have eqn : (a + k, x₀) :: ys ≃ (a, x₀) :: tail := Eq.trans (Eq.symm eqn₁) eqn₂ rw [← lem] have lIneq : ys.length < List.length ((a, x₀) :: tail) := by apply Nat.le_trans lIneqStep simp [List.length_cons, Nat.le_succ] exact ⟨ys, eqn, lIneq⟩ | false => let k := coords tail x₀ have lem : k = coords ((a, x) :: tail) x₀ := by simp [coords, monomCoeff, c, zero_add] rw [← lem] at pos let ⟨ys', eqnStep, lIneqStep⟩ := hyp pos rw [← lem] let ys := (a, x) :: ys' have lIneq : ys.length < ((a, x) :: tail).length := by simp [List.length_cons] apply Nat.succ_lt_succ exact lIneqStep have eqn₁ : (k, x₀) :: ys ≃ (a, x) :: (k, x₀) :: ys' := by apply Quot.sound apply ElementaryMove.swap have eqn₂ : (a, x) :: (k, x₀) :: ys' ≃ (a, x) :: tail := by apply cons_equiv_of_equiv assumption have eqn : (k, x₀) :: ys ≃ (a, x) :: tail := by exact Eq.trans eqn₁ eqn₂ exact ⟨ys, eqn, lIneq⟩ /-- If all coordinates are zero, then moves relate to the empty sum. -/ theorem equiv_e_of_zero_coeffs (s : FormalSum R X) (hyp : ∀ x : X, s.coords x = 0) : s ≃ [] := -- let canc : IsAddLeftCancel R := -- ⟨fun a b c h => by -- rw [← neg_add_cancel_left a b, h, neg_add_cancel_left]⟩ match mt : s with | [] => rfl | h :: t => by let (a₀, x₀) := h let hyp₀ := hyp x₀ rw [coords] at hyp₀ have c₀ : monomCoeff R X x₀ (a₀, x₀) = a₀ := by simp [monomCoeff] rw [c₀] at hyp₀ exact if hz : a₀ = 0 then by rw [hz] at hyp₀ rw [zero_add] at hyp₀ have tail_coeffs : ∀ x : X, coords t x = 0 := by intro x simp [coords] exact if c : (x₀ = x) then by rw [← c] assumption else by let hx := hyp x simp [coords, monomCoeff] at hx have lf : (x₀ == x) = false := decide_eq_false c rw [lf] at hx simp [zero_add] at hx assumption have _ : t.length < (h :: t).length := by simp [List.length_cons] let step : t ≃ [] := by apply equiv_e_of_zero_coeffs exact tail_coeffs rw [hz] have ls : (0, x₀) :: t ≃ t := by apply Quot.sound apply ElementaryMove.zeroCoeff rfl exact Eq.trans ls step else by have non_zero : 0 ≠ coords t x₀ := by intro contra' let contra := Eq.symm contra' rw [contra, add_zero] at hyp₀ contradiction let ⟨ys, eqnStep, lIneqStep⟩ := nonzero_coeff_has_complement x₀ t non_zero have tail_coeffs : ∀ x : X, coords ys x = 0 := by intro x simp [coords] exact if c : (x₀ = x) then by rw [← c] let ceq := coords_well_defined x₀ _ _ eqnStep simp [coords, monomCoeff] at ceq assumption else by let hx := hyp x simp [coords, monomCoeff] at hx have lf : (x₀ == x) = false := decide_eq_false c rw [lf] at hx simp [zero_add] at hx let ceq := coords_well_defined x _ _ eqnStep simp [coords, monomCoeff, lf] at ceq rw [hx] at ceq exact ceq have _ : ys.length < (h :: t).length := by simp [List.length_cons] apply Nat.le_trans lIneqStep apply Nat.le_succ let step : ys ≃ [] := by apply equiv_e_of_zero_coeffs exact tail_coeffs let eqn₁ := cons_equiv_of_equiv _ _ (coords t x₀) x₀ step let eqn₂ : t ≃ (coords t x₀, x₀) :: [] := Eq.trans (Eq.symm eqnStep) eqn₁ let eqn₃ := cons_equiv_of_equiv _ _ a₀ x₀ eqn₂ apply Eq.trans eqn₃ have eqn₄ : sum [(a₀, x₀), (coords t x₀, x₀)] = sum [(a₀ + coords t x₀, x₀)] := by apply Quot.sound apply ElementaryMove.addCoeffs apply Eq.trans eqn₄ rw [hyp₀] apply Quot.sound apply ElementaryMove.zeroCoeff rfl termination_by _ R X s h => s.length decreasing_by assumption /-- If coordinates are equal, the sums are related by moves. -/ theorem equiv_of_equal_coeffs (s₁ s₂ : FormalSum R X) (hyp : ∀ x : X, s₁.coords x = s₂.coords x) : s₁ ≃ s₂ := match s₁ with | [] => have coeffs : ∀ x : X, s₂.coords x = 0 := by intro x let h := hyp x rw [← h] rfl let zl := equiv_e_of_zero_coeffs s₂ coeffs Eq.symm zl | h :: t => let (a₀, x₀) := h by exact if p : 0 = a₀ then by have eq₁ : (a₀, x₀) :: t ≃ t := by apply Quot.sound apply ElementaryMove.zeroCoeff apply Eq.symm assumption have _ : t.length < (h :: t).length := by simp [List.length_cons] have eq₂ : t ≃ s₂ := by apply equiv_of_equal_coeffs t s₂ intro x let ceq := coords_well_defined x ((a₀, x₀) :: t) t eq₁ simp [← ceq, hyp] exact Eq.trans eq₁ eq₂ else by let a₁ := coords t x₀ exact if p₁ : 0 = a₁ then by have cf₂ : s₂.coords x₀ = a₀ := by rw [← hyp] simp [coords, ← p₁, Nat.add_zero, monomCoeff] let ⟨ys, eqn, _⟩ := nonzero_coeff_has_complement x₀ s₂ (by rw [cf₂] assumption) let cfs := fun x => coords_well_defined x _ _ eqn rw [cf₂] at cfs let cfs' := fun (x : X) => Eq.trans (hyp x) (Eq.symm (cfs x)) simp [coords] at cfs' have _ : t.length < (h :: t).length := by simp [List.length_cons] let step := equiv_of_equal_coeffs t ys cfs' let _step' := cons_equiv_of_equiv t ys a₀ x₀ step rw [cf₂] at eqn exact Eq.trans _step' eqn else by let ⟨ys, eqn, ineqn⟩ := nonzero_coeff_has_complement x₀ t p₁ let s₃ := (a₀ + a₁, x₀) :: ys have eq₁ : (a₀, x₀) :: (a₁, x₀) :: ys ≃ s₃ := by apply Quot.sound let lem := ElementaryMove.addCoeffs a₀ a₁ x₀ ys exact lem have eq₂ : (a₀, x₀) :: (a₁, x₀) :: ys ≃ (a₀, x₀) :: t := by apply cons_equiv_of_equiv assumption have eq₃ : s₃ ≃ s₂ := by have _ : ys.length + 1 < t.length + 1 := by apply Nat.succ_lt_succ exact ineqn apply equiv_of_equal_coeffs intro x rw [← hyp x] simp [coords] let d := coords_well_defined x _ _ eqn rw [coords] at d rw [← d] simp [monom_coords_hom, coords, add_assoc] apply Eq.trans (Eq.trans (Eq.symm eq₂) eq₁) eq₃ termination_by _ R X s _ _ => s.length decreasing_by assumption /-! ## Functions invariant under moves pass to the quotient. -/ /-- Lifting functions to the move induced quotient. -/ theorem func_eql_of_move_equiv {β : Sort u} (f : FormalSum R X → β) : (∀ s₁ s₂ : FormalSum R X, ElementaryMove R X s₁ s₂ → f s₁ = f s₂) → (∀ s₁ s₂ : FormalSum R X, s₁ ≈ s₂ → f s₁ = f s₂) := by intro hyp let fbar : FreeModuleAux R X → β := Quot.lift f hyp let fct : ∀ s : FormalSum R X, f s = fbar (sum s) := by apply Quot.liftBeta apply hyp intro s₁ s₂ sim have ec : eqlCoords R X s₁ s₂ := sim rw [eqlCoords] at ec have pullback : sum s₁ = sum s₂ := by apply equiv_of_equal_coeffs intro x exact congrFun ec x simp [fct, pullback] end FormalSum end ElementaryMoves section Injectivity /-! ## Injectivity of inclusions We show that, under appropriate hypotheses, two inclusions into Free Modules are injective. * If `a : R` is nonzero, then `x : X ↦ ⟦[(a, x)]⟧` is injective. * If `x: X`, then `a : R ↦ ⟦[(a, x)]⟧` is injective. These are used in proving injectivity results for related functions on group rings, which act as a check on the correctness of the definitions. -/ open FormalSum /-- For `a: R` and `a ≠ 0`, injectivity of the the function `x: X ↦ [(a, x)]` up to equivalence -/ theorem monom_elem_eq_of_coord_eq_nonzero (a : R)(non_zero: a ≠ 0) (x₀ x₁ : X) : coords [(a, x₀)] = coords [(a, x₁)] → x₀ = x₁ := by intro hyp have sup₀ : support [(a, x₀)] = [x₀] := by rfl have c₁ : coords [(a, x₁)] x₁ = a := by simp [coords, monomCoeff] rw [← c₁] at non_zero symm at non_zero rw [← hyp] at non_zero let lem := nonzero_coord_in_support [(a, x₀)] x₁ non_zero simp [support] at lem apply Eq.symm assumption /-- For `x : X`, injectivity of the the function `a: R ↦ [(a, x)]` up to equivalence -/ theorem monom_coeff_eq_of_coord_eq (x : X) (a₀ a₁ : R) : coords [(a₀, x)] = coords [(a₁, x)] → a₀ = a₁ := by intro hyp let h₁ := congrFun hyp x simp [coords, monomCoeff] at h₁ assumption /-- For `x: X`, the functions `a : R ↦ ⟦[(a, x)]⟧`-/ def coeffInclusion (x₀ : X) : R → R[X] := fun a₀ => ⟦[(a₀, x₀)]⟧ /-- Injectivity of `coeffInclusion` -/ theorem coeffInclusion_injective (x₀ : X) (a₀ a₁ : R) : coeffInclusion x₀ a₀ = coeffInclusion x₀ a₁ → a₀ = a₁ := by intro hyp simp [coeffInclusion] at hyp exact monom_coeff_eq_of_coord_eq x₀ a₀ a₁ hyp /-- For `a: A`, the function `x: X ↦ ⟦[(a, x)]⟧`-/ def baseInclusion (a₀ : R) : X → R[X] := fun x₀ => ⟦[(a₀, x₀)]⟧ /-- Injectivity of `baseInclusion a` give `a ≠0` -/ theorem baseInclusion_injective (a₀ : R) (non_zero : a₀ ≠ 0) (x₀ x₁ : X) : baseInclusion a₀ x₀ = baseInclusion a₀ x₁ → x₀ = x₁ := by intro hyp simp [baseInclusion] at hyp exact monom_elem_eq_of_coord_eq_nonzero a₀ non_zero x₀ x₁ hyp end Injectivity section NormRepr /-! ## Basic `Repr` An instance of `Repr` on Free Modules, mainly for debugging (fairly crude). This is implemented by constructing a norm ball containing all the non-zero coordinates, and then making a list of non-zero coordinates -/ theorem fst_le_max (a b : Nat): a ≤ max a b := by simp [max] exact if c:a ≤ b then by unfold max unfold Nat.instMaxNat unfold maxOfLe simp [if_pos c] assumption else by unfold max unfold Nat.instMaxNat unfold maxOfLe simp [if_neg c] theorem snd_le_max (a b : Nat): b ≤ max a b := by simp [max] exact if c: a ≤ b then by unfold max unfold Nat.instMaxNat unfold maxOfLe simp [if_pos c] else by unfold max unfold Nat.instMaxNat unfold maxOfLe simp [if_neg c] apply Nat.le_of_lt let c' := Nat.gt_of_not_le c assumption theorem eq_fst_or_snd_of_max (a b : Nat) : (max a b = a) ∨ (max a b = b) := by simp [max] exact if c: a ≤ b then by unfold max unfold Nat.instMaxNat unfold maxOfLe simp [if_pos c] else by unfold max unfold Nat.instMaxNat unfold maxOfLe simp [if_neg c] def maxNormSuccOnSupp (norm: X → Nat)(crds : X → R)(s: List X) : Nat := match s with | [] => 0 | head :: tail => if crds head ≠ 0 then max (norm head + 1) (maxNormSuccOnSupp norm crds tail) else maxNormSuccOnSupp norm crds tail theorem max_in_support (norm: X → Nat)(crds : X → R)(s: List X) : maxNormSuccOnSupp norm crds s > 0 → ∃ x : X, crds x ≠ 0 ∧ maxNormSuccOnSupp norm crds s = norm x + 1 := by intro h induction s with | nil => simp [maxNormSuccOnSupp] at h | cons head tail ih => exact if c : crds head =0 then by simp [maxNormSuccOnSupp, c] simp [maxNormSuccOnSupp, c] at h exact ih h else by simp [maxNormSuccOnSupp, c] simp [maxNormSuccOnSupp, c] at h let sl := eq_fst_or_snd_of_max (norm head + 1) (maxNormSuccOnSupp norm crds tail) cases sl case inr p => rw [p] rw [p] at h exact ih h case inl p => rw [p] rw [p] at h exact ⟨head, And.intro c rfl⟩ theorem supp_below_max(norm: X → Nat)(crds : X → R)(s: List X) : (x: X) → x ∈ s → crds x ≠ 0 → norm x + 1 ≤ maxNormSuccOnSupp norm crds s := by intro x h₁ h₂ cases h₁ case head as => rw [maxNormSuccOnSupp] simp [h₂] apply fst_le_max case tail a as th => rw [maxNormSuccOnSupp] let l := supp_below_max norm crds as x th h₂ exact if c:crds a ≠ 0 then by simp [c] apply Nat.le_trans l apply snd_le_max else by simp [c] exact l theorem supp_zero_of_max_zero(norm: X → Nat)(crds : X → R)(s: List X) : maxNormSuccOnSupp norm crds s = 0 → (x: X) → x ∈ s → crds x = 0 := fun hyp x hm => if c:crds x = 0 then c else by simp let l := supp_below_max norm crds s x hm c rw [hyp] at l contradiction def FormalSum.normSucc (norm : X → Nat)(s: FormalSum R X) : Nat := maxNormSuccOnSupp norm s.coords (s.support) open FormalSum theorem normsucc_le(norm : X → Nat)(s₁ s₂: FormalSum R X)(eql : s₁ ≈ s₂): s₁.normSucc norm ≤ s₂.normSucc norm := if c:s₁.normSucc norm = 0 then by rw [c] apply Nat.zero_le else by simp [FormalSum.normSucc] simp [FormalSum.normSucc] at c let c' : maxNormSuccOnSupp norm (coords s₁) (support s₁) > 0 := by cases Nat.eq_zero_or_pos (maxNormSuccOnSupp norm (coords s₁) (support s₁)) contradiction assumption let l := max_in_support norm s₁.coords s₁.support c' let ⟨x₀, p⟩:= l let nonzr' := p.left let l := congrFun eql x₀ rw [l] at nonzr' let nonzr : 0 ≠ s₂.coords x₀ := by intro hyp let l' := Eq.symm hyp contradiction let in_supp := nonzero_coord_in_support s₂ x₀ nonzr rw [p.right] simp apply supp_below_max norm s₂.coords s₂.support x₀ in_supp nonzr' theorem norm_succ_eq(norm : X → Nat)(s₁ s₂: FormalSum R X)(eql : s₁ ≈ s₂): s₁.normSucc norm = s₂.normSucc norm := by apply Nat.le_antisymm <;> apply normsucc_le assumption apply eqlCoords.symm assumption class NormCube (α : Type) where norm : α → Nat cube : Nat → List α def normCube (α : Type) [nc : NormCube α](k: Nat) := nc.cube k instance natCube : NormCube Nat := ⟨id, fun n => (List.range n).reverse⟩ instance finCube {k: Nat} : NormCube (Fin (Nat.succ k)) := let i : Nat → Fin (Nat.succ k) := fun n => ⟨n % (Nat.succ k), by apply Nat.mod_lt apply Nat.zero_lt_succ ⟩ ⟨fun j => j.val, fun n => (List.range (min (k + 1) n)).reverse.map i⟩ instance intCube : NormCube ℤ where norm := Int.natAbs cube : Nat → List ℤ := fun n => (List.range (n)).reverse.map (Int.ofNat) ++ (List.range (n - 1)).map (Int.negSucc) instance prodCube {α β : Type} [na: NormCube α] [nb :NormCube β] : NormCube (α × β) where norm : (α × β) → Nat := fun ⟨a, b⟩ => max (na.norm a) (nb.norm b) cube : Nat → List (α × β) := fun n => (na.cube n).bind (fun a => (nb.cube n).map (fun b => (a, b))) def FreeModule.normBound (x: R[X])[nx : NormCube X] : Nat := by let f : FormalSum R X → Nat := fun s => s.normSucc (nx.norm) apply Quotient.lift f apply norm_succ_eq exact x -- this should be viewable directly if `R` and `X` are, as in our case def FreeModule.coeffList (x: R[X])[nx : NormCube X] : List (R × X) := (nx.cube (x.normBound)).filterMap fun x₀ => let a := x.coordinates x₀ if a =0 then none else some (a, x₀) -- basic repr instance basicRepr [NormCube X][Repr X][Repr R]: Repr (R[X]) := ⟨fun x _ => reprStr (x.coeffList)⟩ end NormRepr
[STATEMENT] lemma eexp_ereal [simp]: "eexp(ereal x) = ereal(exp x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. eexp (ereal x) = ereal (exp x) [PROOF STEP] by (simp add: eexp_def)
close all; clear all; clc; data_file_path = 'bin/ols_phase_transition_gaussian_dict_gaussian_data.mat'; options.export = false; options.export_dir = 'bin'; options.export_name = 'gaussian_dict_gaussian_data'; options.chosen_ks = [2, 4, 8, 16, 32, 64]; spx.pursuit.PhaseTransitionAnalysis.print_results(data_file_path, ... 'OLS', options);
(* Title: HOL/Equiv_Relations.thy Author: Lawrence C Paulson, 1996 Cambridge University Computer Laboratory *) section \<open>Equivalence Relations in Higher-Order Set Theory\<close> theory Equiv_Relations imports BNF_Least_Fixpoint begin subsection \<open>Equivalence relations -- set version\<close> definition equiv :: "'a set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> bool" where "equiv A r \<longleftrightarrow> refl_on A r \<and> sym r \<and> trans r" lemma equivI: "refl_on A r \<Longrightarrow> sym r \<Longrightarrow> trans r \<Longrightarrow> equiv A r" by (simp add: equiv_def) lemma equivE: assumes "equiv A r" obtains "refl_on A r" and "sym r" and "trans r" using assms by (simp add: equiv_def) text \<open> Suppes, Theorem 70: \<open>r\<close> is an equiv relation iff \<open>r\<inverse> O r = r\<close>. First half: \<open>equiv A r \<Longrightarrow> r\<inverse> O r = r\<close>. \<close> lemma sym_trans_comp_subset: "sym r \<Longrightarrow> trans r \<Longrightarrow> r\<inverse> O r \<subseteq> r" unfolding trans_def sym_def converse_unfold by blast lemma refl_on_comp_subset: "refl_on A r \<Longrightarrow> r \<subseteq> r\<inverse> O r" unfolding refl_on_def by blast lemma equiv_comp_eq: "equiv A r \<Longrightarrow> r\<inverse> O r = r" unfolding equiv_def by (iprover intro: sym_trans_comp_subset refl_on_comp_subset equalityI) text \<open>Second half.\<close> lemma comp_equivI: assumes "r\<inverse> O r = r" "Domain r = A" shows "equiv A r" proof - have *: "\<And>x y. (x, y) \<in> r \<Longrightarrow> (y, x) \<in> r" using assms by blast show ?thesis unfolding equiv_def refl_on_def sym_def trans_def using assms by (auto intro: *) qed subsection \<open>Equivalence classes\<close> lemma equiv_class_subset: "equiv A r \<Longrightarrow> (a, b) \<in> r \<Longrightarrow> r``{a} \<subseteq> r``{b}" \<comment> \<open>lemma for the next result\<close> unfolding equiv_def trans_def sym_def by blast theorem equiv_class_eq: "equiv A r \<Longrightarrow> (a, b) \<in> r \<Longrightarrow> r``{a} = r``{b}" by (intro equalityI equiv_class_subset; force simp add: equiv_def sym_def) lemma equiv_class_self: "equiv A r \<Longrightarrow> a \<in> A \<Longrightarrow> a \<in> r``{a}" unfolding equiv_def refl_on_def by blast lemma subset_equiv_class: "equiv A r \<Longrightarrow> r``{b} \<subseteq> r``{a} \<Longrightarrow> b \<in> A \<Longrightarrow> (a, b) \<in> r" \<comment> \<open>lemma for the next result\<close> unfolding equiv_def refl_on_def by blast lemma eq_equiv_class: "r``{a} = r``{b} \<Longrightarrow> equiv A r \<Longrightarrow> b \<in> A \<Longrightarrow> (a, b) \<in> r" by (iprover intro: equalityD2 subset_equiv_class) lemma equiv_class_nondisjoint: "equiv A r \<Longrightarrow> x \<in> (r``{a} \<inter> r``{b}) \<Longrightarrow> (a, b) \<in> r" unfolding equiv_def trans_def sym_def by blast lemma equiv_type: "equiv A r \<Longrightarrow> r \<subseteq> A \<times> A" unfolding equiv_def refl_on_def by blast lemma equiv_class_eq_iff: "equiv A r \<Longrightarrow> (x, y) \<in> r \<longleftrightarrow> r``{x} = r``{y} \<and> x \<in> A \<and> y \<in> A" by (blast intro!: equiv_class_eq dest: eq_equiv_class equiv_type) lemma eq_equiv_class_iff: "equiv A r \<Longrightarrow> x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> r``{x} = r``{y} \<longleftrightarrow> (x, y) \<in> r" by (blast intro!: equiv_class_eq dest: eq_equiv_class equiv_type) lemma disjnt_equiv_class: "equiv A r \<Longrightarrow> disjnt (r``{a}) (r``{b}) \<longleftrightarrow> (a, b) \<notin> r" by (auto dest: equiv_class_self simp: equiv_class_eq_iff disjnt_def) subsection \<open>Quotients\<close> definition quotient :: "'a set \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> 'a set set" (infixl "'/'/" 90) where "A//r = (\<Union>x \<in> A. {r``{x}})" \<comment> \<open>set of equiv classes\<close> lemma quotientI: "x \<in> A \<Longrightarrow> r``{x} \<in> A//r" unfolding quotient_def by blast lemma quotientE: "X \<in> A//r \<Longrightarrow> (\<And>x. X = r``{x} \<Longrightarrow> x \<in> A \<Longrightarrow> P) \<Longrightarrow> P" unfolding quotient_def by blast lemma Union_quotient: "equiv A r \<Longrightarrow> \<Union>(A//r) = A" unfolding equiv_def refl_on_def quotient_def by blast lemma quotient_disj: "equiv A r \<Longrightarrow> X \<in> A//r \<Longrightarrow> Y \<in> A//r \<Longrightarrow> X = Y \<or> X \<inter> Y = {}" unfolding quotient_def equiv_def trans_def sym_def by blast lemma quotient_eqI: assumes "equiv A r" "X \<in> A//r" "Y \<in> A//r" and xy: "x \<in> X" "y \<in> Y" "(x, y) \<in> r" shows "X = Y" proof - obtain a b where "a \<in> A" and a: "X = r `` {a}" and "b \<in> A" and b: "Y = r `` {b}" using assms by (auto elim!: quotientE) then have "(a,b) \<in> r" using xy \<open>equiv A r\<close> unfolding equiv_def sym_def trans_def by blast then show ?thesis unfolding a b by (rule equiv_class_eq [OF \<open>equiv A r\<close>]) qed lemma quotient_eq_iff: assumes "equiv A r" "X \<in> A//r" "Y \<in> A//r" and xy: "x \<in> X" "y \<in> Y" shows "X = Y \<longleftrightarrow> (x, y) \<in> r" proof assume L: "X = Y" with assms show "(x, y) \<in> r" unfolding equiv_def sym_def trans_def by (blast elim!: quotientE) next assume \<section>: "(x, y) \<in> r" show "X = Y" by (rule quotient_eqI) (use \<section> assms in \<open>blast+\<close>) qed lemma eq_equiv_class_iff2: "equiv A r \<Longrightarrow> x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> {x}//r = {y}//r \<longleftrightarrow> (x, y) \<in> r" by (simp add: quotient_def eq_equiv_class_iff) lemma quotient_empty [simp]: "{}//r = {}" by (simp add: quotient_def) lemma quotient_is_empty [iff]: "A//r = {} \<longleftrightarrow> A = {}" by (simp add: quotient_def) lemma quotient_is_empty2 [iff]: "{} = A//r \<longleftrightarrow> A = {}" by (simp add: quotient_def) lemma singleton_quotient: "{x}//r = {r `` {x}}" by (simp add: quotient_def) lemma quotient_diff1: "inj_on (\<lambda>a. {a}//r) A \<Longrightarrow> a \<in> A \<Longrightarrow> (A - {a})//r = A//r - {a}//r" unfolding quotient_def inj_on_def by blast subsection \<open>Refinement of one equivalence relation WRT another\<close> lemma refines_equiv_class_eq: "R \<subseteq> S \<Longrightarrow> equiv A R \<Longrightarrow> equiv A S \<Longrightarrow> R``(S``{a}) = S``{a}" by (auto simp: equiv_class_eq_iff) lemma refines_equiv_class_eq2: "R \<subseteq> S \<Longrightarrow> equiv A R \<Longrightarrow> equiv A S \<Longrightarrow> S``(R``{a}) = S``{a}" by (auto simp: equiv_class_eq_iff) lemma refines_equiv_image_eq: "R \<subseteq> S \<Longrightarrow> equiv A R \<Longrightarrow> equiv A S \<Longrightarrow> (\<lambda>X. S``X) ` (A//R) = A//S" by (auto simp: quotient_def image_UN refines_equiv_class_eq2) lemma finite_refines_finite: "finite (A//R) \<Longrightarrow> R \<subseteq> S \<Longrightarrow> equiv A R \<Longrightarrow> equiv A S \<Longrightarrow> finite (A//S)" by (erule finite_surj [where f = "\<lambda>X. S``X"]) (simp add: refines_equiv_image_eq) lemma finite_refines_card_le: "finite (A//R) \<Longrightarrow> R \<subseteq> S \<Longrightarrow> equiv A R \<Longrightarrow> equiv A S \<Longrightarrow> card (A//S) \<le> card (A//R)" by (subst refines_equiv_image_eq [of R S A, symmetric]) (auto simp: card_image_le [where f = "\<lambda>X. S``X"]) subsection \<open>Defining unary operations upon equivalence classes\<close> text \<open>A congruence-preserving function.\<close> definition congruent :: "('a \<times> 'a) set \<Rightarrow> ('a \<Rightarrow> 'b) \<Rightarrow> bool" where "congruent r f \<longleftrightarrow> (\<forall>(y, z) \<in> r. f y = f z)" lemma congruentI: "(\<And>y z. (y, z) \<in> r \<Longrightarrow> f y = f z) \<Longrightarrow> congruent r f" by (auto simp add: congruent_def) lemma congruentD: "congruent r f \<Longrightarrow> (y, z) \<in> r \<Longrightarrow> f y = f z" by (auto simp add: congruent_def) abbreviation RESPECTS :: "('a \<Rightarrow> 'b) \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> bool" (infixr "respects" 80) where "f respects r \<equiv> congruent r f" lemma UN_constant_eq: "a \<in> A \<Longrightarrow> \<forall>y \<in> A. f y = c \<Longrightarrow> (\<Union>y \<in> A. f y) = c" \<comment> \<open>lemma required to prove \<open>UN_equiv_class\<close>\<close> by auto lemma UN_equiv_class: assumes "equiv A r" "f respects r" "a \<in> A" shows "(\<Union>x \<in> r``{a}. f x) = f a" \<comment> \<open>Conversion rule\<close> proof - have \<section>: "\<forall>x\<in>r `` {a}. f x = f a" using assms unfolding equiv_def congruent_def sym_def by blast show ?thesis by (iprover intro: assms UN_constant_eq [OF equiv_class_self \<section>]) qed lemma UN_equiv_class_type: assumes r: "equiv A r" "f respects r" and X: "X \<in> A//r" and AB: "\<And>x. x \<in> A \<Longrightarrow> f x \<in> B" shows "(\<Union>x \<in> X. f x) \<in> B" using assms unfolding quotient_def by (auto simp: UN_equiv_class [OF r]) text \<open> Sufficient conditions for injectiveness. Could weaken premises! major premise could be an inclusion; \<open>bcong\<close> could be \<open>\<And>y. y \<in> A \<Longrightarrow> f y \<in> B\<close>. \<close> lemma UN_equiv_class_inject: assumes "equiv A r" "f respects r" and eq: "(\<Union>x \<in> X. f x) = (\<Union>y \<in> Y. f y)" and X: "X \<in> A//r" and Y: "Y \<in> A//r" and fr: "\<And>x y. x \<in> A \<Longrightarrow> y \<in> A \<Longrightarrow> f x = f y \<Longrightarrow> (x, y) \<in> r" shows "X = Y" proof - obtain a b where "a \<in> A" and a: "X = r `` {a}" and "b \<in> A" and b: "Y = r `` {b}" using assms by (auto elim!: quotientE) then have "\<Union> (f ` r `` {a}) = f a" "\<Union> (f ` r `` {b}) = f b" by (iprover intro: UN_equiv_class [OF \<open>equiv A r\<close>] assms)+ then have "f a = f b" using eq unfolding a b by (iprover intro: trans sym) then have "(a,b) \<in> r" using fr \<open>a \<in> A\<close> \<open>b \<in> A\<close> by blast then show ?thesis unfolding a b by (rule equiv_class_eq [OF \<open>equiv A r\<close>]) qed subsection \<open>Defining binary operations upon equivalence classes\<close> text \<open>A congruence-preserving function of two arguments.\<close> definition congruent2 :: "('a \<times> 'a) set \<Rightarrow> ('b \<times> 'b) set \<Rightarrow> ('a \<Rightarrow> 'b \<Rightarrow> 'c) \<Rightarrow> bool" where "congruent2 r1 r2 f \<longleftrightarrow> (\<forall>(y1, z1) \<in> r1. \<forall>(y2, z2) \<in> r2. f y1 y2 = f z1 z2)" lemma congruent2I': assumes "\<And>y1 z1 y2 z2. (y1, z1) \<in> r1 \<Longrightarrow> (y2, z2) \<in> r2 \<Longrightarrow> f y1 y2 = f z1 z2" shows "congruent2 r1 r2 f" using assms by (auto simp add: congruent2_def) lemma congruent2D: "congruent2 r1 r2 f \<Longrightarrow> (y1, z1) \<in> r1 \<Longrightarrow> (y2, z2) \<in> r2 \<Longrightarrow> f y1 y2 = f z1 z2" by (auto simp add: congruent2_def) text \<open>Abbreviation for the common case where the relations are identical.\<close> abbreviation RESPECTS2:: "('a \<Rightarrow> 'a \<Rightarrow> 'b) \<Rightarrow> ('a \<times> 'a) set \<Rightarrow> bool" (infixr "respects2" 80) where "f respects2 r \<equiv> congruent2 r r f" lemma congruent2_implies_congruent: "equiv A r1 \<Longrightarrow> congruent2 r1 r2 f \<Longrightarrow> a \<in> A \<Longrightarrow> congruent r2 (f a)" unfolding congruent_def congruent2_def equiv_def refl_on_def by blast lemma congruent2_implies_congruent_UN: assumes "equiv A1 r1" "equiv A2 r2" "congruent2 r1 r2 f" "a \<in> A2" shows "congruent r1 (\<lambda>x1. \<Union>x2 \<in> r2``{a}. f x1 x2)" unfolding congruent_def proof clarify fix c d assume cd: "(c,d) \<in> r1" then have "c \<in> A1" "d \<in> A1" using \<open>equiv A1 r1\<close> by (auto elim!: equiv_type [THEN subsetD, THEN SigmaE2]) moreover have "f c a = f d a" using assms cd unfolding congruent2_def equiv_def refl_on_def by blast ultimately show "\<Union> (f c ` r2 `` {a}) = \<Union> (f d ` r2 `` {a})" using assms by (simp add: UN_equiv_class congruent2_implies_congruent) qed lemma UN_equiv_class2: "equiv A1 r1 \<Longrightarrow> equiv A2 r2 \<Longrightarrow> congruent2 r1 r2 f \<Longrightarrow> a1 \<in> A1 \<Longrightarrow> a2 \<in> A2 \<Longrightarrow> (\<Union>x1 \<in> r1``{a1}. \<Union>x2 \<in> r2``{a2}. f x1 x2) = f a1 a2" by (simp add: UN_equiv_class congruent2_implies_congruent congruent2_implies_congruent_UN) lemma UN_equiv_class_type2: "equiv A1 r1 \<Longrightarrow> equiv A2 r2 \<Longrightarrow> congruent2 r1 r2 f \<Longrightarrow> X1 \<in> A1//r1 \<Longrightarrow> X2 \<in> A2//r2 \<Longrightarrow> (\<And>x1 x2. x1 \<in> A1 \<Longrightarrow> x2 \<in> A2 \<Longrightarrow> f x1 x2 \<in> B) \<Longrightarrow> (\<Union>x1 \<in> X1. \<Union>x2 \<in> X2. f x1 x2) \<in> B" unfolding quotient_def by (blast intro: UN_equiv_class_type congruent2_implies_congruent_UN congruent2_implies_congruent quotientI) lemma UN_UN_split_split_eq: "(\<Union>(x1, x2) \<in> X. \<Union>(y1, y2) \<in> Y. A x1 x2 y1 y2) = (\<Union>x \<in> X. \<Union>y \<in> Y. (\<lambda>(x1, x2). (\<lambda>(y1, y2). A x1 x2 y1 y2) y) x)" \<comment> \<open>Allows a natural expression of binary operators,\<close> \<comment> \<open>without explicit calls to \<open>split\<close>\<close> by auto lemma congruent2I: "equiv A1 r1 \<Longrightarrow> equiv A2 r2 \<Longrightarrow> (\<And>y z w. w \<in> A2 \<Longrightarrow> (y,z) \<in> r1 \<Longrightarrow> f y w = f z w) \<Longrightarrow> (\<And>y z w. w \<in> A1 \<Longrightarrow> (y,z) \<in> r2 \<Longrightarrow> f w y = f w z) \<Longrightarrow> congruent2 r1 r2 f" \<comment> \<open>Suggested by John Harrison -- the two subproofs may be\<close> \<comment> \<open>\<^emph>\<open>much\<close> simpler than the direct proof.\<close> unfolding congruent2_def equiv_def refl_on_def by (blast intro: trans) lemma congruent2_commuteI: assumes equivA: "equiv A r" and commute: "\<And>y z. y \<in> A \<Longrightarrow> z \<in> A \<Longrightarrow> f y z = f z y" and congt: "\<And>y z w. w \<in> A \<Longrightarrow> (y,z) \<in> r \<Longrightarrow> f w y = f w z" shows "f respects2 r" proof (rule congruent2I [OF equivA equivA]) note eqv = equivA [THEN equiv_type, THEN subsetD, THEN SigmaE2] show "\<And>y z w. \<lbrakk>w \<in> A; (y, z) \<in> r\<rbrakk> \<Longrightarrow> f y w = f z w" by (iprover intro: commute [THEN trans] sym congt elim: eqv) show "\<And>y z w. \<lbrakk>w \<in> A; (y, z) \<in> r\<rbrakk> \<Longrightarrow> f w y = f w z" by (iprover intro: congt elim: eqv) qed subsection \<open>Quotients and finiteness\<close> text \<open>Suggested by Florian Kammüller\<close> lemma finite_quotient: assumes "finite A" "r \<subseteq> A \<times> A" shows "finite (A//r)" \<comment> \<open>recall @{thm equiv_type}\<close> proof - have "A//r \<subseteq> Pow A" using assms unfolding quotient_def by blast moreover have "finite (Pow A)" using assms by simp ultimately show ?thesis by (iprover intro: finite_subset) qed lemma finite_equiv_class: "finite A \<Longrightarrow> r \<subseteq> A \<times> A \<Longrightarrow> X \<in> A//r \<Longrightarrow> finite X" unfolding quotient_def by (erule rev_finite_subset) blast lemma equiv_imp_dvd_card: assumes "finite A" "equiv A r" "\<And>X. X \<in> A//r \<Longrightarrow> k dvd card X" shows "k dvd card A" proof (rule Union_quotient [THEN subst]) show "k dvd card (\<Union> (A // r))" apply (rule dvd_partition) using assms by (auto simp: Union_quotient dest: quotient_disj) qed (use assms in blast) subsection \<open>Projection\<close> definition proj :: "('b \<times> 'a) set \<Rightarrow> 'b \<Rightarrow> 'a set" where "proj r x = r `` {x}" lemma proj_preserves: "x \<in> A \<Longrightarrow> proj r x \<in> A//r" unfolding proj_def by (rule quotientI) lemma proj_in_iff: assumes "equiv A r" shows "proj r x \<in> A//r \<longleftrightarrow> x \<in> A" (is "?lhs \<longleftrightarrow> ?rhs") proof assume ?rhs then show ?lhs by (simp add: proj_preserves) next assume ?lhs then show ?rhs unfolding proj_def quotient_def proof safe fix y assume y: "y \<in> A" and "r `` {x} = r `` {y}" moreover have "y \<in> r `` {y}" using assms y unfolding equiv_def refl_on_def by blast ultimately have "(x, y) \<in> r" by blast then show "x \<in> A" using assms unfolding equiv_def refl_on_def by blast qed qed lemma proj_iff: "equiv A r \<Longrightarrow> {x, y} \<subseteq> A \<Longrightarrow> proj r x = proj r y \<longleftrightarrow> (x, y) \<in> r" by (simp add: proj_def eq_equiv_class_iff) (* lemma in_proj: "\<lbrakk>equiv A r; x \<in> A\<rbrakk> \<Longrightarrow> x \<in> proj r x" unfolding proj_def equiv_def refl_on_def by blast *) lemma proj_image: "proj r ` A = A//r" unfolding proj_def[abs_def] quotient_def by blast lemma in_quotient_imp_non_empty: "equiv A r \<Longrightarrow> X \<in> A//r \<Longrightarrow> X \<noteq> {}" unfolding quotient_def using equiv_class_self by fast lemma in_quotient_imp_in_rel: "equiv A r \<Longrightarrow> X \<in> A//r \<Longrightarrow> {x, y} \<subseteq> X \<Longrightarrow> (x, y) \<in> r" using quotient_eq_iff[THEN iffD1] by fastforce lemma in_quotient_imp_closed: "equiv A r \<Longrightarrow> X \<in> A//r \<Longrightarrow> x \<in> X \<Longrightarrow> (x, y) \<in> r \<Longrightarrow> y \<in> X" unfolding quotient_def equiv_def trans_def by blast lemma in_quotient_imp_subset: "equiv A r \<Longrightarrow> X \<in> A//r \<Longrightarrow> X \<subseteq> A" using in_quotient_imp_in_rel equiv_type by fastforce subsection \<open>Equivalence relations -- predicate version\<close> text \<open>Partial equivalences.\<close> definition part_equivp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool" where "part_equivp R \<longleftrightarrow> (\<exists>x. R x x) \<and> (\<forall>x y. R x y \<longleftrightarrow> R x x \<and> R y y \<and> R x = R y)" \<comment> \<open>John-Harrison-style characterization\<close> lemma part_equivpI: "\<exists>x. R x x \<Longrightarrow> symp R \<Longrightarrow> transp R \<Longrightarrow> part_equivp R" by (auto simp add: part_equivp_def) (auto elim: sympE transpE) lemma part_equivpE: assumes "part_equivp R" obtains x where "R x x" and "symp R" and "transp R" proof - from assms have 1: "\<exists>x. R x x" and 2: "\<And>x y. R x y \<longleftrightarrow> R x x \<and> R y y \<and> R x = R y" unfolding part_equivp_def by blast+ from 1 obtain x where "R x x" .. moreover have "symp R" proof (rule sympI) fix x y assume "R x y" with 2 [of x y] show "R y x" by auto qed moreover have "transp R" proof (rule transpI) fix x y z assume "R x y" and "R y z" with 2 [of x y] 2 [of y z] show "R x z" by auto qed ultimately show thesis by (rule that) qed lemma part_equivp_refl_symp_transp: "part_equivp R \<longleftrightarrow> (\<exists>x. R x x) \<and> symp R \<and> transp R" by (auto intro: part_equivpI elim: part_equivpE) lemma part_equivp_symp: "part_equivp R \<Longrightarrow> R x y \<Longrightarrow> R y x" by (erule part_equivpE, erule sympE) lemma part_equivp_transp: "part_equivp R \<Longrightarrow> R x y \<Longrightarrow> R y z \<Longrightarrow> R x z" by (erule part_equivpE, erule transpE) lemma part_equivp_typedef: "part_equivp R \<Longrightarrow> \<exists>d. d \<in> {c. \<exists>x. R x x \<and> c = Collect (R x)}" by (auto elim: part_equivpE) text \<open>Total equivalences.\<close> definition equivp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> bool" where "equivp R \<longleftrightarrow> (\<forall>x y. R x y = (R x = R y))" \<comment> \<open>John-Harrison-style characterization\<close> lemma equivpI: "reflp R \<Longrightarrow> symp R \<Longrightarrow> transp R \<Longrightarrow> equivp R" by (auto elim: reflpE sympE transpE simp add: equivp_def) lemma equivpE: assumes "equivp R" obtains "reflp R" and "symp R" and "transp R" using assms by (auto intro!: that reflpI sympI transpI simp add: equivp_def) lemma equivp_implies_part_equivp: "equivp R \<Longrightarrow> part_equivp R" by (auto intro: part_equivpI elim: equivpE reflpE) lemma equivp_equiv: "equiv UNIV A \<longleftrightarrow> equivp (\<lambda>x y. (x, y) \<in> A)" by (auto intro!: equivI equivpI [to_set] elim!: equivE equivpE [to_set]) lemma equivp_reflp_symp_transp: "equivp R \<longleftrightarrow> reflp R \<and> symp R \<and> transp R" by (auto intro: equivpI elim: equivpE) lemma identity_equivp: "equivp (=)" by (auto intro: equivpI reflpI sympI transpI) lemma equivp_reflp: "equivp R \<Longrightarrow> R x x" by (erule equivpE, erule reflpE) lemma equivp_symp: "equivp R \<Longrightarrow> R x y \<Longrightarrow> R y x" by (erule equivpE, erule sympE) lemma equivp_transp: "equivp R \<Longrightarrow> R x y \<Longrightarrow> R y z \<Longrightarrow> R x z" by (erule equivpE, erule transpE) lemma equivp_rtranclp: "symp r \<Longrightarrow> equivp r\<^sup>*\<^sup>*" by(intro equivpI reflpI sympI transpI)(auto dest: sympD[OF symp_rtranclp]) lemmas equivp_rtranclp_symclp [simp] = equivp_rtranclp[OF symp_on_symclp] lemma equivp_vimage2p: "equivp R \<Longrightarrow> equivp (vimage2p f f R)" by(auto simp add: equivp_def vimage2p_def dest: fun_cong) lemma equivp_imp_transp: "equivp R \<Longrightarrow> transp R" by(simp add: equivp_reflp_symp_transp) subsection \<open>Equivalence closure\<close> definition equivclp :: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" where "equivclp r = (symclp r)\<^sup>*\<^sup>*" lemma transp_equivclp [simp]: "transp (equivclp r)" by(simp add: equivclp_def) lemma reflp_equivclp [simp]: "reflp (equivclp r)" by(simp add: equivclp_def) lemma symp_equivclp [simp]: "symp (equivclp r)" by(simp add: equivclp_def) lemma equivp_evquivclp [simp]: "equivp (equivclp r)" by(simp add: equivpI) lemma tranclp_equivclp [simp]: "(equivclp r)\<^sup>+\<^sup>+ = equivclp r" by(simp add: equivclp_def) lemma rtranclp_equivclp [simp]: "(equivclp r)\<^sup>*\<^sup>* = equivclp r" by(simp add: equivclp_def) lemma symclp_equivclp [simp]: "symclp (equivclp r) = equivclp r" by(simp add: equivclp_def symp_symclp_eq) lemma equivclp_symclp [simp]: "equivclp (symclp r) = equivclp r" by(simp add: equivclp_def) lemma equivclp_conversep [simp]: "equivclp (conversep r) = equivclp r" by(simp add: equivclp_def) lemma equivclp_sym [sym]: "equivclp r x y \<Longrightarrow> equivclp r y x" by(rule sympD[OF symp_equivclp]) lemma equivclp_OO_equivclp_le_equivclp: "equivclp r OO equivclp r \<le> equivclp r" by(rule transp_relcompp_less_eq transp_equivclp)+ lemma rtranlcp_le_equivclp: "r\<^sup>*\<^sup>* \<le> equivclp r" unfolding equivclp_def by(rule rtranclp_mono)(simp add: symclp_pointfree) lemma rtranclp_conversep_le_equivclp: "r\<inverse>\<inverse>\<^sup>*\<^sup>* \<le> equivclp r" unfolding equivclp_def by(rule rtranclp_mono)(simp add: symclp_pointfree) lemma symclp_rtranclp_le_equivclp: "symclp r\<^sup>*\<^sup>* \<le> equivclp r" unfolding symclp_pointfree by(rule le_supI)(simp_all add: rtranclp_conversep[symmetric] rtranlcp_le_equivclp rtranclp_conversep_le_equivclp) lemma r_OO_conversep_into_equivclp: "r\<^sup>*\<^sup>* OO r\<inverse>\<inverse>\<^sup>*\<^sup>* \<le> equivclp r" by(blast intro: order_trans[OF _ equivclp_OO_equivclp_le_equivclp] relcompp_mono rtranlcp_le_equivclp rtranclp_conversep_le_equivclp del: predicate2I) lemma equivclp_induct [consumes 1, case_names base step, induct pred: equivclp]: assumes a: "equivclp r a b" and cases: "P a" "\<And>y z. equivclp r a y \<Longrightarrow> r y z \<or> r z y \<Longrightarrow> P y \<Longrightarrow> P z" shows "P b" using a unfolding equivclp_def by(induction rule: rtranclp_induct; fold equivclp_def; blast intro: cases elim: symclpE) lemma converse_equivclp_induct [consumes 1, case_names base step]: assumes major: "equivclp r a b" and cases: "P b" "\<And>y z. r y z \<or> r z y \<Longrightarrow> equivclp r z b \<Longrightarrow> P z \<Longrightarrow> P y" shows "P a" using major unfolding equivclp_def by(induction rule: converse_rtranclp_induct; fold equivclp_def; blast intro: cases elim: symclpE) lemma equivclp_refl [simp]: "equivclp r x x" by(rule reflpD[OF reflp_equivclp]) lemma r_into_equivclp [intro]: "r x y \<Longrightarrow> equivclp r x y" unfolding equivclp_def by(blast intro: symclpI) lemma converse_r_into_equivclp [intro]: "r y x \<Longrightarrow> equivclp r x y" unfolding equivclp_def by(blast intro: symclpI) lemma rtranclp_into_equivclp: "r\<^sup>*\<^sup>* x y \<Longrightarrow> equivclp r x y" using rtranlcp_le_equivclp[of r] by blast lemma converse_rtranclp_into_equivclp: "r\<^sup>*\<^sup>* y x \<Longrightarrow> equivclp r x y" by(blast intro: equivclp_sym rtranclp_into_equivclp) lemma equivclp_into_equivclp: "\<lbrakk> equivclp r a b; r b c \<or> r c b \<rbrakk> \<Longrightarrow> equivclp r a c" unfolding equivclp_def by(erule rtranclp.rtrancl_into_rtrancl)(auto intro: symclpI) lemma equivclp_trans [trans]: "\<lbrakk> equivclp r a b; equivclp r b c \<rbrakk> \<Longrightarrow> equivclp r a c" using equivclp_OO_equivclp_le_equivclp[of r] by blast hide_const (open) proj end
""" Module: SymbolicDiff (Symbolic Operation for Arithmetic) """ """ @vars(parms...) generate symbolic variables Example: @vars x y """ macro vars(params...) if length(params) == 1 && Meta.isexpr(params[1], :block) args = params[1].args else args = params end body = [] xargs = [] for x = args if typeof(x) == Symbol push!(body, Expr(:(=), esc(x), esc(Expr(:call, :symbolic, Expr(:quote, x))))) push!(xargs, esc(x)) else push!(body, x) end end push!(body, Expr(:tuple, [x for x = xargs]...)) Expr(:block, body...) end """ @bind(envname, block) Set parameter values in the block to the environment Example: @bind env1 x = 1.0 @bind env1 begin x = 1.0 y = 2.0 end """ macro bind(x...) if length(x) == 1 envname = :globalenv arg = x[1] elseif length(x) == 2 envname = x[1] arg = x[2] else throw(ErrorException("@bind should take 1 or 2 arguments")) end vars = [] if Meta.isexpr(arg, :block) body = [_parameter(x, envname, vars) for x = arg.args] expr = Expr(:block, body...) else expr = _parameter(arg, envname, vars) end unique!(vars) esc(Expr(:block, expr, [Expr(:(=), x, Expr(:call, :symbolic, Expr(:quote, x))) for x = vars]..., Expr(:tuple, vars...) )) end function _parameter(x::Any, envname, vars) x end function _parameter(x::Symbol, envname, vars) push!(vars, x) nothing end function _parameter(x::Expr, envname, vars) if Meta.isexpr(x, :(=)) var = x.args[1] push!(vars, var) val = x.args[2] :($(envname)[$(Expr(:quote, var))] = $(val)) else throw(ErrorException("invalid expression for @bind.")) end end """ @expr x Make SymbolicExpression Example: f = @expr x^2 + y """ macro expr(x) esc(_genexpr(x)) end function _genexpr(x) if Meta.isexpr(x, :vect) Expr(:vect, [_genexpr(u) for u = x.args]...) elseif Meta.isexpr(x, :vcat) Expr(:vcat, [_genexpr(u) for u = x.args]...) elseif Meta.isexpr(x, :row) Expr(:row, [_genexpr(u) for u = x.args]...) else Expr(:call, :symbolic, Expr(:quote, x)) end end
lemma norm_of_nat [simp]: "norm (of_nat n::'a::real_normed_algebra_1) = of_nat n"
module decDivZ import ZZ import ZZUtils import Divisors import GCDZZ import Primes import gcd %access public export %default total isDivisibleImpliesIsDivisibleZ:isDivisible a b -> IsDivisibleZ (Pos a) (Pos b) isDivisibleImpliesIsDivisibleZ (n**(gpf,eqpf)) = ((Pos n)**(cong eqpf)) posIntToSuccNat:{m:ZZ}->(IsPositive m) ->(t:Nat**(((m = (Pos t)),(IsSucc t)))) posIntToSuccNat {m = (Pos (S k))} Positive = ((S k)**(Refl,(ItIsSucc ))) succGtZero:{t:Nat}->(IsSucc t)->GT t Z succGtZero {t = (S n)} ItIsSucc = LTESucc LTEZero rehelp2:{m:ZZ}->{k:ZZ}->(s:ZZ)-> m = k->s*k = s*m rehelp2 s prf = rewrite sym $ prf in Refl isDivisibleZImpliesIsDivisible :{a:Nat}->{b:Nat}-> IsPositive (Pos a) -> IsDivisibleZ (Pos a) (Pos b) ->isDivisible a b isDivisibleZImpliesIsDivisible {a = (S k)}{b = Z} Positive x = void (zeroDoesntDivideNonZero PositiveZ x) isDivisibleZImpliesIsDivisible {a = (S k)}{b = (S j)} Positive (m**eqpf) = (case posDivByPosIsPos {c = (Pos (S k))}{d =(Pos (S j))} Positive Positive eqpf of mPos => (case posIntToSuccNat mPos of (t**(equal,tsucc)) => ( t**((succGtZero tsucc),( posInjective( rewrite rehelp2 {m=m}{k=(Pos t)} (Pos (S j)) equal in eqpf)))))) posSSknotOne: (Pos ( S (S k)))=1->Void posSSknotOne Refl impossible posSSknotMinusOne: (Pos ( S (S k)))=(-1)->Void posSSknotMinusOne Refl impossible gt2DoesntDivideOne: {k:Nat}->IsDivisibleZ 1 (Pos ( S (S k))) ->Void gt2DoesntDivideOne {k} (n**eqpf) = (case productOneThenNumbersOne (Pos (S (S k))) n (sym eqpf) of (Left (a, b)) => posSSknotOne a (Right (a, b)) => posSSknotMinusOne a) succNotZ:( S n) = Z ->Void succNotZ Refl impossible decDivisibleZnn: (a:ZZ)->(b:ZZ)->IsNonNegative a->IsNonNegative b -> Dec (IsDivisibleZ a b) decDivisibleZnn (Pos Z) b NonNegative y = Yes (zzDividesZero _) decDivisibleZnn (Pos (S Z)) (Pos Z) NonNegative NonNegative = No (zeroDoesntDivideNonZero PositiveZ ) decDivisibleZnn (Pos (S Z)) (Pos (S Z)) NonNegative NonNegative= Yes ( oneDiv 1) decDivisibleZnn (Pos (S Z)) (Pos (S (S k))) NonNegative NonNegative= No (gt2DoesntDivideOne ) decDivisibleZnn (Pos (S (S k))) (Pos Z) NonNegative NonNegative= No (zeroDoesntDivideNonZero PositiveZ ) decDivisibleZnn (Pos (S (S k))) (Pos (S j)) NonNegative NonNegative= (case decDiv (S (S k)) (LTESucc (LTESucc LTEZero)) (S j) {euc = eculidDivideAux (S(S k)) (S j) (succNotZ)} of (Yes prf) => (Yes (isDivisibleImpliesIsDivisibleZ prf)) (No contra) => No(contra . (isDivisibleZImpliesIsDivisible {b =(S j)} Positive))) |||Given two integers , a and b, it either returns a proof that b|a or ||| a proof that b|a is impossible. decDivisibleZ: (a:ZZ)->(b:ZZ)->(Dec (IsDivisibleZ a b)) decDivisibleZ (Pos k) (Pos j) = decDivisibleZnn (Pos k) (Pos j) NonNegative NonNegative decDivisibleZ (Pos k) (NegS j) = (case decDivisibleZnn (Pos k) (-(NegS j)) NonNegative NonNegative of (Yes prf) => Yes (negativeDivides prf ) (No contra) => No (contra . negativeDivides {d =NegS j} )) decDivisibleZ (NegS k) (Pos j) = (case decDivisibleZnn (-(NegS k)) (Pos j) NonNegative NonNegative of (Yes prf) => Yes ( dDividesNegative prf) (No contra) => No (contra . dDividesNegative {a = (NegS k)})) decDivisibleZ (NegS k) (NegS j) = (case decDivisibleZnn (-(NegS k)) (-(NegS j)) NonNegative NonNegative of (Yes prf) => Yes ( dDividesNegative (negativeDivides prf)) (No contra) => No ( contra . doubleNegativeDivides { a =NegS k}{d = NegS j}))
module _ {a} {A : Set a} where open import Agda.Builtin.Equality open import Agda.Builtin.List infix 4 _⊆_ postulate _⊆_ : (xs ys : List A) → Set a ⊆-trans : ∀{xs ys zs} → xs ⊆ ys → ys ⊆ zs → xs ⊆ zs private variable xs ys zs : List A σ τ : ys ⊆ zs x y : A x≈y : x ≡ y lemma : ∀ us (ρ : us ⊆ zs) (τ' : x ∷ xs ⊆ us) (σ' : ys ⊆ us) (τ'∘ρ≡τ : ⊆-trans τ' ρ ≡ τ) (σ'∘ρ≡σ : ⊆-trans σ' ρ ≡ σ) → us ⊆ us lemma {τ = τ} {σ = σ} us ρ τ' σ' τ'∘ρ≡τ σ'∘ρ≡σ = lem {τ = τ} {σ} us ρ τ' σ' τ'∘ρ≡τ σ'∘ρ≡σ where lem : ∀ {ys zs} {τ : (x ∷ xs) ⊆ zs} {σ : ys ⊆ zs} us (ρ : us ⊆ zs) (τ' : x ∷ xs ⊆ us) (σ' : ys ⊆ us) (τ'∘ρ≡τ : ⊆-trans τ' ρ ≡ τ) (σ'∘ρ≡σ : ⊆-trans σ' ρ ≡ σ) → {!!} lem = {!!}
[STATEMENT] lemma Key_image_eq [simp]: "(Key x \<in> Key`A) = (x\<in>A)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (Key x \<in> Key ` A) = (x \<in> A) [PROOF STEP] by auto
The last known recorded date at the site is featured on Monument 101 as 15 January 909 CE .
#include "benchmark.hpp" #include <lapacke.h> int svd(double *A, int m, int n, double *U, double *s, double *V_t) { const int lda = n; const int ldu = m; const int ldvt = n; const char jobu = 'A'; const char jobvt = 'A'; const int superb_size = (m < n) ? m : n; double *superb = malloc(sizeof(double) * (superb_size - 1)); lapack_int retval = LAPACKE_dgesvd(LAPACK_ROW_MAJOR, jobu, jobvt, m, n, A, lda, s, U, ldu, V_t, ldvt, superb); if (retval > 0) { return -1; } /* Clean up */ free(superb); return 0; } int main() { for (size_t k = 10; k <= 1000; k += 10) { size_t m = k; double *A = create_random_sq_matrix(m); double *U = malloc(sizeof(double) * m * m); double *d = malloc(sizeof(double) * m); double *V_t = malloc(sizeof(double) * m * m); sleep(0.1); struct timespec t = tic(); svd(A, m, m, U, d, V_t); printf("matrix_size: %ld\t: dgesvd: %fs\n", m, toc(&t)); free(A); free(U); free(d); free(V_t); } return 0; }
Formal statement is: lemma measurable_restrict_countable: assumes X[intro]: "countable X" assumes sets[simp]: "\<And>x. x \<in> X \<Longrightarrow> {x} \<in> sets M" assumes space[simp]: "\<And>x. x \<in> X \<Longrightarrow> f x \<in> space N" assumes f: "f \<in> measurable (restrict_space M (- X)) N" shows "f \<in> measurable M N" Informal statement is: If $f$ is a measurable function from a space $M$ to a space $N$ and $X$ is a countable subset of $M$, then $f$ is also measurable when restricted to $M \setminus X$.
-- {-# OPTIONS --show-implicit --show-irrelevant #-} module Data.QuadTree.LensProofs.Valid-LensAtLocation where open import Haskell.Prelude renaming (zero to Z; suc to S) open import Data.Lens.Lens open import Data.Logic open import Data.QuadTree.InternalAgda open import Agda.Primitive open import Data.Lens.Proofs.LensLaws open import Data.Lens.Proofs.LensPostulates open import Data.Lens.Proofs.LensComposition open import Data.QuadTree.LensProofs.Valid-LensLeaf open import Data.QuadTree.LensProofs.Valid-LensWrappedTree open import Data.QuadTree.LensProofs.Valid-LensA open import Data.QuadTree.LensProofs.Valid-LensBCD open import Data.QuadTree.LensProofs.Valid-LensGo open import Data.QuadTree.Implementation.QuadrantLenses open import Data.QuadTree.Implementation.Definition open import Data.QuadTree.Implementation.ValidTypes open import Data.QuadTree.Implementation.SafeFunctions open import Data.QuadTree.Implementation.PublicFunctions open import Data.QuadTree.Implementation.DataLenses ---- Lens laws for go ValidLens-AtLocation-ViewSet : {t : Set} {{eqT : Eq t}} -> (loc : Nat × Nat) -> (dep : Nat) -> {ins : IsTrue (isInsidePow loc dep)} -> ViewSet (atLocation {t} loc dep {ins}) ValidLens-AtLocation-ViewSet (x , y) dep {ins} v s = trans refl (prop-Composition-ViewSet (ValidLens-WrappedTree) (ValidLens-go (x , y) dep {ins}) v s) ValidLens-AtLocation-SetView : {t : Set} {{eqT : Eq t}} -> (loc : Nat × Nat) -> (dep : Nat) -> {ins : IsTrue (isInsidePow loc dep)} -> SetView (atLocation {t} loc dep {ins}) ValidLens-AtLocation-SetView (x , y) dep {ins} s = trans refl (prop-Composition-SetView (ValidLens-WrappedTree) (ValidLens-go (x , y) dep {ins}) s) ValidLens-AtLocation-SetSet : {t : Set} {{eqT : Eq t}} -> (loc : Nat × Nat) -> (dep : Nat) -> {ins : IsTrue (isInsidePow loc dep)} -> SetSet (atLocation {t} loc dep {ins}) ValidLens-AtLocation-SetSet (x , y) dep {ins} v1 v2 s = trans refl (prop-Composition-SetSet (ValidLens-WrappedTree) (ValidLens-go (x , y) dep {ins}) v1 v2 s) ValidLens-AtLocation : {t : Set} {{eqT : Eq t}} -> (loc : Nat × Nat) -> (dep : Nat) -> {ins : IsTrue (isInsidePow loc dep)} -> ValidLens (VQuadTree t {dep}) t ValidLens-AtLocation {t} {{eqT}} (x , y) dep {ins} = CValidLens (atLocation (x , y) dep {ins}) (ValidLens-AtLocation-ViewSet (x , y) dep {ins}) (ValidLens-AtLocation-SetView (x , y) dep {ins}) (ValidLens-AtLocation-SetSet (x , y) dep {ins})
Nate is Canadian. Nate is loud and boisterous. Nate owns the Lukes Lounge in Dixon.
module Compiler.Codegen.Rapid import Data.List import Data.String import System import System.File import Core.Directory import Core.CompileExpr import Core.Context import Core.Options import Compiler.Common import Compiler.VMCode import Libraries.Utils.Path import Rapid.Driver isFgn : (Name, a, NamedDef) -> Bool isFgn (_, _, (MkNmForeign _ _ _)) = True isFgn _ = False shell : List String -> String shell args = showSep " " $ map shellQuote args where shellQuote : String -> String shellQuote s = s runShell : List String -> IO () runShell args = do let cmd = shell args ignore $ fPutStrLn stderr $ "+" ++ cmd rc <- system cmd case rc of 0 => pure () err_rc => do putStrLn $ "command failed with exit code " ++ show err_rc exitFailure globalizeStackmap : String -> IO Bool globalizeStackmap fname = do (Right outFile) <- openFile fname Append | Left err => do putStrLn $ "error opening asm file: " ++ show err pure False ignore $ fPutStr outFile "\n.globl __LLVM_StackMaps\n" ignore $ closeFile outFile pure True getDebug : List String -> Bool getDebug = any isDebug where isDebug : String -> Bool isDebug directive = (trim directive) == "debug" compile : Ref Ctxt Defs -> (tmpDir : String) -> (outputDir : String) -> ClosedTerm -> (outfile : String) -> Core (Maybe String) compile defs tmpDir outputDir term outfile = do let appDirRel = outfile ++ "_rapid" -- relative to build dir let appDirGen = outputDir </> appDirRel -- relative to here let outputFileName = appDirGen </> (outfile ++ ".ll") -- LLVM IR (text) let bcFileName = appDirGen </> (outfile ++ ".bc") -- optimized LLVM bitcode let asmFileName = appDirGen </> (outfile ++ ".s") -- compiled assembler let objectFileName = appDirGen </> (outfile ++ ".o") -- object file let binaryFileName = outputDir </> outfile coreLift_ $ mkdirAll appDirGen directives <- getDirectives (Other "llvm") let debug = getDebug directives coreLift_ $ fPutStrLn stderr ("debug: " ++ show debug) -- load supporting files first, so we can fail early support <- readDataFile $ "rapid" </> "support.ll" runtime <- findDataFile $ "rapid" </> "runtime.bc" platformLib <- findDataFile $ "rapid" </> "platform.a" rapidLLVMPlugin <- findDataFile $ "rapid" </> "librapid.so" cd <- getCompileData False VMCode term coreLift_ $ fPutStrLn stderr $ "got compiledata" let foreigns = map (\(n,_,d) => (n,d)) $ filter isFgn $ namedDefs cd let allFunctions = vmcode cd let optFlags = [ "-mem2reg", "-constprop", "-constmerge", "-sccp", "-dce", "-globaldce", "-rewrite-statepoints-for-gc"] coreLift_ $ writeIR allFunctions foreigns support outputFileName debug let lateTransformFlags = ["-rapid-lower"] coreLift $ do runShell $ ["opt", outputFileName, "-load=" ++ rapidLLVMPlugin] ++ optFlags ++ lateTransformFlags ++ ["-o=" ++ bcFileName] runShell ["llc", "--frame-pointer=all", "-tailcallopt", "-o=" ++ asmFileName, bcFileName] True <- globalizeStackmap asmFileName | False => putStrLn "error" runShell ["clang", "-c", "-o", objectFileName, asmFileName] runShell ["clang", "-pthread", "-o", binaryFileName, objectFileName, runtime, platformLib, "-lm", "-L/usr/local/lib", "-lgmp"] pure () pure $ Nothing execute : Ref Ctxt Defs -> (tmpDir : String) -> ClosedTerm -> Core () execute defs tmpDir term = do let tmpExecutableFile = "idris_tmp" ignore $ compile defs tmpDir tmpDir term tmpExecutableFile coreLift_ $ system (tmpDir </> tmpExecutableFile) pure () export rapidCodegen : Codegen rapidCodegen = MkCG compile execute
import LMT variable {I} [Nonempty I] {E} [Nonempty E] [Nonempty (A I E)] example {a1 a2 a3 : A I E} : ((((a2).write i1 (v2)).write i3 (v2)).read i1) ≠ (v2) → (a2) = (a1) → False := by arr
Set Implicit Arguments. Require Export List. Require Export Arith. Section Carrier. Variable N:Type. Variable A:Type. Variable zero : N. Variable succ : N -> N. Variable comp : N -> N -> comparison. Fixpoint fromNat (x:nat) : N := match x with | 0 => zero | S y => succ (fromNat y) end. Variable size : forall t, list t -> N. Variable sizeNat : forall t (x:list t), fromNat (length x) = size x. (* Definition Buffer t := list t. Definition bufferSize t (b:list t) := @length _ b < 6. *) Inductive Buffer t := Zero | One : t -> Buffer t | Two : t -> t -> Buffer t | Three : t -> t -> t -> Buffer t | Four : t -> t -> t -> t -> Buffer t | Five : t -> t -> t -> t -> t -> Buffer t. Set Maximal Implicit Insertion. Implicit Arguments Zero [t]. Unset Maximal Implicit Insertion. (* Inductive SimpleDeque t := Empty : SimpleDeque t | Full : Buffer t -> SimpleDeque (prod t t) -> Buffer t -> SimpleDeque t. *) (* Inductive LeafTree t := One : t -> LeafTree t | More : LeafTree (prod t t) -> LeafTree t. Definition Elem := LeafTree A. *) Inductive SubStack s : Type -> Type := Single : Buffer s -> Buffer s -> SubStack s s | Multiple : forall t, Buffer s -> Buffer s -> SubStack (prod s s) t -> SubStack s t. Inductive Deque s := Empty : Deque s | Full : forall t, SubStack s t -> Deque (prod t t) -> Deque s. Set Maximal Implicit Insertion. Implicit Arguments Empty [s]. Unset Maximal Implicit Insertion. Definition toListBufferC t (x:Buffer t) r := match x with | Zero => r | One a => a::r | Two a b => a::b::r | Three a b c => a::b::c::r | Four a b c d => a::b::c::d::r | Five a b c d e => a::b::c::d::e::r end. (* Definition toListPairBufferC t (x:Buffer (prod t t)) r := match x with | Zero => r | One (a,b) => a::b::r | Two (a,b) (c,d) => a::b::c::d::r | Three (a,b) (c,d) (e,f) => a::b::c::d::e::f::r | Four (a,b) (c,d) (e,f) (g,h) => a::b::c::d::e::f::g::h::r | Five (a,b) (c,d) (e,f) (g,h) (i,j) => a::b::c::d::e::f::g::h::i::j::r end. *) Fixpoint unzipMix t (x:list (prod t t)) r := match x with | nil => r | (a,b)::tyl => a::b::(unzipMix tyl r) end. (* Require Import Program. Require Import Coq.Logic.JMeq. *) (* Error: Library Coq.Logic.JMeq has to be required first. *) (* Program Fixpoint toListSubStack t s (x:SubStack t s) (r:list s -> list s) : list t := match x with | Single a b => toListBufferC a (r (toListBufferC b nil)) | Multiple _ a b tyl => toListBufferC a (unzipMix (toListSubStack tyl r) (toListBufferC b nil)) end. *) Fixpoint toListSubStack t s (x:SubStack t s) : (list s -> list s) -> list t := match x with | Single a b => fun r => toListBufferC a (r (toListBufferC b nil)) | Multiple _ a b tyl => fun r => toListBufferC a (unzipMix (toListSubStack tyl r) (toListBufferC b nil)) end. Fixpoint toListDeque t (x:Deque t) : list t := match x with | Empty => nil | Full u hed tyl => toListSubStack hed (unzipMix (toListDeque tyl)) end. Inductive Color := Red | Yellow | Green. Definition bufferColor t (b:Buffer t) := match b with | Two _ _ => Green | Three _ _ _ => Green | One _ => Yellow | Four _ _ _ _ => Yellow | _ => Red end. Hint Unfold bufferColor. Hint Unfold length. Definition minColor a b := match a with | Red => Red | Yellow => match b with | Red => Red | _ => Yellow end | _ => b end. Definition bottomSubStackColor s t (x:SubStack s t) := match x with | Single pre suf => match pre with | Zero => bufferColor suf | _ => match suf with | Zero => bufferColor pre | _ => minColor (bufferColor pre) (bufferColor suf) end end | Multiple _ pre suf _ => minColor (bufferColor pre) (bufferColor suf) end. Definition topSubStackColor s t (x:SubStack s t) := match x with | Single pre suf => minColor (bufferColor pre) (bufferColor suf) | Multiple _ pre suf _ => minColor (bufferColor pre) (bufferColor suf) end. Definition dequeColor t (d:Deque t) := match d with | Empty => None | Full _ hed tyl => Some ( match tyl with | Empty => bottomSubStackColor hed | _ => topSubStackColor hed end) end. Fixpoint allSubStackYellow (f:forall s t, SubStack s t -> Color) s t (x:SubStack s t) := f _ _ x = Yellow /\ match x with | Single _ _ => True | Multiple _ _ _ r => allSubStackYellow f r end. Definition tailStackColor (f: forall s t, SubStack s t -> Color) s t (x:SubStack s t) := match x with | Single _ _ => None | Multiple _ _ _ r => Some (f _ _ r) end. Definition yellowOrNothing x := match x with | None => True | Some c => match c with | Yellow => True | _ => False end end. Definition tailStackProp (f: forall s t, SubStack s t -> Prop) s t (x:SubStack s t) := match x with | Single _ _ => True | Multiple _ _ _ r => f _ _ r end. Fixpoint restWellStacked s (x:Deque s) := match x with | Empty => True | Full _ hed tyl => match tyl with | Empty => bottomSubStackColor hed <> Yellow /\ tailStackProp (allSubStackYellow bottomSubStackColor) hed | _ => topSubStackColor hed <> Yellow /\ tailStackProp (allSubStackYellow topSubStackColor) hed /\ restWellStacked tyl end end. Definition wellStacked s (x:Deque s) := match x with | Empty => True | Full _ hed tyl => match tyl with | Empty => tailStackProp (allSubStackYellow bottomSubStackColor) hed | _ => tailStackProp (allSubStackYellow topSubStackColor) hed /\ restWellStacked tyl end end. Fixpoint topDequeColors s (x:Deque s) := match x with | Empty => nil | Full _ hed tyl => match tyl with | Empty => (bottomSubStackColor hed) :: nil | _ => (topSubStackColor hed) :: (topDequeColors tyl) end end. Fixpoint semiRegularColorListGreenBeforeRed x := match x with | nil => True | y::ys => match y with | Red => False | Green => semiRegularColorList ys | Yellow => semiRegularColorListGreenBeforeRed ys end end with semiRegularColorList x := match x with | nil => True | y::ys => match y with | Red => semiRegularColorListGreenBeforeRed ys | _ => semiRegularColorList ys end end. Fixpoint nonEmptySubStack t s (x:SubStack t s) := match x with | Single pre suf => match pre, suf with | Zero,Zero => False | _,_ => True end | Multiple _ pre suf tyl => (match pre, suf with | Zero,Zero => False | _,_ => True end) /\ nonEmptySubStack tyl end. (* Full deques are not empty *) Fixpoint fullDequeIs t (d:Deque t) := match d with | Empty => True | Full _ hed tyl => match tyl with | Empty => nonEmptySubStack hed | _ => nonEmptySubStack hed /\ fullDequeIs tyl end end. Fixpoint eachBufferSubStack (f: forall a, Buffer a -> Prop) s t (x:SubStack s t) := match x with | Single pre suf => f _ pre /\ f _ suf | Multiple _ pre suf tyl => f _ pre /\ f _ suf /\ eachBufferSubStack f tyl end. Fixpoint eachSubStackDeque (f:forall s t, SubStack s t -> Prop) s (x:Deque s) := match x with | Empty => True | Full _ hed tyl => f _ _ hed /\ eachSubStackDeque f tyl end. Definition semiRegular s (x:Deque s) := wellStacked x /\ fullDequeIs x /\ (* eachSubStackDeque (eachBufferSubStack bufferSize) x /\*) semiRegularColorList (topDequeColors x). Hint Unfold semiRegular. Fixpoint topNonYellowIsGreen x := match x with | nil => True | y::ys => match y with | Red => False | Yellow => topNonYellowIsGreen ys | Green => True end end. (* Fixpoint regularColorList x := topNonYellowIsGreen x /\ semiRegularColorList x. *) Definition regular s (x:Deque s) := semiRegular x /\ topNonYellowIsGreen (topDequeColors x). Hint Unfold regular. Definition restoreBottom t (pre suf:Buffer t) : Deque t := match pre,suf with | Zero,Five a b c d e => Full (Single (Two a b) (Three c d e)) Empty | One a,Five b c d e f => Full (Single (Three a b c) (Three d e f)) Empty | Two a b,Five c d e f g => Full (Single (Three a b c) (Four d e f g)) Empty | Three a b c,Five d e f g h => Full (Single (Four a b c d) (Four e f g h)) Empty | Four a b c d,Five e f g h i => Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty | Five a b c d e,Five f g h i j => Full (Multiple (Three a b c) (Three h i j) (Single (One (d,e)) (One (f,g)))) Empty | Five a b c d e, Zero => Full (Single (Two a b) (Three c d e)) Empty | Five a b c d e, One f => Full (Single (Three a b c) (Three d e f)) Empty | Five a b c d e, Two f g => Full (Single (Three a b c) (Four d e f g)) Empty | Five a b c d e, Three f g h => Full (Single (Four a b c d) (Four e f g h)) Empty | Five a b c d e, Four f g h i => Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty | _,_ => Full (Single pre suf) Empty end. Ltac cutThis x := let xx := fresh in remember x as xx; destruct xx. Ltac pisp t := try subst; unfold bufferColor in *; unfold not; intros; simpl in *; auto; t; match goal with | [H:Red=Yellow |- _] => inversion H; pisp t | [H:Red=Green |- _] => inversion H; pisp t | [H:Yellow=Green |- _] => inversion H; pisp t | [H:Yellow=Red |- _] => inversion H; pisp t | [H:Green=Red |- _] => inversion H; pisp t | [H:Green=Yellow |- _] => inversion H; pisp t | [ H : true = false |- _] => inversion H; pisp t | [ H : None = Some ?a |- _] => inversion H; pisp t | [ H : Some ?a = None |- _] => inversion H; pisp t | [ H : False |- _] => inversion H; pisp t | [ H : True |- _] => clear H; pisp t | [ H : ?a = ?a |- _] => clear H; pisp t | [ H : Some ?a = Some ?b |- _] => inversion_clear H; subst; pisp t | [ |- regular (Full _ _) ] => unfold regular; pisp t | [ H : semiRegular (Full _ _) |- _] => unfold semiRegular in H; pisp t | [ |- semiRegular (Full _ _) ] => unfold semiRegular; pisp t | [H : ?A \/ ?B |- _] => destruct H; pisp t | [ H : _ /\ _ |- _ ] => destruct H; pisp t | [ |- _ /\ _ ] => split; pisp t | [ |- context[ match ?x with | Single _ _ => _ | Multiple _ _ _ _ => _ end]] => destruct x; pisp t | [ |- context [match ?x with | Zero => _ | One _ => _ | Two _ _ => _ | Three _ _ _ => _ | Four _ _ _ _ => _ | Five _ _ _ _ _ => _ end]] => destruct x; pisp t | [ H : prod _ _ |- _] => cutThis H; pisp t (* | [ |- context [let (_,_) := ?x in _]] => destruct x; pisp t *) | _ => auto end. Ltac asp := progress pisp auto. Lemma restoreBottomDoes : forall t (pre suf:Buffer t), semiRegular (Full (Single pre suf) Empty) -> regular (restoreBottom pre suf). Proof. intros. destruct pre; asp. Qed. Hint Resolve restoreBottomDoes. Lemma restoreBottomPreserves : forall t (pre suf:Buffer t), let x := (Full (Single pre suf) Empty) in semiRegular x -> toListDeque (restoreBottom pre suf) = toListDeque x. Proof. intros. destruct pre; asp. Qed. Hint Resolve restoreBottomPreserves. Definition restoreOneYellowBottom T (p1 s1:Buffer T) (p2 s2:Buffer (prod T T)) : option (Deque T) := match p1,p2,s2,s1 with | Zero,Zero,One (a,b),Five c d e f g => Some (Full (Single (Three a b c) (Four d e f g)) Empty) | Zero,Zero,Four (a,b) cd ef gh,Five i j k l m => Some (Full (Single (Two a b) (Three k l m)) (Full (Single (Two cd ef) (Two gh (i,j))) Empty)) | Zero,One (a,b),Zero,Five c d e f g => Some (Full (Single (Three a b c) (Four d e f g)) Empty) | Zero,One (a,b),One (c,d), Five e f g h i => Some ( Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty) | Zero,One (a,b),Two (c,d) (e,f), Five g h i j k => Some ( Full (Multiple (Four a b c d) (Three i j k) (Single (One (e,f)) (One (g,h)))) Empty) | Zero,One (a,b),Three (c,d) (e,f) (g,h), Five i j k l m => Some ( Full (Multiple (Four a b c d) (Three k l m) (Single (One (e,f)) (Two (g,h) (i,j)))) Empty) | Zero,One (a,b),Four (c,d) (e,f) (g,h) (i,j), Five k l m n o=> Some ( Full (Multiple (Four a b c d) (Three m n o) (Single (One (e,f)) (Three (g,h) (i,j) (k,l)))) Empty) | Zero,Two (a,b) (c,d), One (e,f), Five g h i j k => Some ( Full (Multiple (Four a b c d) (Three i j k) (Single (One (e,f)) (One (g,h)))) Empty) | Zero,Two (a,b) (c,d),Four (e,f) (g,h) (i,j) (k,l), Five m n o p q=> Some ( Full (Multiple (Four a b c d) (Three o p q) (Single (One (e,f)) (Four (g,h) (i,j) (k,l) (m,n)))) Empty) | Zero,Three (a,b) (c,d) (e,f), One (g,h), Five i j k l m=> Some ( Full (Multiple (Four a b c d) (Three k l m) (Single (One (e,f)) (Two (g,h) (i,j)))) Empty) | Zero,Three (a,b) (c,d) (e,f), Four (g,h) (i,j) (k,l) (m,n), Five o p q r s => Some ( Full (Multiple (Four a b c d) (Three q r s) (Single (Two (e,f) (g,h)) (Four (i,j) (k,l) (m,n) (o,p)))) Empty) |_,_,_,_ => None end. Lemma restoreOneYellowBottomDoes : forall t (p1 s1:Buffer t) p2 s2, semiRegular (Full (Multiple p1 s1 (Single p2 s2)) Empty) -> match restoreOneYellowBottom p1 s1 p2 s2 with | None => True | Some v => regular v end. Proof. intros. destruct p1; asp. Qed. Lemma restoreOneYellowBottomPreserves : forall t (p1 s1:Buffer t) p2 s2, let x := (Full (Multiple p1 s1 (Single p2 s2)) Empty) in semiRegular x -> match restoreOneYellowBottom p1 s1 p2 s2 with | None => True | Some v => toListDeque x = toListDeque v end. Proof. intros. destruct p1; asp. Qed. Lemma restoreBottomPreserves : forall t (pre suf:Buffer t), let x := (Full (Single pre suf) Empty) in semiRegular x -> toListDeque (restoreBottom pre suf) = toListDeque x. Proof. intros. destruct pre; asp. Qed. Hint Resolve restoreBottomPreserves. (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty | Zero,One a,Zero,Five b c d e f => Full (Single (Three a b c) (Three d e f)) Empty | Zero,One a,One b,Five c d e f g => Full (Single (Three a b c) (Four d e f g)) Empty | Zero,One a,One b,Five c d e f g => Full (Single (Three a b c) (Four d e f g)) Empty | One a,Five b c d e f => Full (Single (Three a b c) (Three d e f)) Empty | Two a b,Five c d e f g => Full (Single (Three a b c) (Four d e f g)) Empty | Three a b c,Five d e f g h => Full (Single (Four a b c d) (Four e f g h)) Empty | Four a b c d,Five e f g h i => Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty | Five a b c d e,Five f g h i j => Full (Multiple (Three a b c) (Three h i j) (Single (One (d,e)) (One (f,g)))) Empty | Five a b c d e, Zero => Full (Single (Two a b) (Three c d e)) Empty | Five a b c d e, One f => Full (Single (Three a b c) (Three d e f)) Empty | Five a b c d e, Two f g => Full (Single (Three a b c) (Four d e f g)) Empty | Five a b c d e, Three f g h => Full (Single (Four a b c d) (Four e f g h)) Empty | Five a b c d e, Four f g h i => Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty | _,_ => Full (Single pre suf) Empty end Definition restore s (x:Deque s) : option (Deque s) := match x with | Empty => Some Empty | Full _ y ys => match ys with | Empty => match y with | Single pre suf => Some (restoreBottom pre suf) | Multiple _ pre suf tyl => match tyl with | Single p2 s2 => None | Multiple _ p2 s2 _ => None end end | _ => None end end. Lemma regEmpty : forall s, regular (@Empty s). Proof. intros. unfold regular. unfold semiRegular; unfold topNonYellowIsGreen; unfold topDequeColors; asp. Qed. Hint Resolve regEmpty. Lemma restoreDoes : forall s (x:Deque s), semiRegular x -> match restore x with | None => True | Some v => regular v end. Proof. intros. destruct x; simpl in *; auto. destruct x; simpl in *; auto. destruct s0; auto. destruct s0; auto. Qed. Lemma restorePreserves : forall s (x:Deque s), semiRegular x -> match restore x with | None => True | Some v => toListDeque v = toListDeque x end. Proof. intros. destruct x; simpl in *; auto. destruct x; simpl in *; auto. destruct s0; auto. apply restoreBottomPreserves; auto. destruct s0; auto. Qed. Definition restore s (x:Deque s) : option (Deque s) := match x with | Empty => Some Empty | Full _ y ys => match ys with | Empty => match bottomSubStackColor y with | Green => Some x | Yellow => Some x | Red => match y with | Single pre suf => match pre,suf with | Zero,Five a b c d e => Some (Full (Single (Two a b) (Three c d e)) Empty) | One a,Five b c d e f => Some (Full (Single (Three a b c) (Three d e f)) Empty) | Two a b,Five c d e f g => Some (Full (Single (Three a b c) (Four d e f g)) Empty) | Three a b c,Five d e f g h => Some (Full (Single (Four a b c d) (Four e f g h)) Empty) | Four a b c d,Five e f g h i => Some (Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty) | Five a b c d e,Five f g h i j => Some (Full (Multiple (Three a b c) (Three h i j) (Single (One (d,e)) (One (f,g)))) Empty) | Five a b c d e, Zero => Some (Full (Single (Two a b) (Three c d e)) Empty) | Five a b c d e, One f => Some (Full (Single (Three a b c) (Three d e f)) Empty) | Five a b c d e, Two f g => Some (Full (Single (Three a b c) (Four d e f g)) Empty) | Five a b c d e, Three f g h => Some (Full (Single (Four a b c d) (Four e f g h)) Empty) | Five a b c d e, Four f g h i => Some (Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty) | _,_ => Some x end | Multiple _ pre suf tyl => match pre,suf with | Zero,Five a b c d e => match tyl with | Single p2 s2 => match s2 with | Zero => Some (Full (Multiple Zero (Three c d e) (Single p2 (One (a,b)))) Empty) | _ => None end | _ => None end | _,_ => None end (* | One a,Five b c d e f => Some (Full (Single (Three a b c) (Three d e f)) Empty) | Two a b,Five c d e f g => Some (Full (Single (Three a b c) (Four d e f g)) Empty) | Three a b c,Five d e f g h => Some (Full (Single (Four a b c d) (Four e f g h)) Empty) | Four a b c d,Five e f g h i => Some (Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty) | Five a b c d e,Five f g h i j => Some (Full (Multiple (Three a b c) (Three h i j) (Single (One (d,e)) (One (f,g)))) Empty) | Five a b c d e, Zero => Some (Full (Single (Two a b) (Three c d e)) Empty) | Five a b c d e, One f => Some (Full (Single (Three a b c) (Three d e f)) Empty) | Five a b c d e, Two f g => Some (Full (Single (Three a b c) (Four d e f g)) Empty) | Five a b c d e, Three f g h => Some (Full (Single (Four a b c d) (Four e f g h)) Empty) | Five a b c d e, Four f g h i => Some (Full (Multiple (Four a b c d) (Three g h i) (Single Zero (One (e,f)))) Empty) | _,_ => Some x match tyl with | Single pre1 suf1 => match pre1 with | Zero => match suf1 with | Zero => Some x | _ => None end | _ => None end | _ => None end*) end end | _ => None end end. (* match topSubStackColor y with | Green => x | Yellow => restoreRest ys | Red => *) Ltac cutThis x := let xx := fresh in remember x as xx; destruct xx. Ltac pisp t := try subst; unfold bufferColor in *; simpl in *; auto; t; match goal with | [H:Red=Yellow |- _] => inversion H; pisp t | [H:Red=Green |- _] => inversion H; pisp t | [H:Yellow=Green |- _] => inversion H; pisp t | [H:Yellow=Red |- _] => inversion H; pisp t | [H:Green=Red |- _] => inversion H; pisp t | [H:Green=Yellow |- _] => inversion H; pisp t | [ H : true = false |- _] => inversion H; pisp t | [ H : None = Some ?a |- _] => inversion H; pisp t | [ H : Some ?a = None |- _] => inversion H; pisp t | [ H : False |- _] => inversion H; pisp t | [ H : True |- _] => clear H; pisp t | [ H : ?a = ?a |- _] => clear H; pisp t | [ H : Some ?a = Some ?b |- _] => inversion_clear H; subst; pisp t | [ |- regular (Full _ _) ] => unfold regular; pisp t | [ H : semiRegular (Full _ _) |- _] => unfold semiRegular in H; pisp t | [ |- semiRegular (Full _ _) ] => unfold semiRegular; pisp t (* | [ _ : context[length ?a] |- _] => destruct a; pisp t *) | [H : ?A \/ ?B |- _] => destruct H; pisp t | [ H : _ /\ _ |- _ ] => destruct H; pisp t | [ |- _ /\ _ ] => split; pisp t (* | [ _ : _ = match ?x with | Single _ _ => _ | Multiple _ _ _ _ => _ end |- _] => cutThis x; pisp t *) | [ |- context[ match ?x with | Single _ _ => _ | Multiple _ _ _ _ => _ end]] => destruct x; pisp t | [ |- context [match ?x with | Zero => _ | One _ => _ | Two _ _ => _ | Three _ _ _ => _ | Four _ _ _ _ => _ | Five _ _ _ _ _ => _ end]] => destruct x; pisp t (* | [ _ : context[bufferColor (?a :: ?b :: ?c :: ?d :: ?e)] |- _] => destruct e; pisp t | [ _ : context[bufferColor (?a :: ?b :: ?c :: ?e)] |- _] => destruct e; pisp t | [ _ : context[bufferColor (?a :: ?b :: ?e)] |- _] => destruct e; pisp t (* | [ _ : context[bufferColor (?a :: ?e)] |- _] => destruct e; pisp t*) *) | _ => auto end. Ltac asp := progress pisp auto. Lemma regEmpty : forall s, regular (@Empty s). Proof. intros. unfold regular. unfold semiRegular; unfold topNonYellowIsGreen; unfold topDequeColors; asp. Qed. Hint Resolve regEmpty. Lemma restoreDoes : forall s (x:Deque s), semiRegular x -> match restore x with | None => True | Some v => regular v end. Proof. intros. destruct x. Focus 2. simpl. destruct x; simpl. destruct s0; simpl. Focus 2. destruct s0. destruct b2. destruct b0. Focus 6. destruct b. simpl in *. unfold regular in *. unfold semiRegular in *. destruct H. destruct H0. split. split. simpl in *. asp. asp. simpl. asp. split. asp. destruct x; asp; destruct x; asp. Focus 2. destruct b1; asp. Qed. Lemma restorePreserves : forall s (x:Deque s), semiRegular x -> match restore x with | None => True | Some v => toListDeque v = toListDeque x end. Proof. intros. destruct x; asp; destruct x; asp. Qed. End Carrier. Extraction Language Haskell. Recursive Extraction dequeColor. Lemma help : forall t (p q:t), proj1 (conj p q) = p. Proof. Print proj1. unfold proj1. simpl.
Formal statement is: lemma real_polynomial_function_minus [intro]: "real_polynomial_function f \<Longrightarrow> real_polynomial_function (\<lambda>x. - f x)" Informal statement is: If $f$ is a real-valued polynomial function, then so is $-f$.
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller -/ import combinatorics.simple_graph.adj_matrix import linear_algebra.char_poly.coeff import data.int.modeq import data.zmod.basic import tactic.interval_cases /-! # The Friendship Theorem ## Definitions and Statement - A `friendship` graph is one in which any two distinct vertices have exactly one neighbor in common - A `politician`, at least in the context of this problem, is a vertex in a graph which is adjacent to every other vertex. - The friendship theorem (Erdős, Rényi, Sós 1966) states that every finite friendship graph has a politician. ## Proof outline The proof revolves around the theory of adjacency matrices, although some steps could equivalently be phrased in terms of counting walks. - Assume `G` is a finite friendship graph. - First we show that any two nonadjacent vertices have the same degree - Assume for contradiction that `G` does not have a politician. - Conclude from the last two points that `G` is `d`-regular for some `d : ℕ`. - Show that `G` has `d ^ 2 - d + 1` vertices. - By casework, show that if `d = 0, 1, 2`, then `G` has a politician. - If `3 ≤ d`, let `p` be a prime factor of `d - 1`. - If `A` is the adjacency matrix of `G` with entries in `ℤ/pℤ`, we show that `A ^ p` has trace `1`. - This gives a contradiction, as `A` has trace `0`, and thus `A ^ p` has trace `0`. ## References - [P. Erdős, A. Rényi, V. Sós, *On A Problem of Graph Theory*][erdosrenyisos] - [C. Huneke, *The Friendship Theorem*][huneke2002] -/ open_locale classical big_operators noncomputable theory open finset simple_graph matrix universes u v variables {V : Type u} {R : Type v} [semiring R] section friendship_def variables (G : simple_graph V) /-- This property of a graph is the hypothesis of the friendship theorem: every pair of nonadjacent vertices has exactly one common friend, a vertex to which both are adjacent. -/ def friendship [fintype V] : Prop := ∀ ⦃v w : V⦄, v ≠ w → fintype.card (G.common_neighbors v w) = 1 /-- A politician is a vertex that is adjacent to all other vertices. -/ def exists_politician : Prop := ∃ (v : V), ∀ (w : V), v ≠ w → G.adj v w end friendship_def variables [fintype V] {G : simple_graph V} {d : ℕ} (hG : friendship G) include hG namespace friendship variables (R) /-- One characterization of a friendship graph is that there is exactly one walk of length 2 between distinct vertices. These walks are counted in off-diagonal entries of the square of the adjacency matrix, so for a friendship graph, those entries are all 1. -/ theorem adj_matrix_sq_of_ne {v w : V} (hvw : v ≠ w) : ((G.adj_matrix R) ^ 2) v w = 1 := begin rw [sq, ← nat.cast_one, ← hG hvw], simp [common_neighbors, neighbor_finset_eq_filter, finset.filter_filter, finset.filter_inter, and_comm], end /-- This calculation amounts to counting the number of length 3 walks between nonadjacent vertices. We use it to show that nonadjacent vertices have equal degrees. -/ lemma adj_matrix_pow_three_of_not_adj {v w : V} (non_adj : ¬ G.adj v w) : ((G.adj_matrix R) ^ 3) v w = degree G v := begin rw [pow_succ, mul_eq_mul, adj_matrix_mul_apply, degree, card_eq_sum_ones, sum_nat_cast], apply sum_congr rfl, intros x hx, rw [adj_matrix_sq_of_ne _ hG, nat.cast_one], rintro ⟨rfl⟩, rw mem_neighbor_finset at hx, exact non_adj hx, end variable {R} /-- As `v` and `w` not being adjacent implies `degree G v = ((G.adj_matrix R) ^ 3) v w` and `degree G w = ((G.adj_matrix R) ^ 3) v w`, the degrees are equal if `((G.adj_matrix R) ^ 3) v w = ((G.adj_matrix R) ^ 3) w v` This is true as the adjacency matrix is symmetric. -/ lemma degree_eq_of_not_adj {v w : V} (hvw : ¬ G.adj v w) : degree G v = degree G w := begin rw [← nat.cast_id (G.degree v), ← nat.cast_id (G.degree w), ← adj_matrix_pow_three_of_not_adj ℕ hG hvw, ← adj_matrix_pow_three_of_not_adj ℕ hG (λ h, hvw (G.sym h))], conv_lhs {rw ← transpose_adj_matrix}, simp only [pow_succ, sq, mul_eq_mul, ← transpose_mul, transpose_apply], simp only [← mul_eq_mul, mul_assoc], end /-- Let `A` be the adjacency matrix of a graph `G`. If `G` is a friendship graph, then all of the off-diagonal entries of `A^2` are 1. If `G` is `d`-regular, then all of the diagonal entries of `A^2` are `d`. Putting these together determines `A^2` exactly for a `d`-regular friendship graph. -/ theorem adj_matrix_sq_of_regular (hd : G.is_regular_of_degree d) : ((G.adj_matrix R) ^ 2) = λ v w, if v = w then d else 1 := begin ext v w, by_cases h : v = w, { rw [h, sq, mul_eq_mul, adj_matrix_mul_self_apply_self, hd], simp, }, { rw [adj_matrix_sq_of_ne R hG h, if_neg h], }, end lemma adj_matrix_sq_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) ^ 2 = λ _ _, 1 := by simp [adj_matrix_sq_of_regular hG hd, dmod] section nonempty variable [nonempty V] /-- If `G` is a friendship graph without a politician (a vertex adjacent to all others), then it is regular. We have shown that nonadjacent vertices of a friendship graph have the same degree, and if there isn't a politician, we can show this for adjacent vertices by finding a vertex neither is adjacent to, and then using transitivity. -/ theorem is_regular_of_not_exists_politician (hG' : ¬exists_politician G) : ∃ (d : ℕ), G.is_regular_of_degree d := begin have v := classical.arbitrary V, use G.degree v, intro x, by_cases hvx : G.adj v x, swap, { exact (degree_eq_of_not_adj hG hvx).symm, }, dunfold exists_politician at hG', push_neg at hG', rcases hG' v with ⟨w, hvw', hvw⟩, rcases hG' x with ⟨y, hxy', hxy⟩, by_cases hxw : G.adj x w, swap, { rw degree_eq_of_not_adj hG hvw, exact degree_eq_of_not_adj hG hxw }, rw degree_eq_of_not_adj hG hxy, by_cases hvy : G.adj v y, swap, { exact (degree_eq_of_not_adj hG hvy).symm }, rw degree_eq_of_not_adj hG hvw, apply degree_eq_of_not_adj hG, intro hcontra, rcases finset.card_eq_one.mp (hG hvw') with ⟨⟨a, ha⟩, h⟩, have key : ∀ {x}, x ∈ G.common_neighbors v w → x = a, { intros x hx, have h' := mem_univ (subtype.mk x hx), rw [h, mem_singleton] at h', injection h', }, apply hxy', rw [key ((mem_common_neighbors G).mpr ⟨hvx, G.sym hxw⟩), key ((mem_common_neighbors G).mpr ⟨hvy, G.sym hcontra⟩)], end /-- Let `A` be the adjacency matrix of a `d`-regular friendship graph, and let `v` be a vector all of whose components are `1`. Then `v` is an eigenvector of `A ^ 2`, and we can compute the eigenvalue to be `d * d`, or as `d + (fintype.card V - 1)`, so those quantities must be equal. This essentially means that the graph has `d ^ 2 - d + 1` vertices. -/ lemma card_of_regular (hd : G.is_regular_of_degree d) : d + (fintype.card V - 1) = d * d := begin have v := classical.arbitrary V, transitivity ((G.adj_matrix ℕ) ^ 2).mul_vec (λ _, 1) v, { rw [adj_matrix_sq_of_regular hG hd, mul_vec, dot_product, ← insert_erase (mem_univ v)], simp only [sum_insert, mul_one, if_true, nat.cast_id, eq_self_iff_true, mem_erase, not_true, ne.def, not_false_iff, add_right_inj, false_and], rw [finset.sum_const_nat, card_erase_of_mem (mem_univ v), mul_one], { refl }, intros x hx, simp [(ne_of_mem_erase hx).symm], }, { rw [sq, mul_eq_mul, ← mul_vec_mul_vec], simp [adj_matrix_mul_vec_const_apply_of_regular hd, neighbor_finset, card_neighbor_set_eq_degree, hd v], } end /-- The size of a `d`-regular friendship graph is `1 mod (d-1)`, and thus `1 mod p` for a factor `p ∣ d-1`. -/ lemma card_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (fintype.card V : zmod p) = 1 := begin have hpos : 0 < fintype.card V := fintype.card_pos_iff.mpr infer_instance, rw [← nat.succ_pred_eq_of_pos hpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], have h := congr_arg (λ n, (↑n : zmod p)) (card_of_regular hG hd), revert h, simp [dmod], end end nonempty omit hG lemma adj_matrix_sq_mul_const_one_of_regular (hd : G.is_regular_of_degree d) : (G.adj_matrix R) * (λ _ _, 1) = λ _ _, d := by { ext x, simp [← hd x, degree] } lemma adj_matrix_mul_const_one_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) : (G.adj_matrix (zmod p)) * (λ _ _, 1) = λ _ _, 1 := by rw [adj_matrix_sq_mul_const_one_of_regular hd, dmod] include hG /-- Modulo a factor of `d-1`, the square and all higher powers of the adjacency matrix of a `d`-regular friendship graph reduce to the matrix whose entries are all 1. -/ lemma adj_matrix_pow_mod_p_of_regular {p : ℕ} (dmod : (d : zmod p) = 1) (hd : G.is_regular_of_degree d) {k : ℕ} (hk : 2 ≤ k) : (G.adj_matrix (zmod p)) ^ k = λ _ _, 1 := begin iterate 2 {cases k with k, { exfalso, linarith, }, }, induction k with k hind, { exact adj_matrix_sq_mod_p_of_regular hG dmod hd, }, have h2 : 2 ≤ k.succ.succ := by omega, rw [pow_succ, hind h2], exact adj_matrix_mul_const_one_mod_p_of_regular dmod hd, end variable [nonempty V] /-- This is the main proof. Assuming that `3 ≤ d`, we take `p` to be a prime factor of `d-1`. Then the `p`th power of the adjacency matrix of a `d`-regular friendship graph must have trace 1 mod `p`, but we can also show that the trace must be the `p`th power of the trace of the original adjacency matrix, which is 0, a contradiction. -/ lemma false_of_three_le_degree (hd : G.is_regular_of_degree d) (h : 3 ≤ d) : false := begin -- get a prime factor of d - 1 let p : ℕ := (d - 1).min_fac, have p_dvd_d_pred := (zmod.nat_coe_zmod_eq_zero_iff_dvd _ _).mpr (d - 1).min_fac_dvd, have dpos : 0 < d := by linarith, have d_cast : ↑(d - 1) = (d : ℤ) - 1 := by norm_cast, haveI : fact p.prime := ⟨nat.min_fac_prime (by linarith)⟩, have hp2 : 2 ≤ p := (fact.out p.prime).two_le, have dmod : (d : zmod p) = 1, { rw [← nat.succ_pred_eq_of_pos dpos, nat.succ_eq_add_one, nat.pred_eq_sub_one], simp only [add_left_eq_self, nat.cast_add, nat.cast_one], exact p_dvd_d_pred, }, have Vmod := card_mod_p_of_regular hG dmod hd, -- now we reduce to a trace calculation have := zmod.trace_pow_card (G.adj_matrix (zmod p)), contrapose! this, clear this, -- the trace is 0 mod p when computed one way rw [trace_adj_matrix, zero_pow (fact.out p.prime).pos], -- but the trace is 1 mod p when computed the other way rw adj_matrix_pow_mod_p_of_regular hG dmod hd hp2, dunfold fintype.card at Vmod, simp only [matrix.trace, diag_apply, mul_one, nsmul_eq_mul, linear_map.coe_mk, sum_const], rw [Vmod, ← nat.cast_one, zmod.nat_coe_zmod_eq_zero_iff_dvd, nat.dvd_one, nat.min_fac_eq_one_iff], linarith, end /-- If `d ≤ 1`, a `d`-regular friendship graph has at most one vertex, which is trivially a politician. -/ lemma exists_politician_of_degree_le_one (hd : G.is_regular_of_degree d) (hd1 : d ≤ 1) : exists_politician G := begin have sq : d * d = d := by { interval_cases d; norm_num }, have h := card_of_regular hG hd, rw sq at h, have : fintype.card V ≤ 1, { cases fintype.card V with n, { exact zero_le _, }, { have : n = 0, { rw [nat.succ_sub_succ_eq_sub, nat.sub_zero] at h, linarith }, subst n, } }, use classical.arbitrary V, intros w h, exfalso, apply h, apply fintype.card_le_one_iff.mp this, end /-- If `d = 2`, a `d`-regular friendship graph has 3 vertices, so it must be complete graph, and all the vertices are politicians. -/ lemma neighbor_finset_eq_of_degree_eq_two (hd : G.is_regular_of_degree 2) (v : V) : G.neighbor_finset v = finset.univ.erase v := begin apply finset.eq_of_subset_of_card_le, { rw finset.subset_iff, intro x, rw [mem_neighbor_finset, finset.mem_erase], exact λ h, ⟨(G.ne_of_adj h).symm, finset.mem_univ _⟩ }, convert_to 2 ≤ _, { convert_to _ = fintype.card V - 1, { have hfr:= card_of_regular hG hd, linarith }, { exact finset.card_erase_of_mem (finset.mem_univ _), }, }, { dsimp [is_regular_of_degree, degree] at hd, rw hd, } end lemma exists_politician_of_degree_eq_two (hd : G.is_regular_of_degree 2) : exists_politician G := begin have v := classical.arbitrary V, use v, intros w hvw, rw [← mem_neighbor_finset, neighbor_finset_eq_of_degree_eq_two hG hd v, finset.mem_erase], exact ⟨hvw.symm, finset.mem_univ _⟩, end lemma exists_politician_of_degree_le_two (hd : G.is_regular_of_degree d) (h : d ≤ 2) : exists_politician G := begin interval_cases d, iterate 2 { apply exists_politician_of_degree_le_one hG hd, norm_num }, { exact exists_politician_of_degree_eq_two hG hd }, end end friendship /-- We wish to show that a friendship graph has a politician (a vertex adjacent to all others). We proceed by contradiction, and assume the graph has no politician. We have already proven that a friendship graph with no politician is `d`-regular for some `d`, and now we do casework on `d`. If the degree is at most 2, we observe by casework that it has a politician anyway. If the degree is at least 3, the graph cannot exist. -/ theorem friendship_theorem [nonempty V] : exists_politician G := begin by_contradiction npG, rcases hG.is_regular_of_not_exists_politician npG with ⟨d, dreg⟩, have h : d ≤ 2 ∨ 3 ≤ d := by omega, cases h with dle2 dge3, { exact npG (hG.exists_politician_of_degree_le_two dreg dle2) }, { exact hG.false_of_three_le_degree dreg dge3 }, end
module Control.Applicative.Syntax -------------------------------------------------------------------------------- -- mapN etc -------------------------------------------------------------------------------- public export map2 : Functor f => Functor g => (a -> b) -> (f . g) a -> (f . g) b map2 = map . map public export map3 : Functor f => Functor g => Functor h => (a -> b) -> (f . g . h) a -> (f . g . h) b map3 = map . map . map public export map4 : Functor f => Functor g => Functor h => Functor i => (a -> b) -> (f . g . h . i) a -> (f . g . h . i) b map4 = map . map . map . map infixr 4 <$$>, <$$$>, <$$$$> infixl 3 <**>, <***>, <****> public export (<$$>) : Functor f => Functor g => (a -> b) -> (f . g) a -> (f . g) b (<$$>) = map . map public export (<$$$>) : Functor f => Functor g => Functor h => (a -> b) -> (f . g . h) a -> (f . g . h) b (<$$$>) = map . map . map public export (<$$$$>) : Functor f => Functor g => Functor h => Functor i => (a -> b) -> (f . g . h . i) a -> (f . g . h . i) b (<$$$$>) = map . map . map . map public export (<**>) : Applicative f => Applicative g => (f . g) (a -> b) -> (f . g) a -> (f . g) b x <**> y = [| x <*> y |] public export (<***>) : Applicative f => Applicative g => Applicative h => (f . g . h) (a -> b) -> (f . g . h) a -> (f . g . h) b x <***> y = [| x <**> y |] public export (<****>) : Applicative f => Applicative g => Applicative h => Applicative i => (f . g . h . i) (a -> b) -> (f . g . h . i) a -> (f . g . h . i) b x <****> y = [| x <***> y |] -------------------------------------------------------------------------------- -- Implementations -------------------------------------------------------------------------------- public export record Comp2 (f,g : Type -> Type) (a : Type) where constructor C2 c2 : f (g a) public export Functor f => Functor g => Functor (Comp2 f g) where map f (C2 v) = C2 $ map2 f v public export Applicative f => Applicative g => Applicative (Comp2 f g) where pure = C2 . pure . pure C2 vf <*> C2 va = C2 $ [| vf <*> va |] public export Foldable f => Foldable g => Foldable (Comp2 f g) where foldr fun acc (C2 v) = foldr (flip $ foldr fun) acc v foldl fun acc (C2 v) = foldl (foldl fun) acc v public export Traversable f => Traversable g => Traversable (Comp2 f g) where traverse fun = map C2 . (traverse . traverse) fun . c2
% 01ManifoldsVector.tex \subsection{Submanifolds of Euclidean Space} \paragraph{1.1(3)} Consider for $F(A) = \det{A}$, $F:\mathbb{R^{n^2}} \to \mathbb{R}$, that \[ \begin{gathered} \det{A + tB } = \det{ A ( 1 + tA^{-1} B) } = \det{A} \det{ 1 + tA^{-1}B} \end{gathered} \] How to deal with $\det{1 + tA^{-1}B}$? Recall that \[ \det{ 1 + tA^{-1}B} = \det{A} ( 1 + t\tr{A^{-1} B}) \] because for $ \det{(1 + tX)}$, \[ \begin{gathered} \det{(1+ tX)} = \det{ \matrixp{1& & \\ &\ddots & \\ && 1 } + \matrixp{ t x_{11} & \dots & t x_{1n} \\ \vdots & \ddots & \vdots \\ tx_{n1} & \dots & t x_{nn} } } = \det{ \matrixp{ 1 + tx_{11}& \dots & tx_{1n } \\ \vdots & \ddots & \vdots \\ tx_{n1} & \dots & 1 + tx_{nn}} } = \\ = 1 + t\tr{X} + \mathcal{O}(t^2) \end{gathered} \] since recall $\det{A} = \sum_{\sigma \in S_n} \text{sgn}{(\sigma)} A_{1 \sigma_1} A_{2\sigma_2} \dots A_{n\sigma_n}$, where sum is over all permutations of $\lbrace 1, \dots, n \rbrace$, and so only the $A_{11}\dots A_{nn}$ term would have terms of $\mathcal{O}(t)$. So \[ (DF) \cdot B = \frac{d}{dt} F(x(t)) B = \det{x} \tr{x^{-1} B} \] For $x_0 \in Sl(n)$, $\det{x_0} = 1$. Let $B = \frac{r}{n} x$. Then \[ (DF)\cdot B = \tr{x^{-1} \frac{r}{n} x } = r \] $DF = F_*$ is surjective $\forall \, x \in Sl(n)$ \subsection{Manifolds} \subsection{Tangent Vectors and Mappings} \subsubsection{ Tangent or ``Contravariant Vectors} \subsubsection{ Vectors as Differential Operators} \subsubsection{ The Tangent Space to $M^n$ at a Point } \subsubsection{ Mappings and Submanifolds of Manifolds} \begin{definition} $M^m \subset N^n$ (embedded) submanifold of $N^n$. If $M$ locally s.t. $F: N^n \to \mathbb{R}^{n-m}$ \[ \begin{aligned} & F^1(x^1 \dots x^n) = 0 \\ & \vdots \\ & F^{n-m}(x^1 \dots x^n) = 0 \end{aligned} \] $n-m$ diff. $F^i$ s.t. $\left| \frac{ \partial F^i}{ \partial x^j} \right| $ has rank $n-m$ \end{definition} By implicit function thm., submanifold as graph. \[ \begin{gathered} (x^1 \dots x^m, y^{m+1} \dots y^n ) \\ \begin{aligned} & y^{m+1} = f^{m=1}(x^1 \dots x^m) \\ & \vdots \\ & y^n = f^n(x^1 \dots x^m) \end{aligned} \end{gathered} \] on $F(x) = 0$ \begin{theorem}[1.12] Let $F: M^m \to N^n$, $q \in N^n$ s.t. $F^{-1}(q) \subset M^m $, $F^{-1}(q) \neq \emptyset$ \\ If $F_*$ onto, i.e. $F_*$ rank $n$, $\forall \, F^{-1}(q)$, \\ $F^{-1}(q)$ ($n-m$)-dim. submanifold of $M^m$ \end{theorem} \subsubsection{ Change of Coordinates}
lemma open_Inter [continuous_intros, intro]: "finite S \<Longrightarrow> \<forall>T\<in>S. open T \<Longrightarrow> open (\<Inter>S)"
/// /// @file : Create a FITS file with fake sources and random noise /// /// Control parameters are passed in from a LOFAR ParameterSet file. /// /// @copyright (c) 2007 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// [email protected] /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author Matthew Whiting <[email protected]> #include <askap_simulations.h> #include <FITS/FITSfile.h> #include <simulationutilities/FluxGenerator.h> #include <modelcomponents/Continuum.h> #include <askap/AskapLogging.h> #include <askap/AskapError.h> #include <Common/ParameterSet.h> #include <boost/shared_ptr.hpp> #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <map> #include <stdlib.h> #include <time.h> using namespace askap; using namespace askap::simulations; using namespace askap::simulations::FITS; ASKAP_LOGGER(logger, "tFlux.log"); // Move to Askap Util? std::string getInputs(const std::string& key, const std::string& def, int argc, const char** argv) { if (argc > 2) { for (int arg = 0; arg < (argc - 1); arg++) { std::string argument = std::string(argv[arg]); if (argument == key) { return std::string(argv[arg + 1]); } } } return def; } // Main function int main(int argc, const char** argv) { ASKAPLOG_INIT("tFlux.log_cfg"); LOFAR::ParameterSet parset("tests/tparset.in"); parset = parset.makeSubset("createFITS."); FITSfile file(parset); struct wcsprm *wcs = file.getWCS(); // wcsprt(wcs); std::vector<int> axes = parset.getInt32Vector("axes"); int nz = axes[wcs->spec]; FluxGenerator fluxes(nz); ASKAPLOG_DEBUG_STR(logger, "number of channels = " << nz); Continuum cont(-1., -1., 1.4e9, 1.); double x = 512., y = 512.; boost::shared_ptr<Spectrum> spec(&cont); fluxes.addSpectrum(spec, x, y, wcs); for (size_t i = 0; i < fluxes.nChan(); i++) { std::cout << i << " " << fluxes.getFlux(i) << "\n"; } std::cout << "\n"; FluxGenerator singleFlux(1); cont = Continuum(0., 0., 1.4e9, 1.); spec = boost::shared_ptr<Spectrum>(&cont); singleFlux.addSpectrum(spec, x, y, wcs); for (size_t i = 0; i < singleFlux.nChan(); i++) { std::cout << i << " " << singleFlux.getFlux(i) << "\n"; } }
<unk> <unk> 2
lemma bigomega_real_nat_transfer: "(f :: real \<Rightarrow> real) \<in> \<Omega>(g) \<Longrightarrow> (\<lambda>x::nat. f (real x)) \<in> \<Omega>(\<lambda>x. g (real x))"
function mono_total_next_grevlex_test ( ) %*****************************************************************************80 % %% MONO_TOTAL_NEXT_GREVLEX_TEST tests MONO_TOTAL_NEXT_GREVLEX. % % Licensing: % % This code is distributed under the GNU LGPL license. % % Modified: % % 03 December 2013 % % Author: % % John Burkardt % fprintf ( 1, '\n' ); fprintf ( 1, 'MONO_TOTAL_NEXT_GREVLEX_TEST\n' ); fprintf ( 1, ' MONO_TOTAL_NEXT_GREVLEX can list the monomials\n' ); fprintf ( 1, ' in M variables, of total degree N,\n' ); fprintf ( 1, ' one at a time, in graded reverse lexicographic order.\n' ); fprintf ( 1, '\n' ); fprintf ( 1, ' We start the process with (0,0,...,0,N).\n' ); fprintf ( 1, ' The process ends with (N,0,...,0,0)\n' ); n = 3; m = 3; fprintf ( 1, '\n' ); fprintf ( 1, ' Let M = %d\n', m ); fprintf ( 1, ' N = %d\n', n ); fprintf ( 1, '\n' ); x = [ 0, 0, n ]; i = 1; while ( 1 ) fprintf ( 1, ' %2d:', i ); for j = 1 : m fprintf ( 1, ' %1d', x(j) ); end fprintf ( 1, '\n' ); if ( x(1) == n ) break end x = mono_total_next_grevlex ( m, n, x ); i = i + 1; end return end